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: in python, using in, get specific elements I want to do something like this, but in python : select * from [list] where [element at index n] = 'hello' So far, I have this cells = [' ','hello',' ',' ',' ',' ',' ',' ',' '] emptySpots = [] for s in range(len(cells)): if cells[s] == 'hello': ...
in python, using in, get specific elements
I want to do something like this, but in python : select * from [list] where [element at index n] = 'hello' So far, I have this cells = [' ','hello',' ',' ',' ',' ',' ',' ',' '] emptySpots = [] for s in range(len(cells)): if cells[s] == 'hello': emptySpots.append(s) This gives me a lis...
[ "Your question is confusing. Your code does not get the indexes of the empty cells but of the element hello.\nIt seems you have two questions in one?\nIf you really want to get the number of \"empty cells\" like you claim in your last sentence, you can use list.count:\nempty_spots = cells.count(' ')\n\n", "I wasn...
[ 5, 4, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005904912_list_python.txt
Q: Replace 'add new' with 'select existing' for an object on the admin page in Django I think this is fairly simple, but I'm new to Django and I can't find any questions that match mine. Here is my model-- class Team: # attributes for team class Driver: # attributes for driver team = foreign_key(Team, bl...
Replace 'add new' with 'select existing' for an object on the admin page in Django
I think this is fairly simple, but I'm new to Django and I can't find any questions that match mine. Here is my model-- class Team: # attributes for team class Driver: # attributes for driver team = foreign_key(Team, blank=True, null=True) Now each team is required to have three drivers, and some drivers ...
[ "I'm thinking that the following will let you achieve what you want. You can use this to limit the number of Driver objects attached to a Team as well.\nI would also make sure to check the number of Driver objects on a team in the Driver save method; this would ensure that if you are adding Driver objects to a Team...
[ 0 ]
[]
[]
[ "admin", "django", "django_admin", "python" ]
stackoverflow_0005904673_admin_django_django_admin_python.txt
Q: Python monitor serial port (RS-232) handshake signals I need to monitor the status of serial port signals (RI, DSR, CD,CTS). Looping and polling with 'serial' library, (eg. using functions getRI) is too cpu intensive and response time is not acceptable. Is there a solutions with python? A: On Linux is possible t...
Python monitor serial port (RS-232) handshake signals
I need to monitor the status of serial port signals (RI, DSR, CD,CTS). Looping and polling with 'serial' library, (eg. using functions getRI) is too cpu intensive and response time is not acceptable. Is there a solutions with python?
[ "On Linux is possible to monitor che state change of a signal pin of an RS-232 port using interrupt based notification throught the blocking syscall TIOCMIWAIT:\nfrom serial import Serial\nfrom fcntl import ioctl\nfrom termios import (\n TIOCMIWAIT,\n TIOCM_RNG,\n TIOCM_DSR,\n TIOCM_CD,\n TIOCM_CTS\...
[ 14 ]
[]
[]
[ "python", "serial_port" ]
stackoverflow_0005904895_python_serial_port.txt
Q: compare two files I have two files in this format file1= filename val1 val2 file2= filename val3 val4 I want to compare filenames and if they have the same names , i want to get a third file like this- filename val1 val2 val3 val4 I am picking a filename from file1 and going across file2 to see if i get it. Then...
compare two files
I have two files in this format file1= filename val1 val2 file2= filename val3 val4 I want to compare filenames and if they have the same names , i want to get a third file like this- filename val1 val2 val3 val4 I am picking a filename from file1 and going across file2 to see if i get it. Then seeking pointer back t...
[ "It sounds like what you're looking for is the standard join command (not Python, but a standard Unix shell utility). Here's a snip from the manual page on a system (that seems to have more detail than the Linux man page for join):\n join phonedir names\n\n If the phonedir file contains the following ...
[ 4, 2 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0005905680_python_text_processing.txt
Q: does a python object need to be given the same number of arguments as its class? So I came across this class definition in a pygame tutorial: class GameObject: def _init_(self,image,height,speed): self.speed = speed self.image = image self.pos = image.get_squ...
does a python object need to be given the same number of arguments as its class?
So I came across this class definition in a pygame tutorial: class GameObject: def _init_(self,image,height,speed): self.speed = speed self.image = image self.pos = image.get_squarerect().move(0,height) def move(self): self.pos = self.pos.m...
[ "The self object is supplied implicitly on every method call.\nFor __init__, it's a brand new object and Python supplies a reference to that brand new object as self.\nFor method calls other than __init__, you actually supply the object which is referenced by self, not as an explicit argument but in the object on w...
[ 1, 1, 0 ]
[]
[]
[ "class", "pygame", "python" ]
stackoverflow_0005905615_class_pygame_python.txt
Q: Defining a class in Python class Car: pass class Car(): pass What is the difference between these two? and, a = Car a = Car() also, what is the difference between these two above? Best Regards A: the first statement, a = Car simply makes a an alias to Car class. So after you do that, you could do b...
Defining a class in Python
class Car: pass class Car(): pass What is the difference between these two? and, a = Car a = Car() also, what is the difference between these two above? Best Regards
[ "the first statement, a = Car simply makes a an alias to Car class. So after you do that, you could do b = a() and it would be the same as b = Car()\nOnce you attach the () at the end, it makes python actually initialize the class (either __call__ or just initialize, but you don't have to worry about that), and a b...
[ 8, 1 ]
[]
[]
[ "class", "class_design", "python" ]
stackoverflow_0005905786_class_class_design_python.txt
Q: Python to SQL: list of lists I am currently facing a problem in exporting a python list of list into mySQL DB. Iam using MySQLdb for the same and utilising the executemany command. For example, I have a list of list: k1=[[['Bob', 'Alfred', 'Jen'], ['123 Elm Street', '55 Ninth Ave', '1 Paved Rd'], [00123, 34565, 3...
Python to SQL: list of lists
I am currently facing a problem in exporting a python list of list into mySQL DB. Iam using MySQLdb for the same and utilising the executemany command. For example, I have a list of list: k1=[[['Bob', 'Alfred', 'Jen'], ['123 Elm Street', '55 Ninth Ave', '1 Paved Rd'], [00123, 34565, 30094], ['Newark', 'Salinas', 'Los ...
[ "I don't think this is really a SQL question; let's just concentrate on getting the data in the right form before you even try to call executemany().\nYour k1 example is a list of 2 lists, each of which inner lists is also a list of lists, which are names/address components. So you actually have a list of lists of ...
[ 3, 3, 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0005905721_mysql_mysql_python_python.txt
Q: Linux blocking signals to Python init This is a follow up to my other post Installing signal handler with Python. In short, Linux blocks all signals to PID 1 (including SIGKILL) unless Init has installed a signal handler for a particular signal; as to prevent kernel panic if someone were to send a termination sig...
Linux blocking signals to Python init
This is a follow up to my other post Installing signal handler with Python. In short, Linux blocks all signals to PID 1 (including SIGKILL) unless Init has installed a signal handler for a particular signal; as to prevent kernel panic if someone were to send a termination signal to PID1. The issue I've been having, i...
[ "I did a bit of debugging under KVM and I found that the kernel is delivering signals to pid 1 when the signal handlers are installed by the standard signal module. However, when the signal is received \"something\" causes a clone of the process to be spawned, rather than printing the expected output.\nHere is the...
[ 8, 2 ]
[]
[]
[ "c", "init", "linux", "python", "signals" ]
stackoverflow_0005844364_c_init_linux_python_signals.txt
Q: Python URL handlers for web browsers How can I use Python to add a handler to a browser, so when someone clicks a link like foo://foobar/ it'll open my program to handle it? Ideally there would be a way to do it cross-platform, but I recognize that OS-specific code will probably be needed. A: GNOME Windows OS X ...
Python URL handlers for web browsers
How can I use Python to add a handler to a browser, so when someone clicks a link like foo://foobar/ it'll open my program to handle it? Ideally there would be a way to do it cross-platform, but I recognize that OS-specific code will probably be needed.
[ "GNOME\nWindows\nOS X\n" ]
[ 3 ]
[ "I am not sure, why you are looking for OS Specific code. But there is module called webbrowser, which you are use in your programs as a handler which can open your platform specific browser. Does this help?\n" ]
[ -1 ]
[ "browser_extension", "python", "url" ]
stackoverflow_0005905957_browser_extension_python_url.txt
Q: Django Development: PyMongo or MongoEngine ... and why? Trying to decide between these two, looking for some solid feedback. Thanks. A: MongoEngine is an ORM that wraps PyMongo. Using PyMongo directly will probably be marginally faster/more efficient. If you really like Django's ORM you'll probably like MongoEng...
Django Development: PyMongo or MongoEngine ... and why?
Trying to decide between these two, looking for some solid feedback. Thanks.
[ "MongoEngine is an ORM that wraps PyMongo. Using PyMongo directly will probably be marginally faster/more efficient. If you really like Django's ORM you'll probably like MongoEngine. Look at their documentation, play with their APIs and decide for yourself. I rather like both. You could also take a look at MongoKit...
[ 5 ]
[]
[]
[ "django", "mongodb", "orm", "python" ]
stackoverflow_0005906015_django_mongodb_orm_python.txt
Q: Best practices for getting the most testing coverage with Django/Python? My tests are seriously lacking and I don't have a whole lot of faith in them. What are some of the best practices for getting the most testing coverage I can using Django/Python? I've been taking a look at Freshen and Lettuce, which look pret...
Best practices for getting the most testing coverage with Django/Python?
My tests are seriously lacking and I don't have a whole lot of faith in them. What are some of the best practices for getting the most testing coverage I can using Django/Python? I've been taking a look at Freshen and Lettuce, which look pretty promising, but I can't use them for everything, can I? I'm looking for advi...
[ "\nStop coding.\nWrite the tests for the things your application is supposed to do.\n\nFirst, use the built-in Django testing. Write model tests as TestCase classes inside your models.py. \nDo that now. Before reading any further. Add django.test.TestCase classes right now that create, modify and retrieve mode...
[ 37, 12, 7 ]
[]
[]
[ "code_coverage", "django", "python", "testing", "unit_testing" ]
stackoverflow_0005901139_code_coverage_django_python_testing_unit_testing.txt
Q: I'm trying to send email through 'localhost' in Python but it keeps giving me an "Error 61" I'm running a Mac OS X and used postfix to enable localhost. This is the error message I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2....
I'm trying to send email through 'localhost' in Python but it keeps giving me an "Error 61"
I'm running a Mac OS X and used postfix to enable localhost. This is the error message I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) F...
[ "Use netstat to verify that a SMTP server is bound to port 25 of an appropriate interface in the first place.\n", "Check the postfix log file, which might be at /var/log/mail or something similar, depending on how you installed postfix.\n" ]
[ 2, 0 ]
[]
[]
[ "email", "localhost", "python" ]
stackoverflow_0005906235_email_localhost_python.txt
Q: Does Satchmo's Authorize.net payment module support MasterCard partial authorizations? I have a Django app that uses Satchmo in conjunction with Authorize.net. Authorize.net is now supporting partial authorization for MasterCard and Discover cards, as noted here and here. Does anyone know if these changes are supp...
Does Satchmo's Authorize.net payment module support MasterCard partial authorizations?
I have a Django app that uses Satchmo in conjunction with Authorize.net. Authorize.net is now supporting partial authorization for MasterCard and Discover cards, as noted here and here. Does anyone know if these changes are supported by the Authorize.net payment module in Satchmo? I found a mailing list thread on the s...
[ "The short answer is no, Satchmo's Authorize.net module does not support partial authorization out of the box. The long answer, though, is that it may be easier than you think to create what you want:\n\nThis documentation describes exactly what you need in order to post a partial payment to the\nAuthorize.net syst...
[ 4 ]
[]
[]
[ "authorize.net", "python", "satchmo" ]
stackoverflow_0005823198_authorize.net_python_satchmo.txt
Q: Shutting down gracefully from ThreadingTCPServer I've created a simple test app (Python 2.6.1) that runs a ThreadingTCPServer, based on the example here. If the client sends a command "bye" I want to shut down the server and exit cleanly from the application. The exit part works OK, but when I try to re-run the ...
Shutting down gracefully from ThreadingTCPServer
I've created a simple test app (Python 2.6.1) that runs a ThreadingTCPServer, based on the example here. If the client sends a command "bye" I want to shut down the server and exit cleanly from the application. The exit part works OK, but when I try to re-run the app, I get: socket.error: [Errno 48] Address already i...
[ "If you have not already found an answer, I believe this may assist...\nHow to close a socket left open by a killed program?\nHowever, this is the same solution offered by Alex, so perhaps this is just an opportunity to close an old question.\n" ]
[ 1 ]
[]
[]
[ "python", "socketserver", "tcp" ]
stackoverflow_0003137640_python_socketserver_tcp.txt
Q: Python nested data persistance I need a way to store system configuration data and i've found it easy to understand / comprehend with nested classes: >>> class syscnf: ... class netwrk: ... class iface: ... class eth0: ... address = '192.168.0.100' ... netmas...
Python nested data persistance
I need a way to store system configuration data and i've found it easy to understand / comprehend with nested classes: >>> class syscnf: ... class netwrk: ... class iface: ... class eth0: ... address = '192.168.0.100' ... netmask = '255.255.255.0' ... ...
[ "All the cool kids use json. Also, having your structure use instances instead of bare classes will make it much easier to serialize.\n", "I agree with Ignacio Vazquez-Abrams that using a JSON-like structure would make it a lot easier to work with, meaning you might instead have a structure like:\nsyscnf = {\n '...
[ 4, 3 ]
[]
[]
[ "data_structures", "persistence", "python" ]
stackoverflow_0005906225_data_structures_persistence_python.txt
Q: What is the most common way to configure static files in debug and production for Django When developing a Django application in debug mode, I serve static files using the following code: if settings.DEBUG: urlpatterns += patterns('', (r'^m/(?P<path>.*)$', serve, { 'document_root' : os.path...
What is the most common way to configure static files in debug and production for Django
When developing a Django application in debug mode, I serve static files using the following code: if settings.DEBUG: urlpatterns += patterns('', (r'^m/(?P<path>.*)$', serve, { 'document_root' : os.path.join(os.path.dirname(__file__), "media") }) ) I am using nginx as a front end to...
[ "Using Django 1.3 django.contrib.staticfiles will take care of serving everything for you during development. You don't need to do anything particular in the urls.py. I wrote a little guide for myself after the Django 1.3 update that covers the settings to use:\n# idiom to get path of project\nimport os\nPROJECT_PA...
[ 10, 2 ]
[]
[]
[ "django", "nginx", "python" ]
stackoverflow_0005906197_django_nginx_python.txt
Q: Installing Poster(Streaming HTTP uploads and multipart/form-data encoding) I've been searching the net for instructions on how to install Poster(Streaming HTTP uploads and multipart/form-data encoding) for various OSes (especially Ubuntu and Windows).The official website http://atlee.ca/software/poster/ has awesom...
Installing Poster(Streaming HTTP uploads and multipart/form-data encoding)
I've been searching the net for instructions on how to install Poster(Streaming HTTP uploads and multipart/form-data encoding) for various OSes (especially Ubuntu and Windows).The official website http://atlee.ca/software/poster/ has awesome sample scripts and examples but nothing on how to install the module on variou...
[ "It's quite simple, you can use easy_install or pip, in your terminal run:\neasy_install poster\n\nor\npip install poster\n\nIf you don't have easy_install or pip, install distribute first:\ncurl -O http://python-distribute.org/distribute_setup.py\npython distribute_setup.py\n\nI recommend using pip and reading the...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0005906878_python.txt
Q: Why isn't my yaml being parsed correctly? Does anyone know why this yaml is parsed and read correctly by my app development: autocreate_indexes: false allow_dynamic_fields: true include_root_in_json: false parameterize_keys: true persist_in_safe_mode: false raise_not_found_error: true ...
Why isn't my yaml being parsed correctly?
Does anyone know why this yaml is parsed and read correctly by my app development: autocreate_indexes: false allow_dynamic_fields: true include_root_in_json: false parameterize_keys: true persist_in_safe_mode: false raise_not_found_error: true reconnect_time: 3 uri: mongodb://app:app@f...
[ "The solution was to add the following to my boot.rb\nrequire 'yaml'\nYAML::ENGINE.yamler= 'syck'\n\n", "PyYAML seems to parse it fine:\n>>> yaml.load(s)\n<<< \n{'defaults': {'allow_dynamic_fields': True,\n 'autocreate_indexes': False,\n 'include_root_in_json': False,\n 'par...
[ 1, 0 ]
[]
[]
[ "python", "ruby", "yaml" ]
stackoverflow_0005906848_python_ruby_yaml.txt
Q: Is this description of alternatives in regexes wrong? The wikipedia article on PEG states: The fundamental difference between context-free grammars and parsing expression grammars is that the PEG's choice operator is ordered. If the first alternative succeeds, the second alternative is ignored. Thus ord...
Is this description of alternatives in regexes wrong?
The wikipedia article on PEG states: The fundamental difference between context-free grammars and parsing expression grammars is that the PEG's choice operator is ordered. If the first alternative succeeds, the second alternative is ignored. Thus ordered choice is not commutative, unlike unordered choice...
[ "\"regex\" != \"regular expression\". The latter are pure and simple and of interest only to theoretical computer scientists and symbolic mathematicians.\n\"ordered choice\" is an implementation option of regex processors.\nYou say \"if the alternatives are substrings of each other; then regexes do not behave accor...
[ 1 ]
[]
[]
[ "peg", "python", "regex" ]
stackoverflow_0005906464_peg_python_regex.txt
Q: Base path in paster configuration I'm trying to deploy some Pyramid code to dotcloud. Unfortunately some paths are not mapped in the same way as in local paster deployment. When I'm running the development configuration with local server through paster serve ..., I can access static files configured in: config.add...
Base path in paster configuration
I'm trying to deploy some Pyramid code to dotcloud. Unfortunately some paths are not mapped in the same way as in local paster deployment. When I'm running the development configuration with local server through paster serve ..., I can access static files configured in: config.add_static_view('static', 'appname:static'...
[ "On DotCloud, URLs starting with /static are handled directly by nginx, not by uwsgi. That means that your code will never see those requests: they will be served straight away from the static/ subdirectory of your application.\nOne possible workaround is to setup a symlink from static to appname/static.\nIf you do...
[ 4 ]
[]
[]
[ "dotcloud", "paster", "pyramid", "python", "wsgi" ]
stackoverflow_0005905291_dotcloud_paster_pyramid_python_wsgi.txt
Q: Non-english character getting changed to "." character in linux I am trying to create a "Language File" for adding localization to my Django application. The problem is that when the translate text has some non-english characters then they get replaced by a "." character and Django complains this giving an error....
Non-english character getting changed to "." character in linux
I am trying to create a "Language File" for adding localization to my Django application. The problem is that when the translate text has some non-english characters then they get replaced by a "." character and Django complains this giving an error. For eg: English German Change Password ...
[ "Okay, I solved my problem. I was getting the error invalid multibyte sequence because the problem was that the .po wasn't encoded properly. \nI could confirm this by executing the following command:\nfile -i django.po\n\nIt gave the output that the encoding type of the file was ISO-8859-1 \nSo, I converted the fil...
[ 4, 0 ]
[]
[]
[ "character_encoding", "django", "localization", "python", "unicode" ]
stackoverflow_0005895716_character_encoding_django_localization_python_unicode.txt
Q: Adding attributes to python objects It's a thing that bugged me for a while. Why can't I do: >>> a = "" >>> a.foo = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'foo' ...while I can do the following? >>> class Bar(): ... pass ... >>>...
Adding attributes to python objects
It's a thing that bugged me for a while. Why can't I do: >>> a = "" >>> a.foo = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'foo' ...while I can do the following? >>> class Bar(): ... pass ... >>> a = Bar() >>> a.foo = 10 #ok! What's th...
[ "You can add attributes to any object that has a __dict__.\n\nx = object() doesn't have it, for example.\nStrings and other simple builtin objects also don't have it.\nClasses using __slots__ also do not have it.\nClasses defined with class have it unless the previous statement applies.\n\nIf an object is using __s...
[ 58 ]
[]
[]
[ "attributes", "object", "python" ]
stackoverflow_0005907937_attributes_object_python.txt
Q: Python, saving 2 string outputs as 2 files There are 2 string outputs. Let's call them output1 and output2. Both of them should be saved in one location, each of them should have the same name but having different file extension (both being text files in fact). How can this be done in Python? The program should h...
Python, saving 2 string outputs as 2 files
There are 2 string outputs. Let's call them output1 and output2. Both of them should be saved in one location, each of them should have the same name but having different file extension (both being text files in fact). How can this be done in Python? The program should have standard save dialog, asking for name and lo...
[ "Use whatever GUI toolkit you're using to show the file dialog and get a base filename in filename. Then just\nwith open(filename + '.ext1', 'w') as f:\n f.write(output1)\nwith open(filename + '.ext2', 'w') as f:\n f.write(output2)\n\n" ]
[ 1 ]
[]
[]
[ "python", "save" ]
stackoverflow_0005907976_python_save.txt
Q: How to synch Facebook deauthorization callback with Facebook Javascript SDK I'm using the Facebook Python and Javascript SDKs. And have a deauthorization callback url set up to accept POSTs from Facebook in the event a User deauthorizes the applicaiton. When I receive the POST from Facebook, I set the User to ina...
How to synch Facebook deauthorization callback with Facebook Javascript SDK
I'm using the Facebook Python and Javascript SDKs. And have a deauthorization callback url set up to accept POSTs from Facebook in the event a User deauthorizes the applicaiton. When I receive the POST from Facebook, I set the User to inactive, and will not log them into the site. However this leaves fb:login-button ...
[ "If i understood the problem correctly: \nTry to check the user authorization using something like that: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/\nAnd then do with your buttons whatever you want...\n" ]
[ 0 ]
[]
[]
[ "facebook_graph_api", "facebook_javascript_sdk", "python" ]
stackoverflow_0005900843_facebook_graph_api_facebook_javascript_sdk_python.txt
Q: Python Multiprocessing with PyCUDA I've got a problem that I want to split across multiple CUDA devices, but I suspect my current system architecture is holding me back; What I've set up is a GPU class, with functions that perform operations on the GPU (strange that). These operations are of the style for iterati...
Python Multiprocessing with PyCUDA
I've got a problem that I want to split across multiple CUDA devices, but I suspect my current system architecture is holding me back; What I've set up is a GPU class, with functions that perform operations on the GPU (strange that). These operations are of the style for iteration in range(maxval): result[iteratio...
[ "You need to get all your bananas lined up on the CUDA side of things first, then think about the best way to get this done in Python [shameless rep whoring, I know].\nThe CUDA multi-GPU model is pretty straightforward pre 4.0 - each GPU has its own context, and each context must be established by a different host ...
[ 21, 3 ]
[]
[]
[ "cuda", "multiprocessing", "parallel_processing", "pycuda", "python" ]
stackoverflow_0005904872_cuda_multiprocessing_parallel_processing_pycuda_python.txt
Q: Searching a string in a list in python Hello I have a string which contains a mail address. For example ( user@foo.bar.com ) And I have a list which contains only domains ('bar.com','stackoverflow.com') etc. I want to search the list if it contains my string's domain. Right now I am using a code like this if token...
Searching a string in a list in python
Hello I have a string which contains a mail address. For example ( user@foo.bar.com ) And I have a list which contains only domains ('bar.com','stackoverflow.com') etc. I want to search the list if it contains my string's domain. Right now I am using a code like this if tokens[1].partition("@")[2] in domainlist: token...
[ "It should work like this: \nif any(tokens[1].endswith(domain) for domain in domainlist): \n\n", "If speed is really an issue for you, you can look into methods like Aho-Corasick. There are plenty of implementations available, like esmre/esm http://code.google.com/p/esmre/\nAs pointed out by @Riccardo Galli, simp...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "list", "python", "string", "substring" ]
stackoverflow_0005908190_list_python_string_substring.txt
Q: Can't open file: "NameError: name is not defined" I am creating a program to read a FASTA file and split at some specifc characters such as '>' etc. But I'm facing a problem. The program part is: >>> def read_FASTA_strings(seq_fasta): ... with open(seq_fasta.txt) as file: ... return file.read().s...
Can't open file: "NameError: name is not defined"
I am creating a program to read a FASTA file and split at some specifc characters such as '>' etc. But I'm facing a problem. The program part is: >>> def read_FASTA_strings(seq_fasta): ... with open(seq_fasta.txt) as file: ... return file.read().split('>') The error: Traceback (most recent call last)...
[ "You need to specify the file name as a string literal: \nopen('seq_fasta.txt')\n\n", "You need to quote the filename: open('seq_fasta.txt').\nBesides that, you might choose a different name but file as using this name shadows a builtin name.\n", "Your program is seeing seq_fasta.txt as a object label, similar ...
[ 8, 2, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005908067_file_io_python.txt
Q: Python Visualization: Determining Data Attributes Visually by Mouse Hover and Click I am rendering very large X,Y,Z scientific datasets in the lateral plane and would like to click on the results to obtain greater textual detail about the area chosen by mouse-click. So, for example, imagine a scientific dataset wh...
Python Visualization: Determining Data Attributes Visually by Mouse Hover and Click
I am rendering very large X,Y,Z scientific datasets in the lateral plane and would like to click on the results to obtain greater textual detail about the area chosen by mouse-click. So, for example, imagine a scientific dataset which is rendered as a filled contour plot and there is a bright spot. I would like to cli...
[ "Sounds like you'll need to dive into matplotlib's event handling code. This allows you to take some action when you click on a piece of the plot, or press a key, or whatever. Here are the example programs on the matplotlib site that have to do with event handling.\n" ]
[ 0 ]
[]
[]
[ "data_visualization", "matplotlib", "python" ]
stackoverflow_0005907915_data_visualization_matplotlib_python.txt
Q: Acquiring basic skills working with visualizing/analyzing large data sets I'm looking for a way to learn to be comfortable with large data sets. I'm a university student, so everything I do is of "nice" size and complexity. Working on a research project with a professor this semester, and I've had to visualize r...
Acquiring basic skills working with visualizing/analyzing large data sets
I'm looking for a way to learn to be comfortable with large data sets. I'm a university student, so everything I do is of "nice" size and complexity. Working on a research project with a professor this semester, and I've had to visualize relationships between a somewhat large (in my experience) data set. It was a 15...
[ "I'd say the most basic skill is a good grounding in math and statistics. This can help\nyou assess and pick from the variety of techniques for filtering data, and\nreducing its volume and dimensionality while keeping its integrity. The last\nthing you'd want to do is make something pretty that shows patterns or\...
[ 12, 4, 2, 1 ]
[]
[]
[ "data_visualization", "dataset", "python", "visualization" ]
stackoverflow_0005890935_data_visualization_dataset_python_visualization.txt
Q: Django - Get the list of items with a filter My Models: Item: name desc Type: name Value: text type.ForeignKey(Type) item = ForeignKey(Item) I had an initial list of types from table Type, assume t = [4,5,6]. Now I have to get a list of items have types are t. For example: Data list of V...
Django - Get the list of items with a filter
My Models: Item: name desc Type: name Value: text type.ForeignKey(Type) item = ForeignKey(Item) I had an initial list of types from table Type, assume t = [4,5,6]. Now I have to get a list of items have types are t. For example: Data list of Value: type | item 4 1 5 1 6 ...
[ "Not quite sure this is the best solution, but it works\nfrom itertools import groupby\n\nvalues = Value.objects.filter(type_id__in=t).values_list('type_id', 'item_id')\nvalues = sorted(values, key=lambda x: x[1])\n\nitems = []\nfor key, group in groupby(values, lambda x: x[1]):\n types = [x[0] for x in group]\n...
[ 2, 1 ]
[]
[]
[ "algorithm", "django", "django_models", "django_views", "python" ]
stackoverflow_0005908388_algorithm_django_django_models_django_views_python.txt
Q: Determining Python package location prior to import I want to get the location of a package before importing it. Basically I'd like to do import pkg pkg_path = pkg.__file__ but without having to import pkg. Right now I'm doing: target = "pkg" target_path = None for p in sys.path: search_path = "%s/%s" % (p,...
Determining Python package location prior to import
I want to get the location of a package before importing it. Basically I'd like to do import pkg pkg_path = pkg.__file__ but without having to import pkg. Right now I'm doing: target = "pkg" target_path = None for p in sys.path: search_path = "%s/%s" % (p, target) if os.path.exists(search_path): targ...
[ "Yes, there is imp.find_module():\ntarget_path = imp.find_module(target)\n\n", "You can use [__import__()][1] as follow:\ntarget_path = __import__('pkg').__file__\n\n__import__() is used by import and one of its uses is when the module name is only known at runtime.\n" ]
[ 5, 0 ]
[]
[]
[ "import", "path", "python" ]
stackoverflow_0005899287_import_path_python.txt
Q: Passing a JSON object through POST using Python I'm trying to post a JSON object through a POST. I'm trying to do it as follows: import json, urllib, urllib2 filename = 'test.json' race_id = 2530 f = open(filename, 'r') fdata = json.loads(f.read()) f.close() prefix = 'localhost:8000' count = 0 for points in fda...
Passing a JSON object through POST using Python
I'm trying to post a JSON object through a POST. I'm trying to do it as follows: import json, urllib, urllib2 filename = 'test.json' race_id = 2530 f = open(filename, 'r') fdata = json.loads(f.read()) f.close() prefix = 'localhost:8000' count = 0 for points in fdata['positions'].iteritems(): print '--' + str(cou...
[ "It looks like self.request.get() is returning a unicode object rather than a file-like object. You could try using json.loads() instead of json.load().\n", "json.load() expects a file object, but self.request.get returns the value of the parameter as a string.\nThe solution is easy: use json.loads.\nAlso, free t...
[ 31, 4, 1 ]
[]
[]
[ "google_app_engine", "json", "post", "python" ]
stackoverflow_0003150584_google_app_engine_json_post_python.txt
Q: Can you use multipart upload in boto with strings instead of a file handler? Is it possible to use the S3 multipart upload with strings instead of a file? The strings i am using are being generated during the upload process and so the size and the exact content is unknown the time the multipart upload starts. A: ...
Can you use multipart upload in boto with strings instead of a file handler?
Is it possible to use the S3 multipart upload with strings instead of a file? The strings i am using are being generated during the upload process and so the size and the exact content is unknown the time the multipart upload starts.
[ "There is no explicit \"upload_part_from_string\" method available. You could probably use StringIO to wrap a file-like object around the string and then pass that to \"upload_part_from_file\" but I haven't tested that.\nIt would be easy to add this method. At the time I didn't think it would be all that useful s...
[ 5 ]
[]
[]
[ "amazon_s3", "boto", "multipart", "python" ]
stackoverflow_0005863516_amazon_s3_boto_multipart_python.txt
Q: how to change form variable values from view i've been trying to send data to the following form from my view. i need the variable (choices ) to change each time we call this form class AnswersForm(forms.Form): question = forms.RadioSelect CHOICES=[('sf','asdf')] radioButton = forms.ChoiceField(choices=CHOICES,...
how to change form variable values from view
i've been trying to send data to the following form from my view. i need the variable (choices ) to change each time we call this form class AnswersForm(forms.Form): question = forms.RadioSelect CHOICES=[('sf','asdf')] radioButton = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) view.py : def exam...
[ "You can change the field choices overriding the form init method (so that it accepts a choice parameter) or you can change the field's choices after the init, depending on your needs.\nFirst Case would be like this:\nclass AnswersForm(forms.Form):\n radioButton = forms.ChoiceField(choices=CHOICES, widget=forms....
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005909661_django_python.txt
Q: When you move Tkinter windows stops program Hi I made a music downloading program that works great it tells you the percent its done and then if i move the window at all it stops downloading . I made a diffrent little script that downloads a specified mp3 on the web and i can move it as much as i want and it doese...
When you move Tkinter windows stops program
Hi I made a music downloading program that works great it tells you the percent its done and then if i move the window at all it stops downloading . I made a diffrent little script that downloads a specified mp3 on the web and i can move it as much as i want and it doesent stop. the only reason im not putting up the co...
[ "Most likely the problem is because you are calling update. You should never do that unless you know for certainty what the ramifications are. update causes a new event loop to be entered. Essentially, you end up with an infinite loop inside an infinite loop.\nTry changing your update to update_idletasks and see if...
[ 2 ]
[]
[]
[ "python", "tkinter", "urllib2" ]
stackoverflow_0005906981_python_tkinter_urllib2.txt
Q: Python web server options with nonblocking architecture I am looking for a Python based nonblocking web server environment that is designed to handle large number of simultaneous connections and be responsive under heavy load (C10K). I need it as a backend for my webapp. In a typical scenario the webapp client wil...
Python web server options with nonblocking architecture
I am looking for a Python based nonblocking web server environment that is designed to handle large number of simultaneous connections and be responsive under heavy load (C10K). I need it as a backend for my webapp. In a typical scenario the webapp client will be making several calls to the server using WebSockets. So ...
[ "As one of the core Twisted developers, I will strongly recommend that you use Twisted. :)\nFirst, because it is an excellent library with a development team committed to high quality software. Twisted has an extremely broad array of functionality to offer, ranging from a (well performing) simple web server to dat...
[ 4, 3 ]
[]
[]
[ "c10k", "python", "tornado", "twisted" ]
stackoverflow_0005908497_c10k_python_tornado_twisted.txt
Q: How to search a word in a file and replace the entire line with a new line? I have a file (with extension.hgx) that has some data like this: length = 0.00000783 height = 48 RATIO = 2 X = 1.0 Y = 1.0 I would like to open the file and repla...
How to search a word in a file and replace the entire line with a new line?
I have a file (with extension.hgx) that has some data like this: length = 0.00000783 height = 48 RATIO = 2 X = 1.0 Y = 1.0 I would like to open the file and replace the two lines: height = 48 RATIO = 2 With: heig...
[ "How's this?\nwith open('test.hgx') as f: lines = f.read().splitlines()\nwith open('test.hgx', 'w') as f:\n for line in lines:\n if line.startswith('height') or line.startswith('RATIO'): \n f.write(line.rsplit(' ', 1)[0] + ' 8\\n')\n else:\n f.write(line + '\\n')\n\n", "you need to stop iterati...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005910245_python.txt
Q: Seeding the random number Generator In PHP I m having a application in which i have to select a number out of many numbers according to their weights. Every time I will select , I have send the result to flash.I have found a algorithm in python. I have implemented it in php and was testing for its results. If i w...
Seeding the random number Generator In PHP
I m having a application in which i have to select a number out of many numbers according to their weights. Every time I will select , I have send the result to flash.I have found a algorithm in python. I have implemented it in php and was testing for its results. If i was running that algo in python it was giving goo...
[ "Both rand and mt_rand should both be more than sufficiently random for your task here. If you needed to seed mt_rand you could use mt_srand, but there's no need since PHP 4.2 as this is done for you.\nI suspect the issue is with your code, which seems unnecessarily involved given what I believe you're trying to do...
[ 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005910920_php_python.txt
Q: Python TTY Control I guess I'm not clear on what what the function of the getty/agetty/mgetty programs are on a linux/unix machine. I can start a shell on a tty with something like this: TTY = '/dev/tty3' cpid = os.fork() if cpid == 0: os.closerange(0, 4) sys.stdin = open(TTY, 'r') sys.stdout = open(...
Python TTY Control
I guess I'm not clear on what what the function of the getty/agetty/mgetty programs are on a linux/unix machine. I can start a shell on a tty with something like this: TTY = '/dev/tty3' cpid = os.fork() if cpid == 0: os.closerange(0, 4) sys.stdin = open(TTY, 'r') sys.stdout = open(TTY, 'w') sys.stderr...
[ "I can see at least two things you're missing - there may be more:\nFirstly, you need to call setsid() in the child process after closing the old standard input/standard output, and before opening the new TTY. This does two important things - it makes your new process the leader of a new session, and it disassocia...
[ 5, 0 ]
[]
[]
[ "linux", "python", "termios", "tty", "unix" ]
stackoverflow_0005905855_linux_python_termios_tty_unix.txt
Q: Django - Sort a list by related fields My models: Item: name desc Type: name Value: item.ForeignKey(Item) type.ForeignKey(Type) val.CharField # varchar or numeric Now I have an objects list of items but not a QuerySet, for instance: items = [<object:1>, <object:2>, <object:4>]. And t = 5...
Django - Sort a list by related fields
My models: Item: name desc Type: name Value: item.ForeignKey(Item) type.ForeignKey(Type) val.CharField # varchar or numeric Now I have an objects list of items but not a QuerySet, for instance: items = [<object:1>, <object:2>, <object:4>]. And t = 5 is an id of a row from Type. I want to sort...
[ "You can always use lambda function to sort the list of items (assuming there is a one to one relationship between Item and Value model, otherwise I don't think the question makes sense)\n items.sort(key=lambda object: object.value_set.all()[0].val)\n\nAlthough the point to be noted is that the sorting will be in m...
[ 2, 1, 1 ]
[]
[]
[ "algorithm", "django", "django_models", "django_views", "python" ]
stackoverflow_0005911223_algorithm_django_django_models_django_views_python.txt
Q: elisp equivalent of python shlex.split? I need to parse a command line in elisp, something like: (shlex-split "command \"Some file with spaces\" someother\ quote") ;;That gives ("command" "Some file with spaces" "someother quote") How can I accomplish this in a simple way? A: (split-string-and-unquote "command ...
elisp equivalent of python shlex.split?
I need to parse a command line in elisp, something like: (shlex-split "command \"Some file with spaces\" someother\ quote") ;;That gives ("command" "Some file with spaces" "someother quote") How can I accomplish this in a simple way?
[ "(split-string-and-unquote \"command \\\"Some file with spaces\\\" someother\\ quote\")\n" ]
[ 5 ]
[]
[]
[ "elisp", "python", "shlex" ]
stackoverflow_0005911202_elisp_python_shlex.txt
Q: Google AppEngine Python Cron job urllib I'm in need of setting up a cron job using Google AppEngine which will use urllib2 to execute a web page hosted on another server of mine. I know that the script is executing (checked the logs) but my logging inside my python script never seems to be outputted. #!/usr/bin/en...
Google AppEngine Python Cron job urllib
I'm in need of setting up a cron job using Google AppEngine which will use urllib2 to execute a web page hosted on another server of mine. I know that the script is executing (checked the logs) but my logging inside my python script never seems to be outputted. #!/usr/bin/env python from google.appengine.ext import web...
[ "main() should end after util.run_wsgi_app(application). The rest of that belongs in your handler class.\n", "I just used main.py from the Google App Engine root and then this seems to give me a better result.\nThere was a few problems other than what Drew mentioned too.\n" ]
[ 2, 0 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0005909054_cron_google_app_engine_python.txt
Q: Why there are UglyCase method names in Google API Python libraries? I just wonder why Google is using in API client libraries such UglyCase method names instead of existing_coding_standards? Actually, I am not happy to mess my PEP8 code with something like this (GetEditLink() ...wtf? class name?). A: Well, quoti...
Why there are UglyCase method names in Google API Python libraries?
I just wonder why Google is using in API client libraries such UglyCase method names instead of existing_coding_standards? Actually, I am not happy to mess my PEP8 code with something like this (GetEditLink() ...wtf? class name?).
[ "Well, quoting the PEP8 Code:\n\nmixedCase is allowed only in contexts\n where that's already the prevailing\n style (e.g. threading.py), to retain\n backwards compatibility.\n\nSo either that, or they just like it better.\n" ]
[ 3 ]
[]
[]
[ "google_api", "naming_conventions", "pep8", "python" ]
stackoverflow_0005911681_google_api_naming_conventions_pep8_python.txt
Q: Matplotlib: 2-D plot changing line color with 3rd dimension (category) How do I change the color of a regular 2-D plot according to a third dimension/category? For example, suppose we recorded the coolant temperature of a vehicle with time. We plot that with time on the horizontal axis, and temp on the vertical a...
Matplotlib: 2-D plot changing line color with 3rd dimension (category)
How do I change the color of a regular 2-D plot according to a third dimension/category? For example, suppose we recorded the coolant temperature of a vehicle with time. We plot that with time on the horizontal axis, and temp on the vertical axis. We also recorded at each time whether the "high temp indicator light" ...
[ "Just look at SciPy.Cookbook.MulticoloredLine\nAnother approach could be - add on/off ColorBar in the bottom of plot.\nhth!\n", "I just found this reasonably simple approach: masking the data array and then coloring.\nenter link description here http://matplotlib.sourceforge.net/plot_directive/mpl_examples/pylab_...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005794708_matplotlib_python.txt
Q: _foreign_keys error with Camelot I tried Camelot 10.07.02-c2-4build1 with SQLAlchemy 0.6.4-3 from the Ubuntu 11.04 repos and I get the following stacktrace, when I try to reference a foreign key in the table view: ERROR:camelot.view.model_thread.signal_slot_model_thread:exception caught in model thread while execu...
_foreign_keys error with Camelot
I tried Camelot 10.07.02-c2-4build1 with SQLAlchemy 0.6.4-3 from the Ubuntu 11.04 repos and I get the following stacktrace, when I try to reference a foreign key in the table view: ERROR:camelot.view.model_thread.signal_slot_model_thread:exception caught in model thread while executing get_columns -> QueryTableProxy.se...
[ "The version of SQLAlchemy has changed API that Camelot uses, therefore Camelot needs to be updated.\n" ]
[ 0 ]
[]
[]
[ "orm", "python", "sqlite" ]
stackoverflow_0005890447_orm_python_sqlite.txt
Q: Need to build an app to upload a dbf file remotely and update mysql database Hi I am faced with a task where i have to build an application which has the following requirements:- 1.the users of an organisation upload dbf files(foxpro database files) remotely into my application 2.this dbf file is used to update th...
Need to build an app to upload a dbf file remotely and update mysql database
Hi I am faced with a task where i have to build an application which has the following requirements:- 1.the users of an organisation upload dbf files(foxpro database files) remotely into my application 2.this dbf file is used to update the mysql database which is the central repository This web application has to be bu...
[ "There are at least two Python modules for accessing DBF file formats: dbfpy and dbf. Once you can parse the DBF file, you'll need to pass rows to a translation routine which constructs SQL statements to populate the MySQL tables, using the MySQLdb extension. \nAlso make sure to plan how to recover if an insert f...
[ 1 ]
[]
[]
[ "dbf", "mysql", "php", "python" ]
stackoverflow_0005910558_dbf_mysql_php_python.txt
Q: Python join - quoting values I am using the Python join function to create a string e.g. a = [a, b, c, d] b = ",".join(a) print b b = a,b,c,d but I want b = 'a','b','c','d' is there a way to do this just using the join function (or a shorter way) rather than doing b = "" for x in a: b += "'%s'," % x b = b[:-...
Python join - quoting values
I am using the Python join function to create a string e.g. a = [a, b, c, d] b = ",".join(a) print b b = a,b,c,d but I want b = 'a','b','c','d' is there a way to do this just using the join function (or a shorter way) rather than doing b = "" for x in a: b += "'%s'," % x b = b[:-1]
[ "b = \",\".join(map(repr, a))\n\nWill also correctly escape characters inside the string which may be useful.\n", ">>> b = ['a', 'b', 'c', 'd']\n>>> print ','.join(\"'{0}'\".format(s) for s in b)\n'a','b','c','d'\n\nThe expression inside the join() is a generator expression.\n", "In [1]: a = ['a', 'b', 'c', 'd'...
[ 9, 6, 6, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005911436_python.txt
Q: Get SQL headers from Numpy Array in python With below, I can get the row and col data from SQL: How would I get the table headers as part of the result set or array.? top = csr.execute("Select * from bigtop") d=list(top) a = np.asarray(d, dtype='object') print a Just like I asked here: How do I ...
Get SQL headers from Numpy Array in python
With below, I can get the row and col data from SQL: How would I get the table headers as part of the result set or array.? top = csr.execute("Select * from bigtop") d=list(top) a = np.asarray(d, dtype='object') print a Just like I asked here: How do I create a CSV file from database in Python?
[ "This is a self contained example that illustrates the general idea. numpy.recarray is your friend,\nfrom sqlite3 import connect\nfrom numpy import asarray\n\ndb = connect(\":memory:\")\nc = db.cursor()\nc.execute('create table bigtop (a int, b int, c int)')\n\nfor v in [(1,2,3),(4,5,6),(7,8,9)]:\n c.execute('in...
[ 4, 2, 1 ]
[]
[]
[ "numpy", "python", "sql" ]
stackoverflow_0005903288_numpy_python_sql.txt
Q: Class based view extending UpdateView not saving form correctly Im trying to save a form using UpdateView in Django 1.3 and seemed to have run into a problem. When I am saving the form, it POST's to the current URL and the success url is the same url. When saving the form, the data seems to be changed because all ...
Class based view extending UpdateView not saving form correctly
Im trying to save a form using UpdateView in Django 1.3 and seemed to have run into a problem. When I am saving the form, it POST's to the current URL and the success url is the same url. When saving the form, the data seems to be changed because all the fields on the page are updated, but when I refresh, everything se...
[ "Figured out the solution. The problem was happening because there was an error in the form that wasnt being reported. This seems to occur with hidden fields that need to be set in some way in order for the form to be valid.\nThe solution is pretty simple. You just need to override the post function and account for...
[ 9 ]
[]
[]
[ "django", "django_1.3", "django_views", "python", "views" ]
stackoverflow_0005899810_django_django_1.3_django_views_python_views.txt
Q: Fetch All In APSW You know there isnt any "fetchall" method for APSW. We can only use .next() method. So How can I take the result of an execute command with select query into a list? Thanks in advance A: Version 3.6.22 of apsw let me use cursor.fetchall() to retrieve all rows in a list: import apsw conn = aps...
Fetch All In APSW
You know there isnt any "fetchall" method for APSW. We can only use .next() method. So How can I take the result of an execute command with select query into a list? Thanks in advance
[ "Version 3.6.22 of apsw let me use cursor.fetchall() to retrieve all rows in a list:\nimport apsw\n\nconn = apsw.Connection(':memory:')\ncurs = conn.cursor()\ncurs.execute(\"CREATE TABLE foo (id INTEGER, name VARCHAR(255))\")\ncurs.executemany(\"INSERT INTO foo VALUES (?, ?)\", [(1, 'bar'),(2, 'baz')])\nprint curs....
[ 1 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0005911825_database_python_sqlite.txt
Q: Property user is corrupt in the datastore: Hi I get a strange error message: Property user is corrupt in the datastore Can you tell me what it means and what I should do? Here's the full trace 2011-05-04 01:35:15.144 Property user is corrupt in the datastore: Traceback (most recent call last): File "/base/pytho...
Property user is corrupt in the datastore:
Hi I get a strange error message: Property user is corrupt in the datastore Can you tell me what it means and what I should do? Here's the full trace 2011-05-04 01:35:15.144 Property user is corrupt in the datastore: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine...
[ "This is a known issue with the App Engine datastore. It has nothing to do with your code or app in particular.\nThe App Engine team is working on a fix, there is a workaround posted here while your waiting: http://groups.google.com/forum/#!topic/google-appengine-python/ClkOIalYD3s\n", "When an entity is fetched ...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005880741_google_app_engine_python.txt
Q: python tarinfo permission bits I am using tarfile module to check the permission of the packages in my tar.gz file. My problem are two folds. Permission bits value are different from the value got from ls -l command. From list command, value is 755. But I get 488 in my program. I use the below command function ...
python tarinfo permission bits
I am using tarfile module to check the permission of the packages in my tar.gz file. My problem are two folds. Permission bits value are different from the value got from ls -l command. From list command, value is 755. But I get 488 in my program. I use the below command function - def checkAndExtratZipFile (value...
[ "You're seeing a base-10 representation of an octal number:\n>>> oct(488)\n'0750'\n\nYou need to check flags using attributes on the stat module:\n>>> tarinfo.mode\n488\n>>> tarinfo.mode & stat.S_IXGRP != 0\nTrue\n>>> tarinfo.mode & stat.S_IXOTH != 0\nFalse\n\n" ]
[ 10 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0005912295_python_tar.txt
Q: Is there anyway to hook up Python/Tkinter to an already running Tcl/Tk app? I work a lot on Pure Data, an app written in Tcl/Tk and C. I'd like to be able to make a python API for plugins for modifying the Tcl/Tk GUI. To do this, it seems that I would need to be able to pass the running Tk instance to python, th...
Is there anyway to hook up Python/Tkinter to an already running Tcl/Tk app?
I work a lot on Pure Data, an app written in Tcl/Tk and C. I'd like to be able to make a python API for plugins for modifying the Tcl/Tk GUI. To do this, it seems that I would need to be able to pass the running Tk instance to python, then have Tkinter use that Tcl/Tk instance for its commands. So something like: ro...
[ "Take a look at the send command, you can do exactly that (to Tk applications, not plain Tcl applications). I do this all the time from my Emacs (connect to running Tk applications).\nTcl/Tk won't let you enslave another process, however using the send command, you can easily send over any commands you want to. J...
[ 5, 1, 0 ]
[]
[]
[ "python", "tcl", "tk_toolkit", "tkinter" ]
stackoverflow_0005573493_python_tcl_tk_toolkit_tkinter.txt
Q: i18n on google app engine 1.4.3 and django 1.2 I have found some tutorials that show how to use i18n on gae, but they assume django 0.96. Right now I don't have for example separate script for makemessages and I can't run manage.py. Has anyone tried using i18n recently and could explain to me, how can this be don...
i18n on google app engine 1.4.3 and django 1.2
I have found some tutorials that show how to use i18n on gae, but they assume django 0.96. Right now I don't have for example separate script for makemessages and I can't run manage.py. Has anyone tried using i18n recently and could explain to me, how can this be done? EDIT I have managed to generate po files and comp...
[ "We got it working or at least we think we do. We use the script compile-messages from django 0.96 to compile the .po files and have upgraded to django 1.2 using an I18NRequestHandler so I want to confirm it works. You may have a look at our code at http://montao.googlecode.com and we don't use manage.py since we d...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "internationalization", "python" ]
stackoverflow_0005908927_django_google_app_engine_internationalization_python.txt
Q: Django 1.3 - Admin pages do not get the correct ADMIN_MEDIA_PREFIX settings In my projects settings.py I have set ADMIN_MEDIA_PREFIX='/static/admin/' The admin media is being served in the correct location, browsing to http://127.0.0.1:8000/static/admin/css/base.css gives me the base.css for the admin page. But...
Django 1.3 - Admin pages do not get the correct ADMIN_MEDIA_PREFIX settings
In my projects settings.py I have set ADMIN_MEDIA_PREFIX='/static/admin/' The admin media is being served in the correct location, browsing to http://127.0.0.1:8000/static/admin/css/base.css gives me the base.css for the admin page. But when I inspect the admin pages they are still attempting to find the admin media...
[ "James was right. I had a second settings.py defined for my development environment that was overriding my main settings. I've deleted ADMIN_MEDIA_PREFIX from that file and now everything works as expected. Thank you!!\n", "I sometimes get a similar problem where I've clearly made changes but the code still behav...
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0005875500_django_django_admin_python.txt
Q: Installing PIL on OS X Snow Leopard w/Xcode4 (no PPC support) Xcode4 dropped PPC support, so when I try building PIL, it throws hate: Bens-MacBook-Air:Imaging-1.1.7 bkeating$ python setup.py build running buildrunning build_pyrunning build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' ...
Installing PIL on OS X Snow Leopard w/Xcode4 (no PPC support)
Xcode4 dropped PPC support, so when I try building PIL, it throws hate: Bens-MacBook-Air:Imaging-1.1.7 bkeating$ python setup.py build running buildrunning build_pyrunning build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension /usr/bin/gcc-4.0 -fno-strict-aliasing -fno-common -dynami...
[ "The solution has nothing to do with PIL but rather setting gcc's ARCHFLAGS:\nARCHFLAGS=\"-arch i386 -arch x86_64\" sudo pip install PIL\n\n", "ARCHFLAGS doesn't seem to get passed into sudo. I had to do \nsudo -s\n\nthen ARCHFLAGS=\"-arch i386 -arch x86_64\" pip install PIL\nto make it work.\n", "A better way ...
[ 38, 16, 14, 1 ]
[]
[]
[ "powerpc", "python", "python_imaging_library", "xcode" ]
stackoverflow_0005366882_powerpc_python_python_imaging_library_xcode.txt
Q: Twisted deferred vs blocking in web services I'm struggling to produce the same behavior in web service code that uses Deferred objects as in code that does not. My objective is to write a decorator that will delegate processing of any method (which is decoupled from Twisted) to the Twisted thread pool, so that t...
Twisted deferred vs blocking in web services
I'm struggling to produce the same behavior in web service code that uses Deferred objects as in code that does not. My objective is to write a decorator that will delegate processing of any method (which is decoupled from Twisted) to the Twisted thread pool, so that the reactor is not blocked, without changing any of...
[ "Ok, after reading your question several times, I think I understand what your asking. I have also reworked you code to make a little better than your original answer. This new answer should show off all the powers of deferred's.\nfrom twisted.web import server, resource\nfrom twisted.internet import defer, threads...
[ 4, 1 ]
[]
[]
[ "deferred", "python", "twisted", "web_services" ]
stackoverflow_0005904734_deferred_python_twisted_web_services.txt
Q: Is multiprocessing with RPy safe? Is it safe to call RPy functions in a multiprocessing environment and are there any multiprocessing issues regarding RPy that one should be aware of? A simple example might be the following: from multiprocessing import Pool from rpy import * def f(x): return r.mean(x) if __n...
Is multiprocessing with RPy safe?
Is it safe to call RPy functions in a multiprocessing environment and are there any multiprocessing issues regarding RPy that one should be aware of? A simple example might be the following: from multiprocessing import Pool from rpy import * def f(x): return r.mean(x) if __name__ == '__main__': p = Pool(5) ...
[ "Seeing that multiprocessing spawns new python instance for each worker instance in the pool and they share no common resources -- including instances of the R process, -- chances are it is thread-safe. Best way is to test it and see.\n", "I use multiprocessing and rpy2 with no problems. Can't speak to rpy (v1) b...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "r", "rpy2" ]
stackoverflow_0005707382_multiprocessing_multithreading_python_r_rpy2.txt
Q: Debugging PyQt4 using a core file I have a bug in my python script that is using PyQt4 that causes a segmentation fault. I could not find the bug using pdb, so now I wanna try it with gdb. The core file is written and when I open it and type where, I just get memory addresses and only question marks as function na...
Debugging PyQt4 using a core file
I have a bug in my python script that is using PyQt4 that causes a segmentation fault. I could not find the bug using pdb, so now I wanna try it with gdb. The core file is written and when I open it and type where, I just get memory addresses and only question marks as function names. I already installed the python-qt4...
[ "If I remember correctly, you will also need at least libqt4-dbg and python-dbg, maybe a few others..\n" ]
[ 0 ]
[]
[]
[ "gdb", "pyqt4", "python", "segmentation_fault" ]
stackoverflow_0005902379_gdb_pyqt4_python_segmentation_fault.txt
Q: Difference between closures in python and javascript In JS, we can write closure like: function f(){ var a=0; function g(){ alert(a++); } return g; } g=f() g() However, if I write following code in python def f(): a=0 def g(): a+=1 print a return g g=f() g() Then I get UnboundedLo...
Difference between closures in python and javascript
In JS, we can write closure like: function f(){ var a=0; function g(){ alert(a++); } return g; } g=f() g() However, if I write following code in python def f(): a=0 def g(): a+=1 print a return g g=f() g() Then I get UnboundedLocalError. Can anyone tell me the difference between closur...
[ "When you use a += 1 in Python it refers to a local (uninitialized) variable in scope of g function. Basically you can read variables from upper scopes, but if you try to write it will refer to a variable in most recent scope. To make it work like you want you have to use nonlocal keyword that is only present Pyt...
[ 12, 2 ]
[]
[]
[ "closures", "javascript", "python" ]
stackoverflow_0005910146_closures_javascript_python.txt
Q: django aggregation and filtering result in Django after aggregation. if I use filter on a column that is not aggregated, I get it used in the where clause of the SQL query and not in having as expected. example follows: I have a table for test results. Let's say I have TestA and TestB. Version: 2 | 2 | ...
django aggregation and filtering result
in Django after aggregation. if I use filter on a column that is not aggregated, I get it used in the where clause of the SQL query and not in having as expected. example follows: I have a table for test results. Let's say I have TestA and TestB. Version: 2 | 2 | 2 TestA :Pass |Null |Fail testB :Er...
[ "latest() will return the most recent model in a queryset.\nsite = Site.objects.get(id=1)\nfor test in Test.objects.all():\n test_result = TestResult.objects.filter(site=site, test=test).latest('timeEnd')\n print test_result.result\n\nannotate() just calculates a value, it does not do any filtering. I...
[ 1 ]
[]
[]
[ "django", "filtering", "mysql", "python" ]
stackoverflow_0005901127_django_filtering_mysql_python.txt
Q: wxpython scrolled Panel Not Updating scroll bars I'm using winxp and wxpython ( wxpython 3.1, python 2.6 ) to make a GUI program which will copy the text from a TextCtrl, into a ScrollablePanel that contains a StaticText. This all works fine, however, the Scrolled part doesn't work quite right. It seems like it wo...
wxpython scrolled Panel Not Updating scroll bars
I'm using winxp and wxpython ( wxpython 3.1, python 2.6 ) to make a GUI program which will copy the text from a TextCtrl, into a ScrollablePanel that contains a StaticText. This all works fine, however, the Scrolled part doesn't work quite right. It seems like it won't update in real time. When I ummaximize the window ...
[ "It would be better if you'll post something that could be running right after copy and paste.\nAnyway it appears that you missed the following things that are mandatory to make scrolled panel works:\n\nScrolled panel must have a sizer. This could be done via self.test_panel.SetSizer(self.a_sizer) method. All other...
[ 8 ]
[]
[]
[ "python", "scrolledwindow", "wxpython" ]
stackoverflow_0005912761_python_scrolledwindow_wxpython.txt
Q: How to find the shortest path satisfying constraints on a graph I'm trying to find the shortest path on a weighted graph given the constraint that the path must have a total distance less than some parameter (let's say 1000). I tried the following but I don't know why my code is wrong. def directedDFS(digraph, sta...
How to find the shortest path satisfying constraints on a graph
I'm trying to find the shortest path on a weighted graph given the constraint that the path must have a total distance less than some parameter (let's say 1000). I tried the following but I don't know why my code is wrong. def directedDFS(digraph, start, end, maxTotalDist): visited = [] if not (digraph.hasNode(...
[ "I really can't make heads or tails of the code you provided (firststep_distance? firststep_outer_distance?). Could you provide the name of the algorithm you're trying to implement?\nIf you're just making something up on the fly, and you're not doing with the goal of reinventing graph theory for educational purpos...
[ 1, 0 ]
[]
[]
[ "graph", "graph_theory", "python" ]
stackoverflow_0005913901_graph_graph_theory_python.txt
Q: How do I apply a monkeypatch to GAE? Can you tell me how I apply this patch to google app engine as in where to put it? Thank you def _user_init(self, email=None, _auth_domain=None, _user_id=None, federated_identity=None, federated_provider=None): if not _auth_domain: _auth_domain = os.environ.g...
How do I apply a monkeypatch to GAE?
Can you tell me how I apply this patch to google app engine as in where to put it? Thank you def _user_init(self, email=None, _auth_domain=None, _user_id=None, federated_identity=None, federated_provider=None): if not _auth_domain: _auth_domain = os.environ.get('AUTH_DOMAIN') assert _auth_domain ...
[ "Just use it as-is: Put that code in a module that gets imported before you use the relevant User module or datastore functionality. I included the relevant line to patch the code (the last line) with the patch itself.\n", "Overriding the constructor like this is not safe. If the internal implementation of the Us...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005912462_google_app_engine_python.txt
Q: Event - catch only Qt.Key_Delete I would like to change behavior of Key_Delete for QTableWidget, but because of using Designer I don't want to make any changes in py file with form. So instead of reimplementing QTableWidget like it is this answer: How to implement MousePressEvent for a Qt-Designer Widget in PyQt I...
Event - catch only Qt.Key_Delete
I would like to change behavior of Key_Delete for QTableWidget, but because of using Designer I don't want to make any changes in py file with form. So instead of reimplementing QTableWidget like it is this answer: How to implement MousePressEvent for a Qt-Designer Widget in PyQt I do something like this: class MyForm(...
[ "First: \"but it doesn't work\" is usually not descriptive enough. What behavior did you expect? What was the behavior you saw instead? Were there any error messages?\nI can easily see a few mistakes in here, though.\n\nYou're overriding the method QTableWidget.keyPressEvent, which expects 2 arguments: (QTableWidge...
[ 4 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0005747304_pyqt4_python.txt
Q: How to get a Device Specific UID using Python in ASE on Android? I am working on am Android Scripting Environment (ASE) script in Python to replicate an iPhone app. I need a device UID of some sort. My thoughts where a salted MD5 hash of the MAC address or device phone number, but I can't figure out how to access ...
How to get a Device Specific UID using Python in ASE on Android?
I am working on am Android Scripting Environment (ASE) script in Python to replicate an iPhone app. I need a device UID of some sort. My thoughts where a salted MD5 hash of the MAC address or device phone number, but I can't figure out how to access either of those using the Python APIs within ASE. What can I do to cre...
[ "The newer versions of ASE now include a function call to create these identifiers.\n" ]
[ 0 ]
[]
[]
[ "android", "android_scripting", "ase", "python" ]
stackoverflow_0002633029_android_android_scripting_ase_python.txt
Q: how to combine django and wordpress based on ubuntu and nginx now I have a site which based on django(the python framework) which can run stable. in this site we need to use wordpress as a cms. the server config on ubuntu and nginx, but i don't know how to combine the django and wordpress together.any tips is wond...
how to combine django and wordpress based on ubuntu and nginx
now I have a site which based on django(the python framework) which can run stable. in this site we need to use wordpress as a cms. the server config on ubuntu and nginx, but i don't know how to combine the django and wordpress together.any tips is wonderful. thanks in advance!
[ "If you are trying to integrate a previously existing Wordpress database you can use Django's ./manage.py inspectdb to autogenerate models for you. Wordpress has an extremely simplistic database, it would probably do a fairly decent job. Alternately you could use mezzanine which can import wordpress data, and is a ...
[ 4, 1, 0, 0 ]
[]
[]
[ "django", "python", "wordpress" ]
stackoverflow_0005895707_django_python_wordpress.txt
Q: Take screenshots at fixed intervals with Python using threading.Timer I'm writing a simple GUI application with pyGTK to take desktop screenshots at fixed intervals. To schedule the shots I use the threading.Timer class and to take shots I use os.system calls to scrot. When I click the start taking screenshots but...
Take screenshots at fixed intervals with Python using threading.Timer
I'm writing a simple GUI application with pyGTK to take desktop screenshots at fixed intervals. To schedule the shots I use the threading.Timer class and to take shots I use os.system calls to scrot. When I click the start taking screenshots button the GlapseMain.startScreenshots method is called. When I click the stop...
[ "To response:\nYou also need to call\ngtk.gdk.threads_init()\n\nbefore gtk.main() is called if you want threads with gtk\n\nLet _takeScreenshot() have a while loop instead and do not start a new thread for the next screenshot. You already have a worker thread for this, e.g.\nYou also need a Thread instead of a Time...
[ 4 ]
[]
[]
[ "gtk", "pygtk", "python", "screenshot", "timer" ]
stackoverflow_0005914265_gtk_pygtk_python_screenshot_timer.txt
Q: Creating MySql Table from a python list I have a large list of strings. I need to create a MySQL table where each string in the list is a name of a column (all columns are integers). (I'm on python with sqlalchemy). I looked at examples and it looks like I need to explicitly write each column in schema.Table, whic...
Creating MySql Table from a python list
I have a large list of strings. I need to create a MySQL table where each string in the list is a name of a column (all columns are integers). (I'm on python with sqlalchemy). I looked at examples and it looks like I need to explicitly write each column in schema.Table, which is not so practical for a large list. Is it...
[ "You could use tuple unpacking here.\n>>> column_names = ['col1', 'col2', 'col3']\n>>> columns = (Column(name, Integer) for name in column_names) \n>>> table = Table('table_name', metadata, *columns) # unpacks Column instances\n\nAnd here's an extended example of how you could use this to programmatically create t...
[ 2 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0005914365_mysql_python_sqlalchemy.txt
Q: sh command in python fails I am a beginner in python. I got these scripts from IP vendor. cmd = "sh compile_regression_vcs.sh" try: self.agent.run_commands(cmd, pwd=self.agent.test_dir, extra_env=env) except TestException as e: s = traceback.format_exc() serr = "there were errors:\n%s\n" % (s) sel...
sh command in python fails
I am a beginner in python. I got these scripts from IP vendor. cmd = "sh compile_regression_vcs.sh" try: self.agent.run_commands(cmd, pwd=self.agent.test_dir, extra_env=env) except TestException as e: s = traceback.format_exc() serr = "there were errors:\n%s\n" % (s) self.logger.info(serr) raise Te...
[ "Try this instead:\n/bin/sh compile_regression_vcs.sh\n\nIs compile_regression_vcs.sh in the current directory?\n", "The issue could mainly be the path for you shell and your shell script. \nIt could also be that the environment that you are running in your shell maybe different from the one that you are using in...
[ 2, 2 ]
[]
[]
[ "exception", "python", "sh", "try_catch" ]
stackoverflow_0005913701_exception_python_sh_try_catch.txt
Q: MySQLdb installed from pypm doesn't work with 32-bit python on Mac OSX Before proceeding further, here are some details of my Mac and the installed python (ActivePython) and wxpython versions: Mac version: 10.6.6 Python version: 2.7.1 (ActiveState Python) wxPython version: wxPython2.8-osx-unicode-py2.7 Here is a s...
MySQLdb installed from pypm doesn't work with 32-bit python on Mac OSX
Before proceeding further, here are some details of my Mac and the installed python (ActivePython) and wxpython versions: Mac version: 10.6.6 Python version: 2.7.1 (ActiveState Python) wxPython version: wxPython2.8-osx-unicode-py2.7 Here is a small code that I wrote to test: #! /usr/bin/env arch -i386 /usr/local/bin/py...
[ "Duplicate ;-)\nThis is a known bug -- the mysql-python package is built only for 64-bit at the moment.\n\nI want to use both wxpython and MySQLdb at the same time. How do I do it?\n\nwxPython 2.8 doesn't support 64-bit (due to using Carbon), this is why the PyPM package is built for only 32-bit. You could try usin...
[ 1 ]
[]
[]
[ "macos", "mysql_python", "pypm", "python", "wxpython" ]
stackoverflow_0005910810_macos_mysql_python_pypm_python_wxpython.txt
Q: django model's methods is there a better way to handle those functions inside the model? class MyModel ( models.Model ): name = models.CharField( max_length=50 ) foo = models.CharField( max_length=50 ) def style_foo(): return '<a href="/contract/print/sample/%s/">%s</a>' % ( self.pk, _( 'View ...
django model's methods
is there a better way to handle those functions inside the model? class MyModel ( models.Model ): name = models.CharField( max_length=50 ) foo = models.CharField( max_length=50 ) def style_foo(): return '<a href="/contract/print/sample/%s/">%s</a>' % ( self.pk, _( 'View sample' ) ) style_foo.a...
[ "I'm not entirely sure what you're trying to do, but this might be helpful. First, as a general rule, you shouldn't put formatting/display type of information (such as HTML) into the Model level. You should format the HTML elsewhere, and design the Model so as to return a URL for any given object. For instance:\n# ...
[ 5, 1 ]
[]
[]
[ "django", "field", "methods", "model", "python" ]
stackoverflow_0005914505_django_field_methods_model_python.txt
Q: simple recursive function This is a pretty simple task i feel like i should be able to do- but just for the life of me, cant figure out. I'm trying to write a recursive function to replicate the following: chars = '0123456789abcdef' for a in chars: for b in chars: for c in chars: for d in ...
simple recursive function
This is a pretty simple task i feel like i should be able to do- but just for the life of me, cant figure out. I'm trying to write a recursive function to replicate the following: chars = '0123456789abcdef' for a in chars: for b in chars: for c in chars: for d in chars: print a+...
[ "You don't need recursion if you have itertools:\nfrom itertools import product\nfor a,b,c,d in product('abc', repeat=4):\n print a+b+c+d\n\n", "I'm not going to write it out, because that would defeat the purpose, but here's a hint: Think about the conditions under which you stop recursing. Here's the key bit...
[ 5, 4, 2, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0005914708_python_recursion.txt
Q: Has anyone used rpy2 with py2exe? I am hoping to port some Python code that uses RPY2 to run R functions into dlls using py2exe then, ultimately, to COM objects for integration with a C# project of a collaborator. If incorporating rpy2 into py2exe is not too painful, this could save a fair bit of recoding. Does a...
Has anyone used rpy2 with py2exe?
I am hoping to port some Python code that uses RPY2 to run R functions into dlls using py2exe then, ultimately, to COM objects for integration with a C# project of a collaborator. If incorporating rpy2 into py2exe is not too painful, this could save a fair bit of recoding. Does anyone have suggestions based on their e...
[ "Given the current state of extremely limited support of rpy2 on Microsoft Windows, I'd consider other options.\n" ]
[ 1 ]
[]
[]
[ "c#", "com", "py2exe", "python", "rpy2" ]
stackoverflow_0005850818_c#_com_py2exe_python_rpy2.txt
Q: How to determine if your app is running on local Python Development Server? I need to programatically determine if my app is running in development or not, so that I can provide sandbox values for a variety of constants and methods. Something like: if app.development: # Live mode FREEBASE_USER = "spam123" FREE...
How to determine if your app is running on local Python Development Server?
I need to programatically determine if my app is running in development or not, so that I can provide sandbox values for a variety of constants and methods. Something like: if app.development: # Live mode FREEBASE_USER = "spam123" FREEBASE_PSWD = "eggs123" FREEBASE = freebase else: # Sandbox mode FREEBASE_USER...
[ "import os\n\nDEV = os.environ['SERVER_SOFTWARE'].startswith('Development')\n\n" ]
[ 36 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005914802_google_app_engine_python.txt
Q: Writing a TTL decorator in Python I'm trying to write a TTL decorator in python. Basically I give it raise an exception if the function doesn't answer in the selected time. You can find the thead2 snippets on http://sebulba.wikispaces.com/recipe+thread2 from thread2 import Thread """ A TTL decorator. """ class W...
Writing a TTL decorator in Python
I'm trying to write a TTL decorator in python. Basically I give it raise an exception if the function doesn't answer in the selected time. You can find the thead2 snippets on http://sebulba.wikispaces.com/recipe+thread2 from thread2 import Thread """ A TTL decorator. """ class Worker(Thread): def __init__(self, q...
[ "The code provided is a bit tough to follow -- how is it going to raise an exception in the right place at the right time in the right thread?\nConsider this rough flow:\nDecorator function called with target function. Return a function which:\n\nStarts thread, calling target function\nJoins to thread using thread....
[ 5, 0 ]
[]
[]
[ "decorator", "python", "ttl" ]
stackoverflow_0000576776_decorator_python_ttl.txt
Q: Upload a file-like object with Paramiko? I have a bunch of code that looks like this: with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(fileobj.read()) # fileobj is some file-like object tmpfile.flush() try: self.sftp.put(tmpfile.name, path) except IOError: # error handli...
Upload a file-like object with Paramiko?
I have a bunch of code that looks like this: with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(fileobj.read()) # fileobj is some file-like object tmpfile.flush() try: self.sftp.put(tmpfile.name, path) except IOError: # error handling removed for ease of reading pass I...
[ "Update As of Paramiko 1.10, you can use putfo:\nself.sftp.putfo(fileobj, path)\n\n\nInstead of using paramiko.SFTPClient.put, you can use paramiko.SFTPClient.open, which opens a file-like object. You can write to that. Something like this:\nf = self.sftp.open(path, 'wb')\nf.write(fileobj.read())\nf.close()\n\nNote...
[ 21, 2 ]
[]
[]
[ "paramiko", "python", "sftp" ]
stackoverflow_0005914761_paramiko_python_sftp.txt
Q: Why is this code slower in Python 3? I just wrote this code, and I was wondering why it performs significantly worse in Python 3? Is it the same across all platforms? Is this just bad luck, or is Py3 generally slower? Thanks! Performance: python 2.6 python 3.1 pypy 1.5 linux 2.2s 2.4s 0.8s ...
Why is this code slower in Python 3?
I just wrote this code, and I was wondering why it performs significantly worse in Python 3? Is it the same across all platforms? Is this just bad luck, or is Py3 generally slower? Thanks! Performance: python 2.6 python 3.1 pypy 1.5 linux 2.2s 2.4s 0.8s os x 2.5s 3.4s 0.7s Code:...
[ "Py3k is generally slower than python 2.x. That will change as time passes, but the focus for py3k was feature completeness and stability, not speed.\n", "I think I've answered my own question:\n\nThe net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python...
[ 4, 1 ]
[]
[]
[ "performance", "python", "python_3.x" ]
stackoverflow_0005915019_performance_python_python_3.x.txt
Q: Eliminate unnecessary drawing of an image when using dc? I have three questions that I could really use some help on. Hope I'm not asking too much. 1) I am designing a simple GUI that contains one frame and one panel. Let's say I have two images that I draw on the panel using dc. One image will be continually fad...
Eliminate unnecessary drawing of an image when using dc?
I have three questions that I could really use some help on. Hope I'm not asking too much. 1) I am designing a simple GUI that contains one frame and one panel. Let's say I have two images that I draw on the panel using dc. One image will be continually fade in and out (on a timer), and the second is stationary (doesn...
[ "1) For the Performance, I would recommend using a MemoryDC and update the Drawing only it is required. See here: BufferedCanvas. You may want to use more than 2 buffers because you are using 2 images (see example).\n2) I don't know about this, but have you tried to do the binding to a panel and fade the panel in/o...
[ 0 ]
[]
[]
[ "drawing", "python", "wxpython" ]
stackoverflow_0005906796_drawing_python_wxpython.txt
Q: Can cx-freeze be used in Ubuntu to freeze a python script to a Windows executable? When I use cxfreeze in Ubuntu, it automatically compiles the python script to a Linux executable. I've looked through the documentation extensively, and I can't find a way to freeze the script into a .exe for the purposes of running...
Can cx-freeze be used in Ubuntu to freeze a python script to a Windows executable?
When I use cxfreeze in Ubuntu, it automatically compiles the python script to a Linux executable. I've looked through the documentation extensively, and I can't find a way to freeze the script into a .exe for the purposes of running the program on a Windows machine. Can this be done-?
[ "You can do that.... but you'll have to install Wine (apt-get install wine) and then install in Wine the windows version of Python and all the python libraries your application needs, and then you'll be able to freeze your script into an exe for windows in your ubuntu box.\n" ]
[ 4 ]
[]
[]
[ "cx_freeze", "python" ]
stackoverflow_0005915151_cx_freeze_python.txt
Q: Why weren't certain Python files examined by coverage.py? I'm using coverage.py to measure test coverage in a Python project, but some Python files are not showing up in the coverage report. One thing that is different about these files is that they were not executed by any tests (i.e., if they were included in th...
Why weren't certain Python files examined by coverage.py?
I'm using coverage.py to measure test coverage in a Python project, but some Python files are not showing up in the coverage report. One thing that is different about these files is that they were not executed by any tests (i.e., if they were included in the report, their coverage would be 0%). What are possible reaso...
[ "If your files are even not loaded during your testing session, they won't even appear in coverage result. But you can force coverage.py to measure \"non\" coverage in every file you want with the source option. It will include even non loaded source code to the coverage report.\n" ]
[ 6 ]
[]
[]
[ "coverage.py", "python" ]
stackoverflow_0005915368_coverage.py_python.txt
Q: Check all dependencies of python software before installing in window i make the single exe file for installing my software in window using "python setup.py bdist_wininst" but when install this software using exe it check only for python install in system or not , it does not check other dependencies like pyqt ,p...
Check all dependencies of python software before installing in window
i make the single exe file for installing my software in window using "python setup.py bdist_wininst" but when install this software using exe it check only for python install in system or not , it does not check other dependencies like pyqt ,pycurl library . how i modify this setup file so the generated exe file firs...
[ "Use the install_requires keyword argument to setuptools.setup() to specify other packages your package requires.\nNote: according to the SO question Is it possible to require PyQt from setuptools setup.py? you cannot get setuptools to install it for users who have a Python distribution that's missing it. Anything ...
[ 1 ]
[]
[]
[ "installation", "pyqt4", "python", "setup.py", "windows_installer" ]
stackoverflow_0005915479_installation_pyqt4_python_setup.py_windows_installer.txt
Q: In Python on Unix, determine if I am using my computer? or idle? I would like to write a script to do an heavy network upload, in the background. However, I would like it to pause when I am using my computer (either by detecting network activity or keyboard activity or that I am not idle). What is the best way to ...
In Python on Unix, determine if I am using my computer? or idle?
I would like to write a script to do an heavy network upload, in the background. However, I would like it to pause when I am using my computer (either by detecting network activity or keyboard activity or that I am not idle). What is the best way to detect that I am using the computer, on Python on Unix?
[ "Unixy solution using X11/XScreenSaver to get idle time:\n#!/usr/bin/python\nimport ctypes\nimport os\n\nclass XScreenSaverInfo( ctypes.Structure):\n \"\"\" typedef struct { ... } XScreenSaverInfo; \"\"\"\n _fields_ = [('window', ctypes.c_ulong), # screen saver window\n ('state', ctypes.c_...
[ 10, 2, 1, 0, 0 ]
[]
[]
[ "keyboard", "networking", "python", "python_idle" ]
stackoverflow_0005914506_keyboard_networking_python_python_idle.txt
Q: Howto send a valid XML POST request to ebay API via Python? I guess this is rather a general problem than ebay specific, but I am not sure: I am trying to send an XML request to the ebay developer API to retrieve an XML response. When using curl, everything works fine and I get an XML response telling me which API...
Howto send a valid XML POST request to ebay API via Python?
I guess this is rather a general problem than ebay specific, but I am not sure: I am trying to send an XML request to the ebay developer API to retrieve an XML response. When using curl, everything works fine and I get an XML response telling me which API-keys are missing (if I would provide them via HTTP headers I wou...
[ "It's returning a 500 status and the xml response:\n>>> connection.request(\"POST\", '/services/search/FindingService/v1', xmlparameters)\n>>> resp = connection.getresponse()\n>>> resp.status\n<<< 500\n>>> resp.read()\n<<< '<?xml version=\\'1.0\\' encoding=\\'UTF-8\\'?><ms:errorMessage xmlns:ms=\"http://www.ebay.co...
[ 1, 0 ]
[]
[]
[ "ebay_api", "http_post", "python", "xml" ]
stackoverflow_0005915086_ebay_api_http_post_python_xml.txt
Q: How would I package and sell a Django app? Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Dis...
How would I package and sell a Django app?
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound lik...
[ "Don't try and obfuscate or encrypt the code - it will never work.\nI would suggest selling the Django application \"as a service\" - either host it for them, or sell them the code and support. Write up a contract that forbids them from redistributing it.\nThat said, if you were determined to obfuscate the code in ...
[ 63, 15, 13, 10, 7, 4, 3 ]
[]
[]
[ "django", "piracy_prevention", "python" ]
stackoverflow_0000164901_django_piracy_prevention_python.txt
Q: NumPy: programmatically modify dtype of a structured array I have a structured array, for example: import numpy as np orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')]) sa = np.empty(4, dtype=orig_type) where sa looks like (random data): array([(11772880L, 14527168, 1.079593371731406e-307),...
NumPy: programmatically modify dtype of a structured array
I have a structured array, for example: import numpy as np orig_type = np.dtype([('Col1', '<u4'), ('Col2', '<i4'), ('Col3', '<f8')]) sa = np.empty(4, dtype=orig_type) where sa looks like (random data): array([(11772880L, 14527168, 1.079593371731406e-307), (14528064L, 21648608, 1.9202565460908188e-302), (...
[ "There is no shortcut. You would just construct the new dtype however you like and use .astype().\n", "If your question actually aims at how to construct the new dtype object from the old one, this may be what you are looking for:\norig_type = sa.dtype\ndescr = orig_type.descr\ndescr[1] = (descr[1][0], \"|S10\")\...
[ 5, 4 ]
[]
[]
[ "numpy", "python", "types" ]
stackoverflow_0005906428_numpy_python_types.txt
Q: creating testsuite in python I have python scripts, such as a.py, b.py, c.py located in say directory A: I want to create test suite which will execute all those python scripts sequentially. Those scripts are no a unit test. Those are regular python scripts. Please let me know how do I run them in test suite and g...
creating testsuite in python
I have python scripts, such as a.py, b.py, c.py located in say directory A: I want to create test suite which will execute all those python scripts sequentially. Those scripts are no a unit test. Those are regular python scripts. Please let me know how do I run them in test suite and generate report after execution. Th...
[ "I think what you want is actually done on the shell, or command line if you are on Windows. You can loop through each file and execute each script in order. You are then able to have the actual generate a report to save in a file after they are done processing, by using the open() command in python.\nThe syntax of...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005905703_python.txt
Q: Python Tkinter application doesn't quit properly from TKinter import * class Ui(Frame): def __init__(self) Frame.__init__(self, None) self.grid() bquit=Button(self, text="Quit", command=self.quit_pressed) bquit.grid(row=0, column=0) def quit_pressed(self): self.destroy() app=Ui() app.ma...
Python Tkinter application doesn't quit properly
from TKinter import * class Ui(Frame): def __init__(self) Frame.__init__(self, None) self.grid() bquit=Button(self, text="Quit", command=self.quit_pressed) bquit.grid(row=0, column=0) def quit_pressed(self): self.destroy() app=Ui() app.mainloop() Why doesn't this Tkinter program end properl...
[ "With self.destroy() you're just destroying the Frame, not the the top level container, you need to do self.master.destroy() for it to exit correctly\n", "The reason this does not work is because you are using an incorrect way to end the program in quit_pressed. What you are doing right now is killing the self fr...
[ 5, 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005916187_python_tkinter.txt
Q: Iterate within directory to zip files with python I need to iterate through a folder and find every instance where the filenames are identical (except for extension) and then zip (preferably using tarfile) each of these into one file. So I have 5 files named: "example1" each with different file extensions. I need...
Iterate within directory to zip files with python
I need to iterate through a folder and find every instance where the filenames are identical (except for extension) and then zip (preferably using tarfile) each of these into one file. So I have 5 files named: "example1" each with different file extensions. I need to zip them up together and output them as "example1.t...
[ "You could do this:\n\nlist all files in the directory\ncreate a dictionary where the basename is the key and all the extensions are values\nthen tar all the files by dictionary key\n\nSomething like this:\nimport os\nimport tarfile\nfrom collections import defaultdict\n\nmyfiles = os.listdir(\".\") # List of all...
[ 2, 2, 1, 0, 0 ]
[ "import os\nimport tarfile\n\nallfiles = {}\n\nfor filename in os.listdir(\".\"):\n basename = '.'.join (filename.split(\".\")[:-1] )\n if not basename in all_files:\n allfiles[basename] = [filename]\n else:\n allfiles[basename].append(filename)\n\nfor basename, filenames in allfiles.items():...
[ -1 ]
[ "loops", "python" ]
stackoverflow_0005916097_loops_python.txt
Q: Serializing a FeedParser object to Atom I use feedparser http://www.feedparser.org/ to parse Atom feeds and I do some manipulation on the resulting Python objetcs. After that, I would like to serialize the objects back to Atom. But feedparser does not seem to offer a way to do so? I noticed other Atom libraries li...
Serializing a FeedParser object to Atom
I use feedparser http://www.feedparser.org/ to parse Atom feeds and I do some manipulation on the resulting Python objetcs. After that, I would like to serialize the objects back to Atom. But feedparser does not seem to offer a way to do so? I noticed other Atom libraries like gdata http://code.google.com/p/gdata-pytho...
[ "Generating feeds is fairly easy using a Python template library like Mako, Jinja or Django's.\nAn example using Bottle.py:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n <title>{{! d['title'] }}</title>\n <subtitle>{{! d['subtitle'] }}</subtitle>\n <link rel=\"...
[ 3 ]
[]
[]
[ "atom_feed", "feedparser", "python" ]
stackoverflow_0005916375_atom_feed_feedparser_python.txt
Q: python win32 simulate click Let's say I've got a window for which I want to simulate a mouse click at a specific x, y coordinate. I already have the hwnd but I'm not sure how to construct the lParam. I've used SendMessage in the past to click on buttons, etc., but I knew their hwnds. Any help would be greatly appr...
python win32 simulate click
Let's say I've got a window for which I want to simulate a mouse click at a specific x, y coordinate. I already have the hwnd but I'm not sure how to construct the lParam. I've used SendMessage in the past to click on buttons, etc., but I knew their hwnds. Any help would be greatly appreciated. I also can't help but wo...
[ "I think this is good one for you, you can use by direct or import this to your python program.\n\"\"\"mousemacro.py defines the following functions:\n\nclick() -- calls left mouse click\nhold() -- presses and holds left mouse button\nrelease() -- releases left mouse button\n\nrightclick() -- calls right mouse clic...
[ 11, 8 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0002964051_python_winapi.txt
Q: Ctrl-C doesn't interrupt semaphore.acquire while True: try: queries_semaphore.acquire() query = queries.pop(0) # Do some stuff ... info('Query executed: `%s\'' % str(query)) except KeyboardInterrupt: okay('quit') break The problem is that KeyboardInterrupt i...
Ctrl-C doesn't interrupt semaphore.acquire
while True: try: queries_semaphore.acquire() query = queries.pop(0) # Do some stuff ... info('Query executed: `%s\'' % str(query)) except KeyboardInterrupt: okay('quit') break The problem is that KeyboardInterrupt is raised only after queries_semaphore.acquire() ...
[ "I would create another thread for queries_semaphore.acquire() part and leave main thread for interaction with user. If user hit Ctrl-C then you should unblock working thread by setting semaphore and finish it.\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python", "semaphore" ]
stackoverflow_0005917060_multithreading_python_semaphore.txt
Q: Using couchdbkit (3rd party library) on Google App Engine I'm having difficulty getting couchdbkit to function properly on Google App Engine. I'm either not importing my libraries correctly or I've run afoul of GAE's Python Sandbox rules. Anyone know if I need to include restkit when using couchdbkit on GAE (tha...
Using couchdbkit (3rd party library) on Google App Engine
I'm having difficulty getting couchdbkit to function properly on Google App Engine. I'm either not importing my libraries correctly or I've run afoul of GAE's Python Sandbox rules. Anyone know if I need to include restkit when using couchdbkit on GAE (that's where some of the problems are coming from)? Here's my conf...
[ "I hate to answer my own question, but it appears I was trying to do things outside the confines of GAE's Python Sandbox. I think it took issue with the socket stuff. The good folks at Cloudant pointed me to this Quora answer that lays out more liberal hosting options for Python/Django.\nBTW, I went with WebFacti...
[ 1, 0 ]
[]
[]
[ "cloudant", "couchdbkit", "google_app_engine", "python" ]
stackoverflow_0005906612_cloudant_couchdbkit_google_app_engine_python.txt
Q: Creating a http-proxy that can modify the http response before sending it to the client I'm using wget to grab a something from the web, but I don't want to follow a portion of the page. I thought I could set up a proxy that would remove the parts of the webpage I didn't want to be processed, before returning it t...
Creating a http-proxy that can modify the http response before sending it to the client
I'm using wget to grab a something from the web, but I don't want to follow a portion of the page. I thought I could set up a proxy that would remove the parts of the webpage I didn't want to be processed, before returning it to wget but I'm not sure how I would accomplish that. Is there a proxy that lets me easily mod...
[ "There are several ways you could achieve this goal. This should get you started (using node.js). In the following example I am fetching google.com and replacting all instances of \"google\" with \"foobar\".\n// package.json file...\n{\n \"name\": \"proxy-example\",\n \"description\": \"a simple example of modify...
[ 6, 0 ]
[]
[]
[ "http", "http_proxy", "node.js", "proxy", "python" ]
stackoverflow_0005916512_http_http_proxy_node.js_proxy_python.txt
Q: understanding for loops with reference to list containers in python My question is regarding the following for loop: x=[[1,2,3],[4,5,6]] for v in x: v=[0,0,0] here if you print x you get [[1,2,3],[4,5,6]].. so the v changed is not really a reference to the list in x. But when you do something like the following...
understanding for loops with reference to list containers in python
My question is regarding the following for loop: x=[[1,2,3],[4,5,6]] for v in x: v=[0,0,0] here if you print x you get [[1,2,3],[4,5,6]].. so the v changed is not really a reference to the list in x. But when you do something like the following: x=[[1,2,3],[4,5,6]] for v in x: v[0]=0; v[1]=0; v[2] =0 then you get...
[ "When python executes v = [0, 0, 0], it's \n\nCreating a new list object with three zeroes in it.\nAssigning a reference to the new list to a label called v\n\nIt doesn't matter if v was a reference to something else before. \nIf you want to change the contents of the list currently referenced by v, then you can't...
[ 7, 6 ]
[]
[]
[ "for_loop", "list", "python", "reference" ]
stackoverflow_0005917244_for_loop_list_python_reference.txt
Q: How to change tag name with BeautifulSoup? I am using python + BeautifulSoup to parse an HTML document. Now I need to replace all <h2 class="someclass"> elements in an HTML document, with <h1 class="someclass">. How can I change the tag name, without changing anything else in the document? A: I don't know how ...
How to change tag name with BeautifulSoup?
I am using python + BeautifulSoup to parse an HTML document. Now I need to replace all <h2 class="someclass"> elements in an HTML document, with <h1 class="someclass">. How can I change the tag name, without changing anything else in the document?
[ "I don't know how you're accessing tag but the following works for me:\nimport BeautifulSoup\n\nif __name__ == \"__main__\":\n data = \"\"\"\n<html>\n<h2 class='someclass'>some title</h2>\n<ul>\n <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>\n <li>Aliquam tincidunt mauris eu risus.</li>\...
[ 33, 2, 0 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0005289189_beautifulsoup_html_parsing_python.txt
Q: Python - egg cache extraction error - permission denied - Apache not seeing SetEnv? I'm trying to set up Apache with mod_wsgi to run Django on a Red Hat box but I'm getting the dreaded "Permission denied: '/home/pineg/.python-eggs'" egg cache extraction error. I did what it said and made this the first line: SetEn...
Python - egg cache extraction error - permission denied - Apache not seeing SetEnv?
I'm trying to set up Apache with mod_wsgi to run Django on a Red Hat box but I'm getting the dreaded "Permission denied: '/home/pineg/.python-eggs'" egg cache extraction error. I did what it said and made this the first line: SetEnv PYTHON_EGG_CACHE /opt/tmp in /etc/httpd/conf/httpd.conf And restarted Apache: >sudo /...
[ "This issue and the solution is described in mod_wsgi documentation at:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User\n", "I now nothing about Apache-Django specifics, but in general\nSetEnv PYTHON_EGG_CACHE /opt/tmp\ndoes not set environment variable, it only add it to env...
[ 4, 2, 0 ]
[]
[]
[ "apache", "mod_wsgi", "python", "redhat", "setuptools" ]
stackoverflow_0005912701_apache_mod_wsgi_python_redhat_setuptools.txt
Q: PyQt model/view: which type of model for programmatic changes? I recently started rewriting an application and I'm trying to port it to model/view to reduce the number of kludges I have there. So far I was able to succcessfully make a read-only model inheriting from QAbstractTableModel. This model is something lik...
PyQt model/view: which type of model for programmatic changes?
I recently started rewriting an application and I'm trying to port it to model/view to reduce the number of kludges I have there. So far I was able to succcessfully make a read-only model inheriting from QAbstractTableModel. This model is something like this: class MyModel(QtCore.QAbstractTableModel): def __init__(...
[ "In fact, it's a bit more involved than you were probably hoping for. You have to let your view know when the table is being expanded or contracted. Because the view only updates items on a local basis when they are modified, it has to be informed when the table's shape changes.\nSo, you have to use the beginInse...
[ 1, 1 ]
[]
[]
[ "model_view", "pyqt", "python" ]
stackoverflow_0005917379_model_view_pyqt_python.txt
Q: How to create variable sized __local memory in pyopencl? in my C OpenCL code I use clSetKernelArg to create 'variable size' __local memory for use in my kernels, which is not available in OpenCL per se. See my example: clSetKernelArg(clKernel, ArgCounter++, sizeof(cl_mem), (void *)&d_B); ... clSetKernelArg(clKerne...
How to create variable sized __local memory in pyopencl?
in my C OpenCL code I use clSetKernelArg to create 'variable size' __local memory for use in my kernels, which is not available in OpenCL per se. See my example: clSetKernelArg(clKernel, ArgCounter++, sizeof(cl_mem), (void *)&d_B); ... clSetKernelArg(clKernel, ArgCounter++, sizeof(float)*block_size*block_size, NULL); ....
[ "It is similar to C. You pass it a fixed size array as a local. Here is an example from Enja's radix sort. Notice the last argument is a local memory array.\n def naive_scan(self, num):\n nhist = num/2/self.cta_size*16\n global_size = (nhist,)\n local_size = (nhist,)\n extra_space = nhist / 16 #NUM_BANK...
[ 6, 3 ]
[]
[]
[ "opencl", "pyopencl", "python" ]
stackoverflow_0005912968_opencl_pyopencl_python.txt
Q: Python logging in different systems show different format/level I have a simple command line program written in python. The program logs to screen using the logging module configured in the following way: logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') The weird thing is that in my l...
Python logging in different systems show different format/level
I have a simple command line program written in python. The program logs to screen using the logging module configured in the following way: logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') The weird thing is that in my laptop, the program logs at the right level (INFO) an with the desired...
[ "The basicConfig() API in logging will do nothing (as documented) if the root logger already has handlers configured. Your basicConfig() call may be being ignored because some other code in the server has already configured some handlers for the root logger.\nIn general library code should not add handlers - that's...
[ 1, 0, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0005909081_logging_python.txt