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: What is the difference between how dictionary and list datastructures appear in memory? For instance, if I was to create the following code: a_list = ['this', 'is', 'a', 'sentence'] a_dict = { 0: 'this', 1 : 'is', 2 : 'a', 3 : 'sentence'} then typing in the command prompt >a_list[0] yields >'this' as does >a_di...
What is the difference between how dictionary and list datastructures appear in memory?
For instance, if I was to create the following code: a_list = ['this', 'is', 'a', 'sentence'] a_dict = { 0: 'this', 1 : 'is', 2 : 'a', 3 : 'sentence'} then typing in the command prompt >a_list[0] yields >'this' as does >a_dict[0] yield >'this' Is there anything wrong with saying that a list is a type of dictionary...
[ "Python dictionaries are not limited to integers as keys - anything that's hashable can be keys - strings, tuples, etc. In fact, using integer keys in Python dicts is far from being the most common use.\nPython lists can be viewed as simple dynamic arrays (similar to C++'s std::vector). On the other hand, dicts are...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005788340_python.txt
Q: Reading a CSV file using Python please tell me what's the problem in this code it's giving an error import csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row A: Which version of Python are you using? The with statement is new in 2.6 - if you're using 2.5 yo...
Reading a CSV file using Python
please tell me what's the problem in this code it's giving an error import csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row
[ "Which version of Python are you using?\nThe with statement is new in 2.6 - if you're using 2.5 you need from __future__ import with_statement. If you use a Python older than 2.5 then there's no with statement, so just write:\nimport csv\nf = open('some.csv', 'rb')\nreader = csv.reader(f)\nfor row in reader:\n p...
[ 18, 6 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005788521_csv_python.txt
Q: Python - How do i know when a form button was pressed? (logout) I'm trying to make a logout button for my website in python CGI. I was wondering how would I know when the button was pressed? My logout form is as follows: <form id="logout" method="POST" action=""> <input type="submit" name="logout" value="Logout...
Python - How do i know when a form button was pressed? (logout)
I'm trying to make a logout button for my website in python CGI. I was wondering how would I know when the button was pressed? My logout form is as follows: <form id="logout" method="POST" action=""> <input type="submit" name="logout" value="Logout"> </form> From here, i know that I need to store the form in FieldS...
[ "You need not do handing of logout via POST and also you need to point out to something in the action field for handing either GET or the POST\nHere is an example which shows how to handle it via GET any form submit. You can simply allow clicking of the logout link to a particular portion in the url /logout and han...
[ 1 ]
[]
[]
[ "cgi", "html", "python" ]
stackoverflow_0005788571_cgi_html_python.txt
Q: Python struct.pack() not working in script I have some problems here when I try to use struct.pack from a script. Everything is fine in the interpreter: >>> import struct >>> k=2 >>> struct.pack(">b", k) '\x02' Now when I do the same from a script I have problems: k=2 p = struct.pack(">b", k) pri...
Python struct.pack() not working in script
I have some problems here when I try to use struct.pack from a script. Everything is fine in the interpreter: >>> import struct >>> k=2 >>> struct.pack(">b", k) '\x02' Now when I do the same from a script I have problems: k=2 p = struct.pack(">b", k) print "p is %s"%(p,) return p Result: p is wha...
[ "Everything is fine. The character is unprintable.\nprint \"p is %r\" % (p,)\n\n", "In the interpreter it is displaying the repr of that char and it is interpreting it when you do a print. So you can just do repr(p) in your script if you want to have same result as the interpreter. \n", "You are actually printi...
[ 8, 0, 0 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0005788729_python_struct.txt
Q: namespaces in SOAPpy not working as expected I'm having an issue correctly interfacing with a SOAP API running on Axis2: What happens is I should call the login method with two arguments (loginName and password) and it returns an authentication token that I will use for subsequent interaction. #!/usr/bin/python f...
namespaces in SOAPpy not working as expected
I'm having an issue correctly interfacing with a SOAP API running on Axis2: What happens is I should call the login method with two arguments (loginName and password) and it returns an authentication token that I will use for subsequent interaction. #!/usr/bin/python from SOAPpy import SOAPProxy s_user = 'Administrat...
[ "Looks like it's a known bug in SOAPPy, someone has suggested a simple patch: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=523083\nAlternately (assuming you have access to the service WSDL), SOAPPy lets you specify a WSDL instead of just a namespace. This looks like it will provide better namespace information ...
[ 2 ]
[]
[]
[ "axis2c", "python", "soap", "soappy" ]
stackoverflow_0005493349_axis2c_python_soap_soappy.txt
Q: Export entire regex group to text file When I print the group "print(a)" the entire group is shown. When I save it to a text file "open("sirs1.txt", "w").write(a)" only the last row is saved to the file. import re def main(): f = open('sirs.txt') for lines in f: match = re.search('(AA|BB|CC|DD)......', lines)...
Export entire regex group to text file
When I print the group "print(a)" the entire group is shown. When I save it to a text file "open("sirs1.txt", "w").write(a)" only the last row is saved to the file. import re def main(): f = open('sirs.txt') for lines in f: match = re.search('(AA|BB|CC|DD)......', lines) if match: a = match.group() ...
[ "nosklo is correct the main problem is that you are overwriting the whole file each time you write to it. mehmattski is also correct in that you will also need to explicitly add \\n to each write in order to make the output file readable.\nTry this:\nenter code here\n\nimport re\n\ndef main():\n f = open('sirs.txt...
[ 2, 1, 0 ]
[]
[]
[ "export", "python", "regex", "regex_group", "text_files" ]
stackoverflow_0005777916_export_python_regex_regex_group_text_files.txt
Q: How to pass multiple arguments to a python program via windows right-click context menu I have a python program which is converted to a windows exe using py2exe. I have also added it to the windows context menu. Basically when one right-clicks on any file another option appears with a link to my exe. The problem ...
How to pass multiple arguments to a python program via windows right-click context menu
I have a python program which is converted to a windows exe using py2exe. I have also added it to the windows context menu. Basically when one right-clicks on any file another option appears with a link to my exe. The problem is, when I select multiple files, multiple instances of my program starts up. Is there any w...
[ "If you add that that exe to windows context menu manually, then you did the hard step manually. What are you looking for is ability for py2exe to handle the Windows Shell Context Menu, that is not a trivial step and I doubt if it is possible using py2exe itself as I could find no references to in the docs or in th...
[ 1 ]
[]
[]
[ "arguments", "contextmenu", "python", "windows" ]
stackoverflow_0005788793_arguments_contextmenu_python_windows.txt
Q: Python+Django social network open source projects I'm looking for some open source, free to change and use project written on Pyton+Django with following features: Blog (for site, not for users) Users Registration User Profiles Adding friends, watching what friends added Award system for active users (carma, rat...
Python+Django social network open source projects
I'm looking for some open source, free to change and use project written on Pyton+Django with following features: Blog (for site, not for users) Users Registration User Profiles Adding friends, watching what friends added Award system for active users (carma, rating) Content rating Comments Probably different users l...
[ "Django has authentication and commenting built in, but most of the rest is covered by Pinax.\n", "There is an application that covers all of your requirements: vikuit.\ndjango, python, social network, profiles, rating, registration.... \nIt's open source, so you can adapt or improve. I used their forums and SSO ...
[ 10, 3 ]
[]
[]
[ "django", "project", "python", "social_networking" ]
stackoverflow_0001353097_django_project_python_social_networking.txt
Q: MD5 and SHA-2 collisions in Python I'm writing a simple MP3 cataloguer to keep track of which MP3's are on my various devices. I was planning on using MD5 or SHA2 keys to identify matching files even if they have been renamed/moved, etc. I'm not trying to match MP3's that are logically equivalent (i.e.: same song ...
MD5 and SHA-2 collisions in Python
I'm writing a simple MP3 cataloguer to keep track of which MP3's are on my various devices. I was planning on using MD5 or SHA2 keys to identify matching files even if they have been renamed/moved, etc. I'm not trying to match MP3's that are logically equivalent (i.e.: same song but encoded differently). I have about 8...
[ "I sort of have the feeling that you are reading a chunk of data which is smaller than the expected, and this chunk happens to be the same for both files. I don't know why, but try to open the file in binary with 'rb'. read() should read up to end of file, but windows behaves differently. From the docs\n\nOn Window...
[ 9, 2, 2, 0 ]
[]
[]
[ "hash", "md5", "mp3", "python", "sha" ]
stackoverflow_0005787471_hash_md5_mp3_python_sha.txt
Q: How find info about eth0 device in snmp information? How find info about eth0 device in snmp information ? A: You can access information via : iso(1).org(3).dod(6).internet(1).mgmt(2).mib-2(1).interfaces(2).ifTable(2).ifEntry(1). ... As you can see here under. Here is a table view : You'll find here a discus...
How find info about eth0 device in snmp information?
How find info about eth0 device in snmp information ?
[ "You can access information via :\niso(1).org(3).dod(6).internet(1).mgmt(2).mib-2(1).interfaces(2).ifTable(2).ifEntry(1). ...\n\nAs you can see here under.\n\nHere is a table view :\n\nYou'll find here a discussion about the best SNMP implementation for Python. \n" ]
[ 2 ]
[]
[]
[ "python", "snmp" ]
stackoverflow_0005786951_python_snmp.txt
Q: When running Celery with Django's manage.py command, it returns a strange error When I run the following command, it produces the following error: % python manage.py celeryd -l INFO ~/Workspace/django-projects/proje...
When running Celery with Django's manage.py command, it returns a strange error
When I run the following command, it produces the following error: % python manage.py celeryd -l INFO ~/Workspace/django-projects/project/src Traceback (most recent call last): File "manage.py", line 11, in <module> ...
[ "Should be easy to fix: just upgrade your install of django-celery.\n" ]
[ 1 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0004020423_celery_django_python.txt
Q: python: calling super().__init__ too early in the __init__ method? I have a class hierarchy where __init__ in class Base performs some pre-initialization and then calls method calculate. The calculate method is defined in class Base, but it's expected to be redefined in derived classes. The redefined calculate wil...
python: calling super().__init__ too early in the __init__ method?
I have a class hierarchy where __init__ in class Base performs some pre-initialization and then calls method calculate. The calculate method is defined in class Base, but it's expected to be redefined in derived classes. The redefined calculate will use some of the attributes that are only available in class Derived: c...
[ "Perhaps you shouldn't have the calculate() call in your constructor then. If you can't construct a derived object by allowing the base constructor to complete first, then you must be doing something wrong IMHO. A sensible approach would be to move that call out of the constructor and perhaps create a factory metho...
[ 8, 5, 2, 1 ]
[]
[]
[ "class", "design_patterns", "python" ]
stackoverflow_0005786441_class_design_patterns_python.txt
Q: Find a random method that best fit list of values I have a list of many float numbers, representing the length of an operation made several times. For each type of operation, I have a different trend in numbers. I'm aware of many random generators presented in some python modules, like in numpy.random For example...
Find a random method that best fit list of values
I have a list of many float numbers, representing the length of an operation made several times. For each type of operation, I have a different trend in numbers. I'm aware of many random generators presented in some python modules, like in numpy.random For example, I have binomial, exponencial, normal, weibul, and so ...
[ "You might find it better to think about this in terms of probability distributions, rather than thinking about random number generators. You can then think in terms of testing goodness of fit for your different distributions. \nAs a starting point, you might try constructing probability plots for your samples. Pro...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "random", "statistics" ]
stackoverflow_0005777896_python_random_statistics.txt
Q: desktop development language compiled binary or scripting language (windows)? Does anyone use a scripting language only solution to produce a binary (.exe) to produce a commercial desktop application for windows or mac? e.g. Java, python etc. If so how do you distribute your app and does using a scripting language...
desktop development language compiled binary or scripting language (windows)?
Does anyone use a scripting language only solution to produce a binary (.exe) to produce a commercial desktop application for windows or mac? e.g. Java, python etc. If so how do you distribute your app and does using a scripting language cause any problems with the installation? I'm asking about users that can download...
[ "I have done this in a couple ways. One was to use Python and py2exe, and the other was to use Idle, a Lua-based \"compilable\" language, using InnoSetup to create installers.\nI have had no problems with either, though I haven't used Idle for anything of any significant complexity --- its main advantage is the sm...
[ 1, 0 ]
[]
[]
[ "delphi", "desktop_application", "lua", "python", "windows" ]
stackoverflow_0005789455_delphi_desktop_application_lua_python_windows.txt
Q: What effects do parentheses have on the 'or' operator in Python? Is there a difference between these two statements in python: if tag == ('/event' or '/organization' or '/business'): and if tag == '/event' or '/organization' or '/business': A: They are both wrong. What you need is: if tag == '/event' or tag == ...
What effects do parentheses have on the 'or' operator in Python?
Is there a difference between these two statements in python: if tag == ('/event' or '/organization' or '/business'): and if tag == '/event' or '/organization' or '/business':
[ "They are both wrong. What you need is:\nif tag == '/event' or tag == '/organization' or tag == '/business':\n\nor:\nif tag in ['/event', '/organization', '/business']:\n\n", "The proper solution is\nif tag in ('/event', '/organization', '/business'):\n\nIt not only uses the in operator which is perfect for this ...
[ 12, 12, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005791031_python.txt
Q: Python "generic" class property encode/decode I almost guarantee this is something simple. I am trying to create a generic property to wrap a django text/blob field. This isn't Django specific, its really just an issue with design. I have some class level variables and am using a pseudo delegate to be able to r...
Python "generic" class property encode/decode
I almost guarantee this is something simple. I am trying to create a generic property to wrap a django text/blob field. This isn't Django specific, its really just an issue with design. I have some class level variables and am using a pseudo delegate to be able to reuse an decode method. class DBTable(models.Model...
[ "Simply remove self from get_data and make it a function outside the class.\nget_data_factory(\"blob_a\") will return a function, which expects self as an argument. That is perfectly fine. It does not have to receive (in fact, it should not receive) that value from get_data.\ndef get_data_factory(prop):\n def ge...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005791141_python.txt
Q: How to stop a warning dialog from halting execution of a Python program that's controlling it? Using Win32GUI and Watsup, I'm writing a bit of Python code to automate a search across a database that is accessed through a program that doesn't come with an interface for it. As such, I can take a string from a list a...
How to stop a warning dialog from halting execution of a Python program that's controlling it?
Using Win32GUI and Watsup, I'm writing a bit of Python code to automate a search across a database that is accessed through a program that doesn't come with an interface for it. As such, I can take a string from a list and then input it into the search box and press 'lookup'. However, when the search returns more than ...
[ "I'm not a WATSUP user, but I do something very similar using pywinauto - in my case I'm running a number of automated tests that open various 3rd party programs that, in a similar way, throw up inconvenient warning dialogs. It's a bit difficult to deal with dialogs that you don't know about, however if you do kno...
[ 1 ]
[]
[]
[ "python", "win32gui" ]
stackoverflow_0005774506_python_win32gui.txt
Q: How can I combine multiple lines of text into one line in Python with a delimiter to separate them? I have the following in a text file: line1 text1 text2 text3 line2 something1 something2 I want to create another text file that looks like this: line1|text1|text2|text3 line2|something1|something2 Whenever a line...
How can I combine multiple lines of text into one line in Python with a delimiter to separate them?
I have the following in a text file: line1 text1 text2 text3 line2 something1 something2 I want to create another text file that looks like this: line1|text1|text2|text3 line2|something1|something2 Whenever a line in the text file says "line" I want to add each line below it to that line with a '|' delimiter. Can I ...
[ "If your file is not EXTREMELY big\ndata=open(\"file\").readlines()\nfor n,line in enumerate(data):\n if line.startswith(\"line\"):\n data[n] = \"\\n\"+line.rstrip()\n else:\n data[n]=line.rstrip()\nprint '|'.join(data)\n\n", "Here's a one-liner which uses line1, line2, ... without actually read...
[ 7, 3, 3, 1 ]
[]
[]
[ "python", "text" ]
stackoverflow_0005791581_python_text.txt
Q: Dictionary of class subclasses Whether there is a way to make the dictionary of all class inheritances ? Something like class MagikClass : pass class A(MagikClass) : __name__ = "A" print magik_dict # -> { "A": A } A: Here is a solution that adds an attribute _derived to each class, containi...
Dictionary of class subclasses
Whether there is a way to make the dictionary of all class inheritances ? Something like class MagikClass : pass class A(MagikClass) : __name__ = "A" print magik_dict # -> { "A": A }
[ "Here is a solution that adds an attribute _derived to each class, containing the derived classes of that class:\nclass Meta(type):\n def __new__(cls, name, bases, dict_):\n new_class = type.__new__(cls, name, bases, dict_)\n new_class._derived = {}\n if isinstance(bases[0], Meta):\n ...
[ 4 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005791730_oop_python.txt
Q: Best way to structure a site with media to keep it separate from the base code. ( Opinion based ) I've recently have taken a new server under my wing that has an interesting installation of django on it. The previous developer mixed in the media uploads with the static content and in other modules created it's own...
Best way to structure a site with media to keep it separate from the base code. ( Opinion based )
I've recently have taken a new server under my wing that has an interesting installation of django on it. The previous developer mixed in the media uploads with the static content and in other modules created it's own directory on the root file level of the project. My first reaction to this was general annoyance. ( I'...
[ "I don't think your trick is really needed (anymore).\nIf you use django.template.loaders.app_directories.Loader (docs)\nyou can put a template dir in your app dir and Django will check it for your app-specific templates\nAnd starting with Django 1.3 you can use the staticfiles app to do something similar with all ...
[ 3, 0 ]
[]
[]
[ "database", "django", "file", "python", "theory" ]
stackoverflow_0005791015_database_django_file_python_theory.txt
Q: dbus Variant: How to preserve boolean datatype in Python? I've been experimenting with dbus lately. But I can't seem to get my dbus Service to guess the correct datatypes for boolean values. Consider the following example: import gtk import dbus import dbus.service from dbus.mainloop.glib import DBusGMainLoop cla...
dbus Variant: How to preserve boolean datatype in Python?
I've been experimenting with dbus lately. But I can't seem to get my dbus Service to guess the correct datatypes for boolean values. Consider the following example: import gtk import dbus import dbus.service from dbus.mainloop.glib import DBusGMainLoop class Service(dbus.service.Object): def __init__(self): bus...
[ "I'm not sure which part you're having difficulty with. The types can easily be cast from one form to another, as you show in your example dbus.Boolean(val). You can also use isinstance(value, dbus.Boolean) to test if the value is a dbus boolean, not an integer.\nThe Python native types are converted into dbus type...
[ 0 ]
[]
[]
[ "boolean", "dbus", "gtk", "python", "variant" ]
stackoverflow_0005791095_boolean_dbus_gtk_python_variant.txt
Q: thread safety in django with asynchronous tasks and redis I have a django application that calls an asynchronous task on a queryset (using celery). The task takes the queryset and performs a whole bunch of operations that could potentially take a very long time based on the obects therein. Objects could be shared ...
thread safety in django with asynchronous tasks and redis
I have a django application that calls an asynchronous task on a queryset (using celery). The task takes the queryset and performs a whole bunch of operations that could potentially take a very long time based on the obects therein. Objects could be shared across querysets, so a user could submit a task on a queryset t...
[ "Is it possible for you to architect this slightly differently? Specifically, I would kick off the tasks for each object and then store information about your long running jobs somewhere (e.g., database, cache, etc). When each individual object was finished, it would update the long running job info and check to se...
[ 2 ]
[]
[]
[ "celery", "django", "python", "redis", "thread_safety" ]
stackoverflow_0005531695_celery_django_python_redis_thread_safety.txt
Q: Python regex: Reject one two-digit number and accept other two-digit numbers How can I make a regular expression to not match a certain number with more than 2 digits. for example any number but 13. The second line of code below wont work it will not match 10, 11,... either and the third line will look for a numbe...
Python regex: Reject one two-digit number and accept other two-digit numbers
How can I make a regular expression to not match a certain number with more than 2 digits. for example any number but 13. The second line of code below wont work it will not match 10, 11,... either and the third line will look for a number not starting with 1 but having a 3: str = 'val=13' regex = 'val=[^1][^3]' regex...
[ "Use lookahead assertions:\nIn : re.findall('val=(?!13$)(\\d{2,})', 'val=12') \nOut: ['12']\n\nIn : re.findall('val=(?!13$)(\\d{2,})', 'val=13') \nOut: []\n\n", "Why do you need a regular expression?\n>>> string = 'val=13'\n>>> array=string.split(\"=\")\n>>> if array[0] == \"val\" and int(array[1]) < 100 and int(...
[ 6, 3, 3, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005789740_python_regex.txt
Q: How can I strip unwanted characters from a string in python? I have the following string: text = 'adsfklaiin2007daf adf adflkajf;j 2008afadfkjkj' I want to return: 2007 2008 Any way to do this in Python? A: This is a classic case for regular expressions. Using the re python library you get: re.findall('\d{4}',...
How can I strip unwanted characters from a string in python?
I have the following string: text = 'adsfklaiin2007daf adf adflkajf;j 2008afadfkjkj' I want to return: 2007 2008 Any way to do this in Python?
[ "This is a classic case for regular expressions. Using the re python library you get:\nre.findall('\\d{4}', \"yourStringHere\")\n\nThis will return a list of all four digit items found in the string. Simply adjust your regex as needed.\n", "import re\nnum = re.compile('[\\d]*')\nnumbers = [number for number in nu...
[ 7, 5, 3, 1 ]
[]
[]
[ "python", "string", "text" ]
stackoverflow_0005792567_python_string_text.txt
Q: How do I locally increase the amount of a global variable? I'm writing a program using PyQt and I'm trying to figure out a way to keep adding to a global variable every time a particular button is clicked. This way if my global is 0 then the third time the button is clicked my global would equal 3. Here's the rele...
How do I locally increase the amount of a global variable?
I'm writing a program using PyQt and I'm trying to figure out a way to keep adding to a global variable every time a particular button is clicked. This way if my global is 0 then the third time the button is clicked my global would equal 3. Here's the relevant code. # from the main window class QtCore.QObject.connec...
[ "use the global statement\nglobal myGlobal\nmyGlobal = 0\ndef CadDraw(self):\n global myGlobal\n myGlobal +=1 [the previous value from the last time CadDraw was called plus 1]\n DoStuff()\n\n" ]
[ 3 ]
[]
[]
[ "global_variables", "pyqt4", "python" ]
stackoverflow_0005792553_global_variables_pyqt4_python.txt
Q: Run specific method of the class defined by string I have this sample code class aaa: @staticmethod def method(self): pass @staticmethod def method2(self): pass command = 'method' Now I would like to run method of the class aaa defined by command string. How could I do this? Tha...
Run specific method of the class defined by string
I have this sample code class aaa: @staticmethod def method(self): pass @staticmethod def method2(self): pass command = 'method' Now I would like to run method of the class aaa defined by command string. How could I do this? Thank you very much.
[ "Don't. There's rarely a reason to deal with the issues (security, cleaness, performance, arguably readability, ...) that this approach introduces. Just use command = aaa.method.\nIf you have to use a string (hopefully for a good reason), you can use getattr but you propably should use an explicit mapping specifyin...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005792798_python.txt
Q: Which path module or class do Python folks use instead of os.path? Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using os.path for joining and splitting paths? Have you used: Jason's path module (updated for PEP 355) Mike Orr's Unipath, basically a more moder...
Which path module or class do Python folks use instead of os.path?
Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using os.path for joining and splitting paths? Have you used: Jason's path module (updated for PEP 355) Mike Orr's Unipath, basically a more modern version of the above Noam Raphael's alternative path module that subcl...
[ "I can pick up a Python program and interpret the current standard method without hesitation - it's explicit and there's no ambiguity:\nos.path.join(build_dir, os.path.basename(source_file))\n\nPython's dynamic typing makes the first method rather difficult to comprehend when reading:\nbuild_dir / path(source_file)...
[ 11, 2 ]
[ "Dividing strings to join paths may seem like a \"neat trick\" but it's precisely that kind of thing that Python programmers like to avoid (and btw, programmers in most other langauges.) The os.path module is widely used and easily understood by all. Doing funky things with overloaded operators on the other hand is...
[ -1 ]
[ "path", "python" ]
stackoverflow_0001252639_path_python.txt
Q: Python get __doc__ documentation for instance variable In python, I know I'm supposed to document instance variables like this: self.x = 22 """docstring for x""" #: docstring for x self.x = 22 self.x = 22 #: docstring for x But I can't seem to find a way to get hold of that documentation in code. MyClass.x.__doc...
Python get __doc__ documentation for instance variable
In python, I know I'm supposed to document instance variables like this: self.x = 22 """docstring for x""" #: docstring for x self.x = 22 self.x = 22 #: docstring for x But I can't seem to find a way to get hold of that documentation in code. MyClass.x.__doc__ gives me the doc of the actual type that is in x So the q...
[ "According to PEP 257, instance variables are supposed to be documented in the docstring of the class:\n\nThe docstring for a class should summarize its behavior and list the public methods and instance variables.\n\nJust writing the docstring after the initialisation of an instance variable won't give you any way ...
[ 8, 8 ]
[]
[]
[ "documentation", "python" ]
stackoverflow_0005793306_documentation_python.txt
Q: How to define an icon for a Gedit plugin written in Python I am writing a Gedit plugin and created an icon for it as SVG (which of course can be exported to any format). How could I configure this plugin to show this icon in the plugin listing in Edit > Preferences > Plugins dialog? A: The .plugin file accepts a...
How to define an icon for a Gedit plugin written in Python
I am writing a Gedit plugin and created an icon for it as SVG (which of course can be exported to any format). How could I configure this plugin to show this icon in the plugin listing in Edit > Preferences > Plugins dialog?
[ "The .plugin file accepts an Icon field -- as in this example:\n[Gedit Plugin]\nLoader=python\nModule=TextWrap\nIAge=2\nIcon=gtk-ok\n[... and so on ...]\n\nTaken from the TextWrap plugin source.\nTo add a custom icon to an existing icon theme, place it in the appropriate folder -- i.e. \n$prefix/share/icons/hicolor...
[ 3, 2 ]
[]
[]
[ "gedit", "icons", "plugins", "pygtk", "python" ]
stackoverflow_0005792437_gedit_icons_plugins_pygtk_python.txt
Q: Creating space in between written lines I'm currently creating a function that reads in data from other functions and writing it out to a text file on my desktop. def outputResults(filename): """This function serves to output and write the results from analyzeGenome.py to a text file \ Input: filename of output...
Creating space in between written lines
I'm currently creating a function that reads in data from other functions and writing it out to a text file on my desktop. def outputResults(filename): """This function serves to output and write the results from analyzeGenome.py to a text file \ Input: filename of output file, dictionary of codon frequencies, dicti...
[ "You need to append a linebreak.\nhttp://docs.python.org/library/stringio.html\noutput.write('First line.\\n')\n", "Instead of write, use writelines, which prints everything in the sequence out to a file on its own line. Add a blank string to add double spacing\n filename.writelines([outString, \"\", outString2]...
[ 5, 2 ]
[]
[]
[ "file_io", "io", "python" ]
stackoverflow_0005793715_file_io_io_python.txt
Q: Why does this code output the failure message after success? if data.find('!mdcrack') != -1: nick = data.split('!')[ 0 ].replace(':','') m = hashlib.md5() hash = "" hash_file = str(arg[4]) wordlist = arg[5] try: wordlistfile = open(wordlist,"r") except IOError: ...
Why does this code output the failure message after success?
if data.find('!mdcrack') != -1: nick = data.split('!')[ 0 ].replace(':','') m = hashlib.md5() hash = "" hash_file = str(arg[4]) wordlist = arg[5] try: wordlistfile = open(wordlist,"r") except IOError: sck.send('PRIVMSG ' + chan + " :" 'invalid file' + '\r\n') ...
[ "Surely it will print 'PRIVSG [..] Collision' and after 'PRIVSG [..] The hash given'.\nWhat you have to do is:\ncollision = False\n[..] \nif word_hash==hash_file:\n sck.send('PRIVMSG ' + chan + \" :\" 'Collision! The word corresponding to the given hash is ' + line + '\\r\\n')\n ...
[ 2, 1 ]
[]
[]
[ "control_flow", "python" ]
stackoverflow_0005793946_control_flow_python.txt
Q: Facebook calling Google App Engine code using GET instead of POST I've been developing a Facebook app using Google App Engine in Python and the pyfacebook bindings. For weeks everything worked fine but suddenly it stopped. At first I thought it was a code change so I rolled back the entire dev directory to a versi...
Facebook calling Google App Engine code using GET instead of POST
I've been developing a Facebook app using Google App Engine in Python and the pyfacebook bindings. For weeks everything worked fine but suddenly it stopped. At first I thought it was a code change so I rolled back the entire dev directory to a version I knew worked, but still it failed. It's possible a change I made t...
[ "The typical flow for a user when using the application begins with the user landing at some Canvas URL, like http://apps.facebook.com/runwithfriends/. At this point, Facebook will load up it's chrome, and render a tag to your application. You'll notice there isn't a src specified. Using some JavaScript and the t...
[ 1, 0 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0002241689_facebook_google_app_engine_python.txt
Q: bad math or bad programming, maybe both? I'm writing a Python program to generate the Luna Free State flag from the famous Heinlein novel The Moon is a Harsh Mistress, as a personal project. I've been cribbing heraldry rules and matching mathematical formulas off the web, but something is clearly wrong in my bends...
bad math or bad programming, maybe both?
I'm writing a Python program to generate the Luna Free State flag from the famous Heinlein novel The Moon is a Harsh Mistress, as a personal project. I've been cribbing heraldry rules and matching mathematical formulas off the web, but something is clearly wrong in my bendsinister routine, since the assertion fails whe...
[ "Break the rectangle into two triangles. They will be identical.\nThe Black triangle + Blue Trapezoid is Triangle A.\nThe Black Triangle on its own is Triangle B\nTriangle A and Triangle B are similar triangles so their area is related by the square of the scale factor relating them.\nWe want the Blue Trapezoid to ...
[ 8, 2 ]
[]
[]
[ "geometry", "python", "python_imaging_library" ]
stackoverflow_0005786573_geometry_python_python_imaging_library.txt
Q: I'm getting an IO ERROR for a file that is not in the path where I'm parsing files I continuously get an error when I open all text and log files in a particular path and print the log that the match was found in. Below is the Error returned and the code. Does anyone know why I'm getting this error; the code works...
I'm getting an IO ERROR for a file that is not in the path where I'm parsing files
I continuously get an error when I open all text and log files in a particular path and print the log that the match was found in. Below is the Error returned and the code. Does anyone know why I'm getting this error; the code works the way it's supposed to work? Thanks! ERROR: file: c:\Python27\13.00.log Traceback (m...
[ "When you do a file open the variable 'file' doesn't contain the fullpath hence you get the error.\n", "I think you need to open the file using its absolute path, not just its filename. Try changing your open(..) line to f = open(os.path.join(root, file) and it should work.\nEdit: The following works for me (I'm ...
[ 1, 1 ]
[]
[]
[ "file", "io", "python", "string_matching" ]
stackoverflow_0005794355_file_io_python_string_matching.txt
Q: problem with timeout in netsnmp lib I have simple example: import netsnmp var = netsnmp.Varbind('ifHCInOctets','0') res = netsnmp.snmpgetnext(var,Version = 2,DestHost='localhost',Community='public',Timeout=1000000) print res[0] time python2 test.py show me: real 0m4.086s user 0m0.073s sys 0m0.007s ...
problem with timeout in netsnmp lib
I have simple example: import netsnmp var = netsnmp.Varbind('ifHCInOctets','0') res = netsnmp.snmpgetnext(var,Version = 2,DestHost='localhost',Community='public',Timeout=1000000) print res[0] time python2 test.py show me: real 0m4.086s user 0m0.073s sys 0m0.007s Why 4 seconds = 1000000 ? snmpd server n...
[ "When you pass Timeout=? you are setting the maximum time that snmp's internal select loop should wait before registering a timeout. Setting this to 1000000 means \"wait 1 million microseconds\", which is 1 second.\nHowever there is also a Retries=? argument that specifies the number of times the snmp client will ...
[ 4 ]
[]
[]
[ "net_snmp", "python" ]
stackoverflow_0005792497_net_snmp_python.txt
Q: How do I take info from a text file and put it into a dictionary (Python) I built a previous program that stores info to a txt file (yes I should have used a Db but haven't learned it well yet) anyway what I want to do is have a function or method that pulls that info from the file and stores it into a dictionary,...
How do I take info from a text file and put it into a dictionary (Python)
I built a previous program that stores info to a txt file (yes I should have used a Db but haven't learned it well yet) anyway what I want to do is have a function or method that pulls that info from the file and stores it into a dictionary, all while possibly updating the text file/dict if something needs to change Th...
[ "friend = dict(line.split(\":\", 1) for line in open(\"file\"))\n\nThis splits every line at the first colon to get a sequence of (key, value) pairs, and uses this sequence to initialise the dictionary.\nTo allow empty lines in your file, you could use\nfriend = dict(line.split(\":\", 1) for line in open(\"file\") ...
[ 1 ]
[]
[]
[ "class", "file_io", "function", "python" ]
stackoverflow_0005794592_class_file_io_function_python.txt
Q: Calling an external script from Django admin interface? I have a Django admin interface that is used almost solely as a gui form for making changes to a single postgresql table. There's also a Python script that's currently run manually from the command line whenever a change is made to the database, & I'd like to...
Calling an external script from Django admin interface?
I have a Django admin interface that is used almost solely as a gui form for making changes to a single postgresql table. There's also a Python script that's currently run manually from the command line whenever a change is made to the database, & I'd like to hook that up so it runs whenever someone hits "save" after m...
[ "Generally, things you want to happen at 'save' time are either\n\nPart of the model.\nIf so, you override the model's save method: http://docs.djangoproject.com/en/1.3/ref/models/instances/#saving-objects\nYou can do anything in that save method.\nPart of the view function.\nIf so, you either extend the admin inte...
[ 2, 1 ]
[]
[]
[ "django", "django_admin", "django_views", "python" ]
stackoverflow_0005794097_django_django_admin_django_views_python.txt
Q: How and why does PyCharm alter Python's import logic? I have a PyCharm 1.2.1 on Windows. I have to edit different branches of the same project - somewhat heavy branches, because they live in different folders on disk - say it to be c:\apps\alpha and c:\apps\beta. For each such folder PYTHONPATH variable should be ...
How and why does PyCharm alter Python's import logic?
I have a PyCharm 1.2.1 on Windows. I have to edit different branches of the same project - somewhat heavy branches, because they live in different folders on disk - say it to be c:\apps\alpha and c:\apps\beta. For each such folder PYTHONPATH variable should be adjusted to point to appropriate vendor libraries which liv...
[ "The correct solution is not to try to work around PyCharm's logic, but rather to use the IDE features as they're designed. That means:\n\nNot use any .cmd scripts for starting up PyCharm\nRemove all the paths specific to \"alpha\" and \"beta\" from the list of paths in Settings | Python Interpreters if any are lis...
[ 13 ]
[]
[]
[ "import", "pycharm", "python", "pythonpath" ]
stackoverflow_0005794502_import_pycharm_python_pythonpath.txt
Q: How can I clean up text files in python? I have text in a file that looks like this: text1 5,000 6,000 text2 2,000 3,000 text3 5,000 3,000 text4 1,000 2000 text5 7,000 1,000 text6 2,000 1,000 Is there any way to clean this up in Python so that if there are missing numbers after a text line, ...
How can I clean up text files in python?
I have text in a file that looks like this: text1 5,000 6,000 text2 2,000 3,000 text3 5,000 3,000 text4 1,000 2000 text5 7,000 1,000 text6 2,000 1,000 Is there any way to clean this up in Python so that if there are missing numbers after a text line, the numbers on the subsequent line can be plac...
[ "Assuming there should be exactly three \"words\" on each line, you could use\ntokens = (x for line in open(\"file\") for x in line.split())\nfor t in zip(tokens, tokens, tokens):\n print str.join(\" \", t)\n\nEdit: Since apparently the above prerequisite does not hold, here is an implementation that actually lo...
[ 3, 1 ]
[]
[]
[ "python", "text" ]
stackoverflow_0005794498_python_text.txt
Q: using python to parse colon (:) delimited string to an object i have a string which is a return value of REST API (http://requesttracker.wikia.com/wiki/REST) and is using colon seperated key/value pairs. id: 123414 name: Peter message: bla bla bla bla How can i parse this string to an object? is there an exist...
using python to parse colon (:) delimited string to an object
i have a string which is a return value of REST API (http://requesttracker.wikia.com/wiki/REST) and is using colon seperated key/value pairs. id: 123414 name: Peter message: bla bla bla bla How can i parse this string to an object? is there an existing python parser that i can use?? Here's the string that i want to...
[ "You really need to say which REST api and provide a documentation reference.\nSuperficially, it doesn't look too hard:\n# Look Ma, no imports!\n>>> s = 'id: 1234\\nname: Peter\\nmessage: foo bar zot\\nmsg2: tee:hee\\n'\n>>> dict(map(str.strip, line.split(':', 1)) for line in s.splitlines())\n{'message': 'foo bar z...
[ 5, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005783417_python.txt
Q: setup_environ in django I used this syntax to change the setup_environ live settings from python shell import live_settings from django.core.management import setup_environ setup_environ(live_settings) Is this change temporary or permanent? Will we have to set it back to setup_environ(settings) to have the site ...
setup_environ in django
I used this syntax to change the setup_environ live settings from python shell import live_settings from django.core.management import setup_environ setup_environ(live_settings) Is this change temporary or permanent? Will we have to set it back to setup_environ(settings) to have the site function normally or by defau...
[ "If you're doing it from the shell, the changes will only exist for the duration of that shell instance -- the stuff in settings.py will be used otherwise.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005792011_django_python.txt
Q: Slice to " "space in python If L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]] How would slice L to get everything up to the first space ['abc,'foo','bar'] A: In [1]: L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]] In [2]: [x[0].split(' ')[0] for x in L] Out[2]: ['abc', 'foo', 'bar'] A: L = ...
Slice to " "space in python
If L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]] How would slice L to get everything up to the first space ['abc,'foo','bar']
[ "In [1]: L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]\n\nIn [2]: [x[0].split(' ')[0] for x in L]\nOut[2]: ['abc', 'foo', 'bar']\n\n", "L = [['abc 1234',2], ['foo 1',2] , ['bar 12312434',2]]\nprint [x[0].split()[0] for x in L]\n\n", "for i in range(len(L)):\n s = L[i][0]\n s = s.split(' ')[0]\n ...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0005794776_python_slice.txt
Q: Store NumPy Row and Column Headers I have a numpy 2 dimensional numpy array that contains the daily stock prices for multiple stocks. For example daily_prices = np.array([ [4,3,3,1], [5,4,3,6], [6,3,2,7], [3,9,7,4], [8,4,6,3], [8,3,3,9]]) where each row is a different date, a...
Store NumPy Row and Column Headers
I have a numpy 2 dimensional numpy array that contains the daily stock prices for multiple stocks. For example daily_prices = np.array([ [4,3,3,1], [5,4,3,6], [6,3,2,7], [3,9,7,4], [8,4,6,3], [8,3,3,9]]) where each row is a different date, and each column is a different stock. I'd...
[ "Use a structured array:\nimport numpy as np\n\ndaily_prices = np.array(\n [\n (4,3,3,1),\n (5,4,3,6),\n (6,3,2,7),\n (3,9,7,4),\n (8,4,6,3),\n (8,3,3,9)],\n dtype=[('MSFT','float'),('CSCO','float'),('GOOG','float'),('F','float') ]\n )\n\nThis allows you to access ...
[ 23 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005795748_numpy_python.txt
Q: pdb.set_trace alternative with apache/wsgi I have just migrated my development enviroment from manage.py to apache/wsgi, how ever when I run pdb.set_trace() I get BdbQuit. Is there a way to work with something like pdb.set_trace under apache/wsgi ? A: You'll need a remote debugger. Look into rpdb2 here: http:/...
pdb.set_trace alternative with apache/wsgi
I have just migrated my development enviroment from manage.py to apache/wsgi, how ever when I run pdb.set_trace() I get BdbQuit. Is there a way to work with something like pdb.set_trace under apache/wsgi ?
[ "You'll need a remote debugger. Look into rpdb2 here: http://winpdb.org/docs/embedded-debugging/\nOf course, Apache+WSGI is typically a production environment and is going to be harder to debug then running the development appserver with manage.py.\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "django_wsgi", "pdb", "python" ]
stackoverflow_0005795977_apache_django_django_wsgi_pdb_python.txt
Q: multiply numpy array of scalars by array of vectors I have a numpy array of vectors that I need to multiply by an array of scalars. For example: >>> import numpy >>> x = numpy.array([0.1, 0.2]) >>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]]) I can multiply individual elements like this: >>> x[0]*y[0] array([ 0...
multiply numpy array of scalars by array of vectors
I have a numpy array of vectors that I need to multiply by an array of scalars. For example: >>> import numpy >>> x = numpy.array([0.1, 0.2]) >>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]]) I can multiply individual elements like this: >>> x[0]*y[0] array([ 0.11, 0.22, 0.33]) but when I try and multiply the enti...
[ "I[1]: x = np.array([0.1, 0.2])\n\nI[2]: y = np.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])\n\n\nI[3]: y*x[:,np.newaxis]\nO[3]: \narray([[ 0.11, 0.22, 0.33],\n [ 0.88, 1.1 , 1.32]])\n\n" ]
[ 20 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005795700_numpy_python.txt
Q: If I do "long-polling" with AJAX requests...what does that mean about my threads? Does each client take up one thread? I mean...it's long-polling that one thread, right? So , in order to support 10,000 simultaneous clients, I'll need to spawn up a server that has 10,000 threads? A: Assuming your server dedicate...
If I do "long-polling" with AJAX requests...what does that mean about my threads?
Does each client take up one thread? I mean...it's long-polling that one thread, right? So , in order to support 10,000 simultaneous clients, I'll need to spawn up a server that has 10,000 threads?
[ "Assuming your server dedicates a thread to each request and doesn't time out those requests, the answer is yes. If you plan to do long-polling, you might want to consider an event-based web server. You can find benchmarks of several python ones here: http://nichol.as/benchmark-of-python-web-servers\nSee also: W...
[ 1 ]
[]
[]
[ "ajax", "apache", "http", "python" ]
stackoverflow_0005795142_ajax_apache_http_python.txt
Q: Is there a python module which provides entry points that wrap the openssh client? Is there a Python module which provides provides remote control functions by launching subprocesses implementing the ssh command line interface? The kind of functions that would be useful include: run this command on that machine, ...
Is there a python module which provides entry points that wrap the openssh client?
Is there a Python module which provides provides remote control functions by launching subprocesses implementing the ssh command line interface? The kind of functions that would be useful include: run this command on that machine, and return exit code, stdout and stderr or raise an exception after a timeout test wheth...
[ "You might find Python's Fabric right for your needs. It looks like it uses paramiko but it is smart about caching connections, as documented in the execution model.\nIt won't use an existing long-running connection though.\n", "Some of what you're talking about sounds like you want to use rsync, specifically yo...
[ 3, 1, 0 ]
[]
[]
[ "openssh", "python", "ssh" ]
stackoverflow_0005791766_openssh_python_ssh.txt
Q: python re match, findall or search and then NLP (what to do with it?) I am starting to write code that would capture part of sentence "types" and if they match a criteria, start a specific python script that deals with the "type." I am "finding":) that findall kind of works better for what i am doing hence: m = re...
python re match, findall or search and then NLP (what to do with it?)
I am starting to write code that would capture part of sentence "types" and if they match a criteria, start a specific python script that deals with the "type." I am "finding":) that findall kind of works better for what i am doing hence: m = re.compile(r'([0-9] days from now)') m.match("i think maybe 7 days from now i...
[ "The reason why m.match() fails is that it expects the match to start at the beginning of the string.\nfindall() makes sense if you expect more than one (non-overlapping) match in your string. Otherwise, use the search() method (which will return the first match it finds).\nThis is all well covered in the docs.\n",...
[ 12, 0 ]
[]
[]
[ "nlp", "python", "regex" ]
stackoverflow_0005789126_nlp_python_regex.txt
Q: How to convert DateTimeField in django models to specific timezones like GMT? Hi is it possible to convert datetime field in django to GMT timezones or what ever timezones we need in the models.py like online_date = models.DateTimeField(timezones=GMT) or should i write in python externally to change the format A...
How to convert DateTimeField in django models to specific timezones like GMT?
Hi is it possible to convert datetime field in django to GMT timezones or what ever timezones we need in the models.py like online_date = models.DateTimeField(timezones=GMT) or should i write in python externally to change the format
[ "I've found it is best to have the server timezone set to UTC and then convert dates based on required timezones (for example, the users preferences), rather than storing different timezoned dates in the database. This requires no changing of timezones at the layer you are concerned with.\n" ]
[ 4 ]
[]
[]
[ "datetime", "django", "django_models", "python" ]
stackoverflow_0005795298_datetime_django_django_models_python.txt
Q: How to build numpy with conary recipe for x-86 CentOs i am getting error: rbuild build packages numpy --no-recurse [Tue Apr 26 13:16:53 2011] Creating rMake build job for 1 items Added Job 902 numpy:source=rmake-repository.bericots.com@local:taf32-sandbox-1-devel/1-0.2 [13:17:23] Watching job 902 ...
How to build numpy with conary recipe for x-86 CentOs
i am getting error: rbuild build packages numpy --no-recurse [Tue Apr 26 13:16:53 2011] Creating rMake build job for 1 items Added Job 902 numpy:source=rmake-repository.bericots.com@local:taf32-sandbox-1-devel/1-0.2 [13:17:23] Watching job 902 [13:17:24] [902] Loading 1 out of 1: numpy:source [13:17:26...
[ "It seems you don't have all the dependencies. The install page may help you.\n", "the command $rbuild build packages numpy --no-recurse , should be executed at the level where the package is, not in Development/QA or Release Directories.\n" ]
[ 0, 0 ]
[]
[]
[ "centos", "numpy", "python" ]
stackoverflow_0005794093_centos_numpy_python.txt
Q: Python: add a value to the end of the inner-most right nested list What I'm trying to do, is, given a list with an arbitrary number of other nested lists, recursively descend through the last value in the nested lists until I've reached the maximum depth, and then append a value to that list. An example might make...
Python: add a value to the end of the inner-most right nested list
What I'm trying to do, is, given a list with an arbitrary number of other nested lists, recursively descend through the last value in the nested lists until I've reached the maximum depth, and then append a value to that list. An example might make this clearer: >>> nested_list1 = [1, 2, 3, [4, 5, 6]] >>> last_inner_ap...
[ "How about this:\ndef last_inner_append(x, y):\n try:\n if isinstance(x[-1], list):\n last_inner_append(x[-1], y)\n return x\n except IndexError:\n pass\n x.append(y)\n return x\n\n", "This function returns the deepest inner list:\ndef get_deepest_list(lst, depth = ...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0005795290_list_python_recursion.txt
Q: Package Import woes in Python My structure is thus: companynamespace/ __init__.py projectpackage/ __init__.py somemodule.py companynamespace/__init__.py is empty projectpackage/__init__.py has this line: import companynamespace.projectpackage.somemodule as module_shortname When I open up a python con...
Package Import woes in Python
My structure is thus: companynamespace/ __init__.py projectpackage/ __init__.py somemodule.py companynamespace/__init__.py is empty projectpackage/__init__.py has this line: import companynamespace.projectpackage.somemodule as module_shortname When I open up a python console and type import companynamespa...
[ "There is no need for absolute import in projectpackage/__init__.py, do relative one \nimport somemodule as module_shortname\n\nThe way you're doing it (with absolute import), would lead to circular import, which don't work very well in Python. When you're importing module, you're also calling __init__.py of parent...
[ 5, 1 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0005796625_import_package_python.txt
Q: Python : Generating a gzip string by returning chunks I am going to ask for something I could not find on Stackoverflow. I am doing some Django, and I've recently discovered that I can stream the HTTP output using a generator. The output of a page is perfect for a normal case, however I wanted to stream the page o...
Python : Generating a gzip string by returning chunks
I am going to ask for something I could not find on Stackoverflow. I am doing some Django, and I've recently discovered that I can stream the HTTP output using a generator. The output of a page is perfect for a normal case, however I wanted to stream the page output using GZip compression. I've tried using the simple z...
[ "use zlib.compressobj([level]) and Compress.compress(string) and Compress.flush([mode]) to finish\nimport zlib\ndef compress(chunks):\n c = zlib.compressobj()\n for chunk in chunks:\n yield c.compress(chunk)\n yield c.flush(zlib.Z_FINISH)\n\n", "Compressing the content is a property of your webserv...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005797214_django_python.txt
Q: How to partition a list in smaller lists so that the odds of one element encountering another element is evenly distributed? I'm struggling with an algorithm to divide a group of contestants into smaller groups to make up rounds. Take for example a group of 20 people, which I want to divide into 3 groups (7,7,6). ...
How to partition a list in smaller lists so that the odds of one element encountering another element is evenly distributed?
I'm struggling with an algorithm to divide a group of contestants into smaller groups to make up rounds. Take for example a group of 20 people, which I want to divide into 3 groups (7,7,6). For each round in a contest, the groups are different, so that everybody has to combat everybody else in a rather fair distributio...
[ "You're getting into a topic that has been explored in combinatorics, but actually producing those designs is surprisingly tricky. See http://en.wikipedia.org/wiki/Block_design for a sample of the sorts of things you'll want to learn more about. If you need help, I suggest asking on https://math.stackexchange.com...
[ 1, 0 ]
[]
[]
[ "algorithm", "combinatorics", "python" ]
stackoverflow_0005790293_algorithm_combinatorics_python.txt
Q: Plotting data using percent unit I have used google for search but i do not found an answer. My problem: I have data array and i would like plot by using percent unit. Example: data: [1, 3, 1, 3, 3, 2, 4, 5] 1: 0.25 2: 0.125 3: 0.375 4: 0.125 5: 0.125 PS: i do not want use R only python, matplotlib and if need ...
Plotting data using percent unit
I have used google for search but i do not found an answer. My problem: I have data array and i would like plot by using percent unit. Example: data: [1, 3, 1, 3, 3, 2, 4, 5] 1: 0.25 2: 0.125 3: 0.375 4: 0.125 5: 0.125 PS: i do not want use R only python, matplotlib and if need numpy
[ "Take a look at the hist function in matplotlib: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist\nNumpy also has a histogram function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html\n", "edit: sorry misread your question, i thought you meant only python. Some...
[ 2, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005796146_matplotlib_python.txt
Q: Troubleshooting AttributeError: 'ResultSet' object has no attribute 'findAll' I'm trying to parse the http://www.ted.com/talks page for all the names of the talk. Using BeautifulSoup, here is what I have: import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://www.ted.com/talks") s...
Troubleshooting AttributeError: 'ResultSet' object has no attribute 'findAll'
I'm trying to parse the http://www.ted.com/talks page for all the names of the talk. Using BeautifulSoup, here is what I have: import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://www.ted.com/talks") soup = BeautifulSoup(page) link = soup.findAll(lambda tag: tag.name == 'a' and tag....
[ "link is a collection of Tag objects, which you need to iterate over. For example:\nfor anchor in link:\n print anchor['title']\n\n", "By way of comparison, a pyparsing approach would look like this:\nfrom contextlib import closing\nimport urllib2\nfrom pyparsing import makeHTMLTags, withAttribute\n\n# pull HT...
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005797233_beautifulsoup_python.txt
Q: Python IDLE not accepting quotes Disclaimer: I'm a noob. I've installed Python 3.2 (r32:88452) and ActiveTcl 8.5.9.2 (build 294317) on my OSX 10.6. Both installed without any errors, and I've already managed to run a .PY through Terminal. It runs okay. I run IDLE and it doesn't show any errors. But whenever I pres...
Python IDLE not accepting quotes
Disclaimer: I'm a noob. I've installed Python 3.2 (r32:88452) and ActiveTcl 8.5.9.2 (build 294317) on my OSX 10.6. Both installed without any errors, and I've already managed to run a .PY through Terminal. It runs okay. I run IDLE and it doesn't show any errors. But whenever I press the quote key ('), nothing happens. ...
[ "IDLE uses Tkinter from the Python standard library to supply GUI functionality. Tkinter is an interface to the multi-platform Tk graphical interface, part of Tcl/Tk. Unfortunately, Aqua Tk on OS X does not currently support all of the standard text processing features on OS X.\nThis particular problem appears to...
[ 3, 0 ]
[]
[]
[ "keyboard", "python", "python_idle" ]
stackoverflow_0005797046_keyboard_python_python_idle.txt
Q: how one can scan command output of any program/process to ensure it's success/failure string exists in console using python In python how one can scan command output of any program/process to ensure it's success/failure string exists in console. A: Normally success should be determined from the process's return ...
how one can scan command output of any program/process to ensure it's success/failure string exists in console using python
In python how one can scan command output of any program/process to ensure it's success/failure string exists in console.
[ "Normally success should be determined from the process's return code, not the output it generates. But if you insist on looking at the output then see the stderr argument of the various functions in subprocess.\n", "A more reliable way to do this is to check the process return code (as has already been mentioned...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005797134_python.txt
Q: Deleting words that appear multiple times in a file How can I delete words that appear multiple times in a file and just keep the first one and delete the clones. A: A simple algorithm is to just iterate over all words in the input, adding each one to a set of words you've seen before. If the word was already in...
Deleting words that appear multiple times in a file
How can I delete words that appear multiple times in a file and just keep the first one and delete the clones.
[ "A simple algorithm is to just iterate over all words in the input, adding each one to a set of words you've seen before. If the word was already in the set, remove it.\nHere's an example:\nseen_words = set()\nfor word in words:\n if word not in seen_words:\n print word\n seen_words.add(word)\n\n",...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005797519_python_string.txt
Q: How can I make easy_install.exe not open in a separate window? I'm setting up a new machine and am using 64-bit Python 2.6.6 on Windows 7. I installed a pre-compiled version of setuptools. When I run setuptools from an administrator (or user) command shell, it spawns a new command window and then closes it after ...
How can I make easy_install.exe not open in a separate window?
I'm setting up a new machine and am using 64-bit Python 2.6.6 on Windows 7. I installed a pre-compiled version of setuptools. When I run setuptools from an administrator (or user) command shell, it spawns a new command window and then closes it after completing. I'm unable to see any output. easy_install --help Eve...
[ "I was ultimately able to resolve this. I believe it was the result of the compilation method used for the setuptools binary.\nI had originally used the compiled binaries that were available here:\nhttp://www.lfd.uci.edu/~gohlke/pythonlibs/\nI just had to uninstall the setuptools binary and install one available he...
[ 3 ]
[]
[]
[ "easy_install", "python", "setuptools", "windows_7_x64" ]
stackoverflow_0005775093_easy_install_python_setuptools_windows_7_x64.txt
Q: Markdown emphasis - re substitution How would you implement Markddown's emphasis or bold with regular expressions? Or how is it possible to substitute re \*\*(.*)\*\* with what is inside ** **? A: You can use re.sub(): import re myRegex = re.compile(r"\*\*(.+?)\*\*") string = "some **text** and some **more**" ...
Markdown emphasis - re substitution
How would you implement Markddown's emphasis or bold with regular expressions? Or how is it possible to substitute re \*\*(.*)\*\* with what is inside ** **?
[ "You can use re.sub():\nimport re\n\nmyRegex = re.compile(r\"\\*\\*(.+?)\\*\\*\")\nstring = \"some **text** and some **more**\"\n\noutput = myRegex.sub(r\"\\1\", string)\n\n", "I think Fantasizer has the right idea. \nAdditionally, you should take a look at the Python based Markdown Library\nSpecifically look thr...
[ 3, 2 ]
[]
[]
[ "markdown", "parsing", "python", "regex" ]
stackoverflow_0005797516_markdown_parsing_python_regex.txt
Q: I am failing to get 'required_changes' with python-apt import sys from apt.debfile import DebPackage deb = DebPackage(sys.argv[1]) print(deb.required_changes) I expected the above code to display packages that are supposed to satisfy a dependency of a given deb file, but instead I get a tuple of empty lists: ([],...
I am failing to get 'required_changes' with python-apt
import sys from apt.debfile import DebPackage deb = DebPackage(sys.argv[1]) print(deb.required_changes) I expected the above code to display packages that are supposed to satisfy a dependency of a given deb file, but instead I get a tuple of empty lists: ([], [], []) I made sure to check on a package that I know for ...
[ "I had to call deb.check() to provoke it into returning values for dep.required_changes, etc. Also had to pass it an instance of apt.cache.Cache else it complained:\nimport sys\nfrom apt.cache import Cache\nfrom apt.debfile import DebPackage\n\ncache = Cache()\ndeb = DebPackage(sys.argv[1], cache)\ndeb.check()\npri...
[ 2 ]
[]
[]
[ "apt", "python" ]
stackoverflow_0005795561_apt_python.txt
Q: Encoding and decoding synchsafe integers What is the best way to encode and decode synchsafe integers? A synchsafe integer (used in ID3v2 tags) is one in which the most significant bit is always 0 and is disregarded. For example, 11111111 (255) as a synchsafe integer is 00000001 01111111 (383); and 11111111 11111...
Encoding and decoding synchsafe integers
What is the best way to encode and decode synchsafe integers? A synchsafe integer (used in ID3v2 tags) is one in which the most significant bit is always 0 and is disregarded. For example, 11111111 (255) as a synchsafe integer is 00000001 01111111 (383); and 11111111 11111111 is equivalent to a synchsafe 00000011 0111...
[ "Solution is available on Wikipedia synchsafe page.\n" ]
[ 1 ]
[]
[]
[ "bit_manipulation", "id3", "mp3", "python" ]
stackoverflow_0005798036_bit_manipulation_id3_mp3_python.txt
Q: write a scripting language in python I'm relatively new to programming, and I would like to write a simple scripting language as an exercise, and to learn a bit. I have experience with Python, C, and Ruby, and would like to learn to write a scripting language in Python. What should be my first step? How should I s...
write a scripting language in python
I'm relatively new to programming, and I would like to write a simple scripting language as an exercise, and to learn a bit. I have experience with Python, C, and Ruby, and would like to learn to write a scripting language in Python. What should be my first step? How should I start?
[ "I suppose the first step is to choose a language (or at least style of language). An easy one to start with is the style of Forth, where each \"word\" in the source code is handled in exactly the same way. This makes lexical analysis and parsing nearly trivial.\nAnother small language to start with is Scheme. The ...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "scripting", "scripting_language" ]
stackoverflow_0005798173_python_scripting_scripting_language.txt
Q: What is the reason behind the advice that the substrings in regex should be ordered based on length? longest first >>> p = re.compile('supermanutd|supermanu|superman|superm|super') shortest first >>> p = re.compile('super|superm|superman|supermanu|supermanutd') Why is the longest first regex preferred? A: Alte...
What is the reason behind the advice that the substrings in regex should be ordered based on length?
longest first >>> p = re.compile('supermanutd|supermanu|superman|superm|super') shortest first >>> p = re.compile('super|superm|superman|supermanu|supermanutd') Why is the longest first regex preferred?
[ "Alternatives in Regexes are tested in order you provide, so if first branch matches, then Rx doesn't check other branches. This doesn't matter if you only need to test for match, but if you want to extract text based on match, then it matters.\nYou only need to sort by length when your shorter strings are substrin...
[ 5, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005787670_python_regex.txt
Q: Django Releationship between multiple fields I just need a little help thinking through this, if someone could be so kind. class object_a(models.Model): foo = models.blah bar = models.blah class object_b(models.Model): foop = models.blah barp = models.blah In another model I have a class that I want to h...
Django Releationship between multiple fields
I just need a little help thinking through this, if someone could be so kind. class object_a(models.Model): foo = models.blah bar = models.blah class object_b(models.Model): foop = models.blah barp = models.blah In another model I have a class that I want to have a single relationship with both fields. For e...
[ "Use the contenttypes framework provided by Django:\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Other(models.Model):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005798582_django_django_models_python.txt
Q: How to escape dict from str in python? Come straight to the point. A str object below: s = '{"key1":"value1", "key2":"value2", "key3":"value3"}' As you see, dict is wrapped in str. Now how to escape dict from str? In other words, is it possible d = operate(s), d["key1"] = "value1", and etc? A: >>> ast.literal_ev...
How to escape dict from str in python?
Come straight to the point. A str object below: s = '{"key1":"value1", "key2":"value2", "key3":"value3"}' As you see, dict is wrapped in str. Now how to escape dict from str? In other words, is it possible d = operate(s), d["key1"] = "value1", and etc?
[ ">>> ast.literal_eval('{\"key1\":\"value1\", \"key2\":\"value2\", \"key3\":\"value3\"}')\n{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}\n\n", "i'd use json:\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\nd = json.loads(s)\n\n", "You're looking for eval.\n" ]
[ 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005798831_python.txt
Q: python app engine Model query for models in the same group I have transactional Groups of entities of type db.Model that have a parent defined. I want to query the datastore to only return models that are in the same group. Currently I'm querying all objects of a 'Kind' then removing those that don't have the same...
python app engine Model query for models in the same group
I have transactional Groups of entities of type db.Model that have a parent defined. I want to query the datastore to only return models that are in the same group. Currently I'm querying all objects of a 'Kind' then removing those that don't have the same root entity. Is there a cleaner way to do this - I can't see on...
[ "I think this is what you are looking for. \nget_chlids=ChildObject.all().ancestor(parent1)\n\nTo know more about modeling in appengine. You can have a look here \n", "class TestFamilyTree(unittest.TestCase):\n\ndef test_family_tree(self):\n parent1 = ParentObject()\n parent1.put()\n parent2 = ParentObject()\n...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005793732_google_app_engine_python.txt
Q: Running Cumulative sum of 1d NumPy Array I have a numpy array like x=np.array([1,2,3,4]) I want to create another numpy array y which is the cumulative sum of x, so that y=np.array([1,3,6,10]) What is a good num-Pythonic way to do this? A: y = np.cumsum(x) See http://docs.scipy.org/doc/numpy/reference/ge...
Running Cumulative sum of 1d NumPy Array
I have a numpy array like x=np.array([1,2,3,4]) I want to create another numpy array y which is the cumulative sum of x, so that y=np.array([1,3,6,10]) What is a good num-Pythonic way to do this?
[ "y = np.cumsum(x)\n\nSee http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html\n", "Another option is:\ny = np.add.accumulate(x)\n\nwhich is often times faster than np.cumsum even though the documentation says they are equivalent.\n" ]
[ 27, 8 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005798675_numpy_python.txt
Q: pymongo error when connecting to test:27017 This is my code: con = pymongo.Connection('test',27017) and the error is: (mysite)zjm1126@zjm1126-G41MT-S2:~/桌面/test/mongo$ python a.py Traceback (most recent call last): File "a.py", line 3, in <module> con = pymongo.Connection('test',27017,slave_okay=True) Fil...
pymongo error when connecting to test:27017
This is my code: con = pymongo.Connection('test',27017) and the error is: (mysite)zjm1126@zjm1126-G41MT-S2:~/桌面/test/mongo$ python a.py Traceback (most recent call last): File "a.py", line 3, in <module> con = pymongo.Connection('test',27017,slave_okay=True) File "build/bdist.linux-i686/egg/pymongo/connection....
[ "Obviously there is no mongod daemon running on test:27017.\n" ]
[ 0 ]
[]
[]
[ "mongodb", "python", "ubuntu" ]
stackoverflow_0005799126_mongodb_python_ubuntu.txt
Q: Why are Python's datetime ISO-functions logically incorrect and buggy? I'm kind of stunned that the python datetime .isoformat() function doesn't return correct information. The function correctly returns an ISO 8601-formatted string when a timezone is provided to the fromtimestamp() method. However, the timezone...
Why are Python's datetime ISO-functions logically incorrect and buggy?
I'm kind of stunned that the python datetime .isoformat() function doesn't return correct information. The function correctly returns an ISO 8601-formatted string when a timezone is provided to the fromtimestamp() method. However, the timezone is ignored in the calculation of the resultant. Observe: 13:29 msimsonnet:~...
[ "Make sure you are using \"timezone aware\" datetime objects, not \"naive\" objects.\nIn order to make a timezone \"aware\" datetime object you need to be sure to provide the timezone when you create it.\nMore details are here:\nhttp://docs.python.org/library/datetime.html\nAlso, ISO 8601 does not require timezone,...
[ 17 ]
[]
[]
[ "iso8601", "python" ]
stackoverflow_0005799149_iso8601_python.txt
Q: I'm trying to understand how I can search for three different types of strings The piece of code below takes a string (userstring) and searches all .txt and .log files in a given directory for a match. However, I've added two other variables (userStrHEX & userStrASCII) where I convert the string to hex and ascii t...
I'm trying to understand how I can search for three different types of strings
The piece of code below takes a string (userstring) and searches all .txt and .log files in a given directory for a match. However, I've added two other variables (userStrHEX & userStrASCII) where I convert the string to hex and ascii to search all .txt and .log files against these string formats. Currently, these vari...
[ "The best way is probably to create a regular expression that matches all three strings. Take a look at the documentation for the re module. In a nutshell:\nregex = re.compile( \"(%s|%s|%s)\" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) )\n\nThen instead of \"userstring in line\",...
[ 3 ]
[]
[]
[ "matching", "python", "search", "string" ]
stackoverflow_0005799311_matching_python_search_string.txt
Q: Python game save file I'm writing a game in Python and have come to the point where I need a way of saving the players progress. I was thinking of having the script create a text file and write a couple of lines (for storing stat variables, and the room number) when the player exits the game. But I also need it to...
Python game save file
I'm writing a game in Python and have come to the point where I need a way of saving the players progress. I was thinking of having the script create a text file and write a couple of lines (for storing stat variables, and the room number) when the player exits the game. But I also need it to check if that file exits o...
[ "Two different issues here:\n\nWhat to store in the file and how to store it\nThe logic of when to store and when to load\n\nThe first issue is simpler to address as it's more generic. You have several good options here: one is using Python's ConfigParser class for Windows .ini - like configuration files. Alternati...
[ 4, 0, 0 ]
[]
[]
[ "file", "python", "save" ]
stackoverflow_0005799526_file_python_save.txt
Q: Python module getting too big My module is all in one big file that is getting hard to maintain. What is the standard way of breaking things up? I have one module in a file my_module.py, which I import like this: import my_module "my_module" will soon be a thousand lines, which is pushing the limits of my abilit...
Python module getting too big
My module is all in one big file that is getting hard to maintain. What is the standard way of breaking things up? I have one module in a file my_module.py, which I import like this: import my_module "my_module" will soon be a thousand lines, which is pushing the limits of my ability to keep everything straight. I w...
[ "It depends on what your module is doing actually. Usually it is always a good idea to make your module a directory with an '__init__.py' file inside. So you would first transform your your_module.py to something like your_module/__init__.py.\nAfter that you continue according to your business logic. Here some exam...
[ 5, 2, 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0005799387_python_python_module.txt
Q: Creating a Photo Gallery using Python I'm a novice programmer and thought it would be a fun learning experience to create a photo gallery using python. I've gotten pretty far in the project, but recently got stuck. I have a folder filled with photos. I was able to generate an index page with thumbnails. When I ...
Creating a Photo Gallery using Python
I'm a novice programmer and thought it would be a fun learning experience to create a photo gallery using python. I've gotten pretty far in the project, but recently got stuck. I have a folder filled with photos. I was able to generate an index page with thumbnails. When I click on a thumbnail, a larger version appe...
[ "x=len(next)\n\nfor name in next:\n while x>0:\n x=x-1\n next[x] = next[x].replace(\"jpg\", \"html\")\n\nSince you aren't really resetting x between iterations of for, this probably doesn't do what you intended.\nSame for the next loop starting with:\nfor fname in page:\n while x>0:\n x=x...
[ 1, 1, 0 ]
[]
[]
[ "gallery", "python" ]
stackoverflow_0005787741_gallery_python.txt
Q: Pygame - making a sprite move in the direction it is facing I'm making a top down car racing game and I want to make the car rotate when you press the left and right keys (I’ve already done that part), the sprite's rotation is stored in a variable as degrees. I'd like to be able to make it move according to accele...
Pygame - making a sprite move in the direction it is facing
I'm making a top down car racing game and I want to make the car rotate when you press the left and right keys (I’ve already done that part), the sprite's rotation is stored in a variable as degrees. I'd like to be able to make it move according to acceleration in the direction it is facing. I can figure out the accele...
[ "Trigonometry: The formula to get your coordinate is:\n# cos and sin require radians\nx = cos(radians) * offset\ny = sin(radians) * offset\n\nYou use velocity for offset. (This means a negative velocity will drive backwards).\nso:\ndef rad_to_offset(radians, offset): # insert better func name.\n x = cos(radians...
[ 6, 1 ]
[]
[]
[ "pygame", "python", "rotation", "sprite" ]
stackoverflow_0005346874_pygame_python_rotation_sprite.txt
Q: Legit python if statement? I am new to Python and trying to build a practice project that reads some XML. For some reason this if statement is triggered even for blank whitespace lines: if '<' and '>' in line: Any ideas why? A: You probably want: if ('<' in line) and ('>' in line): Your version is being inter...
Legit python if statement?
I am new to Python and trying to build a practice project that reads some XML. For some reason this if statement is triggered even for blank whitespace lines: if '<' and '>' in line: Any ideas why?
[ "You probably want:\nif ('<' in line) and ('>' in line):\n\nYour version is being interpreted as this:\nif ('<') and ('>' in line):\n\nwhich is probably not what you meant.\nUse parenthesis to make things super-obvious.\n", "Your code says (parethesised for clarity):\nif '<' and ('>' in line):\n\nWhich evaluates ...
[ 9, 9, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005791378_python.txt
Q: modeling user settings in django I would like have additional settings tied to each user in my application (beyond, is_staff, is_admin etc etc). Basically I'd like to have different settings to customize their user experience (ie: don't show tooltips, how many rows to display in results tables, other flags for tur...
modeling user settings in django
I would like have additional settings tied to each user in my application (beyond, is_staff, is_admin etc etc). Basically I'd like to have different settings to customize their user experience (ie: don't show tooltips, how many rows to display in results tables, other flags for turning things on or off). Are there best...
[ "As already said, use UserProfile. To store many flags in the same field there's django-bitfield.\n", "Either put them in the user profile model, or create another model with a one-to-one to User.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python", "settings" ]
stackoverflow_0005797038_django_python_settings.txt
Q: Python and PIL pixel values different for GIF and JPEG I have a question about the pixel values returned from an image opened with PIL load function. I am using the following code: frame = Image.open(fname).load() a = frame[10, 10] If I load a GIF image, a is the integer value 43. But if I convert the image a JPE...
Python and PIL pixel values different for GIF and JPEG
I have a question about the pixel values returned from an image opened with PIL load function. I am using the following code: frame = Image.open(fname).load() a = frame[10, 10] If I load a GIF image, a is the integer value 43. But if I convert the image a JPEG and rerun the code, a is a tuple (253, 254, 100). Why? And...
[ "GIFs are pallettized, whereas JPEGs are RGB. The act of transforming the image disposes of the palette, so you will have to look through the pallette entries in the GIF to find the closest match to the desired color.\n" ]
[ 8 ]
[]
[]
[ "gif", "jpeg", "python", "python_imaging_library" ]
stackoverflow_0005800009_gif_jpeg_python_python_imaging_library.txt
Q: use two variables in django template if tag Hi all not sure how to explain this clearly but here goes.... I need to use two variables like so: {% for client in clients %} {% if user.client.username %} I need {% if user.username %} but the value of username is in client.username from the loop. is there a way t...
use two variables in django template if tag
Hi all not sure how to explain this clearly but here goes.... I need to use two variables like so: {% for client in clients %} {% if user.client.username %} I need {% if user.username %} but the value of username is in client.username from the loop. is there a way to do this?
[ "Are you trying to do something if the value of client.username is equal to the value of user.client.username? If so, you want:\n{% if client.username == user.client.username %} # Works in Django 1.2 and above\n{% ifequal client.username user.client.username %} # Works everywhere\n\n", "If I understand correctly,...
[ 1, 1 ]
[]
[]
[ "django", "django_templates", "google_app_engine", "python" ]
stackoverflow_0005790436_django_django_templates_google_app_engine_python.txt
Q: Is there a cleaner way to chain filters with the Django ORM? I've been doing this: Model.objects.filter(key1=value1)\ .exclude(key2=value2)\ .order_by('key3')\ .select_related(depth=1) but am hating the \. Is there a cleaner style? A: Or, you can take advantage of the fact...
Is there a cleaner way to chain filters with the Django ORM?
I've been doing this: Model.objects.filter(key1=value1)\ .exclude(key2=value2)\ .order_by('key3')\ .select_related(depth=1) but am hating the \. Is there a cleaner style?
[ "Or, you can take advantage of the fact that Django QuerySet operations are cumulative, and lazy:\n myobjects = Model.objects.filter(key1=value1)\n myobjects = myobjects.exclude(key2=value2)\n myobjects = myobjects.order_by('key3')\n myobjects = myobjects.select_related(depth=1)\n\n", "Parens will prevent Python ...
[ 5, 4, 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005798499_django_django_models_python.txt
Q: Replacing images in PDF documents with Python? We generate PDF documents with RGB images stored in a CMS. As part of the PDF processing we sometimes have the need to convert the RGB images to CMYK (for print productions). Converting the images from RGB to CMYK seems to be feasible with Python using LittleCMS and ...
Replacing images in PDF documents with Python?
We generate PDF documents with RGB images stored in a CMS. As part of the PDF processing we sometimes have the need to convert the RGB images to CMYK (for print productions). Converting the images from RGB to CMYK seems to be feasible with Python using LittleCMS and the PyLittleCMS bindings (plus the ICC color profile...
[ "I don't think there's any free Python tools that do exactly what you want. Here are some options:\nPoDoFo doesn't have mature Python bindings but can read and write PDFs, has support for PDF images and color spaces.\nPDFMiner is a pure-Python PDF parser but it doesn't do much with images. This is a start, but wo...
[ 1 ]
[]
[]
[ "cmyk", "pdf", "python", "rgb" ]
stackoverflow_0005799842_cmyk_pdf_python_rgb.txt
Q: Deriving rules about column dependencies on integer data? I have lots of data like the following: <A,B,C,D,E,F> ... I am wondering if there is a way to determine the association between the different columns in the vector. This association is consistent in the entire data. For instance, one rule is if (A changes ...
Deriving rules about column dependencies on integer data?
I have lots of data like the following: <A,B,C,D,E,F> ... I am wondering if there is a way to determine the association between the different columns in the vector. This association is consistent in the entire data. For instance, one rule is if (A changes by 1) B changes by 1 I want to be able to generate these rul...
[ "The technique you have described, though a use case, is usually known as Association Rules or Market Basket Analysis. (The latter term reflects the earliest applications of these algorithms, which was the study of consumer behavior in supermarkets--i.e., if a shopper buys a jar of peanut butter, how often do they ...
[ 3, 1 ]
[]
[]
[ "language_agnostic", "machine_learning", "python", "rules" ]
stackoverflow_0005799026_language_agnostic_machine_learning_python_rules.txt
Q: "Auto code" algorithm for signal flow based programming? Let's assume I've got a graph of a signal flow based "programm" (e.g. something similar to Simulink). I.e. I've got a directed graph with a few starting nodes and a few end nodes as well as lots of nodes inbetween (and hopefully no circular relation) Is ther...
"Auto code" algorithm for signal flow based programming?
Let's assume I've got a graph of a signal flow based "programm" (e.g. something similar to Simulink). I.e. I've got a directed graph with a few starting nodes and a few end nodes as well as lots of nodes inbetween (and hopefully no circular relation) Is there a good and/or well known algorithm (perhaps even available a...
[ "Are you looking for some kind of variation on a Topological Sort? \nSince you know the starting nodes, you can start the algorithm from them. When you meet an \"operation\" node, you create the computation with the nodes leading you to it. Naturally, the graph should be consistent in some ways specific to your pro...
[ 3 ]
[]
[]
[ "algorithm", "graph", "graph_theory", "graph_traversal", "python" ]
stackoverflow_0005801169_algorithm_graph_graph_theory_graph_traversal_python.txt
Q: Tweepy and SocialRegistration troubles I've successfully installed Tweepy. I've successfully installed SocialRegistration (Twitter oauth). But now i'm trying to do things in Tweepy that require authentication and it's not working corrrectly. I keep getting the "authentication required" error page. How can I "conne...
Tweepy and SocialRegistration troubles
I've successfully installed Tweepy. I've successfully installed SocialRegistration (Twitter oauth). But now i'm trying to do things in Tweepy that require authentication and it's not working corrrectly. I keep getting the "authentication required" error page. How can I "connect" SocialRegistration w/ Tweepy? Do I need ...
[ "It's not really clear what you are trying to achieve with the two modules (social-registration and tweepy)\nI'm assuming that you are trying to use tweepy API to do something that requires authentication (eg status updates), so here's how to do an simple oauth authentication in tweepy.\n#Requirements:\n#tweepy\n#c...
[ 1, 0 ]
[]
[]
[ "django", "oauth", "python", "tweepy", "twitter" ]
stackoverflow_0005147700_django_oauth_python_tweepy_twitter.txt
Q: Incorrect response for IMAP command "UID COPY" in python's imaplib? here is my goal: 1. I'm using telnet connection for copying one email from Inbox to Archive: . uid copy 1102 "[Gmail]/All Mail" . OK [COPYUID 646471928 1102 1237] (Success) 2. The same account, copying other message to Archive: ... creating IMAP4...
Incorrect response for IMAP command "UID COPY" in python's imaplib?
here is my goal: 1. I'm using telnet connection for copying one email from Inbox to Archive: . uid copy 1102 "[Gmail]/All Mail" . OK [COPYUID 646471928 1102 1237] (Success) 2. The same account, copying other message to Archive: ... creating IMAP4_SLL instance, logging in, etc ... res = mserver.uid("copy", "1107", "[G...
[ "This is not an incorrect response. The IMAP standard does not specify that the UID of the new message is to be returned by the COPY command. It do, however, specify that the new message shall have the date and flags preserved, so you can write some logic to find the new copy in the new folder.\n" ]
[ 2 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0005801386_imap_imaplib_python.txt
Q: scala: trait for a Function object with variable length arguments? i'm writing some scala code to emulate a python decorator. i'm considering implementing this by having the decorator extend a Function trait. the issue is that i want this decorator to extend a Function that accepts any number of arguments, and the...
scala: trait for a Function object with variable length arguments?
i'm writing some scala code to emulate a python decorator. i'm considering implementing this by having the decorator extend a Function trait. the issue is that i want this decorator to extend a Function that accepts any number of arguments, and the only Function traits i can find only allow a specific number of argumen...
[ "scala> val bar: (Int*) => Int = {args => args.sum}\nbar: (Int*) => Int = <function1>\n\nscala> bar(1,2,3)\nres4: Int = 6\n\nUnfortunatelly, you can't use type inference here:\nscala> val bar = {args: Int* => args.sum}\n<console>:1: error: ';' expected but identifier found.\n val bar = {args: Int* => args.sum...
[ 2, 0, 0 ]
[]
[]
[ "decorator", "python", "scala" ]
stackoverflow_0005798045_decorator_python_scala.txt
Q: Upload a file using django model issue file_name = models.FileField(upload_to=settings.PATH, verbose_name=_('Upload_Path'), \ null=True, blank=True, help_text=' .zip file only') When I rendring this field using forms it Shows me button <input type="file" name="file" id="id_file"> ...
Upload a file using django model issue
file_name = models.FileField(upload_to=settings.PATH, verbose_name=_('Upload_Path'), \ null=True, blank=True, help_text=' .zip file only') When I rendring this field using forms it Shows me button <input type="file" name="file" id="id_file"> and beside this button No file chosen text c...
[ "It depends upon the browser you are using. Jquery has nothing to do with it.. Django forms just create a file field. Browser displays the file open dialog and added file in their own style. This has nothing to do with your code.\n" ]
[ 1 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0005801418_django_jquery_python.txt
Q: Python, context sensitive string substitution Is it possible to do something like this in Python using regular expressions? Increment every character that is a number in a string by 1 So input "123ab5" would become "234ab6" I know I could iterate over the string and manually increment each character if it's a nu...
Python, context sensitive string substitution
Is it possible to do something like this in Python using regular expressions? Increment every character that is a number in a string by 1 So input "123ab5" would become "234ab6" I know I could iterate over the string and manually increment each character if it's a number, but this seems unpythonic. note. This is not ...
[ "a = \"123ab5\"\n\nb = ''.join(map(lambda x: str(int(x) + 1) if x.isdigit() else x, a))\n\nor: \nb = ''.join(str(int(x) + 1) if x.isdigit() else x for x in a)\n\nor:\nimport string\nb = a.translate(string.maketrans('0123456789', '1234567890'))\n\nIn any of these cases:\n# b == \"234ab6\"\n\nEDIT - the first two map...
[ 5, 1, 0 ]
[]
[]
[ "python", "regex", "string_substitution" ]
stackoverflow_0005801564_python_regex_string_substitution.txt
Q: Multiprocessing Python Class Object So I let's say I have a Python class: class Something: def __init__(self, a, b, c): initialize_object_with_args() def run(self): do_something() def result(self): return result Now I want to create multiple objects of that class (all of whic...
Multiprocessing Python Class Object
So I let's say I have a Python class: class Something: def __init__(self, a, b, c): initialize_object_with_args() def run(self): do_something() def result(self): return result Now I want to create multiple objects of that class (all of which are independent - no need for data exch...
[ "Take a look at http://wiki.python.org/moin/ParallelProcessing , especially the http://pypi.python.org/pypi/pprocess .\nThis small library could do exactly what you want: http://honeypot.net/yet-another-python-map\n", "It seems to be very similar to this\nfrom multiprocessing import Pool\n\ndef func(*args):\n ...
[ 0, 0 ]
[]
[]
[ "multithreading", "parallel_processing", "python" ]
stackoverflow_0005801669_multithreading_parallel_processing_python.txt
Q: How can I get the file size on the Internet knowing only the URL I want to get the size of an http://.. file before I download it. I don't know how to use http request. Thanks! A: import urllib2 f = urllib2.urlopen("http://your-url") size= f.headers["Content-Length"] print size A: The HTTP HEAD method was inve...
How can I get the file size on the Internet knowing only the URL
I want to get the size of an http://.. file before I download it. I don't know how to use http request. Thanks!
[ "import urllib2\nf = urllib2.urlopen(\"http://your-url\")\nsize= f.headers[\"Content-Length\"]\nprint size\n\n", "The HTTP HEAD method was invented for scenarios like this (wanting to know data about a response without fetching the response itself). Provided the server returns a Content-Length header (and support...
[ 13, 12, 5, 4 ]
[]
[]
[ "download", "file", "http", "python" ]
stackoverflow_0003601240_download_file_http_python.txt
Q: PyUSB/ similar USB functionality for Python 2.7 Is it possible to get a program like PyUSB, or similar, for python version 2.7? A: I'm not sure what the problem is - the PyUSB page says it supports Python >= 2.4. From other Googled web sources I see people have used it with 2.7 - does it not work for you? What i...
PyUSB/ similar USB functionality for Python 2.7
Is it possible to get a program like PyUSB, or similar, for python version 2.7?
[ "I'm not sure what the problem is - the PyUSB page says it supports Python >= 2.4. From other Googled web sources I see people have used it with 2.7 - does it not work for you? What is the exact trouble you're having?\n" ]
[ 5 ]
[]
[]
[ "python", "python_2.7", "pyusb" ]
stackoverflow_0005802187_python_python_2.7_pyusb.txt
Q: Non-consuming regular expression split in Python How can a string be split on a separator expression while leaving that separator on the preceding string? >>> text = "This is an example. Is it made up of more than once sentence? Yes, it is." >>> re.split("[\.\?!] ", text) ['This is an example', 'Is it made up of m...
Non-consuming regular expression split in Python
How can a string be split on a separator expression while leaving that separator on the preceding string? >>> text = "This is an example. Is it made up of more than once sentence? Yes, it is." >>> re.split("[\.\?!] ", text) ['This is an example', 'Is it made up of more than one sentence', 'Yes, it is.'] I would like t...
[ ">>> re.split(\"(?<=[\\.\\?!]) \", text)\n['This is an example.', 'Is it made up of more than once sentence?', 'Yes, it is.']\n\nThe crucial thing is the use of a look-behind assertion with ?<=.\n", "import re\n\ntext = \"This is an example.A particular case.Made up of more \"\\\n \"than once sentence?Yes, ...
[ 11, 10 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005801945_python_regex.txt
Q: Using numpy.argmax() on multidimensional arrays I have a 4 dimensional array, i.e., data.shape = (20,30,33,288). I am finding the index of the closest array to n using index = abs(data - n).argmin(axis = 1), so index.shape = (20,33,288) with the indices varying. I would like to use data[index] = "values" with v...
Using numpy.argmax() on multidimensional arrays
I have a 4 dimensional array, i.e., data.shape = (20,30,33,288). I am finding the index of the closest array to n using index = abs(data - n).argmin(axis = 1), so index.shape = (20,33,288) with the indices varying. I would like to use data[index] = "values" with values.shape = (20,33,288), but data[index] returns th...
[ "You should be able to access the maximum values indexed by index using numpy.indices():\nx, z, t = numpy.indices(index.shape)\ndata[x, index, z, t]\n\n", "If I understood you correctly, this should work:\nnumpy.put(data, index, values)\n\nI learned something new today, thanks.\n" ]
[ 15, 1 ]
[]
[]
[ "closest", "indexing", "numpy", "python" ]
stackoverflow_0005798364_closest_indexing_numpy_python.txt
Q: PyParsing OR statement This is going to end up being really simple, but I'm trying to match one of the two patterns: "GET /ligonier-broadcast-media/mp3/rym20110421.mp3 HTTP/1.1" or - I've tried something like this: key = Word(alphas + nums + "/" + "-" + "_" + "." + "?" + "=" + "%" + "&") uri = Or("-" | Group( ...
PyParsing OR statement
This is going to end up being really simple, but I'm trying to match one of the two patterns: "GET /ligonier-broadcast-media/mp3/rym20110421.mp3 HTTP/1.1" or - I've tried something like this: key = Word(alphas + nums + "/" + "-" + "_" + "." + "?" + "=" + "%" + "&") uri = Or("-" | Group( Suppress("...
[ "In general, the Or, And, MatchFirst, and Each classes are very rarely used overtly in pyparsing. The recommended style is to use their analogous operator overloads. In your case, you are using both forms, and it is just getting in your way.\nHere is your expression, after a little cleaning up:\nkey = Word(alphanu...
[ 19, 1 ]
[]
[]
[ "amazon_s3", "logging", "pyparsing", "python" ]
stackoverflow_0005798994_amazon_s3_logging_pyparsing_python.txt
Q: Executing a command and storing its output in a variable I'm currently trying to write a python script that, among many things, calls an executable and stores what that executable sends to stdout in a variable. Here is what I have: 1 #!/usr/bin/python 2 import subprocess 3 4 subprocess.call("./pmm", shell=...
Executing a command and storing its output in a variable
I'm currently trying to write a python script that, among many things, calls an executable and stores what that executable sends to stdout in a variable. Here is what I have: 1 #!/usr/bin/python 2 import subprocess 3 4 subprocess.call("./pmm", shell=True) How would I get the output of pmm to be stored in a var...
[ "In Python 2.7 (and 3.1 or above), you can use subprocess.check_output(). Example from the documentation:\n>>> subprocess.check_output([\"ls\", \"-l\", \"/dev/null\"])\n'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n\n", "p = subprocess.Popen([\"./pmm\"], shell=False, stdout=subprocess.PIPE)\noutput = ...
[ 6, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005802412_python.txt
Q: ipython -pylab debugging: Can I stop the execution at a specific line and drop into the shell? When writing python code (mostly numpy + matplotlib), I usually just type the code in vim and run the program to test it: python2 foo.py Occasionally, when this is not sufficient and I need to inspect the problem more t...
ipython -pylab debugging: Can I stop the execution at a specific line and drop into the shell?
When writing python code (mostly numpy + matplotlib), I usually just type the code in vim and run the program to test it: python2 foo.py Occasionally, when this is not sufficient and I need to inspect the problem more thoroughly, I just launch the program in ipython: ipython -pylab foo.py, and then inspect the variabl...
[ "You can import the pdb module into the code and then add a pdb.set_trace() call where you would like to have the code stop. Ipython will drop into the interactive debugger, and you are free to step though your code as you wish.\n", "You can drop into a IPython debug session by inserting the following code at the...
[ 5, 5 ]
[]
[]
[ "debugging", "matplotlib", "numpy", "python" ]
stackoverflow_0005801906_debugging_matplotlib_numpy_python.txt
Q: python temporary files I have this code: import tempfile def tmp_me(): tmp = tempfile.NamedTemporaryFile() tmp1 = tempfile.NamedTemporaryFile() lst = [tmp.name, tmp1.name] return lst def exit_dialog(): lst = tmp_me() print lst import filecmp eq = filecmp.cmp(lst[0],lst[1]) prin...
python temporary files
I have this code: import tempfile def tmp_me(): tmp = tempfile.NamedTemporaryFile() tmp1 = tempfile.NamedTemporaryFile() lst = [tmp.name, tmp1.name] return lst def exit_dialog(): lst = tmp_me() print lst import filecmp eq = filecmp.cmp(lst[0],lst[1]) print eq exit_dialog() I need ...
[ "Error 2 is that the file is not found (ERROR_FILE_NOT_FOUND).\nNamedTemporaryFile has the delete parameter which is by default set to True. Are you sure that the file is not being immediately deleted at the return of your tmp_me method?\nYou could try using:\ntempfile.NamedTemporaryFile(delete=False)\n\n", "Have...
[ 12, 8, 4, 2 ]
[]
[]
[ "python", "temporary_files" ]
stackoverflow_0005802684_python_temporary_files.txt
Q: python sqlite "create table if not exists" problem I'm having an issue using sqlite to create a table only if it doesn't exist. Basically, I have a table that I'm dropping and remaking once in a long while. However, if the table already existed (before I drop and remake it), then I get the following error when t...
python sqlite "create table if not exists" problem
I'm having an issue using sqlite to create a table only if it doesn't exist. Basically, I have a table that I'm dropping and remaking once in a long while. However, if the table already existed (before I drop and remake it), then I get the following error when trying to insert for the first time: Traceback (most rece...
[ "I can duplicate the issue with the following simplified script:\nimport sqlite3\n\nlocation = 'data'\ntable_name = 'table_name'\n\nconn = sqlite3.connect(location)\nc = conn.cursor()\n\nsql = 'create table if not exists ' + table_name + ' (id integer)'\nc.execute(sql)\n\nsql = 'drop table ' + table_name\nc.execute...
[ 40, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0005801170_python_sqlite.txt
Q: which is the best python mongodb lib I am a mongodb beginner and I use pymongo. I want to know it is the best to control mongodb using python. A: Pymongo is the best tool for Mongodb in python. And it's the widely used tool. It's getting popular drastically and it has seen so many versions current being PyMong...
which is the best python mongodb lib
I am a mongodb beginner and I use pymongo. I want to know it is the best to control mongodb using python.
[ "Pymongo is the best tool for Mongodb in python. And it's the widely used tool. It's getting popular drastically and it has seen so many versions current being PyMongo 1.10.1. I think you are in the right direction using pymongo\n", "PyMongo is best if you don't need much of schema, ORMs, otherwise as Bastian s...
[ 4, 3, 0 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0005803020_mongodb_python.txt