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: Can't import scriptext module in PyS60 2.0 on N95 When I try and import scriptext on PyS60 version 2.0 on my N95 phone, I get an import error saying that there is no module named scriptext. How can I work out what the problem is? A: From: http://pys60.garage.maemo.org/doc/s60/scriptext.html Note: The service is...
Can't import scriptext module in PyS60 2.0 on N95
When I try and import scriptext on PyS60 version 2.0 on my N95 phone, I get an import error saying that there is no module named scriptext. How can I work out what the problem is?
[ "From:\nhttp://pys60.garage.maemo.org/doc/s60/scriptext.html\n\nNote: The service is available from\n 'S60 third edition FP2 and later'.\n\nN95 is a 3rd edition FP1 device.\nYou can adapt your app at runtime according to the availability of this module by putting the import in a try..except block:\ntry:\n impor...
[ 1 ]
[]
[]
[ "importerror", "module", "n95", "pys60", "python" ]
stackoverflow_0003092707_importerror_module_n95_pys60_python.txt
Q: Sort list of names in Python, ignoring numbers? ['7', 'Google', '100T', 'Chrome', '10', 'Python'] I'd like the result to be all numbers at the end and the rest sorted. The numbers need not be sorted. Chrome Google Python 100T 7 10 It's slightly more complicated though, because I sort a dictionary by value. def s...
Sort list of names in Python, ignoring numbers?
['7', 'Google', '100T', 'Chrome', '10', 'Python'] I'd like the result to be all numbers at the end and the rest sorted. The numbers need not be sorted. Chrome Google Python 100T 7 10 It's slightly more complicated though, because I sort a dictionary by value. def sortname(k): return get[k]['NAME'] sortedbyname = sort...
[ "I've been struggling to get a dictionary version working, so here's the array version for you to extrapolate from:\ndef sortkey(x):\n try:\n return (1, int(x))\n except:\n return (0, x)\n\nsorted(get, key=sortkey)\n\nThe basic principle is to create a tuple who's first element has the effect of...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0004058455_dictionary_list_python_sorting.txt
Q: how to make a chat room on google app engine , has some demo ? and example? has any app engine already do this ? thanks A: Partychat an example of an XMPP-based chatroom running on App Engine. And it's open-source. A: AppEngine only supports HTTP and limits the response time (which makes Comet a no-go). The o...
how to make a chat room on google app engine , has some demo ? and example?
has any app engine already do this ? thanks
[ "Partychat an example of an XMPP-based chatroom running on App Engine. And it's open-source.\n", "AppEngine only supports HTTP and limits the response time (which makes Comet a no-go).\nThe only (supported) way is XMPP, but it only supports BOSH protocol, which does not facilitate push from server to clients.\nI...
[ 3, 1 ]
[]
[]
[ "chatroom", "google_app_engine", "javascript", "python" ]
stackoverflow_0004057942_chatroom_google_app_engine_javascript_python.txt
Q: Using colons in ConfigParser Python According to the documentation: The configuration file consists of sections, led by a [section] header and followed by name: value entries, with continuations in the style of RFC 822 (see section 3.1.1, “LONG HEADER FIELDS”); name=value is also accepted. Python Docs...
Using colons in ConfigParser Python
According to the documentation: The configuration file consists of sections, led by a [section] header and followed by name: value entries, with continuations in the style of RFC 822 (see section 3.1.1, “LONG HEADER FIELDS”); name=value is also accepted. Python Docs However, writing a config file always u...
[ "If you look at the code defining the RawConfigParser.write method inside ConfigParser.py you'll see that the equal signs are hard-coded. So to change the behavior you could subclass the ConfigParser you wish to use:\nimport ConfigParser\nclass MyConfigParser(ConfigParser.ConfigParser):\n def write(self, fp):\n ...
[ 7 ]
[]
[]
[ "configuration", "file", "python" ]
stackoverflow_0004058400_configuration_file_python.txt
Q: opening a parent folder and highlighting particular child in default file browser using python I am using following code to open a folder in default file browser. if os.name == 'mac': subprocess.call(('open', folderPath)) elif os.name == 'nt': subprocess.call(('start', folderPath)) elif os.name == 'posix': s...
opening a parent folder and highlighting particular child in default file browser using python
I am using following code to open a folder in default file browser. if os.name == 'mac': subprocess.call(('open', folderPath)) elif os.name == 'nt': subprocess.call(('start', folderPath)) elif os.name == 'posix': subprocess.call(('xdg-open', folderPath)) Now the problem is I want to highlight the child folder/fi...
[ "xdg-open doesn't support this, so it has to be done on a per-app basis. After poking around the Nautilus code, I don't think it has this feature either. So, yeah, you're pretty much out of luck.\nFor Windows Explorer, you can use\nsubprocess.call((\"explorer\", \"/select,\", file_path))\n\n" ]
[ 2 ]
[]
[]
[ "directory", "nautilus", "python" ]
stackoverflow_0004030044_directory_nautilus_python.txt
Q: SQL Query that relies on COUNT from another table? - SQLAlchemy I need a query that can return the records from table A that have greater than COUNT records in table B. The query needs to be able to go in line with other filters that might be applied on table A. Example case study: I have a person and appointments...
SQL Query that relies on COUNT from another table? - SQLAlchemy
I need a query that can return the records from table A that have greater than COUNT records in table B. The query needs to be able to go in line with other filters that might be applied on table A. Example case study: I have a person and appointments table. I am looking for all people who have been in for 5 or more ap...
[ "Use a subquery:\nSELECT * from person\nWHERE PersonID IN \n (SELECT PersonId FROM appointments\n GROUP BY PersonId\n HAVING COUNT(*) >= 5)\nAND dob > 25\n\n", "SELECT Person.PersonID, Person.Name\nFROM Person INNER JOIN Appointment\nON Person.PersonID = Appointment.PersonID\nGROUP BY Person.PersonID, Person...
[ 1, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0004057223_python_sql_sqlalchemy.txt
Q: In Django's template engine, how do I display a datetime object in a meaningful way? {{ p.date }} is displayed as: Date: 2010-10-29 21:56:39.226000 How do I make changes to how that's displayed? A: Using date filter, for eg : {{ study.created_date|date:"d/m/Y"}} A: With the date filter.
In Django's template engine, how do I display a datetime object in a meaningful way?
{{ p.date }} is displayed as: Date: 2010-10-29 21:56:39.226000 How do I make changes to how that's displayed?
[ "Using date filter, for eg : {{ study.created_date|date:\"d/m/Y\"}}\n", "With the date filter.\n" ]
[ 5, 1 ]
[]
[]
[ "datetime", "django", "python", "templates" ]
stackoverflow_0004056220_datetime_django_python_templates.txt
Q: best way for a c# developer to break into Tkinter? I'm a full time c# developer, but I want to get more into Python. At the same time, I have a friend who will learn it with me, he however has no programming knowledge. I was thinking about starting with some visual programming. I.E: having buttons, labels and tex...
best way for a c# developer to break into Tkinter?
I'm a full time c# developer, but I want to get more into Python. At the same time, I have a friend who will learn it with me, he however has no programming knowledge. I was thinking about starting with some visual programming. I.E: having buttons, labels and text boxes on a form. Does some kind of IDE exist which al...
[ "\nDoes some kind of IDE exist which allows you to very quickly build a Tkinter app in Python, and compile run it for Windows?\n\nThere's nothing similar to VisualStudio for building tkinter interfaces, although some visual designers do exist take a look at this question.\nKeep in mind that a lot of professional py...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004058443_python_tkinter.txt
Q: Delayed loading of modules in python I'm writing a python applet for data acquisition from scientific instruments and I'm trying to figure out the best way to manage my device "drivers". Each driver is represented by a separate python module in the package that is my program. They each implement some standard inte...
Delayed loading of modules in python
I'm writing a python applet for data acquisition from scientific instruments and I'm trying to figure out the best way to manage my device "drivers". Each driver is represented by a separate python module in the package that is my program. They each implement some standard interface, but mostly it's a gigantic list of ...
[ "There is pkgutil which has iter_modules. (Note: The Python 2 documentation doesn't mention that function, but it works just fine for me on Python 2.6.)\nYou can also do it manually using __file__, os.path and os.listdir.\n", "If the location of the driver packages is known, then you could use the absolute path t...
[ 3, 3, 0 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0004058115_module_package_python.txt
Q: Split list of names into alphabetic dictionary, in Python List. ['Chrome', 'Chromium', 'Google', 'Python'] Result. {'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']} I can make it work like this. alphabet = dict() for name in ['Chrome', 'Chromium', 'Google', 'Python']: character = name[:1].upper()...
Split list of names into alphabetic dictionary, in Python
List. ['Chrome', 'Chromium', 'Google', 'Python'] Result. {'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']} I can make it work like this. alphabet = dict() for name in ['Chrome', 'Chromium', 'Google', 'Python']: character = name[:1].upper() if not character in alphabet: alphabet[character] = list...
[ "Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.\nimport collections\n\nalphabet = collections.defaultdict(list)\nfor word in words:\n alphabet[word[0].upper()].append(word)\n\n", "I don't know if it's Pythonic, but it's more succinct:\nimport itertools\ndef keyfunc(x):...
[ 10, 5 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0004058967_dictionary_list_python.txt
Q: Menubuttons located in the middle of menubar how do I put my menu bar buttons on menu bar's left ? Right now I pack() them with side=LEFT but still they're in the middle. Here's the code for my menu bar: http://pastebin.com/bgncELcb A: What does menubar.pack(side=LEFT) give you? Can you also try with menubar.pac...
Menubuttons located in the middle of menubar
how do I put my menu bar buttons on menu bar's left ? Right now I pack() them with side=LEFT but still they're in the middle. Here's the code for my menu bar: http://pastebin.com/bgncELcb
[ "What does menubar.pack(side=LEFT) give you?\nCan you also try with menubar.pack()?\n", "I recommend against creating menubars a) with frames and menubuttons, and b) with menus in non-standard places. You should use the menu option of your toplevel window if you're at all interested in usability. However, since y...
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0004058272_python_tkinter_user_interface.txt
Q: Column filtering on trace file I am doing visualization analysis on a trace file I generate from ns-2 that traces out the packets sent/received/dropped at various times of the simulation here is a sample trace output - http://pastebin.com/aPm3EFax I want to filter out the column1 after grouping it into S/D/R separ...
Column filtering on trace file
I am doing visualization analysis on a trace file I generate from ns-2 that traces out the packets sent/received/dropped at various times of the simulation here is a sample trace output - http://pastebin.com/aPm3EFax I want to filter out the column1 after grouping it into S/D/R separately, so that I can sum it over to ...
[ "Give this a try:\nawk '{data[$1]+=$2} END{for (d in data) print d,data[d]}' inputfile\n\nOutput:\nD 80.1951\nr 80.059\ns 160.158\n\n", "import collections\nresult=collections.defaultdict(list)\nwith open('data','r') as f:\n for line in f:\n line=line.split()\n key=line[0]\n value=float(li...
[ 1, 0, 0 ]
[]
[]
[ "awk", "python" ]
stackoverflow_0004058588_awk_python.txt
Q: how to change data Automatically not using open the webpage for Per hour i seem like this : class myData(db.Model): today= db.DateTimeProperty() how to set 'today' to now time for Per hour ,not using open the webpage ? thanks A: You need to use a Task Queue.
how to change data Automatically not using open the webpage for Per hour
i seem like this : class myData(db.Model): today= db.DateTimeProperty() how to set 'today' to now time for Per hour ,not using open the webpage ? thanks
[ "You need to use a Task Queue.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0004058087_google_app_engine_javascript_python.txt
Q: Full internal resize of control in wx.Panel Hi at all friends :) I have a problem with a control inside a wx.Panel. With my code the wx.GenericDirCtrl inside a wx.Panel don't fit in all directions in the Panel (or fit only in a direction if I use wx.BoxSizer). I use an istance of MyPanel in a wx.Frame. How I can ...
Full internal resize of control in wx.Panel
Hi at all friends :) I have a problem with a control inside a wx.Panel. With my code the wx.GenericDirCtrl inside a wx.Panel don't fit in all directions in the Panel (or fit only in a direction if I use wx.BoxSizer). I use an istance of MyPanel in a wx.Frame. How I can solve it? Thanks The code is: class MyPanel(wx.Pa...
[ "You're using the Add method wrong. Its signature is \nAdd(self, item, proportion=0, flag=0, border=0, userData=None)\n\nYou've passed the \"flag\" parameter as the proportion parameter.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004058263_python_wxpython.txt
Q: Twisted and connection to SQL Server I have a Twisted application that runs in an x86 64bit machine with Win 2008 server. It needs to be connected to a SQL Server database that runs in another machine (in a cloud actually but I have IP, port, db name, credentials). Do I need to install anything more that Twisted ...
Twisted and connection to SQL Server
I have a Twisted application that runs in an x86 64bit machine with Win 2008 server. It needs to be connected to a SQL Server database that runs in another machine (in a cloud actually but I have IP, port, db name, credentials). Do I need to install anything more that Twisted to my machine? And which API should be use...
[ "twisted.enterprise.adbapi will help you use any DB-API 2.0 module without blocking. It gives you a non-blocking, Deferred-based API by running database operations in a thread pool. python-mssql appears to be a DB-API 2.0 compliant module for MSSQL (I've never used it myself though).\n", "If you want to have po...
[ 2, 1 ]
[]
[]
[ "python", "sql_server", "twisted" ]
stackoverflow_0003657271_python_sql_server_twisted.txt
Q: Is IronPython a 100% pure Python variant? I just downloaded the original Python interpreter from Python's site. I just want to learn this language but to start with, I want to write Windows-based standalone applications that are powered by any RDBMS. I want to bundle it like any typical Windows setup. I searched o...
Is IronPython a 100% pure Python variant?
I just downloaded the original Python interpreter from Python's site. I just want to learn this language but to start with, I want to write Windows-based standalone applications that are powered by any RDBMS. I want to bundle it like any typical Windows setup. I searched old posts on SO and found guys suggesting wxPyth...
[ "IronPython isn't a variant of Python, it is Python. It's an implementation of the Python language based on the .NET framework. So, yes, it is pure Python.\nIronPython is caught up to CPython (the implementation you're probably used to) 2.6, so some of the features/changes seen in Python 2.7 or 3.x will not be pres...
[ 6, 1, 1, 1 ]
[]
[]
[ "ironpython", "python", "wxpython" ]
stackoverflow_0004059201_ironpython_python_wxpython.txt
Q: Any recommendations to improve this function? I am very new to working with SQL queries. Any suggestions to improve this bit of code: (by the way, I really don't care about sql security here; this is a bit of code that will be in a pyexe file connecting to a local sqlite file - so it doesnt make sense to worry abo...
Any recommendations to improve this function?
I am very new to working with SQL queries. Any suggestions to improve this bit of code: (by the way, I really don't care about sql security here; this is a bit of code that will be in a pyexe file connecting to a local sqlite file - so it doesnt make sense to worry about security of the query here). def InitBars(QA = "...
[ "If this is a one-off script where you totally trust all of the input data and you just need to get a job done, then fine.\nIf this is part of a system, and this is indicative of the kind of code in it, there are several problems:\n\nDon't construct SQL queries by appending strings. You said that you don't care ab...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004059499_python.txt
Q: Doing something with each line that belongs to a process's output When using the subprocess module, how can I do something with each line of a process's output? I don't want to wait for all the output, like when using communicate, but rather do something with it as soon as it's produced. Can this be done? A: Unf...
Doing something with each line that belongs to a process's output
When using the subprocess module, how can I do something with each line of a process's output? I don't want to wait for all the output, like when using communicate, but rather do something with it as soon as it's produced. Can this be done?
[ "Unfortunately the proposal to add this to subprocess is not yet accepted: http://www.python.org/dev/peps/pep-3145/\nHere is a recipe for doing it with the existing subprocess: http://code.activestate.com/recipes/440554/\nA commenter also notes this simple solution (with some downsides):\nflags = fcntl.fcntl(subpro...
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0004059684_python_subprocess.txt
Q: How to insert a large number of list entries into sqlite statements Ok, I am using apsw with sqlite, and have a large list of entries.Each entry contains a new row to be inserted. The number of entries is sometimes 20, sometimes 21. Since apsw supports multiple sql statements in curser.execute(), I was wondering i...
How to insert a large number of list entries into sqlite statements
Ok, I am using apsw with sqlite, and have a large list of entries.Each entry contains a new row to be inserted. The number of entries is sometimes 20, sometimes 21. Since apsw supports multiple sql statements in curser.execute(), I was wondering if there would be a less confusing way of inserting all my list entries in...
[ "apsw cursors have an executemany method:\ncursor.executemany('INSERT OR UPDATE INTO database.main values (?)',foo)\n\n" ]
[ 1 ]
[]
[]
[ "list", "python", "sqlite" ]
stackoverflow_0004059776_list_python_sqlite.txt
Q: CherryPy Logging: How do I configure and use the global and application level loggers? I'm having trouble with logging. I'm running CherryPy 3.2 and I've been reading through the docs here, but haven't found any examples of how to configure a local log file for output and how to write to it. Raspberry.py: impor...
CherryPy Logging: How do I configure and use the global and application level loggers?
I'm having trouble with logging. I'm running CherryPy 3.2 and I've been reading through the docs here, but haven't found any examples of how to configure a local log file for output and how to write to it. Raspberry.py: import socket import sys import cherrypy app_roots = { # Sean's laptop dev envir...
[ "Simplifying a bit:\nimport os\nimport socket\nimport sys\n\nimport cherrypy\n\napp_roots = {\n # Sean's laptop dev environment.\n \"mylaptop\": \"/home/src/local-mydomain.com/py\",\n\n # Hosted dev environment. \n \"mydomain.com\" : \"/home/dev/src/py\"\...
[ 10 ]
[]
[]
[ "cherrypy", "logging", "python" ]
stackoverflow_0004056958_cherrypy_logging_python.txt
Q: Generate all possible strings from a list of token I have a list of tokens, like: hel lo bye and i want to generate all the possible combinations of such strings, like: hello lohel helbye byehel lobye byelo Language is not important, any advice? I found Generating permutations using bash, but this makes permutat...
Generate all possible strings from a list of token
I have a list of tokens, like: hel lo bye and i want to generate all the possible combinations of such strings, like: hello lohel helbye byehel lobye byelo Language is not important, any advice? I found Generating permutations using bash, but this makes permutation on a single line.
[ "Your example can be written in Python as\nfrom itertools import combinations\nprint list(combinations([\"hel\", \"lo\", \"bye\"], 2))\n\nTo combine the output to strings again:\nprint [\"\".join(a) for a in combinations([\"hel\", \"lo\", \"bye\"], 2)]\n\nIf you interested in the actual implementation of this funct...
[ 24, 8, 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "bash", "language_agnostic", "python" ]
stackoverflow_0004059550_bash_language_agnostic_python.txt
Q: Strange python's comparison behaviour I have a sample code looking like this, values (position = 2, object.position = 3) : new_position = position old_position = object.position logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position)) if old_position != new_positi...
Strange python's comparison behaviour
I have a sample code looking like this, values (position = 2, object.position = 3) : new_position = position old_position = object.position logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position)) if old_position != new_position: logging.debug("old position oth...
[ "It's probably because you are comparing different incompatible types (e.g. strings and integers). If so, then the order depends on the alphabetical order of the type names.\n>>> '2' > 3\nTrue\n\nThis applies to Python 2.x. In Python 3.x this will raise a TypeError instead.\n", "Are you sure old_position and new_...
[ 4, 2 ]
[ "assuming a sane comparison operator, old_position != new_position is equivalent to old_position < new_position or old_position > new_position\n" ]
[ -2 ]
[ "compare", "python" ]
stackoverflow_0004060066_compare_python.txt
Q: I need to return a link generated after the completion of ModelForm part of forms.py class FormPublicar(forms.ModelForm): class Meta: model = Publicacao exclude = ('usuario', 'aprovado', 'cadastrado_em', 'slug') def enviar(self): titulo = 'mensagem enviada pelo site' destino = self.cleaned_data['e...
I need to return a link generated after the completion of ModelForm
part of forms.py class FormPublicar(forms.ModelForm): class Meta: model = Publicacao exclude = ('usuario', 'aprovado', 'cadastrado_em', 'slug') def enviar(self): titulo = 'mensagem enviada pelo site' destino = self.cleaned_data['emailp'] mensagem = u""" Message that will be sent after completin...
[ "Using reverse() is normally the proper way to generate the portion of the URL without the domain. For example, if your URL config contains something like the following:\n(r'^item/(?P<item>[-%\\w]+)/view/(?P<slug>[-\\w]+)$', 'my_view_function')\n\nThen the following call\nreverse('my_view_function', kwargs={'item':...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004052599_django_python.txt
Q: Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'? I have a DB "TimeZoneField" type for users, how do I use that with the "datetime.datetime()" object to get a strftime() string like '%Y-%m-%dT%H:%M:%S.000Z'? A: This was for Go...
Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'?
I have a DB "TimeZoneField" type for users, how do I use that with the "datetime.datetime()" object to get a strftime() string like '%Y-%m-%dT%H:%M:%S.000Z'?
[ "This was for Google Calendar's Python data API feed and it was a lot of work because Python's datetime library doesn't support ISO 8601:\nhttp://wiki.python.org/moin/WorkingWithTime\nIn addition if you transmit dates with .000Z timezone to Google calendar it will ignore DST (Daylight Savings Time) for events that ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004060354_django_python.txt
Q: any way to invoke fragment identifiers '#' in python Is there any way to invoke fragment identifiers from python? I'm currently using python mechanize. A: I think this earlier question holds your answer: In the HTTP protocol, the fragment (from # onwards) is not sent to the server across the network: it's ...
any way to invoke fragment identifiers '#' in python
Is there any way to invoke fragment identifiers from python? I'm currently using python mechanize.
[ "I think this earlier question holds your answer:\n\nIn the HTTP protocol, the fragment\n (from # onwards) is not sent to the\n server across the network: it's\n locally retained by the browser and\n used, once the server's response is\n fully received, to somehow \"visually\n locate\" the exact spot in the p...
[ 4 ]
[]
[]
[ "fragment_identifier", "mechanize", "python", "url" ]
stackoverflow_0004060110_fragment_identifier_mechanize_python_url.txt
Q: Pygtk: Name is not defined I'm trying out a few pygtk tutorials and have run across a seemingly obvious newbie mistake, but for the life of me can't figure out what's going on here. The error: Traceback (most recent call last): File "main.py", line 8, in class Base: File "main.py", line 61, in Base ...
Pygtk: Name is not defined
I'm trying out a few pygtk tutorials and have run across a seemingly obvious newbie mistake, but for the life of me can't figure out what's going on here. The error: Traceback (most recent call last): File "main.py", line 8, in class Base: File "main.py", line 61, in Base cv.set_line_width(9) NameError: ...
[ "Your code in github reads:\ndef expose(self, widget, data=None): \n selcv = widget.window.cairo_create()\n\n cv.set_line_width(9)\n cv.set_source_rgb(0.7, 0.2, 0.0)\n\n...which would surely explain why cv is not defined when you try to access it.\n", "This was solved by switching to 4-space inden...
[ 1, 0, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004060681_pygtk_python.txt
Q: python/cgi - serves distorted images I have been struggling for a couple hours now with serving jpg's with a python cgi site. For some reason the images always come out distorted. Here is my code: print('Content-type: image/jpg\n') path = 'C:\\Users\\Admin\\Documents\\image.jpg' print file(path, 'rb').read() This...
python/cgi - serves distorted images
I have been struggling for a couple hours now with serving jpg's with a python cgi site. For some reason the images always come out distorted. Here is my code: print('Content-type: image/jpg\n') path = 'C:\\Users\\Admin\\Documents\\image.jpg' print file(path, 'rb').read() This post describes a nearly identical problem...
[ "This article shows sending a file to CGI using C++. The program takes some care to convert stdout to binary:\nint main()\n{\n#if _WIN32\n // Standard I/O is in text mode by default; since we intend\n // to send binary image data to standard output, we have to\n // set it to binary mode.\n // Error hand...
[ 2 ]
[]
[]
[ "apache", "header", "http", "python" ]
stackoverflow_0004060339_apache_header_http_python.txt
Q: is it possible to read the text written in a sticky note using a script in linux? I am using sticky notes in ubuntu . And was wondering if it would be possible to read the text written in sticky notes using any scripting language . A: If you meant the "Sticky Notes" applet you can add to your panel then yes you...
is it possible to read the text written in a sticky note using a script in linux?
I am using sticky notes in ubuntu . And was wondering if it would be possible to read the text written in sticky notes using any scripting language .
[ "If you meant the \"Sticky Notes\" applet you can add to your panel then yes you can read that notes too.\nThe XML file containing all notes typically is located at ~/.gnome2/stickynotes_applet.\nYou just have to parse the information you need out of it. The structure should look like this.\n<?xml version=\"1.0\"?>...
[ 2, 0, 0 ]
[]
[]
[ "perl", "python", "ruby" ]
stackoverflow_0004059851_perl_python_ruby.txt
Q: Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies? I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the p...
Are there any other good alternatives to zc.buildout and/or virtualenv for installing non-python dependencies?
I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to ...
[ "Setuptools may be capable of more of what you're looking for than you realize -- if you need a custom version of lxml to work correctly on MacOS X, for instance, you can put a URL to an appropriate egg inside your setup.py and have setuptools download and install that inside your developers' environments as necess...
[ 4, 3, 0, 0, 0, 0 ]
[]
[]
[ "build_process", "deployment", "python" ]
stackoverflow_0000160834_build_process_deployment_python.txt
Q: How do I use simplejson to decode JSON responses to python objects? JSON serialization Python using simpleJSON How do I create an object so that we can optimize the serialization of the object I'm using simpleJSON 1,2 are fixed variables 3 is a fixed dict of category and score 4 is an array of dicts that are fix...
How do I use simplejson to decode JSON responses to python objects?
JSON serialization Python using simpleJSON How do I create an object so that we can optimize the serialization of the object I'm using simpleJSON 1,2 are fixed variables 3 is a fixed dict of category and score 4 is an array of dicts that are fixed in length (4), the array is a length specificed at run-time. The proc...
[ "Um...\nimport simplejson as json\nresult_object = json.loads(input_json_string)\n\n?\n" ]
[ 5 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0004060959_python_simplejson.txt
Q: Google App Engine: Get entity key to use in a template Assuming I have the following: class Person(db.Model): name = db.StringProperty() I would like to print all the names in an html file using a template. template_values = {'list': Person.all()} And the template will look like this: {% for person in list %} ...
Google App Engine: Get entity key to use in a template
Assuming I have the following: class Person(db.Model): name = db.StringProperty() I would like to print all the names in an html file using a template. template_values = {'list': Person.all()} And the template will look like this: {% for person in list %} <form> <p>{{ person.name}} </p> <button type="button" na...
[ "Use {{person.key.id}}, not just {{id}}. This will call each object's .key().id() method(s).\nHowever, you should also be aware that passing Person.all() as a template value isn't necessarily a great idea; .all() returns a db.Query object, which can be treated as an iterable like you're doing but which will do mul...
[ 6, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004059965_google_app_engine_python.txt
Q: Durand-kerner implementation doesn't work What's wrong with this implementation of the Durand-Kerner algorithm (here) ? def durand_kerner(poly, start=complex(.4, .9), epsilon=10**-16):#float('-inf')): roots = [] for e in xrange(poly.degree): roots.append(start ** e) while True: new = []...
Durand-kerner implementation doesn't work
What's wrong with this implementation of the Durand-Kerner algorithm (here) ? def durand_kerner(poly, start=complex(.4, .9), epsilon=10**-16):#float('-inf')): roots = [] for e in xrange(poly.degree): roots.append(start ** e) while True: new = [] for i, r in enumerate(roots): ...
[ "Your algorithm looks fine, and it works for me for the example in the wikipedia\nimport operator\nclass Poly:\n def __init__(self, *koeff):\n self.koeff = koeff\n self.degree = len(koeff)-1\n\n def __call__(self, val):\n res = 0\n x = 1\n for k in self.koeff:\n r...
[ 1, 1 ]
[]
[]
[ "algorithm", "infinite_loop", "polynomial_math", "python" ]
stackoverflow_0004057684_algorithm_infinite_loop_polynomial_math_python.txt
Q: python: how to validate userdefined condition? what I am struggling with is testing predefined conditions which takes user provided parameters like in example below: cond = "if ( 1 is yes and 2 is no ) or ( 1 is yes and 2 is no )" cond2 = "if (3 is no or 1 is no )" vars = [] lst = cond.split() lst += co...
python: how to validate userdefined condition?
what I am struggling with is testing predefined conditions which takes user provided parameters like in example below: cond = "if ( 1 is yes and 2 is no ) or ( 1 is yes and 2 is no )" cond2 = "if (3 is no or 1 is no )" vars = [] lst = cond.split() lst += cond2.split() for l in lst: if l.isdigit(): ...
[ "Use Python's language services to parse and compile the string, then execute the resulting AST.\n", "so, after some reading based on Ignacio's tip, I think I have it after some string modifications. However, still not quite sure if this is the right approach.\nSo, my condition variable is defined as below \n\n...
[ 1, 0, 0 ]
[]
[]
[ "conditional_statements", "python", "validation" ]
stackoverflow_0004059691_conditional_statements_python_validation.txt
Q: How can I build a regular expression to match a single word? Say I had the following strings: Dublin, Ireland. DublinIreland Ireland, Dublin What regular Expression could I use to find the word Dublin in the above strings, but, it cannot count DublinIreland. As in, DublinIreland doesn't say Dublin, it is a whole...
How can I build a regular expression to match a single word?
Say I had the following strings: Dublin, Ireland. DublinIreland Ireland, Dublin What regular Expression could I use to find the word Dublin in the above strings, but, it cannot count DublinIreland. As in, DublinIreland doesn't say Dublin, it is a whole word that says DublinIreland.
[ "Edit : this answer referred to OP's first question, and it actually still answers is second :-p\nUse boundaries, such as \\b. \\bwent\\b would match went.\n", "This would match all capitalised words:\n/\\b([A-Z][a-z]+)\\b/\n\nOr just the word 'Dublin':\n/\\bDublin\\b/\n\n", "In some languages you can use () to...
[ 7, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004061083_python_regex.txt
Q: Does linux disk buffer cache make python cPickle more efficient than shelve? Is IO more efficient, due to the linux disk buffer cache, when storing frequently accessed python objects as separate cPickle files instead of storing all objects in one large shelf? Does the disk buffer cache operate differently in thes...
Does linux disk buffer cache make python cPickle more efficient than shelve?
Is IO more efficient, due to the linux disk buffer cache, when storing frequently accessed python objects as separate cPickle files instead of storing all objects in one large shelf? Does the disk buffer cache operate differently in these two scenarios with respect to efficiency? There may be thousands of large files ...
[ "I don't know of any theoretical way to decide which method is faster, and even if I did, I'm not sure I would trust it. So let's write some code and test it.\nIf we package our pickle/shelve managers in classes with a common interface, then it will be easy to swap them in and out of your code. So if at some future...
[ 3 ]
[]
[]
[ "caching", "linux", "pickle", "python", "shelve" ]
stackoverflow_0004060937_caching_linux_pickle_python_shelve.txt
Q: Getting started with json I have never worked with json before. I am trying: http://api.worldbank.org//topics?format=JSON and make things with it, but I don't even know how to get started. Following some manuals, I did this: import urllib import urllib2 import simplejson urlb = 'http://api.worldbank.org/topics' da...
Getting started with json
I have never worked with json before. I am trying: http://api.worldbank.org//topics?format=JSON and make things with it, but I don't even know how to get started. Following some manuals, I did this: import urllib import urllib2 import simplejson urlb = 'http://api.worldbank.org/topics' datab = urllib2.urlopen(urlb+'?'+...
[ "Trying printing resultb. Its just a python list with dictionaries inside it. Treat it like you would any list.\n" ]
[ 4 ]
[]
[]
[ "json", "python" ]
stackoverflow_0004061274_json_python.txt
Q: Using Python lxml.html how can I find images within link tags? I am using lxml.html to parse some hmtl to get links, however when it hits a link which contains an image it just returns blank, what it'd really like is to be able to detect if it's an image, and then try and return the image alt text. So it looks lik...
Using Python lxml.html how can I find images within link tags?
I am using lxml.html to parse some hmtl to get links, however when it hits a link which contains an image it just returns blank, what it'd really like is to be able to detect if it's an image, and then try and return the image alt text. So it looks like this... from lxml.html import parse, fromstring doc = fromstring(...
[ "Just modify your css selector:\nfor img in doc.cssselect('a img'):\n\nYou can also use an XPATH expression:\nfor img in doc.xpath('a//img'):\n\n", "for link in doc.xpath('a'):\n img = link.find('img')\n if img is not None:\n print '%s: %s' % (img.get('alt'), link.get('href'))\n else:\n pri...
[ 3, 2 ]
[]
[]
[ "html_parsing", "lxml", "python" ]
stackoverflow_0004061354_html_parsing_lxml_python.txt
Q: multiple return statements in python "def" causes syntax error I'm trying to test my function "def" in a python shell, but when i paste it in there are errors. It seems not to like it when i have multiple return statements inside one "def". For example: def foo(): valid = True if valid: return True return Fal...
multiple return statements in python "def" causes syntax error
I'm trying to test my function "def" in a python shell, but when i paste it in there are errors. It seems not to like it when i have multiple return statements inside one "def". For example: def foo(): valid = True if valid: return True return False Does anyone know why? thanks!
[ "Your indentation is wrong. Should be this:\ndef foo():\n valid = True\n if valid:\n return True\n return False\n\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0004061475_python.txt
Q: Tail Call Optimization in Mono/Ironpython given that CLR supports tail call optimization I was wondering if Mono, and consequently Ironpython running on Mono has support for TCO ? A: I can't give a definitive answer, but there is ample evidence in forums (e.g., here) that because Mono doesn't use a callee-pops-a...
Tail Call Optimization in Mono/Ironpython
given that CLR supports tail call optimization I was wondering if Mono, and consequently Ironpython running on Mono has support for TCO ?
[ "I can't give a definitive answer, but there is ample evidence in forums (e.g., here) that because Mono doesn't use a callee-pops-arguments calling convention, it can't (easily) support tail calls. There is a couple of unresolved bugs, here and here, indicating that F# is still waiting for this.\n" ]
[ 4 ]
[]
[]
[ ".net", "ironpython", "mono", "python" ]
stackoverflow_0004061671_.net_ironpython_mono_python.txt
Q: fit mysql db in memory I am using Redis database where we store the navigational information. These data must be persistent and should be fetched faster. I don't have more than 200 MB data in this data set. I face problem when writing admin modules for redis db and I really missing the sql schema and power of djan...
fit mysql db in memory
I am using Redis database where we store the navigational information. These data must be persistent and should be fetched faster. I don't have more than 200 MB data in this data set. I face problem when writing admin modules for redis db and I really missing the sql schema and power of django style admin modules. Now ...
[ "I would create a read only slave to your mysql database and force its database engines to memory. You'd have to handle failures by re-initializing the read only database, but that can be scripted rather easily.\nThis way you still have your persistence in the regular mysql database and your read speed in the read...
[ 1, 0, 0 ]
[]
[]
[ "mysql", "performance", "python", "sqlalchemy" ]
stackoverflow_0004061828_mysql_performance_python_sqlalchemy.txt
Q: Saving map data in a 2d ORPG I'm trying to figure out how I can best save the map data for a 2d ORPG engine I am developing, the file would contain tile data (Is it blocked, what actual graphics would it use, and various other properties). I am currently using a binary format but I think this might be a bit too li...
Saving map data in a 2d ORPG
I'm trying to figure out how I can best save the map data for a 2d ORPG engine I am developing, the file would contain tile data (Is it blocked, what actual graphics would it use, and various other properties). I am currently using a binary format but I think this might be a bit too limited and hard to debug, what alte...
[ "XML is well supported across basically every language. It may become verbose for large maps, however, depending on how you encode the map data in XML.\nJSON might not be a good choice, simply because I don't think it supports multiline strings, which would be helpful (although not really necessary)\nYAML is anoth...
[ 1, 1, 0 ]
[]
[]
[ "c#", "c++", "python" ]
stackoverflow_0004052990_c#_c++_python.txt
Q: How to access a MS SQL Server using Python 3? I'm using a linux machine to make a little python program that needs to input its result in a SQL Server 2000 DB. I'm new to python so I'm struggling quite a bit to find what's the best solution to connect to the DB using python 3, since most of the libs I looked only ...
How to access a MS SQL Server using Python 3?
I'm using a linux machine to make a little python program that needs to input its result in a SQL Server 2000 DB. I'm new to python so I'm struggling quite a bit to find what's the best solution to connect to the DB using python 3, since most of the libs I looked only work in python 2. As an added bonus question, the f...
[ "One option would be trying the pyodbc branch for python 3 support. I think some people have reported success, but you might want to inquire at the pyodbc discussion group.\nIf you stick to platform independent parts of the python library (most of it), you shouldn't have any issues on windows with py2exe.\n", "I...
[ 1, 0, 0 ]
[]
[]
[ "py2exe", "python", "python_3.x", "sql_server" ]
stackoverflow_0003571819_py2exe_python_python_3.x_sql_server.txt
Q: enumerate in python Say, term='asdf'; InvertedIndex = {}; InvertedIndex[term] = [1,2,2,2,4,5,6,6,6,6,7]. Now we have this function which counts no. of occurances of any item. This is the function I've having a problem with. def TF(term, doc): idx = InvertedIndex[term].index(doc) return next(i for i, item...
enumerate in python
Say, term='asdf'; InvertedIndex = {}; InvertedIndex[term] = [1,2,2,2,4,5,6,6,6,6,7]. Now we have this function which counts no. of occurances of any item. This is the function I've having a problem with. def TF(term, doc): idx = InvertedIndex[term].index(doc) return next(i for i, item in enumerate(InvertedInd...
[ "I feel like I wrote that loop on another answer but the correct answer for what you want to do is InvertedIndex[term].count(doc)\nThis will count the number of times that doc occurs in the list.\n", "At the language-level, your problem is that you're calling 'next' on a sequence, and when the sequence is empty i...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004062448_python.txt
Q: Order of numpy orperations is not equal to logic (and also octave)? Maybe this question should be strictly in the scipy-users, but I'll try here too. So here is something which I discovered lately and is making me wonder. I want to define a scalar which I call Net Absolute Mass Balance Error or in short NAMBE. T...
Order of numpy orperations is not equal to logic (and also octave)?
Maybe this question should be strictly in the scipy-users, but I'll try here too. So here is something which I discovered lately and is making me wonder. I want to define a scalar which I call Net Absolute Mass Balance Error or in short NAMBE. This NAMBE is the absolute difference between a base vector and another ve...
[ "sum(a-b)/sum(a) is not the same as sum((a-b)/a).\nConsider e.g. a=[1,0] and b=[-1,1]. Then sum(a/b) == sum([-1,0]) == -1, but sum(a)/(sum(b) == 1/0 which doesn't make sense.\n" ]
[ 7 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004062360_numpy_python.txt
Q: Language specific redirect I want to create simple application that detects language(using Google API) of phrase and send it to corresponded search engine. For example, if search query is in Russian then I need to redirect it to Yandex.ru in all other cases to Google. That's how I do this: def get(self): ...
Language specific redirect
I want to create simple application that detects language(using Google API) of phrase and send it to corresponded search engine. For example, if search query is in Russian then I need to redirect it to Yandex.ru in all other cases to Google. That's how I do this: def get(self): ...
[ "You need to remove quote() from url = \"http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=\"+ quote(text), its returning a bad result for your Russian query.\nI tested your code in my local python shell and it worked without quote(), but did not work with quote().\n", "I suggest using the Google P...
[ 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004022332_google_app_engine_python.txt
Q: Fail safe code for cgi python scripts Coming from mostly C++ I'm relatively new to python and probably far from thinking in pythonic ways. Recently my web hoster activated python as cgi for my web space. I got an email asking me to test any python scripts on a local server (xampp, ...) since my web space is hosted...
Fail safe code for cgi python scripts
Coming from mostly C++ I'm relatively new to python and probably far from thinking in pythonic ways. Recently my web hoster activated python as cgi for my web space. I got an email asking me to test any python scripts on a local server (xampp, ...) since my web space is hosted on a productivity server. Now my question...
[ "Writing tests is always a good thing to do. Use this alongside coverage.py, and you should get some pretty safe code.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004062750_python.txt
Q: In what structure is a Python object stored in memory? Say I have a class A: class A(object): def __init__(self, x): self.x = x def __str__(self): return self.x And I use sys.getsizeof to see how many bytes instance of A takes: >>> sys.getsizeof(A(1)) 64 >>> sys.getsizeof(A('a')) 64 >>> s...
In what structure is a Python object stored in memory?
Say I have a class A: class A(object): def __init__(self, x): self.x = x def __str__(self): return self.x And I use sys.getsizeof to see how many bytes instance of A takes: >>> sys.getsizeof(A(1)) 64 >>> sys.getsizeof(A('a')) 64 >>> sys.getsizeof(A('aaa')) 64 As illustrated in the experiment ...
[ "It depends on what kind of object, and also which Python implementation :-)\nIn CPython, which is what most people use when they use python, all Python objects are represented by a C struct, PyObject. Everything that 'stores an object' really stores a PyObject *. The PyObject struct holds the bare minimum informat...
[ 27, 0 ]
[]
[]
[ "object", "python", "python_internals" ]
stackoverflow_0004062752_object_python_python_internals.txt
Q: Python regular expressions Is there any regular expression to match this: a continuous string of characters or/and digits XOR a string of any characters between a pairquotation marks (" XOR ')including nested quotations ? Examples: dgsdggsgggdggsggsd 'dsfsasf .asgafaasfafw rq' "sadas fa fasfa " A: Perhaps ...
Python regular expressions
Is there any regular expression to match this: a continuous string of characters or/and digits XOR a string of any characters between a pairquotation marks (" XOR ')including nested quotations ? Examples: dgsdggsgggdggsggsd 'dsfsasf .asgafaasfafw rq' "sadas fa fasfa "
[ "Perhaps relevant: do you know about the shlex module?\n", "Maybe you can try this:\n>>> message = \"blabla df qdsf dqsf \\\"fqdfdqsfsdf fdqs fqdsf\\\"\"\n>>> pattern = \"(\\w+|'.*[^']'|\\\".*[^\\\"]\\\")\"\n>>> re.findall(pattern, message)\n['blabla', 'df', 'qdsf', 'dqsf', '\"fqdfdqsfsdf fdqs fqdsf\"']\n\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004058943_python.txt
Q: string conversion I’ve got a long string object which has been formatted like this myString = “[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]” of course the string is longer than this. Also i have 3 lists with related names: Names = [] Families = [] Ages = [] I want to ...
string conversion
I’ve got a long string object which has been formatted like this myString = “[name = john, family = candy, age = 72],[ name = jeff, family = Thomson, age = 24]” of course the string is longer than this. Also i have 3 lists with related names: Names = [] Families = [] Ages = [] I want to read that string charac...
[ "This can be most easily done using a regex. Basically, construct a regex that extracts the name,family and age from the string and extract the relevant data from the tuples returned to build your lists.\nimport re\n\nif __name__=='__main__':\n myString = \"[name = john adams, family = candy, age = 72],[ name = ...
[ 5, 3, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004063019_python_string.txt
Q: override multiprocessing in python how can i get variable in class which is override multiprocessing in python: #!/usr/bin/env python import multiprocessing import os class TestMultiprocess(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.myvar = '' ...
override multiprocessing in python
how can i get variable in class which is override multiprocessing in python: #!/usr/bin/env python import multiprocessing import os class TestMultiprocess(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.myvar = '' def myfunc(self): return os.g...
[ "The run() will executed in a separate process; processes don't share memory, normally. multiprocessing does support shared variables, though, through the explicit Value class:\n#!/usr/bin/env python\n\nimport multiprocessing\nimport os\n\nclass TestMultiprocess(multiprocessing.Process):\n def __init__(self):\n ...
[ 3, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0004063220_multiprocessing_python.txt
Q: convert python request to PHP-cURL equivalent I am sending a POST request to a URL. It works correctly in python but in php-curl, I always get a bad request error (i.e. my POST data is not as expected by the server) Python code: (works correctly. 200 OK) import httplib, urllib, json def SendRequest(param1): u...
convert python request to PHP-cURL equivalent
I am sending a POST request to a URL. It works correctly in python but in php-curl, I always get a bad request error (i.e. my POST data is not as expected by the server) Python code: (works correctly. 200 OK) import httplib, urllib, json def SendRequest(param1): url = "api.xyz.com" body = {"version": "1.0", "d...
[ "In a case like this, I find that it's always better to look at what goes over the wire instead of trying to puzzle out what might be wrong with the code. \nMy advice:\n\nCreate a little test server using the python BaseHTTPServer and\nderive a class from\nBaseHTTPRequestHandler that doesn't\ndo anything but provi...
[ 1, 1, 1 ]
[]
[]
[ "curl", "php", "python" ]
stackoverflow_0004058405_curl_php_python.txt
Q: How to perform Job scheduling algorithms using python? Well , i want to test out which scheduling algorithm is suitable for my application , but unable to figure out on how to go about testing. i have a set of jobs to be executed , for SMP (Symmetric Multi Process ) execution i used Parallel Python , but not able ...
How to perform Job scheduling algorithms using python?
Well , i want to test out which scheduling algorithm is suitable for my application , but unable to figure out on how to go about testing. i have a set of jobs to be executed , for SMP (Symmetric Multi Process ) execution i used Parallel Python , but not able to apply Job Scheduling algorithm . For ex: if i want to i...
[ "You can only tell if the job you're submitting is the shortest if you know the runtime of all your jobs in advance. This is not an easy thing to know without first running the jobs. SJF is rarely used for this reason. Scheduling in a FIFO is much easier; you stick the jobs in a list as they come in (with lst.appen...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004063534_python.txt
Q: Problem with reading file in Python I have a file: Alus.txt File content: (each name in new line) Margus Mihkel Daniel Mark Juri Victor Marek Nikolai Pavel Kalle Problem: While programm reads this file, there are \n after each name (['Margus\n', 'Mihkel\n', 'Daniel\n', 'Mark\n', 'Juri\n', 'Victor\n', 'Marek\n', ...
Problem with reading file in Python
I have a file: Alus.txt File content: (each name in new line) Margus Mihkel Daniel Mark Juri Victor Marek Nikolai Pavel Kalle Problem: While programm reads this file, there are \n after each name (['Margus\n', 'Mihkel\n', 'Daniel\n', 'Mark\n', 'Juri\n', 'Victor\n', 'Marek\n', 'Nikolai\n', 'Pavel\n', 'Kalle']). How ca...
[ "You can remove the linebreaks with rstrip:\nalus = []\nwith open('alus.txt', 'r') as f:\n for rida in f:\n rida=rida.rstrip()\n if rida: alus.append(rida)\n else: break\n\nBy the way, the usual way to test if a string is empty is\nif not rida:\n\nrather than\nif (rida == ''):\n\nAnd if you ...
[ 4, 4, 3, 1 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0004062858_file_list_python.txt
Q: What is proper Tokenization algorithm? & Error: TypeError: coercing to Unicode: need string or buffer, list found I'm doing an Information Retrieval Task. As part of pre-processing I want to doing. Stopword removal Tokenization Stemming (Porter Stemmer) Initially, I skipped tokenization. As a result I got terms...
What is proper Tokenization algorithm? & Error: TypeError: coercing to Unicode: need string or buffer, list found
I'm doing an Information Retrieval Task. As part of pre-processing I want to doing. Stopword removal Tokenization Stemming (Porter Stemmer) Initially, I skipped tokenization. As a result I got terms like this: broker broker' broker, broker. broker/deal broker/dealer' broker/dealer, broker/dealer. broker/dealer; brok...
[ "There is no single perfect algorithm for tokenization, though your algorithm may suffice for information retrieval purposes. It will be easier to implement using a regular expression:\ndef Tokenize(text):\n words = re.split(r'[-\\.,?!:;_()\\[\\]\\'`\"/\\t\\n\\r \\x0b\\x0c]+', text)\n return [word.strip() for...
[ 1, 0 ]
[]
[]
[ "information_retrieval", "nlp", "python", "tokenize" ]
stackoverflow_0004063423_information_retrieval_nlp_python_tokenize.txt
Q: invisible watermarks in images How do you insert invisible watermarks in images for copyright purposes? I'm looking for a python library. What algorithm do you use? What about performance and efficiency? A: You might want to look into Steganography; that is hiding data inside of images. There are forms that won'...
invisible watermarks in images
How do you insert invisible watermarks in images for copyright purposes? I'm looking for a python library. What algorithm do you use? What about performance and efficiency?
[ "You might want to look into Steganography; that is hiding data inside of images. There are forms that won't get lost if you convert to a lossier format or even crop parts of the image out.\n", "I'm looking for \"unbreakable\" watermarks, so data stored in exif or image metadata are out.\nI have found some intere...
[ 6, 5, 4, 3, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "image", "python", "watermark" ]
stackoverflow_0000044101_image_python_watermark.txt
Q: how to reliably decode various encodings to system default encoding I am trying to work with several documents that all have various encodings - some utf-8, some ISO-8859-2, some ascii etc. Is there a reliable way of decoding to a standard encoding for processing? I have tried the following: import chardet encodin...
how to reliably decode various encodings to system default encoding
I am trying to work with several documents that all have various encodings - some utf-8, some ISO-8859-2, some ascii etc. Is there a reliable way of decoding to a standard encoding for processing? I have tried the following: import chardet encoding = chardet.detect(text) text = unicode(text,encoding['encoding']).decode...
[ "Use decode to convert bytes to unicode, and encode to convert unicode to bytes:\ntext.decode(encoding['encoding'], 'ignore').encode(sys.getdefaultencoding(), 'ignore')\n\nAlthough I would recommend doing your processing on the unicode objects themselves, or UTF-8 encoded strings if you absolutely need to work with...
[ 3, 0 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0004063860_character_encoding_python.txt
Q: Read other items in a python list while iterating through it Possible Duplicate: Python: Looping through all but the last item of a list Is there a better way of iterating through a list when you also need the next item (or any other arbitrary item) in the list? I use this, but maybe someone can do better... val...
Read other items in a python list while iterating through it
Possible Duplicate: Python: Looping through all but the last item of a list Is there a better way of iterating through a list when you also need the next item (or any other arbitrary item) in the list? I use this, but maybe someone can do better... values = [1, 3, 6, 7 ,9] diffs = [] for i in range(len(values)): ...
[ ">>> values = range(10)\n>>> values\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> zip(values[0:],values[1:])\n[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]\n\n", "what about with the aid of pairwise recipe from itertools document\nfrom itertools import tee, izip\n\ndef pairwise(iterable):\n \...
[ 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "iterator", "list", "python" ]
stackoverflow_0004062583_iterator_list_python.txt
Q: Maximum match length of a regular expression What is the easiest way to determine the maximum match length of a regular expression? Specifically, I am using Python's re module. E.g. for foo((bar){2,3}|potato) it would be 12. Obviously, regexes using operators like * and + have theoretically unbounded match lengths...
Maximum match length of a regular expression
What is the easiest way to determine the maximum match length of a regular expression? Specifically, I am using Python's re module. E.g. for foo((bar){2,3}|potato) it would be 12. Obviously, regexes using operators like * and + have theoretically unbounded match lengths; in those cases returning an error or something i...
[ "Using pyparsing's invRegex module:\nimport invRegex\ndata='foo(bar{2,3}|potato)' \nprint(list(invRegex.invert(data)))\n# ['foobarr', 'foobarrr', 'foopotato'] \nprint(max(map(len,invRegex.invert(data))))\n# 9\n\nAnother alternative is to use ipermute from this module.\nimport inverse_regex\ndata='foo(bar{2,3}...
[ 6, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004063392_python_regex.txt
Q: django template question (accessing a list) I am writing a template for my first django website. I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length) The template looks something like this: <html> ...
django template question (accessing a list)
I am writing a template for my first django website. I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length) The template looks something like this: <html> <head><title>First page</title></head><body> ...
[ "In short, Django doesn't do what you want.\nThe for loop has a number of useful properties within a loop.\n\nforloop.counter The current iteration of the loop (1-indexed)\nforloop.counter0 The current iteration of the loop (0-indexed)\nforloop.revcounter The number of iterations from the end of the loop (1...
[ 7, 2, 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004063515_django_django_templates_python.txt
Q: Jinja2 - Given 2 templates (as strings) how to render one that extends the other? I'm making a simple script that works on Jinja2 templates. Right now it's just reading files in from disk manually, i.e. no Jinja Loaders. I have 2 strings (A and B), representing 2 templates. I want to make one template (B) inherit ...
Jinja2 - Given 2 templates (as strings) how to render one that extends the other?
I'm making a simple script that works on Jinja2 templates. Right now it's just reading files in from disk manually, i.e. no Jinja Loaders. I have 2 strings (A and B), representing 2 templates. I want to make one template (B) inherit from the other (A), i.e. I have {% block body %}{% endblock %} in A, and I want to make...
[ "Your best bet probably to use a different template loader. Take a look at DictLoader and FunctionLoader, or try your hand a writing your own template loader.\n" ]
[ 3 ]
[]
[]
[ "jinja2", "python", "templates" ]
stackoverflow_0004064362_jinja2_python_templates.txt
Q: python class attributes not setting? I am having a weird problem with a chatbot I am writing that supports plugin extensions. The base extension class have attributes and methods predefined that will be inherited and can be overloaded and set. Here is the base class: class Ext: # Info about the extension N...
python class attributes not setting?
I am having a weird problem with a chatbot I am writing that supports plugin extensions. The base extension class have attributes and methods predefined that will be inherited and can be overloaded and set. Here is the base class: class Ext: # Info about the extension Name = 'Unnamed' Author = 'Nobody' ...
[ "You forgot a 'self' in class Extension:\ntry: self.AI = self.Load(self.file)\n\nalso, maybe your printing test is inaccurate. Have you tried unit tests?\n", "Is it possible that the block below the SetName call is actually indented differently (say, with tabs instead of spaces) and the following lines are not...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004061740_python.txt
Q: scramble function won't output this function will not give me an output when tested in python's IDLE: import random def scramble(string): rlist = [] while len(rlist) < len(string): n = random.randint(0, len(string) - 1) if rlist.count(string[n]) < string.count(string[n]): rlist += ...
scramble function won't output
this function will not give me an output when tested in python's IDLE: import random def scramble(string): rlist = [] while len(rlist) < len(string): n = random.randint(0, len(string) - 1) if rlist.count(string[n]) < string.count(string[n]): rlist += string[n] rstring = str(rlist) ...
[ "Correctly formatting this seems to solve the problem.\nimport random\n\ndef scramble(string):\n rlist = []\n while len(rlist) < len(string):\n n = random.randint(0, len(string) - 1)\n if rlist.count(string[n]) < string.count(string[n]):\n rlist += string[n]\n rstring = str(rlist) \n ...
[ 0, 0 ]
[]
[]
[ "function", "python", "scramble" ]
stackoverflow_0004064619_function_python_scramble.txt
Q: Python statement uses excessive amounts of RAM This simple statement: zip(xrange(0, 11614321), xrange(0, 11627964)) ...is eating most of my RAM. (>150 MiB!) Why? Edit: Ah, re-reading the docs, I see zip returns a list, not an iterable. Anything like zip that returns an iterable? The larger picture: I'm iterating...
Python statement uses excessive amounts of RAM
This simple statement: zip(xrange(0, 11614321), xrange(0, 11627964)) ...is eating most of my RAM. (>150 MiB!) Why? Edit: Ah, re-reading the docs, I see zip returns a list, not an iterable. Anything like zip that returns an iterable? The larger picture: I'm iterating over two large arrays of file data, and I'm doing t...
[ "Use izip from itertools\n", "If for some reason you didn't want to use the itertools module, it would be trivial to write your own iterator that did the same thing, at least if you know you're dealing with exactly two input iterators.\ndef xzip2(i1, i2):\n i1, i2 = iter(i1), iter(i2)\n while True:\n ...
[ 12, 3 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0004064818_memory_management_python.txt
Q: Python: Cannot pop from empty list? When list is clearly not empty? I'm obviously missing something here. Same project I've been working on for a number of days. Stepping through it bit by bit, seemed to be working fine. I added in a portion of the main() function to actually create the comparison lists, and sudde...
Python: Cannot pop from empty list? When list is clearly not empty?
I'm obviously missing something here. Same project I've been working on for a number of days. Stepping through it bit by bit, seemed to be working fine. I added in a portion of the main() function to actually create the comparison lists, and suddenly starts throwing out cannot pop from empty list error at me, even thro...
[ "First of all , i did get lost while reading your code so maybe i can give you some remark if i may before:\n\nto many instance variable you don't have to create a new instance var just to put on it a set() of another vars like this code : self.mal_set = set(self.mal_list)and you are repeating the same thing many t...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "list", "multithreading", "python" ]
stackoverflow_0004064424_list_multithreading_python.txt
Q: Message queue proxy in Python + Twisted I want to implement a lightweight Message Queue proxy. It's job is to receive messages from a web application (PHP) and send them to the Message Queue server asynchronously. The reason for this proxy is that the MQ isn't always avaliable and is sometimes lagging, or even dow...
Message queue proxy in Python + Twisted
I want to implement a lightweight Message Queue proxy. It's job is to receive messages from a web application (PHP) and send them to the Message Queue server asynchronously. The reason for this proxy is that the MQ isn't always avaliable and is sometimes lagging, or even down, but I want to make sure the messages are d...
[ "You're basically considering writing an ad-hoc extension to your messaging server, the job of which it is to provide whatever reliability guarantees you've asked of it.\nInstead, perhaps you should take the hardware where you were planning to run this new proxy and run another MQ node on it. The new node should t...
[ 4, 1, 0 ]
[]
[]
[ "message_queue", "multithreading", "proxy_classes", "python", "twisted" ]
stackoverflow_0002950777_message_queue_multithreading_proxy_classes_python_twisted.txt
Q: Python Read and Output from Stdin Unbuffered In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like: while (true) { readline break if eof print process(line) } I can't seem to get this kind of behavior in ...
Python Read and Output from Stdin Unbuffered
In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like: while (true) { readline break if eof print process(line) } I can't seem to get this kind of behavior in Python because it buffers the output (i.e. no prin...
[ "Do you have an example which shows the problem?\nFor example (Python 3):\ndef process(line):\n return len(line)\ntry:\n while True:\n line = input()\n print(process(line))\nexcept EOFError:\n pass\n\nPrints the length of each line after each line.\n", "use sys.stdout.flush() to flush out t...
[ 3, 2, 1, 0 ]
[]
[]
[ "loops", "python", "stdin" ]
stackoverflow_0004064401_loops_python_stdin.txt
Q: uTidylib segmentation fault uTidylib is crashing and giving me a segmentation fault every time I try to use it. Here's some info about the crash: Process: Python [432] Path: /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python Identifier: Pytho...
uTidylib segmentation fault
uTidylib is crashing and giving me a segmentation fault every time I try to use it. Here's some info about the crash: Process: Python [432] Path: /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: ??? (???) Code...
[ "pyTidyLib , the utidylib is too old (last time updated 2004 ) \n" ]
[ 2 ]
[]
[]
[ "macos", "python", "segmentation_fault", "tidy" ]
stackoverflow_0004065061_macos_python_segmentation_fault_tidy.txt
Q: Extraction from a string in R or Python I have a csv file with addresses that include ',', empty space, numbers. I have two other files with city and zip codes. I want to read the address file and extract the city name and zip codes. As you will see below the addresses have no easy pattern and is randomly sprink...
Extraction from a string in R or Python
I have a csv file with addresses that include ',', empty space, numbers. I have two other files with city and zip codes. I want to read the address file and extract the city name and zip codes. As you will see below the addresses have no easy pattern and is randomly sprinkled with ',' spaces etc.Here is an example. A...
[ "Use Google Refine. It's an open source project that is perfect for data cleansing and export into a format that actually makes sense. Everything is GUI based and it stores a complete history. You wont need to mess around with tedious regular expressions.\n", "You might consider using something like this, though ...
[ 3, 1, 0 ]
[]
[]
[ "python", "r" ]
stackoverflow_0004064464_python_r.txt
Q: Python problem with circular reference: I get: ImportError: cannot import name Image (from image_blob.py) please help me thanks :s my code: image.py: from google.appengine.ext import db from app.models.item import Item class Image(Item): # imports from app.models.image_blob import ImageBlob #from app...
Python problem with circular reference:
I get: ImportError: cannot import name Image (from image_blob.py) please help me thanks :s my code: image.py: from google.appengine.ext import db from app.models.item import Item class Image(Item): # imports from app.models.image_blob import ImageBlob #from app.models.user import User #from list_user ...
[ "You're trying to import from image_blob.py before the entirety of image.py is processed. At the time which the from app.models.item import Item occurs, class Image hasn't yet been defined, and thus can't yet be imported (the entire class definition must have been processed before the symbol is actually defined).\n...
[ 2 ]
[]
[]
[ "circular_reference", "python" ]
stackoverflow_0004065117_circular_reference_python.txt
Q: Django Time issues My app in django requires to tell the user what time an action occurred. Aside from asking the user what timezone he/she is in, is it possible for me to generate the time on the client end? Off the top of my head, are there a particular representation of time that is timezone independent, (unix...
Django Time issues
My app in django requires to tell the user what time an action occurred. Aside from asking the user what timezone he/she is in, is it possible for me to generate the time on the client end? Off the top of my head, are there a particular representation of time that is timezone independent, (unix time?), and then I can ...
[ "I'd make all my times UTC, as that's a good international-level reference point, and you can always shift that to a local time, given that you know the user's TZ.\nI'd also use the time on the server (datetime.datetime.now()) rather than rely on the client's system clock, as this makes it easy to fake what time so...
[ 2, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004065157_django_python.txt
Q: How to index a Blog as a search engine? I want to create a simple search engine for learning purpose. I want to know how to index a simple blog site. A blog site has many pages and in every page there is a blogpost. But in every page there are other stuff in common as well ( header, footer, category block and othe...
How to index a Blog as a search engine?
I want to create a simple search engine for learning purpose. I want to know how to index a simple blog site. A blog site has many pages and in every page there is a blogpost. But in every page there are other stuff in common as well ( header, footer, category block and other stuff ). In your opinion, How can I index t...
[ "You can use the quite powerfull Zend Lucene search engine for that (PHP 5). \nhttp://framework.zend.com/manual/en/zend.search.lucene.html\n" ]
[ 0 ]
[]
[]
[ "php", "python", "search", "search_engine", "web_crawler" ]
stackoverflow_0004065359_php_python_search_search_engine_web_crawler.txt
Q: How to add a python binding to C#? When you want to call C from python, you write a module like this: http://docs.python.org/extending/extending.html Now, I have a question: I want to write a module for use in Python with C#. How can I get C# to interact with native Python ? (Note: I'm not interested in Python.NET...
How to add a python binding to C#?
When you want to call C from python, you write a module like this: http://docs.python.org/extending/extending.html Now, I have a question: I want to write a module for use in Python with C#. How can I get C# to interact with native Python ? (Note: I'm not interested in Python.NET or IronPython).
[ "I know you are probably not gonna like this answer, but honestly: write it in C++, using boost::python or directly in Cython. \nIt'd be possible to write an extension using C#, but you'd have to convert the data structures used by Python, import a good deal of the Python C API, marshal everything back and forth be...
[ 2 ]
[]
[]
[ ".net", "c#", "python", "python_bindings" ]
stackoverflow_0004065352_.net_c#_python_python_bindings.txt
Q: SQLite vague syntax error Ok, so I'm putting a list of 25 tuples, with each tuple containing 5 items, into an sqlite database. Each time I try the main code to write, I get "apsw.SQLError: SQLError: near "?": syntax error" Here's the code I'm running. Be aware that this is part of a much, much larger server projec...
SQLite vague syntax error
Ok, so I'm putting a list of 25 tuples, with each tuple containing 5 items, into an sqlite database. Each time I try the main code to write, I get "apsw.SQLError: SQLError: near "?": syntax error" Here's the code I'm running. Be aware that this is part of a much, much larger server project for a game, so some of the fu...
[ "I believe it should be:\nself.memcursor.executemany(\"INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)\",self.blocklist)\n\n", "You probably forgot the VALUES keyword:\n self.memcursor.executemany(\"INSERT OR REPLACE INTO main VALUES (?,?,?,?,?)\",self.blocklist)\n\nHave a look here for the correct syntax.\n" ]
[ 3, 0 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0004065457_database_python_sqlite.txt
Q: How to programmatically merge text files with potential conflicts (ala git or svn, etc)? As part of a larger project, I want the ability to take two bodies of text and hand them to a merge algorithm which returns either an auto-merged result (in cases where the changes are not conflicting) or throws an error and (...
How to programmatically merge text files with potential conflicts (ala git or svn, etc)?
As part of a larger project, I want the ability to take two bodies of text and hand them to a merge algorithm which returns either an auto-merged result (in cases where the changes are not conflicting) or throws an error and (potentially) produces a single text document with the conflicting changes highlighted. Basical...
[ "You're probably searching for merge algorithms like 3-way merging, which you can find in many open source projects, e.g. in the bazaar VCS (merge3.py source).\n", "Did you check out difflib \n\nhttp://docs.python.org/library/difflib.html\n\n" ]
[ 11, 1 ]
[]
[]
[ "command_line", "diff", "merge", "python", "text" ]
stackoverflow_0004065541_command_line_diff_merge_python_text.txt
Q: PyGtk - Activating a combo box If I have a combo box in pyGTK and would like to set a list of strings and then on clicking on one activate a command how would I do it? At the moment I have: self.combo_key = gtk.Combo() self.combo_key.set_popdown_strings(self.keys) self.combo_key.entry.set_text(db.keys(...
PyGtk - Activating a combo box
If I have a combo box in pyGTK and would like to set a list of strings and then on clicking on one activate a command how would I do it? At the moment I have: self.combo_key = gtk.Combo() self.combo_key.set_popdown_strings(self.keys) self.combo_key.entry.set_text(db.keys()[0]) self.combo_key.entry.conne...
[ "Try using a gtk.ComboBox instead of gtk.Combo, since the latter is deprecated in favor of the former. To initialise, you can you code like:\nliststore = gtk.ListStore(gobject.TYPE_STRING)\nfor key in self.keys:\n liststore.append((key,))\ncombobox = gtk.ComboBox(liststore)\ncell = gtk.CellRendererText()\ncombo...
[ 2 ]
[]
[]
[ "combobox", "gtk", "pygtk", "python" ]
stackoverflow_0004065680_combobox_gtk_pygtk_python.txt
Q: wx.GenericDirCtrl Event's handling I'm using this control but I can't to handle control click (and others events). This is my code: class BoExplorerPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, wx.ID_ANY) self.initComponents() # initialize Window components def initC...
wx.GenericDirCtrl Event's handling
I'm using this control but I can't to handle control click (and others events). This is my code: class BoExplorerPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, wx.ID_ANY) self.initComponents() # initialize Window components def initComponents(self): print "Inizializzo...
[ "You need to bind to the TreeCtrl of the directory class, not that class itself. \nFixed code below. Note the call to event.Skip() in the event handlers (comment it out to see its effect)\n#!/usr/bin/python\nimport wx\n\nclass BoExplorerPanel(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n\n...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004065734_python_wxpython.txt
Q: How do I get a window's current size using Tkinter? How do I get a windows current size using Tkinter, or possibly with the python standard library? A: Use the following universal widget methods (where w is a widget): w.winfo_height() w.winfo_width() You can also use the following: w.winfo_reqheight() w.winfo_...
How do I get a window's current size using Tkinter?
How do I get a windows current size using Tkinter, or possibly with the python standard library?
[ "Use the following universal widget methods (where w is a widget):\nw.winfo_height()\nw.winfo_width()\n\nYou can also use the following:\nw.winfo_reqheight()\nw.winfo_reqwidth()\n\nRead about Universal widget methods.\n" ]
[ 31 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004065783_python_tkinter.txt
Q: Amarok 1.4 script: knowing who's running you I've been using Amarok 1.4 for a long time, switching to Bogdan Butnaru's packages when KDE stopped supporting it, and I'm now giving Pana a try. I realised that a script I wrote in Python for Amarok 1.4 will not immediately run without changes under Pana. But instead ...
Amarok 1.4 script: knowing who's running you
I've been using Amarok 1.4 for a long time, switching to Bogdan Butnaru's packages when KDE stopped supporting it, and I'm now giving Pana a try. I realised that a script I wrote in Python for Amarok 1.4 will not immediately run without changes under Pana. But instead of converting my script, which basically comes dow...
[ "import os\n\npid = os.getppid()\nwith open(\"/proc/%s/cmdline\" % pid) as f:\n print f.readline()\n\nAssuming you are running Linux. Not sure if you need getppid() or getpid() here.\nNot so pythonic maybe.\n" ]
[ 1 ]
[]
[]
[ "dcop", "linux", "python" ]
stackoverflow_0004062911_dcop_linux_python.txt
Q: Using the RESTful interface to Google's AJAX Search API for "Did you mean"? Is it possible to get spelling/search suggestions (i.e. "Did you mean") via the RESTful interface to Google's AJAX search API? I'm trying to access this from Python, though the URL query syntax is all I really need. Thanks! A: the Google...
Using the RESTful interface to Google's AJAX Search API for "Did you mean"?
Is it possible to get spelling/search suggestions (i.e. "Did you mean") via the RESTful interface to Google's AJAX search API? I'm trying to access this from Python, though the URL query syntax is all I really need. Thanks!
[ "the Google AJAX API don't have a spelling check feature see this, you can use the SOAP service but i think it's no longer available .\nat last you can look at yahoo API they have a feature for spelling check.\nEDIT : check this maybe it can help you:\nimport httplib\nimport xml.dom.minidom\n\ndata = \"\"\"\n<spell...
[ 2, 1 ]
[]
[]
[ "ajax", "python", "rest", "search" ]
stackoverflow_0004065450_ajax_python_rest_search.txt
Q: Queue(maxsize=) not working? I've implemented some threading into a project I've been working on in another thread, but the comments and questions have grown way off topic of the original post, so I figured best thing to do was to make a new question. The problem is this. I want my program to stop iterating over a...
Queue(maxsize=) not working?
I've implemented some threading into a project I've been working on in another thread, but the comments and questions have grown way off topic of the original post, so I figured best thing to do was to make a new question. The problem is this. I want my program to stop iterating over a while loop after an amount of ite...
[ "You're not actually passing the integer 10 as the maxsize. You're passing sys.argv[2]. sys.argv is a list of strings, so at best you're passing \"10\" as the maxsize argument. And unfortunately, in Python 2.x, any integer is less than any string. You probably want to use int(sys.argv[2]) instead.\n" ]
[ 1 ]
[]
[]
[ "python", "set", "threadpool" ]
stackoverflow_0004065885_python_set_threadpool.txt
Q: using locals() inside dictionary comprehension The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated: def f(): a = 1 b = 2 list_ = ['a', 'b'] dict_ = {x : locals()[x] for x in list_} I could ...
using locals() inside dictionary comprehension
The following code doesn't work, I assume because the locals() variable inside the comprehension will refer to the nested block where comprehension is evaluated: def f(): a = 1 b = 2 list_ = ['a', 'b'] dict_ = {x : locals()[x] for x in list_} I could use globals() instead, and it seems to work, but tha...
[ "You could perhaps do this:\ndef f(): \n a = 1 \n b = 2 \n list_ = ['a', 'b'] \n locals_ = locals()\n dict_ = dict((x, locals_[x]) for x in list_)\n\nHowever, I would strongly discourage the use of locals() for this purpose.\n", "I believe that you're right: the locals() inside the dict comprehensi...
[ 8, 4 ]
[]
[]
[ "list_comprehension", "python", "python_3.x" ]
stackoverflow_0004065976_list_comprehension_python_python_3.x.txt
Q: Python 2.x: how to automate enforcing unicode instead of string? How can I automate a test to enforce that a body of Python 2.x code contains no string instances (only unicode instances)? Eg. Can I do it from within the code? Is there a static analysis tool that has this feature? Edit: I wanted this for an applica...
Python 2.x: how to automate enforcing unicode instead of string?
How can I automate a test to enforce that a body of Python 2.x code contains no string instances (only unicode instances)? Eg. Can I do it from within the code? Is there a static analysis tool that has this feature? Edit: I wanted this for an application in Python 2.5, but it turns out this is not really possible becau...
[ "It seems to me like you really need to parse the code with an honest to goodness python parser. Then you will need to dig through the AST your parser produces to see if it contains any string literals.\nIt looks like Python comes with a parser out of the box. From this documentation I got this code sample working:...
[ 1, 1, 0 ]
[]
[]
[ "automated_tests", "enforcement", "python", "static_analysis" ]
stackoverflow_0004046853_automated_tests_enforcement_python_static_analysis.txt
Q: What does fetch() fetch in GAE? This is a follow up to my other question. I thought that mylist = list(Rep().all().fetch(50)) makes mylist a list. But when I try to get its length I get the message self.response.out.write(len(P)) TypeError: object of type 'Rep' has no len() Can anyone explain what I am doing...
What does fetch() fetch in GAE?
This is a follow up to my other question. I thought that mylist = list(Rep().all().fetch(50)) makes mylist a list. But when I try to get its length I get the message self.response.out.write(len(P)) TypeError: object of type 'Rep' has no len() Can anyone explain what I am doing wrong? Rep().replist = L ...
[ "Instead of this:\nRep().replist = L \nRep().put() \nmylist = list(Rep().all().fetch(50)) \nP = mylist.pop() \nself.response.out.write(len(P)) \n\nTry something like this:\nr = Rep()\nr.replist = L \nr.put() ...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004063767_google_app_engine_google_cloud_datastore_python.txt
Q: Using Imagemagick without making files? I'm working in Python to create images from text. I've already been back and forth with PIL and frankly, its font and alignment options need a lot of work. I can subprocess Imagemagick and it works great, except that it seems to always need to write a file to disk. I would l...
Using Imagemagick without making files?
I'm working in Python to create images from text. I've already been back and forth with PIL and frankly, its font and alignment options need a lot of work. I can subprocess Imagemagick and it works great, except that it seems to always need to write a file to disk. I would like to subprocess the image creation and just...
[ "convert and the other ImageMagick commands can output image data to stdout if you specify format:- as the output file. You can capture that output in Python using the subprocess module.\nFor instance:\ncmd = [\"convert\", \"test.bmp\", \"jpg:-\"]\noutput_stream = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdou...
[ 7, 0 ]
[]
[]
[ "imagemagick", "python" ]
stackoverflow_0004066173_imagemagick_python.txt
Q: Python: Syntax Error for imported module - 'codecs.py' I'm using a script which imports some modules, one being codecs. When the script is executed, I'll get a Traceback (most recent call last): on the import codecs line and SyntaxError: ('no viable alternative at input \'""\'', ('C:\\Python26\\lib\\codecs.py', 26...
Python: Syntax Error for imported module - 'codecs.py'
I'm using a script which imports some modules, one being codecs. When the script is executed, I'll get a Traceback (most recent call last): on the import codecs line and SyntaxError: ('no viable alternative at input \'""\'', ('C:\\Python26\\lib\\codecs.py', 268, 17, ' return (b"", 0)\n')). This only occurs when...
[ "\nwhich in turn executes the script which ...\n\nHow does it ‘execute’ the script? You mean an import? A subprocess call? Something else?\nBecause “no viable alternative at input...” is a distinctive ANTLR parser error, and CPython 2.6 doesn't use that.\nJython 2.5 does. But Jython shouldn't be trying to run the c...
[ 2 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0004066328_python_windows_xp.txt
Q: identifying objects, why does the returned value from id(...) change? id(object) This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Can you explain this output? Why does j's id change? >>> i=10 >>> id(i) 6337824 >>> j=10 >>> id(j) 633...
identifying objects, why does the returned value from id(...) change?
id(object) This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Can you explain this output? Why does j's id change? >>> i=10 >>> id(i) 6337824 >>> j=10 >>> id(j) 6337824 >>> j=j+1 >>> id(j) 6337800 >>> id(i) 6337824
[ "Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.\nCheck out what happens when we independently create a new vari...
[ 34, 14, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003402679_python.txt
Q: Proper data structure to represent a Sudoku puzzle? What would be a smart data structure to use to represent a Sudoku puzzle? I.e. a 9X9 square where each "cell" contains either a number or a blank. Special considerations include: Ability to compare across row, column, and in 3X3 "group Ease of implementation (sp...
Proper data structure to represent a Sudoku puzzle?
What would be a smart data structure to use to represent a Sudoku puzzle? I.e. a 9X9 square where each "cell" contains either a number or a blank. Special considerations include: Ability to compare across row, column, and in 3X3 "group Ease of implementation (specifically in Python) Efficiency (not paramount) I suppo...
[ "Actually, I built such a beast, both a solver and a generator, and I used a 2D array. It worked fine.\nYou just had to understand the indexes and where they were and that wasn't too difficult to master.\nThe relative relationships between cells in a row doesn't change depending on the column, same goes for cells i...
[ 11, 8, 2, 0 ]
[]
[]
[ "data_structures", "graph", "python", "sudoku" ]
stackoverflow_0004066075_data_structures_graph_python_sudoku.txt
Q: Using gevent with python xmlrpclib Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch_all(), but without success. from gevent import monkey monkey.patch_all() import gevent import time import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer im...
Using gevent with python xmlrpclib
Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch_all(), but without success. from gevent import monkey monkey.patch_all() import gevent import time import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer import urllib2 def fetch(url): g ...
[ "The socket is patched fine, but there are other problems with your code.\nFirst, this\ndef fetch(url):\n g = gevent.spawn(urllib2.urlopen, url)\n return g.get().read()\n\nis the same as \ndef fetch(url):\n return urllib2.urlopen(url).read()\n\nYou're spawning a new greenlet here but then blocking the curr...
[ 9 ]
[]
[]
[ "gevent", "python", "xmlrpclib" ]
stackoverflow_0004065079_gevent_python_xmlrpclib.txt
Q: In Python, given a directory of full-size images, how can I generate thumbnails using more than one CPU core? I have a 16-core machine but my current resizing function only uses one core, which is really inefficient for a large directory of images. def generateThumbnail(self, width, height): """ Genera...
In Python, given a directory of full-size images, how can I generate thumbnails using more than one CPU core?
I have a 16-core machine but my current resizing function only uses one core, which is really inefficient for a large directory of images. def generateThumbnail(self, width, height): """ Generates thumbnails for an image """ im = Image.open(self._file) (detected_width,detected_height) = im.si...
[ "This sounds like a good solution for the multiprocessing module, which uses the threading interface, but creates separate processes instead of threads.\n" ]
[ 5 ]
[]
[]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0004066606_multithreading_python_python_multithreading.txt
Q: SQLite in Python 2.2.3 I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite. Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload...
SQLite in Python 2.2.3
I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite. Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butc...
[ "There is no out-of-the-box solution; you either have to backport the SQLlite module from Python 2.5 to Python 2.2 or ask your web hoster to upgrade to the latest Python version. \nPython 2.2 is really ancient! At least for security reasons, they should upgrade (no more security fixes for 2.2 since May 30, 2003!).\...
[ 2, 1, 0, 0 ]
[]
[]
[ "hosting", "linux", "python", "sql", "sqlite" ]
stackoverflow_0000737511_hosting_linux_python_sql_sqlite.txt
Q: Alternative to Connection.iterdump for SQLite in Python? I found a function that will help me load a disk SQLite database to a memory database, but have found that the module I need, apsw, doesn't support it, while pysqlite does. I need apsw because it has most of the functions I need that pysqlite does not. Is th...
Alternative to Connection.iterdump for SQLite in Python?
I found a function that will help me load a disk SQLite database to a memory database, but have found that the module I need, apsw, doesn't support it, while pysqlite does. I need apsw because it has most of the functions I need that pysqlite does not. Is there any work around to completely copying to a database?
[ "As singularity pointed out, APSW provides the backup functionality builtin to SQLite.\nThe reason you can't continue to use cursors (in practise the underlying SQLite compiled statements) is because the database schema has potentially completed changed as you have overwritten it with a backup. You can use close m...
[ 2, 0 ]
[]
[]
[ "database", "memory", "python", "sqlite" ]
stackoverflow_0004038111_database_memory_python_sqlite.txt
Q: Query to fetch objects surrounding an object Lets say I am fetching a specific episode of a series. What would be the best way to get the surrounding episodes by episode number? Simplified model: class Episode(models.Model): series = models.ForeignKey(Series) number = models.IntegerField() For example, ep...
Query to fetch objects surrounding an object
Lets say I am fetching a specific episode of a series. What would be the best way to get the surrounding episodes by episode number? Simplified model: class Episode(models.Model): series = models.ForeignKey(Series) number = models.IntegerField() For example, episode 10 would fetch episodes 8-12. Episode 1 woul...
[ "This looks like you're just treating a TV series as an array of episodes. If that's the case, why not something like\nEpisode.objects.filter(series=some_series,number__gte=epnum-2, number__lte=epnum+2)\n\nto find the episodes surrounding the episode epnum, with special cases for when epnum-2<=0 or epnum+2>Episode....
[ 3, 3 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0004066125_database_django_python.txt
Q: reading a file in python I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on? ID YR MO DA YrM MoM DaM 100 2010 2 20 2...
reading a file in python
I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on? ID YR MO DA YrM MoM DaM 100 2010 2 20 2010 8 2010 30 110 2010 ...
[ "Does the same technique for csv modules does not work? \nimport csv\nreader = csv.reader(open(\"filename\"), delimiter=\"\\t\")\n\nDelimiter can be \"\\s\" or \"\\t\".\nYou can also use DictReader this way:\nf = open(filename, '')\ntry:\n reader = csv.DictReader(f)\n for row in reader:\n print row\nfi...
[ 21, 8 ]
[]
[]
[ "csv", "python", "string" ]
stackoverflow_0004065594_csv_python_string.txt
Q: auto collect information in sub_modules when import in python? Suppose I have below python file structure: \function_group |-__init__.py |-sub_function1 |----|__init__.py |----|sub_sub_func1.py |----|sub_sub_func2.py |----|sub_sub_func3.py |-sub_function2 |----|__init__.py ...
auto collect information in sub_modules when import in python?
Suppose I have below python file structure: \function_group |-__init__.py |-sub_function1 |----|__init__.py |----|sub_sub_func1.py |----|sub_sub_func2.py |----|sub_sub_func3.py |-sub_function2 |----|__init__.py |----|sub_sub_func1.py |----|sub_sub_func2.py |----|s...
[ "1: You need\nimport inspect\nimport sys\ninspect.getmembers(sys.modules[__name__], inspect.isfunction)\n\n2: The best answer I can think of is to import the submodules, and inspect them in the top-level.\n\nNo, the onus is on the top-level package (the one which is imported) to do what it needs to do. You can't im...
[ 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0004067096_python_python_module.txt
Q: Python: translating/replacing in a string words that aren't the ones you want Basically, I've got a bunch of phrases and I'm only interested in the ones that contain certain words. What I want to do is 1) find out if that word is there and if it is, 2) erase all the other words. I could do this with a bunch of if'...
Python: translating/replacing in a string words that aren't the ones you want
Basically, I've got a bunch of phrases and I'm only interested in the ones that contain certain words. What I want to do is 1) find out if that word is there and if it is, 2) erase all the other words. I could do this with a bunch of if's and for's but I was wondering if there'd be a short/pythonic approach to it.
[ "A suggested algorithm:\n\nFor each phrase\n\nFind whether the interesting word is there\nIf it is, erase all other words\nOtherwise, just continue to the next phrase\n\n\nYes, implementing this would take \"a bunch of ifs and fors\", but you would be surprised how easily and cleanly such logic translates to Python...
[ 3, 1 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0004066667_python_text_processing.txt
Q: Alternative to locals() in printing a table with a header [Python 3.1] Edit: mistake in the original code. I need to print a table. The first row should be a header, which consists of column names separated by tabs. The following rows should contain the data (also tab-separated). To clarify, let's say I have colum...
Alternative to locals() in printing a table with a header
[Python 3.1] Edit: mistake in the original code. I need to print a table. The first row should be a header, which consists of column names separated by tabs. The following rows should contain the data (also tab-separated). To clarify, let's say I have columns "speed", "power", "weight". I originally wrote the following...
[ "class Columns:\n pass\n\ndef f(row_number):\n c = Columns()\n c.power = retrieve_avg_power(row_number) * 2.5\n c.speed = math.sqrt(power) / 2\n return c.__dict__\n\nThis also lets you specify which of the variables are meant as columns, instead of rather being temporary in the function.\n", "You c...
[ 2, 0, 0 ]
[]
[]
[ "list_comprehension", "locals", "python", "python_3.x" ]
stackoverflow_0004067463_list_comprehension_locals_python_python_3.x.txt
Q: Python function with too many arguments with default values, how to make it cleaner? I have the following function signature, and it looks really ugly, what can I do to make it look cleaner ? def contact( request, sender=settings.DEFAULT_FROM_EMAIL, subj_tmpl='contato/subject.txt',msg_tmpl='contato/msg.html', ...
Python function with too many arguments with default values, how to make it cleaner?
I have the following function signature, and it looks really ugly, what can I do to make it look cleaner ? def contact( request, sender=settings.DEFAULT_FROM_EMAIL, subj_tmpl='contato/subject.txt',msg_tmpl='contato/msg.html', template='contato/contato.html', success_template='contato/success.html', success_redi...
[ "if i were you i think i will do it like this:\ndef contact(request, sender=None, append_message=None, context=None):\n\n if not sender:\n sender = settings.DEFAULT_FROM_EMAIL # i hope that you can access settings here\n\n # The context arg is a dictionary where you can put all the others argument and \n...
[ 4, 3, 0, 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0004067520_django_django_views_python.txt
Q: Debugging Django when no Debug info is displayed | Django I'm serving an app through IIS6. An error is occurring preventing the app from working, I am not 100% sure what it might be. I believe the following is generated by python, but I am not entirely sure. "A server error has occurred. Please contact the admini...
Debugging Django when no Debug info is displayed | Django
I'm serving an app through IIS6. An error is occurring preventing the app from working, I am not 100% sure what it might be. I believe the following is generated by python, but I am not entirely sure. "A server error has occurred. Please contact the administrator" Any ideas on figuring out what is actually going on?...
[ "It looks more like web server error (500?).\nIs debugging enabled? You should be able to see exception message and traceback. Also, check web server error log and define settings.ADMINS. This is usefull in production when debugging is disabled:\n\nWhen DEBUG=False and a view raises an exception, Django will e-mail...
[ 2, 0 ]
[]
[]
[ "debugging", "django", "iis", "python" ]
stackoverflow_0004068210_debugging_django_iis_python.txt
Q: Why is python slower compared to Ruby even with this very simple "test"? See Is there something wrong with this python code, why does it run so slow compared to ruby? for my previous attempt at understanding the differences between python and ruby. As pointed out by igouy the reasoning I came up with for python b...
Why is python slower compared to Ruby even with this very simple "test"?
See Is there something wrong with this python code, why does it run so slow compared to ruby? for my previous attempt at understanding the differences between python and ruby. As pointed out by igouy the reasoning I came up with for python being slower could be something else than due to recursive function calls (stac...
[ "First off, note that the Python version you show is incorrect: you're running this code in Python 2.7, not 3.1 (it's not even valid Python3 code). (FYI, Python 3 is usually slower than 2.)\nThat said, there's a critical problem in the Python test: you're writing it as global code. You need to write it as a funct...
[ 16, 2, 1 ]
[ "It's too simple test. Maybe in such things Ruby is faster. But Python takes advantage, when you need to work with more complex datatypes and their methods. Python have much more implemented \"ways to do this\", and you must choose the one, which is the simplest and enough. Ruby works with more abstract entities an...
[ -3 ]
[ "performance", "python", "ruby", "testing" ]
stackoverflow_0004068122_performance_python_ruby_testing.txt
Q: Tkinter window layering I have two Tkinter windows, How do I keep one window always on top of the other? A: There isn't anything you can do AFAIK. According to the official tk documentation, ...there is no reliable way to track changes to a window's position in the stacking order. About the best you coul...
Tkinter window layering
I have two Tkinter windows, How do I keep one window always on top of the other?
[ "There isn't anything you can do AFAIK. According to the official tk documentation, \n\n...there is no reliable way to track\n changes to a window's position in the\n stacking order.\n\nAbout the best you could do is to periodically raise one window above the other. I don't recommend that because it may have some...
[ 1 ]
[]
[]
[ "python", "tkinter", "windows_7" ]
stackoverflow_0004066359_python_tkinter_windows_7.txt