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:
Deploying Custom SQL Views with Django
I've written some custom PostgreSQL views, which I've wrapped with Django's ORM using the managed=False meta flag. What's the best way to deploy these views, so that running syncdb updates them in the database, and also that the views exist in the test database when I run un... | Deploying Custom SQL Views with Django | I've written some custom PostgreSQL views, which I've wrapped with Django's ORM using the managed=False meta flag. What's the best way to deploy these views, so that running syncdb updates them in the database, and also that the views exist in the test database when I run unittests?
| [
"With an initial SQL file.\n"
] | [
1
] | [] | [] | [
"django",
"django_orm",
"postgresql",
"python"
] | stackoverflow_0007052667_django_django_orm_postgresql_python.txt |
Q:
GStreamer: status of Python bindings and encoding video with mixed audio
I am hoping to find a way to write generated video (non-real time) from Python and mix it with external audio file (MP3) simultaneously.
What's the current status of GStreamer Python bindings, are they up-to-date?
Would it be possible to wri... | GStreamer: status of Python bindings and encoding video with mixed audio | I am hoping to find a way to write generated video (non-real time) from Python and mix it with external audio file (MP3) simultaneously.
What's the current status of GStreamer Python bindings, are they up-to-date?
Would it be possible to write MPEG-4 output with GStreamer and feed raw image frames from Python
Is it p... | [
"Whether or not the binding are \"up-to-date\" really depends on what version of Python you're using. As for Python 2.7, I am using GStreamer without incident. \nI have been fighting a major bug in developing with Python 2.7 and GStreamer on Windows 7 (WinBuilds installers), but I'm able to work with GStreamer just... | [
2
] | [] | [] | [
"encoding",
"gstreamer",
"mpeg_4",
"python",
"video"
] | stackoverflow_0006963302_encoding_gstreamer_mpeg_4_python_video.txt |
Q:
Correct way to integrate a Python module into my code (Hg, Google Code)
I had a custom script programmed and it is using the authors own module that is hosted on Google code in a Mercurial repo. I understand how to clone the repo but this will just stick the source into a folder on my computer. Is there a proper w... | Correct way to integrate a Python module into my code (Hg, Google Code) | I had a custom script programmed and it is using the authors own module that is hosted on Google code in a Mercurial repo. I understand how to clone the repo but this will just stick the source into a folder on my computer. Is there a proper way to add the module into my python install to make it available for my proje... | [
"In exactly the same way. Just pass the address of the repo to pip install, using the -e parameter:\npip install -e hg+http://code.google.com/path/to/repo\n\n",
"If the module isn't on pypi, clone the repository with Hg and see if there's a setup.py file. If there is, open a command prompt, cd to that directory,... | [
3,
0
] | [] | [] | [
"mercurial",
"python"
] | stackoverflow_0007052874_mercurial_python.txt |
Q:
How to handle exceptions in python using the `with` statement in python?
Assuming this piece of code:
connection = get_some_connection() # maybe from oursql
with connection.cursor() as cursor:
cursor.execute('some query')
I understand that after finishing cursor.close() will be executed automatically. What ab... | How to handle exceptions in python using the `with` statement in python? | Assuming this piece of code:
connection = get_some_connection() # maybe from oursql
with connection.cursor() as cursor:
cursor.execute('some query')
I understand that after finishing cursor.close() will be executed automatically. What about exceptions? Must I put them inside?
connection = get_some_connection() # m... | [
"with x as y: z() is basically syntactic sugar for:\ny = x\ny.__enter__()\ntry:\n z()\nfinally:\n if y.__exit__: y.__exit__()\n\nThis is not completely accurate, but that's the gist of it. Note that __exit__() will be passed exception information if an exception was thrown (see the docs) so you can \"handle\... | [
4,
2
] | [] | [] | [
"exception_handling",
"python",
"with_statement"
] | stackoverflow_0007052936_exception_handling_python_with_statement.txt |
Q:
appengine save image to blobstore from url
Im trying to upload an image to the blobstore and return the serving url, this is where im at so far:
url ='http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=blink-182&track=dammit&format=json'
result = urlfetch.fetch(u... | appengine save image to blobstore from url | Im trying to upload an image to the blobstore and return the serving url, this is where im at so far:
url ='http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=blink-182&track=dammit&format=json'
result = urlfetch.fetch(url=url, deadline=10, method=urlfetch.GET,).conte... | [
"You've confused two things.\nA db.Blob is the type of a blob stored within a model. It doesn't have a \"serving URL\". If you want to serve one, you need to write view code to load the model instance it's stored in from the datastore, and return the blob data directly.\nIf you want to store blobs and serve them in... | [
2
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0007052958_blobstore_google_app_engine_python.txt |
Q:
Calling python script from bash script while using GNU Parallel
I am trying to run a python script in parallel (with GNU parallel 20110722). As it could be seen below, I am not able to run in any of the ways I tried.
(^C marks the point where I interrupt the job with ctrl+C because there is no response from the sy... | Calling python script from bash script while using GNU Parallel | I am trying to run a python script in parallel (with GNU parallel 20110722). As it could be seen below, I am not able to run in any of the ways I tried.
(^C marks the point where I interrupt the job with ctrl+C because there is no response from the system).
me@kubuntu:~/Programs/LeitMotifsParallel$ parallel python {1} ... | [
"If http://www.biostars.org/p/11132/#11139 does not answer your question, please elaborate what is missing.\n"
] | [
2
] | [] | [] | [
"bash",
"parallel_processing",
"python"
] | stackoverflow_0007033527_bash_parallel_processing_python.txt |
Q:
Opening PyGTK Python Module Error in py2exe
I have a project written in Python 2.7 and PyGTK, with py2exe for compiling. I have two modules, "Launchpad.py" and "RegistrationScreen.py". I need to open RegistrationScreen.py from Launchpad.py.
I am using the following code currently:
def open_registration(event, data... | Opening PyGTK Python Module Error in py2exe | I have a project written in Python 2.7 and PyGTK, with py2exe for compiling. I have two modules, "Launchpad.py" and "RegistrationScreen.py". I need to open RegistrationScreen.py from Launchpad.py.
I am using the following code currently:
def open_registration(event, data=None):
subprocess.Popen(["python", "Registra... | [
"The problem is the path. RegistrationScreen.py is (probably) compressed inside dist/library.zip, but your code that calls it is looking for it in dist/RegestrationScreen.py.\nI don't know what the best solution to this is... py2exe is kind of a pain for accessing files.\nAlso, you probably don't want to be doing s... | [
1
] | [] | [] | [
"py2exe",
"pygtk",
"python",
"subprocess"
] | stackoverflow_0007052701_py2exe_pygtk_python_subprocess.txt |
Q:
Identify audio sample in a file
I want to be able to identify an audio sample (that is provided by the user) in a audio file I've got (mp3).
The mp3 file is a radio stream that I've kept for testing purposes, and I have the Pre-roll of the show. I want to identify it in the file and get the timestamp where it's pl... | Identify audio sample in a file | I want to be able to identify an audio sample (that is provided by the user) in a audio file I've got (mp3).
The mp3 file is a radio stream that I've kept for testing purposes, and I have the Pre-roll of the show. I want to identify it in the file and get the timestamp where it's playing in the file.
Note: The solution... | [
"This problem falls under the category of audio fingerprinting. If you have matched a sample to a song, then you'll certainly know the timestamp where the sample occurs within the song. There is a great paper by the guys behind Shazam that describes their technique: http://www.ee.columbia.edu/~dpwe/papers/Wang03-sh... | [
3,
2
] | [] | [] | [
"audio",
"c++",
"java",
"python",
"signal_processing"
] | stackoverflow_0007052169_audio_c++_java_python_signal_processing.txt |
Q:
simplejson dumps in Google App Engine Channel API
I am trying to use the Channel API with my Google App Engine django-nonrel project. As per my current requirement I want to send all the users list who are at a certain page, say group_mainpage.html, to every other users who are on the same page. In other words, if... | simplejson dumps in Google App Engine Channel API | I am trying to use the Channel API with my Google App Engine django-nonrel project. As per my current requirement I want to send all the users list who are at a certain page, say group_mainpage.html, to every other users who are on the same page. In other words, if we both are at this page, we both can see our names so... | [
"channel_msg=simplejson.dumps(outstr) should be used to send a JSON array, not HTML. \nTry this:\noutstr={'page_element':render_to_response(\"user_list.html\",template_values)}\n\nand then in your JavaScript code:\n$('#mydiv').append(data['page_element']);\n\nAlso, I think you are missing a '+=' in your result loop... | [
0,
0
] | [] | [] | [
"channel_api",
"django",
"google_app_engine",
"python"
] | stackoverflow_0007045874_channel_api_django_google_app_engine_python.txt |
Q:
Python Import Question
I have a custom package and I am having import problems. The module structure is like this:
- BaseModule
- Exchange
- Communications
- DeviceComm
I am trying to import the Exchange module into the DeviceComm module. How do I do that?
A:
Use Intra-package references:
from .... | Python Import Question | I have a custom package and I am having import problems. The module structure is like this:
- BaseModule
- Exchange
- Communications
- DeviceComm
I am trying to import the Exchange module into the DeviceComm module. How do I do that?
| [
"Use Intra-package references:\nfrom .. import Exchange\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007053247_python.txt |
Q:
web2py CURD.search() and permissions
I've this function for search
@auth.requires_login()
def find_template():
form, rows=crud.search(db.templates,query=db.templates.active==True)
return dict(form=form, rows=rows)
it works fine, but the user is able to find his templates and the other templates of other ... | web2py CURD.search() and permissions | I've this function for search
@auth.requires_login()
def find_template():
form, rows=crud.search(db.templates,query=db.templates.active==True)
return dict(form=form, rows=rows)
it works fine, but the user is able to find his templates and the other templates of other users! (but he can't edit them as i fixed ... | [
"The query argument has to be in proper DAL query format, not a list of conditions. Try:\nquery=((db.templates.active==True) & (db.templates.user_id==auth.user_id))\n\n"
] | [
1
] | [] | [] | [
"crud",
"database",
"python",
"relationship",
"web2py"
] | stackoverflow_0007052859_crud_database_python_relationship_web2py.txt |
Q:
What is more suitable in performance aspect - Multithreading or Multiprocessing?
I would like to run several receivers that will receive data in different ports, but are basically the same.
What is more suitable in performance aspect - Multithreading or Multiprocessing?
A:
The trouble with Python is that the mos... | What is more suitable in performance aspect - Multithreading or Multiprocessing? | I would like to run several receivers that will receive data in different ports, but are basically the same.
What is more suitable in performance aspect - Multithreading or Multiprocessing?
| [
"The trouble with Python is that the most common interpreters contain a global lock -- commonly known as the GIL. This means that only one thread can execute python code at once, so a multi-process model can often make more efficient use of multiple cores than a multi-thread model.\n",
"If the application is I/O... | [
5,
4
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0007053284_multiprocessing_multithreading_python.txt |
Q:
Pythonic shorthand for keys in a dictionary?
Simple question: Is there a shorthand for checking the existence of several keys in a dictionary?
'foo' in dct and 'bar' in dct and 'baz' in dct
A:
all(x in dct for x in ('foo','bar','baz'))
A:
You can use all() with a generator expression:
>>> all(x in dct for x in... | Pythonic shorthand for keys in a dictionary? | Simple question: Is there a shorthand for checking the existence of several keys in a dictionary?
'foo' in dct and 'bar' in dct and 'baz' in dct
| [
"all(x in dct for x in ('foo','bar','baz'))\n\n",
"You can use all() with a generator expression:\n>>> all(x in dct for x in ('foo', 'bar', 'qux'))\nFalse\n>>> all(x in dct for x in ('foo', 'bar', 'baz'))\nTrue\n>>> \n\nIt saves you a whopping 2 characters (but will save you a lot more if you have a longer list t... | [
8,
7,
5
] | [] | [] | [
"dictionary",
"key",
"python"
] | stackoverflow_0007053351_dictionary_key_python.txt |
Q:
Python ValueError: too many values to unpack
I am getting that exception from this code:
class Transaction:
def __init__ (self):
self.materials = {}
def add_material (self, m):
self.materials[m.type + m.purity] = m
def serialize (self):
ser_str = 'transaction_start\n'
... | Python ValueError: too many values to unpack | I am getting that exception from this code:
class Transaction:
def __init__ (self):
self.materials = {}
def add_material (self, m):
self.materials[m.type + m.purity] = m
def serialize (self):
ser_str = 'transaction_start\n'
for k, m in self.materials:
ser_str +... | [
"self.materials is a dict and by default you are iterating over just the keys (which are strings).\nSince self.materials has more than two keys*, they can't be unpacked into the tuple \"k, m\", hence the ValueError exception is raised.\nIn Python 2.x, to iterate over the keys and the values (the tuple \"k, m\"), we... | [
190,
82,
19
] | [] | [] | [
"python"
] | stackoverflow_0007053551_python.txt |
Q:
More efficient way to remove items from large data sets
I have two large lists:
a = [['abcdefghijklmno', 'foo', 'bar'], … ]
b = [['abcdefghij12345', 'foo', 'bar'], … ]
I'm interested in all members of a which don't have a corresponding entry in b, and vice versa, based on comparing a[n][0] and b[n][0] for all n i... | More efficient way to remove items from large data sets | I have two large lists:
a = [['abcdefghijklmno', 'foo', 'bar'], … ]
b = [['abcdefghij12345', 'foo', 'bar'], … ]
I'm interested in all members of a which don't have a corresponding entry in b, and vice versa, based on comparing a[n][0] and b[n][0] for all n in a and b. I create two sets of these sublist items, which al... | [
"I suspect that your test in the list comprehension is calling y.difference for each element. Try this:\ndef remaining(ls, y, z):\n diff = y.difference(z)\n return filter(lambda i: i[0] in diff, ls)\n\n",
"At least def remaining(ls ,y, z): should be rewritten in def remaining(ls, common_set):.\nConsider th... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007053144_python.txt |
Q:
Adding a XML root attribute with hyphens in python XMLBuilder
I'm integrating with the google checkout api and all of their attributes include hyphens in their attribute values. So to create a request to charge an order I need to send an xml post that looks like:
<?xml version="1.0" encoding="UTF-8"?>
<charge-and-... | Adding a XML root attribute with hyphens in python XMLBuilder | I'm integrating with the google checkout api and all of their attributes include hyphens in their attribute values. So to create a request to charge an order I need to send an xml post that looks like:
<?xml version="1.0" encoding="UTF-8"?>
<charge-and-ship-order xmlns="http://checkout.google.com/schema/2" google-order... | [
"You can pass the attributes in a dictionary like this:\nfunction_call(**{'weird-named-key': 'value'})\n\n"
] | [
0
] | [] | [] | [
"python",
"xml",
"xml_builder"
] | stackoverflow_0007053700_python_xml_xml_builder.txt |
Q:
Django: with arguments '('',)' and keyword arguments '{}' not found
I'm kind of new to django. Been working with it for a while, but still do really silly mistakes all the time. This one though, I seem to have a hard time figuring out... Because I'm sorta new to this I'm not very good at explaining my problem, but... | Django: with arguments '('',)' and keyword arguments '{}' not found | I'm kind of new to django. Been working with it for a while, but still do really silly mistakes all the time. This one though, I seem to have a hard time figuring out... Because I'm sorta new to this I'm not very good at explaining my problem, but here goes...
Error message complains about this bit in template:
{% url ... | [
"You don't have an object called object in your context:\n{% url privblog object.id %}\n\nShould be \n{% url privblog pblog_detail_object.id %}\n\nYou might also be having trouble here:\nreturn render_to_response('privblog/privblog_detail.html', context, RequestContext(request))\n\nI've never invoked render_to_resp... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007053735_django_python.txt |
Q:
404 Error when creating a helloworld page using django
I'm working through the djangobook tutorials and I have reached the point where I create the hello world view and runserver to see the page when I get a page not found (404 Error).
urls.py code
from django.conf.urls.defaults import *
from mysite.views import *... | 404 Error when creating a helloworld page using django | I'm working through the djangobook tutorials and I have reached the point where I create the hello world view and runserver to see the page when I get a page not found (404 Error).
urls.py code
from django.conf.urls.defaults import *
from mysite.views import *
urlpatterns = patterns('',
(r'^hello/$', hello),
)
vi... | [
"On trailing slash: https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#append-slash is a lifesaver.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007050083_django_python.txt |
Q:
Substitute parenthesis for their regular expression
I'm trying to copy a file,
>>> originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
>>> copyFile = os.system('cp '+originalFile+' '+NewTmpFile)
But must first replace the spaces and parenthe... | Substitute parenthesis for their regular expression | I'm trying to copy a file,
>>> originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
>>> copyFile = os.system('cp '+originalFile+' '+NewTmpFile)
But must first replace the spaces and parenthesis before the open function will work:
/Users/alvinspive... | [
"( has special meaning in regular expressions (grouping), you have to escape it:\noriginalFile = re.sub(r'\\(',r'\\(', originalFile)\n\nor, since you don't use regex features for the replacement:\noriginalFile = re.sub(r'\\(','\\(', originalFile)\n\n",
"The regular expression r'(' is translated as start a capturi... | [
2,
2,
2,
0
] | [] | [] | [
"parentheses",
"python",
"regex"
] | stackoverflow_0007053780_parentheses_python_regex.txt |
Q:
Communicating between applications?
I am very new to programming, and have had no formal training in it before so please bear with me if this is a vague question.
I was just curious: how do different programs on the same computer communicate with each other? From my programming experience I believe it can be achie... | Communicating between applications? | I am very new to programming, and have had no formal training in it before so please bear with me if this is a vague question.
I was just curious: how do different programs on the same computer communicate with each other? From my programming experience I believe it can be achieved by socket programming?
Thanks
| [
"You can rely on all different kind of inter process communication. (IPC). Have a look at http://en.wikipedia.org/wiki/Inter-process_communication\nOn linux, dbus is used to make applications communicate together. Sockets are only one way to solve this provlem.\n",
"Sockets, shared memory, events / signals, pipes... | [
3,
1,
1
] | [] | [] | [
"c++",
"communication",
"java",
"python"
] | stackoverflow_0007053905_c++_communication_java_python.txt |
Q:
Can I make a regular expression negative lookbehind assertion apply to the whole expression?
I'm using Python re to try to make a regular expression which finds all camel cased words not starting with an exclamation point (!).
Here is what I have:
(?<![!])([A-Z]?[a-z]+[A-Z][a-zA-Z]+)
The negative lookbehind asser... | Can I make a regular expression negative lookbehind assertion apply to the whole expression? | I'm using Python re to try to make a regular expression which finds all camel cased words not starting with an exclamation point (!).
Here is what I have:
(?<![!])([A-Z]?[a-z]+[A-Z][a-zA-Z]+)
The negative lookbehind assertion is only being applied to the first [A-Z] block instead of everything within the parenthesis l... | [
"re.findall(r'(?<![!])\\b\\w+', ' !Hai Yo!')\n\nAnd the result is ['Yo']\nBTW, just change the \\w+ with your validation but keep the \\b.\n",
"Looks like the following will meet your requirement,\n>>> reg=r'[^!]\\b([a-zA-Z][a-z]+[A-Z][a-zA-Z]+)\\b'\n>>> text=\"Welcome to MyWorld! We have !CoolStuff here YouAgre... | [
3,
1
] | [] | [] | [
"expression",
"python",
"regex"
] | stackoverflow_0007053791_expression_python_regex.txt |
Q:
How to find substring in file?
How to find string in binary file using only read(1) ?
For example I want to found position of string 'abst' in file ( without load to memory ) ?
It's work but very primitive:
#!/usr/bin/python2
f = open("/tmp/rr", "rb")
f.seek(0)
cont = 1
while(cont):
a1 = f.read(1)
if a1 ... | How to find substring in file? | How to find string in binary file using only read(1) ?
For example I want to found position of string 'abst' in file ( without load to memory ) ?
It's work but very primitive:
#!/usr/bin/python2
f = open("/tmp/rr", "rb")
f.seek(0)
cont = 1
while(cont):
a1 = f.read(1)
if a1 == 'a':
a2 = f.read(1)
... | [
"Use mmap to search the file with constant memory requirements:\nimport mmap\nwith open('/tmp/rr', 'rb') as f:\n m = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ)\n position = m.index('abst')\n\n",
"Will this work for you?\n#!/usr/bin/python\n\nstring = \"abst\"\nf = open(\"/tmp/rr\", \"rb\")\nf.se... | [
4,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007052883_python.txt |
Q:
Python vs C : Line of Code Comparison vs Dev Time
Hi I'm currently learning Python since the syntax feels so succinct and the idioms match well with my mental model.
However I'm also interested in learning about OS internals and reverse engineering software, which ultimately means knowing C in a rather thorough ca... | Python vs C : Line of Code Comparison vs Dev Time | Hi I'm currently learning Python since the syntax feels so succinct and the idioms match well with my mental model.
However I'm also interested in learning about OS internals and reverse engineering software, which ultimately means knowing C in a rather thorough capacity.
When originally picking a language I did lots o... | [
"\nbut is it possible with libraries, code reuse etc, to have a development time in C close to that of Python\n\nNo.\nYou've missed the most important point. \nPython's interactive. It's not edit-compile-link-execute-break-debug. It's edit-debug.\n",
"Boost is C++, not C (emphatically not C -- virtually all of... | [
10,
6,
1,
1,
1,
0
] | [] | [] | [
"c",
"comparison",
"python"
] | stackoverflow_0003722003_c_comparison_python.txt |
Q:
Checking if something exists in items of list variable in Django template
I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is thi... | Checking if something exists in items of list variable in Django template | I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.
{% if s.name == "Social" for s in sections %}
Hello Social!
{% endif %}
... | [
"Ideally what you would do is create a list that the template gets as such:\nl = [s.name for s in sections]\n\nAnd in the template, use:\n{% if 'Social' in l %}\n\nYou're trying to put more logic into a template than they are meant to have. Templates should use as little logic as possible, while the logic should b... | [
17,
14,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007054189_django_django_templates_python.txt |
Q:
Creating an animated graphics overlay with Python
I'd like to hear the best means for displaying graphics that move on-screen as an overlay with Python. The intended initial platform is Linux. I've worked up some small demos using PyQt using frameless windows and looping and updating their location on screen. T... | Creating an animated graphics overlay with Python | I'd like to hear the best means for displaying graphics that move on-screen as an overlay with Python. The intended initial platform is Linux. I've worked up some small demos using PyQt using frameless windows and looping and updating their location on screen. This works, but I have a feeling it is not the ideal sol... | [
"There are examples for making transparent / unclickable windows in java and in javascript. Here are a couple of transparency related posts for QT.\n"
] | [
0
] | [] | [] | [
"linux",
"overlay",
"pyqt",
"python",
"xorg"
] | stackoverflow_0007045747_linux_overlay_pyqt_python_xorg.txt |
Q:
Python 2 lists compare optimization
Given:
Two csv files (1.8 MB each): AllData_1, AllData_2. Each with ~8,000 lines. Each line consists of 8 columns.
[txt_0,txt_1,txt_2,txt_3,txt_4,txt_5,txt_6,txt_7,txt_8]
Goal:
Based on a match of txt_0 (or, AllData_1[0] == AllData_2 ), compare the contents of the next 4 colu... | Python 2 lists compare optimization | Given:
Two csv files (1.8 MB each): AllData_1, AllData_2. Each with ~8,000 lines. Each line consists of 8 columns.
[txt_0,txt_1,txt_2,txt_3,txt_4,txt_5,txt_6,txt_7,txt_8]
Goal:
Based on a match of txt_0 (or, AllData_1[0] == AllData_2 ), compare the contents of the next 4 columns for these individual rows. If the da... | [
"If you can expect no two lines in a given file to have the same data in column 0, you can significantly improve your code with a few dicts. Instead of the lines\nx0list.append(entry[0])\ny0list.append(y[0])\n\nYou would use:\nx0dict[entry[0]] = entry\ny0dict[y[0]] = y\n\nafter initializing x0dict and y0dict to {}... | [
1,
1
] | [] | [] | [
"compare",
"list",
"performance",
"python"
] | stackoverflow_0007054249_compare_list_performance_python.txt |
Q:
Plot Smooth Curve in PyPlot with Large Y Values
I'm following the advice given in this question for the following data:
import matplotlib.pyplot as plt
from numpy import array, linspace
from scipy.interpolate import spline
xdata = array([25, 36, 49])
ydata = array([145247, 363726, 789055])
xnew = linspace(xdata.... | Plot Smooth Curve in PyPlot with Large Y Values | I'm following the advice given in this question for the following data:
import matplotlib.pyplot as plt
from numpy import array, linspace
from scipy.interpolate import spline
xdata = array([25, 36, 49])
ydata = array([145247, 363726, 789055])
xnew = linspace(xdata.min(),xdata.max(),300)
ysmooth = spline(xdata,ydata,... | [
"What versions of numpy and scipy are you using? Your code works for me with numpy 1.6.0 and scipy 0.9.0 (after moving the linspace import to numpy from scipy.interpolate), after adding a scatterplot:\n\n"
] | [
2
] | [] | [] | [
"curvesmoothing",
"matplotlib",
"python",
"scipy"
] | stackoverflow_0007054541_curvesmoothing_matplotlib_python_scipy.txt |
Q:
PIL smudges image when I overlay another image on it
I'm using the following code to overlay an image onto another image using PIL
path = "/home/blah.png"
background = Image.open(path)
product = Image.open("/home/51tmBaivYhL._SL75_.jpg")
background.paste(product, (20,40))
background.save("/home/newImage.jpg")
The... | PIL smudges image when I overlay another image on it | I'm using the following code to overlay an image onto another image using PIL
path = "/home/blah.png"
background = Image.open(path)
product = Image.open("/home/51tmBaivYhL._SL75_.jpg")
background.paste(product, (20,40))
background.save("/home/newImage.jpg")
These are the images I'm using as the background http://i.img... | [
"The problem has nothing to do with PIL. The problem is the background is a .png, and you are composing it, and then outputting it as a .jpg.\n.png is lossless, very good for synthetic images like your background. .jpg is lossy, very good for natural images like photographs. When you output your background as .j... | [
5,
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0007054646_python_python_imaging_library.txt |
Q:
Any substitutes for pexpect?
I am writing a script using python pexpect to execute another script on a remote machine. It works fine in normal cases, but if there is a time.sleep in the remote script, it fails.
I want to get to the remote machine, start the script in the background and get out. Is this possible ?
... | Any substitutes for pexpect? | I am writing a script using python pexpect to execute another script on a remote machine. It works fine in normal cases, but if there is a time.sleep in the remote script, it fails.
I want to get to the remote machine, start the script in the background and get out. Is this possible ?
Can someone suggest an alternative... | [
"Have you considered paramiko?\nHere's an example ... \n#!/usr/bin/env python\nimport paramiko\n\nssh = paramiko.SSHClient()\nssh.load_system_host_keys()\n\nssh.connect(hostname='example.com', port=22, username='sethu', password='****')\n\nssh.exec_command('nohup sleep 300 &')\n\nssh.close()\n\n"
] | [
1
] | [] | [] | [
"linux",
"pexpect",
"python"
] | stackoverflow_0007051689_linux_pexpect_python.txt |
Q:
Are there any smartphones with good Python interpreter support?
I'm getting a new phone and I am looking to do some programming on it. Python is my language of choice, so I was wondering what phones have support for Python interpreters.
I know, I know, "you program too much already", yeah my girlfriend says that a... | Are there any smartphones with good Python interpreter support? | I'm getting a new phone and I am looking to do some programming on it. Python is my language of choice, so I was wondering what phones have support for Python interpreters.
I know, I know, "you program too much already", yeah my girlfriend says that all the time too, but I can't help it.
I'll probably do a lot of on-th... | [
"With regards to Py4A, in view of discussion at the link below, my guess would be Py 2.7.1, 2.7.2.\nhttp://code.google.com/p/python-for-android/issues/detail?id=10&q=python\n",
"The Nokia n900 comes with Maemo 5 Linux, and can easily run a full Debian Linux for ARM. It's not locked down in any way. I have one (in... | [
2,
1
] | [] | [] | [
"android",
"iphone",
"python",
"smartphone",
"symbian"
] | stackoverflow_0007034636_android_iphone_python_smartphone_symbian.txt |
Q:
How to repeatedly read a file from the last location
I am trying to read a syslog repeatedly and only start from the point I left off last read. I am trying to save the location of tell() is a sperate file and reload to seek before every read.
lf = open("location.file", 'r')
s = lf.readline()
last_... | How to repeatedly read a file from the last location | I am trying to read a syslog repeatedly and only start from the point I left off last read. I am trying to save the location of tell() is a sperate file and reload to seek before every read.
lf = open("location.file", 'r')
s = lf.readline()
last_pos = int(s.strip())
lf.close()
sl = open("/var... | [
"\nWrite str(last_loc) instead of last_loc.\nThe rest are probably optional.\nUse w instead of w+ for writing the location.\nClose /var/log/messages when you're done with it.\nDepending on your version of Python (definitely on 2.6 or newer, maybe on 2.5 depending), you may want to use with to automatially close fil... | [
3,
0
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0007055170_file_file_io_python.txt |
Q:
How to extract certain parts of a web page in Python
Target web page:
http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htm
The section I want to extract:
<tr>
<td>Skilled – Independent (Residence) subclass 885<br />online</td>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td... | How to extract certain parts of a web page in Python | Target web page:
http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htm
The section I want to extract:
<tr>
<td>Skilled – Independent (Residence) subclass 885<br />online</td>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
<td>15 May 2011</td>
<td>N/A</td>
</tr>
Once the ... | [
"\n\"Beau--ootiful Soo--oop!\nBeau--ootiful Soo--oop!\nSoo--oop of the e--e--evening,\nBeautiful, beauti--FUL SOUP!\"\n\n--Lewis Carroll, Alice's Adventures in Wonderland\nI think this is exactly what he had in mind!\nThe Mock Turtle would probably do something like this:\n>>> from BeautifulSoup import BeautifulSou... | [
7,
6,
2
] | [] | [] | [
"html",
"python",
"string"
] | stackoverflow_0007055048_html_python_string.txt |
Q:
Cannot properly decode string
I have a string from reading a .txt file that looks something like this:
str='\x00I\x00S\x00T\x00A\x00\r\x00\n\x00[\x00/\x00B\x00O\x00D\x00Y\x00]\x00\r\x00\n\x00'
The contents of the file is in Portuguese and it won't allow me to encode into utf-8.
When I do print(str), it comes out ... | Cannot properly decode string | I have a string from reading a .txt file that looks something like this:
str='\x00I\x00S\x00T\x00A\x00\r\x00\n\x00[\x00/\x00B\x00O\x00D\x00Y\x00]\x00\r\x00\n\x00'
The contents of the file is in Portuguese and it won't allow me to encode into utf-8.
When I do print(str), it comes out properly, but when I try and do stu... | [
"You need to decode it to a unicode first.\n>>> '\\x00I\\x00S\\x00T\\x00A\\x00\\r\\x00\\n\\x00[\\x00/\\x00B\\x00O\\x00D\\x00Y\\x00]\\x00\\r\\x00\\n'.decode('utf-16be')\nu'ISTA\\r\\n[/BODY]\\r\\n'\n\nIf it's from a file then use codecs.open() instead of open(), passing the appropriate encoding.\n"
] | [
4
] | [] | [] | [
"character_encoding",
"python",
"unicode",
"utf_8"
] | stackoverflow_0007055368_character_encoding_python_unicode_utf_8.txt |
Q:
PYTHON Trouble using escape key to exit
I'm having trouble with the following code. It seems to respond to the escape key but it freezes really bad. I'm using pyscripter with python 2.7 and pygame.
# An example implementation of the algorithm described at
# http://www.niksula.cs.hut.fi/~hkankaan/Homepages/metaball... | PYTHON Trouble using escape key to exit | I'm having trouble with the following code. It seems to respond to the escape key but it freezes really bad. I'm using pyscripter with python 2.7 and pygame.
# An example implementation of the algorithm described at
# http://www.niksula.cs.hut.fi/~hkankaan/Homepages/metaballs.html
#
# The code contains some references ... | [
"I just modified the code like so, thanks giantenigma\n#exit when esc is pressed\nfor event in pygame.event.get():\n if event.type == QUIT:\n return\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n return\n\n",
"Make sure that you call pygame.quit() b... | [
12,
7
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0007053971_pygame_python.txt |
Q:
SimpleXMLRPCServer request dispatching issue
We're developing client-server XML-RPC based application. Server part should know IP address of each client on per request basis.
To accomplish this we mix SocketServer.ThreadingMixIn into SimpleXMLRPCServer and subclass SimpleXMLRPCRequestHandler to redefine it's _disp... | SimpleXMLRPCServer request dispatching issue | We're developing client-server XML-RPC based application. Server part should know IP address of each client on per request basis.
To accomplish this we mix SocketServer.ThreadingMixIn into SimpleXMLRPCServer and subclass SimpleXMLRPCRequestHandler to redefine it's _dispatch method. Below is the code:
class ThreadedXMLR... | [
"You should probably re-raise any exceptions encountered by calling function(ip_addr ...) in your custom _dispatch method, otherwise you risk short-circuiting the built-in error handling. \nHere's what I mean ... \nclass RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):\n def _dispatch(self, method,... | [
0
] | [] | [] | [
"python",
"simplexmlrpcserver",
"xml",
"xml_rpc"
] | stackoverflow_0006506206_python_simplexmlrpcserver_xml_xml_rpc.txt |
Q:
Unable to match URL in URL.conf in Django?
What am I doing wrong ?
My URL : http://localhost:8000/login/
The DEBUG log from Django :
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/login/
Using the URLconf defined in dealers.urls, Django tried these URL patterns, in this order:
^lo... | Unable to match URL in URL.conf in Django? | What am I doing wrong ?
My URL : http://localhost:8000/login/
The DEBUG log from Django :
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/login/
Using the URLconf defined in dealers.urls, Django tried these URL patterns, in this order:
^login|home/ ^login/$
^login|home/ ^home/$
^login|h... | [
"## urls.py\nurlpatterns = patterns('',\n (r'',include('dealerpanel.urls')),\n (r'^admin/', include(admin.site.urls))\n)\n\nChange the prefix for including dealerpanel.urls to be the empty string. I think the way you have it structured it would actually be looking for a url like:\n/login/login/\n/login/home/\n/ho... | [
4,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0007055617_django_django_urls_python.txt |
Q:
python query - function arguments are incorrect type?
i'm pretty new to python and i'm having trouble with passing an argument into the random.choice function.
basically i'm trying to write a loop that will start off by selecting a random letter(which are all names of other lists) from the 'a' list, then input the... | python query - function arguments are incorrect type? | i'm pretty new to python and i'm having trouble with passing an argument into the random.choice function.
basically i'm trying to write a loop that will start off by selecting a random letter(which are all names of other lists) from the 'a' list, then input the selected letter into random.choice again to generate a seq... | [
"You've fallen into the common beginner's trap of mixing up variables and data, and trying to treat your code as data. You shouldn't typically try to do that - don't put the name of a variable into another variable and try to access it that way.\nInstead, keep all the data together in a data structure, and just us... | [
4,
0
] | [
"Just suppose x == 'c'. Then the second call to random.choice is actually\nanswer2 = random.choice('c')\n\nThis is like selecting a letter from a list containing only 'c'. This is NOT equivalent to the following:\nanswer2 = random.choice(c)\n\nYou need to convert the string 'c' into a list referenced by the variab... | [
-1
] | [
"python"
] | stackoverflow_0007055667_python.txt |
Q:
The best way to act with a model in Django
I have a Task model:
class Task(models.Model):
text = models.TextField()
datetime = models.DateTimeField(auto_now_add=True)
taken = models.BooleanField(default=False)
done = models.BooleanField(default=False)
client = models.ForeignKey('UserProfile', r... | The best way to act with a model in Django | I have a Task model:
class Task(models.Model):
text = models.TextField()
datetime = models.DateTimeField(auto_now_add=True)
taken = models.BooleanField(default=False)
done = models.BooleanField(default=False)
client = models.ForeignKey('UserProfile', related_name='tasks_given')
executor = models... | [
"You can use the django-admin site, as illustrated in chapter 2 of the tutorial.\n",
"I'm not exactly sure what you mean by \"best way to act,\" but if you want to handle the object creation and validation, you can write extra methods in your model.\nclass Task(Models.model):\n ...\n ## fields\n ...\n\n ... | [
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007055615_django_django_models_python.txt |
Q:
In memory database with fallback to disk on OOM
I have lots of data to operate on (write, sort, read). This data can potentially be larger than the main memory and doesn't need to be stored permanently.
Is there any kind of library/database that can store these data for me in memory and that does have and automagi... | In memory database with fallback to disk on OOM | I have lots of data to operate on (write, sort, read). This data can potentially be larger than the main memory and doesn't need to be stored permanently.
Is there any kind of library/database that can store these data for me in memory and that does have and automagically fallback to disk if system runs in a OOM situat... | [
"Python's built-in sqlite3 caches file-system writes.\n",
"I will go for the in memory solution and let the OS swap. I can still replace the storage component if this will be really a problem. Thanks agf.\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006942105_python.txt |
Q:
Using flask/blueprint for some static pages
So I am just a little confused on how to build pages with flask without having to state each view.
How would I make a blue print that would pickup on the pages i want to load?
say these are my example pages
templates/
layout.html
section1/
subsection/index.htm... | Using flask/blueprint for some static pages | So I am just a little confused on how to build pages with flask without having to state each view.
How would I make a blue print that would pickup on the pages i want to load?
say these are my example pages
templates/
layout.html
section1/
subsection/index.html
subsection2/index.html
section2
su... | [
"If you'd like to see an example of Blueprint usage, you can have a look at this answer.\nAbout the \"template auto-find\" part of your question: like the documentation explains, blueprints allows to specify a folder where static files and/or templates will be looked for, this way you don't have to specify the full... | [
13
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0007054099_flask_python.txt |
Q:
How to implement this model in Django?
I am new to Django and I getting some difficulties in implementing this model in Django:
Until now I have the model working without the table "Positions", and looks like this:
from django.db import models
import datetime
class Category(models.Model):
n_category = models... | How to implement this model in Django? | I am new to Django and I getting some difficulties in implementing this model in Django:
Until now I have the model working without the table "Positions", and looks like this:
from django.db import models
import datetime
class Category(models.Model):
n_category = models.CharField(max_length=100)
class Directory(... | [
"Create a the model Position which has ForeignKeys to Categories and Directory and all the other data needed. And then use the through argument for the ManyToManyField. This is described in the Django documentation\nExample (which if haven't tested):\nclass Position(models.Model):\n website_postiton = models.Int... | [
2
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0007056356_django_models_python.txt |
Q:
Python implement a preorder method of a binary tree
Why can't this python program run correctly. I would like to build a binary tree and then traverse it in pre-order. When I call the PreOrder method, it returns nothing.
class Node:
def __init__(self, data=None, left=None, right=None):
self.left = left... | Python implement a preorder method of a binary tree | Why can't this python program run correctly. I would like to build a binary tree and then traverse it in pre-order. When I call the PreOrder method, it returns nothing.
class Node:
def __init__(self, data=None, left=None, right=None):
self.left = left
self.right = right
self.data = data
cla... | [
"PreOrder is a method of the class BTree, you might want to change the recursive calls, like so:\ndef PreOrder(self):\n if self.root != None:\n if self.root.data != '*':\n print self.root.data,\n self.root.left.PreOrder()\n self.root.right.PreOrder()\n\nYou also don't need... | [
3,
0,
0,
0
] | [] | [] | [
"binary_tree",
"python"
] | stackoverflow_0007056003_binary_tree_python.txt |
Q:
python should I use generator for this case?
I have a list of almost 2k dictionaries inside it. And I am using the list several times. For instance:
c = myClass()
c.create(source) # where source is a text of approximately 50k chars
# this method creates the list that has approximately 2k dictionar... | python should I use generator for this case? | I have a list of almost 2k dictionaries inside it. And I am using the list several times. For instance:
c = myClass()
c.create(source) # where source is a text of approximately 50k chars
# this method creates the list that has approximately 2k dictionaries
item = c.get(15012) # now, this one loops thru... | [
"It sounds to me like you have to decide which you'd rather do:\n1) Save the values so you don't have to recalculate them, but use more space to do so.\n2) Recalculate them each time, but save on space because you don't have to store them.\nIf you think about it, no matter what kind of generator/list/whatever you'r... | [
5,
3,
1,
1,
1,
0
] | [] | [] | [
"generator",
"performance",
"python"
] | stackoverflow_0007054700_generator_performance_python.txt |
Q:
Print __file__ without file extension
Is there a better way to print __file__ without the extension?
import os
print os.path.splitext(__file__)[0]
A:
You can use string.split, but what's the point? The standard library is giving you the exact tool you need.
A:
Don't do this, use os.path.splitext. However if y... | Print __file__ without file extension | Is there a better way to print __file__ without the extension?
import os
print os.path.splitext(__file__)[0]
| [
"You can use string.split, but what's the point? The standard library is giving you the exact tool you need.\n",
"Don't do this, use os.path.splitext. However if you must, here's a way:\n'.'.join(__file__.split('.')[:-1])\n\n",
">>> 'my.cool.script.py'.rsplit('.', 1)[0]\n<<< 'my.cool.script'\n\n",
"Without s... | [
11,
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0007055963_python.txt |
Q:
How to find objects where the key is NOT in a StringListProperty in GoogleAppEngine
I'm pretty sure the above is NOT directly possible (but I would be happy to be wrong). So here is what I am trying to do, but I can't figure out how to do get a useful query to work.
class Challenge(db.Model):
name = db.String... | How to find objects where the key is NOT in a StringListProperty in GoogleAppEngine | I'm pretty sure the above is NOT directly possible (but I would be happy to be wrong). So here is what I am trying to do, but I can't figure out how to do get a useful query to work.
class Challenge(db.Model):
name = db.StringProperty()
players = db.StringListProperty(default=[])
created_on = db.DateTimePr... | [
"As you guessed, this isn't really possible. Elements in list properties are indexed individually, so a filter for \"not equal to x\" would return any list that has at least one value not equal to x, not the desired result.\nGiven the situation you describe, though, it seems unlikely that users will be in an unboun... | [
3,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007054820_google_app_engine_google_cloud_datastore_python.txt |
Q:
use exclam (!) syntax for factorial in python
Can a working factorial function/operator be defined with a syntax like in mathematics? i.e. using the ! symbol.
I can't think of any use cases of the existing symbol where things could be ambiguous
ipython !shell_escape always has the bang at the start of a line
som... | use exclam (!) syntax for factorial in python | Can a working factorial function/operator be defined with a syntax like in mathematics? i.e. using the ! symbol.
I can't think of any use cases of the existing symbol where things could be ambiguous
ipython !shell_escape always has the bang at the start of a line
something like 0!=1 would be True as usual because the... | [
"If you mean, \"can I define the ! operator in my Python program?,\" the answer is no, Python doesn't have a bang operator that can be defined.\nIf you mean, \"could Python be extended to include a ! operator?,\" the answer is yes, though probably not as a postfix operator like x!. I very much doubt that the Pytho... | [
7,
6
] | [] | [] | [
"factorial",
"operator_overloading",
"python",
"syntax"
] | stackoverflow_0007056908_factorial_operator_overloading_python_syntax.txt |
Q:
Getting a hyperlink URL from an Excel document
I am reading an Excel file using xlrd. In one column I have a company name which is formatted as a hyperlink (meaning there is a URL behind it). When I get the cell value I only get the company name. How can I also get the URL behind it?
Below is the code for reading ... | Getting a hyperlink URL from an Excel document | I am reading an Excel file using xlrd. In one column I have a company name which is formatted as a hyperlink (meaning there is a URL behind it). When I get the cell value I only get the company name. How can I also get the URL behind it?
Below is the code for reading an Excel file using the xlrd module (assume files ar... | [
"In xlrd 0.7.2 or newer, you can use hyperlink_map:\nimport xlrd\nmainData_book = xlrd.open_workbook(\"IEsummary.xls\", formatting_info=True)\nmainData_sheet = mainData_book.sheet_by_index(0)\nfor row in range(1, 101):\n rowValues = mainData_sheet.row_values(row, start_colx=0, end_colx=8)\n company_name = row... | [
11
] | [] | [] | [
"python",
"xlrd"
] | stackoverflow_0007056892_python_xlrd.txt |
Q:
Problem with moving static folders
I have a problem with uploading a django app to dotcloud. I'm using the code below to change django's admin panel static files to /static/admin_media, but it gives me the following error when deploying:
2011-08-14 13:22:35 [www.0] Traceback (most recent call last):
2011-08-14 13... | Problem with moving static folders | I have a problem with uploading a django app to dotcloud. I'm using the code below to change django's admin panel static files to /static/admin_media, but it gives me the following error when deploying:
2011-08-14 13:22:35 [www.0] Traceback (most recent call last):
2011-08-14 13:22:35 [www.0] File "./postinstall", l... | [
"The solution is this answer.\nI needed an empty folder named static, but git didn't transfer it to the server because it was empty.\nCreating .gitignore inside the folder fixed the problem.\n"
] | [
0
] | [] | [] | [
"django",
"dotcloud",
"python"
] | stackoverflow_0007057067_django_dotcloud_python.txt |
Q:
Python's asyncore client to send periodic data to server
I need to connect to a server (e.g. smpp server) and send periodic data every 2 seconds, here's the code:
import asyncore, socket, threading, time
class SClient(asyncore.dispatcher):
buffer = ""
t = None
def __init__(self, host):
asynco... | Python's asyncore client to send periodic data to server | I need to connect to a server (e.g. smpp server) and send periodic data every 2 seconds, here's the code:
import asyncore, socket, threading, time
class SClient(asyncore.dispatcher):
buffer = ""
t = None
def __init__(self, host):
asyncore.dispatcher.__init__(self)
self.create_socket(socket... | [
"Look at the docs for the asyncore loop method. \n\nThe timeout argument sets the timeout parameter for the appropriate\n select() or poll() call, measured in seconds; the default is 30\n seconds.\n\nIt's only firing the handle_write every 30 secs.\n"
] | [
1
] | [] | [] | [
"asyncore",
"client",
"multithreading",
"python"
] | stackoverflow_0007056973_asyncore_client_multithreading_python.txt |
Q:
How do I get node-waf to install?
First, props to whoever did node.js. I've been using it for less than a day and I'm already thinking about using it for stuff I use Python for now.
In fact, whoever did node.js should think about using it for stuff they use Python for now. There is apparently a tool called nod... | How do I get node-waf to install? | First, props to whoever did node.js. I've been using it for less than a day and I'm already thinking about using it for stuff I use Python for now.
In fact, whoever did node.js should think about using it for stuff they use Python for now. There is apparently a tool called node-waf that is in Python and is necessar... | [
"To solve the path problem, I backed up and re-installed Node. To solve the version problem, at the suggestion of some bright soul on the #nodejs channel, I created a symbolic link at ~/bin/python that pointed to the right version (that solved a lot of my own problems too, starting up the wrong version from the co... | [
3
] | [] | [] | [
"node.js",
"npm",
"python",
"waf"
] | stackoverflow_0007051276_node.js_npm_python_waf.txt |
Q:
Using regex to replace object within brackets in a text file
I have an opened text file, f. I need to find every instance of of square brackets enclosing text, inclusive of the brackets. For example, with --
1 - This is the [first] line
2 - (And) another line
3 - [Finally][B] the last
It would match/print:
1 - [F... | Using regex to replace object within brackets in a text file | I have an opened text file, f. I need to find every instance of of square brackets enclosing text, inclusive of the brackets. For example, with --
1 - This is the [first] line
2 - (And) another line
3 - [Finally][B] the last
It would match/print:
1 - [First]
3 - [Finally]
3 - [B]
Once I have printed these matches, I'... | [
"You have to escape the [] chars and use a non greedy operator\nr'\\[.+?\\]'\n\nNote you won't be able to have nested brackets like [foo [bar]] using regex.\nAlso, to remove extra spaces, add \\s? to the end of the regex.\nExample:\n>>> a = '''1 - This is the [first] line\n2 - (And) another line\n3 - [Finally][B] t... | [
2,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007053202_python_regex.txt |
Q:
How to parse a numpy array?
I have Numpy array:
[[12 13 14],[15 16 17],[18 19 20]]
How do I get this
[[12, 13, 14], [15, 16, 17],[18 ,19, 20]]
A:
When you see a numpy array printed without commas, you are just looking at its string representation. If you want it printed with commas, you could convert it to a ... | How to parse a numpy array? | I have Numpy array:
[[12 13 14],[15 16 17],[18 19 20]]
How do I get this
[[12, 13, 14], [15, 16, 17],[18 ,19, 20]]
| [
"When you see a numpy array printed without commas, you are just looking at its string representation. If you want it printed with commas, you could convert it to a Python list:\nIn [45]: print(arr)\n[[12 13 14]\n [15 16 17]\n [18 19 20]]\n\nIn [46]: arr_list = arr.tolist()\n\nIn [47]: print(arr_list)\n[[12, 13, 14... | [
13
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007057487_numpy_python.txt |
Q:
numpy coercion problem for left-sided binary operator
I am implementing an array-like object that should be interoperable with standard numpy arrays. I just hit an annoying problem that narrows down to the following:
class MyArray( object ):
def __rmul__( self, other ):
return MyArray() # value not important... | numpy coercion problem for left-sided binary operator | I am implementing an array-like object that should be interoperable with standard numpy arrays. I just hit an annoying problem that narrows down to the following:
class MyArray( object ):
def __rmul__( self, other ):
return MyArray() # value not important for current purpose
from numpy import array
print array([... | [
"It turns out that numpy offers a simple fix for this problem. The following code works as intended.\nclass MyArray( object ):\n __array_priority__ = 1. # <- fixes the problem\n def __rmul__( self, other ):\n return MyArray()\n\nMore information can be found here.\n"
] | [
1
] | [] | [] | [
"coercion",
"numpy",
"python"
] | stackoverflow_0007042496_coercion_numpy_python.txt |
Q:
Python regex for matching Twitter usernames in the beginning of a tweet
I have a tweet text like this:
"@user1 @user2 blablabla @user3"
I want to use a regex to filter the users in the beginning of a tweet. That would mean @user1 and @user2. There are not always the same number of users, there might be one, two, ... | Python regex for matching Twitter usernames in the beginning of a tweet | I have a tweet text like this:
"@user1 @user2 blablabla @user3"
I want to use a regex to filter the users in the beginning of a tweet. That would mean @user1 and @user2. There are not always the same number of users, there might be one, two, three...
I'm trying this with re.IGNORECASE:
re.compile(ur'^(@[a-z0-9_]*\s)*'... | [
"Without re, but with itertools:\n>>> tw = \"@user1 @user2 blablabla @user3\"\n>>> import itertools\n>>> list(itertools.takewhile(lambda x: x.startswith('@'), tw.split()))\n['@user1', '@user2']\n\n",
"Try this regular expression: ^(@\\w+\\s)+.\nIn @user1 @user2 blablabla @user3 it will match:\n\n",
"Your egrep ... | [
5,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007057512_python_regex.txt |
Q:
Python 3.x dictionary-based keygen help?
I'm studing Python for one month and I'm trying to make a keygen application by using the dictionary. The idea was to compare each letter in name = input('Name: ') to dict.keys() and print as result dict.values() for each letter of name equal to dict.keys(). That's what I... | Python 3.x dictionary-based keygen help? | I'm studing Python for one month and I'm trying to make a keygen application by using the dictionary. The idea was to compare each letter in name = input('Name: ') to dict.keys() and print as result dict.values() for each letter of name equal to dict.keys(). That's what I wrote:
name = input('Name: ')
kalg = dict()
... | [
"I can only guess, but this could be what you want:\nname = input('Name: ')\nkalg = {'a':'50075', 'b': '18099', 'c': '89885'}\nkeylist = [kalg[letter] for letter in name]\nprint(\" \".join(keylist))\n\n",
"Calling print can't \"keep\" anything (since there is no variable to store it in), and repeatedly assigning ... | [
0,
0
] | [] | [] | [
"algorithm",
"dictionary",
"key_generator",
"python"
] | stackoverflow_0007057534_algorithm_dictionary_key_generator_python.txt |
Q:
Why does Python's tuple not have any method?
Why does Python's tuple not have any method associated with it? e.g. tuple.append(), tuple.remove(), etc.?
If the contents of tuple are accessed as we access list items, then why does tuple not have list-related methods?
A:
tuples are immutable, you cannot change thei... | Why does Python's tuple not have any method? | Why does Python's tuple not have any method associated with it? e.g. tuple.append(), tuple.remove(), etc.?
If the contents of tuple are accessed as we access list items, then why does tuple not have list-related methods?
| [
"tuples are immutable, you cannot change their content.\nEDIT - as commented on the question, and I'm not sure came clear from my answer - there are methods for tuples, but not methods that modify them.\n",
"Tuples are immutable, whereas lists can be modified. This in itself explains why tuples don't have any way... | [
13,
7
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0007057757_python_tuples.txt |
Q:
Python dynamic inheritance: How to choose base class upon instance creation?
Introduction
I have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term "dynamic inheritance" is a class that doesn't inhe... | Python dynamic inheritance: How to choose base class upon instance creation? | Introduction
I have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term "dynamic inheritance" is a class that doesn't inherit from any base class in particular, but rather chooses to inherit from one of s... | [
"I would favor composition over inheritance here. I think your current inheritance hierarchy seems wrong. Some things, like opening the file with or gzip have little to do with the actual image format and can be easily handled in one place while you want to separate the details of working with a specific format o... | [
20,
14,
5,
3
] | [] | [] | [
"design_patterns",
"inheritance",
"oop",
"python"
] | stackoverflow_0007057019_design_patterns_inheritance_oop_python.txt |
Q:
Matplotlib in wxpython-plotting aborts
I'm using matplotlib in my wx.Frame to draw some arrows and text at a certain position. The number and position of the arrows is based on previously created data.
I do some calculations but basically it's like this:
arrow = primer
for each primer:
draw one arrow at position ... | Matplotlib in wxpython-plotting aborts | I'm using matplotlib in my wx.Frame to draw some arrows and text at a certain position. The number and position of the arrows is based on previously created data.
I do some calculations but basically it's like this:
arrow = primer
for each primer:
draw one arrow at position y - 0.05 to the previos arrow (primer_y - 0.... | [
"\nStick\n print((primer_x+0.06, primer_y))\n\ninside the loop. You'll find that the arrows cease to be drawn when\nprimer_y becomes negative.\nDon't draw the arrows with self.axes.annotate while labeling the\narrow with self.fig.text. The axis and the figure use different\ncoordinate systems. Changing self.... | [
3
] | [] | [] | [
"matplotlib",
"python",
"wxpython"
] | stackoverflow_0007058494_matplotlib_python_wxpython.txt |
Q:
Pythonic iterable difference
I've written some code to find all the items that are in one iterable and not another and vice versa. I was originally using the built in set difference, but the computation was rather slow as there were millions of items being stored in each set. Since I know there will be at most a... | Pythonic iterable difference | I've written some code to find all the items that are in one iterable and not another and vice versa. I was originally using the built in set difference, but the computation was rather slow as there were millions of items being stored in each set. Since I know there will be at most a few thousand differences I wrote ... | [
"Here is a more pythonic solution:\na, b = set(a_iter), set(b_iter)\n\nreturn a - b, b - a\n\nPythonic does not mean fast, but rather elegant and readable.\nHere is a solution that might be faster:\na, b = set(a_iter), set(b_iter)\n\n# Get all the candidate return values\nsymdif = a.symmetric_difference(b)\n\n# Sin... | [
2,
0,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0007058476_python_python_2.7.txt |
Q:
Iterating over items in a search result view with Django haystack MultiValueField
If I have a MultiValueField on one of my search indexes, and I want to display each value in the search results, how would I do that? It seems like something is not being formatted appropriately or I am somehow misunderstanding the M... | Iterating over items in a search result view with Django haystack MultiValueField | If I have a MultiValueField on one of my search indexes, and I want to display each value in the search results, how would I do that? It seems like something is not being formatted appropriately or I am somehow misunderstanding the MultiValueField?
class PageAttachmentIndex(indexes.SearchIndex):
# This should refer... | [
"The actual issue is that the M2M field is not indexed in SearchEngine. You should return primitive objects( list, string, int, etc.) in the prepare_ function and not Django Moldel instances.\ne.g.\n\ndef prepare_attr(self, obj): \n return [str(v) for v in obj.attrs.all()]\n\n"
] | [
1
] | [] | [] | [
"django",
"django_haystack",
"python",
"search"
] | stackoverflow_0004000482_django_django_haystack_python_search.txt |
Q:
Python: elif or new if?
What is better to use:
if var in X:
#do_whatever
elif (var in Y):
#do_whatever2
or:
if var in X:
#do_whatever
if var in Y:
#do_whatever2
Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??
ED... | Python: elif or new if? | What is better to use:
if var in X:
#do_whatever
elif (var in Y):
#do_whatever2
or:
if var in X:
#do_whatever
if var in Y:
#do_whatever2
Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??
EDIT: Great answers.. But can I... | [
"It makes a difference in some cases.\nSee this example:\ndef foo(var):\n if var == 5:\n var = 6\n elif var == 6:\n var = 8\n else:\n var = 10\n\n return var\n\ndef bar(var):\n if var == 5:\n var = 6\n if var == 6:\n var = 8\n if var not in (5, 6):\n va... | [
16,
5,
2,
2,
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0007052393_if_statement_python.txt |
Q:
How do I get a GtkTreePath or GtkTreeIter to the last row in a GtkTreeModel?
I want to get a GtkTreePath or GtkTreeIter to the last row in a GtkTreeModel, but GtkTreeModel does not have a function for that.
I'll be happy with answers and examples in either C, or Python, or both ;).
A:
You should be able to go th... | How do I get a GtkTreePath or GtkTreeIter to the last row in a GtkTreeModel? | I want to get a GtkTreePath or GtkTreeIter to the last row in a GtkTreeModel, but GtkTreeModel does not have a function for that.
I'll be happy with answers and examples in either C, or Python, or both ;).
| [
"You should be able to go through a GtkTreePath, a bit of a hack maybe but still within the API:\nGtkTreePath *path;\nGtkTreeIter iter;\n\n/* With NULL as iter, we get the number of toplevel nodes. */\ngint rows = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(model), NULL);\n\n/* Now get a path from the index. */\n... | [
4,
3,
2,
2
] | [] | [] | [
"c",
"gtk",
"pygtk",
"python"
] | stackoverflow_0002895577_c_gtk_pygtk_python.txt |
Q:
PIL changes file name while saving
When I use the save method in PIL to save a file, it saves it by the right file name I provide, but on clicking on the file name the path shows to be different. (Sorry, my explanation sucks).
For example, if u go to http://shopperspoll.webfactional.com/media/images/emailTemplate/... | PIL changes file name while saving | When I use the save method in PIL to save a file, it saves it by the right file name I provide, but on clicking on the file name the path shows to be different. (Sorry, my explanation sucks).
For example, if u go to http://shopperspoll.webfactional.com/media/images/emailTemplate/mergedImages/
there is an image named "7... | [
"As 7962716_41tlK2uT%2BSL.SL75.png is a valid filename, it is saved on your filesystem. The browser urlencodes the filename, so 7962716_41tlK2uT%2BSL.SL75.png becomes 7962716_41tlK2uT%252BSL.SL75.png; the percent sign in your filename becomes %25. \nSo PIL does not change your filename, your browser escapes your ac... | [
4
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0007059239_python_python_imaging_library.txt |
Q:
writing "missing array values" to a file
import numpy as np
f1= "test_io.csv"
f2= "test_io2.csv"
array = np.genfromtxt(f1,delimiter=',',missing_values='NA', filling_values=1.e20)
np.savetxt(f2,array,delimiter=',')
#np.savetxt(f2,array,delimiter=', missing_values = 1.e20, filling_values='NA')
As suggested by th... | writing "missing array values" to a file | import numpy as np
f1= "test_io.csv"
f2= "test_io2.csv"
array = np.genfromtxt(f1,delimiter=',',missing_values='NA', filling_values=1.e20)
np.savetxt(f2,array,delimiter=',')
#np.savetxt(f2,array,delimiter=', missing_values = 1.e20, filling_values='NA')
As suggested by the second "savetxt", I would like to be able to... | [
"There isn't a built in way to do it, as it's usually easier to just roll your own, than it is to make a \"one-size-fits-all\" function meet your needs. \nIn your case, I wouldn't bother with the csv module. It's great when you need to read complex data in, but for something this simple, it's far easier to not use... | [
1
] | [] | [] | [
"csv",
"file_io",
"numpy",
"python"
] | stackoverflow_0007053299_csv_file_io_numpy_python.txt |
Q:
how to use the output/value of variable in python
I'm learning python. So here's what I'm after:
Inside a python script I have the following:
back_minutes1 = int(sys.argv[2])
back_minutes = timedelta(minutes=back_minutes)
This works fine, but I'm essentially creating a 'trash variable' to make it work. If this ... | how to use the output/value of variable in python | I'm learning python. So here's what I'm after:
Inside a python script I have the following:
back_minutes1 = int(sys.argv[2])
back_minutes = timedelta(minutes=back_minutes)
This works fine, but I'm essentially creating a 'trash variable' to make it work. If this were say bash, I could probably do something like
back... | [
"Why not \nback_minutes = timedelta(minutes=int(sys.argv[2]))\n\n"
] | [
4
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0007059787_python_variables.txt |
Q:
Estimating aspect ratio of a convex hull
What would be the best way to approximate the aspect ratio of a convex hull in Python? I have already tried doing this by fitting the vertices of the convex hull with an ellipse and taking the ratio of the semi- and major-axis. The results are not satisfactory though, so I'... | Estimating aspect ratio of a convex hull | What would be the best way to approximate the aspect ratio of a convex hull in Python? I have already tried doing this by fitting the vertices of the convex hull with an ellipse and taking the ratio of the semi- and major-axis. The results are not satisfactory though, so I'm now looking into deriving the aspect ratio d... | [
"Typically, you'd find the eigenvectors of the covariance matrix of the point cloud. The aspect ratio is the ratio of the largest to smallest eigenvalues.\nAs an example for a bunch of random points (you'd just apply the same thing to your convex hull, only using the vertices):\nimport matplotlib.pyplot as plt\nim... | [
11
] | [] | [] | [
"geometry",
"python"
] | stackoverflow_0007059841_geometry_python.txt |
Q:
Reopened PyGtk window is empty
I am working with Glade to make a simple GUI application using PyGTK. I have two windows, one only showing up when a button is pressed.
def on_preview_clicked(self, widget):
print "You clicked the Preview button"
prev = self.builder.get_object("previewWindow... | Reopened PyGtk window is empty | I am working with Glade to make a simple GUI application using PyGTK. I have two windows, one only showing up when a button is pressed.
def on_preview_clicked(self, widget):
print "You clicked the Preview button"
prev = self.builder.get_object("previewWindow")
prev.show()
The windo... | [
"Without a working testcase of this, it's difficult to be sure, but try changing it from show() to show_all(), to be sure that all the child widgets of the window are shown as well. \n"
] | [
0
] | [] | [] | [
"glade",
"hide",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0007057960_glade_hide_pygtk_python_user_interface.txt |
Q:
Accessing module level variables, from within a function in the module
I'd like to be able to do something like this:
#mymodule
var = None
def load():
var = something()
Other module(s):
#secondmodule
import mymodule
mymodule.load()
#thirdmodule
from mymodule import var
print var #Shouldn't be None
But I do... | Accessing module level variables, from within a function in the module | I'd like to be able to do something like this:
#mymodule
var = None
def load():
var = something()
Other module(s):
#secondmodule
import mymodule
mymodule.load()
#thirdmodule
from mymodule import var
print var #Shouldn't be None
But I don't know how to reference a modules variable from a function defined in the ... | [
"Just change the function definition to:\ndef load():\n global var # this line has been added to the original code\n var = something()\n\nGlobal variables are read-only from sibling methods. More accurately unless a variable is specified as global, Python consider it as local, but a read access to a local var... | [
92,
23
] | [] | [] | [
"python"
] | stackoverflow_0007060711_python.txt |
Q:
How do I tell pyparsing to discard parts of the parsed string?
I'm writing a parser for some marked-up data, and I'd like to get pyparsing to discard things like start and end tags in the final result, leaving just the data.
Can I do this, or do I just have to name the value appropriately and pull them out manual... | How do I tell pyparsing to discard parts of the parsed string? | I'm writing a parser for some marked-up data, and I'd like to get pyparsing to discard things like start and end tags in the final result, leaving just the data.
Can I do this, or do I just have to name the value appropriately and pull them out manually?
| [
"\"Suppress\" is probably what you want. You can use the Suppress class explicitly, as in dont_care = Suppress(Word(alphas)) or call suppress() on any expression, dont_care = Word(alphas).suppress(). This will suppress the matched tokens from appearing in the parsed output.\n"
] | [
1
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0007060691_parsing_pyparsing_python.txt |
Q:
Itertools for containers
Considder the following interactive example
>>> l=imap(str,xrange(1,4))
>>> list(l)
['1', '2', '3']
>>> list(l)
[]
Does anyone know if there is already an implementation somewhere out there with a version of imap (and the other itertools functions) such that the second time list(l) is exe... | Itertools for containers | Considder the following interactive example
>>> l=imap(str,xrange(1,4))
>>> list(l)
['1', '2', '3']
>>> list(l)
[]
Does anyone know if there is already an implementation somewhere out there with a version of imap (and the other itertools functions) such that the second time list(l) is executed you get the same as the ... | [
"You do not have to build such an object for each type of container. Basically, you have the following:\nmkimap = lambda: imap(str,xrange(1,4))\nlist(mkimap())\nlist(mkimap())\n\nNow you onlky need a nice wrapping object to prevent the \"ugly\" function calls. This could work this way:\nclass MultiIter(object):\n ... | [
7,
1
] | [
"Iterators are my favorite topic ;)\nfrom itertools import imap\n\nclass imap2(object):\n def __init__(self, f, *args):\n self.g = imap(f,*args)\n self.lst = []\n self.done = False\n\n def __iter__(self):\n while True:\n try: # try to get something from g\n ... | [
-1
] | [
"iterator",
"python"
] | stackoverflow_0007060229_iterator_python.txt |
Q:
Getting out of a recursive loop in Python
I have the following code, which results in Python "quitting unexpectedly":
def profile_videos_sort_and_filter(profile, sort, filter, uncredited_videos, list_of_credits=[]):
"""Given a sort and filter, this will order the credits and return a credit_set."""
if filt... | Getting out of a recursive loop in Python | I have the following code, which results in Python "quitting unexpectedly":
def profile_videos_sort_and_filter(profile, sort, filter, uncredited_videos, list_of_credits=[]):
"""Given a sort and filter, this will order the credits and return a credit_set."""
if filter == 'user' or filter == 'all':
if fil... | [
"Add a condition for sort='position' and/or filter='newest'.\n",
"Where do you handle filter=='newest'? The code will loop forever unless you add an elif filter=='newest' and do something on that case.\n"
] | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007061018_django_python.txt |
Q:
Can you recommend a good cross-platform application development framework?
I am looking to tap into the immense wisdom and experience of the Stackoverflow community to help me choose a good cross-platform application development framework.
The target application is a desktop graphics app supporting as many existi... | Can you recommend a good cross-platform application development framework? | I am looking to tap into the immense wisdom and experience of the Stackoverflow community to help me choose a good cross-platform application development framework.
The target application is a desktop graphics app supporting as many existing desktop environments as reasonable (Linux, BSD, Windows, Mac). Ideally Open ... | [
"Qt covers just about everything:\n\nis proper open source, with active development and a vibrant community\nthe portability aspect is covered: goes from embedded to big systems with everything (particular Windows, Mac OS X, Linux) in between; *BSD should not be an issue either, \nthe GUI aspects, \nhas good Open G... | [
10,
2
] | [] | [] | [
"c++",
"cross_platform",
"frameworks",
"python",
"user_interface"
] | stackoverflow_0007058947_c++_cross_platform_frameworks_python_user_interface.txt |
Q:
A scrollbar event when scrolling?
I need an event for detecting if an user has moved the scrollbar position to another one.
In other words, if the user does scroll up/down, would it be possible to catch a signal so I can know the scroll has been changed its position?
I think it's not important, but the scrollbar I... | A scrollbar event when scrolling? | I need an event for detecting if an user has moved the scrollbar position to another one.
In other words, if the user does scroll up/down, would it be possible to catch a signal so I can know the scroll has been changed its position?
I think it's not important, but the scrollbar I refer to is inside a QGraphicsView.
Re... | [
"Sliders have a sliderMoved(int value) signal, where value is the new position of slider. \n",
"If you need to get notified when the scroll bar position is changed, you need to subclass the QGraphicsView and reimplement the QWidget::mouseMoveEvent(QMouseEvent*). For this you also need to enable mouse tracking. He... | [
7,
0
] | [] | [] | [
"c++",
"events",
"pyqt",
"python",
"qt"
] | stackoverflow_0007060534_c++_events_pyqt_python_qt.txt |
Q:
turning an abstract queue upside down with stack
Why does it take 4n calls to turn an abstract queue upside down with the help of an abstract stack? Somebody care to help me with this question please?
A:
I assume you want the nodes to end up in the original queue. In that case you have to remove all the nodes ... | turning an abstract queue upside down with stack | Why does it take 4n calls to turn an abstract queue upside down with the help of an abstract stack? Somebody care to help me with this question please?
| [
"I assume you want the nodes to end up in the original queue. In that case you have to remove all the nodes from the queue one at a time, pushing each onto the stack. So far that's one read (from the queue) and a push (onto the stack). Then you have to pop nodes off the stack and put them back on the queue. Tha... | [
1
] | [] | [] | [
"abstract",
"python",
"queue",
"stack"
] | stackoverflow_0007061070_abstract_python_queue_stack.txt |
Q:
Preventing a class's function attributes from being passed self as the first arg
Okay, so I've got a class where one of the attributes is a callback function. Problem is, whenever I call it from within the class (e.g. as self.function_attr(), it gets passed self as the first argument. Here's an idea of what I'm wo... | Preventing a class's function attributes from being passed self as the first arg | Okay, so I've got a class where one of the attributes is a callback function. Problem is, whenever I call it from within the class (e.g. as self.function_attr(), it gets passed self as the first argument. Here's an idea of what I'm working with:
def callback(a, b):
# do something with a, b
class A:
def __init_... | [
"You just need to make it a staticmethod when you bind it to the class.\ndef callback(a, b):\n # do something with a, b\n\nclass A:\n def __init__(self, callback):\n # now it won't get passed self\n self.callback = staticmethod(callback)\n self.callback(1, 2)\n\nor \nclass A:\n def __i... | [
2,
0
] | [] | [] | [
"oop",
"python",
"syntax"
] | stackoverflow_0007061403_oop_python_syntax.txt |
Q:
How do I pass values from one class to another; each running potentially on different threads?
I have a file called filterspecs.py that contains 3 things:
tls = threading.local()
class A which inherits from django.contrib.admin.views.main.ChangeList
class B which inherits from django.contrib.admin.filterspecs.Fil... | How do I pass values from one class to another; each running potentially on different threads? | I have a file called filterspecs.py that contains 3 things:
tls = threading.local()
class A which inherits from django.contrib.admin.views.main.ChangeList
class B which inherits from django.contrib.admin.filterspecs.FilterSpec
Goal: I want to pass a value, a list, available to an instance of A to an instance of B. Si... | [
"It sounds like you want to share data between not just two classes, but between two completely different HTTP requests. HTTP is stateless -- Apache is not designed to accommodate stateful web applications. You must save the data to a database and read it back in the second request. (Or you can run your web appl... | [
1
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0007061366_django_mod_wsgi_python_wsgi.txt |
Q:
Why CherryPy session does not require a secret key?
I noticed that cherrypy session does not require a secret key configuration. On the contrary, Pylons session does: http://docs.pylonsproject.org/projects/pylons_framework/dev/sessions.html
I'm concerned about security issues if I'm using session to remember user ... | Why CherryPy session does not require a secret key? | I noticed that cherrypy session does not require a secret key configuration. On the contrary, Pylons session does: http://docs.pylonsproject.org/projects/pylons_framework/dev/sessions.html
I'm concerned about security issues if I'm using session to remember user authentication.
Any one can explain why cherrypy session... | [
"There are basically two different ways of maintaining session state: on the server or on the client.\nWith the server-side approach, you keep the session data in files, a database, or in memory on the server and assign an id to it. This session id is then sent to the client and usually stored in a cookie (although... | [
18
] | [] | [] | [
"cherrypy",
"pylons",
"python",
"web_frameworks"
] | stackoverflow_0006719036_cherrypy_pylons_python_web_frameworks.txt |
Q:
Calculating Time in Python (datetime.timedelta?)
I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start startTime and then I timestamp the end of the process endTime and I am trying to get the differ... | Calculating Time in Python (datetime.timedelta?) | I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start startTime and then I timestamp the end of the process endTime and I am trying to get the difference in HH:MM:SS and am having no luck.
I get this err... | [
"Use a datetime instead of a time. Subtracting one time from another is meaningless without a date; you can't just assume that they're on the same day and the left operand comes first.\n",
"Depending on what you're doing with the information, you might want to just use time.time:\nimport time\n\nstarttime = time.... | [
10,
5
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0007061479_datetime_python.txt |
Q:
Changing database per view & accessing multiple databases per view
I'm having some problems using SQLAlchemy in Pyramid. Although I can find examples of what I need, they're normally very short and lacking. So I've ended up with patchy code that barely makes any sense. So I'm hoping someone could give a fuller exa... | Changing database per view & accessing multiple databases per view | I'm having some problems using SQLAlchemy in Pyramid. Although I can find examples of what I need, they're normally very short and lacking. So I've ended up with patchy code that barely makes any sense. So I'm hoping someone could give a fuller example of what I need to do.
I have 4 databases all with the same schema. ... | [
"Configuring and connection for each request seems like a lot of work to me. I would create four session handlers in my model module and just choose from them.\nExample:\nmodels/__init__.py\n\nDBSession1 = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) \nDBSession2 = scoped_session(sessionmaker... | [
8,
1
] | [] | [] | [
"pylons",
"pyramid",
"python",
"sqlalchemy"
] | stackoverflow_0007050579_pylons_pyramid_python_sqlalchemy.txt |
Q:
Minimum Distance Algorithm using GDAL and Python
I'm trying to implement the Minimum Distance Algorithm for image classification using GDAL and Python. After calculating the mean pixel-value of the sample areas and storing them into a list of arrays ("sample_array"), I read the image into an array called "values".... | Minimum Distance Algorithm using GDAL and Python | I'm trying to implement the Minimum Distance Algorithm for image classification using GDAL and Python. After calculating the mean pixel-value of the sample areas and storing them into a list of arrays ("sample_array"), I read the image into an array called "values". With the following code I loop through this array:
va... | [
"You should definitely be using NumPy. I work with some pretty large raster datasets and NumPy burns through them. On my machine, with the code below there's no noticeable delay for a 1000 x 1000 array. An explanation of how this works follows the code.\nimport numpy as np\nfrom scipy.spatial.distance import cdist\... | [
5,
2
] | [] | [] | [
"classification",
"gdal",
"python"
] | stackoverflow_0005903867_classification_gdal_python.txt |
Q:
Do any Python environments support edit-and-continue?
Is it possible in Python to make changes to code that you're currently debugging and continue without having to restart everything? (The way I can in C#, for example.)
A:
You have the full power of the interpreter at your fingertips with pdb, use
import pdb
... | Do any Python environments support edit-and-continue? | Is it possible in Python to make changes to code that you're currently debugging and continue without having to restart everything? (The way I can in C#, for example.)
| [
"You have the full power of the interpreter at your fingertips with pdb, use \nimport pdb\npdb.set_trace()\n\nFrom there you can define and create new objects, redefine existing ones, modify and reload modules, etc. Syntax is simalar to gdb. If you're using ipython, ipdb may be a nicer choice, or you can automati... | [
12,
1
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0007061628_debugging_python.txt |
Q:
python: howto open firefox (osx)
I need to associate to a hyperlink the command to execute firefox.
Seeing as I can do it in a terminal, I used
os.system("/Applications/Firefox.app/Contents/MacOS/firefox"+' \"'+arg+'\" & 2> /dev/null')
but this doesnt work at all: I get a "Firefox is already running" window - wh... | python: howto open firefox (osx) | I need to associate to a hyperlink the command to execute firefox.
Seeing as I can do it in a terminal, I used
os.system("/Applications/Firefox.app/Contents/MacOS/firefox"+' \"'+arg+'\" & 2> /dev/null')
but this doesnt work at all: I get a "Firefox is already running" window - while under Linux my url gets loaded in ... | [
"To be more specific, to choose Firefox, if it is not the standard browser on the OS:\n>>> import webbrowser\n>>> controller = webbrowser.get('Firefox')\n>>> controller.open('http://www.google.com')\nTrue\n\n",
"webbrowser\n"
] | [
3,
2
] | [] | [] | [
"firefox",
"macos",
"python"
] | stackoverflow_0007062094_firefox_macos_python.txt |
Q:
Multiple common prefixes among different paths
Sorry for the title, my problem is as follows. I have a list of paths and I want to get multiple common prefixes. For example, given I have:
['/usr/local/lib/python2.7/dist-packages/pkg_name-0.1-py2.7.egg/pkg_name',
'/usr/local/lib/python2.7/dist-packages/pkg_name-0.... | Multiple common prefixes among different paths | Sorry for the title, my problem is as follows. I have a list of paths and I want to get multiple common prefixes. For example, given I have:
['/usr/local/lib/python2.7/dist-packages/pkg_name-0.1-py2.7.egg/pkg_name',
'/usr/local/lib/python2.7/dist-packages/pkg_name-0.1-py2.7.egg/EGG-INFO',
'/usr/bin/pkg_name']
I want... | [
"The problem is not well-defined. What do you want to have in this case:\n/usr/bin/a\n/usr/bin/b\n/usr/etc\n/usr/local\n\nShall it be one /usr or two: /usr/bin /usr, or three?\nIn either case, the algorithm will be like this:\n\nsort the list\ntake the first element and do os.path.commonprefix() with 2nd, 3rd, ...,... | [
2
] | [] | [] | [
"path",
"prefix",
"prefixes",
"python"
] | stackoverflow_0007062310_path_prefix_prefixes_python.txt |
Q:
What is the correct procedure for multiple, sequential communications over a socket?
I've been struggling along with sockets, making OK progress, but I keep running into problems, and feeling like I must be doing something wrong for things to be this hard.
There are plenty of tutorials out there that implement a T... | What is the correct procedure for multiple, sequential communications over a socket? | I've been struggling along with sockets, making OK progress, but I keep running into problems, and feeling like I must be doing something wrong for things to be this hard.
There are plenty of tutorials out there that implement a TCP client and server, usually where:
The server runs in an infinite loop, listening for a... | [
"\nIf you know that you will communicate between the two processes soon again, there is no need for closing the connection. If your server has to deal with other connections as well, you want to make it multithreaded, though. \nThe same. You know that both have to do the same thing, right?\nYou have to create a new... | [
2
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0007062317_python_sockets.txt |
Q:
Is there a way to know how much data is available in a Python socket to receive?
I have figured out that I must use ioctl. There are similar questions here:
How to tell how much data is in a Socket's send buffer
Determing the number of bytes ready to be recv()'d
My questions are:
What is an equivalent to FIONRE... | Is there a way to know how much data is available in a Python socket to receive? | I have figured out that I must use ioctl. There are similar questions here:
How to tell how much data is in a Socket's send buffer
Determing the number of bytes ready to be recv()'d
My questions are:
What is an equivalent to FIONREAD in Python? How do I call sock.ioctl() to obtain the amount of bytes available?
What... | [
"As there is no portable way of doing this (and often the answer is wrong), there isn't a built-in way of asking for it.\nIf you use non-blocking sockets, simply read as much data as possible, and only data which is present will be returned. \n",
"You could get that number, but the number is less than useful. The... | [
4,
0
] | [] | [] | [
"fcntl",
"ioctl",
"python",
"recv",
"sockets"
] | stackoverflow_0007061488_fcntl_ioctl_python_recv_sockets.txt |
Q:
why would these two SQL statements resulted an operational deadlock error?
I have this table:
CREATE TABLE `notify` (
`id` int(11) NOT NULL auto_increment,
`notify_type` char(1) NOT NULL,
`notify_id` int(10) unsigned NOT NULL,
`create_time` timestamp NOT NULL default '0000-00-00 00:00:00',
`user` int(10)... | why would these two SQL statements resulted an operational deadlock error? | I have this table:
CREATE TABLE `notify` (
`id` int(11) NOT NULL auto_increment,
`notify_type` char(1) NOT NULL,
`notify_id` int(10) unsigned NOT NULL,
`create_time` timestamp NOT NULL default '0000-00-00 00:00:00',
`user` int(10) unsigned NOT NULL,
`update_time` timestamp NOT NULL default '0000-00-00 00:00... | [
"According to MySQL's doc, your query looks fine. However there is a bug that may be related.\nYou can try switching the engine used by the table, in 5.0 you can try BDB (Berkeley DB) but it is unsupported now, otherwise I afraid the best bet is MyISAM.\nOr, putting LOCK TABLES ... UNLOCK TABLES around the insert m... | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0007061874_mysql_python.txt |
Q:
Eclipse - interactive shell for python not working
I've installed and configured Pydev with Eclipse but when I try to use interactive shell I get errors. Can someone have a look and advise?
Code for two functions:
def convert_milage(t): # t - number of miles per 1 gallon
litersPer100Kilometers = 100/ ((t * 1.... | Eclipse - interactive shell for python not working | I've installed and configured Pydev with Eclipse but when I try to use interactive shell I get errors. Can someone have a look and advise?
Code for two functions:
def convert_milage(t): # t - number of miles per 1 gallon
litersPer100Kilometers = 100/ ((t * 1.609) / 3.785)
return litersPer100Kilometers
def li... | [
"You need to open the console for the file you're in, not just use the general python console, as that knows nothing about the functions in your source file.\nPress Ctrl-Alt-Enter and select Current active editor. \nThat should import the current module into your shell and make things work better.\n"
] | [
3
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0007062780_eclipse_pydev_python.txt |
Q:
Probability distribution function in Python
I know how to create an histogram in Python, but I would like that it is the probability density distribution.
Let's start with my example. I have an array d, with a size of 500000 elements. With the following code I am building a simple histogram telling me how many ele... | Probability distribution function in Python | I know how to create an histogram in Python, but I would like that it is the probability density distribution.
Let's start with my example. I have an array d, with a size of 500000 elements. With the following code I am building a simple histogram telling me how many elements of my array d are between every bin.
max_va... | [
"It's not clear what your hist function is. If you're using NumPy's histogram, try setting density=True. See http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html .\n"
] | [
2
] | [] | [] | [
"histogram",
"numpy",
"probability",
"python"
] | stackoverflow_0007062936_histogram_numpy_probability_python.txt |
Q:
AppEngine WebService authentication handling
I'm doing a JSON WebService backend for an iPhone application. Is there any best practice or existing frameworks (I use Python) to handle authentication and keeping a session between requests? I guess you use some form of ticket system because you can't use regular sess... | AppEngine WebService authentication handling | I'm doing a JSON WebService backend for an iPhone application. Is there any best practice or existing frameworks (I use Python) to handle authentication and keeping a session between requests? I guess you use some form of ticket system because you can't use regular sessions like with web browsers?
| [
"You should definitely go for Oauth. \nHave a look to the gtm-oauth library, it allows Cocoa applications to sign in to services using OAuth for authentication and authorization and it works with Google APIs and with any standard OAuth provider.\nCheck this blog post for further information.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007062566_google_app_engine_python.txt |
Q:
saxutils.escape() escapes semicolon twice
I'm trying to escape semicolon in by saxutils.escape method.
saxutils.escape('<;', {';': ';'})
I expect it to produce
'<;'
But it gives
'<;;'
Is this by design? And how can I get my expected result?
A:
Your problem is that saxutils.escape works in... | saxutils.escape() escapes semicolon twice | I'm trying to escape semicolon in by saxutils.escape method.
saxutils.escape('<;', {';': ';'})
I expect it to produce
'<;'
But it gives
'<;;'
Is this by design? And how can I get my expected result?
| [
"Your problem is that saxutils.escape works in two steps. First, it parses <, >, and &, then it uses entities to parse the result of that parsing.\nSo once < has been replaced by <, you've got <;, so you end up with <;;.\nBasically, what it's doing makes sense. If you need to escape semicolons, it's... | [
3,
1,
1
] | [] | [] | [
"python",
"sax"
] | stackoverflow_0007063026_python_sax.txt |
Q:
I want to call a reduce with a list that contains longs an ints in python
I am trying to call a reduce on a list that contains ints and longs. For example,
reduce( int.__mul__, [ 231212312412L, 3 ], 1 )
but I get an unimplemented error. and when I replace the int's mul method with the long's mul method it complai... | I want to call a reduce with a list that contains longs an ints in python | I am trying to call a reduce on a list that contains ints and longs. For example,
reduce( int.__mul__, [ 231212312412L, 3 ], 1 )
but I get an unimplemented error. and when I replace the int's mul method with the long's mul method it complains that it is getting an int. Must I map them all to a long first? like this.
r... | [
">>> from operator import mul\n>>> reduce( mul, map( long, [ 12312412314L, 5 ] ), 1 )\n61562061570L\n>>> reduce( mul, [ 231212312412L, 3 ], 1 )\n693636937236L\n>>> \n\noperator has:\n'abs',\n 'add',\n 'and_',\n 'attrgetter',\n 'concat',\n 'contains',\n 'countOf',\n 'delitem',\n 'delslice',\n 'div',\n 'eq',\n 'floor... | [
7,
5,
3,
2
] | [] | [] | [
"int",
"long_integer",
"python",
"reduce"
] | stackoverflow_0007062617_int_long_integer_python_reduce.txt |
Q:
Iterating over multiple files and replacing a single line - why doesn't it work?
I'm trying to use the fileinput module to iterate over a bunch of files and replace a single line in them. This is how my code looks:
def main():
for root, dirs, files in os.walk('target/generated-sources'):
for line in fi... | Iterating over multiple files and replacing a single line - why doesn't it work? | I'm trying to use the fileinput module to iterate over a bunch of files and replace a single line in them. This is how my code looks:
def main():
for root, dirs, files in os.walk('target/generated-sources'):
for line in fileinput.input([os.path.join(root, file) for file in files if file.endsWith('.java')], ... | [
"Your list comprehension is returning empty lists when a root does not contain .java files. When your script passes an empty list to fileinput.input(), it reverts to the default expecting input from stdin. Since there is nothing coming in from stdin, your script blocks.\nTry this instead:\ndef main():\n for roo... | [
4,
1
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0007063014_python_python_2.x.txt |
Q:
Include a .py-file, still not ruining cronjob (Python, beginner)?
I'm building a service, which has a few cronjobs running, written in Python. However, this is my first Python-project ever, so I'm still a very beginner.
What I'm doing now, is that I have my database-connection handled on every file, so basically i... | Include a .py-file, still not ruining cronjob (Python, beginner)? | I'm building a service, which has a few cronjobs running, written in Python. However, this is my first Python-project ever, so I'm still a very beginner.
What I'm doing now, is that I have my database-connection handled on every file, so basically if I wanted to change the host, I would need to go through all the files... | [
"If it's really just a couple of settings for a single database connection, just put it in a Python module and import it in all of your files. Why add any complexity you don't need?\nIf it's more complicated, use ConfigParser as @AdamMatan suggested.\n# dbconfig.py\nhost = '127.0.0.1'\nuser = 'stack'\npassword = 'o... | [
3,
1,
0
] | [] | [] | [
"cron",
"include",
"php",
"python"
] | stackoverflow_0007063368_cron_include_php_python.txt |
Q:
Best full-text search for google-app-engine
did you know the best full-text search on gae ?
thanks
A:
Read this blog post which details how to add full-text search to App Engine models.
It also details how to make only certain fields searchable, and turn on stemming.
A:
Now we can use experimental Search API:
... | Best full-text search for google-app-engine | did you know the best full-text search on gae ?
thanks
| [
"Read this blog post which details how to add full-text search to App Engine models.\nIt also details how to make only certain fields searchable, and turn on stemming.\n",
"Now we can use experimental Search API:\n\nThe Search API allows your application to perform Google-like searches\n over structured data. Yo... | [
3,
3
] | [
"Google App Engine - Full Text Search\n"
] | [
-2
] | [
"django",
"full_text_search",
"google_app_engine",
"python"
] | stackoverflow_0002679601_django_full_text_search_google_app_engine_python.txt |
Q:
Where can I find the source for type list?
Where can I find the source for Python's list type? I've had a quick look in its SVN repo (2.7 branch) but it's a very scary place.
Edit: Since Python migrated from SVN a while back, to be more contemporary I'll link to its HG repo (2.7 branch) as well.
A:
You can find ... | Where can I find the source for type list? | Where can I find the source for Python's list type? I've had a quick look in its SVN repo (2.7 branch) but it's a very scary place.
Edit: Since Python migrated from SVN a while back, to be more contemporary I'll link to its HG repo (2.7 branch) as well.
| [
"You can find that code in Objects/listobject.c.\nBeware though, it can be scarier than the repo tree :)\n",
"Don't use the svn repository. Use the Mercurial repository, it's much easier to use. (It's also written in Python!) I've had UnicodeDecodeErrors and such viewing the svn repo, too.\nlist is in listobject.... | [
5,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007064395_list_python.txt |
Q:
Why is my MergeSort so slow in Python?
I'm having some troubles understanding this behaviour.
I'm measuring the execution time with the timeit-module and get the following results for 10000 cycles:
Merge : 1.22722930395
Bubble: 0.810706578175
Select: 0.469924766812
This is my code for MergeSort:
def mergeSort(ar... | Why is my MergeSort so slow in Python? | I'm having some troubles understanding this behaviour.
I'm measuring the execution time with the timeit-module and get the following results for 10000 cycles:
Merge : 1.22722930395
Bubble: 0.810706578175
Select: 0.469924766812
This is my code for MergeSort:
def mergeSort(array):
if len(array) <= 1:
return... | [
"list.pop(0) pops the first element and has to shift all remaining ones, this is an additional O(n) operation which must not happen.\nAlso, slicing a list object creates a copy:\nleft = array[:len(array)/2]\nright = array[len(array)/2:]\n\nWhich means you're also using O(n * log(n)) memory instead of O(n).\nI can't... | [
10,
6,
1,
0
] | [] | [] | [
"algorithm",
"mergesort",
"python",
"sorting"
] | stackoverflow_0007063697_algorithm_mergesort_python_sorting.txt |
Q:
Python Class, add 2D points
how can you add two values using __add__ function
(1,2)+(2,3) = (3,5)
def __add__(self, other):
return Point((lambda x,y:x+y),self,other)
is this the way to think?
What is the probable error!!
A:
That's close, except you need to return NotImplemented if it's not a Point:
def __a... | Python Class, add 2D points | how can you add two values using __add__ function
(1,2)+(2,3) = (3,5)
def __add__(self, other):
return Point((lambda x,y:x+y),self,other)
is this the way to think?
What is the probable error!!
| [
"That's close, except you need to return NotImplemented if it's not a Point:\ndef __add__(self, other):\n if not isinstance(other, Point):\n return NotImplemented\n return Point(self.x + other.x, self.y + other.y)\n\n",
"If I'm understanding you correctly, I would probably do it this way:\ndef __add_... | [
2,
0
] | [] | [] | [
"2d",
"class",
"python"
] | stackoverflow_0007064455_2d_class_python.txt |
Q:
python sys.argv differentiate int and string
Simply put, how can I differentiate these two in test.py:
python test.py 1
python test.py '1'
Workaround is OK.
Edit:
This workaround looks cool but too complex: argparse
Let the invoker specify args later, in python code use arg = input('Please enter either an integ... | python sys.argv differentiate int and string | Simply put, how can I differentiate these two in test.py:
python test.py 1
python test.py '1'
Workaround is OK.
Edit:
This workaround looks cool but too complex: argparse
Let the invoker specify args later, in python code use arg = input('Please enter either an integer or a string')
And other workarounds as presente... | [
"The quotes are consumed by the shell. If you want to get them into python, you'll have to invoke like python test.py 1 \"'2'\" \"'3'\" 4\n",
"It is common handling of args, performed by shell. \" and ' are ignored, since you may use them to pass, for instance, few words as one argument.\nThis means that you can'... | [
4,
3,
2,
2,
1,
0
] | [] | [] | [
"command_line_arguments",
"python"
] | stackoverflow_0007050888_command_line_arguments_python.txt |
Q:
How do I post a file over HTTP using the standard Python library
I am currently using PycURL to trigger a build in Jenkins, by posting to a certain URL. The relevant code looks as follows:
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
# These are the form fields expected by Jenkins
data = [
("name", "C... | How do I post a file over HTTP using the standard Python library | I am currently using PycURL to trigger a build in Jenkins, by posting to a certain URL. The relevant code looks as follows:
curl = pycurl.Curl()
curl.setopt(pycurl.URL, url)
# These are the form fields expected by Jenkins
data = [
("name", "CI_VERSION"),
("value", str(version)),
("name", "integr... | [
"u = urllib.urlopen(url, data=urllib.urlencode(\n {'name': 'CI_VERSION', \n 'value': str(version),\n 'file0': open(metadata_fpath).read(),\n etc. \n etc.})) \n\nYou can d... | [
1,
1
] | [] | [] | [
"http",
"http_post",
"python"
] | stackoverflow_0007064180_http_http_post_python.txt |
Q:
Why absolute paths to templates and css in django ? (Isn't that a bad practice ?)
In django, the documentation asks to use the absolute paths and not the relative paths.
Then, how do they manage portability ?
If I have my template in the project folder then, even a rename of the folder will cause breakage.. !
Then... | Why absolute paths to templates and css in django ? (Isn't that a bad practice ?) | In django, the documentation asks to use the absolute paths and not the relative paths.
Then, how do they manage portability ?
If I have my template in the project folder then, even a rename of the folder will cause breakage.. !
Then what is the reason behind this practice ?
Please explain ?
| [
"Could you post a link to that piece of documentation, please?\nIn Django you configure, in settings.py, the search path for templates (through TEMPLATE_DIRS variable). Then, inside a view, you render a template naming its file relative to one of the path included in TEMPLATE_DIRS. That way, whenever you move you t... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007064564_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.