content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I improve the efficiency of this numpy loop I've got a numpy array containing labels. I'd like to get calculate a number for each label based on its size and bounding box. How can I write this more efficiently so that it's realistic to use on large arrays (~15000 labels)? A = array([[ 1, 1, 0, 3, 3], ...
How can I improve the efficiency of this numpy loop
I've got a numpy array containing labels. I'd like to get calculate a number for each label based on its size and bounding box. How can I write this more efficiently so that it's realistic to use on large arrays (~15000 labels)? A = array([[ 1, 1, 0, 3, 3], [ 1, 1, 0, 0, 0], [ 1, 0, 0, 2, 2], ...
[ "I wasn't really able to implement this efficiently using some NumPy vectorised functions, so maybe a clever Python implementation will be faster.\ndef first_row(a, labels):\n d = {}\n d_setdefault = d.setdefault\n len_ = len\n num_labels = len_(labels)\n for i, row in enumerate(a):\n for labe...
[ 7, 5, 5, 1, 1 ]
[]
[]
[ "numpy", "optimization", "python" ]
stackoverflow_0008245817_numpy_optimization_python.txt
Q: How do I make PyCharm/PyDev/other IDEs offer code completion for IronPython namespaces? I like PyCharm and have used it before for my Python projects, but I just started messing with IronPython and I can't figure out how to make PyCharm or any other IDE for that matter (except for VS which works fine) recognize th...
How do I make PyCharm/PyDev/other IDEs offer code completion for IronPython namespaces?
I like PyCharm and have used it before for my Python projects, but I just started messing with IronPython and I can't figure out how to make PyCharm or any other IDE for that matter (except for VS which works fine) recognize the .NET libraries. For example, I have the code: from System.Environment import * path = Envi...
[ "For performance reasons, PyCharm does not generate Python stubs for .NET assemblies by default. You can trigger the generation by putting the caret on an unresolved reference in an import statement, pressing Alt-Enter and selecting the \"Generate stubs for binary module ...\" quickfix.\n", "Just to note, this sh...
[ 5, 3, 0 ]
[]
[]
[ "ironpython", "namespaces", "pycharm", "pydev", "python" ]
stackoverflow_0008109527_ironpython_namespaces_pycharm_pydev_python.txt
Q: Generate graph of the imports I'm getting close to my final goal, which is to generate a nice graph between modules and other imported modules. For example if x imports from y and z, and y imports from t and v I would like to have: x -> y, z y -> t, v Now I already have my import hook defined as below, but runnin...
Generate graph of the imports
I'm getting close to my final goal, which is to generate a nice graph between modules and other imported modules. For example if x imports from y and z, and y imports from t and v I would like to have: x -> y, z y -> t, v Now I already have my import hook defined as below, but running it on a simple file I don't get w...
[ "Maybe with the inspect module.\nModule a.py\nimport inspect\n\nprint inspect.stack()\n\nModule b.py\nimport a\n\nwhen running b.py, I got : \n[\n (<frame object at 0x28a9b70>, '/path/a.py', 5, '<module>', ['print inspect.stack()\\n'], 0),\n (<frame object at 0x28a9660>, 'b.py', 2, '<module>', ['import to_impor...
[ 2, 1, 0 ]
[]
[]
[ "import", "introspection", "python" ]
stackoverflow_0008246413_import_introspection_python.txt
Q: Cython vector operations How can I use the remove function from <algorithm>? (Or any other operation, I want to use this with vectors, I tried to cdef extern to declare it, but there is no template function yet, I think) A: Cython can only reasonably link against compiled code in some external library following...
Cython vector operations
How can I use the remove function from <algorithm>? (Or any other operation, I want to use this with vectors, I tried to cdef extern to declare it, but there is no template function yet, I think)
[ "Cython can only reasonably link against compiled code in some external library following the C calling conventions. To use template functions, you'll have to write an extern \"C\" wrapper function that uses a specific incarnation of the algorithm (i.e. you have to fix the template parameters).\n" ]
[ 6 ]
[]
[]
[ "algorithm", "c++", "cython", "python", "vector" ]
stackoverflow_0008295645_algorithm_c++_cython_python_vector.txt
Q: SQLAlchemy - create an instance in another instances __init__ Newish to SQLAlchemy (so my terminology may be a bit off). I want to create a database object inside the constructor of another, but the problem is I can't add said object to the session, so I get an error. My schema looks a bit like the following: clas...
SQLAlchemy - create an instance in another instances __init__
Newish to SQLAlchemy (so my terminology may be a bit off). I want to create a database object inside the constructor of another, but the problem is I can't add said object to the session, so I get an error. My schema looks a bit like the following: class Tag(Base): __tablename__ = 'tag' id = Column(Integer, Se...
[ "\nInherit Venue from Base. Otherwise Venue won't be mapped.\nMove ForeignKeyConstraint to __table_args__.\nReplace currently meaningless tag property with relationship to Tag. The default value of cascade parameter to relationship contains 'save-update' rule that will add new referred object to the same session a...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008283403_python_sqlalchemy.txt
Q: Draw complex table layout in Python GUI I need to create a GUI in Python for a client server interaction. The GUI is on the client side for which I want to create complex tables. I tried to use wxPython's grid class, but its too tough to create a complex table in that. I saw a couple of examples for simple table l...
Draw complex table layout in Python GUI
I need to create a GUI in Python for a client server interaction. The GUI is on the client side for which I want to create complex tables. I tried to use wxPython's grid class, but its too tough to create a complex table in that. I saw a couple of examples for simple table layouts. I tried to put up a snapshot of the...
[ "Tkinter would be enough for this.\nYou can create any level of complexity on the layout even with the \"grid\" \nlayout manager, which allows you to specify \"columnspam\" and \"rowspam\" for widgets that\nwill take more than a single cell.\n" ]
[ 0 ]
[]
[]
[ "python", "tablelayout", "user_interface" ]
stackoverflow_0008290781_python_tablelayout_user_interface.txt
Q: Another absolute import problem I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout: run.py package/ __init__.py logging/ __init__.py ... run.py from package import main main() package/__init...
Another absolute import problem
I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout: run.py package/ __init__.py logging/ __init__.py ... run.py from package import main main() package/__init__.py from __future__ import absolute...
[ "Relative and absolute imports (PEP 328) are not the problem here.\nWhat happens is that when a module in a package is imported, it is implicitly added to this package's namespace. So\nfrom package.logging import Logging\n\nnot only adds 'Logging' to package._dict_, but also adds 'logging' (the newly import local m...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001263474_python.txt
Q: "Invalidate" RabbitMQ queue or sending "DONE signal" I'm using RabbitMQ with Python/pika to distribute some batch jobs. So I think I have a very common scenario: One process fills a queue with jobs to be done. Multiple workers retrieve jobs, transform data and put the results in a second queue. Another single proc...
"Invalidate" RabbitMQ queue or sending "DONE signal"
I'm using RabbitMQ with Python/pika to distribute some batch jobs. So I think I have a very common scenario: One process fills a queue with jobs to be done. Multiple workers retrieve jobs, transform data and put the results in a second queue. Another single process retrives the results and merges them. The works very f...
[ "No, there is no way to find how many publishers are still publishing to a queue in AMQP. You'll have to roll your own system.\nA way to do this would be to have a fanout exchange that every worker binds a queue to (let's call it the \"control\" exchange), and have the publisher send a special message to it when i...
[ 0 ]
[]
[]
[ "python", "rabbitmq" ]
stackoverflow_0008295078_python_rabbitmq.txt
Q: Debugging in pydev - how to make python objects expandable - as in java debugger? Especially standard types like dictionaries and lists - e.g. imagine you have dictionary of dictionaries of lists - then when you go over some variable (in debug) - the debugger will show it as static object.toString() representation...
Debugging in pydev - how to make python objects expandable - as in java debugger?
Especially standard types like dictionaries and lists - e.g. imagine you have dictionary of dictionaries of lists - then when you go over some variable (in debug) - the debugger will show it as static object.toString() representation instead of expandable (clickable) java or c++ debugger representations. This feature s...
[ "In PyDev Variables view supports expandable objects. Expressions View doesn't.\nThere is already feature request for this\nhttp://sourceforge.net/tracker/index.php?func=detail&aid=2947729&group_id=85796&atid=577332\n", "Grab the latest release (PyDev 2.2.4) where this should be fixed.\nAlso, it might be worth no...
[ 1, 1 ]
[]
[]
[ "debugging", "eclipse", "expandable", "pydev", "python" ]
stackoverflow_0008200969_debugging_eclipse_expandable_pydev_python.txt
Q: Remove beep from message dialog I've tried to google it and I've looked in the wxpython docs but I just can't seem to find a way-- can you remove the annoying "error" beep that wx.MessageDialog makes when it pops up (aka when you call .ShowModal())? A: You may try switching to wx.lib.agw.genericmessagedialog and...
Remove beep from message dialog
I've tried to google it and I've looked in the wxpython docs but I just can't seem to find a way-- can you remove the annoying "error" beep that wx.MessageDialog makes when it pops up (aka when you call .ShowModal())?
[ "You may try switching to wx.lib.agw.genericmessagedialog and see if the problem goes away.\n" ]
[ 3 ]
[]
[]
[ "python", "python_2.7", "wxpython", "wxwidgets" ]
stackoverflow_0007250478_python_python_2.7_wxpython_wxwidgets.txt
Q: Is socket error handling different in python 2.5 than 2.7? Below is a code snip with error trace of a python scripted windows service I am running. It seems to work fine in python 2.7 on windows xp but the production machine I am using runs python 2.5 on windows server 2003. The main error I am having is 'error' o...
Is socket error handling different in python 2.5 than 2.7?
Below is a code snip with error trace of a python scripted windows service I am running. It seems to work fine in python 2.7 on windows xp but the production machine I am using runs python 2.5 on windows server 2003. The main error I am having is 'error' object has no attribute 'errno' Am I doing something that is fund...
[ "As explained here, in python 2.6 :\n\nChanged in version 2.6: socket.error is now a child class of IOError.\n\nand the children classes of IOError have a errno member.\nIf you want to get the errno related to your error in python < 2.6, (and assuming that the way described here is valid for raising socket.error) y...
[ 5 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0008296411_error_handling_python.txt
Q: How to create a letter progression for a variable in a loop in Python? I am trying to change a variable (lett) to the next letter in the alphabet on each iteration of a loop. I have to also be able to set this variable at the beginning of the script to a certain letter (and the initial letter will vary depending o...
How to create a letter progression for a variable in a loop in Python?
I am trying to change a variable (lett) to the next letter in the alphabet on each iteration of a loop. I have to also be able to set this variable at the beginning of the script to a certain letter (and the initial letter will vary depending on the use of the script). I started with creating the following bit of code:...
[ "Use itertools.cycle:\nimport itertools\nimport string\nletters = itertools.cycle(string.lowercase)\n\nWith this, letters is an infinite sequence of letters, running from a to z repeatedly. You can use this in a while loop by calling letters.next() or in a for loop by imposing a termination condition in some fashio...
[ 8, 4, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008296736_python.txt
Q: Avoiding having to put DLLs in CWD Is it possible to avoid having to put DLLs in the same directory as the scripts using them? I would like to be able to put a DLL in one place and have it reachable by any script. ctypes.CDLL() seems to only find DLLs if they are in the CWD. Putting them somewhere in sys.path, or ...
Avoiding having to put DLLs in CWD
Is it possible to avoid having to put DLLs in the same directory as the scripts using them? I would like to be able to put a DLL in one place and have it reachable by any script. ctypes.CDLL() seems to only find DLLs if they are in the CWD. Putting them somewhere in sys.path, or in System32 doesn't work. Specifically I...
[ "Try:\npdcurses_path = ctypes.util.find_library('pdcurses.dll')\nif pdcurses_path:\n pdcurses = ctypes.CDLL(pdcurses_path)\nelse:\n raise ImportError(\"could not locate pdcurses.dll library\")\n\n" ]
[ 2 ]
[]
[]
[ "ctypes", "dll", "python", "windows" ]
stackoverflow_0008296802_ctypes_dll_python_windows.txt
Q: sqlalchemy relational mapping Hi I have a simple question - i have 2 tables (addresses and users - user has one address, lot of users can live at the same address)... I created a sqlalchemy mapping like this: when I get my session and try to query something like class Person(object): ''' classdocs ''' idPerso...
sqlalchemy relational mapping
Hi I have a simple question - i have 2 tables (addresses and users - user has one address, lot of users can live at the same address)... I created a sqlalchemy mapping like this: when I get my session and try to query something like class Person(object): ''' classdocs ''' idPerson = Column("idPerson", Integer, pri...
[ "You define a relationship in a wrong place. I think you are mixing Declarative Extension with non-declarative use:\n\nwhen using declarative, you define your relations in your model. \notherwise, you define them when mapping model to a table\n\nIf option-2 is what you are doing, then you need to remove both relat...
[ 3, 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0008294111_orm_python_sqlalchemy.txt
Q: Python, SimPy: Using yield inside functions Helo, I'm building a relatively complex Discrete Event Simulation Model in SimPy. When I try to put my yield statements inside functions, my program doesn't seem to work. Below shows an example. import SimPy.SimulationTrace as Sim import random ## Model components ## cl...
Python, SimPy: Using yield inside functions
Helo, I'm building a relatively complex Discrete Event Simulation Model in SimPy. When I try to put my yield statements inside functions, my program doesn't seem to work. Below shows an example. import SimPy.SimulationTrace as Sim import random ## Model components ## class Customer(Sim.Process): def visit(self): ...
[ "Calling a generator function returns a generator object that can be iterated over. You are simply ignoring this return value, so nothing happens. Instead, you should iterate over the generator and re-yield all values:\nclass Customer(Sim.Process):\n def visit(self):\n yield Sim.hold, self, 2.0\n ...
[ 6, 1 ]
[]
[]
[ "python", "simpy", "simulation" ]
stackoverflow_0008296892_python_simpy_simulation.txt
Q: sqlalchemy: abusing temporary fields I have a data structure that declares relationships like this (pseudocode): class User: ... class Rating: rater = User post = Post class Post: ratings = hasmany(Rating) page_id = ... I'm building a website using these models, and I'd I'm lazy, so I pass my ...
sqlalchemy: abusing temporary fields
I have a data structure that declares relationships like this (pseudocode): class User: ... class Rating: rater = User post = Post class Post: ratings = hasmany(Rating) page_id = ... I'm building a website using these models, and I'd I'm lazy, so I pass my template the current logged in User, and a...
[ "What you are doing is good enough, except that your query is lacking a WHERE clause between the Post and Rating: \n# ...\n.filter(Post.id==Rating.post_id)\\\n\nBut you can also get the result in one query:\nqry = (session.query(Post, Rating).\n outerjoin(Rating, and_(Post.id==Rating.post_id, Rating.user_id...
[ 1, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008292447_python_sqlalchemy.txt
Q: Python/Django: export to MS Project I'm looking for a Python/Django package able to export data (a list of tasks) in MS Project (or OpenProj or similar), but I've not found any. Any hint? A: You may find that MPXJ will help you, although a little effort will be required! MPXJ is a cross-platform library which r...
Python/Django: export to MS Project
I'm looking for a Python/Django package able to export data (a list of tasks) in MS Project (or OpenProj or similar), but I've not found any. Any hint?
[ "You may find that MPXJ will help you, although a little effort will be required!\nMPXJ is a cross-platform library which runs in Java or .Net and provides import and export functionality for a variety of Project file formats. Depending on your target platform you may be able to use facilities such as Jype, Jython,...
[ 2 ]
[]
[]
[ "django", "export", "gantt_chart", "ms_project", "python" ]
stackoverflow_0008295358_django_export_gantt_chart_ms_project_python.txt
Q: python: which file is newer & by how much time I am trying to create a filedate comparison routine. I suspect that the following is a rather clunky approach. I had some difficulty finding info about timedelta's attributes or methods, or whatever they are called; hence, I measured the datetime difference below only...
python: which file is newer & by how much time
I am trying to create a filedate comparison routine. I suspect that the following is a rather clunky approach. I had some difficulty finding info about timedelta's attributes or methods, or whatever they are called; hence, I measured the datetime difference below only in terms of days, minutes and seconds, and there is...
[ "There is a solution for that already:\nimport os\nmodified_time = os.stat(path).st_mtime # time of most recent content modification\ndiff_time = os.stat(path_1).st_mtime - os.stat(path_2).st_mtime\n\nNow you have the time in seconds since Epoch. why are you creating a new representation, you can create a deltatime...
[ 10 ]
[]
[]
[ "comparison", "python", "timedelta" ]
stackoverflow_0008297003_comparison_python_timedelta.txt
Q: Python script causes git publickey error when not run in IDLE On windows 7 64bit have installed Python 2.7, I have no choice over which version to use. I have used IDLE to write a script and when I press F5 to run the script everything works as expected. However, if I double-click the Python file from within explo...
Python script causes git publickey error when not run in IDLE
On windows 7 64bit have installed Python 2.7, I have no choice over which version to use. I have used IDLE to write a script and when I press F5 to run the script everything works as expected. However, if I double-click the Python file from within explorer or use Py2Exe to make it into an executable the script fails. T...
[ "Try to run the python script under cmd,\nmake sure the cmd is running in administrator privileges.\nIf this works, try to run it from the explorer with mouse right click->run as administrator,\nor in the python.exe properties in the Compatibility tab, mark the \"Run this program as an administrator\" checkbox.\n" ...
[ 0 ]
[]
[]
[ "git", "github", "python", "python_idle", "windows" ]
stackoverflow_0008296973_git_github_python_python_idle_windows.txt
Q: It appears I've run out of 32-bit address space. What are my options? I'm trying to take the covariance of a large matrix using numpy.cov. I get the following error: Python(22498,0xa02e3720) malloc: *** mmap(size=1340379136) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_er...
It appears I've run out of 32-bit address space. What are my options?
I'm trying to take the covariance of a large matrix using numpy.cov. I get the following error: Python(22498,0xa02e3720) malloc: *** mmap(size=1340379136) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Process Python bus error It seems that this is not unc...
[ "To be at your place, I would try to \"pickle\" (save) the matrix on my hard drive, close python , then in command line re-open the pickeled file and do my computation on a \"fresh python\" instance.\nI would do that because maybe your problem is before computing the covariance.\nimport cPickle\nimport numpy\nM = n...
[ 1 ]
[]
[]
[ "bigdata", "numpy", "python" ]
stackoverflow_0008284350_bigdata_numpy_python.txt
Q: Python: Google App Engine , JavaScript Channel API to call back end Hi I am quite new to java script and i am looking a working example to call back ends using java script channel API . I do not have any idea about channel API . Can anyone provide me a working example A: If you're asking how to get a message fro...
Python: Google App Engine , JavaScript Channel API to call back end
Hi I am quite new to java script and i am looking a working example to call back ends using java script channel API . I do not have any idea about channel API . Can anyone provide me a working example
[ "If you're asking how to get a message from the backend to a javascript client: you can't send messages from a backend server to a channel created on a frontend server. This is because the app version number is included in the channel token, and backends have a different app version than frontends. You could, howev...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0008292540_google_app_engine_javascript_python.txt
Q: Mapping a class that contains references to another class I have something like this: class A (): [...] class B (): def __init__(self): self.fubar = A() And I would like to store B into a database via SQLAlchemy. I think that I need to define both A and B as two different tables -- mapping all the other...
Mapping a class that contains references to another class
I have something like this: class A (): [...] class B (): def __init__(self): self.fubar = A() And I would like to store B into a database via SQLAlchemy. I think that I need to define both A and B as two different tables -- mapping all the other properties of A and B appropriately. Then, I need to map A to...
[ "You should indeed define two database entities, A and B, and a 1:1 or 1:n relationship between those two:\nBase = declarative_base()\n\nclass A(Base):\n __tablename__ = 'a'\n\n id = Column(Integer, primary_key=True)\n\nclass B(Base):\n __tablename__ = 'b'\n\n id = Column(Integer, primary_key=True)\n ...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008297363_python_sqlalchemy.txt
Q: OOP: getter/setter methods So I've read that you're supposed to access object attributes through getter/setter methods like object.get_this() or object.set_that(value). Does this code hold for methods that are also defined within the class? Or they are only meant to be used with object instances. For instance, is ...
OOP: getter/setter methods
So I've read that you're supposed to access object attributes through getter/setter methods like object.get_this() or object.set_that(value). Does this code hold for methods that are also defined within the class? Or they are only meant to be used with object instances. For instance, is it idiomatic to do it this way, ...
[ "In python do not use getter/setter methods. Instead just access the attribute itself, or, if you need code to be run every time the attribute is accessed or set, use properties.\n", "I wouldn't access attributes of an object in methods of said object by a different way than what I would expect methods from othe...
[ 48, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0008297723_oop_python.txt
Q: IMAP access to Gmail inbox with XOAUTH I'm following the example, I already have authorized my application (=obtained the access token) but trying to access the inbox results in this: 21:14.12 > NDIB1 AUTHENTICATE XOAUTH 21:14.17 < + 21:14.17 write literal size 480 21:14.74 < NDIB1 NO [ALERT] Invalid cred...
IMAP access to Gmail inbox with XOAUTH
I'm following the example, I already have authorized my application (=obtained the access token) but trying to access the inbox results in this: 21:14.12 > NDIB1 AUTHENTICATE XOAUTH 21:14.17 < + 21:14.17 write literal size 480 21:14.74 < NDIB1 NO [ALERT] Invalid credentials (Failure) 21:14.74 NO response: [A...
[ "The example above uses \"anonymous\" for authentication but, you must set \"Consumer Key\" and \"Consumer Secret\" to the values you've already set in \"Manage Domains\" control panel at:\nhttps://accounts.google.com/ManageDomains\nExample:\nconsumer = oauth.Consumer(<OAuth-Consumer-Key>, <OAuth-Consumer-Secret>)\...
[ 2 ]
[]
[]
[ "gmail", "imap", "oauth", "python" ]
stackoverflow_0003755775_gmail_imap_oauth_python.txt
Q: Is it possible to serve a dynamic (with static files) web app in python as a single package with no other dependencies? Lets say you have a friend who knows how to type python run.py according to your instructions (or double click it). Thats it. The friend doesnt know what apache or nginx is, but needs to server t...
Is it possible to serve a dynamic (with static files) web app in python as a single package with no other dependencies?
Lets say you have a friend who knows how to type python run.py according to your instructions (or double click it). Thats it. The friend doesnt know what apache or nginx is, but needs to server the web application for sharing movies/music with me and other friends. Now you want to make a package containing your script...
[ "As long as your user knows how to download things off the web, and can also type \"python setup.py install\", I'm not sure what other obstacles you foresee. On Windows, it can be even simpler if you package your code using python setup.py bdist_wininst. See http://docs.python.org/distutils/builtdist.html#creating-...
[ 0, 0, 0 ]
[]
[]
[ "cherrypy", "flask", "packaging", "python" ]
stackoverflow_0008209748_cherrypy_flask_packaging_python.txt
Q: multiprocessing missing when running image uploading sample code under Windows I try to follow exactly the image uploading code published in http://code.google.com/appengine/docs/python/images/usingimages.html I use the following app.yaml file application: jstock-webapp version: 1 runtime: python api_version: 1 h...
multiprocessing missing when running image uploading sample code under Windows
I try to follow exactly the image uploading code published in http://code.google.com/appengine/docs/python/images/usingimages.html I use the following app.yaml file application: jstock-webapp version: 1 runtime: python api_version: 1 handlers: - url: /* script: upload.py - url: /sign script: upload.py - url: /img ...
[ "The problem occurs when you try to import _multiprocessing, not multiprocessing.\nSee this thread for a variety of workarounds, foremost of which is to use Python 2.5 instead of 2.6. Better yet, install Python 2.7 and update your app to target it.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008283805_google_app_engine_python.txt
Q: Python Server Pages, Session Timeout Set Real easy one for those Python Server Pages guru's <% user_session = Session.Session(req) user_session['username'] = varUsername user_session['fullname'] = varFullName %> The Session seems to timeout after a short amount of time. How can I set the Session timeout to be 1 h...
Python Server Pages, Session Timeout Set
Real easy one for those Python Server Pages guru's <% user_session = Session.Session(req) user_session['username'] = varUsername user_session['fullname'] = varFullName %> The Session seems to timeout after a short amount of time. How can I set the Session timeout to be 1 hour? Additions: This is not a server session ...
[ "user_session.set_timeout(3600)\n\nWorks for me.\n" ]
[ 0 ]
[]
[]
[ "http", "mod_python", "python", "session_timeout" ]
stackoverflow_0006683313_http_mod_python_python_session_timeout.txt
Q: Simple beginner stuff, multiple conditional test ok, this seems like it should be really simple but Im a bit confused: i have two values - domain and ip its best described with code: whois_result = Popen(['whois', str(domain)], stdout=PIPE,stderr=STDOUT).communicate()[0] debug_output(whois_result) ...
Simple beginner stuff, multiple conditional test
ok, this seems like it should be really simple but Im a bit confused: i have two values - domain and ip its best described with code: whois_result = Popen(['whois', str(domain)], stdout=PIPE,stderr=STDOUT).communicate()[0] debug_output(whois_result) if 'Not found' or 'No entries' in whois_result...
[ "Try this\ndef do_whois(data):\n if data: return Popen(['whois', str(data)], stdout=PIPE,stderr=STDOUT).communicate()[0]\n return 'No entries'\n\ndef check_whois(data):\n if 'No entries' in data or 'Not found' in data:return False\n test = re.search(\"country.+([A-Z].)\",whois_result)\n return test.g...
[ 1, 0, 0 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0008298043_conditional_python.txt
Q: Django MEDIA_URL with CDN and Admin media I'm using, in a Django 1.3 project, a CDN for media resources like images, css and such. I have a problem serving admin resources, what I made is: In settings.py: MEDIA_URL = 'http://cdn.test.com/' ADMIN_MEDIA_PREFIX = '/admin_media/' In INSTALLED_APPS: 'django.contrib.s...
Django MEDIA_URL with CDN and Admin media
I'm using, in a Django 1.3 project, a CDN for media resources like images, css and such. I have a problem serving admin resources, what I made is: In settings.py: MEDIA_URL = 'http://cdn.test.com/' ADMIN_MEDIA_PREFIX = '/admin_media/' In INSTALLED_APPS: 'django.contrib.staticfiles', And in urls.py: (r'^admin_media/(...
[ "Try the following:\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n\n # (... other urls ...)\n)\nurlpatterns += staticfiles_urlpatterns()\n\nAlso, the docum...
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0008267085_django_django_admin_python.txt
Q: Python:Drop down menu I have create in wxPython this drop-down menu: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() ...
Python:Drop down menu
I have create in wxPython this drop-down menu: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() fileMenu.Append(wx.ID_...
[ "I belive it is outside the \"spirit\" of a cross-platform UI library to change the operating systems UI behaviour.\nIn most operating systems, menus won't automatically pop up on mouse over, so wxWindows doesn't do that either.\nThere might be a way to assing a mouseover listener to the menu, and have it automatic...
[ 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008287055_python_wxpython.txt
Q: send_mass_mail in background django I am using send_mass_email to send emails to a list of users. It is working fine until I send it to more than 200 emails at a time. Actually emails are being delivered without a problem. But I am getting time-out error from nginx because it takes long( more than 2 mins) to send ...
send_mass_mail in background django
I am using send_mass_email to send emails to a list of users. It is working fine until I send it to more than 200 emails at a time. Actually emails are being delivered without a problem. But I am getting time-out error from nginx because it takes long( more than 2 mins) to send emails to all 200+ emails. What is the be...
[ "You need to move the tasks to the background (so they don't block the web process). One of the most popular ways to do this is to use a messaging/task queue.\nCelery is one of the most popular distributed task queues, and coupled with the django-celery application makes this trivial.\nFirst you need to setup celer...
[ 3, 3, 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0008295013_django_django_forms_django_models_python.txt
Q: Inserting a row at a specific location in a 2d array in numpy? I have a 2d array in numpy where I want to insert a new row. Following question Numpy - add row to array can help. We can use numpy.vstack, but it stacks at the start or at the end. Can anyone please help in this regard. A: You are probably looking f...
Inserting a row at a specific location in a 2d array in numpy?
I have a 2d array in numpy where I want to insert a new row. Following question Numpy - add row to array can help. We can use numpy.vstack, but it stacks at the start or at the end. Can anyone please help in this regard.
[ "You are probably looking for numpy.insert\n>>> import numpy as np\n>>> a = np.zeros((2, 2))\n>>> a\narray([[ 0., 0.],\n [ 0., 0.]])\n# In the following line 1 is the index before which to insert, 0 is the axis.\n>>> np.insert(a, 1, np.array((1, 1)), 0) \narray([[ 0., 0.],\n [ 1., 1.],\n [ 0....
[ 71 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008298797_numpy_python.txt
Q: Specialized Text Console in wxPython Is there any way that I can build an interactive text console using wxPython window application? It will be used to allow user to provide natural language input for the application to parse the grammar based on the language selected. It is not going to be used to run any shell ...
Specialized Text Console in wxPython
Is there any way that I can build an interactive text console using wxPython window application? It will be used to allow user to provide natural language input for the application to parse the grammar based on the language selected. It is not going to be used to run any shell or commands.
[ "You can use a wx.TextCtrl for input and then when the user is done typing, you can have them press a button to do whatever checking you want done. Alternatively, you could use a wx.Timer to watch for idleness so when the user is idle for x seconds, it does the checking you want automatically too.\n" ]
[ 0 ]
[]
[]
[ "console", "python", "user_interface", "wxpython" ]
stackoverflow_0008280667_console_python_user_interface_wxpython.txt
Q: adding edges by using networkx functions I'm trouble with making graph by networkx. I'm trying to add edges but my code doesn't work. I followed the way suggested by tutorial from http://networkx.lanl.gov/. Is there any help on my code? G.nodes() and G.edges() didn't print out anything. import networkx as nx fh =...
adding edges by using networkx functions
I'm trouble with making graph by networkx. I'm trying to add edges but my code doesn't work. I followed the way suggested by tutorial from http://networkx.lanl.gov/. Is there any help on my code? G.nodes() and G.edges() didn't print out anything. import networkx as nx fh = open("internal_link.txt", 'rb') G = nx.parse_...
[ "By using delimiter='\\t' and '\\n', you are telling NetworkX that you want the lines from fh split on the result of '\\t' and '\\n', which is just '\\n'. Since '\\n' is used to separate lines, no line will contain '\\n' and there will thus be only one token per line, giving no valid edges. \nThe sample data shows ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008296718_python.txt
Q: Can't get pythonXY to work on my laptop I'm migrating from Matlab to python so i decided to try the pythonxy distribution, but after installation i can't open it. When i double click on icon nothing happens. i already try to submite a issue on pythonxy page but didn't get any answer. Does anyone knows what this ...
Can't get pythonXY to work on my laptop
I'm migrating from Matlab to python so i decided to try the pythonxy distribution, but after installation i can't open it. When i double click on icon nothing happens. i already try to submite a issue on pythonxy page but didn't get any answer. Does anyone knows what this problem could be? I'm using Win7 x64 this is ...
[ "This is a known bug in pythonxy: http://code.google.com/p/pythonxy/issues/detail?id=146\nThe problem is that your home path contains non-ASCII characters; you would probably have to run it from a user without non-ASCII chars in the home path to make it work for now, while there are patches in the bug report commen...
[ 2, 0 ]
[]
[]
[ "python", "pythonxy", "windows_7" ]
stackoverflow_0008295987_python_pythonxy_windows_7.txt
Q: Draggable legend with multiple axes problem I’m wondering if anyone has a solution for a problem I’m having when using a draggable legend in conjunction with multiple axes. I’m using gridspec and figure (matplotlib 1.0.1, qt4 backend) to create 2 axes – no pyplot. When the legend is dragged from one axes to the o...
Draggable legend with multiple axes problem
I’m wondering if anyone has a solution for a problem I’m having when using a draggable legend in conjunction with multiple axes. I’m using gridspec and figure (matplotlib 1.0.1, qt4 backend) to create 2 axes – no pyplot. When the legend is dragged from one axes to the other and released, its draggability ceases to wor...
[ "I reproduced the problem. The part of the legend that enters the alien figure becomes unclickable, as if the figure would be catching the mouse position events and not resending them to other handlers.\nThe minimal code that reproduces the problem (to experiment with ipython -pylab) is:\nIn [16]: f211 = plt.subplo...
[ 0 ]
[]
[]
[ "legend", "matplotlib", "python", "qt4" ]
stackoverflow_0005424145_legend_matplotlib_python_qt4.txt
Q: Adding removed tabs in QTabWidget (PyQT) I'm facing an issue with pyQT. So I created a graphical interface with designer, containing a QTabWidget. The things is I would like to hide and show tabs when my function is running. I found one solution that consists in removing all the tabs and adding them later. Lets sa...
Adding removed tabs in QTabWidget (PyQT)
I'm facing an issue with pyQT. So I created a graphical interface with designer, containing a QTabWidget. The things is I would like to hide and show tabs when my function is running. I found one solution that consists in removing all the tabs and adding them later. Lets say I only have two tabs : removedTab = self._a...
[ "You can declare all the tabs you need in your mainwindow object or whatever widget you have:\nEx.:\nself.tab = QtGui.QWidget()\nself.tab.setObjectName(_fromUtf8(\"tab\"))\n\nAnd you can assign the widgets to your tabs normally even if you didn't call the addTab() method yet.\nEx.:\nself.lineEdit = QtGui.QLineEdit(...
[ 2 ]
[]
[]
[ "pyqt", "python", "qt", "qtabwidget" ]
stackoverflow_0008298582_pyqt_python_qt_qtabwidget.txt
Q: Show another window wxpython? I have been looking around the Internet but I am not sure if there is a way to show 2 classes in wxPython in 2 separate windows. And could we communicate between them (like one class being the dialog and the other the main class)? I think I did this before using Show() but I am not su...
Show another window wxpython?
I have been looking around the Internet but I am not sure if there is a way to show 2 classes in wxPython in 2 separate windows. And could we communicate between them (like one class being the dialog and the other the main class)? I think I did this before using Show() but I am not sure how to repeat this. So basically...
[ "Here you have a simple example of two frames communicating:\n\nThe trick is in sending an object reference to share between frames, either creating one inside the other (as in this case) or through a common parent.\nThe code is:\nimport wx\n\nclass MainFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__...
[ 7, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008263513_python_wxpython.txt
Q: Python: how to deal with several .pyd dependencies with the same name? I have in my python workspace two Modules which need sip.pyd Module1.pyd needs sip.pyd (which implements v 8.0-8.1) Module2.pyd needs sip.pyd (another file, that implements v6.0) So I can't just choose the newer one, it doesn't work: I have to ...
Python: how to deal with several .pyd dependencies with the same name?
I have in my python workspace two Modules which need sip.pyd Module1.pyd needs sip.pyd (which implements v 8.0-8.1) Module2.pyd needs sip.pyd (another file, that implements v6.0) So I can't just choose the newer one, it doesn't work: I have to keep them both! (RuntimeError: the sip module implements API v6.0 but the fb...
[ "VirtualEnv is done to handle those case.\n\nvirtualenv is a tool to create isolated Python environments.\n\nUsing virtualenv, you will be able to create 2 environements, one with the sip.pyd in version 8.x another in version 6.0\n", "Assuming you don't have a piece of code needing both files at once. I'd recomme...
[ 1, 1, 0 ]
[]
[]
[ "dependencies", "import", "pyd", "python", "python_sip" ]
stackoverflow_0008298978_dependencies_import_pyd_python_python_sip.txt
Q: How to put the axis for two subplots separately? I am trying to have two sub-plots in the figure in the Python Script. But I am not able to set the axis separately according to my inputs. Can anybody help me to set the x-axis, y-axis for each of the sub-plot separately? I am including the piece of code that I...
How to put the axis for two subplots separately?
I am trying to have two sub-plots in the figure in the Python Script. But I am not able to set the axis separately according to my inputs. Can anybody help me to set the x-axis, y-axis for each of the sub-plot separately? I am including the piece of code that I have done, which was not giving me the result. fig = ...
[ "You can set independent scales very easily (from an ipython -pylab session):\nIn [8]: ax = plt.subplot(121)\nIn [9]: ay = plt.subplot(122)\nIn [10]: ax.set_xlim((-1,2))\nIn [11]: ax.set_ylim((10,20))\nIn [12]: ay.set_xlim((-10,4))\nIn [13]: ay.set_ylim((3,5))\n\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "scale" ]
stackoverflow_0004895455_matplotlib_python_scale.txt
Q: How to add an item at the last nested list of an outer list in python? Is thery any nice compact way of adding an item to the last nested list of an outer list. I.e: a=[1,2,[3,4,[5,6]]] and after the insertion of 7 i want my list to become a=[1,2,[3,4,[5,6,7]]] A: You can use indexing to reference the last inner...
How to add an item at the last nested list of an outer list in python?
Is thery any nice compact way of adding an item to the last nested list of an outer list. I.e: a=[1,2,[3,4,[5,6]]] and after the insertion of 7 i want my list to become a=[1,2,[3,4,[5,6,7]]]
[ "You can use indexing to reference the last inner list:\n>>> a=[1,2,[3,4,[5,6]]]\n>>> a[2][2].append(7)\n>>> a\n[1, 2, [3, 4, [5, 6, 7]]]\n\nOr you can write a function to seek out the last inner list:\n>>> def findlastlist(s):\n while s and isinstance(s[-1], list):\n s = s[-1]\n return s\n\n>>> a=[1,2...
[ 9, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008299414_python.txt
Q: Run Firefox in Backend using Selenium webdriver in Python I am working on a website scraping project using Selenium in Python. I am wondering if I can start the firefox in the backend or open Firefox in another workspace in Ubuntu ? Is it also possible to pass the user-agent properties though the webdriver() ? Tha...
Run Firefox in Backend using Selenium webdriver in Python
I am working on a website scraping project using Selenium in Python. I am wondering if I can start the firefox in the backend or open Firefox in another workspace in Ubuntu ? Is it also possible to pass the user-agent properties though the webdriver() ? Thanks
[ "PyVirtualDisplay should let you run it in the background.\nThere's a short walkthough here.\nAnd yes, you can change the User Agent.\n", "If you're using Gnome you might want to try DevilsPie (or gDevilsPie) to control on which workspace Firefox runs:\nA simple RAW rule would be:\n( if \n( begin \n( is ( applica...
[ 3, 1 ]
[]
[]
[ "python", "selenium", "user_agent", "web_scraping", "webdriver" ]
stackoverflow_0008298360_python_selenium_user_agent_web_scraping_webdriver.txt
Q: Could someone give me their two cents on this optimization strategy Background: I am writing a matching script in python that will match records of a transaction in one database to names of customers in another database. The complexity is that names are not unique and can be represented multiple different ways fro...
Could someone give me their two cents on this optimization strategy
Background: I am writing a matching script in python that will match records of a transaction in one database to names of customers in another database. The complexity is that names are not unique and can be represented multiple different ways from transaction to transaction. Rather than doing multiple queries on the d...
[ "Regarding: \"would this be faster:\"\nThe behind-the-scenes logistics of the SQL engine are really optimized for this sort of thing. You might need to create an SQL PROCEDURE or a fairly complex query, however.\nCaveat, if you're not particularly good at or fond of maintaining SQL, and this isn't a time-sensitive ...
[ 2, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0008299614_mysql_python.txt
Q: How to change the attachment name? I am working on a function that sends emails with an attachment in PYTHON. In order to attach the file, I have to put it with the complete URL from the server, but the name of the file includes the hole URL. How can extrac only the filename from the URL. I get the file from this ...
How to change the attachment name?
I am working on a function that sends emails with an attachment in PYTHON. In order to attach the file, I have to put it with the complete URL from the server, but the name of the file includes the hole URL. How can extrac only the filename from the URL. I get the file from this URL: /var/www/RH/HV/FILE.doc And I want ...
[ "Use os.path.basename():\nimport os.path\n\np = '/var/www/RH/HV/FILE.doc'\nprint os.path.basename(p)\n\nThis assumes you're working with normal file paths, not URLs. But based on the question it looks like you're not looking at URLs.\n" ]
[ 2 ]
[]
[]
[ "html", "python", "sendmail" ]
stackoverflow_0008299888_html_python_sendmail.txt
Q: proxy and retries for getaddrbyhost This function keeps failing me, am I doing this right ? Is there another way to get a domain from an IP address? def ip_to_domain(ip): for i in range(0,4): try: domain = socket.gethostbyaddr(str(ip)) retur...
proxy and retries for getaddrbyhost
This function keeps failing me, am I doing this right ? Is there another way to get a domain from an IP address? def ip_to_domain(ip): for i in range(0,4): try: domain = socket.gethostbyaddr(str(ip)) return domain except IOError: ...
[ "You also need to trap socket.herror... Use something like this and check whether you get a None value in the relevant field...\nimport socket\ndef lookup(addr):\n \"\"\"\n Example usage:\n name, alias, addresslist = lookup('4.2.2.2')\n \"\"\"\n try:\n return socket.gethostbyaddr(addr)\n ex...
[ 0 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0008295810_proxy_python.txt
Q: In twisted how can I make a mixed protocol which returns Lines or Raw based on input? I am trying to develop a mixed protocol which can return a raw response or a Line Based response based on the request. My code looks like class Receiver(LineReceiver): def lineReceived(self, line): (command, args) = self._p...
In twisted how can I make a mixed protocol which returns Lines or Raw based on input?
I am trying to develop a mixed protocol which can return a raw response or a Line Based response based on the request. My code looks like class Receiver(LineReceiver): def lineReceived(self, line): (command, args) = self._parse_command(line) result = self.exec_command(command, args) #Secret sauce returns list...
[ "The transport.write call will send the data to the client. If the client is poorly written, it may lose it because the connection closes immediately after the data is sent. There are many other possible ways the client could fail, too, but there's no way to know what's actually happening since the client code is...
[ 1 ]
[]
[]
[ "network_programming", "python", "twisted" ]
stackoverflow_0008298177_network_programming_python_twisted.txt
Q: calling a function from another function in python I have written this function that takes to strings in order to see if they are anagrams: def anagram_check(str_x, str_y): x = string1.replace(" ","") y = string2.replace(" ","") lower1 = x.lower() lower2 = y.lower() sorted1 = sorted(lower1) ...
calling a function from another function in python
I have written this function that takes to strings in order to see if they are anagrams: def anagram_check(str_x, str_y): x = string1.replace(" ","") y = string2.replace(" ","") lower1 = x.lower() lower2 = y.lower() sorted1 = sorted(lower1) sorted2 = sorted(lower2) if sorted1 == sorted2: ...
[ "As you say, your anagram_check() function works correctly. However, for this problem a more useful function would be one that converts the given word into its \"canonical\" form, such that two anagrams would have the same canonical form.\nOne such function is:\ndef canonical(word):\n return ''.join(sorted(word.lo...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008299612_python.txt
Q: Vectorization of this Numpy double loop How can I vectorize the following double-loop? I have one N by A matrix and one N by B matrix, where A and B may differ and N is much smaller than A and B. I want to produce an A by B matrix as follows, but ideally without the loops: import numpy as np def foo(arr): # c...
Vectorization of this Numpy double loop
How can I vectorize the following double-loop? I have one N by A matrix and one N by B matrix, where A and B may differ and N is much smaller than A and B. I want to produce an A by B matrix as follows, but ideally without the loops: import numpy as np def foo(arr): # can be anything - just an example so that the ...
[ "First vectorise foo(), i.e. modify foo() in a way that it can correctly operate on an array of shape (N, A, B), returning an array of shape (A, B). This step is usually the difficult one. How this is done entirely depends on what foo() does. For the given example, it's very easy to do:\ndef foo(arr):\n retur...
[ 10 ]
[]
[]
[ "linear_algebra", "numpy", "python" ]
stackoverflow_0008299891_linear_algebra_numpy_python.txt
Q: How to return from function if got stuck for 90 seconds? Possible Duplicate: Timeout on a Python function call I want to implement that when the function took more than 90 seconds to complete it should return immediately when timeout. Is there any way to achieve that? def abc(string): import re if re.mat...
How to return from function if got stuck for 90 seconds?
Possible Duplicate: Timeout on a Python function call I want to implement that when the function took more than 90 seconds to complete it should return immediately when timeout. Is there any way to achieve that? def abc(string): import re if re.match('some_pattern', string): return True else: ...
[ "I've edited my post to use jcollado's idea which is simpler.\nThe multiprocessing.Process.join method has a timeout argument which you can use like this:\nimport multiprocessing as mp\nimport time\nimport logging \nimport re\n\nlogger = logging.getLogger(__name__)\n\ndef abc(string, result, wait = 0):\n time.s...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008299131_python.txt
Q: PyLucene Custom TokenStream using PythonTokenStream I am attempting to build a TokenStream from a Python Sequence. Just for fun I want to be able to pass my own Tokens directly to pylucene.Field("MyField", MyTokenStream) I tried to make "MyTokenStream" by... terms = ['pant', 'on', 'ground', 'look', 'like', 'fool...
PyLucene Custom TokenStream using PythonTokenStream
I am attempting to build a TokenStream from a Python Sequence. Just for fun I want to be able to pass my own Tokens directly to pylucene.Field("MyField", MyTokenStream) I tried to make "MyTokenStream" by... terms = ['pant', 'on', 'ground', 'look', 'like', 'fool'] stream = pylucene.PythonTokenStream() for t in terms: ...
[ "The Python* classes are designed to customize behavior by subclassing. In the case of TokenStream, the incrementToken method needs to be overridden.\nclass MyTokenStream(lucene.PythonTokenStream):\n def __init__(self, terms):\n lucene.PythonTokenStream.__init__(self)\n self.terms = iter(terms)\n ...
[ 3 ]
[]
[]
[ "lucene", "pylucene", "python" ]
stackoverflow_0008114545_lucene_pylucene_python.txt
Q: Get first N key pairs from an Ordered Dictionary to another one I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary? For example: I have something like this: dictionary={'a':10,'b':20,'c':30,'d':5} ordered=OrderedDict(sorted(diction...
Get first N key pairs from an Ordered Dictionary to another one
I have an ordered dictionary (OrderedDict) sorted by value. How can I get the top (say 25) key values and add them to a new dictionary? For example: I have something like this: dictionary={'a':10,'b':20,'c':30,'d':5} ordered=OrderedDict(sorted(dictionary.items(), key=lambda x: x[1],reverse=True)) Now ordered is an ord...
[ "The primary purpose of collections.OrderedDict is retaining the order in which the elements were inserted.\nWhat you want here is collections.Counter, which has the n-most-frequent functionality built-in:\n>>> dictionary={'a':10,'b':20,'c':30,'d':5}\n>>> import collections\n>>> collections.Counter(dictionary).most...
[ 16, 6, 3, 1 ]
[]
[]
[ "dictionary", "ordereddictionary", "python" ]
stackoverflow_0008287000_dictionary_ordereddictionary_python.txt
Q: capturing stdout from python in an upstart job I'm struggling to save the stdout output of a python2.6 script into a file when I run it as an upstart job. This is my current test script: #!/usr/bin/python from time import sleep import sys while 1: print "Hello from stdout" print >> sys.stderr, "Hello from...
capturing stdout from python in an upstart job
I'm struggling to save the stdout output of a python2.6 script into a file when I run it as an upstart job. This is my current test script: #!/usr/bin/python from time import sleep import sys while 1: print "Hello from stdout" print >> sys.stderr, "Hello from stderr" sleep(1) if I do $ myscript >> /var/lo...
[ "Buffering and flushing would be the guess.\nstderr is typically an unbuffered stream while stdout is buffered. When you send it to a file it will be buffered in 4k chunks (typically).\nIf you make the following change:\nwhile 1:\n print \"hello from stdout\"\n sys.stdout.flush()\n print >> sys.stderr, \"...
[ 3 ]
[]
[]
[ "python", "stdout", "upstart" ]
stackoverflow_0008300209_python_stdout_upstart.txt
Q: Python split '123' into '1', '2', '3' My program takes a user input such as: >>> x = input() >>> 1 >>> print x >>> one my actual code: >>> import string >>> numbers = ['0','1','2','3','4','5','6','7','8','9'] >>> wordNumbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] >>> my...
Python split '123' into '1', '2', '3'
My program takes a user input such as: >>> x = input() >>> 1 >>> print x >>> one my actual code: >>> import string >>> numbers = ['0','1','2','3','4','5','6','7','8','9'] >>> wordNumbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] >>> myDict = dict(zip(numbers, wordNumbers)) >>> ...
[ "You simply need to use:\nfor translate in myVar:\n\nInstead of:\nfor translate in myVar.split():\n\nIterating over a string gives you its characters one by one, which is what you need.\nIf you do want to convert '123' to '1 2 3' (which isn't needed here because you don't need to use split), you can use:\n' '.join(...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0008300235_python.txt
Q: Keyboard input using stdio.StandardIO in twisted python I have a doubt in twisted python related to my multiclient chat server program. that is, when we give input from keyboard using stdio.StandardIO, where it is stored when we run the reactor? Can anybody give me the answer, please.. A: twisted.internet.stdio...
Keyboard input using stdio.StandardIO in twisted python
I have a doubt in twisted python related to my multiclient chat server program. that is, when we give input from keyboard using stdio.StandardIO, where it is stored when we run the reactor? Can anybody give me the answer, please..
[ "twisted.internet.stdio.StandardIO doesn't \"store\" data anywhere. It is a transport which you associate with a protocol. The protocol you associate with it can do anything you want with the data delivered to it.\nYou can find two examples of using StandardIO in the Twisted documentation, https://twistedmatrix.c...
[ 7 ]
[]
[]
[ "keyboard_input", "python", "twisted" ]
stackoverflow_0008299896_keyboard_input_python_twisted.txt
Q: Using "from __future__ import division" in my program, but it isn't loaded with my program I wrote the following program in Python 2 to do Newton's method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with %run -i NewtonsMetho...
Using "from __future__ import division" in my program, but it isn't loaded with my program
I wrote the following program in Python 2 to do Newton's method computations for my math problem set, and while it works perfectly, for reasons unbeknownst to me, when I initially load it in ipython with %run -i NewtonsMethodMultivariate.py, the Python 3 division is not imported. I know this because after I load my Pyt...
[ "Both ipython -i command and run -i in ipython interpreter ignore from __future__ import division in print05.py script.\n$ cat print05.py \nfrom __future__ import division\nprint(1/2)\n\nIn ipython console:\nIn [1]: print 1/2\n0\nIn [2]: run -i print05.py\n0.5\nIn [3]: division\nOut[3]: _Feature((2, 2, 0, 'alpha', ...
[ 12, 0 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0008290636_python_sympy.txt
Q: sendmail with HTML message I am programming with Python. I already have a function that sends an email with a message and an attachment....My only problem is that I want the message to be HTML, but mine does not respect that..... Here is the function that I'm using def enviarCorreo(fromaddr, toaddr, text, file): ...
sendmail with HTML message
I am programming with Python. I already have a function that sends an email with a message and an attachment....My only problem is that I want the message to be HTML, but mine does not respect that..... Here is the function that I'm using def enviarCorreo(fromaddr, toaddr, text, file): msg = MIMEMultipart('mixed') ...
[ "replace\nmsg.attach(MIMEText(text))\n\nby\nmsg.attach(MIMEText(text, 'html'))\n\n(default is 'plain')\n", "There is an example on the official documentation page that sends HTML email - http://docs.python.org/library/email-examples.html\n" ]
[ 5, 2 ]
[]
[]
[ "html", "mime_message", "mime_types", "python", "sendmail" ]
stackoverflow_0008300860_html_mime_message_mime_types_python_sendmail.txt
Q: python - string template - different values for same key I have an SQL template where I need to substitute random UUIDs. from string import Template import uuid def gen_uuid(): return str(uuid.uuid4()) s = """ insert ... values('foo', ${uuid}); insert ... values('bar', ${uuid}); insert ... values('baz', ${uu...
python - string template - different values for same key
I have an SQL template where I need to substitute random UUIDs. from string import Template import uuid def gen_uuid(): return str(uuid.uuid4()) s = """ insert ... values('foo', ${uuid}); insert ... values('bar', ${uuid}); insert ... values('baz', ${uuid}); """ mappings = { "uuid": gen_uuid # how?? } templ...
[ "The first problem is you're not passing the result of gen_uuid to the template, you're referencing the function object itself. It should be:\nmappings = {\n \"uuid\": gen_uuid()\n}\n\nWith your current approach the gen_uuid function will only be evaluated once, so the same value will be used for each statement....
[ 1, 1, 1 ]
[]
[]
[ "python", "template_engine" ]
stackoverflow_0008300644_python_template_engine.txt
Q: Attribute added with setattr not showing up in help() I've got a class that I'm adding a help-function to with setattr. The function is a properly created instancemethod and works like a charm. import new def add_helpfunc(obj): def helpfunc(self): """Nice readable docstring""" #code setat...
Attribute added with setattr not showing up in help()
I've got a class that I'm adding a help-function to with setattr. The function is a properly created instancemethod and works like a charm. import new def add_helpfunc(obj): def helpfunc(self): """Nice readable docstring""" #code setattr(obj, "helpfunc", new.instancemethod(helpfun...
[ "I there a specific reason you do it the complicate way? Why not just doing it like this:\ndef add_helpfunc(obj):\n def helpfunc(self):\n \"\"\"Nice readable docstring\"\"\"\n #code\n\n obj.helpfunc = helpfunc\n\nAdding the method this way also fixes your help-problem if I am not wrong...\nExamp...
[ 2 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0008300808_python_reflection.txt
Q: how do I execute a 'GRANT SELECT ON' statement using pyodbc I am working with hundreds of msaccess databases. I am trying to build a summary of databases, tables and other objects. To find out all the tables and objects in a given database, I use the query select * from MSysObjects However, I get the pyodbc error...
how do I execute a 'GRANT SELECT ON' statement using pyodbc
I am working with hundreds of msaccess databases. I am trying to build a summary of databases, tables and other objects. To find out all the tables and objects in a given database, I use the query select * from MSysObjects However, I get the pyodbc error message [Microsoft][ODBC Microsoft Access Driver] Record(s) cann...
[ "Try using the tables and columns methods of the cursor. I am unable to test against Access 2003 or 2007, but the following works with Access 2010:\nimport pyodbc\nconnection = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Username\\Desktop\\Database.accdb;')\ncursor = connection....
[ 2 ]
[]
[]
[ "ms_access", "pyodbc", "python", "sql_grant" ]
stackoverflow_0008247991_ms_access_pyodbc_python_sql_grant.txt
Q: Converting sentences in a file to word tokens in a list I'm using python to convert the words in sentences in a text file to individual tokens in a list for the purpose of counting up word frequencies. I'm having trouble converting the different sentences into a single list. Here's what I do: f = open('music.txt',...
Converting sentences in a file to word tokens in a list
I'm using python to convert the words in sentences in a text file to individual tokens in a list for the purpose of counting up word frequencies. I'm having trouble converting the different sentences into a single list. Here's what I do: f = open('music.txt', 'r') sent = [word.lower().split() for word in f] That gives...
[ "Just use a nested loop inside the list comprehension:\nsent = [word for line in f for word in line.lower().split()]\n\nThere are some alternatives to this approach, for example using itertools.chain.from_iterable(), but I think the nested loop is much easier in this case.\n", "Just read the entire file to memory...
[ 5, 1, 0 ]
[]
[]
[ "file", "list_comprehension", "python" ]
stackoverflow_0008301302_file_list_comprehension_python.txt
Q: Image in the HTML email message I am working with a Python function that sends mails wich include an attachment and a HTML message......I want to add an image on the HTML message using <img src="XXXX"> When I try it, the message respects the tag, but does not display the image I want (it displays the not found im...
Image in the HTML email message
I am working with a Python function that sends mails wich include an attachment and a HTML message......I want to add an image on the HTML message using <img src="XXXX"> When I try it, the message respects the tag, but does not display the image I want (it displays the not found image "X")..... does anyone know if thi...
[ "In your html you need the fully qualified path to the image: http://yourdomain.com/images/image.jpg\nYou should be able to take the URL in the image tag, paste it into the browser's address bar and view it there. If you can't see it, you've got the wrong path.\n", "You need to write src=\"cid:ContentId\" to refe...
[ 1, 1 ]
[]
[]
[ "html", "mime_message", "mime_types", "python", "sendmail" ]
stackoverflow_0008301501_html_mime_message_mime_types_python_sendmail.txt
Q: Python - Output creating blank spaces I'm encountering a very strange issue in a python script I've written. This is the piece of code that is producing abnormal results: EDIT: I've included the entire loop in the code segment now. data = open(datafile,'r') outERROR = open(outERRORfile,'w') precision=[0] scale=[0]...
Python - Output creating blank spaces
I'm encountering a very strange issue in a python script I've written. This is the piece of code that is producing abnormal results: EDIT: I've included the entire loop in the code segment now. data = open(datafile,'r') outERROR = open(outERRORfile,'w') precision=[0] scale=[0] lines = data.readlines() limit = 0 if file...
[ "At a guess, perhaps you have control characters in the input stream that cause some unexpected behaviour. No sure exactly what outERROR is in the above context, but you can imagine, for example, that a form feed character in the input could have this sort of effect.\nTry cleaning the data of non-printable characte...
[ 1 ]
[ "Call open with 'rb' and 'wb' to ensure binary mode, otherwise the data can be altered by the system trying to mess with line endings\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0008301240_python.txt
Q: Python 2.7 'NoneType' object has no attribute I am new to Python and working with a set of objects (Node) and just trying to iterate over the set of objects and printout the variable 'H'. Unfortunately I keep getting the error: ("AttributeError: 'NoneType' object has no attribute 'H'"). Any insight as to why this ...
Python 2.7 'NoneType' object has no attribute
I am new to Python and working with a set of objects (Node) and just trying to iterate over the set of objects and printout the variable 'H'. Unfortunately I keep getting the error: ("AttributeError: 'NoneType' object has no attribute 'H'"). Any insight as to why this is happening would be greatly appreciated. Here is ...
[ "The error \"AttributeError: 'NoneType' object has no attribute 'H'\" means that one of the Nodes in open_list is being assigned the value 'None' instead of being initialized. Does anything happen to open_list between the lines you show and the line with an error? \n" ]
[ 3 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0008301486_ironpython_python.txt
Q: PYTHON | stop user killing process A very cool function was mentioned here: Prevent user process from being killed with "End Process" from Process Explorer Does anyone know how to translate this C++ code to Python (or re-edit it so that it at least compiles in C/C++, assuming that is what it is in): static const b...
PYTHON | stop user killing process
A very cool function was mentioned here: Prevent user process from being killed with "End Process" from Process Explorer Does anyone know how to translate this C++ code to Python (or re-edit it so that it at least compiles in C/C++, assuming that is what it is in): static const bool ProtectProcess() { HANDLE hProce...
[ "Here is a rather crude ctypes translation of the code you posted. It even appears to work! Note that I remove the call to CloseHandle which is simply wrong. You should not call CloseHandle on a pseudo-handle, which is what GetCurrentProcess returns.\nfrom ctypes import *\nfrom ctypes.wintypes import *\nfrom win32c...
[ 2, 1 ]
[]
[]
[ "process_management", "python" ]
stackoverflow_0008296309_process_management_python.txt
Q: Looking for a good replacement for Psyco (Python->C compiler) We really like Psyco to speed things up, but it also has some drawbacks: it consumes too much memory it can also slow some code down compiling your code can take too much time it doesn't support 64-bit systems What would be good alternatives (Django s...
Looking for a good replacement for Psyco (Python->C compiler)
We really like Psyco to speed things up, but it also has some drawbacks: it consumes too much memory it can also slow some code down compiling your code can take too much time it doesn't support 64-bit systems What would be good alternatives (Django support required)?
[ "You could try using PyPy, which is an implementation of Python in Python. It is a replacement for the standard CPython implementation and boasts large speed increases.\nFrom its website:\n\nSpeed: thanks to its Just-in-Time compiler, Python programs often run\n faster on PyPy. \nMemory usage: large, memory-hungry...
[ 5, 2 ]
[]
[]
[ "c", "compiler_construction", "django", "psyco", "python" ]
stackoverflow_0008301824_c_compiler_construction_django_psyco_python.txt
Q: How to override HTTPForbidden in Ptah? I'm trying out a Pyramid-based web framework, called Ptah, for the first time; I need to override HTTPForbidden view, so that people who are denied access are confronted with a login form. from pyramid import security from pyramid.httpexceptions import HTTPFound, HTTPForbidd...
How to override HTTPForbidden in Ptah?
I'm trying out a Pyramid-based web framework, called Ptah, for the first time; I need to override HTTPForbidden view, so that people who are denied access are confronted with a login form. from pyramid import security from pyramid.httpexceptions import HTTPFound, HTTPForbidden import ptah from ptah import form, view ...
[ "It's no difference how you do HTTPForbidden in Pyramid.\n", "This code works fine using ptah 0.1 and using a scaffolding which throws a ForbiddenError, ala ptah301 scaffold. \n" ]
[ 2, 1 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008266826_pyramid_python.txt
Q: Pass arguments to a slot using QTimer I have written a pyQt client-server application. (python:3.2.2 , pyQT:4.8.6) The sender sends a message to the listening receivers, and the receivers send a response to the sender. I dont want the response to be sent instantly, but after a small delay. This is part of the re...
Pass arguments to a slot using QTimer
I have written a pyQt client-server application. (python:3.2.2 , pyQT:4.8.6) The sender sends a message to the listening receivers, and the receivers send a response to the sender. I dont want the response to be sent instantly, but after a small delay. This is part of the receiver code: ----------------------------...
[ "Have you taken a look at QObject.invokeMethod()?\nIt has been supported since PyQt 4.4 and it should allow you to call a slot with arguments when you don't have a signal that match.\n" ]
[ 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "python_3.x", "qt" ]
stackoverflow_0008298980_pyqt_pyqt4_python_python_3.x_qt.txt
Q: Creating an MSPaint clone in Python? I'm looking to create a VERY simple MSPaint clone in Python with the ability to save and load files. Ideally the program would limit the user to a 4-color palette. What would be the simplest way of going about this? Keep in mind that I'm fairly new to programming, so any ass...
Creating an MSPaint clone in Python?
I'm looking to create a VERY simple MSPaint clone in Python with the ability to save and load files. Ideally the program would limit the user to a 4-color palette. What would be the simplest way of going about this? Keep in mind that I'm fairly new to programming, so any assistance could be helpful.
[ "You probably want to take a look at pygame.\nThe answers to this question should be helpful: How to create MS Paint clone with Python and pygame\n" ]
[ 1 ]
[]
[]
[ "clone", "paint", "python", "save" ]
stackoverflow_0008302175_clone_paint_python_save.txt
Q: What is the best, efficient way to index/store code (scripts, queries) for search/retrieval? We have a whole lot of code, queries in a whole bunch of folders on a Linux box. Whenever I have to find a script, I do a fgrep -ircl --include=*.{sql, py, sh} "Keyword" * . I am planning on creating a simple search interf...
What is the best, efficient way to index/store code (scripts, queries) for search/retrieval?
We have a whole lot of code, queries in a whole bunch of folders on a Linux box. Whenever I have to find a script, I do a fgrep -ircl --include=*.{sql, py, sh} "Keyword" * . I am planning on creating a simple search interface (web) which lets you search for a keyword, file type and displays the location of the file and...
[ "I wrote a perl script waaaaay back when to provide a web interface result, still works on my deprecated blackbeltvb.com website if you want to look. It did a live search though, not indexed, and without excerpts. \nI also wrote the search for wugnet.com that did ranked results and excerpts, and architected the sea...
[ 0, 0 ]
[]
[]
[ "indexing", "python" ]
stackoverflow_0008302197_indexing_python.txt
Q: Python IDLE hangs when opening/saving files I just downloaded the latest Python IDLE 3.2 for Windows 7 (64-bit). I can open, edit, and save existing .py files, but if I open a new document and try to save it, IDLE hangs. After a few attempts, I tried using a regular text editor to create a hello world program (pla...
Python IDLE hangs when opening/saving files
I just downloaded the latest Python IDLE 3.2 for Windows 7 (64-bit). I can open, edit, and save existing .py files, but if I open a new document and try to save it, IDLE hangs. After a few attempts, I tried using a regular text editor to create a hello world program (plain ASCII). But I cannot even open that file: IDL...
[ "It appears IDLE doesn't cope with paths that have spaces in them. I worked around the problem by choosing directory paths that don't have spaces.\n" ]
[ 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0008183670_python_python_idle.txt
Q: Is there any good reason not to use unicode as opposed to string? Many problems I've ran into in Python have been related to not having something in Unicode. Is there any good reason to not use Unicode by default? I understand needing to translate something in ASCII, but it seems to be the exception and not the ru...
Is there any good reason not to use unicode as opposed to string?
Many problems I've ran into in Python have been related to not having something in Unicode. Is there any good reason to not use Unicode by default? I understand needing to translate something in ASCII, but it seems to be the exception and not the rule. I know Python 3 uses Unicode for all strings. Should this encourag...
[ "Generally, I'm going to say \"no\" there's not a good reason to use string over unicode. Remember, as well, that you don't have to call unicode() to create a unicode string, you can do so by prefixing the string with a lowercase u like u\"this is a unicode string\".\n", "In Python 2.x:\n\nA str object is basica...
[ 6, 4 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0008302833_python_unicode.txt
Q: django modelform inheritance I've run into a django error that's got tearing out my hair. Background: I have a set of models inheriting from each other, and I'm trying to build a set of forms with a parallel structure. Here's the base type for an object creation form: class CreateSharedObjectForm(ModelForm): de...
django modelform inheritance
I've run into a django error that's got tearing out my hair. Background: I have a set of models inheriting from each other, and I'm trying to build a set of forms with a parallel structure. Here's the base type for an object creation form: class CreateSharedObjectForm(ModelForm): def save(self, status, object_type, ...
[ "are you sure you don't want super(NewBatchForm, self).save inside NewBatchForm?\n(you have super(CreateSharedObjectForm, self)\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "inheritance", "python", "super" ]
stackoverflow_0008302827_django_django_forms_inheritance_python_super.txt
Q: Why do strptime and strftime behave differently, and what do you do about it? I'm on Python 2.5 and running in App Engine, doing pagination with code that looks like: NEXT_FORMAT = "%Y-%m-%d %H:%M:%S" current = model.completed_on.strftime(NEXT_FORMAT) completed_before = datetime.datetime.strptime(current, NEXT_F...
Why do strptime and strftime behave differently, and what do you do about it?
I'm on Python 2.5 and running in App Engine, doing pagination with code that looks like: NEXT_FORMAT = "%Y-%m-%d %H:%M:%S" current = model.completed_on.strftime(NEXT_FORMAT) completed_before = datetime.datetime.strptime(current, NEXT_FORMAT) Every now and then strftime will drop out a time that looks like 2011-11-24...
[ "Change it to this:\nNEXT_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\"\n\nThis will convert the microsecond part as well.\nOr, if you want to strip off the microseconds, you can use replace before you call strptime.\ncurrent = current.replace(microsecond=0)\n\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008302990_google_app_engine_python.txt
Q: why the output is not good in some cases? i feel stupid and don't know why the output is not good in some cases. here is the output (at the end) it sould find the first sub string in given string for example: sim('banan','na') -> 'na' def rev (str): rev_str='' i = len(str)-1; while (i >= 0): ...
why the output is not good in some cases?
i feel stupid and don't know why the output is not good in some cases. here is the output (at the end) it sould find the first sub string in given string for example: sim('banan','na') -> 'na' def rev (str): rev_str='' i = len(str)-1; while (i >= 0): rev_str += str[i]; i = i-1; return re...
[ "def sim(haystack, needle):\n if needle in haystack:\n return needle\n\nIf you want indices:\ndef sim(haystack, needle):\n index = haystack.index(needle) # throws ValueError when not found\n return (index, index + len(needle))\n\n", "I agree with Cat's solution. FWIW, you probably want to study a ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008302820_python.txt
Q: How can I draw a bunch of squares? I am very new to python. I need to draw this shape for college but i find it really hard so i am trying to do square before going into that image. Anyway here is my question: How can i have 8 rows? (There are 8 square in 1 row) I can not keep adding def start_point1(): This would...
How can I draw a bunch of squares?
I am very new to python. I need to draw this shape for college but i find it really hard so i am trying to do square before going into that image. Anyway here is my question: How can i have 8 rows? (There are 8 square in 1 row) I can not keep adding def start_point1(): This wouldn't be the proper way to do it. #!/usr/...
[ "In this kind of problems, you should ask yourself what is the \"atomic\" operation that - repeated over and over - will generate your complete solution. You already found your basic \"atom\": drawing a side of a square:\nt.forward(60)\n\nNow, what is the next level of \"atomicity\"? Well, repeating four times a si...
[ 8, 0 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0008302942_python_turtle_graphics.txt
Q: pymongo generator fails - 'return' with argument inside generator I am trying to do the following : def get_collection_iterator(collection_name, find={}, criteria=None): collection = db[collection_name] # prepare the list of values of collection if collection is None: logging.error('Mongo coul...
pymongo generator fails - 'return' with argument inside generator
I am trying to do the following : def get_collection_iterator(collection_name, find={}, criteria=None): collection = db[collection_name] # prepare the list of values of collection if collection is None: logging.error('Mongo could not return the collecton - ' + collection_name) return None ...
[ "It seems the problem is that Python doesn't allow you to mix return and yield -- you use both within get_collection_iterator.\nClarification (thanks to rob mayoff): return x and yield can't be mixed, but a bare return can\n", "Your problem is in the event None must be returned, but it is detected as a syntax err...
[ 12, 3 ]
[]
[]
[ "generator", "pymongo", "python" ]
stackoverflow_0008303483_generator_pymongo_python.txt
Q: Neo4j API explanation for Python Does anybody knows where can I find a document of the Neo4j API for Python? I'm newbie and I'm looking for a document with the list of methods and properties and the explanation of each one, or something similar. I'm using the Neo4j Community Edition (well in fact I'm using the emb...
Neo4j API explanation for Python
Does anybody knows where can I find a document of the Neo4j API for Python? I'm newbie and I'm looking for a document with the list of methods and properties and the explanation of each one, or something similar. I'm using the Neo4j Community Edition (well in fact I'm using the embedded Neo4j database in Python). At sa...
[ "I've found myself in a similar situation, and after reading the source code of python-embedded in github, I did realize that in the examples that they show, it's almost everything that you could make in a different way from python, if you take a look to the code, they are just light wrappers to be able to use neo...
[ 2, 1 ]
[]
[]
[ "neo4j", "python" ]
stackoverflow_0008182959_neo4j_python.txt
Q: Getting python -m module to work for a module implemented in C I have a pure C module for Python and I'd like to be able to invoke it using the python -m modulename approach. This works fine with modules implemented in Python and one obvious workaround is to add an extra file for that purpose. However I really w...
Getting python -m module to work for a module implemented in C
I have a pure C module for Python and I'd like to be able to invoke it using the python -m modulename approach. This works fine with modules implemented in Python and one obvious workaround is to add an extra file for that purpose. However I really want to keep things to my one single distributed binary and not add a...
[ "-m implementation is in runpy._run_module_as_main . Its essence is:\nmod_name, loader, code, fname = _get_module_details(mod_name)\n<...>\nexec code in run_globals\n\nA compiled module has no \"code object\" accociated with it so the 1st statement fails with ImportError(\"No code object available for <module>\"). ...
[ 5, 0 ]
[ "I think that you need to start by making a separate file in Python and getting the -m option to work. Then, turn that Python file into a code object and incorporate it into your binary in such a way that it continues to work.\nLook up setuptools in PyPi, download the .egg and take a look at the file. You will see ...
[ -2, -2 ]
[ "python" ]
stackoverflow_0006165824_python.txt
Q: Selecting based on __key__ (a unique identifier) in google appengine Again i have """ A site message """ class Message( db.Model ) : # from/to/ a few other fields subject = db.StringProperty() body = db.Text() sent = db.DateTimeProperty( auto_now_add=True ) Now I'm trying to pick out a Message by its KE...
Selecting based on __key__ (a unique identifier) in google appengine
Again i have """ A site message """ class Message( db.Model ) : # from/to/ a few other fields subject = db.StringProperty() body = db.Text() sent = db.DateTimeProperty( auto_now_add=True ) Now I'm trying to pick out a Message by its KEY. I saved off the key earlier and planted it in an HTML form. The resu...
[ "Don't bother with GQL for key-based retrieval -- make a key object from the string:\nk = db.Key('aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw')\n\nand just db.get(k). If you insist on GQL, btw, that k -- a suitably constructed instance of db.Key, NOT a string object!-) -- is also what you need to substitute into the GQL q...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001419522_google_app_engine_python.txt
Q: PyGTK: Allow usage of Tab in AccelGroup When using gtk.AccelGroup any combination with Tab charater is invalid. Now I do understand that UI navigation is done using this key but in some special cases I need to override that behavior. Is there a way to make AccelGroup allow usage of this key? For example: group = g...
PyGTK: Allow usage of Tab in AccelGroup
When using gtk.AccelGroup any combination with Tab charater is invalid. Now I do understand that UI navigation is done using this key but in some special cases I need to override that behavior. Is there a way to make AccelGroup allow usage of this key? For example: group = gtk.AccelGroup() group.connect(gtk.gdk.keyval_...
[ "You can easily get key names and values with this :\n #!/usr/bin/env python\n\n import gtk\n import gtk\n\n def catch_button(window, event, label):\n keyval = event.keyval\n name = gtk.gdk.keyval_name(keyval)\n mod = gtk.accelerator_get_label(keyval, event.state)\n label.set_markup('<span size=\"xx-lar...
[ 1, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0006834036_gtk_pygtk_python.txt
Q: wx.ListBox.HitTest not working on Mac The following code sample works under linux (ubuntu) and Windows XP, but not under OSX. import wx class frame(wx.Frame): def __init__(self,p=None): wx.Frame.__init__(self,p) self.box = wx.ListBox(self) self.box.AppendItems( ["Zero","One","Two","Thre...
wx.ListBox.HitTest not working on Mac
The following code sample works under linux (ubuntu) and Windows XP, but not under OSX. import wx class frame(wx.Frame): def __init__(self,p=None): wx.Frame.__init__(self,p) self.box = wx.ListBox(self) self.box.AppendItems( ["Zero","One","Two","Three","Four","Five","Six"]) self.box.B...
[ "There is no work around if the listbox is scrolling. The scroll is handled be the underlying Carbon library and scroll position is not accurately reported back through wx.\nI found the bug in the wxWidgets source code and opened a ticket on the wxWidgets trac, http://trac.wxwidgets.org/ticket/13699, with a patch....
[ 1 ]
[]
[]
[ "cross_platform", "python", "wxpython", "wxwidgets" ]
stackoverflow_0008217990_cross_platform_python_wxpython_wxwidgets.txt
Q: Unable to import pyglet.media.avbin My traceback is as follows: C:\Romeo\Scripts>python Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import pyglet.media.avbin Traceback (most recent call last): File ...
Unable to import pyglet.media.avbin
My traceback is as follows: C:\Romeo\Scripts>python Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import pyglet.media.avbin Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:...
[ "This was discussed on the pyglet mailing list at some point, as I discovered, but in case other people look here for an answer, put the avbin.dll in your syswow64 folder on windows 64 versions. It's not clear why this should be the place given that to run pyglet you need to be using the 32 bit python and the the ...
[ 5, 3, 0 ]
[]
[]
[ "pyglet", "python" ]
stackoverflow_0003954495_pyglet_python.txt
Q: Referencing variable from static method inside another action in Pylons I've got: class ArticleController(SubbaseController): def view(self): c.referral = self.detect_referral.referrer return render('/article.mako') @staticmethod def detect_referral(): referrer = request.META.get('HTTP_REFERRER', '')...
Referencing variable from static method inside another action in Pylons
I've got: class ArticleController(SubbaseController): def view(self): c.referral = self.detect_referral.referrer return render('/article.mako') @staticmethod def detect_referral(): referrer = request.META.get('HTTP_REFERRER', '') I'm trying to reference the referrer inside of the view action from the det...
[ "It's a local variable inside detect_referral(), and as such its lifetime is limited to the execution time of the method. Before the method is called and after the method returns local variables simply don't exist. (You don't even seem to call the method, so the local variable exists at no time of the execution o...
[ 0, 0 ]
[]
[]
[ "pylons", "pyramid", "python" ]
stackoverflow_0008302919_pylons_pyramid_python.txt
Q: call python from php Possible Duplicate: Call Python From PHP And Get Return Code probably a very stupid question I have a python module lets say hi.py which have the following print "hi" now I want to execute this file from php <?php #code here ?> So how do I call that python file from php. Thanks A: Use t...
call python from php
Possible Duplicate: Call Python From PHP And Get Return Code probably a very stupid question I have a python module lets say hi.py which have the following print "hi" now I want to execute this file from php <?php #code here ?> So how do I call that python file from php. Thanks
[ "Use the exec function to invoke Python.\nExample:\n$output = array();\nexec(\"python hi.py\", $output);\nvar_dump( $output);\n\nThere are other commands for executing commands on the machine PHP is running on, see the docs.\n", "you can call php exec function and call\npython -c \"print 'hi'\"\n\nor if you have ...
[ 5, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0008303923_php_python.txt
Q: Iterate through multiple class using find_element_by_class_name in Selenium I am using Selenium webdriver in Python for a web-scraping project. The webpage, I am working on has a number of Table entries with the same class name. <table class="table1 text print"> I am using find_element_by_class_name. However I a...
Iterate through multiple class using find_element_by_class_name in Selenium
I am using Selenium webdriver in Python for a web-scraping project. The webpage, I am working on has a number of Table entries with the same class name. <table class="table1 text print"> I am using find_element_by_class_name. However I am getting a error : *Compound class names not permitted * Another question: How ...
[ "You should use find_elements_by_class_name. This will return an iterable object.\n", "The error you describe happens when you provide multiple class names rather than a single one. An easy way around this is to get the elements using CSSSelector or XPath. Alternatively, you could use find_elements_by_class_nam...
[ 4, 1 ]
[]
[]
[ "python", "selenium", "web_scraping", "webdriver" ]
stackoverflow_0008285383_python_selenium_web_scraping_webdriver.txt
Q: Elegant way to transform a list of dict into a dict of dicts I have a list of dictionaries like in this example: listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}] I know that 'name' exists in each dictionary (as well as the other keys) and that it is ...
Elegant way to transform a list of dict into a dict of dicts
I have a list of dictionaries like in this example: listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}] I know that 'name' exists in each dictionary (as well as the other keys) and that it is unique and does not occur in any of the other dictionaries in the ...
[ "d = {}\nfor i in listofdict:\n d[i.pop('name')] = i\n\nif you have Python2.7+:\n{i.pop('name'): i for i in listofdict}\n\n", "dict((d['name'], d) for d in listofdict)\n\nis the easiest if you don't mind the name key remaining in the dict.\nIf you want to remove the names, you can still easily do it in one line...
[ 14, 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008303993_dictionary_python.txt
Q: Why are there two headers within a jpg file? I've been working with Python to create an image viewer: I noticed that when I was working with one of the files that it had two headers? Or at least two occurrences of JFIF, which I thought was unusual. Is there any particular reason that the file is structured like t...
Why are there two headers within a jpg file?
I've been working with Python to create an image viewer: I noticed that when I was working with one of the files that it had two headers? Or at least two occurrences of JFIF, which I thought was unusual. Is there any particular reason that the file is structured like this? Here is a sample of the file: See lines st...
[ "It looks like a thumbnail resource, judging from its ID being 0x040C. To find the ID, look at the line with 8BIM...New Win and read about: image resource blocks and image resource IDs.\n" ]
[ 5 ]
[]
[]
[ "header", "hex", "jpeg", "photoshop", "python" ]
stackoverflow_0008302159_header_hex_jpeg_photoshop_python.txt
Q: Trouble with GAE/Python Recursive link checking and entry update Assuming I have entries in a datastore that reference other datastore entities: id link val_1 val_2 ----------------------------- 1 None 10 None 2 1 None 4 3 2 None 5 4 3 None 2 et...
Trouble with GAE/Python Recursive link checking and entry update
Assuming I have entries in a datastore that reference other datastore entities: id link val_1 val_2 ----------------------------- 1 None 10 None 2 1 None 4 3 2 None 5 4 3 None 2 etc... etc... etc... etc... I need to recursively progress through ...
[ "Looks like you are essentially pushing an update out across a hierarchical dataset. Consider using either GAE's built in parent/ancestor functionality or rolling your own by adding a db.ListProperty(db.Key) to your model that includes a list of all 'link' record keys. This would save you considerable time by all...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008276708_google_app_engine_python.txt
Q: Comparing 2 files in Python while ignoring comments Is there an easy way to compare 2 files in Python while ignoring certain lines? I want to ignore Python style comments (a line beginning with #) and check if all other lines are the same. I guess there's always reading the file line by line and manually comparing...
Comparing 2 files in Python while ignoring comments
Is there an easy way to compare 2 files in Python while ignoring certain lines? I want to ignore Python style comments (a line beginning with #) and check if all other lines are the same. I guess there's always reading the file line by line and manually comparing.
[ "First remove the comments from both files. Then use a Differ to compare the resulting files.\n", "Do you just want to report if they are the same or are different? Or do you also want to know the first place where they are different, or do you want to know all of the places where they are different?\nI'll assume...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008302783_python.txt
Q: Is it possible to precompile an entire python package? We have a significant ~(50kloc) tree of packages/modules (approx 2200files) that we ship around to our cluster with each job. The jobs run for ~12 hours, so the overhead of untarring/bootrapping (i.e. resolving PYTHONPATH for each module) usually isn't a big d...
Is it possible to precompile an entire python package?
We have a significant ~(50kloc) tree of packages/modules (approx 2200files) that we ship around to our cluster with each job. The jobs run for ~12 hours, so the overhead of untarring/bootrapping (i.e. resolving PYTHONPATH for each module) usually isn't a big deal. However, as the number of cores in our worker nodes hav...
[ "We had problems like this on our cluster. (The Lustre filesystem was slow for metadata operations.) Our solution was to use the \"zip import\" facilities in Python.\nIn our case we made a single zip of the stdlib (placed in the name given already in sys.path, like \"/usr/lib/python26.zip\") and another zip of our ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008301130_python.txt
Q: Using multiprocessing inside decorator generates error: can't pickle function...it's not found as I came across a problem that I can't solve and it's associated with multiprocessing and use it inside the decorator. When I'm calling the method run_in_parallels using multiprocessing I 'm getting the error: Can't pic...
Using multiprocessing inside decorator generates error: can't pickle function...it's not found as
I came across a problem that I can't solve and it's associated with multiprocessing and use it inside the decorator. When I'm calling the method run_in_parallels using multiprocessing I 'm getting the error: Can't pickle <function run_testcase at 0x00000000027789C8>: it's not found as __main__.run_testcase The call tak...
[ "The function you're passing to Process.__init__() is not picklable in Windows. Read 16.6 multiprocessing - Programming guidelines - Windows .\nRegarding your error with a top-level function - I suspect the way you defined it, it is generated differently each time and thus is really \"not the same object\" in child...
[ 4, 1 ]
[]
[]
[ "decorator", "multiprocessing", "pickle", "python" ]
stackoverflow_0008126654_decorator_multiprocessing_pickle_python.txt
Q: How do I create request handlers dynamically in CherryPy? How would one go about creating request handler's at runtime with CherryPy? The default dispatch method shows creating the handler objects explicitly and building the tree that way: class OnePage(object): def index(self): return "one page!" ...
How do I create request handlers dynamically in CherryPy?
How would one go about creating request handler's at runtime with CherryPy? The default dispatch method shows creating the handler objects explicitly and building the tree that way: class OnePage(object): def index(self): return "one page!" index.exposed = True class HelloWorld(object): onepage = ...
[ "You can use routes, if that's your thing, or build a root object with the default-dispatcher approach, I personally use the default routing, is more natural, and goes along with the growing of the code, but some people feel more comfortable with the notion of separated logic from routing to application, your choi...
[ 5 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0008303692_cherrypy_python.txt
Q: Python fabric sudo() returning weird escape characters in output The code I'm trying to run: from fabric.api import * from fabric.contrib.files import * def git(): with cd('/home/something'): output = sudo('git log --pretty=oneline --no-color --abbrev-commit -n 1 HEAD') print repr(output) Exe...
Python fabric sudo() returning weird escape characters in output
The code I'm trying to run: from fabric.api import * from fabric.contrib.files import * def git(): with cd('/home/something'): output = sudo('git log --pretty=oneline --no-color --abbrev-commit -n 1 HEAD') print repr(output) Executed with fabric 0.9.something: $ fab git [localhost] Executing task ...
[ "As per Fabric's changelog:\nAs part of the changes made in #7, run and sudo have had the default value of their pty kwargs changed from False to True. This, plus the addition of the combine_stderr kwarg/env var, may result in significant behavioral changes in remote programs which operate differently when attached...
[ 3 ]
[]
[]
[ "fabric", "linux", "python", "shell" ]
stackoverflow_0007753988_fabric_linux_python_shell.txt
Q: serving logs via HTTP Here is what i am trying to achieve: I have a few Linux servers that have my web App deployed on. Currently my development team access the web app, run their test cases and then SSH into my Linux boxes to view or get the logs. I don't like them to be able to SSH/FTP into any servers and i am ...
serving logs via HTTP
Here is what i am trying to achieve: I have a few Linux servers that have my web App deployed on. Currently my development team access the web app, run their test cases and then SSH into my Linux boxes to view or get the logs. I don't like them to be able to SSH/FTP into any servers and i am looking for a solution to g...
[ "Flask and Bottle are popular choices for this kind of lightweight HTTP work.\nAt PyCon AU, Richard Jones compared and contrasted about ten such frameworks: http://www.youtube.com/watch?v=AYjPIMe0BhA His video is worth watching.\n", "Have you considered using a log aggregation and analysis solutions like Splunk?...
[ 2, 2 ]
[]
[]
[ "httpserver", "linux", "logging", "python", "simplehttpserver" ]
stackoverflow_0008304227_httpserver_linux_logging_python_simplehttpserver.txt
Q: Multiple installation configurations for a Python package I'm working on creating a Python package that is somewhat modular in nature and I was wondering what's the best way to go about handling multiple installation configurations? Take the following setup.py for the package of a simple document parser: setup( ...
Multiple installation configurations for a Python package
I'm working on creating a Python package that is somewhat modular in nature and I was wondering what's the best way to go about handling multiple installation configurations? Take the following setup.py for the package of a simple document parser: setup( name = 'my_document_parser', ... entry_points = { ...
[ "The default installation will install everything in your install_requires and packages sections. Packages under extras_require will never be installed by your setup.py script; only if you create some logic for this kind of installation.\nBy default, setuptools and distutils have no way to explictly say \"install u...
[ 0 ]
[]
[]
[ "distribute", "packaging", "pip", "python" ]
stackoverflow_0008292859_distribute_packaging_pip_python.txt
Q: Module-wide destructor in Python? I am wondering if there is a module-wide destructor such that we can make use of it to finalize or call some specific shut down functions in a module? For example, some handlers of the module logbook are created and pust into the stack (ex, handler1.push_application() and it is be...
Module-wide destructor in Python?
I am wondering if there is a module-wide destructor such that we can make use of it to finalize or call some specific shut down functions in a module? For example, some handlers of the module logbook are created and pust into the stack (ex, handler1.push_application() and it is better to pop up those handlers when your...
[ "The atexit module allows you to register cleanup functions that Python will perform on interpreter termination.\n" ]
[ 6 ]
[]
[]
[ "destructor", "logging", "python" ]
stackoverflow_0008304313_destructor_logging_python.txt
Q: Why is this parsing of JSON failing in django/python The code below ends up printing failure. try: print request.raw_post_data json_data = simplejson.loads(request.raw_post_data) except: print "failure" The out put of the first print is JSON: {"password":"wfbarks","email":"wfb...
Why is this parsing of JSON failing in django/python
The code below ends up printing failure. try: print request.raw_post_data json_data = simplejson.loads(request.raw_post_data) except: print "failure" The out put of the first print is JSON: {"password":"wfbarks","email":"wfbarks","username":"wfbarks"} Does anybody know what is wro...
[ "The JSON: part is not valid JSON. Strip it before loads. The remainder (i.e. {\"password\":\"wfbarks\",\"email\":\"wfbarks\",\"username\":\"wfbarks\"}) should be valid JSON.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008304615_django_python.txt
Q: Display an attached image on the HTML message I have develop a function in PYTHON that sends emails with one .doc attachment and one image attachment (.jpg) The message of the email is HTML. I want to know how to display the Attached Image on the HTML message....is there any instruction that can help me with this?...
Display an attached image on the HTML message
I have develop a function in PYTHON that sends emails with one .doc attachment and one image attachment (.jpg) The message of the email is HTML. I want to know how to display the Attached Image on the HTML message....is there any instruction that can help me with this??? Thanks a lot.... Here is the function I develope...
[ "In your html, use img tags with a src of:\ncid:<filename used in your Content-Disposition header>\n\nSo, for instance:\n<p>\n<img src=\"cid:image1.jpeg\"/>\n</p>\n\n" ]
[ 11 ]
[]
[]
[ "html", "mime_message", "mime_types", "python", "sendmail" ]
stackoverflow_0008304618_html_mime_message_mime_types_python_sendmail.txt
Q: Login to a website through web-scraping tool in Python I am using Selenium webdriver in Python for a web-scraping project. I would like to login by entering the login details and then click the submit button. I am able to enter the Username and Password. But I am not able to mouseclick the submit button. The "sub...
Login to a website through web-scraping tool in Python
I am using Selenium webdriver in Python for a web-scraping project. I would like to login by entering the login details and then click the submit button. I am able to enter the Username and Password. But I am not able to mouseclick the submit button. The "submit" button is of type <input>. <input type="image" src="/i...
[ "I had good luck using mechanize. It's pretty straightforward and simple to use.\nHere's a stripped-down version of a script I made:\nfrom BeautifulSoup import BeautifulSoup\nfrom tidylib import tidy_document\n\nimport mechanize\nimport cookielib\n\nif __name__ == '__main__':\n browser = mechanize.Browser()\n\n c...
[ 9, 4 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "urllib2", "web_scraping" ]
stackoverflow_0008304672_beautifulsoup_python_selenium_urllib2_web_scraping.txt
Q: How Would I Display the Score in this Simple Game? I've tried using the blit function to paste it to the surface but that didn't work because I couldn't use a surface as a source for the score as I did with the player, enemy, and food variables. I also tried using self.score = Score((75, 575)) but that didn't work...
How Would I Display the Score in this Simple Game?
I've tried using the blit function to paste it to the surface but that didn't work because I couldn't use a surface as a source for the score as I did with the player, enemy, and food variables. I also tried using self.score = Score((75, 575)) but that didn't work because for some reason it said "self" wasn't defined. ...
[ "Your problem isn't with blit or any other part of pygame; it is with your use of the self keyword. Self is a reference to an object's attributes. You do not call self.score outside of the Score class itself.\nInstead, initialize a score object in the beginning of the game and add to the score as needed. This is ho...
[ 2, 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008303685_pygame_python.txt