content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to remove an obsolete pynotify notification? I just started with python and wrote myself a nice, small script that uses gnome-notifications via pynotify, like this: import pynotify pynotify.init("Application") alert = pynotify.Notification("Title", "Description") alert.show(); This works great, but the thi...
How to remove an obsolete pynotify notification?
I just started with python and wrote myself a nice, small script that uses gnome-notifications via pynotify, like this: import pynotify pynotify.init("Application") alert = pynotify.Notification("Title", "Description") alert.show(); This works great, but the thing is, when I execute the script twice in a row it tak...
[ "I searched around for a while and came to the conclusion that it is not possible in this case.\nYou are able to use Notification.update() to update an existing notification object. But you can't query existing ones from the system to modify or hide them. It may be possible to store the object somewhere via seriali...
[ 6 ]
[]
[]
[ "gnome", "pynotify", "python" ]
stackoverflow_0007149161_gnome_pynotify_python.txt
Q: Python mini-game isn't working correctly #!/usr/bin/env python from random import randint b = randint(0, 100) print b a = raw_input("Try your luck, choose number (0-100): ") if a.isdigit(): if(a == b): print 'great!' else: print('wrong! that number was %s' % b) else: print "string isn't...
Python mini-game isn't working correctly
#!/usr/bin/env python from random import randint b = randint(0, 100) print b a = raw_input("Try your luck, choose number (0-100): ") if a.isdigit(): if(a == b): print 'great!' else: print('wrong! that number was %s' % b) else: print "string isn't number" And the problem is: $ python luck.py...
[ "You compare a string (result of raw_input) with a number (result of randint), try to test with \nif a.isdigit():\n if(int(a) == b):\n\n", "b is an integer. a is a string. You need to convert it with int(a).\nAlso, it may be more pythonic to ask forgiveness rather than permission:\ntry:\n if (int(a)==b):\n ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007206656_python.txt
Q: Best way to denormalize data in Django? I'm developing a simple web app, and it makes a lot of sense to store some denormalized data. Imagine a blogging platform that keeps track of Comments, and the BlogEntry model has a "CommentCount" field that I'd like to keep up to date. One way of doing this would be to use...
Best way to denormalize data in Django?
I'm developing a simple web app, and it makes a lot of sense to store some denormalized data. Imagine a blogging platform that keeps track of Comments, and the BlogEntry model has a "CommentCount" field that I'd like to keep up to date. One way of doing this would be to use Django signals. Another way of doing this w...
[ "You have managers in Django.\nUse a customized manager to do creates and maintain the FK relationships.\nThe manager can update the counts as the sets of children are updated.\nIf you don't want to make customized managers, just extend the save method. Everything you want to do for denormalizing counts and sums c...
[ 17, 10, 5, 3 ]
[ "Why not just get the set of comments, and find the number of elements, using the count() method:\ncount = blog_entry.comment_set.count()\n\nThen you can pass that into your template.\nOr, alternative, in the template itself, you can do:\n{{ blog_entry.comment_set.count }}\n\nto get the number of comments.\n" ]
[ -1 ]
[ "django", "mysql", "python" ]
stackoverflow_0001100924_django_mysql_python.txt
Q: Django models problem I have a big proble. I implemented a form which holds various fields, among which EmailFIeld must be OPTIONAL. Here's the model: email = models.EmailField(max_length=50,blank=True,default='no@address.spec', verbose_name=_('email'), help_text=_('Email')) But when I do the valida...
Django models problem
I have a big proble. I implemented a form which holds various fields, among which EmailFIeld must be OPTIONAL. Here's the model: email = models.EmailField(max_length=50,blank=True,default='no@address.spec', verbose_name=_('email'), help_text=_('Email')) But when I do the validation of the form and return...
[ "As I remembered, default means that this field won't be blank, if user do not delete specified address. So this validation error can be because of .spec, try to replace it with .com. And you can also add null = True in your model and required = False in form class.\n", "If you intitially setup the model with ema...
[ 3, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0007206237_django_django_forms_django_models_python.txt
Q: sorting on foreign key columns in django admin? I have two tables : customers and attributes.They are related as customers.id=attributes.id (for a given id joining the info of customers and attributes one can get the whole profile of the customer).In the Django admin panel of attributes, I want fields from both ta...
sorting on foreign key columns in django admin?
I have two tables : customers and attributes.They are related as customers.id=attributes.id (for a given id joining the info of customers and attributes one can get the whole profile of the customer).In the Django admin panel of attributes, I want fields from both tables to be shown,search on any field that i wish and ...
[ "did you try this one?\nattributes = Attributes.objects.fi.select_related(\"event_def\", \"location\", \"space\")\n\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0007186065_django_django_admin_django_models_python.txt
Q: Python: how to handle the exceptions of argparse? I'd like to use my program this way: pythonScript -f filename But if I forgot -f, I still want to get the filename. So I want this "pythonScript filename" also work (->I can get the file name from args.fileName or from handling the exception) I know this must be ea...
Python: how to handle the exceptions of argparse?
I'd like to use my program this way: pythonScript -f filename But if I forgot -f, I still want to get the filename. So I want this "pythonScript filename" also work (->I can get the file name from args.fileName or from handling the exception) I know this must be easy, I just can not find a way to do it. Anyone can help...
[ "If you want -f to be required, you can make it that way with argparse. Just include \"required = True\" inside of the add_argument function.\nRemember that required option is contradictory. It's not suggested to make options required, but sometimes helpful. If the option is not given, then the destination remains ...
[ 3 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0007206941_argparse_python.txt
Q: Displaying Http404 parameter in 404.html template If I raise a 404 exception in Django using raise Http404("Error text") how can I display the Http404 parameter ("Error text" in this case) in my 404.html template? (I am using the default Django view to handle 404 errors.) A: Check out defining your own 404 Hand...
Displaying Http404 parameter in 404.html template
If I raise a 404 exception in Django using raise Http404("Error text") how can I display the Http404 parameter ("Error text" in this case) in my 404.html template? (I am using the default Django view to handle 404 errors.)
[ "Check out defining your own 404 Handler. In the view that you write, you can receive the error text and then pass it to the 404 templates.\nKeep in mind that based on the HTTP standards, the 404 error is supposed to be for Page Not Found, not a generic error page. Depending on your use case, maybe reevaluate the u...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007206147_django_python.txt
Q: how do write a list of string into a csv file in python? I have a list of strings with spaces, periods, commas and semi colons and I'm wondering how do I get these into a csv file? I need each list of strings to correspond to one line. A: with open('my.csv', 'w') as handle: handle.write('\n'.join(list_of_str...
how do write a list of string into a csv file in python?
I have a list of strings with spaces, periods, commas and semi colons and I'm wondering how do I get these into a csv file? I need each list of strings to correspond to one line.
[ "with open('my.csv', 'w') as handle:\n handle.write('\\n'.join(list_of_strings))\n\n?\nWe need more info on your \"list of strings\" to know if you need to do any more than that.\n", "Did you have a look to the csv module (especially the examples part )?\n" ]
[ 2, 2 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0007207186_csv_list_python.txt
Q: More relative import oddness: .. notation I noticed I've made about 5 questions asking about relative imports, each with working solutions but with different situations. The more I read the docs and the more I try out different cases the more I'm getting confused and questioning whether I'm actually reading the wo...
More relative import oddness: .. notation
I noticed I've made about 5 questions asking about relative imports, each with working solutions but with different situations. The more I read the docs and the more I try out different cases the more I'm getting confused and questioning whether I'm actually reading the words correctly. From pep 328: A single leading d...
[ "As you found out, from ..lib import myLib does not work as main is not a package. Relative imports only work within a module's own package. In your example, lib and other are two distinct packages.\nPutting an __init__.py in main only works if you move run outside of the newly created main package, so that the c...
[ 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0007207265_import_python.txt
Q: print content of files in remote server using: python, ssh, subprocess, find -print0 I'm Trying to connect to a remote server using python subprocess and ssh, list the files in a directory using 'find . -print0' and print out the content of each file line by line avoiding memory issues. any ideas guys? A: I woul...
print content of files in remote server using: python, ssh, subprocess, find -print0
I'm Trying to connect to a remote server using python subprocess and ssh, list the files in a directory using 'find . -print0' and print out the content of each file line by line avoiding memory issues. any ideas guys?
[ "I would sugest bash, but if you really want to stick with python.\nhttp://www.lag.net/paramiko/ is a client for ssh. From that, if you know ssh, is just executing some commands from the other side.\n", "Maybe you could have a look to Fabric, it is implemented in Python and is aware of managing big streams betwee...
[ 1, 0 ]
[]
[]
[ "python", "ssh", "subprocess" ]
stackoverflow_0007207479_python_ssh_subprocess.txt
Q: Python regex problem I'm trying to match some html with a regex, and the regex works fine if like this: import re reg = r";!--\"\'<[a-i0-9]{8}>=&\{\(\)\}" html_data = "some html data" if re.search(reg, html_data): print("Match") But if it get's the html data either from reading a local file or getting it f...
Python regex problem
I'm trying to match some html with a regex, and the regex works fine if like this: import re reg = r";!--\"\'<[a-i0-9]{8}>=&\{\(\)\}" html_data = "some html data" if re.search(reg, html_data): print("Match") But if it get's the html data either from reading a local file or getting it from the web it fails. I've...
[ "For me, your problem is due to your erroneous interpretation of this:\n<input type=\"text\" value=\";!--\\\"\\'<a41cgb04>=&{()}\" name=\"url\" maxlength=\"200\" class=\"url\" style=\"width:495px;\">\n\nYou think that the backslashes in front of \" and ' are in the source code. But I think that one of the two is in...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007206143_python_regex.txt
Q: Python Referenced For Loop I'm playing with for loops in Python and trying to get used to the way they handle variables. Take the following piece for code: a=[1,2,3,4,5] b=a b[0]=6 After doing this, the zeroth element of both b and a should be 6. The = sign points a reference at the array, yes? Now, I take a for ...
Python Referenced For Loop
I'm playing with for loops in Python and trying to get used to the way they handle variables. Take the following piece for code: a=[1,2,3,4,5] b=a b[0]=6 After doing this, the zeroth element of both b and a should be 6. The = sign points a reference at the array, yes? Now, I take a for loop: a=[1,2,3,4,5] for i in a: ...
[ "That isn't how it works. The for loop is iterating through the values of a. The variable i actually has no sense of what is in a itself. Basically, what is happening:\n# this is basically what the loop is doing:\n# beginning of loop:\ni = a[0]\ni = 6\n# next iteration of for loop:\ni = a[1]\ni = 6\n# next iteratio...
[ 5, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007207695_python.txt
Q: Pythonic Referenced For Loop I have a for loop as follows: a=[1,2,3,4,5] for i in a: i=6 What I would like is for every element of a to become 6. Now I know that this for loop won't do it, because I am merely changing the what i refers to. I instead could write: a=[1,2,3,4,5] for i in len(range(a)): a[i]=...
Pythonic Referenced For Loop
I have a for loop as follows: a=[1,2,3,4,5] for i in a: i=6 What I would like is for every element of a to become 6. Now I know that this for loop won't do it, because I am merely changing the what i refers to. I instead could write: a=[1,2,3,4,5] for i in len(range(a)): a[i]=6 But that doesn't seem very Pyth...
[ "The for-variable is always a simple value, not a reference; there is no way to know that it came from a list and thus write back to the list on changing.\nThe len(a) approach is the usual idiom, although you need range (or xrange) too:\nfor i in range(len(a)):\n\nor, just as commonly, use the enumerate function to...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007207907_python.txt
Q: Equivalent python functions for several matlab image processing functions Is there an equivalent python function for each of the following (maybe in the PIL??): edge(image, 'canny') strel('line',..) strel('diamond',1) imdilate(...) imfil(...) imerode(...) medfilt2(...) All of my simulation code is in python, but n...
Equivalent python functions for several matlab image processing functions
Is there an equivalent python function for each of the following (maybe in the PIL??): edge(image, 'canny') strel('line',..) strel('diamond',1) imdilate(...) imfil(...) imerode(...) medfilt2(...) All of my simulation code is in python, but not the IC generation! I wanna get my IC generation into python so I don't have ...
[ "There are lots of image processing libraries for Python, though they are spread across a number of packages:\n\nscipy.ndimage\nscikits.image\nmahotas\npymorph\nOpenCV\nPIL\n\nJust go through the documentation pages and look for an equivalent to each of the functions you listed. I think you will find edge detection...
[ 5, 1 ]
[]
[]
[ "image_processing", "matlab", "python", "python_imaging_library" ]
stackoverflow_0007197669_image_processing_matlab_python_python_imaging_library.txt
Q: translation in celery tasks I used ugettext in one of my tasks. I had edited the po file. But it didn't work. Does anyone know why? thanks! from django.utils.translation import ugettext @task def testtask(): ..... msg = ugettext('test') ..... Read the celery document, I put the language parameter in ...
translation in celery tasks
I used ugettext in one of my tasks. I had edited the po file. But it didn't work. Does anyone know why? thanks! from django.utils.translation import ugettext @task def testtask(): ..... msg = ugettext('test') ..... Read the celery document, I put the language parameter in the task, and do activate(languag...
[ "Django determines the current language using the LocaleMiddleware. As a celery task is processed out of any request scope, so it will fall back to LANGUAGE_CODE. As you stated you need to activated the language manually, then the language is bound to the local thread and therefore available for ugettext.\n" ]
[ 3 ]
[]
[]
[ "celery", "django", "python", "translation" ]
stackoverflow_0007199256_celery_django_python_translation.txt
Q: How can a java.lang.float be encoded as TH3IFMw? I need to parse some data that has encoded primitive types (ints, floats, doubles, floats) outputted by java. I'm adding this functionality to an existing set of python scripts, so rewriting it in Java isn't really an option. I'd like to re-implement and/or use a ...
How can a java.lang.float be encoded as TH3IFMw?
I need to parse some data that has encoded primitive types (ints, floats, doubles, floats) outputted by java. I'm adding this functionality to an existing set of python scripts, so rewriting it in Java isn't really an option. I'd like to re-implement and/or use a python library to decode the data (e.g. TH3IFMw for a ...
[ "I think this is encoding a long int, not a float. In particular, it's probably 0x0000004c7dc814cc, but might be 0x00000131f7205330. \n\nMy reasoning...\nLooking through the code you linked to, it doesn't look like anything remotely out of the ordinary is being done to floats, and the standard valueOf implementatio...
[ 1 ]
[]
[]
[ "java", "python", "value_of" ]
stackoverflow_0007163646_java_python_value_of.txt
Q: Dynamically increase/decrease total price in order form that uses radio buttons I'm trying to dynamically calculate the total of an order using Django/Python and Javascript. I'm using radio buttons with pre-defined values, which are displayed based upon which products are currently in stock and what other items su...
Dynamically increase/decrease total price in order form that uses radio buttons
I'm trying to dynamically calculate the total of an order using Django/Python and Javascript. I'm using radio buttons with pre-defined values, which are displayed based upon which products are currently in stock and what other items support. Example: motherboard that supports a max of 8gb of ram would display 4 radio b...
[ "var id = $(\".ram\") is an array of all the items with this class name.\nThis will loop through them all.\n$(\".ram\").each(function() {\n alert($(this).attr(\"price\"))\n})\n\nYou can address them individually using an index like this:\nfor(var x=0;x<$(\".ram\").length;x++) {\n alert($(\".ram\").eq(x))\n}\...
[ 2, 2 ]
[]
[]
[ "django", "forms", "javascript", "jquery", "python" ]
stackoverflow_0007208315_django_forms_javascript_jquery_python.txt
Q: String Occurrence Counting Algorithm I am curious what is the most efficient algorithm (or commonly used) to count the number of occurrences of a string in a chunk of text. From what I read, the Boyer–Moore string search algorithm is the standard for string searches but I am not sure if counting occurrences in an...
String Occurrence Counting Algorithm
I am curious what is the most efficient algorithm (or commonly used) to count the number of occurrences of a string in a chunk of text. From what I read, the Boyer–Moore string search algorithm is the standard for string searches but I am not sure if counting occurrences in an efficient way would be same as searching a...
[ "For starters, yes, you can accomplish this with Boyer-Moore very efficiently. However, depending on some other parameters of your problem, there might be a better solution.\nThe Aho-Corasick string matching algorithm will find all occurrences of a set of pattern strings in a target string and does so in time O(m ...
[ 3, 1 ]
[ "Hellnar,\nYou can use a simple dictionary to count occurrences in a String. The algorithm is a counting algorithm, here is an example: \n\"\"\"\nThe counting algorithm is used to count the occurences of a character\nin a string. This allows you to compare anagrams and strings themselves.\nex. animal, lamina a=2,n=...
[ -1 ]
[ "algorithm", "python", "search", "string", "string_search" ]
stackoverflow_0002768038_algorithm_python_search_string_string_search.txt
Q: What is wrong with this singleton? Currently I'm using a rather simplistic implementation of a singleton. However, I've never seen anything like this suggested on the web, which leads me to believe there might be something wrong with it... class Singleton: def __init__(): raise ... @staticmethod ...
What is wrong with this singleton?
Currently I'm using a rather simplistic implementation of a singleton. However, I've never seen anything like this suggested on the web, which leads me to believe there might be something wrong with it... class Singleton: def __init__(): raise ... @staticmethod def some(): pass @static...
[ "Yeah, it's a singleton, that's what's wrong with it. If you're going to make all methods static, don't bother making a class at all, just use free functions.\n", "That's not a singleton. It's a stateless global collection of methods, wrapped in a type.\nNothing inherently wrong with it, unless you believe that i...
[ 11, 2, 1, 1, 1 ]
[]
[]
[ "python", "singleton" ]
stackoverflow_0007207347_python_singleton.txt
Q: Similar C string format in Python I need to read a file with some strange string lines like : \x72\xFE\x20TEST_STRING\0\0\0 but when I do a print of this string (with repr()) it prints this : r\xfe TEST_STRING\x00\x00\x00 Example : >>> test = '\x72\xFE\x20TEST_STRING\0\0\0' >>> print test r? TEST_STRING >>> print...
Similar C string format in Python
I need to read a file with some strange string lines like : \x72\xFE\x20TEST_STRING\0\0\0 but when I do a print of this string (with repr()) it prints this : r\xfe TEST_STRING\x00\x00\x00 Example : >>> test = '\x72\xFE\x20TEST_STRING\0\0\0' >>> print test r? TEST_STRING >>> print repr(test) 'r\xfe TEST_STRING\x00\x00\...
[ "You should use python's raw strings, like this (note the 'r' in front of the string)\ntest = r'\\x72\\xFE\\x20TEST_STRING\\0\\0\\0'\n\nThen it won't try to interpret the escapes as special characters.\nWhen reading from a text file python shouldn't be trying to interpret the string as having multi-byte unicode cha...
[ 1, 1, 1, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0007208488_encoding_python.txt
Q: Help with wrapping a command line tool in Python I'm really stuck with a problem I'm hoping someone can help me with. I'm trying to create a wrapper in Python3.1 for a command line program called spooky. I can successfully run this program on the command line like this: $ spooky -a 4 -b .97 My first Python wrappe...
Help with wrapping a command line tool in Python
I'm really stuck with a problem I'm hoping someone can help me with. I'm trying to create a wrapper in Python3.1 for a command line program called spooky. I can successfully run this program on the command line like this: $ spooky -a 4 -b .97 My first Python wrapper attempt for spooky looked like this: import subproce...
[ "You need to drop the stdout=subprocess.PIPE. Doing that disconnects the stdout of your process from Python's stdout and makes it retrievable using the Popen.communicate() function, like so:\nimport subprocess\n\nspooky_path = 'ls'\ncmd = [spooky_path, '-l']\nprocess = subprocess.Popen(cmd, stdout=subprocess.PIPE)\...
[ 5, 0 ]
[]
[]
[ "python", "subprocess", "wrapper" ]
stackoverflow_0007208648_python_subprocess_wrapper.txt
Q: replace characters not working in python I am using beautiful soup and I am writing a crawler and have the following code in it: print soup.originalEncoding #self.addtoindex(page, soup) links=soup('a') for link in links: if('href' in dict(link.attrs))...
replace characters not working in python
I am using beautiful soup and I am writing a crawler and have the following code in it: print soup.originalEncoding #self.addtoindex(page, soup) links=soup('a') for link in links: if('href' in dict(link.attrs)): link...
[ "string.replace() returns the string with the replaced values. It doesn't modify the original so do something like this:\nlink['href'] = link['href'].replace(\"..\", \"\")\n\n", "string.replace() returns a copy of the string with characters replaced, as strings in Python are immutable. Try\ns = link['href'].repl...
[ 62, 15, 11 ]
[]
[]
[ "python" ]
stackoverflow_0007208861_python.txt
Q: python get by index for a dictionary I have subclass that inherits from a dict. On __getitem__ method I'd like to check whether the key is numeric or not. If it is numeric I'd like to implement some other behavior and if it not then I'd like continue as it would normally do. Example: class M(dict): ... def _...
python get by index for a dictionary
I have subclass that inherits from a dict. On __getitem__ method I'd like to check whether the key is numeric or not. If it is numeric I'd like to implement some other behavior and if it not then I'd like continue as it would normally do. Example: class M(dict): ... def __getitem__(self, key): if self.isNum...
[ "# continue the same way as it would have done\n\nHere use the super() function. (this is not a joke)\nhttp://docs.python.org/library/functions.html#super\n", "Not sure if this is what you are looking for...\nclass M(dict):\n\n def __getitem__(self, key):\n try:\n temp = int(key)\n ...
[ 2, 2, 1 ]
[ "You need to index by the list of the keys for the dictionary.\nExample:\nx = dict({\"name\": \"Tom\", \"surname\": \"Baker\", \"age\": \"55\"})\nprint x[x.keys()[0]]\n'55'\n\nEdit: As I suspected, the order is not guaranteed.\n\n\"Keys and values are listed in an arbitrary order which is non-random,\n varies acro...
[ -2 ]
[ "dictionary", "python", "subclass" ]
stackoverflow_0007208931_dictionary_python_subclass.txt
Q: Forcing imported method to use local variables I have a module 'b' importing a method from module "a", where method "a.method" uses a variable defined in "a" must be overriden in "b". simply, in codes: module a.py: local_var = 1 def method(): print local_var module b.py: from a import method local_var = 2 p...
Forcing imported method to use local variables
I have a module 'b' importing a method from module "a", where method "a.method" uses a variable defined in "a" must be overriden in "b". simply, in codes: module a.py: local_var = 1 def method(): print local_var module b.py: from a import method local_var = 2 print method() running python b.py prints 1, instead...
[ "You can't. This is by design. Each module has its own namespace.\nYou can, however, save the current value of var, assign a new value, call the method and restore the original value.\n# module a.py:\n\nlocal_var = 1\ndef method():\n print local_var\n\n# module b.py:\n\nimport a\nold_local_var = a.local_var\na.l...
[ 1, 1 ]
[]
[]
[ "import", "module", "python", "scope" ]
stackoverflow_0007206048_import_module_python_scope.txt
Q: Creating a dictionary from a passed in string I have a variable foo = "'totalteams': 10, 'totalrounds': 11" Why can't I do this? data=dict(foo) so I can do print data['totalteams'] I need to use python 2.5 because of google. How do I do what I want? thanks A: foo = "'totalteams': 10, 'totalrounds': 11" data = ...
Creating a dictionary from a passed in string
I have a variable foo = "'totalteams': 10, 'totalrounds': 11" Why can't I do this? data=dict(foo) so I can do print data['totalteams'] I need to use python 2.5 because of google. How do I do what I want? thanks
[ "foo = \"'totalteams': 10, 'totalrounds': 11\"\ndata = eval(\"{%s}\" % foo)\nprint data['totalteams']\n\n", "Because a string is not a dictionary. You have a couple of options:\nMake a dictionary literal:\ndata = {'totalteams': 10, 'totalrounds': 11}\nprint data['totalteams']\n\nHave a JSON string or something si...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "variable_assignment" ]
stackoverflow_0007208955_dictionary_python_variable_assignment.txt
Q: Can list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL? I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count? (I've defined an __eq__ to define uniqueness on my o...
Can list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL?
I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count? (I've defined an __eq__ to define uniqueness on my object definition). So in RDBMS-land, something like this: CREATE TABLE x(n NUMBER(1)); INSERT...
[ "Lennart Regebro provided a nice one-liner that does what you want: \n>>> values = [1,1,1,2]\n>>> print [(x,values.count(x)) for x in set(values)]\n[(1, 3), (2, 1)]\n\nAs S.Lott mentions, a defaultdict can do the same thing.\n", ">>> from collections import Counter\n>>> Counter([1,1,1,2])\nCounter({1: 3, 2: 1}...
[ 11, 11, 6, 5, 1 ]
[]
[]
[ "count", "list", "python", "python_2.6" ]
stackoverflow_0002148480_count_list_python_python_2.6.txt
Q: python - elegantly handle sequence of multiple arguments Thus far I was handling multiple arguments via Optparse as a string, Eg: --update_entities="host_group hostname entity_type entities2monitor" where entities2monitor has variable arguments, grabbing them inside the callback function via (notice the [3:]), h...
python - elegantly handle sequence of multiple arguments
Thus far I was handling multiple arguments via Optparse as a string, Eg: --update_entities="host_group hostname entity_type entities2monitor" where entities2monitor has variable arguments, grabbing them inside the callback function via (notice the [3:]), host = value.split() (host_group, hostname, entity_type, entiti...
[ "I'm not sure if this is what you want, but it seems to me that you could use argparse and use the nargs argument to specify how many arguments should be consumed.\nYou probably know it already, but here's a link: http://docs.python.org/dev/library/argparse.html#nargs\nusing nargs=+ or nargs=* will put your argumen...
[ 1, 1 ]
[]
[]
[ "command_line_arguments", "optparse", "python" ]
stackoverflow_0007209075_command_line_arguments_optparse_python.txt
Q: update one dictionary with another by adding values rather then replacing it I have many dictionaries like this: dict1 = {1:[1,2,3],2:[2,3,4]} dict2 = {2:[3,4,5],3:[4,5,6]} I need to get dict = {1:[1,2,3],2:[2,3,4,3,4,5],3:[4,5,6]} # ^ # | order is unimportant What is ...
update one dictionary with another by adding values rather then replacing it
I have many dictionaries like this: dict1 = {1:[1,2,3],2:[2,3,4]} dict2 = {2:[3,4,5],3:[4,5,6]} I need to get dict = {1:[1,2,3],2:[2,3,4,3,4,5],3:[4,5,6]} # ^ # | order is unimportant What is the best way of doing it?
[ "Simple iteration an extending list...\nfor key, value in dict2.iteritems():\n dict1.setdefault(key, []).extend(value)\n\n", "Iterate through the keys of dict2; if the same key exists in dict1, concatenate the lists and set in dict1; otherwise just set in dict1\n", "dict1 = {1:[1,2,3],2:[2,3,4]}\ndict2 = {2:...
[ 7, 1, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007206610_dictionary_python.txt
Q: Testing wchar_t* for convertable characters I'm working on talking to a library that handles strings as wchar_t arrays. I need to convert these to char arrays so that I can hand them over to Python (using SWIG and Python's PyString_FromString function). Obviously not all wide characters can be converted to chars. ...
Testing wchar_t* for convertable characters
I'm working on talking to a library that handles strings as wchar_t arrays. I need to convert these to char arrays so that I can hand them over to Python (using SWIG and Python's PyString_FromString function). Obviously not all wide characters can be converted to chars. According to the documentation for wcstombs, I ou...
[ "Clearly, as you found, it's essential to zero-terminate your input data.\nRegarding the final paragraph, I would convert from wide to UTF8 and call PyUnicode_FromString.\nNote that I am assuming you are using Python 2.x, it's presumably all different in Python 3.x.\n" ]
[ 0 ]
[]
[]
[ "c", "python", "widechar" ]
stackoverflow_0007209502_c_python_widechar.txt
Q: python2.5 says platform dependent libraries not found Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license...
python2.5 says platform dependent libraries not found
Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> import operator T...
[ "Module operator should come from file operator.so, presumably in /usr/local/lib/lib-dynload in your case since that seems to be where you've installed things. So what .so files are in that directory?\nAssuming operator.so is indeed missing (i.e., assuming it's not some trivial case of wrong permissions on some dir...
[ 1, 1, 0 ]
[]
[]
[ "configuration", "python" ]
stackoverflow_0001261848_configuration_python.txt
Q: Why the QNetworkReply readAll() returns zero bytes? I am using qtwebkit in pyqt4 to download images through QNetworkReply: import os import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import QWebPage class dxBrowser(QWebPage): def __init__(self,url): QWebPage.__init__(self) ...
Why the QNetworkReply readAll() returns zero bytes?
I am using qtwebkit in pyqt4 to download images through QNetworkReply: import os import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import QWebPage class dxBrowser(QWebPage): def __init__(self,url): QWebPage.__init__(self) self._url=url self.manager=self.networkAccessMana...
[ "\nEDIT: Maybe I figured this out. The qtwebkit may have retrieve the\n content of the qnetworkreply, a QIODevice, the size of it would be 0\n after readall().Maybe the qtwebkit as a browser has read it for\n rendering, I guess.\n\nYes and there is an easy work-around: add a QNetworkDiskCache to the manager (wit...
[ 2 ]
[]
[]
[ "network_programming", "networking", "pyqt4", "python", "qtwebkit" ]
stackoverflow_0007136962_network_programming_networking_pyqt4_python_qtwebkit.txt
Q: How to run PyQt4 with flash web page? I use this very simple python script Problem loading a specific website through Qt Webkit to display a web page. It works well, but it doesn't detect my installed libflashplayer.so on linux x86_64 (that displays http://www.adobe.com/go/getflash/ URL) . What can I do to be able...
How to run PyQt4 with flash web page?
I use this very simple python script Problem loading a specific website through Qt Webkit to display a web page. It works well, but it doesn't detect my installed libflashplayer.so on linux x86_64 (that displays http://www.adobe.com/go/getflash/ URL) . What can I do to be able to run flash web pages ? (flash works well...
[ "You need to enable the plugins explicitly with:\nQWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True)\n\n" ]
[ 2 ]
[]
[]
[ "flash", "pyqt4", "python" ]
stackoverflow_0007198092_flash_pyqt4_python.txt
Q: python prime crunching: processing pool is slower? So I've been messing around with python's multiprocessing lib for the last few days and I really like the processing pool. It's easy to implement and I can visualize a lot of uses. I've done a couple of projects I've heard about before to familiarize myself with i...
python prime crunching: processing pool is slower?
So I've been messing around with python's multiprocessing lib for the last few days and I really like the processing pool. It's easy to implement and I can visualize a lot of uses. I've done a couple of projects I've heard about before to familiarize myself with it and recently finished a program that brute forces game...
[ "the most efficient way to use multiprocessing is to divide the work into n equal sized chunks, with n the size of the pool, which should be approximately the number of cores on your system. The reason for this is that the work of starting subprocesses and communicating between them is quite large. If the size of...
[ 14 ]
[]
[]
[ "multiprocessing", "pool", "python" ]
stackoverflow_0007209657_multiprocessing_pool_python.txt
Q: Why does list.remove() not behave as one might expect? from pprint import * sites = [['a','b','c'],['d','e','f'],[1,2,3]] pprint(sites) for site in sites: sites.remove(site) pprint(sites) outputs: [['a', 'b', 'c'], ['d', 'e', 'f'], [1, 2, 3]] [['d', 'e', 'f']] why is it not None, or an empty list [] ...
Why does list.remove() not behave as one might expect?
from pprint import * sites = [['a','b','c'],['d','e','f'],[1,2,3]] pprint(sites) for site in sites: sites.remove(site) pprint(sites) outputs: [['a', 'b', 'c'], ['d', 'e', 'f'], [1, 2, 3]] [['d', 'e', 'f']] why is it not None, or an empty list [] ?
[ "It's because you're modifying a list as you're iterating over it. You should never do that.\nFor something like this, you should make a copy of the list and iterate over that.\nfor site in sites[:]:\n sites.remove(site)\n\n", "Because resizing a collection while iterating over it is the Python equivalent to u...
[ 51, 11, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007210578_python.txt
Q: How can I measure the width of a string rendering via tkFont without creating a window first? I can do the measure of text with tkFont, but I don't want a root window --> tk.Tk() A: Now I have this, and it works root = tk.Tk() font = tkFont.Font(family=fn, size=fs) w, h = (font.measure(text), font.metrics("lines...
How can I measure the width of a string rendering via tkFont without creating a window first?
I can do the measure of text with tkFont, but I don't want a root window --> tk.Tk()
[ "Now I have this, and it works\nroot = tk.Tk()\nfont = tkFont.Font(family=fn, size=fs)\nw, h = (font.measure(text), font.metrics(\"linespace\"))\nroot.destroy()\n\n", "You did mean to ask: “How can I measure the width of a string rendering via tkFont without creating a window first?”\nAn the answer is: you can’t....
[ 5, 3 ]
[]
[]
[ "fonts", "python", "tkinter" ]
stackoverflow_0007193798_fonts_python_tkinter.txt
Q: Python: ctypes + C malloc error. C memory problem or Python/ctypes problem? everyone. I'm having a memory allocation error using ctypes and a C code. I'm wondering if the memory problem is inside of C, or caused by an improper use of ctypes. The memory error is python(79698) malloc: * error for object 0x15627ac...
Python: ctypes + C malloc error. C memory problem or Python/ctypes problem?
everyone. I'm having a memory allocation error using ctypes and a C code. I'm wondering if the memory problem is inside of C, or caused by an improper use of ctypes. The memory error is python(79698) malloc: * error for object 0x15627ac08: incorrect checksum for freed object >- object was probably modified after bei...
[ "I had this problem and here is what I figured out:\nIf you map something with ctypes and then free it you will get an error when the ctypes object is destroyed. So, before you call free(), you need to make sure that there are no remaining references to it in the python code.\nSo, your C code will be like:\nchar* p...
[ 4 ]
[]
[]
[ "c", "ctypes", "malloc", "python" ]
stackoverflow_0006230719_c_ctypes_malloc_python.txt
Q: Python or command line utility - sort and filter file? Given data of the form: a b 1.1 c d 2.3 b a 1.1 Is it possible to sort such a file based on the thired column and remove lines where the entry in the third column is duplicated, such that the output will be: a b 1.1 c d 2.3 or, c d 2.3 b a 1.1 . I am capabl...
Python or command line utility - sort and filter file?
Given data of the form: a b 1.1 c d 2.3 b a 1.1 Is it possible to sort such a file based on the thired column and remove lines where the entry in the third column is duplicated, such that the output will be: a b 1.1 c d 2.3 or, c d 2.3 b a 1.1 . I am capable of using only python, R or command line utilities to perfo...
[ "Unix sort should be able to do the work for you:\ncat file | sort -u -k3,3n\na b 1.1\nc d 2.3\ncat file | sort -u -k3,3rn\nc d 2.3\na b 1.1\n", "f = open('text.txt','rb')\nfilter = []\nrows = []\nfor line in f:\n line = line.replace('\\r\\n','')\n data = line.split(' ')\n if len(data) >= 3:\n if ...
[ 8, 2 ]
[]
[]
[ "command_line", "python", "text_processing" ]
stackoverflow_0007210734_command_line_python_text_processing.txt
Q: In Python App Engine How Do I Uniquely Identify An Instance Of My App Running On The Dev SDK? My application relies on an external service that it communicates with using urlfetch. I have multiple developers each running their own instance of my application on their development computers while they add features. E...
In Python App Engine How Do I Uniquely Identify An Instance Of My App Running On The Dev SDK?
My application relies on an external service that it communicates with using urlfetch. I have multiple developers each running their own instance of my application on their development computers while they add features. Each developer instance needs to be able to uniquely identify itself to the external service so that...
[ "The only trick I've seen to identify instances is using a global variable address.\nUNIQUE_INSTANCE_ID = {} # at module level\nlogging.debug(\"Instance %s.\" % (str(\"%X\" % id( UNIQUE_INSTANCE_ID )).zfill(16)))\n\nThat seems to work fairly well to uniquely identify an instance; but it only identifies an instance,...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007195930_google_app_engine_python.txt
Q: UDP security and identifying incoming data I have been creating an application using UDP for transmitting and receiving information. The problem I am running into is security. Right now I am using the IP/socketid in determining what data belongs to whom. However, I have been reading about how people could simply s...
UDP security and identifying incoming data
I have been creating an application using UDP for transmitting and receiving information. The problem I am running into is security. Right now I am using the IP/socketid in determining what data belongs to whom. However, I have been reading about how people could simply spoof their IP, then just send data as a specific...
[ "One solution is to use TCP because it is immune to spoofing the source address over the open internet because of the three-way-handshake (More information on why TCP source address spoofing is impossible.). If you still want to use UDP, you could have a simulated three way handshake to begin the connection. A ...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "cryptography", "encryption", "python", "security", "udp" ]
stackoverflow_0002808092_cryptography_encryption_python_security_udp.txt
Q: problems with python-mailer and google? I've just tried the following: server = smtplib.SMTP(smtpname, smtpport) server.ehlo() server.starttls() server.ehlo() server.login(username, password) server.sendmail(username, recipient, "TEST") server.close() smtpname is "smtp.gmail.com", smtpport is 587, username is a g...
problems with python-mailer and google?
I've just tried the following: server = smtplib.SMTP(smtpname, smtpport) server.ehlo() server.starttls() server.ehlo() server.login(username, password) server.sendmail(username, recipient, "TEST") server.close() smtpname is "smtp.gmail.com", smtpport is 587, username is a google acc + "@gmail.com", recipient is a 2nd ...
[ "Take a look at the email example\nYour use of \"TEST\" string should be a properly formatted MIME message.\nIn your case, it should be be:\n from email.mime.text import MIMEText\nimport smtplib\n\n# Create a MIME text message and populate its values\nmsg = MIMEText(\"TEST\")\nmsg['Subject'] = \"TEST\"\nmsg['Fro...
[ 2 ]
[]
[]
[ "gmail", "python", "smtp", "smtplib" ]
stackoverflow_0006297840_gmail_python_smtp_smtplib.txt
Q: C# custom database engine, how to implement SQL As a personal project, I have been developing my own database software in C#. Many current database systems can use SQL commands for queries. Is there anyone here that could point me in the right direction of implementing such a system in a database software written ...
C# custom database engine, how to implement SQL
As a personal project, I have been developing my own database software in C#. Many current database systems can use SQL commands for queries. Is there anyone here that could point me in the right direction of implementing such a system in a database software written completely from scratch? For example a user familiar ...
[ "A full-on database engine is a pretty serious undertaking. You're not going to sit down and have a complete engine next week, so I'd have thought you would want to write the SQL parser piecemeal: adding features to the parser as the features are supported in the engine.\nI'm guessing this is just something fun to...
[ 3 ]
[]
[]
[ "c#", "database", "java", "python", "sql" ]
stackoverflow_0007211204_c#_database_java_python_sql.txt
Q: Problem importing matplotlib.mlab and .pyplot in python 2.7 on Mac OSX 10.6 I am trying to plot a histogram using matplotlib in Python 2.7 on OSX 10.6 I have verified that I can import numpy, scipy, and matplotlib into python. A sample script on the matplotlib website does #!/usr/bin/env python import numpy as np ...
Problem importing matplotlib.mlab and .pyplot in python 2.7 on Mac OSX 10.6
I am trying to plot a histogram using matplotlib in Python 2.7 on OSX 10.6 I have verified that I can import numpy, scipy, and matplotlib into python. A sample script on the matplotlib website does #!/usr/bin/env python import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt However, I get an...
[ "For the ImportError: It seems that there is an architecture mismatch. Maybe you have installed a 32-bit version of matplotlib, but are using a 64-bit Python? What does the following shell command print?\nfile /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/nxutils.so\n\nF...
[ 3, 2 ]
[]
[]
[ "matplotlib", "osx_snow_leopard", "python" ]
stackoverflow_0007157330_matplotlib_osx_snow_leopard_python.txt
Q: How to write messages in file from threads in twisted? I want to write a custom log file this simple string, but log.msg write all events from script. How to made a third custom log file ? ( log.err, log.msg, log.custom ) ? A: Have you seen the logging module? It allows you to log to several files at the same t...
How to write messages in file from threads in twisted?
I want to write a custom log file this simple string, but log.msg write all events from script. How to made a third custom log file ? ( log.err, log.msg, log.custom ) ?
[ "Have you seen the logging module? It allows you to log to several files at the same time. Or are you simply redirecting output from stdout? In that case, you could set sys.stdout to your own subclass of StringIO and override the write method to write to several files.\n" ]
[ 2 ]
[]
[]
[ "python", "twisted.web" ]
stackoverflow_0007210299_python_twisted.web.txt
Q: Python C API: Modify search path How can I add a speciific directory to the search path using the C API? And a related question: will the changes be local to the application, or is the search path global? A: Use PySys_GetObject("path") to retrieve sys.path, then manipulate it as you would any other sequence or l...
Python C API: Modify search path
How can I add a speciific directory to the search path using the C API? And a related question: will the changes be local to the application, or is the search path global?
[ "Use PySys_GetObject(\"path\") to retrieve sys.path, then manipulate it as you would any other sequence or list. Changes will be local to the Python interpreter/VM.\n", "You can update search path using the well-known Python code but called from within your C module:\nPyRun_SimpleString(\n \"import sys\\n\"\n ...
[ 15, 14 ]
[]
[]
[ "c", "python" ]
stackoverflow_0007137412_c_python.txt
Q: Dynamic login/logout URLs in Django I have an app that serves pages like this /stage/stagename. stagename is variable. The URL mappers just look for a [0-9A-Za-z]+ to fill that slot. Now, because of my setup, My app will be rooted at /stage/stagename. I cannot change this (without massive changes to my setup whic...
Dynamic login/logout URLs in Django
I have an app that serves pages like this /stage/stagename. stagename is variable. The URL mappers just look for a [0-9A-Za-z]+ to fill that slot. Now, because of my setup, My app will be rooted at /stage/stagename. I cannot change this (without massive changes to my setup which is too tedious right now and a last opt...
[ "If you can get redirect_to into the context for your login template, then there is a mechanism you can use to choose vary the redirect URL.\nIn your login template, add an extra hidden input to the form\n<input type=\"hidden\" name=\"next\" value=\"{% url redirect_to %}\">\n\nNow in your urls.py file, you can spec...
[ 1, 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0004013754_django_django_authentication_python.txt
Q: ctypes and memory leak test.c: #include <stdint.h> #include <stdio.h> #include <stdlib.h> #define MAXFRAGMENTS 4000000 typedef struct { uint64_t FirstFragmentTimestamp; } fragment_t; typedef struct { fragment_t** fragments; } bts_t; bts_t* initialize() { uint32_t i; bts_t* bts; bts = (bts_t ...
ctypes and memory leak
test.c: #include <stdint.h> #include <stdio.h> #include <stdlib.h> #define MAXFRAGMENTS 4000000 typedef struct { uint64_t FirstFragmentTimestamp; } fragment_t; typedef struct { fragment_t** fragments; } bts_t; bts_t* initialize() { uint32_t i; bts_t* bts; bts = (bts_t *) malloc(sizeof(bts_t)); ...
[ "This may not be your only problem, but the ctypes type c_ulong corresponds to the C type unsigned long, which is only 32 bits. You should use c_ulonglong instead, which is 64 bits.\n", "It works on Windows (gcc 4.5.3):\nimport os\nm = bts_initialize()\nos.system('tasklist /fi \"imagename eq python.exe\"')\nbts_...
[ 1, 1, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007210965_ctypes_python.txt
Q: url_for appending query string in Pylons in routes.py: map.connect("/panel/transaction/list/{count}/",controller='transaction',action='list' , count=0) map.connect('/panel/transaction/tcard/{key}/{transaction_id}/',controller='transaction',action='tcard' , key='a',transaction_id=0) When i open url like this /pane...
url_for appending query string in Pylons
in routes.py: map.connect("/panel/transaction/list/{count}/",controller='transaction',action='list' , count=0) map.connect('/panel/transaction/tcard/{key}/{transaction_id}/',controller='transaction',action='tcard' , key='a',transaction_id=0) When i open url like this /panel/transaction/tcard/a/12/ then h.url_for(contr...
[ "You're experiencing the Route Memory feature of Routes.\nhttp://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html#route-memory\n" ]
[ 1 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0007167944_pylons_python_routes.txt
Q: Better pattern for multi-listener notifications with `gevent.event.Event`? I've found that most of the time when I use gevent.event.Event, my code looks something like this: old_event = self.some_event self.some_event = Event() old_event.set() With the listeners looking something like: while 1: self.some_even...
Better pattern for multi-listener notifications with `gevent.event.Event`?
I've found that most of the time when I use gevent.event.Event, my code looks something like this: old_event = self.some_event self.some_event = Event() old_event.set() With the listeners looking something like: while 1: self.some_event.wait() … do stuff … Is this the “right way to do it”? Or is there a bette...
[ "Well, you can also clear() the event.\nevent.set()\nevent.clear()\n\nThis will notify the listeners that are currently waiting for the event, but the listeners that are started to wait() later will be blocked until the next call to set().\n" ]
[ 1 ]
[]
[]
[ "gevent", "python" ]
stackoverflow_0007209842_gevent_python.txt
Q: Class Variables and Threading- An unexpected behavior I've encountered an unexpected behavior with threading. I've attached a short example below to demonstrate the behavior: from multiprocessing import Process, Lock import time class inc: def __init__(self): print "Initializing a new class" ...
Class Variables and Threading- An unexpected behavior
I've encountered an unexpected behavior with threading. I've attached a short example below to demonstrate the behavior: from multiprocessing import Process, Lock import time class inc: def __init__(self): print "Initializing a new class" self.value = 0 def add_one(self): self.value ...
[ "You are not using \"thread locking\", you are using process locking. Since processes don't share heap content, each time f gets different object.\nSee threading - Python library for operations with threads. It allows you to achieve needed behavior.\nProbably just replace \nfrom multiprocessing import Process, Lo...
[ 3 ]
[]
[]
[ "call", "class", "multithreading", "python" ]
stackoverflow_0007213051_call_class_multithreading_python.txt
Q: I don't even know what infile > outfile means. How am I supposed to use it? I don't know how to use Python, and I'm trying to use a script on a document. I have no idea how to tell it do this! If I just run the script, this is the message I get: Use: C:\Python27\hun2html.py infile > outfile Traceback (most recent...
I don't even know what infile > outfile means. How am I supposed to use it?
I don't know how to use Python, and I'm trying to use a script on a document. I have no idea how to tell it do this! If I just run the script, this is the message I get: Use: C:\Python27\hun2html.py infile > outfile Traceback (most recent call last): File "C:\Python27\hun2html.py", line 75, in <module> sys.exit(...
[ "It means that you should write the path to the file you want to use for input where infile is and the path to the file you want to store the output where outfile is. For example,\nC:\\Python27\\hun2html.py C:\\input.txt > C:\\output.txt\n\nNote that the input file is being passed as a parameter (accessed in the co...
[ 1, 0, 0 ]
[]
[]
[ "command_line", "file_io", "python", "shell" ]
stackoverflow_0007213170_command_line_file_io_python_shell.txt
Q: How can I take an integer input from user and store it to an array? How can I take an integer input from the user and store it to an array? and once stored print it. Iv tried to do it this way but I get the error: 'number' not defined My code: number = [] if __name__=="__main__": x = int(raw_input("Enter a numb...
How can I take an integer input from user and store it to an array?
How can I take an integer input from the user and store it to an array? and once stored print it. Iv tried to do it this way but I get the error: 'number' not defined My code: number = [] if __name__=="__main__": x = int(raw_input("Enter a number:")) number.append(x) print number
[ "My guess is that you have a letter case error in the real code. You define Number but print number, or vice versa. Names in Python are case sensitive.\nOr perhaps you have code in a function which tries to access number which was declared outside the function.\nWithout seeing your actual code it's hard to say and ...
[ 2, 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0007213277_arrays_python.txt
Q: subprocess stdout/stderr to finite size logfile I have a process which chats a lot to stderr, and I want to log that stuff to a file. foo 2> /tmp/foo.log Actually I'm launching it with python subprocess.Popen, but it may as well be from the shell for the purposes of this question. with open('/tmp/foo.log', 'w')...
subprocess stdout/stderr to finite size logfile
I have a process which chats a lot to stderr, and I want to log that stuff to a file. foo 2> /tmp/foo.log Actually I'm launching it with python subprocess.Popen, but it may as well be from the shell for the purposes of this question. with open('/tmp/foo.log', 'w') as stderr: foo_proc = subprocess.Popen(['foo'], st...
[ "You should be able to use the stdlib logging package to do this. Instead of connecting the subprocess' output directly to a file, you can do something like this:\nimport logging\n\nlogger = logging.getLogger('foo')\n\ndef stream_reader(stream):\n while True:\n line = stream.readline()\n logger.deb...
[ 3, 1, 1 ]
[]
[]
[ "file_io", "logging", "python", "subprocess", "unix" ]
stackoverflow_0007157234_file_io_logging_python_subprocess_unix.txt
Q: Convert binary string representation of a byte to actual binary value in Python I have a binary string representation of a byte, such as 01010101 How can I convert it to a real binary value and write it to a binary file? A: Use the int function with a base of 2 to read a binary value as an integer. n = int('010...
Convert binary string representation of a byte to actual binary value in Python
I have a binary string representation of a byte, such as 01010101 How can I convert it to a real binary value and write it to a binary file?
[ "Use the int function with a base of 2 to read a binary value as an integer.\nn = int('01010101', 2)\n\nPython 2 uses strings to handle binary data, so you would use the chr() function to convert the integer to a one-byte string.\ndata = chr(n)\n\nPython 3 handles binary and text differently, so you need to use the...
[ 12 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0007213996_binary_python.txt
Q: Why does django open with pype? when i type in the command prompt django-admin.py startproject mysite the django-admin.py will open automatically with pype, now if i type cd mysite it says the system cannot find the path specified I'm using activepython (i don't think that activepython has anything to do with it...
Why does django open with pype?
when i type in the command prompt django-admin.py startproject mysite the django-admin.py will open automatically with pype, now if i type cd mysite it says the system cannot find the path specified I'm using activepython (i don't think that activepython has anything to do with it), django installed using pypm. I can...
[ "\"but the path is incorrect i don't have an application data folder in C:\\Documents and Settings\\Administrator\\\"\nThis would mean that your Python or Django installation is corrupted (probably due to reinstall Python).\nTry go to square zero and reinstall both Python and Djangon on your computer. Also if it st...
[ 1 ]
[]
[]
[ "django", "python", "windows" ]
stackoverflow_0007206762_django_python_windows.txt
Q: Django - How to add custom error message in Form? How can I add a custom error message in a Django form? For example, I want to add a new error message in a view if two e-mails aren't the same. A: First you must define a function that begins with clean_[your field name] --- for example: def clean_email. Then wri...
Django - How to add custom error message in Form?
How can I add a custom error message in a Django form? For example, I want to add a new error message in a view if two e-mails aren't the same.
[ "First you must define a function that begins with clean_[your field name] --- for example: def clean_email. Then write your validation in your function and assign an error name and use it in error_messages of your field.\nclass ValidationForm(forms.Form):\n email = forms.EmailField(label = 'Email', error_messag...
[ 13 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0007214042_django_forms_python.txt
Q: Is it possible for a decorator to return a function with the same parameters as the wrapped function? So I'm writing a simple heap data structure for my own convienience and realized that to do it correctly, I need to check if many arguments are hashable in order for heapq operations to work correctly. import heap...
Is it possible for a decorator to return a function with the same parameters as the wrapped function?
So I'm writing a simple heap data structure for my own convienience and realized that to do it correctly, I need to check if many arguments are hashable in order for heapq operations to work correctly. import heapq def hashable(func): def hidden(self, item): try: hash(item) func(se...
[ "Why make hashable a decorator? Why not just make it a function you can invoke that will raise an exception normally, and then just invoke it in the function body, passing it the thing you want to check?\nIn fact, judging from how you wrote the decorator, isn't hash() already exactly that? Why not, instead of this:...
[ 3, 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0007212083_decorator_python.txt
Q: How to override Django LocaleMiddleware with a user preference I am using LocaleMiddleware to automatically set the language for the user. However I want the user to be able to set a preference that overrides the locale if he or she wants too It seems the Django LocaleMiddleware doesn't allow this? A: https://co...
How to override Django LocaleMiddleware with a user preference
I am using LocaleMiddleware to automatically set the language for the user. However I want the user to be able to set a preference that overrides the locale if he or she wants too It seems the Django LocaleMiddleware doesn't allow this?
[ "https://code.djangoproject.com/browser/django/trunk/django/utils/translation/trans_real.py#L366\nI see that django checks for session variable, cookie to set language.\nYou should probably set django_language = 'language_code'\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007214353_django_python.txt
Q: Save byte string to varchar column in database Below is the contents of a tuple: ('g\xba\xfc\x995m\x9a\xf0\x1d\x8b4f1\x05\xdel\xc8;\x10\xffl\xfd{\xc7MA!\x90\xe5N \xf9\x98\xf80\xe0wu\x82B\xb5\xc6\xb1T\\Px_\xfarT\x04\xd4\xe1\xfb?\x81\xa2M\x94P\ xa6\x89bM\x00\x18Q\xf7\x979\xd4V\xc5=\xc6\xff.\xf4\x857\t\xdd\xb0\xe4\xd...
Save byte string to varchar column in database
Below is the contents of a tuple: ('g\xba\xfc\x995m\x9a\xf0\x1d\x8b4f1\x05\xdel\xc8;\x10\xffl\xfd{\xc7MA!\x90\xe5N \xf9\x98\xf80\xe0wu\x82B\xb5\xc6\xb1T\\Px_\xfarT\x04\xd4\xe1\xfb?\x81\xa2M\x94P\ xa6\x89bM\x00\x18Q\xf7\x979\xd4V\xc5=\xc6\xff.\xf4\x857\t\xdd\xb0\xe4\xda\x1b8\x b6T\xfbK\x0c\xd4\xc8\x99\xd0\r\xfd\x18\xcfd...
[ "If it's an arbitrary byte string, you should use something like base64 to convert it to text:\nimport base64\nencoded = base64.b64encode(byteString)\n# Now insert \"encoded\" into the database\n\nThen:\nimport base64\n# Retrieve encoded from the database...\nbyteString = base64.b64decode(encoded)\n\nYou should not...
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007214426_django_python.txt
Q: Python Django Import Error I am newbie to django.I m using python 2.6 with django 1.3v I am trying to create a simple blog application.When I access the http://127.0.0.1:8000/admin/ I'm getting the error No module named urls.I gave this url(r'^admin/', include('django.contrib.admin.urls')) in urls.py. urls.py fr...
Python Django Import Error
I am newbie to django.I m using python 2.6 with django 1.3v I am trying to create a simple blog application.When I access the http://127.0.0.1:8000/admin/ I'm getting the error No module named urls.I gave this url(r'^admin/', include('django.contrib.admin.urls')) in urls.py. urls.py from django.conf.urls.defaults imp...
[ "Thanks.There was improper indentation.I fixed it.\n", "Did you enable django.contrib.admin in your settings.py INSTALLED_APPS tuple?\nDjango will only know of python modules (also called 'django app's in django terminology) if you have state them in the INSTALLED_APPS tuple in your django project's settings.py f...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007214434_django_django_admin_python.txt
Q: Is there nice-looking one-liner to split into variables with type casting? I use following code: x,y = line.split() x,y = float(x),float(y) Is there any way to beautify that code into one-line? A: You could use a list comprehension or generator expression. As delnan points out in the comment, map is also an agr...
Is there nice-looking one-liner to split into variables with type casting?
I use following code: x,y = line.split() x,y = float(x),float(y) Is there any way to beautify that code into one-line?
[ "You could use a list comprehension or generator expression. As delnan points out in the comment, map is also an agreeable choice in this case.\nList comprehension\nx,y = [float(x) for x in line.split()]\n\nGenerator expression\nx,y = (float(x) for x in line.split())\n\nmap\nx,y = map(float, line.split())\n\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0007214730_python.txt
Q: Pango Markup on Expander Label I have a project in Python 2.7 and PyGTK 2.24. I have the following code in my project: expTSet = gtk.Expander() expTSet.set_use_markup(True) expTSet.set_label('<span font_family="serif" size="18" weight="bold">Teacher Settings</span>') settingFixed.put(expTSet, 30, 2...
Pango Markup on Expander Label
I have a project in Python 2.7 and PyGTK 2.24. I have the following code in my project: expTSet = gtk.Expander() expTSet.set_use_markup(True) expTSet.set_label('<span font_family="serif" size="18" weight="bold">Teacher Settings</span>') settingFixed.put(expTSet, 30, 200) expTSet.show() The expander...
[ "Pango font sizes are not in points (like HTML/CSS), but rather thousandths of points. So size=\"18\" means your font size is 0.018 points, which is too small to read. Change it to size=\"18000\" and it will work as intended.\n" ]
[ 2 ]
[]
[]
[ "pango", "pygtk", "python" ]
stackoverflow_0007213179_pango_pygtk_python.txt
Q: how can I lock entire class I have the following pseudo code: class A: mutex lockForB class B: def __init__(self, A): //the type of A is class A lock(A.lockForB) # ... unlock(A.lockForB) # other function have the same locking I understand from oop point of view it is very bad...
how can I lock entire class
I have the following pseudo code: class A: mutex lockForB class B: def __init__(self, A): //the type of A is class A lock(A.lockForB) # ... unlock(A.lockForB) # other function have the same locking I understand from oop point of view it is very bad idea to use such design, but if ...
[ "I have no idea what you're trying to accomplish. It's unlikely that a class level lock is what you want but your pseudocode is not so far from the actual code so I'll just fill in the blanks. Honestly, without some idea what you're attempting to synchronize access to it's going to be a challenge to help you.\ncl...
[ 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0007214886_oop_python.txt
Q: Python create/import custom module in same directory I'm trying to create a simple python script and import a couple of custom classes. I'd like to do this as one module. Here is what I have: point/point.py class Point: """etc.""" point/pointlist.py class PointList: """etc.""" point/__init__.py from . im...
Python create/import custom module in same directory
I'm trying to create a simple python script and import a couple of custom classes. I'd like to do this as one module. Here is what I have: point/point.py class Point: """etc.""" point/pointlist.py class PointList: """etc.""" point/__init__.py from . import point, pointlist script.py import sys, point verbose...
[ "Sorry, I seem to have made a blunder in my earlier answer and comments:\nThe problem here is that you should access the objects in point through the module you import:\npoint/__init__.py:\nfrom point import Point\nfrom pointlist import PointList\n\nscript.py:\nimport sys, point\nverbose = False\npointlist = point....
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0007215320_python.txt
Q: Google App Engine python, GQL, select only one column from datastore Im trying to pull only one column from a datastore table I have a Books model with id, key, title, author, isbn and price everything = db.GqlQuery('SELECT * FROM Books') gives me everything, but say i only want the title books = db.GqlQuery('SELE...
Google App Engine python, GQL, select only one column from datastore
Im trying to pull only one column from a datastore table I have a Books model with id, key, title, author, isbn and price everything = db.GqlQuery('SELECT * FROM Books') gives me everything, but say i only want the title books = db.GqlQuery('SELECT title FROM Books') Ive tried everything people have suggested but nothi...
[ "You can't. GQL is not SQL, and the datastore is not a relational database. An entity is stored as a single serialized protocol buffer, and it's impossible to fetch part of an entity; the whole thing needs to be deserialized.\n", "A design consideration in the datastore is to use redundancy where you wouldn't in ...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python" ]
stackoverflow_0007213991_google_app_engine_gql_gqlquery_python.txt
Q: python socket hangs on connect I'm trying to make a transparent proxy in python using the socket module. but for some reason it hangs on connect()ing the socket. here is the code i'm using: from __future__ import division import socket import struct #import mcpackets import sys import time #CUSTOM SETTINGS HOST="1...
python socket hangs on connect
I'm trying to make a transparent proxy in python using the socket module. but for some reason it hangs on connect()ing the socket. here is the code i'm using: from __future__ import division import socket import struct #import mcpackets import sys import time #CUSTOM SETTINGS HOST="192.168.178.28" PORT=25565 #END CUSTO...
[ "This is a part of TCP sockets implementation where the operating system refuses to allow a new socket connection after a socket with the same name has been disconnected recently.\nIn order to force this request, set the REUSEADDR socket option on your socket, before connecting it (for both of your server socket cr...
[ 6, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0007214553_python_sockets.txt
Q: Why MongoDB does not recognize my user on Celery connection? I have a Python/Flask webapp with MongoDB database on DotCloud hosting. I would like to set up Celery on the Python service using the MongoDB service as the Celery queue. Celery starts and it finds my celeryconfig.py file, which contains: BROKER_BACKEND ...
Why MongoDB does not recognize my user on Celery connection?
I have a Python/Flask webapp with MongoDB database on DotCloud hosting. I would like to set up Celery on the Python service using the MongoDB service as the Celery queue. Celery starts and it finds my celeryconfig.py file, which contains: BROKER_BACKEND = "mongodb" BROKER_HOST = "data.myapp.dotcloud.com" BROKER_PORT = ...
[ "Finally I learnt that \"kombu_default\" (in the MongoDB logs) was the database used for message queue by Celery.\nSo, to get Celery + MongoDB working, I only add the parameter BROKER_VHOST = \"celery\" to the celeryconfig.py file.\n" ]
[ 2 ]
[]
[]
[ "celery", "dotcloud", "mongodb", "pymongo", "python" ]
stackoverflow_0007207435_celery_dotcloud_mongodb_pymongo_python.txt
Q: Pygtk TextView setting cursor at the beginning I have a gtk.TextView() and every time the user puts text in it and hit return I want to print the text in the terminal and erase everything in the text area and so, put the cursor at the beginning of the textview. I tried to : self.textbuffer.set_text("") or : start...
Pygtk TextView setting cursor at the beginning
I have a gtk.TextView() and every time the user puts text in it and hit return I want to print the text in the terminal and erase everything in the text area and so, put the cursor at the beginning of the textview. I tried to : self.textbuffer.set_text("") or : start, end = self.textbuffer.get_bounds() self.textbuffer...
[ "Here is what is happening:\nThe user presses the enter key and your code is being run. The widget then takes over again and does what it always does when Return is pressed, which is to move the cursor to the next line.\nBut if you bind your command to the key release event,\nself.textview.connect(\"key_release_eve...
[ 3 ]
[]
[]
[ "cursor_position", "pygtk", "python", "textview" ]
stackoverflow_0007209176_cursor_position_pygtk_python_textview.txt
Q: Giving my Python application a web interface to monitor it, using Tornado I've got a Python application which is daemonized and running on a server 24/7. I'd like to be able to give an incredibly simple web interface so that I can monitor the changing values of a few variables within the program. I'm using Tornad...
Giving my Python application a web interface to monitor it, using Tornado
I've got a Python application which is daemonized and running on a server 24/7. I'd like to be able to give an incredibly simple web interface so that I can monitor the changing values of a few variables within the program. I'm using Tornado, and I'm up and running with the simple 'Hello, world' that you can find on t...
[ "Is it possible to use the threading package and run Tornado inside of its own thread?\nEdit:\nThe threading module documentation at http://docs.python.org/library/threading.html has more details, but I am imagining something like this:\nimport threading\nt = threading.Thread(target = tornado.ioloop.IOLoop.instance...
[ 4, 2, 0, 0 ]
[]
[]
[ "daemon", "multithreading", "python", "tornado" ]
stackoverflow_0004043129_daemon_multithreading_python_tornado.txt
Q: Windows 7 MARGINS structure in Python I'm attempting to get some of the more interesting Windows Aero effects working in Python. The DwmExtendFrameIntoClientArea function can be used to extend the Aero glass into the client area. It requires a Window handle and a pointer to a MARGINS structure. I already know how...
Windows 7 MARGINS structure in Python
I'm attempting to get some of the more interesting Windows Aero effects working in Python. The DwmExtendFrameIntoClientArea function can be used to extend the Aero glass into the client area. It requires a Window handle and a pointer to a MARGINS structure. I already know how to get a window's handle in Python; howeve...
[ "I do not have Win7 running to test this but try defining the struct with ctypes:\nclass MARGINS(ctypes.Structure):\n _fields_ = [(\"cxLeftWidth\", c_int),\n (\"cxRightWidth\", c_int),\n (\"cyTopHeight\", c_int),\n (\"cyBottomHeight\", c_int)\n ]\nmargins = MARGIN...
[ 4 ]
[]
[]
[ "aero", "margins", "python", "pywin32", "windows_7" ]
stackoverflow_0007197327_aero_margins_python_pywin32_windows_7.txt
Q: Python and tfidf algorithm, make it faster? I am implementing the tf-idf algorithm in a web application using Python, however it runs extremely slow. What I basically do is: 1) Create 2 dictionaries: First dictionary: key (document id), value (list of all found words (incl. repeated) in doc) Second dictionary; ...
Python and tfidf algorithm, make it faster?
I am implementing the tf-idf algorithm in a web application using Python, however it runs extremely slow. What I basically do is: 1) Create 2 dictionaries: First dictionary: key (document id), value (list of all found words (incl. repeated) in doc) Second dictionary; key (document id), value (set containing unique w...
[ "Well, you have to re-think and re-design somehow the way you hold your data, or in other words, implement an \"orthodox\" version of your \"inverted index\".\nYour bottleneck is the \"on-the-fly\" calculation of the document frequency (DF) for the terms. It would be a clever idea for this to be dynamic, so every t...
[ 5, 3 ]
[]
[]
[ "dictionary", "python", "tf_idf" ]
stackoverflow_0007215850_dictionary_python_tf_idf.txt
Q: Django Development Server Question I noticed that when I am developing a Django App in debug mode, I sometimes see this output on my server stdout: Traceback (most recent call last): File "/Users/josephmisiti/projects/temp/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 284, in run self.fi...
Django Development Server Question
I noticed that when I am developing a Django App in debug mode, I sometimes see this output on my server stdout: Traceback (most recent call last): File "/Users/josephmisiti/projects/temp/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 284, in run self.finish_response() File "/Users/josephmis...
[ "The browser closed the socket connection before the server could finish sending the response (e.g. you closed the tab before it loaded all the way). Don't worry about it. \n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007215973_django_python.txt
Q: Is it possible create instance of derived type from instance of base class Some thing like this: class Reference (object): pass new_type = type ('{0}_refrence'.format (type (instance).__name__), (type (instance), Reference), {}) new_instance = new_type (instance) I want to make instance to be derived from...
Is it possible create instance of derived type from instance of base class
Some thing like this: class Reference (object): pass new_type = type ('{0}_refrence'.format (type (instance).__name__), (type (instance), Reference), {}) new_instance = new_type (instance) I want to make instance to be derived from Refrence but behave as usual... Is it possible? Thx in advance!
[ "If I understood what you want to do...\nclass Reference(object): pass\n\ninstance = 2\nnew_type = type('{0}_reference'.format(instance.__class__.__name__), (instance.__class__, Reference), {})\nnew_instance = new_type(instance)\n\nHope this helps.\n" ]
[ 0 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0007215673_metaclass_python.txt
Q: Randomly NoneType object is not callable error Recently I've got this problem in my application: File "main.py", line 31, in File "app.pyc", line 205, in run TypeError: 'NoneType' object is not callable" My code: xml = EXML() for pid, product in store.products.items(): xml.addRow() xml.addCell((prod...
Randomly NoneType object is not callable error
Recently I've got this problem in my application: File "main.py", line 31, in File "app.pyc", line 205, in run TypeError: 'NoneType' object is not callable" My code: xml = EXML() for pid, product in store.products.items(): xml.addRow() xml.addCell((product['name']).encode('utf-8'), "String") xml.addC...
[ ">>> None.encode\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'NoneType' object has no attribute 'encode'\n>>> None()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'NoneType' object is not callable\n\nOn the given line you w...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007213254_python.txt
Q: Use variables when saving objects in Django In Django, is there a way to identify which attribute of an object I want to edit by using a POST/GET variable instead of explicitly naming it? For example, I want to do this: def edit_user_profile(request): field_to_edit = request.POST.get('id') value = request....
Use variables when saving objects in Django
In Django, is there a way to identify which attribute of an object I want to edit by using a POST/GET variable instead of explicitly naming it? For example, I want to do this: def edit_user_profile(request): field_to_edit = request.POST.get('id') value = request.POST.get('value') user = User.objects.get(pk=...
[ "Gabi's answer is exactly what you want. You could use setattr instead though:\nsetattr(user, field_to_edit, strip_tags(value))\n\nWhich is (very very slightly!) more intuitive.\n", "You can use the getattr function:\ngetattr(user, field_to_edit) = strip_tags(value)\n\n" ]
[ 3, 0 ]
[]
[]
[ "django", "python", "variables" ]
stackoverflow_0007216259_django_python_variables.txt
Q: Redirecting pages in Django with regular expressions? I am working on a very Ajax-heavy site that uses History.js, which basically ports HTML5's pushState and replaceState to HTML4. Anyways, in HTML4 browsers, the pseudo-url is added after the hash tag in an url. I want to redirect any requests to any page with a ...
Redirecting pages in Django with regular expressions?
I am working on a very Ajax-heavy site that uses History.js, which basically ports HTML5's pushState and replaceState to HTML4. Anyways, in HTML4 browsers, the pseudo-url is added after the hash tag in an url. I want to redirect any requests to any page with a hash in the url to the url after the hash. For example, a u...
[ "Django doesn't have access to whatever is after the hashtag. This is by design (HTTP Protocol). The only way to do it, is to have javascript on the page that looks for hashtags, and redirects as needed.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007216323_django_python.txt
Q: Howto selenium testing infratstructure with python? Any suggestions on how to setup a selenium testing environment using python. I know question is vague but for being the standard for web front end testing selenium does not want to seem to work, a useful tutorial would be fine. My current dev environment is setup...
Howto selenium testing infratstructure with python?
Any suggestions on how to setup a selenium testing environment using python. I know question is vague but for being the standard for web front end testing selenium does not want to seem to work, a useful tutorial would be fine. My current dev environment is setup like this: Checked out code: /home/workspace/trunk Pyt...
[ "Assuming your using Selenium 2 (AKA webdriver), and you should because it's awesome, it will create a new, temporary, profile for you and install the extension is uses to drive the browser. So just write your test suite and create your driver instance in your test and use it.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_rc" ]
stackoverflow_0007183397_python_selenium_selenium_rc.txt
Q: Problem with file concatenation in Python? I have 3 files 1.txt, 2.txt, and 3.txt and I am trying to concatenate together the contents of these files into one output file in Python. Can anyone explain why the code below only writes the content of 1.txt and not 2.txt or 3.txt? I'm sure it's something really simple,...
Problem with file concatenation in Python?
I have 3 files 1.txt, 2.txt, and 3.txt and I am trying to concatenate together the contents of these files into one output file in Python. Can anyone explain why the code below only writes the content of 1.txt and not 2.txt or 3.txt? I'm sure it's something really simple, but I can't seem to figure out the problem. imp...
[ "you constantly overwrite the same file.\neither use:\nwith open('concat_file.txt', \"a\")\n\nor\nwith open('concat_file.txt', \"w\") as concat_file:\n for my_file in glob.iglob('/Users/me/Desktop/*.txt'):\n shutil.copyfileobj(open(my_file, \"r\"), concat_file)\n\n", "I believe that what's wrong with yo...
[ 4, 0 ]
[]
[]
[ "concatenation", "file_io", "python", "shutil" ]
stackoverflow_0007216968_concatenation_file_io_python_shutil.txt
Q: What's the best way to pipeline assets to a CDN with Django? When it comes time to deploy, one best practice is compressing static assets (js, css), and moving them to a CDN. There are a few Django apps that handle some aspects (django-compressor, django-pipeline each come to mind), but they each have their own pr...
What's the best way to pipeline assets to a CDN with Django?
When it comes time to deploy, one best practice is compressing static assets (js, css), and moving them to a CDN. There are a few Django apps that handle some aspects (django-compressor, django-pipeline each come to mind), but they each have their own problems. For example, django-compressor wants to generate content ...
[ "django-pipeline 1.1.12 is now caching hash, so you should be fine, see the changelog.\nDisclaimer: I'm one of the author of django-pipeline.\n", "Are you running Django 1.3? If so, then you can write your own custom file storage backend that uploads things to a CDN. Luckily, if you want to use Amazon S3, then dj...
[ 6, 1 ]
[]
[]
[ "cdn", "deployment", "django", "python" ]
stackoverflow_0007142989_cdn_deployment_django_python.txt
Q: Trying to build a Python class in a C extension that can be instantiated from a Python module I'm trying to build an exception class that I can use both in a C extension and the Python modules that import the extension. I'm using the PyErr_NewException to create the class as a superclass of the Exception class, b...
Trying to build a Python class in a C extension that can be instantiated from a Python module
I'm trying to build an exception class that I can use both in a C extension and the Python modules that import the extension. I'm using the PyErr_NewException to create the class as a superclass of the Exception class, but I can't figure out how to create an __init__ constructor for the class. I assume that is the be...
[ "You should pass a dict as the third argument to PyErr_NewException. The dict should have an __init__ key bound to your initializer function.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007216925_python.txt
Q: Python - delete old files I'm somewhat new to python and have been trying to figure this out on my own but only getting bits and pieces so far. Basically i'm looking for a script that will recursively search a directory and it's sub-directories and delete files that are at least 24 hours old but not alter the dir...
Python - delete old files
I'm somewhat new to python and have been trying to figure this out on my own but only getting bits and pieces so far. Basically i'm looking for a script that will recursively search a directory and it's sub-directories and delete files that are at least 24 hours old but not alter the directories. Any advice or example...
[ "This uses the os.walk method to recursively search a directory. For each file, it checks the modified date with os.path.getmtime and compares that with datetime.now (the current time). datetime.timedelta is constructed to create a timedelta of 24 hours.\nIt searches the directory os.path.curdir which is the curren...
[ 38, 7 ]
[]
[]
[ "python" ]
stackoverflow_0007217196_python.txt
Q: Python GIL and threads synchronization After having read various articles that explain GIS and threads in Python, and Are locks unnecessary in multi-threaded Python code because of the GIL? which is a very useful answer, I have one "last question". If, ideally, my threads only operate on shared data through atomic...
Python GIL and threads synchronization
After having read various articles that explain GIS and threads in Python, and Are locks unnecessary in multi-threaded Python code because of the GIL? which is a very useful answer, I have one "last question". If, ideally, my threads only operate on shared data through atomic (Python VM) instructions, e.g. appending an...
[ "That really depends on your application. You may need locks for your specific use case just like in any other language, but you don't need to protect the python objects getting corrupted anyway. In that sense you don't need locks.\nHere's an example that uses a bunch of pretty much atomic operations, but can sti...
[ 2, 0, 0, 0 ]
[]
[]
[ "gil", "multithreading", "python" ]
stackoverflow_0007098900_gil_multithreading_python.txt
Q: How to submit different scripts to the command line in python - I'm trying to loop through and submit shell scripts to the command line in python. While this works for a given file: os.system('qsub /directory/filename') This does not: file = '/directory/filename' os.system('qsub file') Python is interpreting th...
How to submit different scripts to the command line in python -
I'm trying to loop through and submit shell scripts to the command line in python. While this works for a given file: os.system('qsub /directory/filename') This does not: file = '/directory/filename' os.system('qsub file') Python is interpreting the word 'file' instead of the object file. How can I get around this?...
[ "Try this:\nfile = '/directory/filename'\nos.system('qsub %s' % file)\n\nYou have to pass 'file' as an argument. \nSee http://diveintopython.net/native_data_types/formatting_strings.html for some examples or http://docs.python.org/library/stdtypes.html#string-formatting for the official docs.\n" ]
[ 2 ]
[ "'qsub file' is a string use 'qsub ' + file\n", "Use:\nos.system('qsub %s' % file)\n\n" ]
[ -1, -1 ]
[ "command_line", "python", "shell" ]
stackoverflow_0007217413_command_line_python_shell.txt
Q: How can I mask elements of a record array in Numpy? I understand how to create a masked array, and I would like to use masking in a record array so that I can access this data using named attributes. The masking seems to be "lost" when I create a record array from a masked array: >>> data = np.ma.array(np.ma.zero...
How can I mask elements of a record array in Numpy?
I understand how to create a masked array, and I would like to use masking in a record array so that I can access this data using named attributes. The masking seems to be "lost" when I create a record array from a masked array: >>> data = np.ma.array(np.ma.zeros(30, dtype=[('date', '|O4'), ('price', '<f8')]),mask=[i<...
[ "I haven't found much documentation on numpy.ma.mrecords.MaskedRecords, except for a brief mention here. You can find some examples on how to use it by studying the unit tests that come with numpy. (e.g. \n/usr/lib/python2.6/dist-packages/numpy/ma/tests/test_mrecords.py).\nimport numpy as np\nimport numpy.ma.mrecor...
[ 4 ]
[]
[]
[ "masked_array", "numpy", "python", "structured_array" ]
stackoverflow_0007217606_masked_array_numpy_python_structured_array.txt
Q: Django way to do conditional formatting What is the correct way to do conditional formatting in Django? I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be ...
Django way to do conditional formatting
What is the correct way to do conditional formatting in Django? I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want g...
[ "I'm a big fan of putting ALL \"business\" logic in the view function and ALL presentation in the templates/CSS.\nOption 1 is ideal. You return a list of pairs: ( date, state ), where the state is the class name (\"past\", \"present\", \"future\").\nYour template then uses the state information as the class for a ...
[ 8, 4, 2, 0 ]
[]
[]
[ "django", "django_templates", "formatting", "python" ]
stackoverflow_0001068573_django_django_templates_formatting_python.txt
Q: Database to store arrays of integers and bitset in I am building a small image search engine that uses image descriptors that are both binary numbers and integer valued (numpy) arrays which are both the 'keys' which should both form the basis for an inverted file like approach. The value is simply the image name/i...
Database to store arrays of integers and bitset in
I am building a small image search engine that uses image descriptors that are both binary numbers and integer valued (numpy) arrays which are both the 'keys' which should both form the basis for an inverted file like approach. The value is simply the image name/identifier they originated from. I am looking for a data...
[ "Arrays in Python are instances of the class array\nIf you mean \"list\", use preferably the term 'list'\nIf I understand correctly, you use a data structure having integers as keys, and binary numbers as values: in Python it's a dictionary\nIf you want to record this data structure in a file, use the module cPickl...
[ 2 ]
[]
[]
[ "arrays", "database", "python" ]
stackoverflow_0007217956_arrays_database_python.txt
Q: AppEngine Initial Datastore I have a python application that I've been running with the devserver and everything seems to work fine except I am having problems initializing my datastore. Basically I need to set up data store values from a bunch of files that are on my local drive, but I don't want to upload go goo...
AppEngine Initial Datastore
I have a python application that I've been running with the devserver and everything seems to work fine except I am having problems initializing my datastore. Basically I need to set up data store values from a bunch of files that are on my local drive, but I don't want to upload go google. I set up a simple python scr...
[ "Download the data using appcfg.py (after enabling the remote_api), then re-'upload' it to local devappserver.\nhttp://blog.mfabrik.com/2011/03/14/mirroring-app-engine-production-data-to-development-server-using-appcfg-py/\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007217658_google_app_engine_python.txt
Q: Handling memory usage for big calculation in python I am trying to do some calculations with python, where I ran out of memory. Therefore, I want to read/write a file in order to free memory. I need a something like a very big list object, so I thought writing a line for each object in the file and read/write to t...
Handling memory usage for big calculation in python
I am trying to do some calculations with python, where I ran out of memory. Therefore, I want to read/write a file in order to free memory. I need a something like a very big list object, so I thought writing a line for each object in the file and read/write to that lines instead of to memory. Line ordering is importan...
[ "You want to find the largest prime divisor of a. (Project Euler Question 3)\nYour current choice of algorithm and implementation do this by:\n\nGenerate a list numbers of all candidate primes in range (3 <= n <= sqrt(a), or (a+1)/2 as you currently do)\nSieve the numbers list to get a list of primes {p} <= sqrt(a)...
[ 2, 0, 0, 0 ]
[]
[]
[ "prime_factoring", "python", "sieve_of_eratosthenes", "stack_overflow" ]
stackoverflow_0007216845_prime_factoring_python_sieve_of_eratosthenes_stack_overflow.txt
Q: Python wrapper for the amazon product api Possible Duplicate: Amazon API library for Python? I was wondering if there are any python wrappers out there for the amazon product api with good documentation? Thanks A: Relatively lightweight and still under development is python-amazon-product-api. As far as know t...
Python wrapper for the amazon product api
Possible Duplicate: Amazon API library for Python? I was wondering if there are any python wrappers out there for the amazon product api with good documentation? Thanks
[ "Relatively lightweight and still under development is python-amazon-product-api.\nAs far as know this API is fully functional. Its documentation for example the operations page is also rather light, but adequate given the intuitive interface. \n" ]
[ 0 ]
[ "I like bottlenose (in PyPi and on github).\n" ]
[ -1 ]
[ "amazon_product_api", "amazon_web_services", "python" ]
stackoverflow_0005615773_amazon_product_api_amazon_web_services_python.txt
Q: problems ... BeautifulSoup Parsing <h2 class="sectionTitle">BACKGROUND</h2> Mr. Paul J. Fribourg has bla bla</span> <div style="margin-top:8px;"> <a href="javascript:void(0)" onclick="show_more(this);">Read Full Background</a> </div> I would like to extract information from Mr. Paul to blabla Some webpage has...
problems ... BeautifulSoup Parsing
<h2 class="sectionTitle">BACKGROUND</h2> Mr. Paul J. Fribourg has bla bla</span> <div style="margin-top:8px;"> <a href="javascript:void(0)" onclick="show_more(this);">Read Full Background</a> </div> I would like to extract information from Mr. Paul to blabla Some webpage has <p> infront of Mr. Paul, so I could use...
[ "It's hard to tell from the example you have given us, but it looks to me that you could just get the next node after an h2. In this example, Lewis Carroll has a p-aragraph tag and your friend Paul has only a closing span tag:\n>>> from BeautifulSoup import BeautifulSoup\n>>>\n>>> html = '''\n... <h2 class=\"sectio...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007218084_beautifulsoup_python.txt
Q: Beautiful Soup adding quotations of HTML attributes Thanks in advance, I'm currently using beautiful soup to parse comment tags out of a set block of HTML. The issue I'm having is the html that is scraped has no quotations encapsulating the attribute values of the HTML tags. However BeautifulSoup seems to add thes...
Beautiful Soup adding quotations of HTML attributes
Thanks in advance, I'm currently using beautiful soup to parse comment tags out of a set block of HTML. The issue I'm having is the html that is scraped has no quotations encapsulating the attribute values of the HTML tags. However BeautifulSoup seems to add these in, which in some case may be desirable but unfortunate...
[ "You have a tag where some attribute values are quoted and some unquoted. What do you mean by 'add quoting back': either edit each attribute value to kludge the quotes in (probably a terrible idea), or else add quoting when it renders. It depends on what other processing you're doing to the tag. Here's code to add...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007200623_beautifulsoup_python.txt
Q: How to use LoopingCall with threads? I have a simple example: from twisted.internet import utils, reactor from twisted.internet import defer from twisted.internet import threads from twisted.internet.task import LoopingCall,deferLater import time def test1(): print 'test' def test2(res): l = [] ...
How to use LoopingCall with threads?
I have a simple example: from twisted.internet import utils, reactor from twisted.internet import defer from twisted.internet import threads from twisted.internet.task import LoopingCall,deferLater import time def test1(): print 'test' def test2(res): l = [] for i in xrange(3): l.append(t...
[ "LoopingCall will run the callable you pass to it every N seconds, where N is the number you pass to start. It doesn't wait N seconds after the previous call finishes, it waits N seconds after the previous call started. In other words, it tries to stay on the interval defined by N and the starting time, running a...
[ 5 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007218108_python_twisted.txt
Q: How to split python script in parts and to import the parts in a loop? First, sorry for my stupid title :) And here is my problem.. Actually it's not a problem. Everything works, but I want to have better structure... I have a python script with a loop "looped" each second. In the loop there are many many IFs. Is ...
How to split python script in parts and to import the parts in a loop?
First, sorry for my stupid title :) And here is my problem.. Actually it's not a problem. Everything works, but I want to have better structure... I have a python script with a loop "looped" each second. In the loop there are many many IFs. Is it possible to put each IF in a separate file and then to include it in the ...
[ "perhaps you wonder how to work with your own modules in general.\nmake one file named 'weather.py' and have it contain the appropriate if-statements like:\n\"\"\" weather.py - conditions to check \"\"\"\n\ndef check_all(*args, **kwargs):\n \"\"\" check all conditions \"\"\"\n if check_temperature(kwargs['tem...
[ 6, 4, 1, 1, 0, 0 ]
[]
[]
[ "import", "include", "loops", "python" ]
stackoverflow_0007216993_import_include_loops_python.txt
Q: Threadsafe printing across multiple processes python 2.x I have experienced a very weird issue that I just can't explain when dealing with printing to a file from multiple processes (started with the subprocess module). The behavior I am seeing is that some of my output is slightly truncated and some of it is jus...
Threadsafe printing across multiple processes python 2.x
I have experienced a very weird issue that I just can't explain when dealing with printing to a file from multiple processes (started with the subprocess module). The behavior I am seeing is that some of my output is slightly truncated and some of it is just completely missing. I am using a slightly modified version ...
[ "In each process you create a ThreadSafeFile for sys.stdout, each of which has a lock, but they're different locks; there's nothing connecting the locks used in all the different processes. So you're getting the same effect as if you used no locks at all; no process is ever going to be blocked by a lock held in ano...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007217715_multithreading_python.txt
Q: How to propagate tree nodes in Python I am dealing with a tree structure in a Python program. Each node in a tree has a dictionary "sons", whose keys hold arc information, and values are the son nodes. The question is to propagate a list of nodes to all their sons. I use: current_nodes = reduce(lambda s,x:s+x, map...
How to propagate tree nodes in Python
I am dealing with a tree structure in a Python program. Each node in a tree has a dictionary "sons", whose keys hold arc information, and values are the son nodes. The question is to propagate a list of nodes to all their sons. I use: current_nodes = reduce(lambda s,x:s+x, map(lambda node:node.sons.values(),current_nod...
[ "from itertools import chain\nlist(chain.from_iterable(node.sons.values() for node in current_nodes))\n\nShould be faster. map and reduce on lambdas are slow. I don't know how fast chain is; you could try\nsum((node.sons.values() for node in current_nodes), [])\n\nas well.\n" ]
[ 4 ]
[]
[]
[ "python", "reduce", "tree" ]
stackoverflow_0007218809_python_reduce_tree.txt
Q: Rendering an iCal .ics file using Django: fixing incorrect newlines I'm using Django's render_to_response to create an .ics file on the fly for people to download. The raw content of this .ics file is fine, and validates when I use this tool. However, when I upload the file that is generated, I get this error: Yo...
Rendering an iCal .ics file using Django: fixing incorrect newlines
I'm using Django's render_to_response to create an .ics file on the fly for people to download. The raw content of this .ics file is fine, and validates when I use this tool. However, when I upload the file that is generated, I get this error: Your calendar is using an invalid newline format. Make sure to use \r\n to ...
[ "render_to_response is a shortcut for Template.render(Context). If you called Template.render yourself, it would return a string. So you could then call string.replace('\\n', '\\r\\n'). \n" ]
[ 1 ]
[]
[]
[ "django", "icalendar", "python" ]
stackoverflow_0007177865_django_icalendar_python.txt
Q: Telling __import__ where to look - am I stuck with sys.path? I have a project in pure Python with a rudimentary plugin system: you write a module that defines a class with a specific interface and name, and the program imports the module and subsequently instantiates the class as needed. Currently, the plugins all...
Telling __import__ where to look - am I stuck with sys.path?
I have a project in pure Python with a rudimentary plugin system: you write a module that defines a class with a specific interface and name, and the program imports the module and subsequently instantiates the class as needed. Currently, the plugins all come from a specific folder (subdirectory of where the main .py f...
[ "This might seem weird, but you can modify a module's __path__ variable and then import from it. Then you're not messing with the global import space in sys.path. \nEdit: If the directories are loaded at run time, then you don't need a plugins.py file to store them. You can create the module dynamically:\nmain.py:\...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007218673_python.txt
Q: Two python scripts behave differently when use different name for a user defined class I am learning python. I encounter a strange problem. I create a class named "test" with several member functions and all is fine. However, when I substitute the class name to "test1", it goes wrong. I used vimdiff, diff and beyo...
Two python scripts behave differently when use different name for a user defined class
I am learning python. I encounter a strange problem. I create a class named "test" with several member functions and all is fine. However, when I substitute the class name to "test1", it goes wrong. I used vimdiff, diff and beyond compare to verify the two files, and see only the class name is different. Here is the fi...
[ "This seems to have something to do with the order in which objects are destroyed at the end of the Python program. For some reason test gets deleted after ada and ywenlong, but test1 gets deleted before them. Why? I have no clue.\nYou can test out the arbitrariness of the deletion order with this program:\nclass t...
[ 1, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007218795_class_python.txt
Q: storing computed function to disk for fast access in python There are two parts to my question. One: I have to do a double integration on a grid answer = integrate ( f(x,y) times besselfunction(x,y)) Now, I have read that the besselfunction can be precomputed and saved to disk for fast access. How do I do this? ...
storing computed function to disk for fast access in python
There are two parts to my question. One: I have to do a double integration on a grid answer = integrate ( f(x,y) times besselfunction(x,y)) Now, I have read that the besselfunction can be precomputed and saved to disk for fast access. How do I do this? Right now, I am evaluating the besselfunction from scipy.special ...
[ "You seem to be looking for an on-disk memoization solution.\nYou could probably make a memoization decorator that uses berkeleydb to store the results of all function calls computed so far onto disk (if you can carry the resulting berkeleydb file around to every machine you run your program on and don't mind it be...
[ 0 ]
[]
[]
[ "python", "scipy", "spline" ]
stackoverflow_0007218869_python_scipy_spline.txt
Q: Python, loop through lines in a file; if line equals line in another file, return original line Text file 1 has the following format: 'WORD': 1 'MULTIPLE WORDS': 1 'WORD': 2 etc. I.e., a word separated by a colon followed by a number. Text file 2 has the following format: 'WORD' 'WORD' etc. I need to extract s...
Python, loop through lines in a file; if line equals line in another file, return original line
Text file 1 has the following format: 'WORD': 1 'MULTIPLE WORDS': 1 'WORD': 2 etc. I.e., a word separated by a colon followed by a number. Text file 2 has the following format: 'WORD' 'WORD' etc. I need to extract single words (i.e., only WORD not MULTIPLE WORDS) from File 1 and, if they match a word in File 2, ret...
[ "If file2 is not humongous, slurp them into a set:\nfile2=set(open(\"file2\").read().split())\nfor line in open(\"file1\"):\n if line.split(\":\")[0].strip(\"'\") in file2:\n print line\n\n", "I guess by \"poorly functioning\" you mean speed wise? Because I tested and it does appear to work.\nYou could ...
[ 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "text_processing" ]
stackoverflow_0007218643_python_regex_text_processing.txt
Q: Trouble using pyopengl in Python 2.6.6 What I'm trying to do is code a basic OpenGL 2.0 window, when I run the code from a file, it works for the first couple of runs, then it dumps errors. If I run the same exact code from the IDLE GUI, I get a window every time. The following is first a list of added Python 2.6...
Trouble using pyopengl in Python 2.6.6
What I'm trying to do is code a basic OpenGL 2.0 window, when I run the code from a file, it works for the first couple of runs, then it dumps errors. If I run the same exact code from the IDLE GUI, I get a window every time. The following is first a list of added Python 2.6.6 packages, the code and the errors. Am I u...
[ "The numpy Cython extension for OpenGL was probably built with numpy 1.3.x. So either you recompile OpenGL (especially the Cython extension) with your new numpy version or you downgrade numpy to 1.3.x. (if this does not help try to downgrade to 1.4.x and 1.5.x as well - as I do not exactly know what changed in what...
[ 0, 0 ]
[]
[]
[ "error_handling", "pyopengl", "python", "python_2.x" ]
stackoverflow_0007006040_error_handling_pyopengl_python_python_2.x.txt