content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: What are the open source projects out there that is built with the pyramid project? I'm learning pyramid. I'd like to see me some open source projects and get a quick start. A: I'd suggest looking at shootout, a pretty complete Pyramid demo app.
What are the open source projects out there that is built with the pyramid project?
I'm learning pyramid. I'd like to see me some open source projects and get a quick start.
[ "I'd suggest looking at shootout, a pretty complete Pyramid demo app.\n" ]
[ 1 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0007669416_pyramid_python.txt
Q: parsing arguments from python to c++ I wanted to know how could I change the values of arguments in a C++/C program from python. In the program below I use the Newton-Raphson method to compute the roots of a function. What I want is to change the value of the variable xn (for the initial guess) to a certain value...
parsing arguments from python to c++
I wanted to know how could I change the values of arguments in a C++/C program from python. In the program below I use the Newton-Raphson method to compute the roots of a function. What I want is to change the value of the variable xn (for the initial guess) to a certain value given in a python interface. This code is...
[ "If you want it to act like Python then it's best to just write it in Python.\nYou cannot just \"change the numbers\" of a compiled program. What you CAN do, however, is make the program accept parameters that you then change at runtime. You can do this in C++ with command-line parameters, configuration files, or a...
[ 1, 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0007680226_c++_python.txt
Q: Python Regular Expression nltk website extraction Hi I have never had to deal with regex before and I'm trying to preprocess some raw text with Python and NLTK. when I tried to tokenize the document using : tokens = nltk.regexp_tokenize(corpus, sentence_re) sentence_re = r'''(?x) # set flag to allow verbose rege...
Python Regular Expression nltk website extraction
Hi I have never had to deal with regex before and I'm trying to preprocess some raw text with Python and NLTK. when I tried to tokenize the document using : tokens = nltk.regexp_tokenize(corpus, sentence_re) sentence_re = r'''(?x) # set flag to allow verbose regexps ([A-Z])(\.[A-Z])+\.? # abbreviations, e.g. U.S.A...
[ "In this tokenizer RegularExpressions are used to specify how the Tokens you want to extract from the text can look like.\nI'm a bit confused which of the many regular expressions above you used, but for a very simple tokenization to non-whitespace tokens you could use:\n>>> corpus = \"this is a sentence. and anoth...
[ 3 ]
[]
[]
[ "nltk", "python", "regex" ]
stackoverflow_0007679970_nltk_python_regex.txt
Q: How can I keep Task Manager from killing my pythonw script? I want to run a python script for several days, performing a huge database calculation, on a "public" windows computer in my work place. Since this task is important, I want to prevent closing it from the task manager. Is it possible to protect a python...
How can I keep Task Manager from killing my pythonw script?
I want to run a python script for several days, performing a huge database calculation, on a "public" windows computer in my work place. Since this task is important, I want to prevent closing it from the task manager. Is it possible to protect a python script from being closed by the task manager (windows xp)? If it...
[ "Hopefully you aren't giving \"public\" general users administrative privileges. Don't give the public account permission to close your script. Then you just run your script from a different user account than the account the general public can use.\n" ]
[ 0 ]
[]
[]
[ "process", "python", "taskmanager", "windows" ]
stackoverflow_0007671375_process_python_taskmanager_windows.txt
Q: how do you split a string to create nested list? How would you split a string like '1,55,6,89,2|7,29,44,5,8|767,822,999' on the two delimiters ',' and '|' such that you have a list with the values like: [[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]] A: List comprehension are the most terse way to accom...
how do you split a string to create nested list?
How would you split a string like '1,55,6,89,2|7,29,44,5,8|767,822,999' on the two delimiters ',' and '|' such that you have a list with the values like: [[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]
[ "List comprehension are the most terse way to accomplish this.\n>>> s = '1,55,6,89,2|7,29,44,5,8|767,822,999'\n>>> [[int(x) for x in ss.split(',')] for ss in s.split('|')]\n[[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]\n\n", "my_data = [x.split(',') for x in input_string.split('|')]\n\n", "my_data = [...
[ 6, 0, 0 ]
[ "import re\n\n\nregx = re.compile('(\\A)|(\\|)|(\\Z)')\n\ndef repl(mat, di = {1:'[[', 2:'],[', 3:']]'} ):\n return di[mat.lastindex]\n\nss = '1,55,6,89,2|7,29,44,5,8|767,822,999'\n\nmy_data = eval( regx.sub(repl,ss) )\n\nprint my_data[1]\nprint my_data[1][2]\n\nresult\n[7, 29, 44, 5, 8]\n44\n\nI know: some will ...
[ -3 ]
[ "list", "python", "split", "string" ]
stackoverflow_0007680729_list_python_split_string.txt
Q: Redirecting existing Windows Explorer instance I have a program that opens a lot of folders right now, and I am hoping that I can use the already open explorer instances to open new ones. I have this code: import subprocess subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"') I have seen threads on doin...
Redirecting existing Windows Explorer instance
I have a program that opens a lot of folders right now, and I am hoping that I can use the already open explorer instances to open new ones. I have this code: import subprocess subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"') I have seen threads on doing this in C#. Does anyone know a way it can be done...
[ "I do not believe you can do this. If there is any hope you will probably need to look at Python for .Net, you might give IronPython a try. But the code above using subprocess is simply giving you the same result as if you ran that string in command line. Which launches the explorer application with those arguments...
[ 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007662521_python_windows.txt
Q: Inexplicable Urllib2 problem between virtualenv's. I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: Log in to a remote website Move to another page Perform a POST by filling in a form I've created 4 separate, clean virtualenvs (with ...
Inexplicable Urllib2 problem between virtualenv's.
I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: Log in to a remote website Move to another page Perform a POST by filling in a form I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with dif...
[ "You might try setting the debuglevel=1 for urllib2 and see what it comes up with:\nimport urllib2\nh=urllib2.HTTPHandler(debuglevel=1)\nopener = urllib2.build_opener(h)\n...\n\n", "This is a total shot in the dark, but are your VPSs 64-bit and your home computer 32-bit, or vice versa? Maybe a difference in defa...
[ 1, 1, 1, 0 ]
[]
[]
[ "cookies", "http", "mechanize", "python", "urllib2" ]
stackoverflow_0007508686_cookies_http_mechanize_python_urllib2.txt
Q: What's the best language/technique to perform advanced data cleansing and formatting on a SQL/MySQL/PostgreSQL table? We have a bunch of utility scripts in Visual FoxPro, which we use to interactively cleanse/format data. We'd like to start migrating this code to make use of other database platforms, like MySQL o...
What's the best language/technique to perform advanced data cleansing and formatting on a SQL/MySQL/PostgreSQL table?
We have a bunch of utility scripts in Visual FoxPro, which we use to interactively cleanse/format data. We'd like to start migrating this code to make use of other database platforms, like MySQL or SQLite. For instance we have a script that we run which converts the name and/or address lines to proper upper/lower ca...
[ "It seems like you're trying to do several things all at once. Could you take a step-by-step approach? Perhaps cleansing the data as they are right now using your normal, usual scripts. Then migrate the database to MySQL.\nIt is easy to migrate the database if VisualFoxPro offers a way to export the database to, sa...
[ 0 ]
[]
[]
[ "data_cleaning", "foxpro", "mysql", "python", "sqlalchemy" ]
stackoverflow_0007681017_data_cleaning_foxpro_mysql_python_sqlalchemy.txt
Q: Modifying module globals using externally defined function I have a very simple decorator function I use to expose functions defined in a module via the module’s __all__ property. Because I use it for multiple modules within a package, I have it defined in the package’s __init__.py. Because I cannot use __all__ fr...
Modifying module globals using externally defined function
I have a very simple decorator function I use to expose functions defined in a module via the module’s __all__ property. Because I use it for multiple modules within a package, I have it defined in the package’s __init__.py. Because I cannot use __all__ from within the definition, as it would refer to the __all__ of th...
[ "You might like Thomas Rachel's AllList decorator:\nclass AllList(list):\n \"\"\"list which can be called in order to be used as a __all__-adding decorator\"\"\"\n def __call__(self, obj):\n \"\"\"for decorators\"\"\"\n self.append(obj.__name__)\n return obj \n\nImport it from whereever, ...
[ 2 ]
[]
[]
[ "python", "python_3.x", "python_module" ]
stackoverflow_0007681410_python_python_3.x_python_module.txt
Q: in python how do I figure out the current path of the os.walk()? So I let a user to set a path to a directory that may contain subdirectories (more levels), and files. I use os.walk() in my code to scan the whole directory: for root, subdirs, files in os.walk(thispath): for myfile in files: shutil.move(os.p...
in python how do I figure out the current path of the os.walk()?
So I let a user to set a path to a directory that may contain subdirectories (more levels), and files. I use os.walk() in my code to scan the whole directory: for root, subdirs, files in os.walk(thispath): for myfile in files: shutil.move(os.path.realpath(myfile), os.path.join(thispath,filename)) but "os.path.r...
[ "for root, subdirs, files in os.walk(this_path):\n for my_file in files:\n shutil.move(os.path.join(root, my_file), os.path.join(this_path, filename))\n\n" ]
[ 1 ]
[]
[]
[ "absolute", "os.walk", "path", "python" ]
stackoverflow_0007681606_absolute_os.walk_path_python.txt
Q: How do you port bash aliases to ipython > 0.10? How do you port your bash aliases to IPython version >= 0.11? This question has already been answered for IPython < 0.11, and link for that is here: http://ipython.scipy.org/Wiki/tips A: Here is my solution. Improvements welcome! In your ipython config, add the fo...
How do you port bash aliases to ipython > 0.10?
How do you port your bash aliases to IPython version >= 0.11? This question has already been answered for IPython < 0.11, and link for that is here: http://ipython.scipy.org/Wiki/tips
[ "Here is my solution. Improvements welcome!\nIn your ipython config, add the following lines: (mine is here: ~/.config/ipython/profile_default/ipython_config.py)\nc = get_config()\n\n## Port bash aliases to ipython\nimport os, string\na = os.popen(\"bash -l -c 'alias'\").read()\na = a.translate(string.maketrans(\"=...
[ 2 ]
[]
[]
[ "aliases", "bash", "configuration", "ipython", "python" ]
stackoverflow_0007584536_aliases_bash_configuration_ipython_python.txt
Q: Parsing a document with BeautifulSoup while not-parsing the contents of tags I'm writing a blog app with Django. I want to enable comment writers to use some tags (like <strong>, a, et cetera) but disable all others. In addition, I want to let them put code in <code> tags, and have pygments parse them. For exampl...
Parsing a document with BeautifulSoup while not-parsing the contents of tags
I'm writing a blog app with Django. I want to enable comment writers to use some tags (like <strong>, a, et cetera) but disable all others. In addition, I want to let them put code in <code> tags, and have pygments parse them. For example, someone might write this comment: I like this article, but the third code exampl...
[ "The problem is that <code> is treated according to the normal rules for HTML markup, and content inside <code> tags is still HTML (The tags exists mainly to drive CSS formatting, not to change the parsing rules).\nWhat you are trying to do is create a different markup language that is very similar, but not identic...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "django", "html", "pygments", "python" ]
stackoverflow_0004007434_beautifulsoup_django_html_pygments_python.txt
Q: Issue for insert using psycopg I am reading data from a .mat file using the Pytables module. After reading the data, I want to insert this data into the database using psycopg. Here is a sample code piece: file = tables.openFile(matFile) x = 0 #populate the matData list for var in dest: data = file.getNode('/' ...
Issue for insert using psycopg
I am reading data from a .mat file using the Pytables module. After reading the data, I want to insert this data into the database using psycopg. Here is a sample code piece: file = tables.openFile(matFile) x = 0 #populate the matData list for var in dest: data = file.getNode('/' + var)[:] matData.append(data) ...
[ "The INSERT statement has invalid syntax. There something wrong inside the for loop you mention.\nYou should include the for loop in the question.\n\nINSERT INTO \"DUMMY1km\" (data) VALUES ([[-3000 -3000 -3000 .....\n\nA valid statement could look like this - assuming your column is of type integer[].\n... which yo...
[ 2 ]
[]
[]
[ "matlab", "postgresql", "psycopg2", "pytables", "python" ]
stackoverflow_0007681622_matlab_postgresql_psycopg2_pytables_python.txt
Q: NoReverseMatch at / when redirecting urls url(r'^add/$', 'advice.views.add_new_advice'), url(r'^$', 'advice.views.index'), url(r'^(?P<advice_id>\d+)/$', 'advice.views.detail'), views def add_new_advice(request): if request.method == "POST": form = AdviceForm(request.POST) if form.is_valid(): ...
NoReverseMatch at / when redirecting
urls url(r'^add/$', 'advice.views.add_new_advice'), url(r'^$', 'advice.views.index'), url(r'^(?P<advice_id>\d+)/$', 'advice.views.detail'), views def add_new_advice(request): if request.method == "POST": form = AdviceForm(request.POST) if form.is_valid(): new_advice = form.cleaned_data...
[ "You didn't call anything \"detail\" so it's not going to find it. Either add the name in your urls.py, use the full path to the function, or pass the function itself instead of a string.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007681869_django_python.txt
Q: Problem with importing module and NameError: global name 'module' is not defined Sorry, if this question has been asked before. I've looked around for quite a while and I haven't found a solution. So I've created a class in the file ResourceOpen.py class ResourceOpen(): import urllib.request def __init_...
Problem with importing module and NameError: global name 'module' is not defined
Sorry, if this question has been asked before. I've looked around for quite a while and I haven't found a solution. So I've created a class in the file ResourceOpen.py class ResourceOpen(): import urllib.request def __init__(self, source): try: # Try to open URL pa...
[ "Don't import on the class level, just do:\nimport urllib.request\n\nclass ResourceOpen(): \n\n def __init__(self, source):\n try:\n # Try to open URL\n page = urllib.request.urlopen(source)\n self.text = page.read().decode(\"utf8\")\n except ...
[ 5, 0 ]
[]
[]
[ "module", "namespaces", "python" ]
stackoverflow_0005146122_module_namespaces_python.txt
Q: django rollback transaction in save method I have the following piece of code overriding the save method of a model: @transaction.commit_on_success def save(self, *args, **kwargs): try: transaction.commit() self.qa.vote_down_count += 1 self.qa.save() super(self.__class__, self...
django rollback transaction in save method
I have the following piece of code overriding the save method of a model: @transaction.commit_on_success def save(self, *args, **kwargs): try: transaction.commit() self.qa.vote_down_count += 1 self.qa.save() super(self.__class__, self).save(*args, **kwargs) except: tra...
[ "Why not simply do:\n@transaction.commit_manually\ndef save(self, *args, **kwargs):\n try:\n super(self.__class__, self).save(*args, **kwargs)\n self.qa.vote_down_count += 1\n self.qa.save()\n except:\n transaction.rollback()\n raise\n else:\n transaction.commit()\...
[ 6, 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003174694_django_python.txt
Q: Auto-restart system in Python I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process. I'm considering implementing a while loop that essentially does ps -ef | grep process name and when the...
Auto-restart system in Python
I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process. I'm considering implementing a while loop that essentially does ps -ef | grep process name and when the process isn't found it starts anot...
[ "Why implement it yourself? An existing utility like daemon or Debian's start-stop-daemon is more likely to get the other difficult stuff right about running long-living server processes.\nAnyway, when you start the service, put its pid in /var/run/<name>.pid and then make your ps command just look for that process...
[ 5, 3, 1, 1, 0, 0 ]
[]
[]
[ "linux", "pid", "python", "restart" ]
stackoverflow_0000902085_linux_pid_python_restart.txt
Q: How can I place delimiters between numbers and text in Python? I'm having trouble placing delimiters in the following text. I want to place a '|' between the text and between each of the 3 subsequent numbers. The problem is that sometimes the numbers are actually dashes to signify 0 (i.e., -- instead of 0). text...
How can I place delimiters between numbers and text in Python?
I'm having trouble placing delimiters in the following text. I want to place a '|' between the text and between each of the 3 subsequent numbers. The problem is that sometimes the numbers are actually dashes to signify 0 (i.e., -- instead of 0). text = """ A line of text 85 25,653 -75,321 Another - line ...
[ "Using Python string methods:\nfor line in text.splitlines():\n line = line.split()\n if line:\n print '|'.join((' '.join(line[:-3]), '|'.join(line[-3:])))\n\nThis splits the line wherever there is whitespace, then joins the three data columns with |s and the text together with s, then adds a final | b...
[ 2 ]
[]
[]
[ "delimiter", "python", "text" ]
stackoverflow_0007682070_delimiter_python_text.txt
Q: python non-web application pattern In web design I use MVC pattern, but sometimes I need to create non-web application. This may be some parser or GUI utility program. What pattern is a classic solution for this kind of application? A: MVC is just as applicable to non-web applications. The only things that chan...
python non-web application pattern
In web design I use MVC pattern, but sometimes I need to create non-web application. This may be some parser or GUI utility program. What pattern is a classic solution for this kind of application?
[ "MVC is just as applicable to non-web applications. The only things that change are the View (GUI controls instead of web controls) and the types of input the Controller can/must deal with.\n", "The most straightforward approach for utility type program would be something like the following pseudocode-ish Python ...
[ 3, 1 ]
[]
[]
[ "parsing", "python", "user_interface" ]
stackoverflow_0007681871_parsing_python_user_interface.txt
Q: Python threading.Thread can be stopped only with private method self.__Thread_stop() I have a function that accepts a large array of x,y pairs as an input which does some elaborate curve fitting using numpy and scipy and then returns a single value. To try and speed things up I am trying to have two threads that I...
Python threading.Thread can be stopped only with private method self.__Thread_stop()
I have a function that accepts a large array of x,y pairs as an input which does some elaborate curve fitting using numpy and scipy and then returns a single value. To try and speed things up I am trying to have two threads that I feed the data to using Queue.Queue . Once the data is done. I am trying to have the threa...
[ "In general it is a bad idea to kill a thread that modifies shared resource.\nCPU intensive tasks in multiple threads are worse than useless in Python unless you release GIL while performing computations. Many numpy functions do release GIL.\nThreadPoolExecutor example from the docs\nimport concurrent.futures # on ...
[ 5, 4, 0 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0007680589_multithreading_python_queue.txt
Q: printing a list from a database Here is the program called Telephone: import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number ...
printing a list from a database
Here is the program called Telephone: import shelve import string UNKNOWN = 0 HOME = 1 WORK = 2 FAX = 3 CELL = 4 class phoneentry: def __init__(self, name = 'Unknown', number = 'Unknown', type = UNKNOWN): self.name = name self.number = number self.type = type # create st...
[ "You need to use something more sophisticated than cmp(); try fnmatch.fnmatch() instead, passing '*' to find all entries. You may want to look at fnmatch.filter() as well.\n" ]
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007682343_list_python.txt
Q: How do I split a line by commas, but ignore commas within quotes Python Possible Duplicate: How to read a CSV line with "? I have seen a number of related questions but none have directly addressed what I am trying to do. I am reading in lines of text from a CSV file. All the items are in quotes and some have ...
How do I split a line by commas, but ignore commas within quotes Python
Possible Duplicate: How to read a CSV line with "? I have seen a number of related questions but none have directly addressed what I am trying to do. I am reading in lines of text from a CSV file. All the items are in quotes and some have additional commas within the quotes. I would like to split the line along c...
[ "Don't try to re-invent the wheel.\nIf you want to read lines from a CSV file, use Python's csv module from the standard library.\nExample:\n> cat test.py\nimport csv\nwith open('some.csv') as f:\n reader = csv.reader(f)\n for row in reader:\n print(row)\n> cat some.csv\n\"114111\",\"Planes,Trains,and ...
[ 39 ]
[ "You can probably split on \",\" that is \"[quote][comma][quote]\"\nthe other option is coming up with an escape character, so if somebody wants to embed a comma in the string they do \\c and if they want a backslash they do \\\\. Then you have to split the string, then unescape it before processing.\n" ]
[ -5 ]
[ "csv", "python" ]
stackoverflow_0007682561_csv_python.txt
Q: Python: Get file path from a text file Let say there is a sample text file in Linux [SampleText.txt] 1234 = 1234 abcd = 1234 efgh = /home/user/targetfile1.txt ijkl = /home/user/targetfile2.txt How I can get the specific path (/home/user/targetfile1.txt & /home/user/targetfile2.txt) out from the SampleText.t...
Python: Get file path from a text file
Let say there is a sample text file in Linux [SampleText.txt] 1234 = 1234 abcd = 1234 efgh = /home/user/targetfile1.txt ijkl = /home/user/targetfile2.txt How I can get the specific path (/home/user/targetfile1.txt & /home/user/targetfile2.txt) out from the SampleText.txt and place it in a variable?
[ "You need the ConfigParser module:\nhttp://docs.python.org/library/configparser.html\nIt parses files that look like this. Not knowing your exact situation, I can't be sure. \n", "My suggested approach is to parse the file as a general configuration file, and store things that look like assignments. If you have o...
[ 1, 1 ]
[]
[]
[ "extract", "path", "python" ]
stackoverflow_0007682712_extract_path_python.txt
Q: Django/gevent socket.IO with redis pubsub. Where do I put things? I have an isolated python script that simply captures data from Twitter's streaming API and then on the receipt of each message, using redis pubsub it publishes to the channel "tweets". Here is that script: def main(): username = "username" ...
Django/gevent socket.IO with redis pubsub. Where do I put things?
I have an isolated python script that simply captures data from Twitter's streaming API and then on the receipt of each message, using redis pubsub it publishes to the channel "tweets". Here is that script: def main(): username = "username" password = "password" track_list = ["apple", "microsoft", "google"]...
[ "The problem was that I was using socket.broadcast_channel when I should have been using socket.send.\n" ]
[ 3 ]
[]
[]
[ "django", "gevent", "publish_subscribe", "python", "socket.io" ]
stackoverflow_0007678402_django_gevent_publish_subscribe_python_socket.io.txt
Q: Getting Apache cgi to send json in Python I have an apache server that I am using for cgi. I am writing my cgis in Python. As long as my responses are of the form "Content-Type: text/html\n #" it works. But if I send anything else, I get a 500 error and my logs say "malformed header from script. Bad header" Can ...
Getting Apache cgi to send json in Python
I have an apache server that I am using for cgi. I am writing my cgis in Python. As long as my responses are of the form "Content-Type: text/html\n #" it works. But if I send anything else, I get a 500 error and my logs say "malformed header from script. Bad header" Can I change my configurations to make it work? Is...
[ "As with all CGI, you need a blank line between the headers and the body.\nprint 'Content-Type: text/plain'\nprint\nprint 'Hello, World!'\n\n", "You need to send a Content-Type header to tell the browser what type of data you're sending it. Without that you'll get the 500 error you're experiencing.\n" ]
[ 4, 1 ]
[]
[]
[ "ajax", "apache", "cgi", "python" ]
stackoverflow_0007683597_ajax_apache_cgi_python.txt
Q: django/python: screen sharing api I am looking for a screen sharing functionality api in django/python which allows remote users to view your desktop in real time. Any recommendations on a library/api to use? Thanks. A: Django is a web development framework; remote desktop viewing is a client-side task. It may b...
django/python: screen sharing api
I am looking for a screen sharing functionality api in django/python which allows remote users to view your desktop in real time. Any recommendations on a library/api to use? Thanks.
[ "Django is a web development framework; remote desktop viewing is a client-side task. It may be possible to integrate screen sharing into a web site that is built using Django, but Django itself will likely have no involvement with the \"guts\" of the task.\n" ]
[ 4 ]
[]
[]
[ "api", "django", "python" ]
stackoverflow_0007683769_api_django_python.txt
Q: Test for list membership and get index at the same time in Python It seems silly to write the following: L = [] if x in L: L[x] = something else: L[x] = something_else Doesn't this perform the look-up for x twice? I tried using index(), but this gives an error when the value is not found. Ideally I would ...
Test for list membership and get index at the same time in Python
It seems silly to write the following: L = [] if x in L: L[x] = something else: L[x] = something_else Doesn't this perform the look-up for x twice? I tried using index(), but this gives an error when the value is not found. Ideally I would like to say like: if x is in L, save that index and: ... I can appre...
[ "Do you mean you want setdefault(key[, default])\na = {}\na['foo'] # KeyError\na.setdefault('foo', 'bar') # key not exist, set a['foo'] = 'bar'\na.setdefault('foo', 'x') # key exist, return 'bar'\n\n", "Another option is try/except:\nd = {}\ntry:\n d[x] = something_else\nexcept KeyError:\n d[x] = something\...
[ 2, 2, 1, 0 ]
[]
[]
[ "idioms", "indexing", "list", "python" ]
stackoverflow_0007683049_idioms_indexing_list_python.txt
Q: How to determine file's extended attributes and resource forks with their size on Mac OSX? I had written a small utility for creating xml for any folder structure and comparison of folders via generated xml that supports both win and Mac as platforms. However on Mac, recursively calculating folder size don't adds ...
How to determine file's extended attributes and resource forks with their size on Mac OSX?
I had written a small utility for creating xml for any folder structure and comparison of folders via generated xml that supports both win and Mac as platforms. However on Mac, recursively calculating folder size don't adds up to total size. On investigation, it came that it is due to extended attributes and resource f...
[ "Merely a partial answer ... but to learn the size of resource forks you can simply use the namedfork psuedodirectory\nos.path.getsize(\"<path to file of interest>/..namedfork/rsrc\")\n\nIts theoretically possible that other named forks may exist ... but you can't discover a list of available forks.\nAs to the exte...
[ 3, 3, 2 ]
[]
[]
[ "file_forks", "macos", "python" ]
stackoverflow_0007573440_file_forks_macos_python.txt
Q: Way to download/decode .torrent files? Is there a way to download all of the chunks or contents from a Torrent file In python? say i had a torrent file with contents song1.mp3 song2.mp3 song3.mp3 how would i download these files? A: You can use a python client. The last version of the original Bittorrent client ...
Way to download/decode .torrent files?
Is there a way to download all of the chunks or contents from a Torrent file In python? say i had a torrent file with contents song1.mp3 song2.mp3 song3.mp3 how would i download these files?
[ "You can use a python client.\nThe last version of the original Bittorrent client is available via Sourceforge:\nhttp://sourceforge.net/p/bittorrent/code/\nThere is also Bittornado as a pure python client:\nhttp://www.bittornado.com/\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007683181_python.txt
Q: Activate render man in Maya 2012 For some reason my render window in Maya doesn't work. Is there any way I can activate it by using MEL script or Python? I think it's disabled. Thanks. A: Maybe this helps: http://3dg.me/3d-graphics/maya/fix-for-maya-2012-error-setparent-object-renderview-not-found You can delet...
Activate render man in Maya 2012
For some reason my render window in Maya doesn't work. Is there any way I can activate it by using MEL script or Python? I think it's disabled. Thanks.
[ "Maybe this helps: http://3dg.me/3d-graphics/maya/fix-for-maya-2012-error-setparent-object-renderview-not-found\nYou can delete (save it before delete) your prefs directory. It helps sometimes\n" ]
[ 0 ]
[]
[]
[ "maya", "mel", "python" ]
stackoverflow_0007620676_maya_mel_python.txt
Q: UserWarning: Module _mysql was already imported from /usr/lib/pymodules/python2.6/_mysql.so I have deployed a django project on a server running under debian lenny. Every time it starts up the following warning pops up: /var/www/environment/XXX/src/django-pytest/django_pytest/test_runner.py:3: UserWarning: Module ...
UserWarning: Module _mysql was already imported from /usr/lib/pymodules/python2.6/_mysql.so
I have deployed a django project on a server running under debian lenny. Every time it starts up the following warning pops up: /var/www/environment/XXX/src/django-pytest/django_pytest/test_runner.py:3: UserWarning: Module _mysql was already imported from /usr/lib/pymodules/python2.6/_mysql.so, but /usr/lib/pymodules/p...
[ "Your problem was caused by having 2 \"distribute\" packages installed as can be seen from the yolk output provided.\n", "I have simply removed django_pytest from INSTALLED_APPS. The problem is now gone. Not nice but it works (tm).\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0006704774_django_python_virtualenv.txt
Q: Sort float in list of lists in Python? I am trying to sort a nested list structure based on the last values of each nested lists. My list looks like this: li = [['a1', 1, 1.56], ['b3', '6', 9.28], ['c2', 1, 6.25]...] The output I would like is: ['b3', '6', 9.28] ['c2', 1, 6.25] ['a1', 1, 1.56] I have tried a few...
Sort float in list of lists in Python?
I am trying to sort a nested list structure based on the last values of each nested lists. My list looks like this: li = [['a1', 1, 1.56], ['b3', '6', 9.28], ['c2', 1, 6.25]...] The output I would like is: ['b3', '6', 9.28] ['c2', 1, 6.25] ['a1', 1, 1.56] I have tried a few solutions that haven't worked using itemget...
[ "You're close with one of your approaches, but what you actually want is this:\nli.sort(key = itemgetter(2), reverse = True)\n\n", "rank_list = sorted(li, key=itemgetter(2))\n\n", "Strings can't be sorted, that's what AttributeError: 'str' object has no attribute 'sort' want to tell you. \nYou want to sort the ...
[ 4, 0, 0, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0007681665_list_python_sorting.txt
Q: Python, SqlAlchemy: Many to many relationship, find those without Say I have two types of objects, Movies and Tags, related by the ORM in a many to many relationship with an association table indicated by the secondary argument to relationship(), and I want to be able to find, say, all the Movies without Tags? Wha...
Python, SqlAlchemy: Many to many relationship, find those without
Say I have two types of objects, Movies and Tags, related by the ORM in a many to many relationship with an association table indicated by the secondary argument to relationship(), and I want to be able to find, say, all the Movies without Tags? What kind of query would I run to achieve that effect?
[ "If the TagId was part of the Movies object, this would be a simple case of checking if the TagId on Movies was null:\nsession.query(Movies).filter(Movies.TagId == None).all() \n\nBut your many-to-many comment suggests a MoviesTags link entity, so its trickier and involves linking to MoviesTags using a left outer...
[ 2, 2 ]
[]
[]
[ "database_design", "pylons", "python", "sql", "sqlalchemy" ]
stackoverflow_0007681103_database_design_pylons_python_sql_sqlalchemy.txt
Q: Website automation using Python I m trying to automate a Web Application validation performed by my team.I have choosen Python as the language to do this, although my exp. with Python is very limited.I have done similar things in the past using Perl. Now the problem is that after posting the url of the website it ...
Website automation using Python
I m trying to automate a Web Application validation performed by my team.I have choosen Python as the language to do this, although my exp. with Python is very limited.I have done similar things in the past using Perl. Now the problem is that after posting the url of the website it directs to a logon page which is made...
[ "Spynner may help http://code.google.com/p/spynner/ \n", "Maybe you can take a look a Selenium. It's a firefox plugin that enables automation, but it also has a webdriver system where you can write automation scripts in various languages (including python), and a server execute the code in various browsers. I nev...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007683988_python.txt
Q: Small clarification needed on numpy.any for matrices I am having a slight problem in getting numpy.any() to work fine on my problem. Consider I have a 3D matrix of N X M X M matrix, where I need to get rid of any matrix MXM that has all its elements the same [all zeros to say]. Here is an example to illustrate my ...
Small clarification needed on numpy.any for matrices
I am having a slight problem in getting numpy.any() to work fine on my problem. Consider I have a 3D matrix of N X M X M matrix, where I need to get rid of any matrix MXM that has all its elements the same [all zeros to say]. Here is an example to illustrate my issue x = np.arange(250).reshape(10,5,5) x[0,:,:] = 0 Wha...
[ "In a 10x5x5 matrix with x[0,:,:] = 0 I would expect a result of:\n[False, True, True, True, True, True, True, True, True, True]\n\nbecause it is the first of ten 5x5 arrays which is all zero and not of five.\nYou get this result using\nx.any(axis=1).any(axis=1)\n\nor\nx.any(axis=2).any(axis=1)\n\nwhich me...
[ 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007684501_numpy_python.txt
Q: One To Many Relationship definition with reflection and declarative syntax in sqlalchemy gives join condition error I am trying to set One-To-Many relationship on an existing database. Simplified DDL is : create table accnt ( code varchar(20) not null , def varchar(100) , constraint pk_accnt primary key (cod...
One To Many Relationship definition with reflection and declarative syntax in sqlalchemy gives join condition error
I am trying to set One-To-Many relationship on an existing database. Simplified DDL is : create table accnt ( code varchar(20) not null , def varchar(100) , constraint pk_accnt primary key (code) ); commit; create table slorder ( code varchar(20) not null , def varchar(100) , dt date , c_accnt varchar(2...
[ "I think you have to add ForeignKey in child table.\nBy the way of define ForeignKey you can assign value to c_accnt and also assign object of parent to accnt.\nInternally sqlalchemy fire the query which you wrote in primaryjoin. If there is no foreign key then model can't understand on which field it has to run a ...
[ 2, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007681701_python_sqlalchemy.txt
Q: How to detect the right font to use depending on the langage For a program of mine I have a database full of street name (using GIS stuff) in unicode. The user selects any part of the world he wants to see (using openstreetmap, google maps or whatever) and my program displays every streets selected using a nice fo...
How to detect the right font to use depending on the langage
For a program of mine I have a database full of street name (using GIS stuff) in unicode. The user selects any part of the world he wants to see (using openstreetmap, google maps or whatever) and my program displays every streets selected using a nice font to show their names. As you may know not every font can display...
[ "Use utf-8 text and a font that has glyphs for every possible character defined, like Arial/Verdana in Windows. That bypasses the entire detection problem. One font will handle everything.\n", "You need information about the language of the text.\nAnd when you decide what fonts you want, you do a mapping from lan...
[ 0, 0 ]
[]
[]
[ "fonts", "localization", "python", "unicode" ]
stackoverflow_0007638787_fonts_localization_python_unicode.txt
Q: Python PLY - something wrong with this grammar? I am trying to use Python PLY for a simple expression parser, and I can't get it to work. The code is available at bitbucket, but the offending parts are: First, the definitions: def p_expr_minus(p): '''expr : expr MINUS term''' p[0] = p[1]-p[3] and def p_...
Python PLY - something wrong with this grammar?
I am trying to use Python PLY for a simple expression parser, and I can't get it to work. The code is available at bitbucket, but the offending parts are: First, the definitions: def p_expr_minus(p): '''expr : expr MINUS term''' p[0] = p[1]-p[3] and def p_term_divide(p): '''term : term DIVIDE factor'''...
[ "Your parser is fine, but you are doing something stupid in your main() method:\ndef main():\n data = \"3*4+5*6-10\"\n data = raw_input()\n print yacc.parse(data[::-1])\n\nYou are feeding the parser with the reversed string: data[::-1]! No wonder that (9+7) gives an error, it is seen as )7+9( by the parse...
[ 2 ]
[]
[]
[ "grammar", "ply", "python" ]
stackoverflow_0007679263_grammar_ply_python.txt
Q: SQLite table in RAM instead of FLASH We're currently working on a python project that basically reads and writes M2M data into/from a SQLite database. This database consists of multiple tables, one of them storing current values coming from the cloud. This last table is worrying me a bit since it's being written v...
SQLite table in RAM instead of FLASH
We're currently working on a python project that basically reads and writes M2M data into/from a SQLite database. This database consists of multiple tables, one of them storing current values coming from the cloud. This last table is worrying me a bit since it's being written very often and the application runs on a fl...
[ "A very simple, SQL-only solution to create a in-memory table is using SQLite's ATTACH command with the special \":memory:\" pseudo-filename:\nATTACH DATABASE \":memory:\" AS memdb;\nCREATE TABLE memdb.my_table (...);\n\nSince the whole database \"memdb\" is kept in RAM, the data will be lost once you close the dat...
[ 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007685015_python_sqlite.txt
Q: subclassing beautifulsoup html parser, getting type error I wrote a little wrapper using beautifulsoup great html parser recently I tried to improve the code and make all beautifulsoup methods available directly in the wrapper class (instead of through a class property ) and I thought subclassing the beautifulsoup...
subclassing beautifulsoup html parser, getting type error
I wrote a little wrapper using beautifulsoup great html parser recently I tried to improve the code and make all beautifulsoup methods available directly in the wrapper class (instead of through a class property ) and I thought subclassing the beautifulsoup parser would be the best way to achieve this. Here is the the ...
[ "The error is not happening in BeautifulSoup code. Rather, your IDLE is not able to retreive and print the object. Try print str(e) instead.\n\nAnyway, subclassing BeautifulSoup in your situation may not be the best idea. Do you really want to inherit all of the parsing methods (like convert_charref, handle_pi or e...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007684794_beautifulsoup_python.txt
Q: Python: calling Fortran with subprocess and giving commands via communicate I want to call a Fortran program from python. I use the Popen statement from subprocess like this: p = Popen(['./finput'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) I then want to send some file names to the fortran program. The fortran pro...
Python: calling Fortran with subprocess and giving commands via communicate
I want to call a Fortran program from python. I use the Popen statement from subprocess like this: p = Popen(['./finput'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) I then want to send some file names to the fortran program. The fortran program reads them from stdin and then opens the files. If I use something like: p_s...
[ "Sounds like your Fortran might be getting Unicode, are you using Python 3? If so, then construct the string to be passed then use string.encode()\n" ]
[ 2 ]
[]
[]
[ "communicate", "python", "subprocess" ]
stackoverflow_0007684922_communicate_python_subprocess.txt
Q: Optimal file structure organization of Python module unittests? Sadly I observed that there are are too many ways to keep your unittest in Python and they are not usually well documented. I am looking for an "ultimate" structure, one would accomplish most of the below requirements: be discoverable by test framewo...
Optimal file structure organization of Python module unittests?
Sadly I observed that there are are too many ways to keep your unittest in Python and they are not usually well documented. I am looking for an "ultimate" structure, one would accomplish most of the below requirements: be discoverable by test frameworks, including: pytest nosetests tox the tests should be outside ...
[ "Here's the approach I've been using:\nDirectory structure\n# All __init__.py files are empty in this example.\napp\n package_a\n __init__.py\n module_a.py\n package_b\n __init__.py\n module_b.py\n test\n __init__.py\n test_app.py\n __init__.py\nmain.py\n\nmain....
[ 19 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0007685483_python_unit_testing.txt
Q: Add method that works with either a Point Object or a tuple One of my exercises says to write an add method for Points that works with either a Point object or a tuple: If the second operand is a Point, the method should return a new Point whose x coordinate is the sum of the x coordinates of the operands, and li...
Add method that works with either a Point Object or a tuple
One of my exercises says to write an add method for Points that works with either a Point object or a tuple: If the second operand is a Point, the method should return a new Point whose x coordinate is the sum of the x coordinates of the operands, and likewise for the y coordinates. If the second operand is a tuple, t...
[ "You can simply derive your class from the tuple (or just implement __getitem__).\nclass Point(tuple):\n def __new__(cls, x, y):\n return tuple.__new__(cls, (x, y))\n\n def __add__(self, other):\n return Point(self[0] + other[0], self[1] + other[1])\n\n def __repr__(self):\n return 'Po...
[ 2, 1 ]
[]
[]
[ "add", "overloading", "python" ]
stackoverflow_0007685984_add_overloading_python.txt
Q: Django - Prepare objects from a view for Current User Consider this model class Exercise(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Score(models.Model): """Scores of users by exercise""" exo = models.ForeignKey(Exercise) user = models.ForeignK...
Django - Prepare objects from a view for Current User
Consider this model class Exercise(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Score(models.Model): """Scores of users by exercise""" exo = models.ForeignKey(Exercise) user = models.ForeignKey(User) score = models.IntegerField() class Meta: ...
[ "What I'd do would be to get all the user's current scores up front, create a dictionary mapping exercise to score, then add the score as an attribute of each exercise. Something like:\nuser_scores = request.user.score_set.all()\nscore_dict = dict((sc.exo_id, sc.score) for sc in user_scores)\nexos = Exercise.object...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0007685012_django_django_views_python.txt
Q: Python script with a sleep() statement does not log when run in background I have a simple Python script I would like to run in the background, with the output redirected to a file e.g. ./test.py > output.log 2>&1 & This works fine so long as there is no sleep statement in my Python script: #! /usr/bin/env python...
Python script with a sleep() statement does not log when run in background
I have a simple Python script I would like to run in the background, with the output redirected to a file e.g. ./test.py > output.log 2>&1 & This works fine so long as there is no sleep statement in my Python script: #! /usr/bin/env python import sys import time from time import gmtime, strftime urls=['http://a', 'h...
[ "The output doesn't get lost, it simply takes a very long time to reach the file. This has to do with buffering: with the sleep it takes a long time for the output buffer to accumulate enough data to get flushed.\nIf you call sys.stdout.flush() just before calling sleep(), that'll make the output appear right away:...
[ 4, 1 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0007686207_bash_python_shell.txt
Q: Preserving styles using python's xlrd,xlwt, and xlutils.copy I'm using xlrd, xlutils.copy, and xlwt to open up a template file, copy it, fill it with new values, and save it. However, there doesn't seem to be any easy way to preserve the formatting of the cells; it always gets blown away and set to blank. Is ther...
Preserving styles using python's xlrd,xlwt, and xlutils.copy
I'm using xlrd, xlutils.copy, and xlwt to open up a template file, copy it, fill it with new values, and save it. However, there doesn't seem to be any easy way to preserve the formatting of the cells; it always gets blown away and set to blank. Is there any simple way I can do this? Thanks! /YGA A sample script: from...
[ "There are two parts to this.\nFirst, you must enable the reading of formatting info when opening the source workbook. The copy operation will then copy the formatting over.\nimport xlrd\nimport xlutils.copy\n\ninBook = xlrd.open_workbook('input.xls', formatting_info=True)\noutBook = xlutils.copy.copy(inBook)\n\nSe...
[ 55, 12 ]
[]
[]
[ "python", "xlrd", "xlwt" ]
stackoverflow_0003723793_python_xlrd_xlwt.txt
Q: python: AttributeError, 'module' object has no attribute 'something' Previously I asked a question here. That problem solved but there are error while developing the script. Currently, an option is obtained from command line like: ... -b b1 the code processing that is: import Mybench, optparse parser.add_option("...
python: AttributeError, 'module' object has no attribute 'something'
Previously I asked a question here. That problem solved but there are error while developing the script. Currently, an option is obtained from command line like: ... -b b1 the code processing that is: import Mybench, optparse parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") if o...
[ "bench_name is a string, not an identifier, so you need to use getattr():\nprocess.append(getattr(Mybench, bench_name))\n\n", "For me there's a difference between :\n - process.b1\n - process.bench_name => process.\"b1\"\ngetattr() may be the key of your wills.\n" ]
[ 4, 2 ]
[]
[]
[ "attributes", "command_line", "python" ]
stackoverflow_0007686704_attributes_command_line_python.txt
Q: Best way to access Firebird DB from a remote desktop. I have a Firebird DB set up on my computer and I want to be able to retrieve data from a different computer. What is the best way to go about this? I am running windows and using python. A: Run Firebird server on the computer with database file and connect ...
Best way to access Firebird DB from a remote desktop.
I have a Firebird DB set up on my computer and I want to be able to retrieve data from a different computer. What is the best way to go about this? I am running windows and using python.
[ "Run Firebird server on the computer with database file and connect to it from remote computer. You will need in Firebird client library installed on remote computer.\n", "I think we need a bit more info.\nDo you want database access - as in \"I want to be able to edit table layout and define new tables, views, p...
[ 0, 0, 0 ]
[]
[]
[ "database", "firebird", "python" ]
stackoverflow_0007666944_database_firebird_python.txt
Q: Combine XML files similar to ConfigParser's multiple file support I'm writing an application configuration module that uses XML in its files. Consider the following example: <?xml version="1.0" encoding="UTF-8"?> <Settings> <PathA>/Some/path/to/directory</PathA> <PathB>/Another/path</PathB> </Settings> No...
Combine XML files similar to ConfigParser's multiple file support
I'm writing an application configuration module that uses XML in its files. Consider the following example: <?xml version="1.0" encoding="UTF-8"?> <Settings> <PathA>/Some/path/to/directory</PathA> <PathB>/Another/path</PathB> </Settings> Now, I'd like to override certain elements in a different file that gets ...
[ "You could convert the XML into an instance of Python class:\nimport lxml.etree as ET\nimport io\n\nclass Settings(object):\n def __init__(self,text):\n root=ET.parse(io.BytesIO(text)).getroot()\n self.settings=dict((elt.tag,elt.text) for elt in root.xpath('/Settings/*'))\n def update(self,other...
[ 1, 0 ]
[]
[]
[ "configuration_files", "python", "xml" ]
stackoverflow_0007685087_configuration_files_python_xml.txt
Q: Generate python code of a class from an python instance of this class In my code, I generate new python classes at runtime. For some of them, I want to generate the python code, just as if I wrote these classes in a .py file. Let's say that I created dynamically a class A: type('A', (), {'bar':True} which is equiv...
Generate python code of a class from an python instance of this class
In my code, I generate new python classes at runtime. For some of them, I want to generate the python code, just as if I wrote these classes in a .py file. Let's say that I created dynamically a class A: type('A', (), {'bar':True} which is equivalent to the code: class A(object): bar=True What I want is to genera...
[ "You can use compile(), exec() or eval() depending on your exact needs.\n", "Generating the Python code from the class object itself is practically impossible. You need to save the instructions for generating the class in another way.\n\nThe best way may be having a function to make the class, and importing & cal...
[ 2, 2, 0 ]
[]
[]
[ "code_generation", "metaprogramming", "python" ]
stackoverflow_0007686620_code_generation_metaprogramming_python.txt
Q: Python slice command forgotten out of the loop I want to build some lists (a, b, c, d) by extending periodically those given in input. The structure of the periodicity is such that the first element of each list must not be repeated, while all the other elements must be until the maximum length set in input is rea...
Python slice command forgotten out of the loop
I want to build some lists (a, b, c, d) by extending periodically those given in input. The structure of the periodicity is such that the first element of each list must not be repeated, while all the other elements must be until the maximum length set in input is reached (it is possible that the period does not get to...
[ "The problem is that mylist = mylist[:max_len] creates a new list instead of modifying mylist in place, so the results never propagate back to a et al.\nIf you replace:\nmylist = mylist[:max_len]\n\nwith\nmylist[:] = mylist[:max_len]\n\nthat'll fix it.\nAs an aside, you could use itertools for the transformation:\n...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007686871_python.txt
Q: Get date from ISO week number in Python Possible Duplicate: What’s the best way to find the inverse of datetime.isocalendar()? I have an ISO 8601 year and week number, and I need to translate this to the date of the first day in that week (Monday). How can I do this? datetime.strptime() takes both a %W and a %U ...
Get date from ISO week number in Python
Possible Duplicate: What’s the best way to find the inverse of datetime.isocalendar()? I have an ISO 8601 year and week number, and I need to translate this to the date of the first day in that week (Monday). How can I do this? datetime.strptime() takes both a %W and a %U directive, but neither adheres to the ISO 86...
[ "With the isoweek module you can do it with:\nfrom isoweek import Week\nd = Week(2011, 40).monday()\n\n", "%W takes the first Monday to be in week 1 but ISO defines week 1 to contain 4 January. So the result from\ndatetime.strptime('2011221', '%Y%W%w')\n\nis off by one iff the first Monday and 4 January are in di...
[ 75, 37 ]
[]
[]
[ "iso", "python", "week_number" ]
stackoverflow_0005882405_iso_python_week_number.txt
Q: PyGtk CellRendererProgress start/end positions Is there any way to fill a gtk.CellRendererProgress indicating the start and end positions? Not just the end. As an example of what I would need to do is, instead of this: |##############################----------| (from 0% to 80%) I need to do this: |--------#######...
PyGtk CellRendererProgress start/end positions
Is there any way to fill a gtk.CellRendererProgress indicating the start and end positions? Not just the end. As an example of what I would need to do is, instead of this: |##############################----------| (from 0% to 80%) I need to do this: |--------######################----------| (from 25% to 80%) It's l...
[ "No, you can't do that. But you can write a custom cell renderer that does that, based on the code for CellRendererProgress.\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007672421_gtk_pygtk_python.txt
Q: Embedded WSGI backend for Python desktop app using webkit Disclaimer: I'm not very familiar with any of the things mentioned in the question title. Would it be possible to use a browser control (like Webkit) as a frontend for a WSGI app (using a framework like Flask) without starting a local WSGI server? Basically...
Embedded WSGI backend for Python desktop app using webkit
Disclaimer: I'm not very familiar with any of the things mentioned in the question title. Would it be possible to use a browser control (like Webkit) as a frontend for a WSGI app (using a framework like Flask) without starting a local WSGI server? Basically the requests and responses are managed by a middle layer betwe...
[ "It is in theory possible to write your own WSGI container that implements a full API and adapts that to WSGI. flup might bring some inspiration.\n", "Earlier today I saw exactly what you're asking for -- a way to call WSGI through an API without actually connecting over the network. However, it shouldn't be that...
[ 1, 0, 0 ]
[]
[]
[ "local", "python", "wsgi" ]
stackoverflow_0003521548_local_python_wsgi.txt
Q: Cleaning up an object only if an exception is raised I need to have a file deleted if not all the operations that must be done on it were successful (that is, if an exception is raised). It could have been as simple as using except:, deleting the file and then re-raising the exception, but in that case the origina...
Cleaning up an object only if an exception is raised
I need to have a file deleted if not all the operations that must be done on it were successful (that is, if an exception is raised). It could have been as simple as using except:, deleting the file and then re-raising the exception, but in that case the original exception would be lost if the file cannot be deleted in...
[ "Another option is to simply store the exception if you don't want to lose it:\nPython 3.x version:\ntry:\n file_path = \"whatever.jpg\"\n # do stuff with file\nexcept BaseException as e:\n try:\n os.unlink(file_path)\n except Exception:\n traceback.print_exc()\n raise e\n\nThe Python 2...
[ 5 ]
[]
[]
[ "exception", "python", "try_catch_finally" ]
stackoverflow_0007687012_exception_python_try_catch_finally.txt
Q: python/opencv: how to identify a cycle with points on the images given? I have a sequence of images of the heart arteries. Scanning through the images fast, could see the pattern on how the artery moves when the heart beats. On each image, the same junction point is detected and one can analyze the motion of the j...
python/opencv: how to identify a cycle with points on the images given?
I have a sequence of images of the heart arteries. Scanning through the images fast, could see the pattern on how the artery moves when the heart beats. On each image, the same junction point is detected and one can analyze the motion of the junction point. I have an array, storing the coordinates of the detected junc...
[ "you have to be more specific with the algorithm, can you please attach a screen shot.\nthe only algorithm I have been thinking about is a viola johnes for object detection. \nenjoy... \n" ]
[ -1 ]
[]
[]
[ "numpy", "opencv", "python", "scipy" ]
stackoverflow_0007679401_numpy_opencv_python_scipy.txt
Q: modeless dialog tkinter I'm using a class called customDialog, based on Based on http://effbot.org/tkinterbook/tkinter-dialog-windows.htm The standard code creates a class which subclasses Toplevel, and creates modal dialogs. I'm trying to adapt the code so it can also create modeless dialogs. The standard code ca...
modeless dialog tkinter
I'm using a class called customDialog, based on Based on http://effbot.org/tkinterbook/tkinter-dialog-windows.htm The standard code creates a class which subclasses Toplevel, and creates modal dialogs. I'm trying to adapt the code so it can also create modeless dialogs. The standard code calls the Toplevel constructor,...
[ "Remove the line that says self.grab_set(). A \"grab\" means to grab all events and direct them toward this window, which you don't want.\nIf you read a bit deeper into the web page where you got the code you'll see that it mentions this exact line and why it is there:\n\n... Next, the constructor creates the dialo...
[ 6 ]
[]
[]
[ "dialog", "non_modal", "python", "tkinter" ]
stackoverflow_0007687090_dialog_non_modal_python_tkinter.txt
Q: Are docstrings for internal functions (python) necessary? In python we designate internal function/ private methonds with an underscore at the beginning. Should these functions be documented with docstrings(is it required?)? (the formal documentation i mean, not the one helping the code-reader to understand the co...
Are docstrings for internal functions (python) necessary?
In python we designate internal function/ private methonds with an underscore at the beginning. Should these functions be documented with docstrings(is it required?)? (the formal documentation i mean, not the one helping the code-reader to understand the code) What is common practice for this?
[ "Lo, I quote from PEP 8, the wise words of which should be considered law. Upon this very topic, PEP 8 saith:\n\n\nWrite docstrings for all public modules, functions, classes, and\n methods. Docstrings are not necessary for non-public methods, but you\n should have a comment that describes what the method do...
[ 44 ]
[]
[]
[ "documentation", "pep8", "python", "standards" ]
stackoverflow_0007687407_documentation_pep8_python_standards.txt
Q: How to avoid nested try-s of increasing complexity/indentation in Python I have code like this: try: request=parse_request except: print "cannot parse your malformed request" exit() else: try: fh=a_factory_function() except: print "cannot create object" else: if requ...
How to avoid nested try-s of increasing complexity/indentation in Python
I have code like this: try: request=parse_request except: print "cannot parse your malformed request" exit() else: try: fh=a_factory_function() except: print "cannot create object" else: if request['operation']=='search': pass elif request['operation']...
[ "Errors should not pass silently. If you ask me, printing a message instead of raising an exception in this situation counts as “silently”.\nCalling exit() is worse – any time your function is called, no matter how deep in an imported library, a malformed request will kill the program.\nThe more Pythonic alternativ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007687029_python.txt
Q: More concise assignment for elements in a list (Python)? How can I do the following in a more concise, "pythonic" way: for element in some_list: if some_condition: element.some_attr = some_value A: The only thing that's not pythonic in your code is that you're not using 4 spaces for inden...
More concise assignment for elements in a list (Python)?
How can I do the following in a more concise, "pythonic" way: for element in some_list: if some_condition: element.some_attr = some_value
[ "The only thing that's not pythonic in your code is that you're not using 4 spaces for indentation.\n“Pythonic” doesn't always mean “concise”; for example the following is shorter, but less readable than your loop:\n[setattr(e, 'some_attr', some_value) for e in some_list if some_condition]\n\nSo, stick to the code ...
[ 1, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python", "python_2.x", "variable_assignment" ]
stackoverflow_0007687374_list_list_comprehension_python_python_2.x_variable_assignment.txt
Q: 'tuple' object does not support item assignment I am using the PIL library. I am trying to make an image look red-er, this is what i've got. from PIL import Image image = Image.open('balloon.jpg') pixels = list(image.getdata()) for pixel in pixels: pixel[0] = pixel[0] + 20 image.putdata(pixels) image.save...
'tuple' object does not support item assignment
I am using the PIL library. I am trying to make an image look red-er, this is what i've got. from PIL import Image image = Image.open('balloon.jpg') pixels = list(image.getdata()) for pixel in pixels: pixel[0] = pixel[0] + 20 image.putdata(pixels) image.save('new.bmp') However I get this error: TypeError: 'tu...
[ "PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:\npixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]\nimage.putdata(pixels)\n\nAlso, if the pixel is already too red, adding 20 will overflow the value. You probably want something li...
[ 63, 9, 6, 3, 3, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0007687510_python_python_imaging_library.txt
Q: How to pass variable to a python cgi script What I want to do is have a single python program in cgi-bin that is executed by each of many pages on the site, and displays a line of HTML on each page that is different for each file, but keyed to the URL of that file on the site. I know how to get the URL using javas...
How to pass variable to a python cgi script
What I want to do is have a single python program in cgi-bin that is executed by each of many pages on the site, and displays a line of HTML on each page that is different for each file, but keyed to the URL of that file on the site. I know how to get the URL using javascript (e.g. on http://constitution.org/cs_event.h...
[ "CGI puts various things to do with the current request into the script's shell environment, which you can access in the normal way with os.environ. In particular, os.environ['HTTP_HOST'] will get you the server name, and os.environ['SCRIPT_NAME'] will get you the path.\n" ]
[ 0 ]
[]
[]
[ "cgi", "html", "python", "url" ]
stackoverflow_0007687490_cgi_html_python_url.txt
Q: FieldError on ManyToMany after upgrading to Django 1.3 Just been updating to Django 1.3 and come across an odd error. I'm getting the following error from some code which works with version 1.2.7. FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type The odd thing bei...
FieldError on ManyToMany after upgrading to Django 1.3
Just been updating to Django 1.3 and come across an odd error. I'm getting the following error from some code which works with version 1.2.7. FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type The odd thing being email_config_set is a related name for a ManyToMany field...
[ "The problem in this case was due to dynamic models, and their creation order. More specifically, some models which were dynamically created after others, were not defined when the _meta caches were filled, and therefore lead to errors. Clearing the caches or changing the creation order resolves this problem.\nSee ...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007502566_django_django_models_python.txt
Q: Maximum flow - Ford-Fulkerson: Undirected graph I am trying to solve the maxium flow problem for a graph using Ford–Fulkerson algorithm. The algorithm is only described with a directed graph. What about when the graph is undirected? What I have done to mimic an undirected graph is to use two directed edges between...
Maximum flow - Ford-Fulkerson: Undirected graph
I am trying to solve the maxium flow problem for a graph using Ford–Fulkerson algorithm. The algorithm is only described with a directed graph. What about when the graph is undirected? What I have done to mimic an undirected graph is to use two directed edges between a pair of vertices. What confuses me is: Should each...
[ "Your approach using two antiparallel edges works. If your edge is a->b (capacity 10, we send 7 over it), we introduce a new residual edge (from b to a that has residual capacity 17, the residual edge from a to b has the remaining capacity 3). \nThe original back-edge (from b to a) can be left as it is or the new r...
[ 11 ]
[]
[]
[ "algorithm", "ford_fulkerson", "python" ]
stackoverflow_0007687732_algorithm_ford_fulkerson_python.txt
Q: python - not creating image I am trying to import an image, then manipulate its rgb colors. This is what i've got: from PIL import Image image = Image.open('grapes.jpg') pixels = list(image.getdata()) for pixel in pixels: pixel = (pixel[0] - 50, pixel[1] , pixel[2]) image.putdata(pixel) image.save('grapes_m...
python - not creating image
I am trying to import an image, then manipulate its rgb colors. This is what i've got: from PIL import Image image = Image.open('grapes.jpg') pixels = list(image.getdata()) for pixel in pixels: pixel = (pixel[0] - 50, pixel[1] , pixel[2]) image.putdata(pixel) image.save('grapes_modified.jpg') as you can see, i ...
[ "The for cycle doesn't replace the content of each pixel, it just creates a new instance and then tosses it away. You should create a new array, for example:\nnewdata = [ (pixel[0] - 50, pixel[1] , pixel[2]) for pixel in pixels ]\n\n" ]
[ 3 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0007688182_python_python_imaging_library.txt
Q: Python- initialisation of built in variables/attributes When and how are the builtin attributes initialized? __doc__, __name__ (I guess I know about this one :) ), __class__, __setattr__ etc. In my other question regarding docstrings, one of the answers mentioned that docstrings are just simple strings and I tried...
Python- initialisation of built in variables/attributes
When and how are the builtin attributes initialized? __doc__, __name__ (I guess I know about this one :) ), __class__, __setattr__ etc. In my other question regarding docstrings, one of the answers mentioned that docstrings are just simple strings and I tried with ', " and """ and they all worked. But when I used a var...
[ "It's different for each one. (After all, each one's special!) Some are the class attributes, some are instance attributes, some are inherited.\n__doc__ is initialized when the class is created (you can also pass it in the dict argument to the type constructor). The special syntax only works for string literals, bu...
[ 2 ]
[]
[]
[ "built_in", "docstring", "init", "initialization", "python" ]
stackoverflow_0007688037_built_in_docstring_init_initialization_python.txt
Q: convert dec number to 6 bit binary number I am looking to convert a dec number to a 6 bit binary number.. bin() works fine but omits leading zeros which are important. for example: 0 = 000000 1 = 000001 2 = 000010 etc... with the largest dec number allowed being 63. A: Either what Matt said in the comment (bin...
convert dec number to 6 bit binary number
I am looking to convert a dec number to a 6 bit binary number.. bin() works fine but omits leading zeros which are important. for example: 0 = 000000 1 = 000001 2 = 000010 etc... with the largest dec number allowed being 63.
[ "Either what Matt said in the comment (bin(63)[2:].zfill(6)), or use format strings in Python 2.6+:\n'{0:06b}'.format(63)\n\nYou can omit the first zero in Python 2.7+ as you can implicitly number groups.\n", "Or just:\nn2=[2**x for x in xrange(0, 7)]\nn2.reverse()\n\ndef getx(x):\n ret = ''\n for z in n2:\...
[ 9, 0 ]
[]
[]
[ "bin", "binary", "python" ]
stackoverflow_0007687928_bin_binary_python.txt
Q: Looking for working demos of APIs (any language) into Outlook to data mine emails to produce social graphs and knowledge graphs and tagging I'd like to data mine my Outlook mailboxes at work to be able to learn more about interactions with people and their areas of expertise: Generate social graphs from To: and C...
Looking for working demos of APIs (any language) into Outlook to data mine emails to produce social graphs and knowledge graphs and tagging
I'd like to data mine my Outlook mailboxes at work to be able to learn more about interactions with people and their areas of expertise: Generate social graphs from To: and Cc: lists to show people as nodes on a network with lines between who they interact with Tag people with concepts (i.e. from pronouns and recognis...
[ "You can link outlook folders to databases \n-- outlookcode.com/article.aspx?ID=25 \n-- support.microsoft.com/kb/209946\n...and once extracted to: list, cc: list and email text body strings from the database, you could consider ideas for data mining the data from the book \"Natural Language Processsing With Python\...
[ 3 ]
[]
[]
[ "data_mining", "outlook", "python", "text_parsing" ]
stackoverflow_0007686841_data_mining_outlook_python_text_parsing.txt
Q: How to setup PyCharm so '^M' doesn't show up in ubuntu When I load .py edited with PyCharm for Win on Ubuntu platform, I can see each line trailed with ^M. Is there a setting in PyCharm that I can avoid this annoying character? A: Settings | Code Style | General | Line Separator, set to \n (Unix).
How to setup PyCharm so '^M' doesn't show up in ubuntu
When I load .py edited with PyCharm for Win on Ubuntu platform, I can see each line trailed with ^M. Is there a setting in PyCharm that I can avoid this annoying character?
[ "Settings | Code Style | General | Line Separator, set to \\n (Unix).\n" ]
[ 6 ]
[]
[]
[ "ide", "pycharm", "python", "ubuntu" ]
stackoverflow_0007688398_ide_pycharm_python_ubuntu.txt
Q: Local Appengine stopped working I tried to run one of my AppEnigne projects (python) today but it will no longer launch, this is the stack trace I'm getting. *** Running dev_appserver with the following flags: --admin_console_server= --port=8080 --clear_datastore Python command: /usr/bin/python2.5 Traceback (...
Local Appengine stopped working
I tried to run one of my AppEnigne projects (python) today but it will no longer launch, this is the stack trace I'm getting. *** Running dev_appserver with the following flags: --admin_console_server= --port=8080 --clear_datastore Python command: /usr/bin/python2.5 Traceback (most recent call last): File "/Appl...
[ "Thanks to Nick and Wobble I've figured it out. I recently updated my XCode install to the 4.2 GM release and removed the beta versions. Along the way OSX forgot where gcc was installed and prevented it from compiling the python modules like logging. This resulted in missing .pyo files inside /System/Library/Framew...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007681290_google_app_engine_python.txt
Q: How do I convert excel file with n worksheets into n csv files? Is there a way to convert the worksheets in an excel file into a number of csv files? A: Yes. There is. xlrd will allow you to read a spreadsheet. http://pypi.python.org/pypi/xlrd csv will allow you to write CSV files. http://docs.python.org/li...
How do I convert excel file with n worksheets into n csv files?
Is there a way to convert the worksheets in an excel file into a number of csv files?
[ "Yes. There is.\n\nxlrd will allow you to read a spreadsheet. http://pypi.python.org/pypi/xlrd\ncsv will allow you to write CSV files. http://docs.python.org/library/csv.html\n\nThis happened to me so often, that I uploaded a spreadsheet reader library to SourceForge.\nhttp://sourceforge.net/projects/stingrayrea...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007675189_python.txt
Q: Removing delimiters I have a file looking like this: ('chr1', '1499102', '1500297') ('chr1', '1811177', '1812131') ('chr1', '2312420', '2313646') ('chr1', '6683999', '6684724') N number of rows. I want to print it like this: chr1 (tab) 1499102 (tab) 1500297 Any one liner shell or python or perl. A: perl -nE '$...
Removing delimiters
I have a file looking like this: ('chr1', '1499102', '1500297') ('chr1', '1811177', '1812131') ('chr1', '2312420', '2313646') ('chr1', '6683999', '6684724') N number of rows. I want to print it like this: chr1 (tab) 1499102 (tab) 1500297 Any one liner shell or python or perl.
[ "perl -nE '$,=\"\\t\"; say eval' file.txt\n\nMaking use of perl's output record separator, $, to provide the tabs. eval should be safe to use on single quoted strings, and is probably the best option. \n", "using python:\nfor line in open('filename'): print('%s\\t%s\\t%s'%(eval(line)))\n\n(of course, you need to ...
[ 8, 4, 4, 3, 2, 2 ]
[]
[]
[ "perl", "python", "shell" ]
stackoverflow_0007686194_perl_python_shell.txt
Q: How do I pass in a field to filter a Django model? I'm have a function that accepts two parameters: filter_field and filter_value. I want to filter my model like so: Alert.objects.filter(filter_field=filter_value) However, I get the following error: Cannot resolve keyword 'filter_field' into field. Choices are .....
How do I pass in a field to filter a Django model?
I'm have a function that accepts two parameters: filter_field and filter_value. I want to filter my model like so: Alert.objects.filter(filter_field=filter_value) However, I get the following error: Cannot resolve keyword 'filter_field' into field. Choices are ... Is there way to pass in the string that is being stor...
[ "You can pass keyword arguments to filter:\nkwargs = {filter_field: filter_value}\nAlert.objects.filter(**kwargs)\n\n" ]
[ 3 ]
[]
[]
[ "django", "filter", "model", "python", "string" ]
stackoverflow_0007688980_django_filter_model_python_string.txt
Q: Running Python Script from Cron.d I'm trying to run a Django management command via a crontab installed to /etc/cron.d/mycron on Ubuntu. I first tested my basic setup by writing the following to /etc/cron.d/mycron: * * * * * root command echo "Test $(date)" 2>&1 >> /tmp/mycron.log And I confirmed /tmp/mycron.log ...
Running Python Script from Cron.d
I'm trying to run a Django management command via a crontab installed to /etc/cron.d/mycron on Ubuntu. I first tested my basic setup by writing the following to /etc/cron.d/mycron: * * * * * root command echo "Test $(date)" 2>&1 >> /tmp/mycron.log And I confirmed /tmp/mycron.log was updated once a minute and contains ...
[ "The output you need is either in /tmp/mycron.log, or mailed to root. Type mail from under root to check.\nAlso, why are you trying different variations? The syntax of crontab files is strictly defined (man crontab -S 5), for /etc/crontab it is: \nmin hour day month weekday user cmdline\n\nfor personal crontabs, it...
[ 3 ]
[]
[]
[ "cron", "django", "python" ]
stackoverflow_0007689190_cron_django_python.txt
Q: PySchool- List (Topic 6-22) I am a beginner in python and i am trying to solve some questions about lists. I got stuck on one problem and I am not able to solve it: Write a function countLetters(word) that takes in a word as argument and returns a list that counts the number of times each letter appears. The...
PySchool- List (Topic 6-22)
I am a beginner in python and i am trying to solve some questions about lists. I got stuck on one problem and I am not able to solve it: Write a function countLetters(word) that takes in a word as argument and returns a list that counts the number of times each letter appears. The letters must be sorted in alphab...
[ "Use sets !\n m = \"google\"\n u = set(m)\n sorted([(l, m.count(l)) for l in u]) \n\n\n >>> [('e', 1), ('g', 2), ('l', 1), ('o', 2)]\n\n", "A hint: Note that you can loop through a string in the same way as a list or other iterable object in python:\ndef countLetters(word):\n\n for letter in word:\n print let...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007678825_python.txt
Q: python - how to put values in a word length histogram i want to put values at y-axis in the histogram i made. I want every 100 values for example to put "100-|" , "200-|" etc. My code is: def histogram(lenghts): xmax=max(lengths.keys()) ymax=max(lenght.values()) symbol="" indexing="" for j in...
python - how to put values in a word length histogram
i want to put values at y-axis in the histogram i made. I want every 100 values for example to put "100-|" , "200-|" etc. My code is: def histogram(lenghts): xmax=max(lengths.keys()) ymax=max(lenght.values()) symbol="" indexing="" for j in range(ymax,-1,-10): symbol="{0}".format("|") ...
[ "Here you have a working code. The trick is in the module operator that is used to draw the scale number of the y axis when the y axis is a number close to a hundred.\nThere were some other minor problems in your code with the variable names.\ndef histogram(lenghts):\n xmax = max(lenghts.keys())\n ymax = max(...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007687306_python.txt
Q: Calling a class method in python I'm looking to call a method in python from a different class like so: class foo(): def bar(name): return 'hello %s' % name def hello(name): a = foo().bar(name) return a Where hello('world') would return 'Hello World'. I'm aware I've done something wrong here,...
Calling a class method in python
I'm looking to call a method in python from a different class like so: class foo(): def bar(name): return 'hello %s' % name def hello(name): a = foo().bar(name) return a Where hello('world') would return 'Hello World'. I'm aware I've done something wrong here, does anyone know what it is? I think ...
[ "In Python, non-static methods explicitly take self as their first argument.\nfoo.bar() either needs to be a static method:\nclass foo():\n @staticmethod\n def bar(name):\n return 'hello %s' % name\n\nor has to take self as its first argument:\nclass foo():\n def bar(self, name):\n return 'he...
[ 6, 3, 3, 3 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0007689837_methods_python.txt
Q: How can I convert from U+0043 to C using Python? Does something exist that can take as input U+0043 and produce as output the letter C, maybe even a small description of the character ( like LATIN CAPITAL LETTER C )? EDIT: the U+0043 is just an example. I would like a generic solution please, that could work for ...
How can I convert from U+0043 to C using Python?
Does something exist that can take as input U+0043 and produce as output the letter C, maybe even a small description of the character ( like LATIN CAPITAL LETTER C )? EDIT: the U+0043 is just an example. I would like a generic solution please, that could work for as many codepoints as possible.
[ "unicodedata.name looks promising. You need a bit of (trivial) parsing, of course, if you have a string input like U+0043.\n", "The hackish way:\nimport unicodedata\n\ncodepoint = b\"U+0043\"\nchar = codepoint.replace('U+', \"\\u\").decode('unicode-escape')\n# or char = unichr(int(codepoint.replace('U+', ''), 16...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0007689527_python_unicode.txt
Q: Doing something every 60 seconds, asynchronously Here is a basic sample of code to show the base of the IRC bot I have running: s=socket.socket() s.connect((foo, 1234)) s.send('NICK foo\r\n') s.send('USER foo bar baz :qux\r\n') while True: readbuffer=readbuffer+s.recv(1024) temp=string.split(readbuffer, "...
Doing something every 60 seconds, asynchronously
Here is a basic sample of code to show the base of the IRC bot I have running: s=socket.socket() s.connect((foo, 1234)) s.send('NICK foo\r\n') s.send('USER foo bar baz :qux\r\n') while True: readbuffer=readbuffer+s.recv(1024) temp=string.split(readbuffer, "\n") readbuffer=temp.pop() for line in temp: ...
[ "I suggest reading this article. It goes over the details of coroutines, and asynchronous processing in python. Included is a bunch of sample python code that you can play with.\n", "Yes, you could. And yes, it would be outside the loop unless you wanted to time out the 60-second interval inside the loop by, say,...
[ 0, 0, 0 ]
[]
[]
[ "irc", "python" ]
stackoverflow_0007689242_irc_python.txt
Q: Having trouble writing XML in Python I have a XML file that I read with Python. I want to make some changes in the XML file and write it back out. Here is my code: from xml.dom.minidom import * filename = "file.xml" dom = xml.dom.minidom.parse(filename) dicts = dom.getElementsByTagName("dict") for dict in dict...
Having trouble writing XML in Python
I have a XML file that I read with Python. I want to make some changes in the XML file and write it back out. Here is my code: from xml.dom.minidom import * filename = "file.xml" dom = xml.dom.minidom.parse(filename) dicts = dom.getElementsByTagName("dict") for dict in dictList: keys = dict.getElementsByTagNa...
[ "Replace\nkey.firstChild.wholeText = \"new text\"\n\nwith either\nkey.firstChild.replaceWholeText(\"new text\")\n\nor\nkey.firstChild.data = \"new text\"\n\nThe key here is that xml.dom.minidom.Text.wholeText is a data descriptor, meant to be used more like a function than like an attribute. In fact, it collects d...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007689691_python.txt
Q: When documenting Python code with doxygen are you supposed to document self parameter? I have some Python code that was documented with doxygen and I would like to know if it's normal to document self parameter for methods? Example: ## @par Description: # Some desc # @note # # @param something @e string: a s...
When documenting Python code with doxygen are you supposed to document self parameter?
I have some Python code that was documented with doxygen and I would like to know if it's normal to document self parameter for methods? Example: ## @par Description: # Some desc # @note # # @param something @e string: a string # # @return @b Boolean: True if ... # # @b Example: # @code # # instance.myMe...
[ "I don't know what common practice is, but I wouldn't do it. It just adds clutter to the docs, since its usage is obvious. Clutter in documentation is bad beacuse it obscures the stuff you really want to see.\n" ]
[ 3 ]
[]
[]
[ "doxygen", "python" ]
stackoverflow_0007689876_doxygen_python.txt
Q: Why is ElementTree.iterparse() raising a ParseError? import xml.etree.ElementTree as ET xmldata = file('my_xml_file.xml') tree = ET.parse(xmldata) root = tree.getroot() root_iter = root.iter() Now I can call root_iter.next() and get my Element objects. The problem is the real file I am working with is huge and I...
Why is ElementTree.iterparse() raising a ParseError?
import xml.etree.ElementTree as ET xmldata = file('my_xml_file.xml') tree = ET.parse(xmldata) root = tree.getroot() root_iter = root.iter() Now I can call root_iter.next() and get my Element objects. The problem is the real file I am working with is huge and I can't fit all of it in memory. So I am trying to use: par...
[ "The code I had was perfectly fine, except I was calling ElementTree.iterparse() on a file object I had already read with ElementTree.parse(). D'oh!\n\nSo for those who happen to make the same mistake, the solution is to either open a new file object or use file.seek(0) to reset the file cursor.\n" ]
[ 3 ]
[]
[]
[ "elementtree", "parsing", "python", "xml", "xml_parsing" ]
stackoverflow_0007689679_elementtree_parsing_python_xml_xml_parsing.txt
Q: How do I loop through the rows in a column and count them using Python? I am trying to loop through column in an access table using Python. The column I have is sorted ascending. I am trying to loop though the rows and when the value in the column changes, I want to get count of of all those values. In the exampl...
How do I loop through the rows in a column and count them using Python?
I am trying to loop through column in an access table using Python. The column I have is sorted ascending. I am trying to loop though the rows and when the value in the column changes, I want to get count of of all those values. In the example column below, the first group of values I want to count are the M1's. When ...
[ "Your intuition to use itertools.groupby was correct:\nfor key, group in groupby(column):\n count = sum(1 for item in group) # Thanks JBernardo\n # the key is what is in the column, count is the number of items\n\nAlternatively, if all you need is the counts, it's as simple as:\nfrom collections import Counte...
[ 4, 1 ]
[]
[]
[ "count", "loops", "python" ]
stackoverflow_0007689569_count_loops_python.txt
Q: How to do fade-in sound in Python?? def fade_in (snd, fade_length): '''doing a sound fade-in for that wave file''' new_snd = sound.copy(snd) for sample in new_snd: snd_index = sound.get_index(sample) factor = 0 snd_samp = sound.get_sample(snd, snd_index) if snd_index <= fade_length: lef...
How to do fade-in sound in Python??
def fade_in (snd, fade_length): '''doing a sound fade-in for that wave file''' new_snd = sound.copy(snd) for sample in new_snd: snd_index = sound.get_index(sample) factor = 0 snd_samp = sound.get_sample(snd, snd_index) if snd_index <= fade_length: left = (sound.get_left(snd_samp) * factor) ...
[ "left and right will always be zero, as you set factor to zero every run in the for-loop. You have to declare factor outside of the for-loop:\ndef fade_in (snd, fade_length):\n new_snd = sound.copy(snd)\n factor = 0\n\n for sample in new_snd:\n snd_index = sound.get_index(sample)\n snd_samp =...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007690153_python.txt
Q: SQLAlchemy - Mapping subset of columns from inner join of autoloaded tables I've just started using SQLAlchemy to work with an existing Postgres DB. What I'd like to do is autoload two tables, perform an inner join and map a subset of the columns to an object. To accomplish all but the last part, I've written the ...
SQLAlchemy - Mapping subset of columns from inner join of autoloaded tables
I've just started using SQLAlchemy to work with an existing Postgres DB. What I'd like to do is autoload two tables, perform an inner join and map a subset of the columns to an object. To accomplish all but the last part, I've written the following code: from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy.s...
[ "You need to map a select() with the desired columns. Mapping a join() causes sqlalchemy to turn it into the corresponding select * from <join>: \n(skip this block: this just creates the test fixture)\n>>> from sqlalchemy.orm import mapper, sessionmaker\n>>> from sqlalchemy.sql import join, select\n>>> from sqlal...
[ 2 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0007690107_orm_python_sqlalchemy.txt
Q: Python sys.argv out of range, don't understand why I have a script that I've been using for a some time to easily upload files to my server. It has been working great for a long time, but I can't get it to work on my new desktop computer. The code is simple: import os.path import sys import os from ftplib import F...
Python sys.argv out of range, don't understand why
I have a script that I've been using for a some time to easily upload files to my server. It has been working great for a long time, but I can't get it to work on my new desktop computer. The code is simple: import os.path import sys import os from ftplib import FTP host = "" acc = "" pw = "" filepath = sys.argv[1] i...
[ "Your .py association in the registry is incorrect. It's missing %* at the end.\n", "Try:\n\\python27\\python file_uploader.py backup.sql \n\n" ]
[ 5, 1 ]
[]
[]
[ "command_line", "ftp", "python", "shell" ]
stackoverflow_0007690150_command_line_ftp_python_shell.txt
Q: How do I use BeautifulSoup to strip the tags and just deliver the text back into the soup? I'm trying to replace any <p> tags with just the contents in my soup. This is in the middle of other processing that I'm doing using BeautifulSoup. This is slightly different to a similar question on extracting the text. Ex...
How do I use BeautifulSoup to strip the tags and just deliver the text back into the soup?
I'm trying to replace any <p> tags with just the contents in my soup. This is in the middle of other processing that I'm doing using BeautifulSoup. This is slightly different to a similar question on extracting the text. Example input: ... </p> ... <p>Here is some text</p> ... and some more Desired output: ... ... Her...
[]
[]
[ "I didn't use beautifulSoup, but it should be similar to the built in HTMLParser library. This is a class I built to parse input html and convert the tags to a required different \"markup\". \nclass BaseHTMLProcessor(HTMLParser):\n def reset(self): \n # extend (called by HTMLPars...
[ -1 ]
[ "beautifulsoup", "python" ]
stackoverflow_0007690493_beautifulsoup_python.txt
Q: distutils: how to include test files in source distribution and not in build? I have a simple, pure python project that I want to make available with distutils. I have successfully created compressed tar files for the python modules and some license text files. These are the relevant parts of the setup.py setup ar...
distutils: how to include test files in source distribution and not in build?
I have a simple, pure python project that I want to make available with distutils. I have successfully created compressed tar files for the python modules and some license text files. These are the relevant parts of the setup.py setup argument list: packages=['pkgA', 'pkgA.subpkgA1', 'pkgA.sub...
[ "You don’t have to put anything in data_files. The arguments to distutils.core.setup (py_modules, packages, data_files, etc.) control what will be built and installed; to distribute additional file, use a MANIFEST.in file: http://docs.python.org/dev/distutils/sourcedist#specifying-the-files-to-distribute There yo...
[ 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0006275449_distutils_python.txt
Q: What is the difference between these two configurations to run Django? I have these two configurations. I would like to know what's the difference and which one is better and faster? First configuration: #!/home/user/bin/python import sys, os sys.path.insert(0,"/home/user/projects/") os.environ['DJANGO_SETTINGS_MO...
What is the difference between these two configurations to run Django?
I have these two configurations. I would like to know what's the difference and which one is better and faster? First configuration: #!/home/user/bin/python import sys, os sys.path.insert(0,"/home/user/projects/") os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings' from flup.server.fcgi import WSGIServer ...
[ "Django uses WSGI natively, so running it through FastCGI adds another layer for the HTTP messages to travel through. Having said that, if you have the choice between a quick FastCGI container or a slow WSGI container, you may be better off living with the extra layer.\n" ]
[ 1 ]
[]
[]
[ "apache", "django", "django_wsgi", "fastcgi", "python" ]
stackoverflow_0007690839_apache_django_django_wsgi_fastcgi_python.txt
Q: Finding number of repeats inside a list in a file with Python I need to find the number of times an entry in the list repeats consecutively. For example, consider the following file "hello hello [A B C]" "my world [D C F L]" "tick tock [A L]" In this file, the number of times C repeats is 2 A repeat is not counte...
Finding number of repeats inside a list in a file with Python
I need to find the number of times an entry in the list repeats consecutively. For example, consider the following file "hello hello [A B C]" "my world [D C F L]" "tick tock [A L]" In this file, the number of times C repeats is 2 A repeat is not counted as it is not repeating consecutively. I am not sure of using re a...
[ "the most simple way is to use re to parse the file.\nregular expression that could work : \\[([A-Z]\\s)+[A-Z]\\]\nthen with the list of \"list string\" (aka [\"[A B C]\",\"[ F G R]\"] ) convert it to a list.\nthe format must be like this for \"[A B C]\" \"ABC\", so remove spaces and [] for each one.\nconverted_str...
[ 1, 0, 0 ]
[]
[]
[ "list", "python", "repeat", "string" ]
stackoverflow_0007690184_list_python_repeat_string.txt
Q: "Appending" instead of overriding superclass instance variables Is there a way, in Python, to do something like this? class A(): var = "1, 2, 3" class B(): var = ... ", 4" instance = B() instance.var # = 1, 2, 3, 4 A: The example given in the question uses neither a superclass nor an instance variable....
"Appending" instead of overriding superclass instance variables
Is there a way, in Python, to do something like this? class A(): var = "1, 2, 3" class B(): var = ... ", 4" instance = B() instance.var # = 1, 2, 3, 4
[ "The example given in the question uses neither a superclass nor an instance variable. From the title of the question, presumably you wanted to use both. Here's an example of how it would work:\nclass A(object):\n def __init__(self):\n self.var = \"1,2,3\"\n\nclass B(A):\n def __init__(self):\n super(B,self...
[ 4, 1 ]
[]
[]
[ "python", "subclass" ]
stackoverflow_0007690900_python_subclass.txt
Q: Storing a matlab file using python I have a complex data structure data = {} temp = {} data['bigdata'] = temp; After this I copy 'key' and 'data' values from some other data structure into temp, like this for key in backup.keys(): temp[key] = [] and for key in backup.keys(): for val in backup[key]: ...
Storing a matlab file using python
I have a complex data structure data = {} temp = {} data['bigdata'] = temp; After this I copy 'key' and 'data' values from some other data structure into temp, like this for key in backup.keys(): temp[key] = [] and for key in backup.keys(): for val in backup[key]: temp[key].append(val); After that ...
[ "edit: Answer (and question somewhat) have changed significantly to be more general. It would still be useful it the asker would tell us what kinds of objects the values in backup are.\nThe scipy.io.savemat can apparently take a dictionary of dictionaries of arrays, so this structure\nfrom numpy import array\nimpo...
[ 6 ]
[]
[]
[ "matlab", "python", "scipy" ]
stackoverflow_0007689958_matlab_python_scipy.txt
Q: Celery/Redis some (many) messages getting dropped I'm using Celery (2.2.4) with Redis (v.2.2.2) as my message broker. Any idea what would cause SOME (most) messages to randomly and inconsistently get lost? A: The only reason that seems logical is that you exceed the memory that your redis-instance uses. So some...
Celery/Redis some (many) messages getting dropped
I'm using Celery (2.2.4) with Redis (v.2.2.2) as my message broker. Any idea what would cause SOME (most) messages to randomly and inconsistently get lost?
[ "The only reason that seems logical is that you exceed the memory that your redis-instance uses. So some messages are discarded ( with LRU policy (?) ).\n" ]
[ 0 ]
[]
[]
[ "celery", "django_celery", "python", "redis" ]
stackoverflow_0005225899_celery_django_celery_python_redis.txt
Q: PyQt widgets in multiple files i'd like to learn PyQt by writing a simple game. the first widget would have buttons like "New game", "Quit", etc. i am having trouble understanding how to transition from that menu widget to a new one. for instance, if i were to click New Game, how do i have a new widget appear ...
PyQt widgets in multiple files
i'd like to learn PyQt by writing a simple game. the first widget would have buttons like "New game", "Quit", etc. i am having trouble understanding how to transition from that menu widget to a new one. for instance, if i were to click New Game, how do i have a new widget appear that replaces the old one and asks f...
[ "if you want to switch between forms then you can use QStackedWidget.\nBelow you can find a working sample code:\nimport sys\nfrom functools import partial\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\n\nclass Form1(QWidget):\n showForm2Signal = pyqtSignal()\n\n def __init__(self, parent=None):\n ...
[ 4 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007690677_pyqt_python.txt
Q: Streaming text logfiles into RabbitMQ, then reconstructing at other end? Requirements We have several servers (20-50) - Solaris 10 and Linux (SLES) - running a mix of different applications, each generating a bunch of log events into textfiles. We need to capture these to a separate monitoring box, where we can do...
Streaming text logfiles into RabbitMQ, then reconstructing at other end?
Requirements We have several servers (20-50) - Solaris 10 and Linux (SLES) - running a mix of different applications, each generating a bunch of log events into textfiles. We need to capture these to a separate monitoring box, where we can do analysis/reporting/alerts. Current Approach Currently, we use SSH with a remo...
[ "You seem to be describing centralized syslog with rabbitmq as the transport.\nIf you could live with syslog, take a look at syslog-ng. Otherwise, you might\nsave some time by using parts of logstash ( http://logstash.net/ ).\n", "If it would be possible you can make the Application publish the events Asynchronou...
[ 0, 0, 0 ]
[]
[]
[ "logging", "python", "rabbitmq" ]
stackoverflow_0007600083_logging_python_rabbitmq.txt
Q: Joining multiple iteratorars by a key Given: n iterators, and a function to get a key for an item for each of them Assuming: The iterators provide the items sorted by the key The keys from any iterator are unique I want to iterate through them joined by the keys. Eg, given the following 2 lists: [('a', {type:'x...
Joining multiple iteratorars by a key
Given: n iterators, and a function to get a key for an item for each of them Assuming: The iterators provide the items sorted by the key The keys from any iterator are unique I want to iterate through them joined by the keys. Eg, given the following 2 lists: [('a', {type:'x', mtime:Datetime()}), ('b', {type='y', mti...
[ "The example at the beginning of your question is different than at the end. \nFor the first example, I would do this:\nx = [('a', {}), ('b', {})]\ny = [('b', {}), ('c', {})]\nxd, yd = dict(x), dict(y)\ncombined = []\nfor k in sorted(set(xd.keys()+yd.keys())):\n row = []\n for d in (xd, yd):\n row.app...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007689205_python.txt
Q: execute python script with function from command line, Linux I have my python file called convertImage.py and inside the file I have a script that converts an image to my liking, the entire converting script is set inside a function called convertFile(fileName) Now my problem is I need to execute this python scrip...
execute python script with function from command line, Linux
I have my python file called convertImage.py and inside the file I have a script that converts an image to my liking, the entire converting script is set inside a function called convertFile(fileName) Now my problem is I need to execute this python script from the linux command line while passing the convertFile(fileNa...
[ "This\nif __name__ == \"__main__\":\n command= \" \".join( sys.argv[1:] )\n eval( command )\n\nThis will work. But it's insanely dangerous.\nYou really need to think about what your command-line syntax is. And you need to think about why you're breaking the long-established Linux standards for specifying ar...
[ 24, 6, 2 ]
[]
[]
[ "command_line", "linux", "python", "shell" ]
stackoverflow_0007691599_command_line_linux_python_shell.txt
Q: function definition in eval I try to define a function with a variable name. Names are retrieved from a database. For every name I want to define a button and have separate handling: title=['BNL','CE'] for i in range(0,len(title)): panelvpu.add(Button(title[i])) for i in range(0,len(title)): eval('def onB...
function definition in eval
I try to define a function with a variable name. Names are retrieved from a database. For every name I want to define a button and have separate handling: title=['BNL','CE'] for i in range(0,len(title)): panelvpu.add(Button(title[i])) for i in range(0,len(title)): eval('def onButtonClick'+title[i]+'(self, eve...
[ "There are a number of problems here:\n1) eval is for evaluating an expression, not executing statements.\n2) exec would need the entire function in one exec, not split onto separate lines as you have it.\n3) There are much easier ways to create functions, depending on what you want to have in the body. Tell us ab...
[ 9 ]
[]
[]
[ "eval", "pyjamas", "python" ]
stackoverflow_0007691458_eval_pyjamas_python.txt
Q: ArcGIS Python: Using Calendars in the Graphical Interface Forms I am a GIS Specialist using Python within ArcGIS10. I am creating a script and importing it into the the ArcGIS default graphical interface form. In the default forms, I can set certain parameters made of different data types. One of the parameters I ...
ArcGIS Python: Using Calendars in the Graphical Interface Forms
I am a GIS Specialist using Python within ArcGIS10. I am creating a script and importing it into the the ArcGIS default graphical interface form. In the default forms, I can set certain parameters made of different data types. One of the parameters I would like to set is to have a field where the user opens a calendar ...
[ "If you are running the script in an ArcGIS 10 toolbox, a calendar popup is not possible. Even worse, it does not look like the Date data type provides any validation from the toolbox. This means that you will need to either validate that an actual date has been entered in your code or you can modify the validati...
[ 2 ]
[]
[]
[ "arcgis", "arcpy", "calendar", "forms", "python" ]
stackoverflow_0006795719_arcgis_arcpy_calendar_forms_python.txt
Q: Audio watermarking with Ruby, PHP or Python I'm working on a project where I need to post-process a bunch of audio files in various formats. Firstly, the files need to be converted to .WAV format. Secondly, depending on their length, I need to insert a short audible watermark at certain intervals in each of the ...
Audio watermarking with Ruby, PHP or Python
I'm working on a project where I need to post-process a bunch of audio files in various formats. Firstly, the files need to be converted to .WAV format. Secondly, depending on their length, I need to insert a short audible watermark at certain intervals in each of the new .WAV files. The first part is easy, using th...
[ "This gets complicated. You need to actually mix the audio, which to my knowledge, isn't possible with FFMPEG. The other problem you're going to have is loss of quality if you take an MP3, convert it to WAV so you can work with it, and re-encode it back to MP3.\nI think you can use Sox for this: http://sox.sourc...
[ 1, 1 ]
[]
[]
[ "audio", "php", "python", "ruby", "watermark" ]
stackoverflow_0007689668_audio_php_python_ruby_watermark.txt