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:
Python/Perl: timed loop implementation (also with microseconds)?
I would like to use Perl and/or Python to implement the following JavaScript pseudocode:
var c=0;
function timedCount()
{
c=c+1;
print("c=" + c);
if (c<10) {
var t;
t=window.setTimeout("timedCount()",100);
}
}
// main:
timedCount(... | Python/Perl: timed loop implementation (also with microseconds)? | I would like to use Perl and/or Python to implement the following JavaScript pseudocode:
var c=0;
function timedCount()
{
c=c+1;
print("c=" + c);
if (c<10) {
var t;
t=window.setTimeout("timedCount()",100);
}
}
// main:
timedCount();
print("after timedCount()");
var i=0;
for (i=0; i<5; i++) {
prin... | [
"The simplest and most general way I can think of doing this in Python is to use Twisted (an event-based networking engine) to do this.\nfrom twisted.internet import reactor\nfrom twisted.internet import task\n\nc, i = 0, 0\ndef timedCount():\n global c\n c += 1\n print 'c =', c\n\ndef mainCount():\n gl... | [
4,
3,
2,
1
] | [] | [] | [
"loops",
"perl",
"python",
"timing"
] | stackoverflow_0007293341_loops_perl_python_timing.txt |
Q:
Control a specific pin on the Arduino Uno board using pyserial
I have a python code that sends in a pattern, in which a light has to blink in. (say eg. 101010. pattern may vary every time the code is run). when it is executing this infinitely i want an interrupt( again sent by the python code )to save the present ... | Control a specific pin on the Arduino Uno board using pyserial | I have a python code that sends in a pattern, in which a light has to blink in. (say eg. 101010. pattern may vary every time the code is run). when it is executing this infinitely i want an interrupt( again sent by the python code )to save the present conditions of the lights (say it is running 1 of the sequence) and p... | [
"Have a look at this:\nhttps://github.com/ajfisher/arduino-command-server\nIt's something I pulled together on the Arduino side to issue arbitrary commands like switch a pin high / low and set PWM levels etc. It works over both serial and network though it's a touch buggy on the network side at the moment.\nTo use ... | [
0
] | [] | [] | [
"arduino",
"pyserial",
"python"
] | stackoverflow_0007288700_arduino_pyserial_python.txt |
Q:
What's wrong with this python code that should rename files?
this code is meant to ask for a directory, then list al files in that directory, then rename then to their position in that list, problem is I always get error 2, file not found, while if i print the list it apperently does find the files because the lis... | What's wrong with this python code that should rename files? | this code is meant to ask for a directory, then list al files in that directory, then rename then to their position in that list, problem is I always get error 2, file not found, while if i print the list it apperently does find the files because the list is not blank.
import os, sys
path = input("input path: ") ... | [
"Yup, so you do need to add the code from my comment. The problem is os.listdir is only returning base file names so when the rename is called, it expects to find those files in whatever directory Python thinks it should be in. By adding the os.path.join, it will build out the fully qualified path to the file so th... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0007296855_python.txt |
Q:
Django South ignoring my custom rules
I am using a custom Django model field to and widget to render a GoogleMap widget in my admin, i also want to use South with my project to handle database migrations. However after much effort i am unable to generate a custom South rule that fits, this are my custom model and ... | Django South ignoring my custom rules | I am using a custom Django model field to and widget to render a GoogleMap widget in my admin, i also want to use South with my project to handle database migrations. However after much effort i am unable to generate a custom South rule that fits, this are my custom model and the last of the many instrospection rules t... | [
"center isn't a keyword argument, it's a positional argument. You shouldn't use positional arguments with South, it doesn't understand them. (See Custom Fields: Keyword Arguments). You could solve this by providing center with a default value( center=None would be fine) and then following the example code at the... | [
1
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0007295030_django_django_south_python.txt |
Q:
What are dict_keys, dict_items and dict_values?
I came across these three types when I used collections.Counter's viewkeys(), viewitems() and viewvalues() methods.
The values those three methods returned are of types dict_keys, dict_items and dict_values.
They are iterable, as I have noticed.
But my question is, ... | What are dict_keys, dict_items and dict_values? | I came across these three types when I used collections.Counter's viewkeys(), viewitems() and viewvalues() methods.
The values those three methods returned are of types dict_keys, dict_items and dict_values.
They are iterable, as I have noticed.
But my question is, why do these three types exist? Or what's their usage... | [
"The What's new in 2.7 document is one place these are introduced. These \"views\" were introduced (proposed here) for Python 3 (and backported to 2.7, as you've seen) to serve as a best-of-all-worlds for the pieces of the dict they refer to.\nBefore we had the keys/values/items methods which simply made lists. Thi... | [
34
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0007296716_dictionary_list_python.txt |
Q:
Calculating a game's high score table
I need to create a function/method ( in python) which calculates a high score "leaderboard". Each player will have played any number of rounds of the game, recieving a score for each round. I want to know what's the best way to sort the top ranking players (accounting for scor... | Calculating a game's high score table | I need to create a function/method ( in python) which calculates a high score "leaderboard". Each player will have played any number of rounds of the game, recieving a score for each round. I want to know what's the best way to sort the top ranking players (accounting for score AND number of rounds played). The possibl... | [
"What you are asking is essentially how we define \"good\" players and it's not an easy problem. As you mentioned, a simple average score or picking-the-highest-score will not be an ideal answer depending on your game design.\nI'd like to recommend that you read about ELO rating system for Chess and other modified ... | [
2,
2
] | [] | [] | [
"google_app_engine",
"math",
"python"
] | stackoverflow_0007297217_google_app_engine_math_python.txt |
Q:
What is the easiest way to move data from one database to another backup database using SQLalchemy?
I am relatively new to SQLalchemy and have done basic database creation, insert, update and delete. I have found it quite simple to use so far. My question is:
I want to move records from one database to another bac... | What is the easiest way to move data from one database to another backup database using SQLalchemy? | I am relatively new to SQLalchemy and have done basic database creation, insert, update and delete. I have found it quite simple to use so far. My question is:
I want to move records from one database to another backup database. What is the simplest way to do this in SQLalchemy?
| [
"You would just go direct to the database utiltites and back it up there. Nothing to do with SQLAlchemy\n",
"\nI don't want the database to get to big and unwieldy\n\nDatabase scaling is big topic, but it still fits in the realm of optimization, which can be summed up with three simple rules:\n\nDon't\nDon't\n(Ex... | [
0,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007216100_python_sqlalchemy.txt |
Q:
In Python, How do you prevent partial matches using re.search if you are using a dictionary key as your pattern
How do you prevent parital matches while using re.search if you are using a dictionary key as your pattern in Python. For this question I would like to avoid iterating through the nested list in the dic... | In Python, How do you prevent partial matches using re.search if you are using a dictionary key as your pattern | How do you prevent parital matches while using re.search if you are using a dictionary key as your pattern in Python. For this question I would like to avoid iterating through the nested list in the dictionary value. I've tried appending regular expressions to the search pattern but it results in error.
Partial Match... | [
"If you’re only trying to match an IPv4 address, you can use the regex 192\\.168\\.1\\.\\d+.\n>>> import re\n>>> text = '192.168.1.2, 192.168.11.9, 192.168.1.255, 10.14.1.1'\n>>> regex = '192\\.168\\.1\\.\\d+'\n>>> re.search(regex, text).group()\n'192.168.1.2'\n>>> re.findall(regex, text)\n['192.168.1.2', '192.168.... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007297213_python.txt |
Q:
Django - Understanding X-Sendfile
I've been doing some research regarding file downloads with access control, using Django. My goal is to completely block access to a file, except when accessed by a specific user. I've read that when using Django, X-Sendfile is one of the methods of choice for achieving this (base... | Django - Understanding X-Sendfile | I've been doing some research regarding file downloads with access control, using Django. My goal is to completely block access to a file, except when accessed by a specific user. I've read that when using Django, X-Sendfile is one of the methods of choice for achieving this (based on other SO questions, etc). My rudim... | [
"\nYes, that's just how it works.\nThe exact implementation depends on the webserver but in the case of nginx, it's recommended to mark the location as internal to prevent external access.\nNginx can asynchronously serve files while with Django you need one thread per request which can get problematic for higher nu... | [
27
] | [] | [] | [
"django",
"download",
"protected_resource",
"python",
"x_sendfile"
] | stackoverflow_0007296642_django_download_protected_resource_python_x_sendfile.txt |
Q:
What's the best way to do an existence check on a cookie with python/GAE?
In my code I'm using
user_id = self.request.cookies.get( 'user_id', '' )
if user_id != '':
me = User.get_by_id( int( user_id ) )
but to me this doesn't look right even though it technically works...it looks imprecise. Is there a b... | What's the best way to do an existence check on a cookie with python/GAE? | In my code I'm using
user_id = self.request.cookies.get( 'user_id', '' )
if user_id != '':
me = User.get_by_id( int( user_id ) )
but to me this doesn't look right even though it technically works...it looks imprecise. Is there a better way I can check for the existence of a cookie?
| [
"I've never use AppEngine but I guess request.cookies is just a normal dictionary object like for example in Django. You can try the following:\nif 'user_id' in self.request.cookies:\n # cookie exists\n\n",
"Try and Except clauses are very handy for situations like this where you need a clear and obvious workf... | [
2,
1
] | [] | [] | [
"cookies",
"google_app_engine",
"python"
] | stackoverflow_0007297000_cookies_google_app_engine_python.txt |
Q:
Recreate some sqlalchemy object
Ok, so I'm having a bit of a problem here. I need to be able to create a sort of import/export functionality for some sqlalchemy. Now these are not objects I'm defining, so to get the columns I'm doing:
for attr, value in res.__class__.__dict__.iteritems():
if isinstance(value,... | Recreate some sqlalchemy object | Ok, so I'm having a bit of a problem here. I need to be able to create a sort of import/export functionality for some sqlalchemy. Now these are not objects I'm defining, so to get the columns I'm doing:
for attr, value in res.__class__.__dict__.iteritems():
if isinstance(value, InstrumentedAttribute):
da... | [
"Serializing can't really be generalized for all possible sqlalchemy mapped classes, classes might have properties that aren't stored in the database, or that must be inferred across multiple levels of indirection through relationship properties. In short, only you know how to serialize a particular class for a pa... | [
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007239873_python_sqlalchemy.txt |
Q:
Use if __name__ == '__main__': for tests
When you write some scripts that are self sufficient, is it a bad idea to use the if __name__ == '__main__' as a place to write tests?
A:
It really depends on your code and purposes of your script. For big and complex projects you for sure have to put all your tests into... | Use if __name__ == '__main__': for tests | When you write some scripts that are self sufficient, is it a bad idea to use the if __name__ == '__main__' as a place to write tests?
| [
"It really depends on your code and purposes of your script. For big and complex projects you for sure have to put all your tests into a separate place.\nBut while working on something small it might be a good solution to have tests along with code - it is the main idea of doctest (it is a great Python module that... | [
6,
5,
3,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0007297719_python_unit_testing.txt |
Q:
using GAE datastore for job management
I have a 'Calculation' entity in my datastore with say, 7 million objects under that entity. It has the following properties (python runtime):
class Calculation(db.Model):
question = db.StringProperty(required=True)
answer = db.StringProperty()
suppose examples of th... | using GAE datastore for job management | I have a 'Calculation' entity in my datastore with say, 7 million objects under that entity. It has the following properties (python runtime):
class Calculation(db.Model):
question = db.StringProperty(required=True)
answer = db.StringProperty()
suppose examples of the 'question' property are things like '1+1',... | [
"I don't know if i have really understand. But you simply need to return for your first ajax call the key of the entity Calculation and the question. When the user makes a response you firstly get the entity by the key and update the property answer.\nStep 1, The ajax call return a question in JSON (for example):\n... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007297542_google_app_engine_google_cloud_datastore_python.txt |
Q:
Gtk spell checking in python with PyGObject on Ubuntu
I've created a little helper application using Python and GTK. I've never used GTK before. As per the comment on http://www.pygtk.org/ I used the PyGObject interface.
Now I would like to add spell checking to my Gtk.TextBuffer.
I found a library called GtkSpell... | Gtk spell checking in python with PyGObject on Ubuntu | I've created a little helper application using Python and GTK. I've never used GTK before. As per the comment on http://www.pygtk.org/ I used the PyGObject interface.
Now I would like to add spell checking to my Gtk.TextBuffer.
I found a library called GtkSpell and an associated python-gtkspell in the package manager, ... | [
"I wrote one, yesterday because I had the same problem, so it's a bit alpha but it works fine. You could get the source from: https://github.com/koehlma/pygtkspellcheck. It requires pyenchant and I only test it with Python 3 on Archlinux. If something doesn't work feel free to fill out a bug report on Github.\nYou ... | [
4,
1
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0005762766_gtk_python.txt |
Q:
Javascript rendering in tornado webserver
In following code snippet I'm trying to add JavaScript Files from Tornado server in HTML file in <HEAD> tag.
DEBUG_SCRIPTS = ''' <script src="src/main.js" type="text/javascript"></script> '''
class Entries(tornado.web.UIModule):
def javascript_files(self):
return... | Javascript rendering in tornado webserver | In following code snippet I'm trying to add JavaScript Files from Tornado server in HTML file in <HEAD> tag.
DEBUG_SCRIPTS = ''' <script src="src/main.js" type="text/javascript"></script> '''
class Entries(tornado.web.UIModule):
def javascript_files(self):
return 'src/main.js'
class MainHandler(tornado.web.R... | [
"javascript files only works with UIModules. Javascript files included that way are appended to the page just before the end of the body tag, though, not in the head tag.\nIf you really want the file included in the head tag, you can simply output the value of params['CORE_SCRIPTS'] in the head tag of your template... | [
3
] | [] | [] | [
"javascript",
"python",
"tornado",
"web.py"
] | stackoverflow_0007294998_javascript_python_tornado_web.py.txt |
Q:
Tornado authentication help
I just started using tornado and got it set up with nginx proxing tornado and php and everything is working corretly
What im trying to achieve is a notification system.
When a user does something such as send an email or update a field in the database if the other user is browsing the ... | Tornado authentication help | I just started using tornado and got it set up with nginx proxing tornado and php and everything is working corretly
What im trying to achieve is a notification system.
When a user does something such as send an email or update a field in the database if the other user is browsing the web he will get notified.
So usin... | [
"It's not quite that simple. You need to keep a list of waiting messages, and the users they are for. The example chat application is probably the best place to start, although it just delivers each message to everyone. \nHowever, it shouldn't be too hard to modify. You could, for example, add a dict mapping users ... | [
0
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0007297742_python_tornado.txt |
Q:
Django models: mutual references between two classes and impossibility to use forward declaration in python
I have defined two models where each one references the other, like so:
class User(models.Model):
# ...
loves = models.ManyToManyField(Article, related_name='loved_by')
class Article(models.Model):
... | Django models: mutual references between two classes and impossibility to use forward declaration in python | I have defined two models where each one references the other, like so:
class User(models.Model):
# ...
loves = models.ManyToManyField(Article, related_name='loved_by')
class Article(models.Model):
# ...
author = models.ForeignKey(User)
You see, the problem is both classes references each other. No ma... | [
"You can find the solution in the docs:\n\nIf you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:\nclass Car(models.Model):\n manufacturer = models.ForeignKey('Manufacturer')\n # ...\n\nclass Manufacturer(models.Mo... | [
48
] | [] | [] | [
"django",
"foreign_keys",
"forward_declaration",
"model",
"python"
] | stackoverflow_0007298326_django_foreign_keys_forward_declaration_model_python.txt |
Q:
Using __init__ in django to annotate a model with extra information
I wrote an __init__ method for one of my models that adds some auxiliary information to the object by dynamically adding an attribute to the object that does not reflect a column in the database:
class MyModel(models.Model):
title = Models.Cha... | Using __init__ in django to annotate a model with extra information | I wrote an __init__ method for one of my models that adds some auxiliary information to the object by dynamically adding an attribute to the object that does not reflect a column in the database:
class MyModel(models.Model):
title = Models.CharField()
description = Models.TextField()
def __init__(self, *ar... | [
"Try usung the serialiser's optional fields argument.\nserialized_items = serializers.serialize(\"json\", itemlist, fields=['.....', 'aux_info'])\n\nMay i also suggest that using the __init__ method to add fields is considdered bad form in django and would be much better achieved like so:\nclass MyModel(models.Mode... | [
1
] | [] | [] | [
"django",
"python",
"serialization"
] | stackoverflow_0007288137_django_python_serialization.txt |
Q:
Pythonic handling of this error case
In the code below, is my use of assert justified? If anything is wrong, an error will occur anyway when I try to access the attributes. On the other hand, the assert provides a descriptive error message.
Do you think I should keep the assertion?
class WeakBoundMethod:
def _... | Pythonic handling of this error case | In the code below, is my use of assert justified? If anything is wrong, an error will occur anyway when I try to access the attributes. On the other hand, the assert provides a descriptive error message.
Do you think I should keep the assertion?
class WeakBoundMethod:
def __init__(self, meth):
assert (hasat... | [
"assert is not for input validation, it's for finding flaws in the assumptions you built your code on. It's a debugging and documentation tool, but it can be disabled. If you want to provide a good error message, raise TypeError(\"Object is not a bound method\") - that's what it's for.\n",
"It appears to me that ... | [
4,
1
] | [] | [] | [
"assert",
"error_handling",
"python"
] | stackoverflow_0007298412_assert_error_handling_python.txt |
Q:
How to measure/profile "Datastore Reads/Writes" from a single request?
The "new pricing model" has resources "Datastore Reads" and "Datastore Writes". But I could not find detailed information on exactly how this is measured.
Hard to optimize datastore utilization if I can not profile it! Any clues on how to do th... | How to measure/profile "Datastore Reads/Writes" from a single request? | The "new pricing model" has resources "Datastore Reads" and "Datastore Writes". But I could not find detailed information on exactly how this is measured.
Hard to optimize datastore utilization if I can not profile it! Any clues on how to do that? http://code.google.com/appengine/articles/managing-resources.html doesnt... | [
"Have you trying AppStats, it can help you: http://code.google.com/appengine/docs/python/tools/appstats.html\nWith this software you can profiling all API call.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007298400_google_app_engine_google_cloud_datastore_python.txt |
Q:
Compare dictionary values and key in python
I have a dictionary item. It has strings as keys and the values are lists e.g.:
item['title'] = [u'python']
item['image'] = [u'/link/to/image']
item['link'] = [u'link to article']
I want to check if any value is 0 in length, but link or image may be empty, so I did the ... | Compare dictionary values and key in python | I have a dictionary item. It has strings as keys and the values are lists e.g.:
item['title'] = [u'python']
item['image'] = [u'/link/to/image']
item['link'] = [u'link to article']
I want to check if any value is 0 in length, but link or image may be empty, so I did the following:
for key, value in item.iterite... | [
"You confused the logical or with and. For example, if the key is \"image\", you check the following:\nif \"image\" != 'image' or \"image\" != 'link':\n#if False or True:\n#if True:\n\nInstead, you want\nif key != 'image' and key != 'link':\n\nor, easier to read:\nif key not in ('image', 'link'):... | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0007298918_python.txt |
Q:
PhysFS and Python embedding
I am writing a game engine and I'd like it to have Python scripting as well as support for mods using PhysFS.
My game data is stored something like this:
/
native
scripts
sprites
...
mods
mymodname
scripts
What I want is for the mod scripts to be able to 'import' the native scrip... | PhysFS and Python embedding | I am writing a game engine and I'd like it to have Python scripting as well as support for mods using PhysFS.
My game data is stored something like this:
/
native
scripts
sprites
...
mods
mymodname
scripts
What I want is for the mod scripts to be able to 'import' the native scripts as if they were in the same... | [
"You could create a symbolic link so that you can link those files/folders are in a higher directory, with PhysFS you can do:\nPHYSFS_permitSymbolicLinks()\n\nThen have PhysFS follow your symbolic links, hope this help :-)\nEDIT: What I would do is symbolically link /mods/scripts to /native/mods-scripts so that /na... | [
1,
0
] | [] | [] | [
"c++",
"physfs",
"python"
] | stackoverflow_0007088196_c++_physfs_python.txt |
Q:
Calculating user, nice, sys, idle, iowait, irq and sirq from /proc/stat
/proc/stat shows ticks for user, nice, sys, idle, iowait, irq and sirq like this:
cpu 6214713 286 1216407 121074379 260283 253506 197368 0 0 0
How can I calculate the individual utilizations (in %) for user, nice etc with these values? Like t... | Calculating user, nice, sys, idle, iowait, irq and sirq from /proc/stat | /proc/stat shows ticks for user, nice, sys, idle, iowait, irq and sirq like this:
cpu 6214713 286 1216407 121074379 260283 253506 197368 0 0 0
How can I calculate the individual utilizations (in %) for user, nice etc with these values? Like the values that shows in 'top' or 'vmstat'.
| [
"This code calculates user utilization spread over all cores.\nimport os\nimport time\nimport multiprocessing\n\ndef main():\n jiffy = os.sysconf(os.sysconf_names['SC_CLK_TCK'])\n num_cpu = multiprocessing.cpu_count()\n\n stat_fd = open('/proc/stat')\n stat_buf = stat_fd.readlines()[0].split()\n user... | [
11,
4
] | [] | [] | [
"c",
"kernel",
"linux",
"procfs",
"python"
] | stackoverflow_0007298646_c_kernel_linux_procfs_python.txt |
Q:
Synchronized Qt TreeWidgets
I'm new to Python and PyQt. What is the best way to keep 4 QtTreeWidgets synchronized so that the items are the same as well as all the attributes of all the items? These widgets appear in different dialog boxes at different times during a session. For a number of reasons, I need to kee... | Synchronized Qt TreeWidgets | I'm new to Python and PyQt. What is the best way to keep 4 QtTreeWidgets synchronized so that the items are the same as well as all the attributes of all the items? These widgets appear in different dialog boxes at different times during a session. For a number of reasons, I need to keep as much of the existing code, s... | [
"Yes using the MVC facilities is the way to go ...\nEven though you are using QTreeWidget you are still working with a class derived from QAbstractItemView therefore the model() and setModel() calls are available. Take a model from one of the widgets that you are creating and then set it in the other widgets. Whene... | [
3,
0
] | [] | [] | [
"pyqt",
"python",
"qt",
"qtreewidget"
] | stackoverflow_0007297507_pyqt_python_qt_qtreewidget.txt |
Q:
django ListView specifying variable available for all methods inside the class
My url has a keyword "shop_name" variable.
There's also the Shop model with "name" field.
In my ListView class I need to make repeating queries to Shop model to get a unicode variable from Shop.get_type() method. Depending on the result... | django ListView specifying variable available for all methods inside the class | My url has a keyword "shop_name" variable.
There's also the Shop model with "name" field.
In my ListView class I need to make repeating queries to Shop model to get a unicode variable from Shop.get_type() method. Depending on the result, a proper template directory is selected or queryset (Using subclassed django model... | [
"Save it in self.shop.\nget_queryset is the first method called (see the code for BaseListView's get method). So one solution would be to get your variable there, just as you do in your code, and then also save it to self.shop (just as the BaseListView does with self.object_list).\ndef get_queryset(self):\n self... | [
4
] | [] | [] | [
"django",
"generics",
"listview",
"python",
"views"
] | stackoverflow_0007295886_django_generics_listview_python_views.txt |
Q:
Python: extrapolate a trend using 2 or more data points
I need to be able to extrapolate, using 2-n data points, a curved trend line which can then be 'queried'. In my head it would look a bit like this (the blue line):
This is for a 'calories calculator' - I have data points regarding the amount of calories bur... | Python: extrapolate a trend using 2 or more data points | I need to be able to extrapolate, using 2-n data points, a curved trend line which can then be 'queried'. In my head it would look a bit like this (the blue line):
This is for a 'calories calculator' - I have data points regarding the amount of calories burned for an activity based on a certain weight: e.g. if you're... | [
"numpy and scipy contain routines that let you fit expressions to data points. once you have an expression you can plot it for any range of time you like.\nthis answer - Nonlinear e^(-x) regression using scipy, python, numpy - contains an example of non-linear regression (it's an exponential, like in your question... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007299350_python.txt |
Q:
Running Multiple Methods At Once In Python
I am trying to run a method which has an infinite loop in it to create a video display. This method is called within another loop that handles hardware input and as such cannot loop as fast as the video, causing lag if I use the outer loop to run the video. Is there a way... | Running Multiple Methods At Once In Python | I am trying to run a method which has an infinite loop in it to create a video display. This method is called within another loop that handles hardware input and as such cannot loop as fast as the video, causing lag if I use the outer loop to run the video. Is there a way to start the video loop and then start the hard... | [
"Yes, you can use Python's own threading module, or a cooperative microthreading module like gevent.\nNote that Python's threading mechanism carries this disclaimer for CPython (the default Python implementation on most boxes):\n\nDue to the Global Interpreter Lock, in CPython only one thread can execute Python cod... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007299526_python.txt |
Q:
: [Errno 13] Permission denied using cElementTree on appengine
Trying to grab an xml file from an internet source and parse it for some values.
My code:
def get_xml(self):
#xml_url = "http://www.shoppingcar.it/feed/export_vel.asp?parametro=1"
xml_url = "http://dl.dropbox.com/u/102727/AutoVeloce%20XML%... | : [Errno 13] Permission denied using cElementTree on appengine | Trying to grab an xml file from an internet source and parse it for some values.
My code:
def get_xml(self):
#xml_url = "http://www.shoppingcar.it/feed/export_vel.asp?parametro=1"
xml_url = "http://dl.dropbox.com/u/102727/AutoVeloce%20XML%20Splitter/shoppingcar.xml"
MAX_RETRY = 3
retry_left = MAX_... | [
"parse function expects file object. Try parse(StringIO(XML)) instead.\n"
] | [
1
] | [
"You may not be authorized to use this link (i.e. to make a request on this link).\n"
] | [
-1
] | [
"google_app_engine",
"python",
"xml"
] | stackoverflow_0007299344_google_app_engine_python_xml.txt |
Q:
How to build a keyworded tuple?
I am trying to use ArgumentParser.set_defaults from argparse. I want a keyworded tuple like this: parser.set_defaults(bar=42, baz='badger')
I have the item from the output of ConfigParser.items which is: ('baz','badger').
How do I convert this into the keyworded tuple that set_defau... | How to build a keyworded tuple? | I am trying to use ArgumentParser.set_defaults from argparse. I want a keyworded tuple like this: parser.set_defaults(bar=42, baz='badger')
I have the item from the output of ConfigParser.items which is: ('baz','badger').
How do I convert this into the keyworded tuple that set_defaults is expecting?
| [
"If you have a list [(key, value), (key, value), ...], you can turn it into a dict with that_dict = dict(that_list). Then you can unpack it into set_defaults, i.e. parser.set_default(**that_dict).\n"
] | [
1
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0007299808_argparse_python.txt |
Q:
A class that only allows me to fill instances of the first type created
This is what it does: The content of the first instance of the class ( in this case mok1 ) gets filled with water. I can fill it infinitely but as soon as the first instance is created, I can only fill that instance and generate a error by any... | A class that only allows me to fill instances of the first type created | This is what it does: The content of the first instance of the class ( in this case mok1 ) gets filled with water. I can fill it infinitely but as soon as the first instance is created, I can only fill that instance and generate a error by any other instance. Is there a cleaner and better way to do this? Now I use the ... | [
"I think the question is related to that of how to effectively implement a Singleton. While you apparently want to allow multiple instances (hence you don't have a Singleton), you still need to identify that first instance. \nThe problem with your solution is that you are not identifying the first instance, but the... | [
0,
0,
0,
0
] | [] | [] | [
"class",
"instance",
"python",
"state",
"variables"
] | stackoverflow_0007248720_class_instance_python_state_variables.txt |
Q:
win32com + Excel + Django + Apache = problem
I have some problem with opening Excel document in web application
running under Apache(mod_wsgi)/Windows 2008 Server (there is no
problem when the application is running on django developer server -
one thread).
My code:
def my_view(request):
import pythoncom
fro... | win32com + Excel + Django + Apache = problem | I have some problem with opening Excel document in web application
running under Apache(mod_wsgi)/Windows 2008 Server (there is no
problem when the application is running on django developer server -
one thread).
My code:
def my_view(request):
import pythoncom
from win32com.client import DispatchEx
pythoncom.... | [
"After hours of researching the exact same problem I found the solution. It has nothing to do with pythoncom / win32com, but with the fact that the apache is running as a service.\nThe solution can be found here:\nhttp://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef9... | [
3,
0
] | [] | [] | [
"apache",
"excel",
"multithreading",
"python",
"win32com"
] | stackoverflow_0004803850_apache_excel_multithreading_python_win32com.txt |
Q:
Unable To Reach Sentry Log Server Error 400
I get the following error when my Sentry client tries logging an error:
Unable to reach Sentry log server: HTTP Error 400: BAD REQUEST (url: http://localhost:8000/sentry/store/, body: Missing data)
Traceback (most recent call last):
File "/home/deploy/en... | Unable To Reach Sentry Log Server Error 400 | I get the following error when my Sentry client tries logging an error:
Unable to reach Sentry log server: HTTP Error 400: BAD REQUEST (url: http://localhost:8000/sentry/store/, body: Missing data)
Traceback (most recent call last):
File "/home/deploy/env/lib/python2.6/site-packages/sentry/client/base.... | [
"I had this problem too.\nHave looked into the sentry codebase and found the place where it throws the 400 (line 424 of web/views.py)\nIt happens in the else clause that checks for the header HTTP_AUTHORIZATION. To get this to be passed through, I had to add WSGIPassAuthorization On to my apache conf....\nI think t... | [
2
] | [] | [] | [
"django",
"python",
"sentry"
] | stackoverflow_0007086878_django_python_sentry.txt |
Q:
Python: How can I parse { apple: "1" , orange: "2" } into Dictionary?
I have received an output , it likes this.
{
orange: '2',
apple: '1',
lemon: '3'
}
I know it is not a standard JSON format, but is it still possible to parse into Python Dictionary type? Is it a must that orange , apple , lemon must... | Python: How can I parse { apple: "1" , orange: "2" } into Dictionary? | I have received an output , it likes this.
{
orange: '2',
apple: '1',
lemon: '3'
}
I know it is not a standard JSON format, but is it still possible to parse into Python Dictionary type? Is it a must that orange , apple , lemon must be quoted?
Thanks you
| [
"This is valid YAML (a superset of JSON). Use PyYAML to parse it:\n>>> s = '''\n... {\n... orange: '2',\n... apple: '1',\n... lemon: '3'\n... }'''\n>>> import yaml\n>>> yaml.load(s)\n{'orange': '2', 'lemon': '3', 'apple': '1'}\n\nMore, since there is a tab space inside the string s, we better remove it ... | [
14
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0007300050_dictionary_json_python.txt |
Q:
Wrong validation error on a django modelform field when passed through clean method
Model and ModelForm in django project are defined like this :
class Consumption(models.Model):
date=models.DateTimeField(default=datetime.now)
product_name=models.ForeignKey(Stock,to_field='product_name')
quantity=model... | Wrong validation error on a django modelform field when passed through clean method | Model and ModelForm in django project are defined like this :
class Consumption(models.Model):
date=models.DateTimeField(default=datetime.now)
product_name=models.ForeignKey(Stock,to_field='product_name')
quantity=models.IntegerField()
customer=models.CharField(max_length=50,null=True,blank=True)
d... | [
"You're returning the whole cleaned_data dictionary from the clean_quantity method, rather than just the value of quantity. \n",
"You won't need to typecast cleaned_data.get('quantity') to int. Django's to_python() method on the form base class will do that for you. All forms will try to convert their values to P... | [
3,
2
] | [] | [] | [
"django",
"django_forms",
"python",
"validation"
] | stackoverflow_0007299547_django_django_forms_python_validation.txt |
Q:
How to display the options' label in ModelMultipleChoiceField?
I have this:
class HouseForm(forms.ModelForm):
amenities = ModelMultipleChoiceField(
queryset=Amenity.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=False
)
Is there a way I can construct my own list of ... | How to display the options' label in ModelMultipleChoiceField? | I have this:
class HouseForm(forms.ModelForm):
amenities = ModelMultipleChoiceField(
queryset=Amenity.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required=False
)
Is there a way I can construct my own list of checkboxes? Instead of the default in unordered list?
Here's what I ... | [
"subclass forms.CheckboxSelectMultiple (render() method?) to give you the required output.\nclass TabularSelectMultiple(SelectMultiple):\n def render(self, name, value, attrs=None, choices=()):\n if value is None: value = []\n has_id = attrs and 'id' in attrs\n final_attrs = self.build_attrs... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007288308_django_python.txt |
Q:
Accept either single dict or list of dicts as function argument
I'd like to accept either one dict or a list of dicts as a function argument. So far, I've come up with the following, but I suspect I've missed something completely obvious, and am using something fragile (isinstance):
def wrap(f):
def enc(inp):
... | Accept either single dict or list of dicts as function argument | I'd like to accept either one dict or a list of dicts as a function argument. So far, I've come up with the following, but I suspect I've missed something completely obvious, and am using something fragile (isinstance):
def wrap(f):
def enc(inp):
if isinstance(inp, list):
for item in inp:
... | [
"I would accept a variable number of arguments:\ndef wrap(f):\n def enc(*args):\n for item in args:\n f(item)\n return enc\n\nThen you can either pass a single dictionary, multiple dictionaries or a list by unpacking it.\nSee Arbitrary Argument Lists in the Python tutorial.\n",
"I would av... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0007299944_python.txt |
Q:
Django Debug Toolbar Install Problems
I am having issues trying to get the django-debug-toolbar up and running. I have all of the necessary info added to INSTALLED_APPS, MIDDLEWARE_CLASSES, and my ip is in the INTERNAL_IPS tuple. I have run the setup.py script and everything seems to load fine as I am getting no e... | Django Debug Toolbar Install Problems | I am having issues trying to get the django-debug-toolbar up and running. I have all of the necessary info added to INSTALLED_APPS, MIDDLEWARE_CLASSES, and my ip is in the INTERNAL_IPS tuple. I have run the setup.py script and everything seems to load fine as I am getting no errors from django or apache.
However, noth... | [
"I had this same issue for awhile. \nHave you tried logging into the admin panel? If the toolbar displays there, but does not display in your code, it's very likely that you are missing the opening and closing tags in your template. By default, django debug toolbar attaches to the BODY tag, though you can chang... | [
8,
2
] | [] | [] | [
"django",
"django_debug_toolbar",
"python"
] | stackoverflow_0005034850_django_django_debug_toolbar_python.txt |
Q:
Polymorphic macros in Jinja
I am looking for a way to have a Jinja macro that calls different implementations depending on the type of object that is being passed. Basically, standard Python method polymorphism. Right now, I'm using an ugly workaround similar to this:
{% macro menuitem(obj) %}
{% set type = obj.... | Polymorphic macros in Jinja | I am looking for a way to have a Jinja macro that calls different implementations depending on the type of object that is being passed. Basically, standard Python method polymorphism. Right now, I'm using an ugly workaround similar to this:
{% macro menuitem(obj) %}
{% set type = obj.__class__.__name__ %}
{% if typ... | [
"The essence of OOP: polymorphism.\nCreate a presentation Layer for your objects:\n\nclass MenuPresentation:\n def present(self):\n raise NotImplementedException()\n\nclass ImageMenuPresentation(MenuPresentation):\n def present(self):\n return \"magic url \"\n\nclass TextMenuPresentation(MenuPrese... | [
7,
2
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0006428484_jinja2_python.txt |
Q:
Can't get Python to read until the end of a file
I have tried this a few different ways, but the result always seems to be the same. I can't get Python to read until the end of the file here. It stops only about halfway through. I've tried Binary and ASCII modes, but both of these have the same result. I've also c... | Can't get Python to read until the end of a file | I have tried this a few different ways, but the result always seems to be the same. I can't get Python to read until the end of the file here. It stops only about halfway through. I've tried Binary and ASCII modes, but both of these have the same result. I've also checked for any special characters in the file where it... | [
"The Python reference manual about read() says:\n\nAlso note that when in non-blocking mode, less data than was requested\n may be returned, even if no size parameter was given.\n\nThere is also a draft PEP about that matter, which apparently was not accepted. A PEP is a Python Enhancement Proposal.\nSo the sad st... | [
3,
2,
1,
1
] | [] | [] | [
"directory",
"file",
"linux",
"python"
] | stackoverflow_0007297220_directory_file_linux_python.txt |
Q:
How to plot a data cube in python
I was wondering if there's a way to plot a data cube in Python. I mean I have three coordinate for every point
x=part.points[:,0]
y=part.points[:,1]
z=part.points[:,2]
And for every point I have a scalar field t(x,y,z)
I would like to plot a 3D data cube showing the position of t... | How to plot a data cube in python | I was wondering if there's a way to plot a data cube in Python. I mean I have three coordinate for every point
x=part.points[:,0]
y=part.points[:,1]
z=part.points[:,2]
And for every point I have a scalar field t(x,y,z)
I would like to plot a 3D data cube showing the position of the point and for every point a color wh... | [
"You can use matplotlib.\nHere you have a working example (that moves!):\nimport random\nfrom matplotlib import pyplot\nfrom mpl_toolkits.mplot3d import Axes3D\n\nmypoints = []\nfor _ in range(100):\n mypoints.append([random.random(), #x\n random.random(), #y\n random... | [
10,
0
] | [] | [] | [
"cube",
"plot",
"python"
] | stackoverflow_0006870922_cube_plot_python.txt |
Q:
Changing Django Flatpage Label to another name in Django admin dashboard
Am pretty new to django and am trying to make use of the flatpage module in one of the site am going to create. I am able to setup everything for an admin user to create a page using the flatpage module, but the problem now is that I want to ... | Changing Django Flatpage Label to another name in Django admin dashboard | Am pretty new to django and am trying to make use of the flatpage module in one of the site am going to create. I am able to setup everything for an admin user to create a page using the flatpage module, but the problem now is that I want to change the Flatpages name thats displayed on the admin dashboard with somethin... | [
"I am very new to Django, too, but here is my attempt:\nIn your models.py, you need to override the FlatPage model, to provide your own Meta class for it, so you should do something like the below:\nfrom django.contrib.flatpages.models import FlatPage\n\n\nclass MyFlatPage(FlatPage):\n\n class Meta:\n ver... | [
2
] | [] | [] | [
"django",
"django_flatpages",
"python"
] | stackoverflow_0007300141_django_django_flatpages_python.txt |
Q:
How can I smooth a set of 3D points?
this question is an extension of my previous question that you can find here:
How to plot a data cube in python
The thing is that I have a 3D plot of point but if I follow the method of my previous question I could get an overflow error when I have too many points to plot.
I h... | How can I smooth a set of 3D points? | this question is an extension of my previous question that you can find here:
How to plot a data cube in python
The thing is that I have a 3D plot of point but if I follow the method of my previous question I could get an overflow error when I have too many points to plot.
I have to plot millions of points so I need t... | [
"As I answered in original question, the Dots plot is good for you. It is produced by MathGL -- GPL plotting library. Add it don't need many memory if you save in bitmap format (PNG, JPEG, GIF and so on).\nHowever, there are another option for smoothing itself:\n(i) make histogram of point distribution (i.e. averag... | [
0
] | [] | [] | [
"plot",
"python"
] | stackoverflow_0007092036_plot_python.txt |
Q:
Getting Beaker working with GAE
I'm trying to port an app I've been running locally to GAE. The app uses the Bottle.py framework. I use Beaker for session management. I'm a bit of a noob and am having trouble getting Beaker imported properly. Help greatly appreciated.
I'm running the ported app using GoogleAppE... | Getting Beaker working with GAE | I'm trying to port an app I've been running locally to GAE. The app uses the Bottle.py framework. I use Beaker for session management. I'm a bit of a noob and am having trouble getting Beaker imported properly. Help greatly appreciated.
I'm running the ported app using GoogleAppEngineLauncher.app under Mac OS X 10.6... | [
"SessionMiddleware is in middleware.py. Try:\nfrom beaker.middleware import SessionMiddleware\n\n",
"I answered my question by re-approaching the problem with webapp and Google's Users service which has better documentation for working with GAE.\n"
] | [
0,
0
] | [] | [] | [
"beaker",
"bottle",
"google_app_engine",
"python"
] | stackoverflow_0007224870_beaker_bottle_google_app_engine_python.txt |
Q:
access class attributes from within other attribute definitions in python
I'm writing some code, in which a class defines a few nested classes (to keep things neater and grouped by purpose). I want the nested classes to use the attribute of the enclosing class (see below). This attribute would provide a default va... | access class attributes from within other attribute definitions in python | I'm writing some code, in which a class defines a few nested classes (to keep things neater and grouped by purpose). I want the nested classes to use the attribute of the enclosing class (see below). This attribute would provide a default value that is set on top of the enclosing class and not a 'magic number'.
class... | [
"Use None as a placeholder value, and substitute for default if it hasn't been provided.\nclass Indicator:\n number_of_dots = 5\n\n class Dots:\n def __init__(self, number = None):\n if number is None:\n number = Indicator.number_of_dots\n\n self._current = 0... | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0007300506_python_python_3.x.txt |
Q:
How can I dynamically generate a set of TestCase subclasses from another module?
I have one python module that defines a set of base classes which another python module then implements.
The core python module also has test cases that test if the base classes are correctly implemented.
In the second module's test s... | How can I dynamically generate a set of TestCase subclasses from another module? | I have one python module that defines a set of base classes which another python module then implements.
The core python module also has test cases that test if the base classes are correctly implemented.
In the second module's test suite, I would like to automatically generate the TestCase subclasses from the first mo... | [
"Something that may do almost exactly what you want is twisted.internet.test.reactormixins.ReactorBuilder. You can see how it's used in test_tcp, for example.\n"
] | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0007298959_python_twisted.txt |
Q:
Replace BeautifulSoup with another (standard) HTML parsing module in this Python script
I have made a script with BeautifulSoup which works fine and is very readable, but I want to redistribute it some day, and BeautifulSoup is an external dependency I would like to avoid, specially considering Windows use.
Here i... | Replace BeautifulSoup with another (standard) HTML parsing module in this Python script | I have made a script with BeautifulSoup which works fine and is very readable, but I want to redistribute it some day, and BeautifulSoup is an external dependency I would like to avoid, specially considering Windows use.
Here is the code, it gets every usermap link from a given google maps user. The ####### marked line... | [
"Unfortunately, Python does not have useful HTML parsing in the standard library, so the only reasonable way to parse HTML is by using a third party module like lxml.html or BeautifulSoup. This does not mean that you have to have a separate dependency--these modules are free software and if you do not want an exter... | [
4,
0
] | [
"I have tried this code (see below) and it shows up a list of links. As I have no beautiful soup installed and don't want to, it is very difficult to me to check the results against what your code gives. \nThe \"pure\" python code without any \"soup\" is even shorter and more readable.\nAnyway, here it is. Tell me ... | [
-1
] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0007287675_beautifulsoup_html_parsing_python.txt |
Q:
Pulling raw_input options form a list
Hi I'm just starting to learn Python, I'm using the book "learn python the hard way" and one of the exercises is to build a simple game. I wanted to give options to the user from a list.
For example I would make a list called animals which would include 3 animals, lion tiger a... | Pulling raw_input options form a list | Hi I'm just starting to learn Python, I'm using the book "learn python the hard way" and one of the exercises is to build a simple game. I wanted to give options to the user from a list.
For example I would make a list called animals which would include 3 animals, lion tiger and fish. is is possible to offer selected e... | [
"favourite = raw_input(' or '.join(animals))\n\nThis will take all the strings from the list animals and join them together with or in between, so you'll end up with\n\nLion or Tiger or Fish\n\nif you want to add a question mark and space to the end, you can do\nfavourite = raw_input(' or '.join(animals) + '? ')\n\... | [
3,
1
] | [] | [] | [
"input",
"list",
"python"
] | stackoverflow_0007301040_input_list_python.txt |
Q:
Tkinter binding a function with arguments to a widget
I have a tkinter frame and a button attached to it:
from tkinter import *
def rand_func(a,b,c,effects):
print (a+b+c)
root=Tk()
frame=Frame(root)
frame.bind("<Return>",lambda a=10, b=20, c=30: rand_func(a,b,c))
frame.pack()
button=Button(frame, text="cli... | Tkinter binding a function with arguments to a widget | I have a tkinter frame and a button attached to it:
from tkinter import *
def rand_func(a,b,c,effects):
print (a+b+c)
root=Tk()
frame=Frame(root)
frame.bind("<Return>",lambda a=10, b=20, c=30: rand_func(a,b,c))
frame.pack()
button=Button(frame, text="click me", command=lambda a=1,b=2,c=3,eff=None:rand_func(a,b,c... | [
"When you create a binding with bind, Tkinter automatically adds an argument that has information about the event. You'll need to account for that either in your rand_func definition or in how you call it. \nThis argument is not included when you use the command attribute. You must take care to account for this ext... | [
38,
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007299955_python_tkinter.txt |
Q:
Use Python Re module to extract text from multiline
I'd like to retrieve the Auth= value from the multiline string below. I've tried Python re.match with no success. Will appreciate if I can get any help?
SID=DQAAALsAAABCeyCMlOaYMHkv55TUQFxA71fxE1LpgpmL1G_o8YennFwBhar2I_LNmJjGjvLHVQy8tSRfYdLnUIHhKyD0FTZBzXyG_s8U4... | Use Python Re module to extract text from multiline | I'd like to retrieve the Auth= value from the multiline string below. I've tried Python re.match with no success. Will appreciate if I can get any help?
SID=DQAAALsAAABCeyCMlOaYMHkv55TUQFxA71fxE1LpgpmL1G_o8YennFwBhar2I_LNmJjGjvLHVQy8tSRfYdLnUIHhKyD0FTZBzXyG_s8U4Pt97n9hPz68ZFSM42Qv6Qxuk74TQygHJXhjLWXNuD5mMsh8_MAs-nmhST... | [
"import re\n\ntext = \"SID=DQAAALsAAABCeyCMlOaYMHkv55TUQFxA71fxE1LpgpmL1G_o8YennFwBhar2I_LNmJjGjvLHVQy8tSRfYdLnUIHhKyD0FTZBzXyG_s8U4Pt97n9hPz68ZFSM42Qv6Qxuk74TQygHJXhjLWXNuD5mMsh8_MAs-nmhSToNFIyWoP-uTZ_LN2yQS1o9MB43fzuIIxp-1euXGxMceVVrjyidrYeEB13HS5kMHH-HGjiZhoIJBmu5es7pLPj9Ie8NJZ1K3kFhdVEJa4sLSID=DQAAAL4AAACypRIVy... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006364688_python_regex.txt |
Q:
Local variable error in Django
I'm trying to create a comments section for a web page. However, the function I used in my views.py file returns an error: "Local variable referenced before assignment." Here is the code:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_t... | Local variable error in Django | I'm trying to create a comments section for a web page. However, the function I used in my views.py file returns an error: "Local variable referenced before assignment." Here is the code:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
... | [
"I see one variable that might not be assigned, depending on how the if statements fire: comment. Set it to null or something to start:\ndef comment(request):\n commentlist = []\n comment = ''\n\nAnd rename the function to something else, maybe get_comment() - it's a bad idea to have variables the same name a... | [
0
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0007301357_django_python_templates.txt |
Q:
Using GET and POST with Authorization HTTP header in Python
I am trying to get the list of Maps created by me in Google Maps, and the Maps API says the following:
Retrieving a List of Maps
The Maps Data API provides a feed that lists the maps created by a particular user; this feed is known as a "metafeed". A typ... | Using GET and POST with Authorization HTTP header in Python | I am trying to get the list of Maps created by me in Google Maps, and the Maps API says the following:
Retrieving a List of Maps
The Maps Data API provides a feed that lists the maps created by a particular user; this feed is known as a "metafeed". A typical Maps Data API metafeed is a GET request of the following for... | [
"Using urllib2 will make everything easier:\nimport urllib2\n\nrequest = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')\nrequest.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)\nurllib2.urlopen(request).read()\n\nBTW, isn't the Google Maps Data API deprecated? http:/... | [
8
] | [] | [] | [
"google_api",
"http",
"http_headers",
"python"
] | stackoverflow_0007301593_google_api_http_http_headers_python.txt |
Q:
What kind of tests should one write in Django
Let's says I have a Djano app. Users can sign up, get a activation mail, activate their accounts and log in. After logging in, users can can create, update and delete objects rhough a custom Form which uses the Manager to handle the Model.
What should I be testing here... | What kind of tests should one write in Django | Let's says I have a Djano app. Users can sign up, get a activation mail, activate their accounts and log in. After logging in, users can can create, update and delete objects rhough a custom Form which uses the Manager to handle the Model.
What should I be testing here — should I use the request framework to make reque... | [
"Yes, Django unit tests, using the Client feature, are capable of testing whether or not your routes and forms are correct. \nIf you want full-blown behavior-driven testing from the outside, you can used a BDD framework like Zombie. \nAs for which tests you need, Django author Jacob Kaplan-Moss answered the quest... | [
2
] | [] | [] | [
"django",
"django_testing",
"python",
"testing",
"unit_testing"
] | stackoverflow_0007301681_django_django_testing_python_testing_unit_testing.txt |
Q:
app engine: upload file without form / without pre-generated upload url (from mobile app)
I'm making an android app that uploads photos to an app engine backend.
According to the app engine documentation, the way to upload files is to present the user with a form that posts to a dynamic url that was generated bef... | app engine: upload file without form / without pre-generated upload url (from mobile app) | I'm making an android app that uploads photos to an app engine backend.
According to the app engine documentation, the way to upload files is to present the user with a form that posts to a dynamic url that was generated before the form was rendered (e.g. http://mysite.com/_ah/upload/ag5kZXZ-aGVsbG93b3JsZHIbCxIVX19CbG... | [
"You can use the new experimental file-like API to directly write data to the blobstore;\nyou just have to create your server component, Java servlet or Python web handler, that reads the multipart form and stores the image in the blobstore.\n"
] | [
0
] | [] | [] | [
"blob",
"file_upload",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007300646_blob_file_upload_google_app_engine_google_cloud_datastore_python.txt |
Q:
tkinter create labels and entrys dynamically
I want to create a simple GUI where I can enter some values. A label before and at the and an button to start the script.
I was using something like this:
w = Label(master, text="weight:")
w.grid(sticky=E)
w = Label(root, text="bodyfathydrationmuscle:bones")
w.grid(stic... | tkinter create labels and entrys dynamically | I want to create a simple GUI where I can enter some values. A label before and at the and an button to start the script.
I was using something like this:
w = Label(master, text="weight:")
w.grid(sticky=E)
w = Label(root, text="bodyfathydrationmuscle:bones")
w.grid(sticky=E)
w = Label(root, text="hydration:")
w.grid(st... | [
"Your program suggests that Entrybodyfat and the other variables should be generated on the fly, but you don't want to do that.\nThe normal approach is to store the entries and labels in a list or a map:\nfrom Tkinter import *\n\nroot = Tk()\n\nnames = [\"weight\", \"bodyfat\", \"hydration\", \"muscle\", \"bones\"]... | [
8
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007300041_python_tkinter.txt |
Q:
Project Euler Number 338
I'm stuck on Project Euler problem 338. Here is what I've done so far...
Let's denote a rectangle with width and height x and y respectively (x,y). To form new rectangles you can consider cutting a kind of stairway down the diagonal (as is shown in in the problem description) with d steps.... | Project Euler Number 338 | I'm stuck on Project Euler problem 338. Here is what I've done so far...
Let's denote a rectangle with width and height x and y respectively (x,y). To form new rectangles you can consider cutting a kind of stairway down the diagonal (as is shown in in the problem description) with d steps. But to form a new rectangle t... | [
"I don't have a solution yet, but something interesting for Python. I realized that Python can be used as a convenient tool for notation of algorithms! Basically I wrote down a program similar to yours and started transforming the program logically which leave the results unchanged. I came up with\ndef order(x,y):\... | [
1
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0007223392_algorithm_math_python.txt |
Q:
Converting string to datetime object in Python (GAE)?
I'm very new to Python, but I need to migrate a project from PHP to Python (running in GAE environment) and I need to move all data from one database to GAE's one.
The chellenge is to write data strings into datetime objects.
Dates are stored as strings, which ... | Converting string to datetime object in Python (GAE)? | I'm very new to Python, but I need to migrate a project from PHP to Python (running in GAE environment) and I need to move all data from one database to GAE's one.
The chellenge is to write data strings into datetime objects.
Dates are stored as strings, which where created using PHP's pattern "l dS of F Y ( h:i:s A )"... | [
"If you can use dateutil with GAE, then\nIn [70]: import dateutil.parser as parser\nIn [71]: parser.parse('Sunday 31st of July 2005 ( 02:05:50 PM )',fuzzy=True)\nOut[71]: datetime.datetime(2005, 7, 31, 14, 5, 50)\n\nOtherwise, you'll have to rely on re to manipulate the date string into a format strptime can parse.... | [
3
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0007302316_datetime_python_time.txt |
Q:
Remove duplicates with a different equality test in Python
I'm looking for a Python function similar to nubBy in Haskell, which removes duplicate but with a different equality test.
The function would take the equality test and the list as parameters, and would return the list of elements with no duplicates.
Examp... | Remove duplicates with a different equality test in Python | I'm looking for a Python function similar to nubBy in Haskell, which removes duplicate but with a different equality test.
The function would take the equality test and the list as parameters, and would return the list of elements with no duplicates.
Example:
In [1]: remove(lambda x, y: x+y == 12, [2, 3, 6, 9, 10])
Out... | [
"There is no built-in method (as the use case is rather esoteric), but you can easily write one:\ndef removeDups(duptest, iterable):\n res = []\n for e in iterable:\n if not any(duptest(e, r) for r in res):\n res.append(e)\n return res\n\nNow, in the console:\n>>> removeDups(lambda x,y: x+y == 10, [2,3,... | [
2,
1
] | [] | [] | [
"duplicates",
"haskell",
"python"
] | stackoverflow_0007302378_duplicates_haskell_python.txt |
Q:
How do I check if more than one key is being pushed at a time?
I am creating a keylogger to monitor my PC and I want to have a key combination that shuts the keylogger off or turns on the user interface, not sure yet. But the problem is that I can't figure out how to check if two or three buttons are being pressed... | How do I check if more than one key is being pushed at a time? | I am creating a keylogger to monitor my PC and I want to have a key combination that shuts the keylogger off or turns on the user interface, not sure yet. But the problem is that I can't figure out how to check if two or three buttons are being pressed at the same time ? How do I do that ?
Here's my source so far :
htt... | [
"You should be able to get a keyup/keydown event, rather than a keypress event.\nThen all you do is keep a list of buttons that are down, and remove the button when keyup is called.\n",
"Use GetKeyState to see if another key is pressed. Try this to quit when ctrl-shift-q is pressed:\nimport win32con\n\ndef OnKeyb... | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003157561_python_windows.txt |
Q:
Preserve code readability while optimising
I am writing a scientific program in Python and C with some complex physical simulation algorithms. After implementing algorithm, I found that there are a lot of possible optimizations to improve performance. Common ones are precalculating values, getting calculations out... | Preserve code readability while optimising | I am writing a scientific program in Python and C with some complex physical simulation algorithms. After implementing algorithm, I found that there are a lot of possible optimizations to improve performance. Common ones are precalculating values, getting calculations out of cycle, replacing simple matrix algorithms wi... | [
"Just as a general remark (I'm not too familiar with Python): I would suggest you make sure that you can easily exchange the slow parts of the 'reference implementation' with the 'optimized' parts (e.g., use something like the Strategy pattern). \nThis will allow you to cross-validate the results of the more sophis... | [
15,
3,
3,
1
] | [] | [] | [
"algorithm",
"code_readability",
"optimization",
"performance",
"python"
] | stackoverflow_0007300903_algorithm_code_readability_optimization_performance_python.txt |
Q:
How can I use Google Map Feed API to get a list of my Google Maps using Python?
I want to create a script in Python which downloads the current KML files of all the Maps I created on Google Maps.
To do so manually, I can use this:
http://maps.google.com.br/maps/ms?msid=USER_ID.MAP_ID&msa=0&output=kml
where USER_I... | How can I use Google Map Feed API to get a list of my Google Maps using Python? | I want to create a script in Python which downloads the current KML files of all the Maps I created on Google Maps.
To do so manually, I can use this:
http://maps.google.com.br/maps/ms?msid=USER_ID.MAP_ID&msa=0&output=kml
where USER_ID is a constant number Google uses to identify me, and MAP_ID is the individual map i... | [
"The correct answer to this question involves using Google Maps Data API, HTML interface, which by the way is deprecated but still solves my need in a more official way, or at least more convincing than parsing a web page. Here it goes:\n# coding: utf-8\n\nimport urllib2, urllib, re, getpass\n\nusername = 'heltonbi... | [
1,
0
] | [] | [] | [
"google_maps",
"kml",
"python"
] | stackoverflow_0007235639_google_maps_kml_python.txt |
Q:
Python: What is the right way to modify list elements?
I've this list with tuples:
l = [('a','b'),('c','d'),('e','f')]
And two parameters: a key value, and a new value to modify. For example,
key = 'a'
new_value= 'B' # it means, modify with 'B' the value in tuples where there's an 'a'
I've this two options (both... | Python: What is the right way to modify list elements? | I've this list with tuples:
l = [('a','b'),('c','d'),('e','f')]
And two parameters: a key value, and a new value to modify. For example,
key = 'a'
new_value= 'B' # it means, modify with 'B' the value in tuples where there's an 'a'
I've this two options (both works):
f = lambda t,k,v: t[0] == k and (k,v) or t
new_lis... | [
"Here is one solution involving altering the items in-place.\ndef replace(list_, key, new_value):\n for i, (current_key, current_value) in enumerate(list_):\n if current_key == key:\n list_[i] = (key, new_value)\n\nOr, to append if it's not in there,\ndef replace_or_append(list_, key, new_value... | [
4,
3,
2,
2
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0007302756_data_structures_python.txt |
Q:
How to find if a string contains all the certain characters?
For example:
Characters to match: 'czk'
string1: 'zack' Matches
string2: 'zak' Does not match
I tried (c)+(k)+(z) and [ckz] which are obviously wrong. I feel this is a simple task, but i am unable to find an answer
A:
The most natural way would proba... | How to find if a string contains all the certain characters? | For example:
Characters to match: 'czk'
string1: 'zack' Matches
string2: 'zak' Does not match
I tried (c)+(k)+(z) and [ckz] which are obviously wrong. I feel this is a simple task, but i am unable to find an answer
| [
"The most natural way would probably to use sets rather than regex, like so\nset('czk').issubset(s)\n\nCode is very often simpler and easier to maintain without using regex much.\n",
"Basically you have to sort the string first so you get \"ackz\" and then you can use a regex like /.*c.*k.*z.*/ to match against.\... | [
4,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007302445_python_regex.txt |
Q:
Python Math Regex
I am creating a programming language in Python and one main component that I'm missing for the basic language is the ability to parse mathematical equations. I have the function to parse the math but I need to be able to check if the input is a math equation. I'm looking for a regex to match so... | Python Math Regex | I am creating a programming language in Python and one main component that I'm missing for the basic language is the ability to parse mathematical equations. I have the function to parse the math but I need to be able to check if the input is a math equation. I'm looking for a regex to match something like 3*x^(4*y)+... | [
"You can't do what you want with regular expressions, it isn't a regular language. Python has extensions that you could abuse to do what you want but it would be un-maintainable and would not gain you anything over using a parser.\nWhat you want is a Parser, a great easy to use library for Python is called pyparsin... | [
10,
2,
2,
0,
0
] | [] | [] | [
"language_design",
"math",
"parsing",
"python",
"regex"
] | stackoverflow_0007275980_language_design_math_parsing_python_regex.txt |
Q:
Ntop Python API
Can anyone point me towards tutorials for using the Python API in Ntop (other than that Luca Deris paper)?
In web interfaces there is about > online documentation > python engine but I think this link has an error. Does anyone have access to that document to re-post online for me?
A:
If you have ... | Ntop Python API | Can anyone point me towards tutorials for using the Python API in Ntop (other than that Luca Deris paper)?
In web interfaces there is about > online documentation > python engine but I think this link has an error. Does anyone have access to that document to re-post online for me?
| [
"If you have ntop installed you can look at the example files in /usr/share/ntop/python (that's where they're at in the Ubuntu package version, at least).\nIf you have epydoc installed you can run make from within the /usr/share/ntop/python/docs directory to generate the documentation. Once you do that the About >... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003686080_python.txt |
Q:
Tkinter label height to fit content
I have a label into which I am going to put content of different sizes. I would like to know how high I need to make the label so that I can size the window so it can stay the same for the different content sizes. I have a strategy, but it seems more complicated then it should... | Tkinter label height to fit content | I have a label into which I am going to put content of different sizes. I would like to know how high I need to make the label so that I can size the window so it can stay the same for the different content sizes. I have a strategy, but it seems more complicated then it should be.
I want to set a label to a given wid... | [
"You are correct that the height attribute doesn't change. That attribute doesn't tell you the actual height, only the height it is configured to be. The actual height depends on factors such as how much text is in it, the wrap length, the font, and how the widget geometry is managed. \ntkinter Font objects have a ... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007294852_python_tkinter.txt |
Q:
Is there any way to create a "project file" in Emacs?
I say "project file" in the loosest sense. I have a few python projects that I work on with ropemacs using emacs W32 for Windows. What would be ideal is if I could have an icon I could click on on my desktop to open up emacs, open up the rope project, and set... | Is there any way to create a "project file" in Emacs? | I say "project file" in the loosest sense. I have a few python projects that I work on with ropemacs using emacs W32 for Windows. What would be ideal is if I could have an icon I could click on on my desktop to open up emacs, open up the rope project, and set the speed bar in the top-level directory of that project. ... | [
"You could get everything set up the way you want for a project, then use the answer I posted about using desktop.el and named sessions:\nWhat alternate session managers are available for Emacs?\n",
"I'm actually working on a solution to this very problem. I always had a group of files I wanted to open/close at ... | [
6,
4,
2,
2,
1,
1,
0
] | [] | [] | [
"elisp",
"emacs",
"python",
"ropemacs",
"windows"
] | stackoverflow_0001052969_elisp_emacs_python_ropemacs_windows.txt |
Q:
python saving the excess of a float to int conversion
x=10.5
if x==10.5:
x=int(x)+1
y= .5
ok i have x=10.5 i want to round up to 11 but say the .5 to use later is there any way to do this when i dont know what x will be all the time?
i have to real place to start or even if its possible i do k... | python saving the excess of a float to int conversion | x=10.5
if x==10.5:
x=int(x)+1
y= .5
ok i have x=10.5 i want to round up to 11 but say the .5 to use later is there any way to do this when i dont know what x will be all the time?
i have to real place to start or even if its possible i do know how to change it to an int but i want to store what eve... | [
"One fell swoop:\n>>> divmod(10.5,1)\n(10.0, 0.5)\n\nThe docs for divmod can be found here.\n",
"x = 10.5\nx,chopped = int(x), x - int(x)\n\n",
"take the number modulus 1\n>>> 10.5%1\n0.5\n\n",
"This question is rather poorly worded. Is this what you are trying to do?\nx = 10.5\n\ny = math.fmod(x, 1.0) # y = ... | [
7,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007302928_python.txt |
Q:
GET shows 304 in django and test fails when entries are listed
in my django app,I am using a css file and some images for my web pages.I have defined the media_root and media_url as
in settings.py
MEDIA_ROOT = '/home/me/dev/python/django/myproject/mysite/media/'
MEDIA_URL = '/site_media/myapp/'
ADMIN_MEDIA_PREFIX ... | GET shows 304 in django and test fails when entries are listed | in my django app,I am using a css file and some images for my web pages.I have defined the media_root and media_url as
in settings.py
MEDIA_ROOT = '/home/me/dev/python/django/myproject/mysite/media/'
MEDIA_URL = '/site_media/myapp/'
ADMIN_MEDIA_PREFIX = '/media/'
TEMPLATE_DIRS = (
'/home/me/dev/python/django/myproject/... | [
"You are getting confused with the way MEDIA_URL uses the absolute path defined by MEDIA_ROOT. \nWhen you make a request to '/site_media/myapp/' it will look at the top level of MEDIA_ROOT (in this case '/home/me/dev/python/django/myproject/mysite/media/'). If you request /site_media/myapp/css/mystyle.css then it w... | [
0
] | [] | [] | [
"django",
"get",
"python",
"unit_testing"
] | stackoverflow_0007299474_django_get_python_unit_testing.txt |
Q:
How do I find every element that is in both of two other lists?
Write a function commonElements(a1, a2) that takes in 2 tuples as arguments and returns a sorted tuple containing elements that are found in both tuples.
My task is :
>>> commonElements((1, 2, 3), (2, 5, 1))
(1, 2)
>>> commonElements((1, 2... | How do I find every element that is in both of two other lists? | Write a function commonElements(a1, a2) that takes in 2 tuples as arguments and returns a sorted tuple containing elements that are found in both tuples.
My task is :
>>> commonElements((1, 2, 3), (2, 5, 1))
(1, 2)
>>> commonElements((1, 2, 3, 'p', 'n'), (2, 5 ,1, 'p'))
(1, 2, 'p')
>>> commonElement... | [
"def commonElements(a1, a2):\n return tuple(sorted(set(a1).intersection( set(a2) )))\n\n",
"You've forgot the sorting requirement?\nEDIT\nApparently, set sorts its elements in ascending order, but this is probably an implementation detail. If you were asked to write this function as a test, maybe you're requi... | [
4,
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007301723_python.txt |
Q:
Extract rows and save to multiple csv files
I am trying to solve the following problem using Python: I've a table (csv) from which I want to extract consecutively row 1 + 2, then row 1 + 3, then row 1 + 4, etc. The extracts should be saved again as csv file and named according to the first string in the 2nd row t... | Extract rows and save to multiple csv files | I am trying to solve the following problem using Python: I've a table (csv) from which I want to extract consecutively row 1 + 2, then row 1 + 3, then row 1 + 4, etc. The extracts should be saved again as csv file and named according to the first string in the 2nd row to be extracted (2, 3, 4, 5,...). Now my question ... | [
"fname = argv[1]\nwith open(fname) as i:\n reader = csv.reader(i)\n\n first_row = next(reader)\n for cur_row in reader:\n out_name = cur_row[0]\n with open(out_name, 'wb') as o:\n writer = csv.writer(o)\n writer.writerow(first_row)\n writer.writerow(cur_row)\n... | [
1,
0
] | [] | [] | [
"csv",
"python",
"split"
] | stackoverflow_0007300859_csv_python_split.txt |
Q:
I keep on having problems with syntax and calculating the roots of the quadratic equation
Hey I am having problems with calculating the roots of the quadratic equation with the quadratic formula, using python's complex number functionality.
When I try
>>> if root<0:
root=abs(complex(root))
j=comple... | I keep on having problems with syntax and calculating the roots of the quadratic equation | Hey I am having problems with calculating the roots of the quadratic equation with the quadratic formula, using python's complex number functionality.
When I try
>>> if root<0:
root=abs(complex(root))
j=complex(0,1)
x1=(-b+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
else:
I get the... | [
"Not sure I understand your problem, but it looks like you are not properly indenting -- Python uses white space to mark blocks, so the above should look like:\nif root<0:\n root=abs(complex(root))\n j=complex(0,1)\n x1=(-b+j+sqrt(root))/2*a\n x2=(-b-j+sqrt(root))/2*a\nelse:\n x1=(-b+j+sqrt(root))/2*... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007303464_python.txt |
Q:
Python __future__ outside of a specific module
In python 2.7, by using
from __future__ import division, print_function
I can now have print(1/2) showing 0.5.
However is it possible to have this automatically imported at python startup ?
I tried to use the sitecustomize.py special module but the inport is only ... | Python __future__ outside of a specific module | In python 2.7, by using
from __future__ import division, print_function
I can now have print(1/2) showing 0.5.
However is it possible to have this automatically imported at python startup ?
I tried to use the sitecustomize.py special module but the inport is only valid inside the module and not in the shell.
As I'm... | [
"matplotlib on python 3 is closer than you may think: https://github.com/matplotlib/matplotlib-py3; http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib.\nWhy not use PYTHONSTARTUP instead of sitecustomize.py?\nlocalhost-2:~ $ cat startup.py \nfrom __future__ import print_function\nfrom __future__ import division\... | [
6,
2,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007303423_matplotlib_python.txt |
Q:
Key event in savefig in python. How to do it?
I'm try to understand python doing some codes. I want to select a part of a open image with zoom and save the selected part.
Right now i'm trying to quickly save the open and zoom image by pressing a key. For explain better, i need to fire a function savefig() by pres... | Key event in savefig in python. How to do it? | I'm try to understand python doing some codes. I want to select a part of a open image with zoom and save the selected part.
Right now i'm trying to quickly save the open and zoom image by pressing a key. For explain better, i need to fire a function savefig() by pressing a keyboard key.
I tried to use urwid module :... | [
"You don't explicitly say it, but it appears that you're using matplotlib to do this. \nI can't say for certain from what you've posted, but I'd guess that what's happening is that s is already bound to \"save figure\" for a matplotlib figure. (And by default, matplotlib uses a Tk-based backend, thus the Tk error.)... | [
3
] | [] | [] | [
"image_processing",
"keyboard",
"matplotlib",
"python"
] | stackoverflow_0007299826_image_processing_keyboard_matplotlib_python.txt |
Q:
Selenium RC css selector with adjacent sibling combinator picks wrong table row
Edit: I made a mistake in the table data that I originally posted with. Correction's in bold.
I'm writing Python for Selenium RC. In the document below I'm trying to select the table row that contains "United States" and "1", but th... | Selenium RC css selector with adjacent sibling combinator picks wrong table row | Edit: I made a mistake in the table data that I originally posted with. Correction's in bold.
I'm writing Python for Selenium RC. In the document below I'm trying to select the table row that contains "United States" and "1", but the selector is always selecting the row that contains "United States" and "214" instea... | [
"check some examples that can be helpful for creating complex css3 locators\n"
] | [
-1
] | [] | [] | [
"css_selectors",
"python",
"selenium"
] | stackoverflow_0007286201_css_selectors_python_selenium.txt |
Q:
Python SQLAlchemy syntax error
I'm getting a maddening syntax error when I run the following program. Here is the error:
File "Create_the_database.py", line 64
^
SyntaxError: invalid syntax
Here is the code (long, but repetitive so easy to skim):
import sqlalchemy
from sqlalchemy import *
engine = create_en... | Python SQLAlchemy syntax error | I'm getting a maddening syntax error when I run the following program. Here is the error:
File "Create_the_database.py", line 64
^
SyntaxError: invalid syntax
Here is the code (long, but repetitive so easy to skim):
import sqlalchemy
from sqlalchemy import *
engine = create_engine('sqlite:///Users/benscholz/Drop... | [
"It worked fine for me after fixing two things.\n\nVariable meta should be metadata. 2nd arg of Table() referred the global variable.\nLines from createUsersTable() to metadata.create_all(engine) should be moved down to the bottom. Functions can't be called before defining them. \n\nAs for the syntax error, I gue... | [
1
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0007303513_python_sqlalchemy_sqlite.txt |
Q:
How to define a python string (quasi-)constant that has dynamic inputs?
For example:
MY_MESSAGE = 'Dear %s, hello.'
# ...
name = "jj"
print MY_MESSAGE % name
Does python have a feature for accomplishing something like my above code?
A:
Yes, the exact way you wrote it. Your code is fine.
A:
Python does not rea... | How to define a python string (quasi-)constant that has dynamic inputs? | For example:
MY_MESSAGE = 'Dear %s, hello.'
# ...
name = "jj"
print MY_MESSAGE % name
Does python have a feature for accomplishing something like my above code?
| [
"Yes, the exact way you wrote it. Your code is fine.\n",
"Python does not really have the same concept of \"constant\" that you will find in C. So what you have there is a fairly good approach.\nI would actually argue that this is one example of \"we're all consenting adults\" does not hold up terribly well. Thin... | [
5,
3,
2,
1
] | [] | [] | [
"constants",
"python",
"string"
] | stackoverflow_0007303252_constants_python_string.txt |
Q:
why inheriting from object type
In one of my past questions, a answerer suggests me that it is better to inherit from object when the class you want to create is like from scratch, which is no need to inherit from other class.
For example, like what I always do:
class my_class:
"a class inherits from nothing"... | why inheriting from object type | In one of my past questions, a answerer suggests me that it is better to inherit from object when the class you want to create is like from scratch, which is no need to inherit from other class.
For example, like what I always do:
class my_class:
"a class inherits from nothing"
def __init__(self):
pa... | [
"Inheriting from nothing creates an old-style class, which has different behaviour to new-style classes. I don't remember the specifics just now (see here for an explanation), but as a general rule, there's no reason to favour old-style classes, so you should always inherit from object (if nothing else).\n"
] | [
5
] | [] | [] | [
"inheritance",
"object",
"python",
"python_2.7"
] | stackoverflow_0007304056_inheritance_object_python_python_2.7.txt |
Q:
Python: Counting URL in a specific class
I would like to count URLs in a specific class.
the class which is
<h1 class="sectionTitle">INSIDERS AT LOEWS CORP (L)</h1>
have some links like
<a href="../../../research/stocks/people/relationship.asp?personId=228893&symbol=L:US">
I would like to count the number of t... | Python: Counting URL in a specific class | I would like to count URLs in a specific class.
the class which is
<h1 class="sectionTitle">INSIDERS AT LOEWS CORP (L)</h1>
have some links like
<a href="../../../research/stocks/people/relationship.asp?personId=228893&symbol=L:US">
I would like to count the number of this kind of links under only this class.
This... | [
"Being a big fan of jQuery I recommend PyQuery which offers a strong selector like jQuery. \nfrom pyquery import PyQuery as pq\ndom = pq(file('your.html').read())\nprint len(dom('h1.sectionTitle + table a'))\n\nh1 is the element and . is for class name. You can use # for id name if the target is not class but id. ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007303193_python.txt |
Q:
How to log smtp debug information to a file?
As you know, python smtplib has a debug level.When I set it a true param, it will print some send information.
The problem is, I try to get the debug info to log into a file, but They just stay on my cmd console.
How can I do to log them?
Info like this:
connect: ('192.... | How to log smtp debug information to a file? | As you know, python smtplib has a debug level.When I set it a true param, it will print some send information.
The problem is, I try to get the debug info to log into a file, but They just stay on my cmd console.
How can I do to log them?
Info like this:
connect: ('192.168.1.101', 25)
connect: (25, '192.168.1.101')
rep... | [
"The smtplib prints directly to stderr, e.g. line 823 in smtplib.py:\nprint>>stderr, 'connect fail:', host\n\nYou'd have to either monkey patch sys.stderr before you import smtplib or smtplib.stderr before you run your mail code.\nI might also suggest patching smtplib.stderr with a custom object that has a write me... | [
11,
1,
0
] | [] | [] | [
"cmd",
"email",
"python",
"smtp",
"smtplib"
] | stackoverflow_0007303351_cmd_email_python_smtp_smtplib.txt |
Q:
Why is my stream socket only queuing one connection at a time from my browser?
I am binding a socket to localhost:8888, in order to make a simple server.
Here is the simple python script that I used to create the server.
import os
import socket
import fcntl
tuples = socket.getaddrinfo('localhost', 8888, socket.AF... | Why is my stream socket only queuing one connection at a time from my browser? | I am binding a socket to localhost:8888, in order to make a simple server.
Here is the simple python script that I used to create the server.
import os
import socket
import fcntl
tuples = socket.getaddrinfo('localhost', 8888, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE | socket.AI_ADDRCONFIG)
res = tup... | [
"It is likely an optimisation on the side of your browser, trying to reuse the same connection - see http://en.wikipedia.org/wiki/HTTP_persistent_connection.\nIf you want to make sure, sniff the traffic using wireshark, although your localhost based address may require some fancy setup.\n"
] | [
1
] | [] | [] | [
"browser",
"python",
"sockets",
"tcp"
] | stackoverflow_0007304198_browser_python_sockets_tcp.txt |
Q:
SQLAlchemy Query Dynamic Field
I have a table with many columns --
class Dummy(object):
__tablename__ = 'dummies'
c1 = Column(Integer)
c2 = Column(Integer)
c3 = Column(Integer)
...
cN = Column(Integer)
Can I query through all columns individually without specifying each column name manuall... | SQLAlchemy Query Dynamic Field | I have a table with many columns --
class Dummy(object):
__tablename__ = 'dummies'
c1 = Column(Integer)
c2 = Column(Integer)
c3 = Column(Integer)
...
cN = Column(Integer)
Can I query through all columns individually without specifying each column name manually? --
for i in range(1, N):
c_na... | [
"You can iterate over the columns in a table. First, the table:\nfrom sqlalchemy.orm.attributes import manager_of_class\ndummy_table = manager_of_class(Dummy).mapper.mapped_table\n\nand finally, the query\nfor col in dummy_table.columns:\n dummy = session.query(Dummy).filter(col == 0).first()\n\nOr maybe, you a... | [
3
] | [] | [] | [
"database",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0007304271_database_python_sql_sqlalchemy.txt |
Q:
python: examine XSD xml schema
I would like to examine a XSD schema in python. Currently I'm using lxml which is doing it's job very very well when it only has to validate a document against the schema. But, I want to know what's inside of the schema and access the elements in the lxml behavior.
The schema:
<?xml... | python: examine XSD xml schema | I would like to examine a XSD schema in python. Currently I'm using lxml which is doing it's job very very well when it only has to validate a document against the schema. But, I want to know what's inside of the schema and access the elements in the lxml behavior.
The schema:
<?xml version="1.0"?>
<xsd:schema xmlns:x... | [
"PyXB can process xsd:include. I used PyXB for Amazon.com's huge product schema files where included file includes further xsd files at multiple levels. Highly recommended.\n"
] | [
0
] | [] | [] | [
"lxml",
"python",
"xsd"
] | stackoverflow_0002720575_lxml_python_xsd.txt |
Q:
JSON decode issue
I'm trying to decode JSON output of a Java program (jackson) and having some issues.
The cause of the problem is the following snippet:
{
"description": "... lives\uMOVE™ OFFERS ",
}
Which causes ValueError: Invalid \uXXXX escape.
Any ideas on how to fix this?
EDIT: The output is from an Avr... | JSON decode issue | I'm trying to decode JSON output of a Java program (jackson) and having some issues.
The cause of the problem is the following snippet:
{
"description": "... lives\uMOVE™ OFFERS ",
}
Which causes ValueError: Invalid \uXXXX escape.
Any ideas on how to fix this?
EDIT: The output is from an Avro file, the Avro packag... | [
"What's the original string supposed to look like? \\uXXXX is a unicode escape sequence, so it's interpreting \\uMOVE as a single character, but it's not a valid unicode value. JSON is always assumed to be unicode, so you'll likely need to fix the string in the originating app\n",
"Try quoting the \\u like this:... | [
4,
1,
1,
0,
0
] | [] | [] | [
"avro",
"jackson",
"java",
"json",
"python"
] | stackoverflow_0006697401_avro_jackson_java_json_python.txt |
Q:
AttributeError: 'unicode' object has no attribute '_sa_instance_state'
I'm just learning how to use SQLAlchemy. I'm trying to do the following, but storing title and link in two separate tables:
temp = Submissions(title=u'Facebook Homepage', link=u'http://facebook.com')
session.add(temp)
session.flush()
transactio... | AttributeError: 'unicode' object has no attribute '_sa_instance_state' | I'm just learning how to use SQLAlchemy. I'm trying to do the following, but storing title and link in two separate tables:
temp = Submissions(title=u'Facebook Homepage', link=u'http://facebook.com')
session.add(temp)
session.flush()
transaction.commit()
via:
class Links(Base):
__tablename__ = 'links'
id = Col... | [
"You can't quite do that with relationship. \nYou need to arrange for the Link to be looked up in some way. \nThe most obvious is to just look it up directly.\nsubmission_link = session.query(Links) \\\n .filter(Links.link == u'http://facebook.com') \\\n .first()\ni... | [
8,
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007296296_python_sqlalchemy.txt |
Q:
Bottle on Python, how to make a custom response
Well, I am working with bottle right now. And I am now wondering how excatly I am able to build a custom response. I have a little script which operates some data, which I send and then, I want to send a response-code, if there was done some modification or not ... I... | Bottle on Python, how to make a custom response | Well, I am working with bottle right now. And I am now wondering how excatly I am able to build a custom response. I have a little script which operates some data, which I send and then, I want to send a response-code, if there was done some modification or not ... I was looking through the docs of bottle and didn't fi... | [
"To create custom responses, you need to use a bottle.BaseResponse object. The documentation describes the class, and it seems quite easy to use. So, to achieve what you want, just create a BaseResponse object with the status code you wish (and any other data you'd need to include), and return it from your view.\n"... | [
2
] | [] | [] | [
"bottle",
"python"
] | stackoverflow_0007305051_bottle_python.txt |
Q:
How should apache/nginx and django play nicely together in respect of 404 errors?
Here is a simplified version of our setup:
Nginx reverse proxy front end serving static files
Apache + mod_wsgi serving a django app in /store and wordpress for all other URLs
404 errors outside /store work fine (via an apache 404 ... | How should apache/nginx and django play nicely together in respect of 404 errors? | Here is a simplified version of our setup:
Nginx reverse proxy front end serving static files
Apache + mod_wsgi serving a django app in /store and wordpress for all other URLs
404 errors outside /store work fine (via an apache 404 handler).
However, 404 errors within /store hit the django 404.html. I'd really like no... | [
"you could always symlink your 404 page as {django}/templates/404.html\n",
"I have worked out what I think is the \"correct\" way of doing this which is to set:\n WSGIErrorOverride On\nIn my Apache vhost. This seems to achieve the desired goal of Apache handle the 404 errors. \n"
] | [
0,
0
] | [] | [] | [
"apache",
"django",
"http_status_code_404",
"nginx",
"python"
] | stackoverflow_0007017838_apache_django_http_status_code_404_nginx_python.txt |
Q:
How can I use xml.sax module on an executable made with PyInstaller?
I want to have my application read a document using xml.sax.parse. Things work fine but when I move the executable to a Windows server 2008 machine things break down. I get an SAXReaderNotAvailable exception with "No parsers found" message.
The s... | How can I use xml.sax module on an executable made with PyInstaller? | I want to have my application read a document using xml.sax.parse. Things work fine but when I move the executable to a Windows server 2008 machine things break down. I get an SAXReaderNotAvailable exception with "No parsers found" message.
The setup I'm using to build the executable is:
64 bit windows 7
Python 2.7.2 ... | [
"SAX readers seems to be dynamically imported, so the static analysis can't detect them and they can't be embedded with application.\nTo correct this, you'll have to be explicit to force PyInstaller to import those hidden modules. \nTry to add this to you .spec (thanks Velociraptors) file :\nhiddenimports = ['xml.s... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007241240_python.txt |
Q:
Redirecting one directory to another
I am working on a mod script in Python for a legacy game. This game looks for the folder "AI" in its installation directory. Now, everytime before the game runs, a certain folder is chosen (say, AI_1 or AI_2), which should behave as if it is the AI folder (the actual AI folder ... | Redirecting one directory to another | I am working on a mod script in Python for a legacy game. This game looks for the folder "AI" in its installation directory. Now, everytime before the game runs, a certain folder is chosen (say, AI_1 or AI_2), which should behave as if it is the AI folder (the actual AI folder doesn't exist).
I thought of a few solutio... | [
"Why don't you have the folder(s) zipped & unzip the folder when ever the game loads (into temp folder), from there things would be simpler. since the data is in temp, you can delete the information when the program exits or let windows clean it up.\nthis suggestion would work if the folder size is relatively smal... | [
0,
0
] | [] | [] | [
"directory",
"python",
"windows"
] | stackoverflow_0007305455_directory_python_windows.txt |
Q:
Temporary "unpatching" functionality within mock.side_effect
Is there any way to temporary undo patching using mock within side_effect?
In particular I'd like to make something like this work:
from mock import patch
import urllib2
import unittest
class SimpleTest(unittest.TestCase):
def setUp(self):
s... | Temporary "unpatching" functionality within mock.side_effect | Is there any way to temporary undo patching using mock within side_effect?
In particular I'd like to make something like this work:
from mock import patch
import urllib2
import unittest
class SimpleTest(unittest.TestCase):
def setUp(self):
self.urlpatcher = patch('urllib2.urlopen')
self.urlopen = s... | [
"Why not just temporarily .stop() the patch?\nself.urlopen.stop()\n# points to the real `urlopen()` now\nurllib2.urlopen()\n# put the patch in place again\nself.urlopen.start()\n\n"
] | [
3
] | [] | [] | [
"mocking",
"python",
"unit_testing"
] | stackoverflow_0007304588_mocking_python_unit_testing.txt |
Q:
Python Command line execution
I am trying to rename a set of pdf files in my desktop using a simple python script. I am somehow not very successful. My current code is :
import os,subprocess
path = "/Users/armed/Desktop/"
for file in os.listdir(path)
command = ['mv', '*.pdf' , 'test.pdf'] // mv Command to r... | Python Command line execution | I am trying to rename a set of pdf files in my desktop using a simple python script. I am somehow not very successful. My current code is :
import os,subprocess
path = "/Users/armed/Desktop/"
for file in os.listdir(path)
command = ['mv', '*.pdf' , 'test.pdf'] // mv Command to rename files to test.pdf
subproc... | [
"\nThe same command works when executed in the terminal.\n\nExcept it's not the same command. The code is running:\n'mv' '*.pdf' 'test.pdf'\n\nbut when you type it out it runs:\n'mv' *.pdf 'test.pdf'\n\nThe difference is that the shell globs the * wildcard before executing mv. You can simulate what it does by using... | [
6,
1
] | [] | [] | [
"command_line_arguments",
"python"
] | stackoverflow_0007306178_command_line_arguments_python.txt |
Q:
What is the use of __threshold__ in Python?
I was going through some Python automation scripts and I saw the new (for me) keyword of ___threshold__ = 0.6. What it indicate? What it is used for?
A:
There are only three hits for python "__threshold__" in Google. This doesn't have any special meaning in Python, it... | What is the use of __threshold__ in Python? | I was going through some Python automation scripts and I saw the new (for me) keyword of ___threshold__ = 0.6. What it indicate? What it is used for?
| [
"There are only three hits for python \"__threshold__\" in Google. This doesn't have any special meaning in Python, it's just an identifier someone chose to use. __this_format__ is only supposed to be used by built-in names, to prevent confusion like this.\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0007306574_python.txt |
Q:
Procedural graphics for learning Python
Can anyone recommend a good compact Python graphics library (with tutorials) which is suitable for motivating stronger students in an introductory programming course? I mean library for creating images, not image processing.
A:
I'm afraid there aren't any libraries that ha... | Procedural graphics for learning Python | Can anyone recommend a good compact Python graphics library (with tutorials) which is suitable for motivating stronger students in an introductory programming course? I mean library for creating images, not image processing.
| [
"I'm afraid there aren't any libraries that have been written only for creating images. Most of the examples I have seen around are using some kind of image processing library (like PiL) and rely on clever algorithms.\nBesides, procedural generation of various data structures can be used in variety of scenarios bes... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007306099_python.txt |
Q:
PyGtk : Modify Background color/image of gtk FileChooserButton
I have tried following to change background color for Filechooser Button, but nothing changed..
gtkrc file:
style "FilechooserButtonStyle" = "button_style"
{
base[NORMAL] = '#F5F5F5'
base[SELECTED] = 'red'
bg[NORMAL] = 'green'
bg_pixmap[NORMAL] = "... | PyGtk : Modify Background color/image of gtk FileChooserButton | I have tried following to change background color for Filechooser Button, but nothing changed..
gtkrc file:
style "FilechooserButtonStyle" = "button_style"
{
base[NORMAL] = '#F5F5F5'
base[SELECTED] = 'red'
bg[NORMAL] = 'green'
bg_pixmap[NORMAL] = "button.jpg"
xthickness = 10
ythickness = 10
GtkFileChooserButton... | [
"I'm not so familiar with the .rc files, but this works in the code :\n#!/usr/bin/env python\n# example filechooser.py\n\nimport pygtk\npygtk.require('2.0')\n\nimport gtk\n\ndialog = gtk.FileChooserDialog(\"Open..\", None,\n gtk.FILE_CHOOSER_ACTION_OPEN,\n (gtk.ST... | [
1
] | [] | [] | [
"background_color",
"colors",
"gtk",
"pygtk",
"python"
] | stackoverflow_0007305251_background_color_colors_gtk_pygtk_python.txt |
Q:
django/python | Get files from database, zip, then send to browser
Please help me with my problem.
I'm sorry if this sounds noobie, coz I really am. There are files (jpg, docs) in a certain database, how would I select those file in the database, save them in a zip file, then send over to the browser as HttpRespon... | django/python | Get files from database, zip, then send to browser | Please help me with my problem.
I'm sorry if this sounds noobie, coz I really am. There are files (jpg, docs) in a certain database, how would I select those file in the database, save them in a zip file, then send over to the browser as HttpResponse or something like this:
response = HttpResponse(mimetype='application... | [
"You're looking for zipfile and StringIO. Create a StringIO, open it as a ZipFile, add files to it, then send it.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007307185_django_python.txt |
Q:
Python including C code
We are developing software in Python, but two of our team know only C/C++. My question is, how can we make plugins or is it possible to include dll in Python and how?
A:
Unless you already have existing C/C++ libraries you want to integrate into Python, it's a waste of time. Toss a copy o... | Python including C code | We are developing software in Python, but two of our team know only C/C++. My question is, how can we make plugins or is it possible to include dll in Python and how?
| [
"Unless you already have existing C/C++ libraries you want to integrate into Python, it's a waste of time. Toss a copy of the tutorial on their desks and tell them to take a few days to learn it.\n",
"http://docs.python.org/extending/extending.html\nhttp://docs.python.org/extending/\nhttp://en.wikibooks.org/wiki/... | [
5,
2
] | [] | [] | [
"include",
"python"
] | stackoverflow_0007307356_include_python.txt |
Q:
flickAPI: How do I list the sets for my user account?
I wish to list all the sets created by this user along with the set id. I am using flickrApi and Python. Here's my code. The setName is returning "none" in the output.
The elm.get('title') is returning "none".
import flickrapi
api_key = 'APIKEY'
api_secret... | flickAPI: How do I list the sets for my user account? | I wish to list all the sets created by this user along with the set id. I am using flickrApi and Python. Here's my code. The setName is returning "none" in the output.
The elm.get('title') is returning "none".
import flickrapi
api_key = 'APIKEY'
api_secret = 'APISECRET'
flickr = flickrapi.FlickrAPI(api_key, api_s... | [
"When you're working with flickrapi in Python, it's frequently useful to print the XML which is returned by the API calls in order to see what's going on. In your example, if you add:\n from xml.etree import ElementTree\n\n... at the top, and then add:\nprint ElementTree.tostring(favs)\n\n... you'll see that the s... | [
2
] | [] | [] | [
"api",
"flickr",
"python"
] | stackoverflow_0007303799_api_flickr_python.txt |
Q:
Building a list with binary numbers in binary representation in Python
I have a very big list of 0's and 1's that are represented as integers - by default - by python, I think: [randint(0, 1) for i in range(50*98)]
And I want to optimize the code so that it utilizes much less memory. The obvious way is to use just... | Building a list with binary numbers in binary representation in Python | I have a very big list of 0's and 1's that are represented as integers - by default - by python, I think: [randint(0, 1) for i in range(50*98)]
And I want to optimize the code so that it utilizes much less memory. The obvious way is to use just 1 bit to represent each of these numbers.
Is it possible to build a list of... | [
"This uses the bitstring module and constructs a BitArray object from your list:\nfrom bitstring import BitArray\nb = BitArray([randint(0, 1) for i in range(50*98)])\n\nInternally this is now stored packed as bytes so will take considerably less memory. You can slice, index, check and set bits etc. with the usual n... | [
4,
2,
1,
0,
0
] | [] | [] | [
"binary",
"list",
"python"
] | stackoverflow_0007307622_binary_list_python.txt |
Q:
Asterisk art in python
I would like to produce this picture in python!
*
**
***
****
*****
******
*******
********
*********
**********
I entered this:
x=1
while x<10:
print '%10s' %'*'*x
x=x+1
Which sadly seems to produce something composed of the right number o... | Asterisk art in python | I would like to produce this picture in python!
*
**
***
****
*****
******
*******
********
*********
**********
I entered this:
x=1
while x<10:
print '%10s' %'*'*x
x=x+1
Which sadly seems to produce something composed of the right number of dots as the picture above,... | [
" '%10s' %'*'*x\n\nis being parsed as\n('%10s' % '*') * x\n\nbecause the % and * operators have the same precedence and group left-to-right[docs]. You need to add parentheses, like this:\nx = 1\nwhile x < 10:\n print '%10s' % ('*' * x)\n x = x + 1\n\nIf you want to loop through a range of numbers, it's con... | [
13,
8,
2,
1,
1
] | [] | [] | [
"ascii_art",
"python",
"string"
] | stackoverflow_0007308344_ascii_art_python_string.txt |
Q:
Writing PowerShell CmdLets in Python Dynamically
I want to be able to write PowerShell CmdLets using IronPython, and furthermore I need one CmdLet to look at the environment and add CmdLets to the PowerShell based on the contents. For example, reading a directory, and adding a CmdLet Remove- for every filename it ... | Writing PowerShell CmdLets in Python Dynamically | I want to be able to write PowerShell CmdLets using IronPython, and furthermore I need one CmdLet to look at the environment and add CmdLets to the PowerShell based on the contents. For example, reading a directory, and adding a CmdLet Remove- for every filename it sees there.
| [
"As far as I know it can't be done!\nThe problem here is that an IronPython class is not a CLR class or compatible with a CLR class. A CLR class is static and an IronPython class is dynamic and the DLR, as far as I know, doesn't for example provide IronPython classes to have .net CLR attributes, which you need for ... | [
3
] | [] | [] | [
".net",
"ironpython",
"powershell",
"powershell_cmdlet",
"python"
] | stackoverflow_0006146892_.net_ironpython_powershell_powershell_cmdlet_python.txt |
Q:
sh script equivalent of python script
Ok, so I have the following situation. I need to edit the PYTHONPATH dynamically on a target PC. Now the structure of the project is:
trunk
bin
start_script
dependencies
dependencies
From python I could do, from start_script:
root_path = os.path.spli... | sh script equivalent of python script | Ok, so I have the following situation. I need to edit the PYTHONPATH dynamically on a target PC. Now the structure of the project is:
trunk
bin
start_script
dependencies
dependencies
From python I could do, from start_script:
root_path = os.path.split(os.path.dirname(os.path.abspath(__file__)... | [
"You could just update the PYTHONPATH environment variable at the same moment you update sys.path in start_script, using the os.environ dict. \n",
"I would use a .pth file. See http://docs.python.org/install/index.html#inst-search-path\nA .pth file is a file consisting in one directory path per line. It will inse... | [
4,
1,
0
] | [] | [] | [
"python",
"scripting_language",
"sh"
] | stackoverflow_0007307432_python_scripting_language_sh.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.