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 to modify a Vim buffer with a python script?
The official Vim python interface documentation states, that modifying buffers with python is very simple, basically:
:py import vim
:py vim.current.buffer[0] = "Hello world"
However, python throws an exception, when I try to do that:
Traceback (most recent call l... | How to modify a Vim buffer with a python script? | The official Vim python interface documentation states, that modifying buffers with python is very simple, basically:
:py import vim
:py vim.current.buffer[0] = "Hello world"
However, python throws an exception, when I try to do that:
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError... | [
"Works for me, \"Hello World\" is inserted in buffer. Is your vim compiled with +python\nI'm using version 7.3.162\nEDIT\nlooking in the hg log for if_python.c I see a lot issues related to python, e.g. this one:\nchangeset: 2641:b803b2776880\ntag: v7-3-062\nuser: Bram Moolenaar <bram@vim.org>\ndat... | [
3,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0006157222_python_vim.txt |
Q:
Install django db log
I tried to install django db log from here https://github.com/dcramer/django-db-log, by running python setup.py install, but for some reason when I add the app to the settings.py file, it's not working. here's the error that I get:
Request Method: GET
Request URL: http://localhost:8000... | Install django db log | I tried to install django db log from here https://github.com/dcramer/django-db-log, by running python setup.py install, but for some reason when I add the app to the settings.py file, it's not working. here's the error that I get:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: ... | [
"From the django-db-log's project page:\nThis project is no longer updated. Please see http://github.com/dcramer/django-sentry for its successor\n\nSo I simply assume that this project is not compatible with Django-1.3.1 due to various deprecations...\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007963387_django_python.txt |
Q:
QSettings(): How to save to current working directory
For an app that can be run directly from a flash/pen/usb/jump/thumb drive, for portability in moving from one machine to another it can make sense for user settings to be stored on the memory stick in the same directory that the program is being run from (rathe... | QSettings(): How to save to current working directory | For an app that can be run directly from a flash/pen/usb/jump/thumb drive, for portability in moving from one machine to another it can make sense for user settings to be stored on the memory stick in the same directory that the program is being run from (rather than Windows/Mac/Linux user or system dirs per machine).
... | [
"You can use that overload class QSettings(fileName, format[, parent=None]) like this:\nself.settings = QSettings(\"__settings.ini\", QSettings.IniFormat)\n\nIf the path is relative, the file will already be opened in the current working directory, but that may not be what you want. You may try one of these answers... | [
9
] | [] | [] | [
"pyqt4",
"pyside",
"python"
] | stackoverflow_0007962292_pyqt4_pyside_python.txt |
Q:
How can I pretty print the arguments' float default value in python 2.x?
Give follow python function define:
def Foo(a=0.1, b=1.6):
pass
when I call 'help(Foo)', I will get:
Help on function Foo in module __main__:
Foo(a=0.10000000000000001, b=1.6000000000000001)
But I wish get:
Help on function Foo in modul... | How can I pretty print the arguments' float default value in python 2.x? | Give follow python function define:
def Foo(a=0.1, b=1.6):
pass
when I call 'help(Foo)', I will get:
Help on function Foo in module __main__:
Foo(a=0.10000000000000001, b=1.6000000000000001)
But I wish get:
Help on function Foo in module __main__:
Foo(a=0.1, b=1.6)
dear all of you, is there a way to print this p... | [
"In Python 2.7, this happens by default.\nPython 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> def Foo(a=0.1, b=1.6):\n pass\n\n>>> help(Foo)\nHelp on function Foo in module _... | [
1,
1
] | [] | [] | [
"floating_point",
"format",
"python"
] | stackoverflow_0007961768_floating_point_format_python.txt |
Q:
using subprocess over different files python
I've got a problem with a short script, it'd be great if you could have a look!
import os
import subprocess
root = "/Users/software/fmtomov1.0/remaker_lastplot/source_relocation/observed_arrivals_loc3d"
def loop_loc3d(file_in):
"""Loops loc3d over the source files... | using subprocess over different files python | I've got a problem with a short script, it'd be great if you could have a look!
import os
import subprocess
root = "/Users/software/fmtomov1.0/remaker_lastplot/source_relocation/observed_arrivals_loc3d"
def loop_loc3d(file_in):
"""Loops loc3d over the source files"""
return subprocess.call (['loc3d'], shell=T... | [
"I assume you would call loc3d filename from the CLI. If so, then:\ndef loop_loc3d(filename):\n \"\"\"Loops loc3d over the source files\"\"\"\n return subprocess.call (['loc3d',filename])\n\ndef relocation():\n for subdir, dirs, files in os.walk(root):\n for file in files:\n filename = os... | [
1,
1,
0,
0
] | [] | [] | [
"file",
"python",
"subprocess"
] | stackoverflow_0007937689_file_python_subprocess.txt |
Q:
python multiprocessing self-feeding consumer locks forever
The problem is that the consumer never exits, it just hangs doing nothing. The code was intended to work like this:
A queue is created and some task_data passed into it. A specified number of consumers are created to process the data. When a consumer finds... | python multiprocessing self-feeding consumer locks forever | The problem is that the consumer never exits, it just hangs doing nothing. The code was intended to work like this:
A queue is created and some task_data passed into it. A specified number of consumers are created to process the data. When a consumer finds out that the queue is empty, because there is still a chance th... | [
"Looks like a good sleep really helps, a refreshed mind can do much more..\nAnyway, I found a solution after studying the python documentation.\nclass Consumer(multiprocessing.Process):\n\n def __init__(self, task_queue, results, consumers_finished):\n multiprocessing.Process.__init__(self)\n self.... | [
2
] | [] | [] | [
"multiprocessing",
"process",
"python",
"queue"
] | stackoverflow_0007958560_multiprocessing_process_python_queue.txt |
Q:
Pyramid-debugging a resource cannot be found error
What are possible causes of "The resource could not be found" error in Pyramid?
From my limited exeperiece debugging my Pyramid app, errors with routes and Python syntax error trigger a more explicit error message.
Is there a way to get the development server to ... | Pyramid-debugging a resource cannot be found error | What are possible causes of "The resource could not be found" error in Pyramid?
From my limited exeperiece debugging my Pyramid app, errors with routes and Python syntax error trigger a more explicit error message.
Is there a way to get the development server to trace a request (similiar to the way running a rails ser... | [
"So that's a HTTPNotFound error, which Pyramid has a debugging option for to help you out.\nhttps://docs.pylonsproject.org/projects/pyramid/en/1.2-branch/narr/viewconfig.html#notfound-errors\n"
] | [
0
] | [] | [] | [
"paster",
"pyramid",
"python"
] | stackoverflow_0007961112_paster_pyramid_python.txt |
Q:
mod_wsgi and EC2 how to compile against httpd provided
I'm trying to install install mod_wsgi on a EC2 instance. I'm using the amazon 64bit linux ami , and the problem is how do I install it when apxs doesn't exist in this image. Instead it uses httpd for the apache configuration. The problem is the compiled versi... | mod_wsgi and EC2 how to compile against httpd provided | I'm trying to install install mod_wsgi on a EC2 instance. I'm using the amazon 64bit linux ami , and the problem is how do I install it when apxs doesn't exist in this image. Instead it uses httpd for the apache configuration. The problem is the compiled version of mod_wsgi is python 2.6.6 where the core python 2.6.7
A... | [
"It doesn't matter that there is a patch level revision difference so long as the Python installation provides a shared library and mod_wsgi is using the Python shared library. See:\nhttp://code.google.com/p/modwsgi/wiki/InstallationIssues#Python_Version_Mismatch\nThere would only be an issue if the major/minor ver... | [
0
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"apache",
"mod_wsgi",
"python"
] | stackoverflow_0007962240_amazon_ec2_amazon_web_services_apache_mod_wsgi_python.txt |
Q:
wxpython: How to set width and height of a wxnotebook?
i am having troubles, with I believe is the sizers. I cannot set the size of the notebook the way i want it to be. Right now I put a button and the position of the button determines the size of the notebook (it will stretch it) however i want it to just be abl... | wxpython: How to set width and height of a wxnotebook? | i am having troubles, with I believe is the sizers. I cannot set the size of the notebook the way i want it to be. Right now I put a button and the position of the button determines the size of the notebook (it will stretch it) however i want it to just be able to do this without using the button. I have played around ... | [
"Try something like this:\nCOLORS = [\"red\", \"blue\", \"black\", \"yellow\", \"green\"]\nNUMBERS = ['0', '1', '2', '3', '4']\nPANELS = [\"Things\", \"More things\", \"Ultra!\"]\n\nimport random\nimport wx\n\nclass TabPanel(wx.Panel):\n def __init__(self, *args, **kwargs):\n wx.Panel.__init__(self, *args... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007960087_python_wxpython.txt |
Q:
How to add elements from one dictionary into other? Python
I have main dictionary.
mainDict = {'count': 10, 'a': {'abc': {'additional': 0, 'missing': 0, 'changed': 0}}}
Now i have new dictionary with same keys as in mainDict, called this dictionary as b with different values.
b = {'count': 20, 'a': {'abc': {'add... | How to add elements from one dictionary into other? Python | I have main dictionary.
mainDict = {'count': 10, 'a': {'abc': {'additional': 0, 'missing': 0, 'changed': 0}}}
Now i have new dictionary with same keys as in mainDict, called this dictionary as b with different values.
b = {'count': 20, 'a': {'abc': {'additional': 10, 'missing': 10, 'changed': 10}}}
I want to update(... | [
"def recursive_dict_sum_helper(v1, v2):\n # \"add\" two values: if they can be added with '+', then do so,\n # otherwise expect dictionaries and treat them appropriately.\n try: return v1 + v2\n except: return recursive_dict_sum(v1, v2)\n\ndef recursive_dict_sum(d1, d2):\n # Recursively produce the n... | [
3,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007963694_dictionary_python.txt |
Q:
How can one quickly check if a SimpleXMLRPCServer server is online?
The server is on a local network.
I tried using a try-except and call one of the server's methods but, if the server is off-line, that takes around 1 second and for my application this is way too long.
Is there a quick way to just check if the s... | How can one quickly check if a SimpleXMLRPCServer server is online? | The server is on a local network.
I tried using a try-except and call one of the server's methods but, if the server is off-line, that takes around 1 second and for my application this is way too long.
Is there a quick way to just check if the server that the ServerProxy is targeting is online?
| [
"I'd do it exactly as you did it. Easier to ask for forgiveness than permission ;) That's common python coding style. The only thing you could probably do is to adjust the network timeout.\nIf you want to check that reliably, you're on the best way imo. An answer from a server might could delay to about a second, i... | [
1
] | [] | [] | [
"network_programming",
"python"
] | stackoverflow_0007964576_network_programming_python.txt |
Q:
complex SOAP request prints single line response
I am completely new to Python and Suds.In order to test different clients, I succeeded in C#, java, perl and now term is about Python-suds...can some one help...
here is the client code----
from suds.client import Client
wsdl = 'http://www.cbs.dtu.dk/ws/SignalP/Sign... | complex SOAP request prints single line response | I am completely new to Python and Suds.In order to test different clients, I succeeded in C#, java, perl and now term is about Python-suds...can some one help...
here is the client code----
from suds.client import Client
wsdl = 'http://www.cbs.dtu.dk/ws/SignalP/SignalP_3_1_ws0.wsdl'
client = Client(wsdl)
seq="""val1
va... | [
"I figured out an answer myself, but it seems it's not 100%; I am getting a correct response envelope, but the request envelope has incorrect formatting for val2 and val3.\nHere I put altogether (I used logging to know the input/ouput):\nfrom suds.client import Client\nimport logging\n\nlogging.basicConfig(level=lo... | [
0
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0007952010_python_soap_suds.txt |
Q:
hadoop-streaming : reduce task in pending state says "No room for reduce task."
My map task completes successfully and I can see the application logs, but reducer stays in pending state
Kind % Complete Num Tasks Pending Running Complete Killed Failed/Killed Task Attempts
map 100.00% 200 0 0 ... | hadoop-streaming : reduce task in pending state says "No room for reduce task." | My map task completes successfully and I can see the application logs, but reducer stays in pending state
Kind % Complete Num Tasks Pending Running Complete Killed Failed/Killed Task Attempts
map 100.00% 200 0 0 200 0 0 / 40
reduce 0.00% 1 1 0 0 0 0 / 0
When I look at reduce ta... | [
"Your disk on the host where the reducer is run is too small. Your reducer input takes approx. 172 gbs, but you have only 63gb free.\nMaybe combiner could be useful for you. Have a look here: http://tumblr.mobocracy.net/post/6589143971/using-a-combiner-with-hadoop-jobs\n"
] | [
1
] | [] | [] | [
"hadoop",
"hadoop_streaming",
"mapreduce",
"python",
"reduce"
] | stackoverflow_0007962730_hadoop_hadoop_streaming_mapreduce_python_reduce.txt |
Q:
Gibberish from urlopen
I am trying to read some utf-8 files from the addresses in the code below. It works for most of them, but for some files the urllib2 (and urllib) is unable to read.
The obvious answer here is that the second file is corrupt, but the strange thing is that IE reads them both with no problem a... | Gibberish from urlopen | I am trying to read some utf-8 files from the addresses in the code below. It works for most of them, but for some files the urllib2 (and urllib) is unable to read.
The obvious answer here is that the second file is corrupt, but the strange thing is that IE reads them both with no problem at all. The code has been tes... | [
">>> f=urllib2.urlopen(\"http://www.gutenberg.org/cache/epub/144/pg144.txt\")\n>>> f.headers.dict\n{'content-length': '304513', ..., 'content-location': 'pg144.txt.utf8.gzip', 'content-encoding': 'gzip', ..., 'content-type': 'text/plain; charset=utf-8'}\n\nEither set a header that prevents the site sending a gzip-e... | [
2,
0
] | [
"You know it's not a solution, but you should look http://pypi.python.org/pypi/requests library, no matter if you still want to use urllib can look the source code of Requests, to understand how it works with utf-8 strings .\n"
] | [
-1
] | [
"python",
"urlopen",
"utf_8"
] | stackoverflow_0007964726_python_urlopen_utf_8.txt |
Q:
Duplicates in a dictionary (Python)
I need to write a function that returns true if the dictionary has duplicates in it. So pretty much if anything appears in the dictionary more than once, it will return true.
Here is what I have but I am very far off and not sure what to do.
d = {"a", "b", "c"}
def has_duplicat... | Duplicates in a dictionary (Python) | I need to write a function that returns true if the dictionary has duplicates in it. So pretty much if anything appears in the dictionary more than once, it will return true.
Here is what I have but I am very far off and not sure what to do.
d = {"a", "b", "c"}
def has_duplicates(d):
seen = set()
d={}
for ... | [
"def has_duplicates(d):\n return False\n\nDictionaries do not contain duplicate keys, ever. Your function, btw., is equivalent to this definition, so it's correct (just a tad long).\nIf you want to find duplicate values, that's\nlen(set(d.values())) != len(d)\n\nassuming the values are hashable.\n",
"If you ar... | [
7,
7,
3,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007960934_dictionary_python.txt |
Q:
Templatizing images using gimp
My wife recently started a business making soap bars and the soap labels have quickly spiraled out of control into tons of diverging Gimp .xcf files. The only difference between the files are the names of the product, description, and ingredients. I'd like to make a template and pr... | Templatizing images using gimp | My wife recently started a business making soap bars and the soap labels have quickly spiraled out of control into tons of diverging Gimp .xcf files. The only difference between the files are the names of the product, description, and ingredients. I'd like to make a template and produce the labels from a .xcf file an... | [
"The Python Imaging Library (PIL) can quite easily read in an image, put some text on it, and write it back out. Use the Image module to read and write, and the ImageDraw module to add the text.\nI doubt that it can use the .xcf format though, you'll probably want to convert to .png.\n",
"You can script GIMP in P... | [
1,
1
] | [] | [] | [
"gimp",
"python"
] | stackoverflow_0007958276_gimp_python.txt |
Q:
when using "group_by" in a query, select an element from each group
I was wondering how to extract an arbitrary element from a class when querying with "group by". For example:
class Post(Base):
id = Column(Integer, primary_key=True)
created = Column(DateTime)
comments = Column(Integer)
creator = C... | when using "group_by" in a query, select an element from each group | I was wondering how to extract an arbitrary element from a class when querying with "group by". For example:
class Post(Base):
id = Column(Integer, primary_key=True)
created = Column(DateTime)
comments = Column(Integer)
creator = Column(Integer, ForeignKey('user.id'))
anonymous = Column(Boolean)
cl... | [
"In SQL, you should be able to do something like:\nSELECT Post.creator, \n sum(Post.comments) total_comments\n max(Post.Created) latest_post\n max(Post.anonymous) any_anonymous\nFROM Post\nGROUP BY Post.creator\n\n"
] | [
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0007963436_python_sql_sqlalchemy.txt |
Q:
Python 2.4 - unittest: TypeError: run() takes exactly 2 arguments (1 given)
I can't quite figure this one out, the following code works perfectly with Python 2.6+
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestMrdfWriter("testParParser"))
suite.addTest(TestMrdfWriter("testMr... | Python 2.4 - unittest: TypeError: run() takes exactly 2 arguments (1 given) | I can't quite figure this one out, the following code works perfectly with Python 2.6+
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestMrdfWriter("testParParser"))
suite.addTest(TestMrdfWriter("testMrdfWriter"))
unittest.TextTestRunner(verbosity=2).run(suite())
With Python 2.... | [
"I don't think the code works in Python2.6 either. It should be\nunittest.TextTestRunner(verbosity=2).run(suite)\n\nwithout the parentheses after suite.\n"
] | [
1
] | [] | [] | [
"python",
"typeerror",
"unit_testing"
] | stackoverflow_0007965118_python_typeerror_unit_testing.txt |
Q:
DJANGO Aggregate with Foreignkey
I'm trying to do a group by clause on a foreign key but am having a couple of issues.
The code;
status_applications = DevelopmentAssessment.objects.values('status').annotate(total = Count('status'))
The field status only returns an integer for the status value instead of the relat... | DJANGO Aggregate with Foreignkey | I'm trying to do a group by clause on a foreign key but am having a couple of issues.
The code;
status_applications = DevelopmentAssessment.objects.values('status').annotate(total = Count('status'))
The field status only returns an integer for the status value instead of the related object. Is there a way to have it r... | [
"You basically already have an answer.\nstatus_applications is a QuerySet that contains a set of related objects (statuses) you are asking for.\nstatus_applications[0] would be the first, [1] second and so on.\nTo access the count of each simply do:\nfor status in status_applications:\n print status, status.tota... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007961117_django_python.txt |
Q:
Is there any possible way to embedd javascript in python for windows?
I've searched high and low for a solution to this and I've also gone through How to execute Javascript from Python on Windows? but it was asked a while ago.
In the meantime has the world come up with a better solution?
And no python-spidermonkey... | Is there any possible way to embedd javascript in python for windows? | I've searched high and low for a solution to this and I've also gone through How to execute Javascript from Python on Windows? but it was asked a while ago.
In the meantime has the world come up with a better solution?
And no python-spidermonkey does not work for windows.
Anyone successful in having embedded javascript... | [
"Check out PyV8: http://code.google.com/p/pyv8/\n"
] | [
3
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0007965863_javascript_python.txt |
Q:
Can't import Webkit from gi.repository
When I try to import Webkit from gi.repository, it gives an ImportError:
from gi.repository import Webkit
ERROR:root:Could not find any typelib for Webkit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name Webkit
What am ... | Can't import Webkit from gi.repository | When I try to import Webkit from gi.repository, it gives an ImportError:
from gi.repository import Webkit
ERROR:root:Could not find any typelib for Webkit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name Webkit
What am I doing wrong?
| [
"Your error seems a typo and the library is not found for that.\nYou have to put \"WebKit\" instead of \"Webkit\".\nAdditionaly if you use Ubuntu check the library existence with:\n$ locate girepository | grep WebKit\n/usr/lib/girepository-1.0/WebKit-3.0.typelib\n\nIf doesn't exist you need install the package gir1... | [
34
] | [] | [] | [
"gtk3",
"importerror",
"pygobject",
"python",
"webkit"
] | stackoverflow_0007823972_gtk3_importerror_pygobject_python_webkit.txt |
Q:
Calling a method from an imported python file
I have this directory structure.
In my project root directory I have a main python file say main.py. Also in the this root direcory there is folder called Tests. This test folder will have series of test files (known only at run time) e.g test1.py,test2.py etc...
In my... | Calling a method from an imported python file | I have this directory structure.
In my project root directory I have a main python file say main.py. Also in the this root direcory there is folder called Tests. This test folder will have series of test files (known only at run time) e.g test1.py,test2.py etc...
In my testfiles e.g Test1.py I have this sort of structu... | [
"Starting from Python 2.7, the functionality you need is included in the built-in unittest module. For earlier versions of Python this module has been backported under the name unittest2.\nIf for some reason you want to roll your own test discovery, here is a basic approach:\nimport glob\nimport sys\nimport TestBa... | [
1,
0,
0
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0007965935_class_oop_python.txt |
Q:
Are there any standard Command line conventions for dashes and arguments?
What are the command-line conventions regarding when to use 2 dashes, 1 dash, or simply no options at all and simply read inputs in order?
I realize there are many variants, but do any conventions stand out as the industry standard (say in ... | Are there any standard Command line conventions for dashes and arguments? | What are the command-line conventions regarding when to use 2 dashes, 1 dash, or simply no options at all and simply read inputs in order?
I realize there are many variants, but do any conventions stand out as the industry standard (say in Java, or C, or Python)?
| [
"Read up on the background section of Python's optparse module, it answers some of your questions and exemplifies with some common argument formatting standards seen in the wild. The optparse module author recommends a style that roughly corresponds to the POSIX conventions for command line arguments, with the addi... | [
6,
4,
1
] | [] | [] | [
"command_line_arguments",
"java",
"python",
"unix"
] | stackoverflow_0007966077_command_line_arguments_java_python_unix.txt |
Q:
Do python packages (multi-file modules) behave exactly as one big module?
I've just read an article that supposedly introduced me to a new concept: Up to now I was sure that python packages (i.e directories with an __init__.py file) behave exactly the same as java packages, that is - little namespaces to help arra... | Do python packages (multi-file modules) behave exactly as one big module? | I've just read an article that supposedly introduced me to a new concept: Up to now I was sure that python packages (i.e directories with an __init__.py file) behave exactly the same as java packages, that is - little namespaces to help arrange the code (minus java's "package" scoping).
But, according to this link:
A ... | [
"Maybe the point is simply that a package is just a specific type of module.\n/base\n /animals\n /__init__.py\n /dog.py\n\nIt just means that anything that you define in or import into __init__.py will be visible inside the animals module.\nSo animals is a module (that is a package) and animals.dog... | [
4,
4,
1,
0
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0002392704_module_package_python.txt |
Q:
Python - opening cli/gui editors (vim, nano, geany...)
I'd like to open an editor (cli or gui-based) via Python script. I can do this with os.system('vim file'), but I'd also like to get output in case command fails. subprocess.getstatusoutput('vim file') doesn't work for opening programs with specific interface.
... | Python - opening cli/gui editors (vim, nano, geany...) | I'd like to open an editor (cli or gui-based) via Python script. I can do this with os.system('vim file'), but I'd also like to get output in case command fails. subprocess.getstatusoutput('vim file') doesn't work for opening programs with specific interface.
What's the best alternative?
| [
"subprocess.check_call([EDITOR, file_path])\n\nwill raise an OSError exception if EDITOR fails to run.\n",
"You can use os.execv(path, args) if the command fails, an OSError will be thrown. You can find more details on os.execv documentation.\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007966451_python.txt |
Q:
Assigning values to a class dynamically
I have a python class like this
class Car(Base):
def __init__(self, details):
for field,value in details.iteritems():
self[field] = value
and I call it like this
car_details['make'] = 'Dodge'
car_details['model'] = 'Ram'
car = Car(car_details)
how... | Assigning values to a class dynamically | I have a python class like this
class Car(Base):
def __init__(self, details):
for field,value in details.iteritems():
self[field] = value
and I call it like this
car_details['make'] = 'Dodge'
car_details['model'] = 'Ram'
car = Car(car_details)
however it fails with
TypeError: 'Car' object do... | [
"you're looking for setattr(): \ndef __init__(self, details):\n for field,value in details.iteritems():\n setattr(self, field, value)\n\n",
"You could use Alex Martelli's Bunch:\nclass Car(Base): \n def __init__(self, details):\n self.__dict__.update(details)\n\nNote that if you change the ... | [
3,
2,
0
] | [] | [] | [
"python",
"variable_assignment"
] | stackoverflow_0007966027_python_variable_assignment.txt |
Q:
scrapy crawl: error: no such option : -o
When I run the command scrapy crawl openings -o items.json -t json as mentioned in the tutorial, I get:
Usage
=====
scrapy crawl [options] <spider|url> ...
crawl: error: no such option: -o
I am simply following the scrapy tutorial, when I run the command without the ou... | scrapy crawl: error: no such option : -o | When I run the command scrapy crawl openings -o items.json -t json as mentioned in the tutorial, I get:
Usage
=====
scrapy crawl [options] <spider|url> ...
crawl: error: no such option: -o
I am simply following the scrapy tutorial, when I run the command without the output option it works fine.
scrapy crawl openi... | [
"That option is only for the latest version of Scrapy, which can be found on GitHub.\nIf you are using version 0.12 (latest stable as can be seen on scrapy.org), you should use:\nscrapy crawl openings --set FEED_URI=items.json --set FEED_FORMAT=json\nSee also: http://readthedocs.org/docs/scrapy/en/0.12/intro/tutori... | [
7
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0007963316_python_scrapy.txt |
Q:
Get data from inner page and merge with current page
in my html page there is table with two columns, the first one name and the second one a Link in which there is a date, i want to be able to download this page get this date and raise it, so in the output i will have Name and Date.
For example
in the first page ... | Get data from inner page and merge with current page | in my html page there is table with two columns, the first one name and the second one a Link in which there is a date, i want to be able to download this page get this date and raise it, so in the output i will have Name and Date.
For example
in the first page we have
<table>
<tr>
<td>A</td>
<t... | [
"My approach it to create the item, fill it with the data i have on this page, then yield a request for the page with missing data, passing the item within meta. When the second page is downloaded i get the item from meta and fill with the other data:\ndef parseItem(self, response):\n '''Get date from the first ... | [
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0007944802_python_scrapy_web_crawler.txt |
Q:
django templatetag
am looking for a django templatetag that will count words and substring a whole paragraph without chopping off words. Is there a built in function? I tried looking into the built-in function list at Django template documentation but couldn't find anything.
Please advice?
A:
As far as I am awa... | django templatetag | am looking for a django templatetag that will count words and substring a whole paragraph without chopping off words. Is there a built in function? I tried looking into the built-in function list at Django template documentation but couldn't find anything.
Please advice?
| [
"As far as I am aware there is not built-in tag to do this. Depending on the nature of the words you want (they aren't inside, or part of a for-loop - although even then you could just do this recursively) you could just do what you want in the views.py and pass the output as a variable to the template?\nSo you'd d... | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004707008_django_python.txt |
Q:
Method entry points in a class variable
How can I go about installing as a class variable a table that contains the entry points to the methods?
For clarification, consider the following -working- code:
class A(object):
def go(self, n):
method = self.table[n]
method(self)
def add(self):
... | Method entry points in a class variable | How can I go about installing as a class variable a table that contains the entry points to the methods?
For clarification, consider the following -working- code:
class A(object):
def go(self, n):
method = self.table[n]
method(self)
def add(self):
print "add"
def multiply(self):
... | [
"It already contains one. It's called __dict__.\nclass foo(object):\n def go(self, method):\n getattr(self, method)()\n\n def a(self):\n ...\n\n def b(self):\n ...\n\nIf you reaaaally want numeric indices, you can do e.g.\nclass foo(object):\n methods = { 1: 'a', 2: 'b' }\n def g... | [
6,
1
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0007967200_python_python_2.x.txt |
Q:
What is the most preferred way to pass object attributes to a function in Python?
I am certain I am doing this "incorrectly" even though it works. Right now when I call a function I just pass the whole object i.e.
class my_file_obj:
def __init__(self,filename):
self.filename = filename
self.o... | What is the most preferred way to pass object attributes to a function in Python? | I am certain I am doing this "incorrectly" even though it works. Right now when I call a function I just pass the whole object i.e.
class my_file_obj:
def __init__(self,filename):
self.filename = filename
self.owner = None
self.file_type = None
self.fileflag = 0
self.md5 = ... | [
"Well, it's quite obvious. It depends on whether some_function needs the whole object or just the filename, in which case you pass the whole my_file_obj instance or just the filename.\n",
"I think some_function(file_obj1) is the most pythonic.\nsome_function(file_obj1.filename) doesn't pass the object to the func... | [
5,
0,
0,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007967146_oop_python.txt |
Q:
How to access model attributes in custom manager?
I have a Django model for an object with a DateField. I also have two managers that filter these objects for a specific date range.
class SchoolYearManager(models.Manager):
def get_query_set(self):
now = datetime.datetime.now()
current_year = no... | How to access model attributes in custom manager? | I have a Django model for an object with a DateField. I also have two managers that filter these objects for a specific date range.
class SchoolYearManager(models.Manager):
def get_query_set(self):
now = datetime.datetime.now()
current_year = now.year
start_date = datetime.date(current_year,... | [
"How could this work? What event date could it be referring to? When you call Event.past_school_year_events.all(), you don't have a model instance. self.model, as the name implies, refers to the model class. So how could it know what date you mean?\nI can't actually work out what it is you're trying to do - where y... | [
1
] | [] | [] | [
"django",
"django_models",
"filter",
"python"
] | stackoverflow_0007967476_django_django_models_filter_python.txt |
Q:
HTML/Javascript/CSS GUI for the development of desktop applications with python?
I wonder if there's a python GUI like pyqt etc. which works purely with html and javascript for layouting desktop applications...
Do you know if there are projects like this? Does this make sense at all ;-) Or it it just me finding th... | HTML/Javascript/CSS GUI for the development of desktop applications with python? | I wonder if there's a python GUI like pyqt etc. which works purely with html and javascript for layouting desktop applications...
Do you know if there are projects like this? Does this make sense at all ;-) Or it it just me finding that a nice tool...
| [
"If it were Python-based but had nothing to do with Python, would you really care if it wasn't Python based?\nAnyways, yes, a project exists. A pretty big one too. It's called XULRunner. The project is maintained by Mozilla and is used for the GUI of every Mozilla program.\nIt features an XML-based syntax (XUL):\n<... | [
10,
2,
0
] | [] | [] | [
"css",
"html",
"python",
"user_interface"
] | stackoverflow_0007967575_css_html_python_user_interface.txt |
Q:
match numbers if line starts with keyword
I've got a file that looks like this:
foo: 11.00 12.00 bar 13.00
bar: 11.00 12.00 bar
foo: 11.00 12.00
and would like to extract all numbers in lines beginning with the keyword "foo:". Expected result:
['11.00', '12.00', '13.00']
['11.00', '12.00']
Now, this is easy, if... | match numbers if line starts with keyword | I've got a file that looks like this:
foo: 11.00 12.00 bar 13.00
bar: 11.00 12.00 bar
foo: 11.00 12.00
and would like to extract all numbers in lines beginning with the keyword "foo:". Expected result:
['11.00', '12.00', '13.00']
['11.00', '12.00']
Now, this is easy, if I use two regexes, like this:
if re.match(... | [
"Not exactly what you asked for, but since it's recommended to use standard Python tools instead of regexes where possible, I'd do something like this:\nimport re\n\nwith open('numbers.txt', 'r') as f:\n [re.findall(r'\\d+\\.\\d+', line) for line in f if line.startswith('foo')]\n\nUPDATE\nAnd this will return th... | [
4,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007966939_python_regex.txt |
Q:
Is there an easy way to manipulate XML documents in Python?
I have done a little research around the matter, but haven't really been able to come up with anything useful. What I need is to not just parse and read, but actually manipulate XML documents in python, similar to the way JavaScript is able to manipulate... | Is there an easy way to manipulate XML documents in Python? | I have done a little research around the matter, but haven't really been able to come up with anything useful. What I need is to not just parse and read, but actually manipulate XML documents in python, similar to the way JavaScript is able to manipulate HTML documents.
Allow me to give an example. say I have the fol... | [
"If you want to avoid installing lxml.etree, you can use xml.etree from the standard library.\nHere is Acorn's answer ported to xml.etree:\nimport xml.etree.ElementTree as et # was: import lxml.etree as et\n\nxmltext = \"\"\"\n<root>\n <fruit>apple</fruit>\n <fruit>pear</fruit>\n <fruit>mango</fruit>\n ... | [
14,
12
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0007967082_python_xml.txt |
Q:
Restricting access to static files in Python App Engine
I would like to restrict access to static *html and other files on google app engine. The reason that I want to do this is because a considerable amount of my application is written in the javascript that is delivered with the HTML files and I only want auth... | Restricting access to static files in Python App Engine | I would like to restrict access to static *html and other files on google app engine. The reason that I want to do this is because a considerable amount of my application is written in the javascript that is delivered with the HTML files and I only want authorized people to have access to this code.
I would also like ... | [
"The point of using static handlers is to be able to serve files without spinning up an instance of your Python app. If you need custom authentication logic to run first, static handlers won't work.\nAs for real-world applications, I think most people just accept that their Javascript and HTML aren't protectable. P... | [
4
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0007962326_authentication_google_app_engine_python.txt |
Q:
Using annotate on list
Currently, I have a view that shows all my investments maturing within the next 5 years, for each client. What I would like to do is show the total for each financial institution, displayed like:
Institution | Amount | Maturity Amount
TD | 1000 | 1250
Scotia | 1203 | 9383
etc
This is m... | Using annotate on list | Currently, I have a view that shows all my investments maturing within the next 5 years, for each client. What I would like to do is show the total for each financial institution, displayed like:
Institution | Amount | Maturity Amount
TD | 1000 | 1250
Scotia | 1203 | 9383
etc
This is my code for showing the next ... | [
"It looks like you might be able to get your database calculate this for you.\nIn SQL this might look something like:\nSELECT sum(investment.amount)\nFROM investment, maturity_date\nWHERE investment.id = maturity_date.investment_id and year=%s\nGROUP BY investment.amount\n\nHave a look at Django's documentation for... | [
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007967768_django_django_templates_django_views_python.txt |
Q:
How to import external Python script?
I am writing a game engine in Python and the thing is I am not sure how to handle external scripts (think source engine mods, LUA). Every scene, entity in a game can have custom script attached to it, but game engine is not aware of those scripts until the scene is being loade... | How to import external Python script? | I am writing a game engine in Python and the thing is I am not sure how to handle external scripts (think source engine mods, LUA). Every scene, entity in a game can have custom script attached to it, but game engine is not aware of those scripts until the scene is being loaded. For example there could be a script, whi... | [
"You can use __import__() for this. Say your entity has a script attribute that can be either None or the name of a script (that is in a known location, which is on sys.path), you could use the following code to run the main() function from that script:\nif entity.script is not None:\n custom_script = __import_... | [
0,
0,
0
] | [] | [] | [
"external",
"import",
"python"
] | stackoverflow_0007958537_external_import_python.txt |
Q:
urlpatterns don't get updated after DB insertion?
I'm having an html form which inserts data into one table called srv.
I've built the urls.py in such a way to capture every insertion:
for item in srv.objects.all():
linkSrv = item.loc.lower() + '/srv/' + item.subctg.lower() + '/' + item.title.lower()
urlpa... | urlpatterns don't get updated after DB insertion? | I'm having an html form which inserts data into one table called srv.
I've built the urls.py in such a way to capture every insertion:
for item in srv.objects.all():
linkSrv = item.loc.lower() + '/srv/' + item.subctg.lower() + '/' + item.title.lower()
urlpatterns += patterns('',
url(r'^' + linkSrv + '/$', '... | [
"You should just use something like this:\nurlpatterns += patterns('',\n url(r'^(?P<loc>\\w+)/(?P<subctg>\\w+)/(?P<title>\\w+)/$',\n 'beta.views.queryFromIndexDeep'),\n)\n\nUsing regular expressions to match your view is way easier, and recommended. In your view, the above would match a f... | [
2,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0007967902_django_django_urls_python.txt |
Q:
How to delete record in Sqlite
I'm learning Python with the tutorial app from Flask and I can't figure how to reference a certain row in the database. I m trying to delete a record by using the delete link in the template.I spent a whole day trying everything I could find and to really understand this. I know it's... | How to delete record in Sqlite | I'm learning Python with the tutorial app from Flask and I can't figure how to reference a certain row in the database. I m trying to delete a record by using the delete link in the template.I spent a whole day trying everything I could find and to really understand this. I know it's simple but I don't get it!
Here's t... | [
"Sebastien the delete_entry function is deleting the last entry in the db \nwhere id=(select max(id)from entries)\nWhat you have to do is insert a parameter in the url for deletion like '/delete/:id' where the id is the id of the entry you want deleted, then change the template to generate the url as so:\n<a href=\... | [
5
] | [] | [] | [
"flask",
"jinja2",
"python",
"sqlite"
] | stackoverflow_0007968167_flask_jinja2_python_sqlite.txt |
Q:
Create (k, v1, ..., vn) tuples based on matching dict keys
I'm using Python 2.6, and I have two datasets, each being a list of dictionaries. The two datasets look like this:
[{'foo': 3}, {'bar': 4}]
[{'bar': 1}, {'foo': 8}]
From these two datasets, I want to create a single list of tuples that would look like thi... | Create (k, v1, ..., vn) tuples based on matching dict keys | I'm using Python 2.6, and I have two datasets, each being a list of dictionaries. The two datasets look like this:
[{'foo': 3}, {'bar': 4}]
[{'bar': 1}, {'foo': 8}]
From these two datasets, I want to create a single list of tuples that would look like this for the input data:
[('foo', 3, 8), ('bar', 4, 1)]
It is imp... | [
"You can use a defaultdict:\nfrom collections import defaultdict\n\ndatasets = [{'foo': 3}, {'bar': 4}], [{'bar': 1}, {'foo': 8}] \n\nresult = defaultdict(list)\n\nfor dataset in datasets:\n for eachdict in dataset:\n for key, value in eachdict.iteritems():\n result[key].append(value)\n\n# t... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0007968039_python.txt |
Q:
When and how is a many-to-many relationship created when saving a model?
I have a set of document objects and label objects, and I want those two objects to be linked. It's a typical many-to-many relationship. I have the following code:
Models.py:
class Document(models.Model):
title = models.CharField(max_leng... | When and how is a many-to-many relationship created when saving a model? | I have a set of document objects and label objects, and I want those two objects to be linked. It's a typical many-to-many relationship. I have the following code:
Models.py:
class Document(models.Model):
title = models.CharField(max_length=50, unique=True)
title_slug = models.SlugField(max_length=50, unique=Tr... | [
"As other people said, you cannot save in one-shot Document object and its ManyToMany field, because django create \"intermediatary join table\", which need the Document object's ID, which is not defined at that point.\nThere is a save_m2m function in ModelForm, that is supposed to be called by the Form itself, as ... | [
4,
2,
2,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007683207_django_django_models_python.txt |
Q:
How do I use python for web development without relying on a framework?
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing python.
The only thing I have found so far that lets me do... | How do I use python for web development without relying on a framework? | I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing python.
The only thing I have found so far that lets me do this in the most obvious way possible is web.py but I have slight concerns o... | [
"The way to go is wsgi.\nWSGI is the Web Server Gateway Interface. It is a specification for web servers and application servers to communicate with web applications (though it can also be used for more than that). It is a Python standard, described in detail in PEP 333. \nAll current frameworks support wsgi. A lot... | [
39,
19,
9,
8,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"performance",
"python",
"web.py"
] | stackoverflow_0000596729_performance_python_web.py.txt |
Q:
How to remove a menu item from Gedit from a plugin
I developed a plugin to replace some functionality in Gedit. This functionality is presented through one menu item.
How could I remove the current menu item to add a identical new one, except that this new menu item will be bound to my callback?
A:
I didn't try ... | How to remove a menu item from Gedit from a plugin | I developed a plugin to replace some functionality in Gedit. This functionality is presented through one menu item.
How could I remove the current menu item to add a identical new one, except that this new menu item will be bound to my callback?
| [
"I didn't try it on existing applications, but in general it boils down to the following steps.\n\nGet the UIManager: GObject.property(type=Gedit.Window).get_ui_manager().\nAcquire the current UI definition using UIManager.get_ui. Use this to determine which item to remove.\nRetrieve the item using Builder.get_obje... | [
1
] | [] | [] | [
"gedit",
"gtk",
"menuitem",
"pygtk",
"python"
] | stackoverflow_0007959951_gedit_gtk_menuitem_pygtk_python.txt |
Q:
receiving 401 errors inconsistently from python urllib2.urlopen call
I have a python script that makes a series of url calls using urllib2. The url is on http, but requires authentication. I am currently trying to run the script such that it will make over 100 calls. Every time I run the script, some calls fail... | receiving 401 errors inconsistently from python urllib2.urlopen call | I have a python script that makes a series of url calls using urllib2. The url is on http, but requires authentication. I am currently trying to run the script such that it will make over 100 calls. Every time I run the script, some calls fail with error code 401, and some pass. All calls are for the same URL using... | [
"The code looks correct to me, so I don't see the issue.\nHere are a few thoughts on how to proceed:\n\nI usually work-out the http requests at the command line using curl before translating it into a script.\nThe requests library is easier to use than urllib2\nWhen you receive a response, print out the headers so ... | [
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0007968481_python_urllib2.txt |
Q:
Listening for a particular pattern
I use the following listener to listen to a particular pattern. I expects to find "hello" somewhere among the data being sent to it. The process method is called many times each second so there's no idea in saving all the data processed in an ever growing list. Is there a nicer w... | Listening for a particular pattern | I use the following listener to listen to a particular pattern. I expects to find "hello" somewhere among the data being sent to it. The process method is called many times each second so there's no idea in saving all the data processed in an ever growing list. Is there a nicer way to do this?
class Listener:
def _... | [
"Perhaps something like this:\nclass Listener:\n def __init__(self, data_to_catch):\n self.data_to_catch = data_to_catch\n self.data = \"\"\n self.found = False\n self.pos = 0\n\n def process(self, data):\n if self.found:\n return\n\n self.data += data\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007968370_python.txt |
Q:
Namespace, argparse, and usage
This is really a few questions:
Is there a reason argparse uses a namespace instead of a dictionary?
Assuming I have a class with __init__(self, init_method, *args). The init_method parameter tells the init_function which way I want to initialize the class, while arg parameter gives... | Namespace, argparse, and usage | This is really a few questions:
Is there a reason argparse uses a namespace instead of a dictionary?
Assuming I have a class with __init__(self, init_method, *args). The init_method parameter tells the init_function which way I want to initialize the class, while arg parameter gives all the arguments neccesary for the... | [
"It is easy to convert a Namespace into a dictionary using vars():\n>>> vars(args)\n\n",
"\nThe designers of arparse apparently felt it would be more convenient to access arguments as\nargs.arg_name\n\nrather than\nargs[\"arg_name\"]\n\nThis might be a matter of taste, though. I would have happily gone with the ... | [
69,
19
] | [] | [] | [
"argparse",
"namespaces",
"python"
] | stackoverflow_0007968697_argparse_namespaces_python.txt |
Q:
How to best utilize the hist() to show a cumulative and normed histogram?
I have a problem while dealing with a data set which the value range from 0 to tens of thousand. And there is no problem to show the histogram of the whole data set using hist(). However, if I only want to show the cumulative and normed deta... | How to best utilize the hist() to show a cumulative and normed histogram? | I have a problem while dealing with a data set which the value range from 0 to tens of thousand. And there is no problem to show the histogram of the whole data set using hist(). However, if I only want to show the cumulative and normed detailed histogram using say x = [0, 120], I have to use 600000 bins to assure the ... | [
"You can set bins to a list, not an integer, e.g., bins=[1,2,3,..,120,30000,60000]. \nTo answer your commnet below, here is an excerpt from the documentation:\n\nbins:\nEither an integer number of bins or a sequence giving the bins. If bins is an integer, bins + 1 bin edges will be returned, consistent with numpy.... | [
1,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007960446_matplotlib_python.txt |
Q:
Default value for field in Django model
Suppose I have a model:
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
Currently I am using the default admin to create/edit objects of this type.
How do I remove the ... | Default value for field in Django model | Suppose I have a model:
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
Currently I am using the default admin to create/edit objects of this type.
How do I remove the field b from the admin so that each object ca... | [
"Set editable to False and default to your default value.\nhttp://docs.djangoproject.com/en/stable/ref/models/fields/#editable\nb = models.CharField(max_length=7, default='0000000', editable=False)\n\nAlso, your id field is unnecessary. Django will add it automatically.\n",
"You can also use a callable in the de... | [
186,
27,
26
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0000755857_django_django_admin_django_models_python.txt |
Q:
Why does creating a neo4j.GraphDatabase from within a Paste app cause a segfault?
The following code causes Java to segfault:
import os.path
import neo4j
from paste import httpserver, fileapp
import tempfile
from webob.dec import wsgify
from webob import Response, Request
HOST = '127.0.0.1'
PORT = 8080
class Deb... | Why does creating a neo4j.GraphDatabase from within a Paste app cause a segfault? | The following code causes Java to segfault:
import os.path
import neo4j
from paste import httpserver, fileapp
import tempfile
from webob.dec import wsgify
from webob import Response, Request
HOST = '127.0.0.1'
PORT = 8080
class DebugApp(object):
@wsgify
def __call__(self, req):
# db = neo4j.GraphData... | [
"The issue is not with Paste per se, but with the neo4j Python bindings, which use JPype. Paste creates threads to handle incoming requests; neo4j is supposed to be thread-safe, but JPype comes with this caveat from the documentation (1):\n\n\"For the most part, python threads based on OS level threads (i.e posix ... | [
3
] | [] | [] | [
"neo4j",
"paste",
"python",
"webob"
] | stackoverflow_0007942423_neo4j_paste_python_webob.txt |
Q:
Finding consecutive values within a list
I have a list of values:
a = [1,3,4,5,2]
I now want the following function:
does_segment_exist(a, [1,3,4]) #True
does_segment_exist(a, [3,4,5]) #True
does_segment_exist(a, [4,5,2]) #True
does_segment_exist(a, [1,4,5]) #False
does_segment_exist(a, [1,3]) #True
does_segment... | Finding consecutive values within a list | I have a list of values:
a = [1,3,4,5,2]
I now want the following function:
does_segment_exist(a, [1,3,4]) #True
does_segment_exist(a, [3,4,5]) #True
does_segment_exist(a, [4,5,2]) #True
does_segment_exist(a, [1,4,5]) #False
does_segment_exist(a, [1,3]) #True
does_segment_exist(a, [1,4]) #False
So the values must be... | [
"You can use a rolling window iterator, in this case one from an old version of the itertools docs:\nfrom itertools import islice\n\ndef window(seq, n=2):\n \"Returns a sliding window (of width n) over data from the iterable\"\n \" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... \"\n it = i... | [
4,
1,
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0007968881_list_python_python_3.x.txt |
Q:
When comparing the values of words in python, why would "Nick" be greater than "George"?
I am studying for an upcoming assignment and trying to figure out what the following program prints:
d = ["Bob", "Tom", "George", "Susan", "Mary"]
n = raw_input("Enter a name: ") # assume user enters Robert
for name in d :
... | When comparing the values of words in python, why would "Nick" be greater than "George"? | I am studying for an upcoming assignment and trying to figure out what the following program prints:
d = ["Bob", "Tom", "George", "Susan", "Mary"]
n = raw_input("Enter a name: ") # assume user enters Robert
for name in d :
if name < n :
print name
print
size = len( d )
i = 0
while i < (size - 1) :
... | [
"They are in dictionary order, so the first letter is the only thing that matters if it isn't the same.\nTo do what you want, use\nvalue=sum([ord(x) for x in name])\n\n"
] | [
5
] | [] | [] | [
"ascii",
"character",
"python"
] | stackoverflow_0007969827_ascii_character_python.txt |
Q:
TypeError: cannot concatenate 'str' and 'list' objects
I have a snippet of code which works:
p = subprocess.Popen('psftp servername'.split(),stdin=subprocess.PIPE, tdout=subprocess.PIPE, shell=True)
p.stdin.write('lcd P:\\ORACLE_UNIX\\Development\n')
p.stdin.write('get //opt//jboss//current//server//default... | TypeError: cannot concatenate 'str' and 'list' objects | I have a snippet of code which works:
p = subprocess.Popen('psftp servername'.split(),stdin=subprocess.PIPE, tdout=subprocess.PIPE, shell=True)
p.stdin.write('lcd P:\\ORACLE_UNIX\\Development\n')
p.stdin.write('get //opt//jboss//current//server//default//conf//DMS.properties\n')
p.stdin.write('bye\n')
p.... | [
"devserver.split() returns a list, which is why you're seeing that error - you're trying to concatenate a string with a list.\nYou could try this instead:\np = subprocess.Popen(['psftp', devserver], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n\n.split() is no longer needed since you already have the... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007969836_python.txt |
Q:
python reading strings
Can anyone help me with the following query
what is the pythonic way to cleanse the following strings:
Lets say I have the word
"abcd
or
'blahblah
then the words actually are
abcd, blahblah
I can think of a basic way.. but actually I am reading a huge text file..
and explicitly writin... | python reading strings | Can anyone help me with the following query
what is the pythonic way to cleanse the following strings:
Lets say I have the word
"abcd
or
'blahblah
then the words actually are
abcd, blahblah
I can think of a basic way.. but actually I am reading a huge text file..
and explicitly writing a code to read char by cha... | [
"You can strip unwanted characters from the beginning and end of a string using the str.strip() method.\n>>> '\"abcd'.strip( '\"\\'' )\n'abcd'\n>>> '\\'blahblah'.strip( '\"\\'' )\n'blahblah'\n>>> print( '\"abcd'.strip( '\"\\'' ) )\nabcd\n>>> print( '\\'blahblah'.strip( '\"\\'' ) )\nblahblah\n\n",
"Looks like you ... | [
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007969761_python_string.txt |
Q:
annotate() adding more than needed
I'm having a small issue with my annotate(sum()) function. Now what I want it to do is show a total for all maturities in the given plan, inside the list. Which for the first one it does. Code below:
#get the invesments maturing this year
for p in plans:
cu... | annotate() adding more than needed | I'm having a small issue with my annotate(sum()) function. Now what I want it to do is show a total for all maturities in the given plan, inside the list. Which for the first one it does. Code below:
#get the invesments maturing this year
for p in plans:
cur_inv = Investment.objects.all().filter(... | [
"You're using += with the total_m* vars but never resetting them to 0 in your loop. They don't automatically reset, just because a new iteration has started.\nFWIW, you should try to optimize your code here. You're generating 6*len(plans) queries, which could be rather costly.\n"
] | [
1
] | [] | [] | [
"annotate",
"django",
"django_views",
"python"
] | stackoverflow_0007969746_annotate_django_django_views_python.txt |
Q:
SSE4a with ctypes in python? (gcc __builtin_popcount)
Here is the sample code
Efficiently find binary strings with low Hamming distance in large set
static inline int distance(unsigned x, unsigned y)
{
return __builtin_popcount(x^y);
}
Is it possible to rewrite the above gcc code in python using ctypes
(prefer... | SSE4a with ctypes in python? (gcc __builtin_popcount) | Here is the sample code
Efficiently find binary strings with low Hamming distance in large set
static inline int distance(unsigned x, unsigned y)
{
return __builtin_popcount(x^y);
}
Is it possible to rewrite the above gcc code in python using ctypes
(preferably Win/*nix compatible)?
TIA!
| [
"The gmpy library can calculate the Hamming distance between two integers. Even though it may be more general than you require, it will be faster than calling code via ctypes.\nDisclaimer: I maintain gmpy.\n"
] | [
3
] | [] | [] | [
"ctypes",
"gcc",
"python",
"sse"
] | stackoverflow_0007962152_ctypes_gcc_python_sse.txt |
Q:
What's the difference between globals(), locals(), and vars()?
What is the difference between globals(), locals(), and vars()? What do they return? Are updates to the results useful?
A:
Each of these return a dictionary:
globals() always returns the dictionary of the module namespace
locals() always returns a... | What's the difference between globals(), locals(), and vars()? | What is the difference between globals(), locals(), and vars()? What do they return? Are updates to the results useful?
| [
"Each of these return a dictionary:\n\nglobals() always returns the dictionary of the module namespace\nlocals() always returns a dictionary of the current namespace\nvars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument.\n\nlocals and vars could ... | [
214
] | [] | [] | [
"python"
] | stackoverflow_0007969949_python.txt |
Q:
GAE: Setting multiple cookies (or a multi-value cookie) with SimpleCookie
I'm using Google App Engine. How do I set either multiple cookies or a multi-value cookie with a single response?
Right now I'm using this code from the URL http://localhost:8085/server/showcookie?emailAddress=myemail@gmail.com&secretCode=1
... | GAE: Setting multiple cookies (or a multi-value cookie) with SimpleCookie | I'm using Google App Engine. How do I set either multiple cookies or a multi-value cookie with a single response?
Right now I'm using this code from the URL http://localhost:8085/server/showcookie?emailAddress=myemail@gmail.com&secretCode=1
C = Cookie.SimpleCookie()
C["emailAddress"] = self.request.get('emailAddress')
... | [
"Using two SimpleCookie objects solves it:\nC1 = Cookie.SimpleCookie()\nC1[\"emailAddress\"] = self.request.get('emailAddress')\nC2 = Cookie.SimpleCookie()\nC2[\"secretCode\"] = self.request.get('secretCode')\nC2[\"secretCode\"][\"path\"] = \"/\"\nself.response.headers.add_header(\"Set-Cookie\", C1.output(header=''... | [
4,
1,
1
] | [] | [] | [
"cookies",
"google_app_engine",
"python"
] | stackoverflow_0007899551_cookies_google_app_engine_python.txt |
Q:
Python's foreach backwards
Does python have a means of doing foreach backwards? I'm hoping to do a filter() (or list comprehension) and reverse a list at the same time, so that I can avoid doing it separately (which I suspect will be slower). I'm using python 2.4 (I have to unfortunately), but I'm also curious w... | Python's foreach backwards | Does python have a means of doing foreach backwards? I'm hoping to do a filter() (or list comprehension) and reverse a list at the same time, so that I can avoid doing it separately (which I suspect will be slower). I'm using python 2.4 (I have to unfortunately), but I'm also curious what the list comprehension solut... | [
"You are looking for the built-in reversed():\n>>> for i in reversed(range(5)):\n... print i\n... \n4\n3\n2\n1\n0\n\nThis iterates over the sequence in reverse, without creating an additional copy of your list.\n",
"It is not the right way to do it in the same time with filtering. Just use reverse, it will be... | [
29,
2,
-1
] | [] | [] | [
"foreach",
"python",
"python_2.4"
] | stackoverflow_0007969841_foreach_python_python_2.4.txt |
Q:
Simplifying Django views form handling logic
Just a shot in the dark, but maybe someone is able to suggest something interesting.
Whenever I have forms in my view, there are a lot of if-else statements, and it is hard to follow the logic. Is there some pattern or python language feature to simplify this? I've had ... | Simplifying Django views form handling logic | Just a shot in the dark, but maybe someone is able to suggest something interesting.
Whenever I have forms in my view, there are a lot of if-else statements, and it is hard to follow the logic. Is there some pattern or python language feature to simplify this? I've had this problem for as long as I can remember, and fo... | [
"Have you had a look at Class Based Views (new in 1.3). You write your views as classes and inherit the necessary funcionality from multiple base views and also mixins. This means you can break your views out into their constituant parts and have nice code separation:\nhttps://docs.djangoproject.com/en/dev/topics/c... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007968259_django_python.txt |
Q:
Arbitrary python names with slashes in import statement
Gone through related questions,but cannot find this specific answer.
We're embedding python into our application, and have added a hook to sys.meta_path
to allow the import of arbitrarily named modules.
(That is, module definitions do not reside on disk, but ... | Arbitrary python names with slashes in import statement | Gone through related questions,but cannot find this specific answer.
We're embedding python into our application, and have added a hook to sys.meta_path
to allow the import of arbitrarily named modules.
(That is, module definitions do not reside on disk, but are defined in memory within the package).
This allows things... | [
"Well, an obvious workaround would be to use some different character in the sources, e.g. pipe, and have your hook replace such characters with slashes. Depending on what exactly you need that would be more or less painful, though.\nE.g.\nimport lol|foo\n\nwhere the first line of your hook looks like\nmodule_name... | [
0
] | [] | [] | [
"import",
"names",
"python",
"syntax"
] | stackoverflow_0007969051_import_names_python_syntax.txt |
Q:
Python Regular Expression OR not matching
For some reason,
m = re.search('(<[^pib(strong)(br)].*?>|</[^pib(strong)]>)', '</b>')
matches the string, but
m = re.search('(</[^pib(strong)]>)', '</b>')
does not. I am trying to match all tags that are not
<p>, <b>, </p>, </b>
and so on. Am I misunderstanding somethin... | Python Regular Expression OR not matching | For some reason,
m = re.search('(<[^pib(strong)(br)].*?>|</[^pib(strong)]>)', '</b>')
matches the string, but
m = re.search('(</[^pib(strong)]>)', '</b>')
does not. I am trying to match all tags that are not
<p>, <b>, </p>, </b>
and so on. Am I misunderstanding something about how '|' works?
| [
"You're doing it wrong. First of all, characters between [] are matched differently: [ab] will match either a or b, so in your case [^pib(strong)] will match everything that is not a p, an i, a b, a (, etc. (note the negation from ^). Your first regex matching is merely a coincidence.\nAlso, you shouldn't be parsin... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007970070_python_regex.txt |
Q:
Gmail IMAP Authentication -- imaplib.authenticate takes exactly 3 args (4 given)
I'm trying to enable Gmail IMAP access from my web application. Right now, users can grant access to the web application, successfully retrieving and storing the user's token and secret. But, when I try to authenticate the IMAP conn... | Gmail IMAP Authentication -- imaplib.authenticate takes exactly 3 args (4 given) | I'm trying to enable Gmail IMAP access from my web application. Right now, users can grant access to the web application, successfully retrieving and storing the user's token and secret. But, when I try to authenticate the IMAP connection for retrieving emails, it gives the following error:
TypeError: authenticate() ... | [
"When using oauth2 for IMAP, you need to use it in conjunction with oauth2.clients.imap, so:\nimport oauth2 as oauth\nimport oauth2.clients.imap as imaplib\n\n# the rest of your code as it was\n\nYou can see an example towards the bottom of this page: https://github.com/simplegeo/python-oauth2\n",
"The authentica... | [
2,
1
] | [] | [] | [
"gmail",
"oauth",
"python"
] | stackoverflow_0007963820_gmail_oauth_python.txt |
Q:
How can I make a regular expression to extract all anchor tags or links from a string?
I've seen other questions which will parse either all plain links, or all anchor tags from a string, but nothing that does both.
Ideally, the regular expression will be able to parse a string like this (I'm using Python):
>>> im... | How can I make a regular expression to extract all anchor tags or links from a string? | I've seen other questions which will parse either all plain links, or all anchor tags from a string, but nothing that does both.
Ideally, the regular expression will be able to parse a string like this (I'm using Python):
>>> import re
>>> content = '
<a href="http://www.google.com">http://www.google.com</a> Some o... | [
"Usually you should never parse HTML with regular expressions since HTML isn't a regular language. Here it seems you only want to get all the http-links either they are in an A element or in text. How about getting them all and then remove the duplicates?\nTry something like\nset(re.findall(\"(http:\\/\\/.*?)[\\\"'... | [
1,
1,
0,
0
] | [
"No, it will not be able to parse string like this. Regexp are capable of simple matching and you can't handle parsing a complicated grammar as html just with one or two regexps.\n"
] | [
-1
] | [
"python",
"regex"
] | stackoverflow_0007969946_python_regex.txt |
Q:
Count letters in text
I have text file as follows...
s1
MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP
MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ
FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD
s2
MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP
LRD... | Count letters in text | I have text file as follows...
s1
MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP
MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ
FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD
s2
MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP
LRDLLMFPMEDISISVIGRQRRTVQSTVPE... | [
"total = 0\nfor line in infile:\n line = line.strip(\"\\n\")\n if line.startswith('>'):\n name = line\n else:\n pattern = line.count('P') \n total += pattern\n print '%s:%s' %(name,pattern)\n\n#this goes outside the for loop\nout.write('%s:%s\\n' %(name,total))\n\n",
"Don't pa... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007970672_python.txt |
Q:
Why does 4 < '3' return True in Python 2?
Why does 4 < '3' return True in Python 2?
Is it because when I place single quotes around a number Python sees it as a string and strings are bigger than numbers?
A:
Yes, any number will be less than any string (including the empty string) in Python 2.
In Python 3, you c... | Why does 4 < '3' return True in Python 2? | Why does 4 < '3' return True in Python 2?
Is it because when I place single quotes around a number Python sees it as a string and strings are bigger than numbers?
| [
"Yes, any number will be less than any string (including the empty string) in Python 2.\nIn Python 3, you can't make arbitrary comparisons. You'll get a TypeError.\n\nFrom the link in eryksun's comment:\nif (PyNumber_Check(v))\n vname = \"\";\nelse\n vname = v->ob_type->tp_name;\nif (PyNumber_Check(w))\n ... | [
31,
7
] | [
"The default comparison operation in cpython 2 is based on the memory address of the object in question. From type_richcompare() in python 2.7:\n/* Compare addresses */\nvv = (Py_uintptr_t)v;\nww = (Py_uintptr_t)w;\nswitch (op) {\ncase Py_LT: c = vv < ww; break;\ncase Py_LE: c = vv <= ww; break;\ncase Py_EQ: c = ... | [
-1
] | [
"comparison",
"operators",
"python",
"python_2.x"
] | stackoverflow_0007969552_comparison_operators_python_python_2.x.txt |
Q:
wxPython: using Show() and Hide()
I'm working on a simple program that collects and checks user-input. In addition to displaying
a message box if the user-supplied input fails the checks, I'd also like to add a prompt
just to the right of the input field telling the user what type of data is required. To accomplis... | wxPython: using Show() and Hide() | I'm working on a simple program that collects and checks user-input. In addition to displaying
a message box if the user-supplied input fails the checks, I'd also like to add a prompt
just to the right of the input field telling the user what type of data is required. To accomplish this I've created a single-row FlexGr... | [
"EDIT: For the new question(s), I would use pubsub to solve this. Put a listener the init of the MyDialog class and then publish a message to it when the Validate method is run in the other class. In the message handler that you will theoretically create in MyDialog, you'll want Show your other widget and call Layo... | [
3
] | [] | [] | [
"hide",
"python",
"show",
"validation",
"wxpython"
] | stackoverflow_0007970296_hide_python_show_validation_wxpython.txt |
Q:
write() creating partially readable / corrupt files
I have a long string (DNA sequence with \n at regular intervals) that I'm trying to write to a file.
Writing with the code below, I have a file that cannot be fully accessed by getline in a C++ program- that is, istream seems to think the file only has about a d... | write() creating partially readable / corrupt files | I have a long string (DNA sequence with \n at regular intervals) that I'm trying to write to a file.
Writing with the code below, I have a file that cannot be fully accessed by getline in a C++ program- that is, istream seems to think the file only has about a dozen lines. Likewise, if I do cat or more on the file I o... | [
"Used ghex to discover my source file was using carriage returns (\\r) instead of newline (\\n) characters. \n",
"Perhaps your C++ program don't flush the output stream enough. Or perhaps there is a null byte somewhere...\n"
] | [
2,
0
] | [] | [] | [
"file_io",
"linux",
"python"
] | stackoverflow_0007930446_file_io_linux_python.txt |
Q:
How can I ensure that one of my class's methods is always called even if a subclass overrides it?
For example, I have a
class BaseHandler(object):
def prepare(self):
self.prepped = 1
I do not want everyone that subclasses BaseHandler and also wants to implement prepare to have to remember to call
supe... | How can I ensure that one of my class's methods is always called even if a subclass overrides it? | For example, I have a
class BaseHandler(object):
def prepare(self):
self.prepped = 1
I do not want everyone that subclasses BaseHandler and also wants to implement prepare to have to remember to call
super(SubBaseHandler, self).prepare()
Is there a way to ensure the superclass method is run even if the su... | [
"I have solved this problem using a metaclass.\nUsing a metaclass allows the implementer of the BaseHandler to be sure that all subclasses will call the superclasses prepare() with no adjustment to any existing code.\nThe metaclass looks for an implementation of prepare on both classes and then overwrites the subcl... | [
16,
4,
3,
2,
0
] | [] | [] | [
"python",
"subclass"
] | stackoverflow_0007970200_python_subclass.txt |
Q:
How to create/list events in calendars other than default using Google's API for Python?
Using the gdata API for Python, how do I create or list events in a calendar other than the default one?
A:
You have to get the url of the custom calendar you want to read/write to, and supply it in the event query. This is ... | How to create/list events in calendars other than default using Google's API for Python? | Using the gdata API for Python, how do I create or list events in a calendar other than the default one?
| [
"You have to get the url of the custom calendar you want to read/write to, and supply it in the event query. This is what I came up with:\n#define cal_client:\nself.cal_client = gdata.calendar.client.CalendarClient(source='Milosz-GCal-1.0')\n#initiate calendar service (log in):\nself.cal_client.ClientLogin(email, p... | [
0
] | [] | [] | [
"gdata_api",
"google_calendar_api",
"python"
] | stackoverflow_0007877181_gdata_api_google_calendar_api_python.txt |
Q:
Matlab to Python Conversion
I am trying to convert some code from Matlab to Python, but I am unfamiliar with a considerable amount of the Matlab syntax and functionality. I have managed to do a some of the conversion using the PIL and Numpy python package, but I was hoping someone would be able to explain what is ... | Matlab to Python Conversion | I am trying to convert some code from Matlab to Python, but I am unfamiliar with a considerable amount of the Matlab syntax and functionality. I have managed to do a some of the conversion using the PIL and Numpy python package, but I was hoping someone would be able to explain what is going on with some elements of th... | [
"How about getting start with this page http://www.scipy.org/NumPy_for_Matlab_Users? Also if you have brief description of what this is supposed to do, that would be good\n",
"You're correct: FFT_LF(:,:,i,j) refers to a multidimensional array. In this case, FFT_LF is a 4-D array, but the calculations result in... | [
4,
0
] | [] | [] | [
"matlab",
"numpy",
"python",
"scipy",
"translation"
] | stackoverflow_0007960761_matlab_numpy_python_scipy_translation.txt |
Q:
Migration to GAE
What is the best way to migrate MySQL tables to Google Datastore and create python models for them?
I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. C... | Migration to GAE | What is the best way to migrate MySQL tables to Google Datastore and create python models for them?
I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for th... | [
"In general, generating your models automatically shouldn't be too difficult. Suppose you have a csv file for each table, with lines consisting of (field name, data type), then something like this would do the job:\n# Maps MySQL types to Datastore property classes\ntype_map = {\n 'char': 'StringProperty',\n '... | [
4,
2,
1,
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001489886_django_google_app_engine_google_cloud_datastore_python.txt |
Q:
Accessing QTextHtmlImporter in PyQt4
I'm writing a cross platform app in PyQt4. For a particular feature, I would like to access the QTextHtmlImporter class of Qt4. There is no direct python adapter class available in PyQt4. The class is part of the src/gui/text/qtextdocumentfragment_p.h file. Is there any way... | Accessing QTextHtmlImporter in PyQt4 | I'm writing a cross platform app in PyQt4. For a particular feature, I would like to access the QTextHtmlImporter class of Qt4. There is no direct python adapter class available in PyQt4. The class is part of the src/gui/text/qtextdocumentfragment_p.h file. Is there any way I can access that in Python?
I would like... | [
"QTextHtmlImporter isn't even part of the Qt4 API, so the short answer is: no, there's no way to access it in PyQt4.\nYou could, of course, attempt to port the code to PyQt4, but I'm guessing that would be a non-trivial task.\nThe question is: why do you think you need to do this?\nWhy can't you use QTextCursor.ins... | [
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0007971095_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Python: printing dictionary of dictionary with variables
I'm trying to retrieve some values from a dictionary, should be fairly easy.
For whatever reason, I cannot use a variable to retrieve a value.
I have two dictionaries, one with a mapping of uids -> usernames (via getent passwd), and a second dictionary which... | Python: printing dictionary of dictionary with variables | I'm trying to retrieve some values from a dictionary, should be fairly easy.
For whatever reason, I cannot use a variable to retrieve a value.
I have two dictionaries, one with a mapping of uids -> usernames (via getent passwd), and a second dictionary which contains a dictionary for each key, basically:
dMap = { 12345... | [
"The keys in dMap are integers, but in qDict the keys are strings.\nYou need to convert your integer k to a string before using it as a key in qDict:\nfor k in dMap:\n print 'Key: ',k\n print qDict[str(k)]\n\n",
"You built the two dictionaries using different types for the keys. One dict has an integer key... | [
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007971309_dictionary_python.txt |
Q:
Nested try statements in python?
Is there a nicer way of doing the following:
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
It looks pretty nasty and I'd rather not do:
if ha... | Nested try statements in python? | Is there a nicer way of doing the following:
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
It looks pretty nasty and I'd rather not do:
if hasattr(a, 'method1'):
a.method1()
e... | [
"A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts\ndef something(a):\n for methodname in ['method1', 'method2', 'method3']:\n try:\n m = getattr(a, methodname)\n... | [
26,
22,
5,
4,
3,
1
] | [] | [] | [
"python",
"try_catch"
] | stackoverflow_0000701466_python_try_catch.txt |
Q:
TypeError in scipy.signal.sepfir2d
I'm attempting to calculate the derivatives of optical flow (as referenced in my previous SO question) and am running into a TypeError when performing the calculation.
I first read the video in using OpenCV and use its optical flow methods to find the velocities. Then I use the s... | TypeError in scipy.signal.sepfir2d | I'm attempting to calculate the derivatives of optical flow (as referenced in my previous SO question) and am running into a TypeError when performing the calculation.
I first read the video in using OpenCV and use its optical flow methods to find the velocities. Then I use the scipy.signal library to run a gaussian fi... | [
"After much testing (looking at the source for sepfir2d didn't help at all), it turns out the issue was in the fact that my velx and vely were using 32-bit floating point primitives, when they needed to be 64-bit. That fixed it.\n"
] | [
1
] | [] | [] | [
"image_processing",
"opencv",
"opticalflow",
"python",
"scipy"
] | stackoverflow_0007968539_image_processing_opencv_opticalflow_python_scipy.txt |
Q:
Turning a tuple of tuples into a dictionary
So I've got tuples inside of tuples, and I would like to turn them into a key: value pair.
((1L, 'I.T.'), (2L, 'Project Management'), (3L, 'Creative'), (4L, 'Programming'), (5L, 'Sales'), (6L, 'Administration'), (7L, 'AV'), (8L, 'Human Resources'), (9L, 'Conference Rooms... | Turning a tuple of tuples into a dictionary | So I've got tuples inside of tuples, and I would like to turn them into a key: value pair.
((1L, 'I.T.'), (2L, 'Project Management'), (3L, 'Creative'), (4L, 'Programming'), (5L, 'Sales'), (6L, 'Administration'), (7L, 'AV'), (8L, 'Human Resources'), (9L, 'Conference Rooms'), (10L, 'Testing'), (11L, 'none'))
How would I... | [
"Just pass it to the dict constructor/function! It can take any iterable of (key, value) tuples and create a dictionary from it.\n>>> x = ((1L, 'I.T.'), (2L, 'Project Management'), (3L, 'Creative'), (4L, 'Programming'), (5L, 'Sales'), (6L, 'Administration'), (7L, 'AV'), (8L, 'Human Resources'), (9L, 'Conference Roo... | [
11,
2
] | [] | [] | [
"python"
] | stackoverflow_0007971914_python.txt |
Q:
How to do getElementsByTagName() using ElementTree?
I've used Python's miniDom library before. It had a useful method that I'm missing in the ElementTree library :
getElementsByTagName('bar')
getElementsByTagName() finds all children of a given name, no
matter how deep, thus working recursively. This is usually g... | How to do getElementsByTagName() using ElementTree? | I've used Python's miniDom library before. It had a useful method that I'm missing in the ElementTree library :
getElementsByTagName('bar')
getElementsByTagName() finds all children of a given name, no
matter how deep, thus working recursively. This is usually good, but
can cause problems if similar nodes exist at mul... | [
"ElementTree uses an XPath subset for selecting nodes within the XML tree. You can use tree.findall( './/bar' ) to find all bar nodes within the tree.\n"
] | [
7
] | [] | [] | [
"getelementsbytagname",
"python",
"xml"
] | stackoverflow_0007971972_getelementsbytagname_python_xml.txt |
Q:
Generate slug field in existing table
I have table with data. Is it possible slug field automatically generated on existing table? Or is there any other alternative? Thanks
Here is my table
A:
Using the slugify template filter, you can write a script, or loop through the objects in the shell.
>>> from django.tem... | Generate slug field in existing table | I have table with data. Is it possible slug field automatically generated on existing table? Or is there any other alternative? Thanks
Here is my table
| [
"Using the slugify template filter, you can write a script, or loop through the objects in the shell.\n>>> from django.template.defaultfilters import slugify\n>>> for obj in MyModel.objects.all():\n... obj.slug = slugify(obj.title)\n... obj.save()\n\n",
"I have a convenience model I use in all projects fo... | [
18,
4,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007971689_django_python.txt |
Q:
Local variable output in a function surprises me
The following program:
a_var = 10
b_var = 15
e_var = 25
def a_func(a_var):
print "in a_func a_var = ",a_var
b_var = 100 + a_var
d_var = 2*a_var
print "in a_func b_var = ",b_var
print "in a_func d_var = ",d_var
print "in a_func e_var = ",e_v... | Local variable output in a function surprises me | The following program:
a_var = 10
b_var = 15
e_var = 25
def a_func(a_var):
print "in a_func a_var = ",a_var
b_var = 100 + a_var
d_var = 2*a_var
print "in a_func b_var = ",b_var
print "in a_func d_var = ",d_var
print "in a_func e_var = ",e_var
return b_var + 10
c_var = a_func(b_var)
Print... | [
"You probably should take a look at variable scoping to understand why things work this way; passed-in parameters will take precedence.\n",
"It's because the parameter to your function is called a_var and this hides the global variable.\nYou call the function as a_func(b_var) so the argument has the value 15.\n",... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007971858_python.txt |
Q:
python generator: unpack entire generator in parallel
Suppose I have a generator whose __next__() function is somewhat expensive and I want to try to parallelize the calls. Where do I throw in the parallization?
To be slightly more concrete, consider this example:
# fast, splitting a file for example
raw_blocks = ... | python generator: unpack entire generator in parallel | Suppose I have a generator whose __next__() function is somewhat expensive and I want to try to parallelize the calls. Where do I throw in the parallization?
To be slightly more concrete, consider this example:
# fast, splitting a file for example
raw_blocks = (b for b in block_generator(fin))
# slow, reading blocks, c... | [
"No. You must call next() sequentially because any non-trivial generator's next state is determined by its current state.\ndef gen(num):\n j=0\n for i in xrange(num):\n j += i\n yield j\n\nThere's no way to parallelize calls to the above generator without knowing its state at each point it yield... | [
6,
6
] | [] | [] | [
"generator",
"parallel_processing",
"python"
] | stackoverflow_0007972295_generator_parallel_processing_python.txt |
Q:
Beautiful Stone Soup case sensitivity on XML tag names
I am attempting to use Beautiful Stone Soup (BSS) to modify existing XML that has case-sensitive tag names. When BSS reads in the XML, it coerces all the tag names to lower case, and I can't find an easy way to recover the original capitalization pattern when ... | Beautiful Stone Soup case sensitivity on XML tag names | I am attempting to use Beautiful Stone Soup (BSS) to modify existing XML that has case-sensitive tag names. When BSS reads in the XML, it coerces all the tag names to lower case, and I can't find an easy way to recover the original capitalization pattern when writing it back out to file. This causes problems downstream... | [
"Have you tried ElementTree instead? Beautiful Soup is great for pulling data out of HTML, no doubt. But ElementTree pretty much sets the bar for Pythonic handling of XML.\nIt has been a while since I needed it, but I don't remember ET doing anything untoward to my tag names.\n"
] | [
2
] | [] | [] | [
"beautifulsoup",
"python",
"xml"
] | stackoverflow_0007972407_beautifulsoup_python_xml.txt |
Q:
Creating JSON in Python and parsing in Java
My application involves sending JSONs from a RESTful Python back-end server to an android device via HTTP requests. However, I keep getting a JsonParseException. Here is how the JSON is created and returned:
articleList = []
obj = Content.objects.filter(id = 332).values(... | Creating JSON in Python and parsing in Java | My application involves sending JSONs from a RESTful Python back-end server to an android device via HTTP requests. However, I keep getting a JsonParseException. Here is how the JSON is created and returned:
articleList = []
obj = Content.objects.filter(id = 332).values()[0]
articleList.append(obj)
data = {'articl... | [
"Pasting the JSON String you've provided into a String of a Java program, works - due to the fact that quotation marks (acting as String notation termination characters) are escaped. These quotation marks should hoever not be escaped, when reading the JSON from an external resource (a Stream, document or similar), ... | [
2
] | [] | [] | [
"android",
"gson",
"java",
"json",
"python"
] | stackoverflow_0007972372_android_gson_java_json_python.txt |
Q:
Keeping count in recursive function
I'm trying to figure out how to write a recursive function (with only one parameter) that returns the number of times the substring “ou” appears in the string. Where I'm confused at is that I'm not allowed to use any built-in string functions other than len, or the string operat... | Keeping count in recursive function | I'm trying to figure out how to write a recursive function (with only one parameter) that returns the number of times the substring “ou” appears in the string. Where I'm confused at is that I'm not allowed to use any built-in string functions other than len, or the string operators [] and [:] for indexing and splicing.... | [
"Very inefficient, but should work:\ndef count_it(target):\n if len(target) < 2:\n return 0\n else:\n return (target[:2] == 'ou') + count_it(target[1:])\n\nSee it working online: ideone\nIt's basically the same idea as the code you posted, except that it moves only one character at a time throug... | [
2,
0
] | [] | [] | [
"counting",
"function",
"python",
"recursion"
] | stackoverflow_0007972398_counting_function_python_recursion.txt |
Q:
Python bottlenecks; Determining optimum chunk size for a file comparison function
I'm writing a file comparison function. I know of filecmp.cmp but in my dataset it is expected that a lot of the files will be the same so I thought rather than comparing each potential match with each other it would be better to imp... | Python bottlenecks; Determining optimum chunk size for a file comparison function | I'm writing a file comparison function. I know of filecmp.cmp but in my dataset it is expected that a lot of the files will be the same so I thought rather than comparing each potential match with each other it would be better to implement a multi-file comparison that can compare them all at once. (Also, since I'm new ... | [
"I suggest you use a binary search methodology to select the size value.\nStart with a large value (one that you know to be too large) and reduce it by half. If it's faster, reduce it by half again. If it's slower, go to the next half interval. Continue until you hit the best value.\n"
] | [
4
] | [] | [] | [
"data_structures",
"optimization",
"performance",
"python",
"python_3.x"
] | stackoverflow_0007972624_data_structures_optimization_performance_python_python_3.x.txt |
Q:
Python app behaving unusually, is URL parameter being cached?
I'm trying Google AppEngine and Python today for the first time and managed to get a simple example running. It worked but something wierd is happening: when a URL parameter value changes, it's not registered unless I restart the app.
In my example belo... | Python app behaving unusually, is URL parameter being cached? | I'm trying Google AppEngine and Python today for the first time and managed to get a simple example running. It worked but something wierd is happening: when a URL parameter value changes, it's not registered unless I restart the app.
In my example below, if I run: http://localhost:8080/?x=hello it will return 'x is he... | [
"You're getting the form value outside the handler, in the module-level code. Obviously, that is defined when the module is first loaded, at the time of the first request. You should be doing that inside the get method.\n",
"You can do something like this to access the parameter value in the handler:\nx = self.re... | [
5,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007964012_google_app_engine_python.txt |
Q:
Pregenerated localized python email templates
I'm working on a simple python based system that sends a verification email to users.
We have users from all over the planet, thus would like to use a localized email template.
What is the pythonic approach to do this?
I thought about just having each email template in... | Pregenerated localized python email templates | I'm working on a simple python based system that sends a verification email to users.
We have users from all over the planet, thus would like to use a localized email template.
What is the pythonic approach to do this?
I thought about just having each email template in a separate file, and load it up based on the local... | [
"You might want to checkout the gettext module for handling language translations of bits of text if you have very complex templates: that would be the Pythonic solution there.\nhttp://docs.python.org/library/gettext.html\nYou might also want to check out the locale module.\nhttp://www.doughellmann.com/PyMOTW/local... | [
0
] | [] | [] | [
"email",
"localization",
"python"
] | stackoverflow_0007972518_email_localization_python.txt |
Q:
How to unzip python eggs?
I'm trying to bundle some egg dependencies when using py2exe and as stated on the py2exe site, it doesn't work with those and I need to unzip them first. I've tried to first run easy_install -m lxml and then easy_install --always-unzip lxml==2.2.2, but it didn't work. Then I tried to set ... | How to unzip python eggs? | I'm trying to bundle some egg dependencies when using py2exe and as stated on the py2exe site, it doesn't work with those and I need to unzip them first. I've tried to first run easy_install -m lxml and then easy_install --always-unzip lxml==2.2.2, but it didn't work. Then I tried to set the unzipping behaviour to defa... | [
"Quick hack/workaround: egg files are just zip files, so you can use the python zipfile module to unzip them. Maybe you could rename the easy_install file to \"easy_install_pre.exe\", and create a new .bat file named \"easy_install.bat\":\neasy_install_pre.exe %1\nunzip_eggs.py %1\n\n",
"The zippped package file ... | [
2,
0
] | [] | [] | [
"easy_install",
"egg",
"py2exe",
"python"
] | stackoverflow_0002019565_easy_install_egg_py2exe_python.txt |
Q:
count of the multiple values in a dictionary python
I have a dictionary where each keys have multiple values.
I am trying to count the total number of values.
For example:
key: 1, value: abc, bcd, egf
key: 2, value: asj,asfah,afhs,jhsafh
so, the total number of values are 3+4 = 7
What is the pythonic way to get t... | count of the multiple values in a dictionary python | I have a dictionary where each keys have multiple values.
I am trying to count the total number of values.
For example:
key: 1, value: abc, bcd, egf
key: 2, value: asj,asfah,afhs,jhsafh
so, the total number of values are 3+4 = 7
What is the pythonic way to get this count.
Thanks
| [
"How about:\nsum(len(val) for val in dictionary.itervalues())\n\nNote that this uses a generator instead of creating a temporary list of lengths.\n",
"You'll want to iterate through all the keys and values in the dictionary, finding the length of each set of values.\nThe following does uses a list comprehension t... | [
7,
4,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007972674_dictionary_python.txt |
Q:
PyGTK - webkit.WebView not working with Ubuntu 11.04
here is code snippets:
import gtk, webkit, os
w = gtk.Window()
w.set_title("Example Editor")
w.connect("destroy", gtk.main_quit)
w.resize(500, 500)
editor = webkit.WebView()
editor.load_html_string("<p>This is a <b>test</b>", "file:///")
editor.set_editable(Tr... | PyGTK - webkit.WebView not working with Ubuntu 11.04 | here is code snippets:
import gtk, webkit, os
w = gtk.Window()
w.set_title("Example Editor")
w.connect("destroy", gtk.main_quit)
w.resize(500, 500)
editor = webkit.WebView()
editor.load_html_string("<p>This is a <b>test</b>", "file:///")
editor.set_editable(True)
def on_action(action):
editor.execute_script(
"... | [
"I have the same issue as described above, however I'm using Ubuntu 11.10 (Gnome3)\nIf I add the content editable=true attribute to the p tag, it works as expected.\nself.editor.load_html_string(\"<p contenteditable=\\\"true\\\">This is a test\", \"file:///\")\n\ncontenteditable=true is inherited, so all child are ... | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"ubuntu_11.04",
"webkit"
] | stackoverflow_0007564651_gtk_pygtk_python_ubuntu_11.04_webkit.txt |
Q:
Writing to Multiple Files in Python
I want to write "print 'hello'" to a bunch of *.py files in the same directory. How do you do that? I've searched all over the Web and SO, and I can't find out how.
Like in pseudo-code, "all files with *.py in a certain directory, open and write 'print 'hello'', close file".
I... | Writing to Multiple Files in Python | I want to write "print 'hello'" to a bunch of *.py files in the same directory. How do you do that? I've searched all over the Web and SO, and I can't find out how.
Like in pseudo-code, "all files with *.py in a certain directory, open and write 'print 'hello'', close file".
I'm sorry, I'm a n00b, I just started lear... | [
"You can use glob:\nimport glob\nfor file in glob.glob(\"*.py\"):\n with open(file, \"a\") as f:\n # f.write(\"print 'hello'\")\n # etc.\n\n",
"Use glob.glob to select files by pattern.\nfrom glob import glob\nfrom os.path import join\n\nfor f in glob(join(DIRECTORY, '*.pyc')):\n # open f and ... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0007973127_python.txt |
Q:
Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle
I need to write a set of wrappers in python around symmetric ciphers (AES,DES, etc) in various modes of operation that allow for crypto agility. Specifically, the code that is calling the wrappers needs to need no know... | Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle | I need to write a set of wrappers in python around symmetric ciphers (AES,DES, etc) in various modes of operation that allow for crypto agility. Specifically, the code that is calling the wrappers needs to need no knowledge for what actually is protecting the data so it can be changed out dynamically
Basically the foll... | [
"Following Kirk, but peeling off at the last minute, let the polymorphic key take care of choosing the right kind of decryptor:\nfoo = MagicalEncryptor()\nfoo.ciphertext = foo.encrypt(data)\nkey = foo.key \n\nbar = key.decryptor()\ndata = bar.decrypt(ciphertext)\n\nIt can create the appropriate decryptor and pass i... | [
1,
0,
0
] | [] | [] | [
"encryption",
"oop",
"python"
] | stackoverflow_0007918446_encryption_oop_python.txt |
Q:
Unicode in Youtube APIs for video search in python
I'm trying to use youtube's data api to search where the search term
includes Chinese characters.
But the search query is not returning correct results.
I'm using python and I just wrote some test code that uses unicode.
In the test code, I hard code a unicode ter... | Unicode in Youtube APIs for video search in python | I'm trying to use youtube's data api to search where the search term
includes Chinese characters.
But the search query is not returning correct results.
I'm using python and I just wrote some test code that uses unicode.
In the test code, I hard code a unicode term, convert it to utf-8, then url
encode it as the search... | [
"I believe the gdata API should take care of formatting query parameters for you. So you shouldn't need to urllib.quote_plus your query manually, and doing so will result in a double-escaped string, leaving you literally searching for a video whose name is a load of percents.\n"
] | [
4
] | [] | [] | [
"python",
"search",
"unicode",
"utf_8",
"youtube_api"
] | stackoverflow_0007962304_python_search_unicode_utf_8_youtube_api.txt |
Q:
How can I install aggdraw after this error?
I am trying to install the aggdraw python library to create high quality graphics but I keep getting this error:
agg22/include/agg_array.h: In member function `agg::int8u*
What is the workaround for this? How can I install it?
A:
You should follow the instructions in ... | How can I install aggdraw after this error? | I am trying to install the aggdraw python library to create high quality graphics but I keep getting this error:
agg22/include/agg_array.h: In member function `agg::int8u*
What is the workaround for this? How can I install it?
| [
"You should follow the instructions in http://www.pocketuniverse.ca/archive/2008/december/11/pil-and-aggdraw/ to patch AGG rather than just have the compiler allow the 64-bit incompatible code to compile.\nHere's one way you could do it in the shell:\ncd /tmp\nsvn co http://svn.effbot.org/public/tags/aggdraw-1.2a3-... | [
10,
3
] | [] | [] | [
"aggdraw",
"graphics",
"python"
] | stackoverflow_0003486187_aggdraw_graphics_python.txt |
Q:
Django - logging unique ID
I am assigning a unique ID to every incoming request and want to this to be automatically included in the logs whenever logging is done (without explicitly including it in all places). I am using a middleware to generate and store this unique ID in a thread local.
I want to modify Djang... | Django - logging unique ID | I am assigning a unique ID to every incoming request and want to this to be automatically included in the logs whenever logging is done (without explicitly including it in all places). I am using a middleware to generate and store this unique ID in a thread local.
I want to modify Django's logging formatter to include... | [
"Use a Filter: the technique is described in this post. Though it refers to IP addresses, you can just as easily use the approach to log your unique request IDs.\n"
] | [
5
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0007963595_django_logging_python.txt |
Q:
Computing persistence number of an integer
I am trying to make a code that does the following:
Multiplying the digits of an integer and continuing the process gives
the surprising result that the sequence of products always arrives at
a single-digit number.
For example:
715 -> 35 -> 15 -> 5
88 -> 64 -> 24... | Computing persistence number of an integer | I am trying to make a code that does the following:
Multiplying the digits of an integer and continuing the process gives
the surprising result that the sequence of products always arrives at
a single-digit number.
For example:
715 -> 35 -> 15 -> 5
88 -> 64 -> 24 -> 8
27 -> 14 -> 4
The number of products ne... | [
"You should use a while or for loop to multiply the digits instead of hardcoding what to do with the first, second and so on digits.\nIn pseudocode...\nproductSoFar = 1\ndigitsLeftToMultipy = #the number\nwhile there are digits left to multiply:\n get the next digit and\n update produtsSoFar and digitsLeftToM... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007973690_python.txt |
Q:
Import error using gaepytz (pytz in gae)
I am trying to use pytz on gae and found gaepytz. But, I get an import error when importing it and I think it is because I am not placing the original pytz and gaepytz side by side correctly in my app dir. (assuming I need to!)
./appdir/pytz [ original pytz folder, includi... | Import error using gaepytz (pytz in gae) | I am trying to use pytz on gae and found gaepytz. But, I get an import error when importing it and I think it is because I am not placing the original pytz and gaepytz side by side correctly in my app dir. (assuming I need to!)
./appdir/pytz [ original pytz folder, including zoneinfo subdir]
./appdir/gaepytz
in a f... | [
"This error occurs if you try to run the dev_appserver with Python 2.7, which doesn't currently work. Use Python 2.5 instead. If you're developing against the Python 2.7 runtime, remember that the dev_appserver doesn't yet have support for it, and you'll have to deploy in order to test your code.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"pytz"
] | stackoverflow_0007948933_google_app_engine_python_pytz.txt |
Q:
python sqlite3 error in FreeBSD 9
Trying to install this ipython version. infact there's a django-starter project which uses buildout for his needs.. And that scripts tried to get ipython 0.11 with easy_install.I tried to grep everything out from this package but there's no ipython mentioned in any files at all. s... | python sqlite3 error in FreeBSD 9 | Trying to install this ipython version. infact there's a django-starter project which uses buildout for his needs.. And that scripts tried to get ipython 0.11 with easy_install.I tried to grep everything out from this package but there's no ipython mentioned in any files at all. so I can't install newer version I need ... | [
"Judging from your error message and our exchange in the comments, I think the big problem is you might just be missing sqlite3 support for python.\nFrom your error messages I take it you're running FreeBSD, so you should install the databases/py-sqlite3 package from ports.\nI don't know much about FreeBSD's ports ... | [
1
] | [] | [] | [
"easy_install",
"freebsd",
"python"
] | stackoverflow_0007973660_easy_install_freebsd_python.txt |
Q:
Adding `exec "pass"` to a function allows modifications of locals() to be reflected in the namespace?
Reading the answer to the question, What's the difference between globals(), locals(), and vars()?, The following explanation was given for how locals() works:
if locals() is called inside a function it construct... | Adding `exec "pass"` to a function allows modifications of locals() to be reflected in the namespace? | Reading the answer to the question, What's the difference between globals(), locals(), and vars()?, The following explanation was given for how locals() works:
if locals() is called inside a function it constructs a dictionary of the function namespace as of that moment and returns it -- any further name assignments a... | [
"This answer to another question has a nice explanation of what is going on. Here is the summary:\n\nThe presence of an exec statement causes Python 2 to compile f in a totally non-optimized fashion, so locals are in a dict instead of in an array as they normally would be. (The performance hit can be considerable)... | [
3
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0007973709_namespaces_python.txt |
Q:
Python - Sequence not equal, but it is what I am expecting
def parse(self, input):
input = input.replace("\n", "").replace(" ", "")
bits = input.split("=>")
return bits[:-1]
Given "a => \nb => \nc=> " the output in the console is ["a", "b", "c"] which is exactly what I want. I guess the console must b... | Python - Sequence not equal, but it is what I am expecting | def parse(self, input):
input = input.replace("\n", "").replace(" ", "")
bits = input.split("=>")
return bits[:-1]
Given "a => \nb => \nc=> " the output in the console is ["a", "b", "c"] which is exactly what I want. I guess the console must be formatting the output, but I cannot explain why my tests are f... | [
"I just tested this using the module below, and my test passes just fine:\nimport unittest\n\nclass InputParser:\n def parse(self, input):\n input = input.replace(\"\\n\", \"\").replace(\" \", \"\")\n bits = input.split(\"=>\")\n return bits[:-1]\n\nclass InputParserTest ( unittest.TestCase ... | [
2
] | [] | [] | [
"console",
"python",
"sequences",
"unit_testing"
] | stackoverflow_0007973766_console_python_sequences_unit_testing.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.