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: Python reference count and ctypes Hallo, I have some troubles understanding the python reference count. What I want to do is return a tuple from c++ to python using the ctypes module. C++: PyObject* foo(...) { ... return Py_BuildValue("(s, s)", value1, value2); } Python: pointer = c_foo(...) # c_foo loaded w...
Python reference count and ctypes
Hallo, I have some troubles understanding the python reference count. What I want to do is return a tuple from c++ to python using the ctypes module. C++: PyObject* foo(...) { ... return Py_BuildValue("(s, s)", value1, value2); } Python: pointer = c_foo(...) # c_foo loaded with ctypes obj = cast(pointer, py_objec...
[ "On further research I found out that one can specify the return type of the function.\nhttp://docs.python.org/library/ctypes.html#callback-functions\nThis makes the cast obsolete and the ref count is no longer a problem.\nclib = ctypes.cdll.LoadLibrary('some.so')\nc_foo = clib.c_foo\nc_foo.restype = ctypes.py_obje...
[ 5, 4 ]
[]
[]
[ "c", "ctypes", "python", "reference_counting" ]
stackoverflow_0003931525_c_ctypes_python_reference_counting.txt
Q: os.path.exists not accepting variable input Whenever I call os.path.exists(variable) it will return false but if I call os.path.exists('/this/is/my/path') it will return true. import os import sys test = None print("Test directory") test= sys.stdin.readline() test.strip('\n') print(os.path.exists(test)) I know t...
os.path.exists not accepting variable input
Whenever I call os.path.exists(variable) it will return false but if I call os.path.exists('/this/is/my/path') it will return true. import os import sys test = None print("Test directory") test= sys.stdin.readline() test.strip('\n') print(os.path.exists(test)) I know that os.path.exists can return false if there is a...
[ "You have to do \ntest = test.strip(\"\\n\")\n\nStrings are immutable, so strip() returns a new string.\n(At least your code works for me then, if it is still not working for you, it must be something else.)\n", "strip() does not modify the string, it returns a new string. Try this:\nimport os\nimport sys\nsys.s...
[ 6, 1, 0 ]
[]
[]
[ "immutability", "python", "string" ]
stackoverflow_0003954387_immutability_python_string.txt
Q: Current Status of PEP 8 Rules? Are all PEP 8 rules still valid? Are there any which are obsolete? Isn't there a more explanatory cheat sheet that this one. A: Here is the current version of PEP 8. It was last updated 2010 August 29. A: PEP 8 is still the preferred style guide for Python code. Watching the chan...
Current Status of PEP 8 Rules?
Are all PEP 8 rules still valid? Are there any which are obsolete? Isn't there a more explanatory cheat sheet that this one.
[ "Here is the current version of PEP 8. It was last updated 2010 August 29.\n", "PEP 8 is still the preferred style guide for Python code. Watching the changes to Django, for instance, I see edits for PEP 8 (such as \"2 blank lines after the imports.)\nThey are still suggestions, though strong ones, and difference...
[ 6, 2, 1 ]
[]
[]
[ "coding_style", "pep8", "python" ]
stackoverflow_0003954593_coding_style_pep8_python.txt
Q: difficulties with python assignment I am new to programing and am having difficulties writing a program dealing with files. The program is to read a file, calculate an employees pay and an updated YTD pay total. After calculations the program will write to a new file. This is what I have so far: empName = "" prev...
difficulties with python assignment
I am new to programing and am having difficulties writing a program dealing with files. The program is to read a file, calculate an employees pay and an updated YTD pay total. After calculations the program will write to a new file. This is what I have so far: empName = "" prevYTD = 0.0 payRate = 0.0 hoursWorked = 0.0...
[ "Not sure what the problem is but some idiom can make it easy for you.\n\nYou can avoid testing for EOF and the while loop.\n\nFile is iteratable hence you can iterate over it.\nfor line in open('myfile','r'):\n doSomething(line)\n\nSee the details at : http://docs.python.org/tutorial/inputoutput.html\n[Edit: Ba...
[ 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003954671_file_python.txt
Q: Subclass/Child class I had this class and subclass : class Range: def __init__(self, start, end): self.setStart(start) self.setEnd(end) def getStart(self): return self.start def setStart(self, s): self.start = s def getEnd(self): return self.end def setEnd(self, e): self.end = e def getL...
Subclass/Child class
I had this class and subclass : class Range: def __init__(self, start, end): self.setStart(start) self.setEnd(end) def getStart(self): return self.start def setStart(self, s): self.start = s def getEnd(self): return self.end def setEnd(self, e): self.end = e def getLength(self): return le...
[ "First, a little bit of cleanup. I'm not completely convinced that your original class, DNAFeature, is actually correct. DNAFeature seems to be inheriting from some other class, named Range, that we're missing here so if you have that code please offer it as well. In that original class, you need to define the vari...
[ 1, 1 ]
[]
[]
[ "bioinformatics", "python" ]
stackoverflow_0003954356_bioinformatics_python.txt
Q: Python: How to use platform.win32_ver() on a remote machine? So of course I'm new to Python and to programming in general... I am trying to get OS version information from the network. For now I only care about the windows machines. using PyWin32 I can get some basic information, but it's not very reliable. This i...
Python: How to use platform.win32_ver() on a remote machine?
So of course I'm new to Python and to programming in general... I am trying to get OS version information from the network. For now I only care about the windows machines. using PyWin32 I can get some basic information, but it's not very reliable. This is an example of what I am doing right now: win32net.NetWkstaGetInf...
[ "A good way is to use WMI. The following links from Microsoft contain enough information to write code for your purposes:\n\nConnecting to WMI on a Remote Computer\nWMI Tasks: Operating Systems\n\nThe missing piece is how to do this in Python. For that, consult Tim Golden's site:\n\nWMI for Python\nWMI Cookbook\n...
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003712992_python_windows.txt
Q: Twisted + Django + Reverse Proxy I am deploying twisted as a web server for my site. I am looking into possibilities of reverse proxying. I have the following code right now hooked up to my reactor for django. I am using comet, and I realize that I absolutely must use port 80 hence I am looking into possibilities...
Twisted + Django + Reverse Proxy
I am deploying twisted as a web server for my site. I am looking into possibilities of reverse proxying. I have the following code right now hooked up to my reactor for django. I am using comet, and I realize that I absolutely must use port 80 hence I am looking into possibilities of reverse proxying. On this site, I ...
[ "It is not clear to me why you want to use a reverse-proxy. I think you're trying to use the right tool for the wrong reasons.\nReverse proxy is useful because you can have a lightweight server like nginx handle thousands of http keep-alive connections with very little memory overhead. The connections between the r...
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003947432_python_twisted.txt
Q: Why does "python -mtimeit" show less time when the code contains some module imports? On my single core 1.4 GHz computer, I ran the following 2 timeit codes: suzan:~$ python -mtimeit " def count(n): while n > 0: n -= 1 count(10000000) " 10 loops, best of 3: 1.73 sec per loop suzan:~$ suzan:~$ python -m...
Why does "python -mtimeit" show less time when the code contains some module imports?
On my single core 1.4 GHz computer, I ran the following 2 timeit codes: suzan:~$ python -mtimeit " def count(n): while n > 0: n -= 1 count(10000000) " 10 loops, best of 3: 1.73 sec per loop suzan:~$ suzan:~$ python -mtimeit " import os def count(n): while n > 0: n -= 1 count(10000000) " 1...
[ "I get effectively (to within 0.4%) the same time with both snippets. Python imports the os module as part of the normal import\n>>> import sys\n>>> \"os\" in sys.modules\nTrue\n>>> \n\nso the second bit of code, with the \"import os\", isn't even hitting the disk. All it does is a check against sys.modules.\nYou c...
[ 1, 1 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0003742655_python_timeit.txt
Q: Is it possible to use Python to measure response time? I'm running some experiments and I need to precisely measure participants' response time to questions. I know there are some commercial software, but I was wondering if I can do this with Python. Does python provides suitable functionality to measure the respo...
Is it possible to use Python to measure response time?
I'm running some experiments and I need to precisely measure participants' response time to questions. I know there are some commercial software, but I was wondering if I can do this with Python. Does python provides suitable functionality to measure the response time in millisecond unit? Thank you, Joon
[ "Just do something like this:\nfrom time import time\nstarttime = time()\naskQuestion()\ntimetaken = time() - starttime\n\n", "You could measure the execution time between the options displayed and the input received.\nhttp://docs.python.org/library/timeit.html\ndef whatYouWantToMeasure():\n pass\n\nif __name_...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003954900_python.txt
Q: Why I can call 'print' from 'eval' For code: #!/usr/bin/python src = """ print '!!!' import os """ obj = compile(src, '', 'exec') eval(obj, {'__builtins__': False}) I get output: !!! Traceback (most recent call last): File "./test.py", line 9, in <module> eval(obj, {'__builtins__': False}) File "", line...
Why I can call 'print' from 'eval'
For code: #!/usr/bin/python src = """ print '!!!' import os """ obj = compile(src, '', 'exec') eval(obj, {'__builtins__': False}) I get output: !!! Traceback (most recent call last): File "./test.py", line 9, in <module> eval(obj, {'__builtins__': False}) File "", line 3, in <module> ImportError: __import__...
[ "The __import__ method is invoked by the import keyword: python.org\nIf you want to be able to import a module you need to leave the __import__ method in the builtins: \nsrc = \"\"\"\nprint '!!!'\nimport os\n\"\"\"\n\nobj = compile(src, '', 'exec')\neval(obj, {'__builtins__': {'__import__':__builtins__.__import__...
[ 7, 2, 0, 0 ]
[]
[]
[ "built_in", "eval", "import", "printing", "python" ]
stackoverflow_0003949727_built_in_eval_import_printing_python.txt
Q: Python string to integer value I'd like to know how to convert strings in Python to their corresponding integer values, like so: >>>print WhateverFunctionDoesThis('\x41\x42') >>>16706 I've searched around but haven't been able to find an easy way to do this. Thank you. A: >>> import struct >>> struct.unpack(">...
Python string to integer value
I'd like to know how to convert strings in Python to their corresponding integer values, like so: >>>print WhateverFunctionDoesThis('\x41\x42') >>>16706 I've searched around but haven't been able to find an easy way to do this. Thank you.
[ ">>> import struct\n>>> struct.unpack(\">h\",'\\x41\\x42')\n(16706,)\n>>> struct.unpack(\">h\",'\\x41\\x42')[0]\n16706\n\nFor other format chars see the documentation\n", "If '\\x41\\x42' is 16-based num, like AB. You can use string to convert it.\nimport string\n\nagaga = '\\x41\\x42'\nstring.atoi(agaga, 16)\n>>...
[ 7, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003955196_python.txt
Q: Python Bed module I need to create a Bed module with these functions: readBed(file)
–
read 
a 
BED 
format 
file 
and
 constructs 
a 
list 
of 
gene 
model 
objects 
from 
the
 data
 it 
contains.

 writeBed(models=models,fname=file)
 – 
writes 
the 
given 
list
 of
 gene 
model 
objects
 and 
 writes
 them 
to 
...
Python Bed module
I need to create a Bed module with these functions: readBed(file)
–
read 
a 
BED 
format 
file 
and
 constructs 
a 
list 
of 
gene 
model 
objects 
from 
the
 data
 it 
contains.

 writeBed(models=models,fname=file)
 – 
writes 
the 
given 
list
 of
 gene 
model 
objects
 and 
 writes
 them 
to 
a
 file 
named 
fname. ...
[ "I'll start with the Range class. Firstly, you shouldn't use get/set methods, instead just use the variable. Get/set methods in python are almost always bad practice. Even if you need validation, you can use properties.\nIf you're using python 2.x, you need to inherit from object to get new-style classes. If you're...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003955120_python.txt
Q: Python Mechanize keeps giving me 'response_seek_wrapper' when I try to use .open I'm not sure what's going on, as the script used to work (before I messed around with my python on my system...) But when I try something along the lines of import mechanize browser = mechanize.Browser() browser.open("http://google.co...
Python Mechanize keeps giving me 'response_seek_wrapper' when I try to use .open
I'm not sure what's going on, as the script used to work (before I messed around with my python on my system...) But when I try something along the lines of import mechanize browser = mechanize.Browser() browser.open("http://google.com") I get something like <response_seek_wrapper at 0x10123fd88 whose wrapped object =...
[ "it's not an exception, is it?\nnothing wrong is happening, you just got a return value, which is esentially a response object, equivalent to br.response().\nsee\n>>> r = browser.open(\"http://google.com\")\n>>> r\n<response_seek_wrapper at 0x9bb116c whose wrapped object = <closeable_response at 0x9bb426c whose fp ...
[ 5 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003955301_mechanize_python.txt
Q: How to use Query.order() on string properties containing non-english characters? How to use Query.order() on string properties containing non-english characters so entities where fetched in correct order? Query.order is oddly putting any non-english characters on the end of the list, like this: Dolnośląskie Kujaws...
How to use Query.order() on string properties containing non-english characters?
How to use Query.order() on string properties containing non-english characters so entities where fetched in correct order? Query.order is oddly putting any non-english characters on the end of the list, like this: Dolnośląskie Kujawsko-Pomorskie Lubelskie Lubuskie Mazowieckie Małopolskie <- incorrect order Opolskie Po...
[ "Normalizing the strings into a separate property is the only solution to what you want; they're sorted by unicode codepoints, and the letters that are part of ASCII have much lower values than non-ASCII characters.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003955617_google_app_engine_google_cloud_datastore_python.txt
Q: replace only one variable in web.py templates I am passing variable to template in web.py and have the same condition in some places. Like this: $if myvar=="string1": $passed argument1 ............ $if myvar =="striung2": $passed argument2 If say myvar is "string1" and I pass passed = "AAA" then I have AAA arg...
replace only one variable in web.py templates
I am passing variable to template in web.py and have the same condition in some places. Like this: $if myvar=="string1": $passed argument1 ............ $if myvar =="striung2": $passed argument2 If say myvar is "string1" and I pass passed = "AAA" then I have AAA argument1 on my page, but the other if statements get ...
[ "Your question is unclear. What are you trying to do? It sounds like you just need to use else:\nif myvar == \"string1\":\n print passed\nelse:\n # something\n\nBut it's very hard to understand what you are asking.\n" ]
[ 0 ]
[]
[]
[ "python", "templates", "web.py" ]
stackoverflow_0002399289_python_templates_web.py.txt
Q: How to speed up string construction from characters in a doubly-nested list? A common speedup for string concatenations is changing something like s = "" for x in list: s += some_function(x) to slist = [some_function(elt) for elt in somelist] s = "".join(slist) However, how could this apply if your 'for' wa...
How to speed up string construction from characters in a doubly-nested list?
A common speedup for string concatenations is changing something like s = "" for x in list: s += some_function(x) to slist = [some_function(elt) for elt in somelist] s = "".join(slist) However, how could this apply if your 'for' was doubly nested? For example... s = "" for x in list: for y in x: s +=...
[ "''.join(func(c) for s in somelist for c in s)\n\n", "string_list = []\nfor x in list:\n for y in x:\n string_list.append(some_function(y))\n\nthe_string = ''.join(string_list)\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003956181_python.txt
Q: Python: Convert this list into dictionary I've got a problem , and do not know how to code in python. I've got a list[10, 10, 10, 20, 20, 20, 30] I want it be in a dictionary like this {"10": 1, "20": 3, "30" : 1} How could I achieve this? A: from collections import Counter a = [10, 10, 10, 20, 20, 20, 30] c =...
Python: Convert this list into dictionary
I've got a problem , and do not know how to code in python. I've got a list[10, 10, 10, 20, 20, 20, 30] I want it be in a dictionary like this {"10": 1, "20": 3, "30" : 1} How could I achieve this?
[ "from collections import Counter\na = [10, 10, 10, 20, 20, 20, 30]\nc = Counter(a)\n# Counter({10: 3, 20: 3, 30: 1})\n\nIf you really want to convert the keys to strings, that's a separate step:\ndict((str(k), v) for k, v in c.iteritems())\n\nThis class is new to Python 2.7; for earlier versions, use this implement...
[ 16, 4, 1, 1 ]
[]
[]
[ "dictionary", "formatting", "list", "python" ]
stackoverflow_0003956206_dictionary_formatting_list_python.txt
Q: Add new column on Elixir I use Elixir as an ORM for a MySQL database. I want to add new column to my schema. / How can I keep the original data in MySQL and update the schema automatically? The concept is called migrate in Ruby on rails. A: You're looking for sqlalchemy-migrate. Elixir is a layer on top of SQL...
Add new column on Elixir
I use Elixir as an ORM for a MySQL database. I want to add new column to my schema. / How can I keep the original data in MySQL and update the schema automatically? The concept is called migrate in Ruby on rails.
[ "You're looking for sqlalchemy-migrate. Elixir is a layer on top of SQLAlchemy, and sqlalchemy-migrate was inspired by RoR migrate.\n" ]
[ 0 ]
[]
[]
[ "migration", "mysql", "python", "python_elixir" ]
stackoverflow_0003956388_migration_mysql_python_python_elixir.txt
Q: Submitting a form in mechanize I'm having issues submitting the result of a form submission (I can submit a form, but I can't submit the form on the page that follows the first). I have: browser = mechanize.Browser() browser.set_handle_robots(False) browser.open('https://www.example.com/login') browser.select_form...
Submitting a form in mechanize
I'm having issues submitting the result of a form submission (I can submit a form, but I can't submit the form on the page that follows the first). I have: browser = mechanize.Browser() browser.set_handle_robots(False) browser.open('https://www.example.com/login') browser.select_form(nr=0) browser.form['j_username'] =...
[ "try again browser.select_form(nr=0) instead of req.select_form(nr=0). (after submitting or clicking a link or so, the new response is considered as an actual browser page - like in a browser :) )\n" ]
[ 9 ]
[]
[]
[ "forms", "mechanize", "python" ]
stackoverflow_0003956280_forms_mechanize_python.txt
Q: Debug a module built with Boost.Python in QtCreator I have a module built with Boost.Python and I want to debug it in QtCreator (or perhaps gdb). I prefer a visual environment if possible. A: http://leohart.wordpress.com/2010/10/18/debug-a-module-built-with-boost-python-within-qtcreator/ After a while, I finally...
Debug a module built with Boost.Python in QtCreator
I have a module built with Boost.Python and I want to debug it in QtCreator (or perhaps gdb). I prefer a visual environment if possible.
[ "http://leohart.wordpress.com/2010/10/18/debug-a-module-built-with-boost-python-within-qtcreator/\nAfter a while, I finally figured out how to do it. I documented it in the link above so future searches can find it.\n" ]
[ 1 ]
[]
[]
[ "boost_python", "c++", "debugging", "python", "qt_creator" ]
stackoverflow_0003956365_boost_python_c++_debugging_python_qt_creator.txt
Q: Embedding Python on Windows: why does it have to be a DLL? I'm trying to write a software plug-in that embeds Python. On Windows the plug-in is technically a DLL (this may be relevant). The Python Windows FAQ says: 1.Do not build Python into your .exe file directly. On Windows, Python must be a DLL to handle impo...
Embedding Python on Windows: why does it have to be a DLL?
I'm trying to write a software plug-in that embeds Python. On Windows the plug-in is technically a DLL (this may be relevant). The Python Windows FAQ says: 1.Do not build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key ...
[ "You need to link to pythonXY.dll as a DLL, instead of linking the relevant code directly into your executable, because otherwise the Python runtime can't load other DLLs (the extension modules it relies on.) If you make your own DLL you could theoretically link all the Python code in that DLL directly, since it do...
[ 4, 2, 1, 1 ]
[]
[]
[ "dll", "python", "windows" ]
stackoverflow_0003953039_dll_python_windows.txt
Q: Escaping unicode strings for MySQL in Python (avoiding exceptions.UnicodeEncodeError) I am using Twisted to asynchronously access our database in Python. My code looks like this: from twisted.enterprise import adbapi from MySQLdb import _mysql as mysql ... txn.execute(""" INSERT INTO users_accounts_data_sna...
Escaping unicode strings for MySQL in Python (avoiding exceptions.UnicodeEncodeError)
I am using Twisted to asynchronously access our database in Python. My code looks like this: from twisted.enterprise import adbapi from MySQLdb import _mysql as mysql ... txn.execute(""" INSERT INTO users_accounts_data_snapshots (accountid, programid, fieldid, value, timestamp, jobid) VALUES ('%s', '%s', '%s...
[ "Do not format strings like this. It is a massive security hole. It is not possible to do the quoting correctly by yourself. Do not try.\nUse the second parameter to 'execute'. Simply put, instead of txn.execute(\"... %s, %s ...\" % (\"xxx\", \"yyy\")), do txn.execute(\"... %s, %s ...\", (\"xxx\", \"yyy\")). N...
[ 11, 2 ]
[]
[]
[ "mysql", "python", "twisted" ]
stackoverflow_0003956906_mysql_python_twisted.txt
Q: how itertools.tee works, can type 'itertools.tee' be duplicated in order to save it's "status"? Below are some tests about itertools.tee: li = [x for x in range(10)] ite = iter(li) ================================================== it = itertools.tee(ite, 5) >>> type(ite) <type 'listiterator'> ...
how itertools.tee works, can type 'itertools.tee' be duplicated in order to save it's "status"?
Below are some tests about itertools.tee: li = [x for x in range(10)] ite = iter(li) ================================================== it = itertools.tee(ite, 5) >>> type(ite) <type 'listiterator'> >>> type(it) <type 'tuple'> >>> type(it[0]) <type 'itertools.tee'> >>> >>> ...
[ "tee takes over the original iterator; once you tee an iterator, discard the original iterator since the tee owns it (unless you really know what you're doing).\nYou can make a copy of a tee with the copy module:\nimport copy, itertools\nit = [1,2,3,4]\na, b = itertools.tee(it)\nc = copy.copy(a)\n\n... or by callin...
[ 16 ]
[]
[]
[ "duplicates", "iterator", "python", "tee" ]
stackoverflow_0003957270_duplicates_iterator_python_tee.txt
Q: What is the PHP equivalent to Python's Try: ... Except: I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else. This is what it would look like in Python: try: print "stuf" except: print "something else" Wha...
What is the PHP equivalent to Python's Try: ... Except:
I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else. This is what it would look like in Python: try: print "stuf" except: print "something else" What would this be in PHP?
[ "http://php.net/manual/en/language.exceptions.php\ntry {\n print 'stuff';\n} catch (Exception $e) {\n var_dump($e);\n}\n\nNote: this only works for exceptions, not errors.\nSee http://www.php.net/manual/en/function.set-error-handler.php for that.\n", "try {\n\n // do stuff ...\n\n} catch (Exception $e) {...
[ 7, 5, 1, 1, 0, 0 ]
[]
[]
[ "exception", "php", "python", "try_catch" ]
stackoverflow_0003956278_exception_php_python_try_catch.txt
Q: Is elixir out-dated? My sqlalchemy is 0.6.3, and elixir is 0.7.1 I created a model class which extends Entity: from elixir import * class User(Entity): pass And save the a user as: user = User() user.save() It reports Session has no attribute 'save' I looked into the code of elixir, found it invokes sqlalche...
Is elixir out-dated?
My sqlalchemy is 0.6.3, and elixir is 0.7.1 I created a model class which extends Entity: from elixir import * class User(Entity): pass And save the a user as: user = User() user.save() It reports Session has no attribute 'save' I looked into the code of elixir, found it invokes sqlalchemy.org.session.Session#sav...
[ "I am using the same versions of SQLAlchemy and Elixir so it is definitely compatible. Not sure what you are trying to do with the above code.\n", "Remember to call setup_all(True) before doing anything with session or query. This will do the necessary ORM mappings for the session and the query to work properly.\...
[ 1, 1 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0003668026_python_python_elixir_sqlalchemy.txt
Q: Pylons with Elixir I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (cleverdevil, beachcoder, adam hoscilo) and even an entire new framework about how to go about doing this; however, I am not certain about the differences bet...
Pylons with Elixir
I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (cleverdevil, beachcoder, adam hoscilo) and even an entire new framework about how to go about doing this; however, I am not certain about the differences between them. Which one is ...
[ "Personally, I'd go with beachcoder's recipe as updated here. That said, with the possible exception of Tesla (which I'm not familiar with), they're all lightweight enough that it should be easy to switch between them if you have any kind of trouble; all the hard work is in your model.\n", "Graham Higgins wrote a...
[ 1, 1 ]
[]
[]
[ "pylons", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0000192345_pylons_python_python_elixir_sqlalchemy.txt
Q: Dependency injection in (Python) Google App Engine I want to achieve maximum testability in my Google App Engine app which I'm writing in Python. Basically what I'm doing is creating an all-purpose base handler which inherits the google.appengine.ext.webapp.RequestHandler. My base handler will expose common functi...
Dependency injection in (Python) Google App Engine
I want to achieve maximum testability in my Google App Engine app which I'm writing in Python. Basically what I'm doing is creating an all-purpose base handler which inherits the google.appengine.ext.webapp.RequestHandler. My base handler will expose common functionality in my app such as repository functions, a sessio...
[ "The simplest way to achieve what you want would be to create a module-level variable containing the class of the session to create:\n# myhandler.py\nsession_class = gmemsess.Session\n\nclass Handler(webapp.Request\n def _getsession(self):\n if not self._session:\n self._session = session_class...
[ 2, 1 ]
[]
[]
[ "dependency_injection", "google_app_engine", "python" ]
stackoverflow_0003949015_dependency_injection_google_app_engine_python.txt
Q: Is is possible to read a file from S3 in Google App Engine using boto? I want to manipulate a pickled python object stored in S3 in Google App Engine's sandbox. I use the suggestion in boto's documentation: from boto.s3.connection import S3Connection from boto.s3.key import Key conn = S3Connection(config.key, co...
Is is possible to read a file from S3 in Google App Engine using boto?
I want to manipulate a pickled python object stored in S3 in Google App Engine's sandbox. I use the suggestion in boto's documentation: from boto.s3.connection import S3Connection from boto.s3.key import Key conn = S3Connection(config.key, config.secret_key) bucket = conn.get_bucket('bucketname') key = bucket.get_key...
[ "You don't need to write to a file or a StringIO at all. You can call key.get_contents_as_string() to return the key's contents as a string. The docs for key are here.\n", "You can write into a blob and use the StringIO to retrieve the data\nfrom boto.s3.connection import S3Connection\nfrom boto.s3.key import Key...
[ 7, 3 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto", "google_app_engine", "python" ]
stackoverflow_0003948391_amazon_s3_amazon_web_services_boto_google_app_engine_python.txt
Q: unable to convert pdf to text using python script i want to convert all my .pdf files from a specific directory to .txt format using the command pdftotext... but i wanna do this using a python script... my script contains: import glob import os fullPath = os.path.abspath("/home/eth1/Downloads") for fileName in ...
unable to convert pdf to text using python script
i want to convert all my .pdf files from a specific directory to .txt format using the command pdftotext... but i wanna do this using a python script... my script contains: import glob import os fullPath = os.path.abspath("/home/eth1/Downloads") for fileName in glob.glob(os.path.join(fullPath,'*.pdf')): fullFileN...
[ "You are passing fullFileName literally to os.popen. You should do something like this instead (assuming that fullFileName does not have to be escaped):\nos.popen('pdftotext %s' % fullFileName)\n\nAlso note that os.popen is considered deprecated, it's better to use the subprocess module instead:\nimport subprocess\...
[ 3, 1 ]
[]
[]
[ "glob", "python" ]
stackoverflow_0003958039_glob_python.txt
Q: What is the best way to detect and redirect a mobile browsser in AppEngine? Specfically, I am working in Python. A: Check it out @mobiforge : http://mobiforge.com/developing/story/creating-mobile-web-sites-with-google-app-engine A: set your doctype to <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//E...
What is the best way to detect and redirect a mobile browsser in AppEngine?
Specfically, I am working in Python.
[ "Check it out @mobiforge : http://mobiforge.com/developing/story/creating-mobile-web-sites-with-google-app-engine\n", "set your doctype to\n<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">\n\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "mobile_phones", "mobile_website", "python" ]
stackoverflow_0003957794_google_app_engine_mobile_phones_mobile_website_python.txt
Q: Prototype based object orientation. The good, the bad and the ugly? I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and ...
Prototype based object orientation. The good, the bad and the ugly?
I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditio...
[ "Prototype-based OO lends itself poorly to static type checking, which some might consider a bad or ugly thing. Prototype-based OO does have a standard way of creating new objects, you clone and modify existing objects. You can also build factories, etc.\nI think what people like most (the \"good\") is that proto...
[ 13, 7, 2, 1, 0 ]
[]
[]
[ "javascript", "language_agnostic", "lua", "oop", "python" ]
stackoverflow_0000385403_javascript_language_agnostic_lua_oop_python.txt
Q: Django Templates Variable Resolution Hey there, it's been a week with Django back here so don't mind me if the question is stupid, though I searched over stackoverflow and google with no luck. I've got a simple model called Term (trying to implement tags and categories for my news module) and I have a template tag...
Django Templates Variable Resolution
Hey there, it's been a week with Django back here so don't mind me if the question is stupid, though I searched over stackoverflow and google with no luck. I've got a simple model called Term (trying to implement tags and categories for my news module) and I have a template tag called taxonomy_list which should output ...
[ "It's not really a question of variable resolution. The issue is how you're getting the terms from the Post object.\nWhen, inside your template tag, you do for term in terms.all(), the all is telling Django to re-evaluate the queryset, which means querying the database again. So, your carefully-annotated terms are ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003957977_django_python.txt
Q: Minimax explained for an idiot I've wasted my entire day trying to use the minimax algorithm to make an unbeatable tictactoe AI. I missed something along the way (brain fried). I'm not looking for code here, just a better explanation of where I went wrong. Here is my current code (the minimax method always returns...
Minimax explained for an idiot
I've wasted my entire day trying to use the minimax algorithm to make an unbeatable tictactoe AI. I missed something along the way (brain fried). I'm not looking for code here, just a better explanation of where I went wrong. Here is my current code (the minimax method always returns 0 for some reason): from copy impor...
[ "Step 1: Build your game tree\nStarting from the current board generate all possible moves your opponent can make.\nThen for each of those generate all the possible moves you can make.\nFor Tic-Tac-Toe simply continue until no one can play. In other games you'll generally stop after a given time or depth.\nThis lo...
[ 20, 7, 3 ]
[]
[]
[ "minimax", "python", "tic_tac_toe" ]
stackoverflow_0003956258_minimax_python_tic_tac_toe.txt
Q: determing file object size before using file object I am attempting to determine the size of a downloaded file in python before parsing and manipulating it with BeautifulSoup. (I intend to update to ElementTree soon, but having briefly played with it, it does not solve the problem I am posing here, as far as I can...
determing file object size before using file object
I am attempting to determine the size of a downloaded file in python before parsing and manipulating it with BeautifulSoup. (I intend to update to ElementTree soon, but having briefly played with it, it does not solve the problem I am posing here, as far as I can see). import urllib2, BeautifulSoup query = 'http://myex...
[ "Copy the content of the file into a variable and work with it:\nimport urllib2, BeautifulSoup\n\nquery = 'http://myexample.file.com/file.xml'\nf = urllib2.urlopen(query)\ncontent = f.read()\nprint len(content)\nsoup = BeautifulSoup.BeautifulStoneSoup(content)\n\n" ]
[ 2 ]
[]
[]
[ "file_copying", "filesize", "python" ]
stackoverflow_0003959356_file_copying_filesize_python.txt
Q: Uploading images from a django application to a Google AppEngine application I am not running Django on AppEngine. I just want to use AppEngine as a content delivery network, basically a place I can host and serve images for free. It's for a personal side project. The situation is this: I have the URL of an image ...
Uploading images from a django application to a Google AppEngine application
I am not running Django on AppEngine. I just want to use AppEngine as a content delivery network, basically a place I can host and serve images for free. It's for a personal side project. The situation is this: I have the URL of an image hosted on another server/provider. Instead of hotlinking to that image its better ...
[ "Afaik you can not store files in App Engine programmatically. You can just store them, when uploading your app.\nYou can however store information in its data store. So you would need to deploy an app, that authenticates your user and then writs the image to the gae's data store \n", "In my application, i use a ...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003958224_google_app_engine_python.txt
Q: Unpack BinaryString sent from JavaScript FileReader API to Python I'm trying to unpack a binary string sent via Javascript's FileReader readAsBinaryString method in my python app. It seems I could use the struct module for this. I'm unsure what to provide as as the format for the unpack exactly. Can someone confi...
Unpack BinaryString sent from JavaScript FileReader API to Python
I'm trying to unpack a binary string sent via Javascript's FileReader readAsBinaryString method in my python app. It seems I could use the struct module for this. I'm unsure what to provide as as the format for the unpack exactly. Can someone confirm this is the right approach, and if so, what format I should specify?...
[ "It sounds as if you just have an ordinary string (or bytes object in Python 3), so I'm not sure what you need to unpack.\nOne method of accessing the byte data is to use a bytearray; this lets you index the byte data easily:\n>>> your_data = b'\\x00\\x12abc'\n>>> b = bytearray(your_data)\n>>> b[0]\n0\n>>> b[1]\n18...
[ 3 ]
[]
[]
[ "filereader", "html", "javascript", "python" ]
stackoverflow_0003959380_filereader_html_javascript_python.txt
Q: Python: getting an object's “attribute/method/property” either as a parameter to a method or as a property In the WMI module (yeah, my boss wants me to program in Windows — but at least it’s not in COBOL), it seems that you can access a WMI value either by passing it’s name as a string parameter of a method, blab...
Python: getting an object's “attribute/method/property” either as a parameter to a method or as a property
In the WMI module (yeah, my boss wants me to program in Windows — but at least it’s not in COBOL), it seems that you can access a WMI value either by passing it’s name as a string parameter of a method, blabla=wmithingy().getvalue('nameOfValue') or as a property/method: blabla=wmithingy().nameOfValue() Am I dreaming...
[ "Either the getvalue() method uses getattr(), or the __getattr__() method defers to the getvalue() method.\n" ]
[ 2 ]
[]
[]
[ "properties", "python", "windows", "wmi" ]
stackoverflow_0003959589_properties_python_windows_wmi.txt
Q: Using Microsoft Access SQL operators in Python ODBC Short version: When I try to use Access's DatePart function via ODBC, it cannot be resolved. Longer version: I have a Microsoft Access query which returns rows with a timestamp and a score. I want to sort it by day and then by score - effectively a high-score ta...
Using Microsoft Access SQL operators in Python ODBC
Short version: When I try to use Access's DatePart function via ODBC, it cannot be resolved. Longer version: I have a Microsoft Access query which returns rows with a timestamp and a score. I want to sort it by day and then by score - effectively a high-score table for the day. For want of a better function, I used th...
[ "Are you sure that using quotes \"yyyy\" instead of apostrophes 'yyyy' is valid in that dialect of SQL?\n", "Datetimes are stored in access as floating point numbers. The number to the left of the decimal point is the date, the fractional part to the right of the decimal point is the time (expressed in terms of ...
[ 2, 2 ]
[]
[]
[ "ms_access", "odbc", "pyodbc", "python", "sql" ]
stackoverflow_0003956778_ms_access_odbc_pyodbc_python_sql.txt
Q: Multiple communication channels with Twisted Python I am currently researching the Twisted framework as a way of implementing a network-based backup application, and I would like to achieve something that I cannot find any examples of on the net. I plan to implement the system using the Perspective Broker, but I w...
Multiple communication channels with Twisted Python
I am currently researching the Twisted framework as a way of implementing a network-based backup application, and I would like to achieve something that I cannot find any examples of on the net. I plan to implement the system using the Perspective Broker, but I will also need a way of transferring binary files from the...
[ "\nThe reason for having these two separate communication channels is down to the fact that I would like to make the client multi-threaded (one thread scanning the directory tree, while another thread transfers the changed files to the server).\n\nThis reasoning doesn't follow. You can use a single protocol runnin...
[ 2 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0003959863_python_tcp_twisted.txt
Q: How do I re-route network traffic using Python? Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some ...
How do I re-route network traffic using Python?
Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some work done. I looked at the available options and also...
[ "Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs.\n" ]
[ 2 ]
[]
[]
[ "network_programming", "networking", "python", "social_networking", "tcp" ]
stackoverflow_0003960294_network_programming_networking_python_social_networking_tcp.txt
Q: How to migrate a CSV file to Sqlite3 (or MySQL)? - Python I'm using Python in order to save the data row by row... but this is extremely slow! The CSV contains 70million lines, and with my script I can just store 1thousand a second. This is what my script looks like reader = csv.reader(open('test_results.csv', 'r...
How to migrate a CSV file to Sqlite3 (or MySQL)? - Python
I'm using Python in order to save the data row by row... but this is extremely slow! The CSV contains 70million lines, and with my script I can just store 1thousand a second. This is what my script looks like reader = csv.reader(open('test_results.csv', 'r')) for row in reader: TestResult(type=row[0], name=row[1],...
[ "For MySQL imports:\nmysqlimport [options] db_name textfile1 [textfile2 ...]\n\nFor SQLite3 imports: \nref How to import load a .sql or .csv file into SQLite?\n", "I don't know if this will make a big enough difference, but since you're dealing with the Django ORM I can suggest the following:\n\nEnsure that DEBUG...
[ 4, 3 ]
[]
[]
[ "csv", "django", "mysql", "python", "sqlite" ]
stackoverflow_0003958750_csv_django_mysql_python_sqlite.txt
Q: Django Forms validation error - TypeError 'str' object is not callable so...i've been banging my head on this for a bit. I'm getting the most bizarre error when attempting to validate a form. I pass input to the form wanting to test behavior when the form fails validation, i.e. i expect it to fail validation. i've...
Django Forms validation error - TypeError 'str' object is not callable
so...i've been banging my head on this for a bit. I'm getting the most bizarre error when attempting to validate a form. I pass input to the form wanting to test behavior when the form fails validation, i.e. i expect it to fail validation. i've got this code for a form: class CTAForm(forms.Form): first_name =...
[ "You get an error about a string not being callable, but your errorclass for your form is a string, not an error class.\n cta_form = cta_form_class(request.POST, error_class='error')\n\nNow the only reference in the docs I can find for error_class is as a list of strings, so you may just try\n cta_form = cta...
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "python", "validation" ]
stackoverflow_0003952408_django_django_forms_python_validation.txt
Q: Read to right of specific symbol in file from Python I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python. Here is the format: virus=signature I need to be able to take 'virus' and write it to one file, then take 'signature' a...
Read to right of specific symbol in file from Python
I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python. Here is the format: virus=signature I need to be able to take 'virus' and write it to one file, then take 'signature' and write it to another. This is what I've tied so far: h...
[ "with open(fname) as inputf, open(virf, 'w') as viruses, open(sigs, 'w') as signatures:\n for line in inputf:\n virus, _, sig = line.partition('=')\n viruses.write(virus + '\\n')\n signatures.write(sig)\n\n", "f1=open(\"first.txt\",\"a\")\nf2=open(\"second.txt\",\"a\")\nfor line in open(\"...
[ 4, 1 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0003960571_file_python_string.txt
Q: easiest way to make a live 3d scene, a bit like a simple game (for simulator visualisation purposes) I am building a ship simulator that will produce accurate position and orientation values for a prototype hull design in some defined sea-state. In terms of programming, I have 2 arrays (vectors) in MATLAB containi...
easiest way to make a live 3d scene, a bit like a simple game (for simulator visualisation purposes)
I am building a ship simulator that will produce accurate position and orientation values for a prototype hull design in some defined sea-state. In terms of programming, I have 2 arrays (vectors) in MATLAB containing the position and acceleration values for x, y, z, yaw, pitch and roll. Because the visualisations in MA...
[ "Not an expert, but few leads are\n\nvtk, portable and integrates, regarding complexity look at sample code\ncomparison of engines in a related so question (and online database it links to)\n\nThe above might be called complex and bloated if compared to low level API such as OpenGL, but you have to define what kind...
[ 1, 1, 0 ]
[]
[]
[ "3d", "c#", "java", "opengl", "python" ]
stackoverflow_0003958772_3d_c#_java_opengl_python.txt
Q: Python timeit problem I'm trying to use the timeit module but I don't know how. I have a main: from Foo import Foo if __name__ == '__main__': ... foo = Foo(arg1, arg2) t = Timer("foo.runAlgorithm()") print t.timeit(2) and my Class Foo has a method named as runAlgorithm() the error is this: NameError: ...
Python timeit problem
I'm trying to use the timeit module but I don't know how. I have a main: from Foo import Foo if __name__ == '__main__': ... foo = Foo(arg1, arg2) t = Timer("foo.runAlgorithm()") print t.timeit(2) and my Class Foo has a method named as runAlgorithm() the error is this: NameError: global name 'foo' is not de...
[ "Instead of using the necessary setup parameter for setting up the timeit environment, you can simply pass the method (or anything that is callable):\nt = Timer(foo.runAlgorithm)\n\nFrom the documentation:\n\nChanged in version 2.6: The stmt and setup parameters can now also take objects that are callable without a...
[ 16, 2 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0003960834_python_timeit.txt
Q: Basic Python file searching and I/O I'm trying to complete a simple task in Python and I'm new to the language (I'm C++). I hope someone might be able to point me in the right direction. Problem: I have an XML file (12mb) full of data and within the file there are start tags 'xmltag' and end tags '/xmltag' that re...
Basic Python file searching and I/O
I'm trying to complete a simple task in Python and I'm new to the language (I'm C++). I hope someone might be able to point me in the right direction. Problem: I have an XML file (12mb) full of data and within the file there are start tags 'xmltag' and end tags '/xmltag' that represent the start and end of the data sec...
[ "Check BeautifulSoup\nfrom BeautifulSoup import BeautifulSoup\n\nwith open('bigfile.xml', 'r') as xml:\n soup = BeautifulSoup(xml):\n for xmltag in soup('xmltag'):\n print xmltag.contents\n\n", "Dive Into Python 3 have a great chapter about this:\n\nhttp://diveintopython3.org/xml.html#xml-parse\n\nIt...
[ 4, 2, 1, 0 ]
[ "xml=open(\"xmlfile\").read()\nx=xml.split(\"</xmltag>\")\nfor block in x:\n if \"<xmltag>\" in block:\n print block.split(\"<xmltag>\")[-1]\n\n" ]
[ -2 ]
[ "file", "python", "search", "text", "xml" ]
stackoverflow_0003959989_file_python_search_text_xml.txt
Q: Get current system time of a machine on the network I understand that I can query system time of my machine like this: from datetime import datetime datetime.now() Is there a way to query the system time of another machine on the windows network? Eg of \\mynetworkpc. A: on a Windows machine there is net time \...
Get current system time of a machine on the network
I understand that I can query system time of my machine like this: from datetime import datetime datetime.now() Is there a way to query the system time of another machine on the windows network? Eg of \\mynetworkpc.
[ "on a Windows machine there is net time \\\\<remote-ip address> to get the time of a remote machine but I don't know if it is portable.\n>>> import subprocess\n>>> subprocess.call(r\"net time \\\\172.21.5.135\")\nCurrent time at \\\\172.21.5.135 is 10/18/2010 12:32 PM\n\nThe command completed successfully.\n\n0\n>>...
[ 6, 0 ]
[]
[]
[ "networking", "python", "system", "time" ]
stackoverflow_0003960829_networking_python_system_time.txt
Q: Python function prints None I have the following exercise: The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. Here's what I've done, but the second print functio...
Python function prints None
I have the following exercise: The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. Here's what I've done, but the second print function only prints 'None'. def sleep_i...
[ "Functions in python return None unless explicitly instructed to do otherwise.\nIn your function above, you don't take into account the case in which weekday is True. The interpreter reaches the end of the function without reading a return statement (since the condition predecing yours evaluates to False), and retu...
[ 6 ]
[]
[]
[ "function", "python", "return_value" ]
stackoverflow_0003961099_function_python_return_value.txt
Q: I'm new to python and having trouble with this looping code I'm trying to copy sections in a file within a set of XML tags > <tag>I want to copy the data here</tag>` Please note I found out the data around the tags is not valid XML so I can't import a normal library and have to find it via string comparison :( *...
I'm new to python and having trouble with this looping code
I'm trying to copy sections in a file within a set of XML tags > <tag>I want to copy the data here</tag>` Please note I found out the data around the tags is not valid XML so I can't import a normal library and have to find it via string comparison :( * There are multiple sections of text I want to extract in the f...
[ "There's a few issues with your code:\n\nIf input is really in the format of \"<STARTTAG> ... </STARTTAG>\", capturing lines isn't going to cut it as you're going to grab at least the <STARTTAG> instance.\nYou're using a literal string prefix (r\"<//STARTTAG>\") but you're using two forward slashes. From your exam...
[ 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003961227_python_string.txt
Q: call remote programs by URL with python I am developing a GUI in python with wxPython framework to launch several subprocess programs. Now I could do it for the local files, e.g. if we have a compiled .out file under the path "/AAA/BBB/xxx.out", I could do with command like this: subprocess.Popen("/AAA/BBB/xxx.out...
call remote programs by URL with python
I am developing a GUI in python with wxPython framework to launch several subprocess programs. Now I could do it for the local files, e.g. if we have a compiled .out file under the path "/AAA/BBB/xxx.out", I could do with command like this: subprocess.Popen("/AAA/BBB/xxx.out", stdout=subprocess.PIPE) Now, I am thinkin...
[ "For loading this online file as subprocess from within your program, you are going to have to download it for a temporary location. Just use urllib2 module to download the file together with http://docs.python.org/library/tempfile.html to create a temporary placeholder for it. They you can execute it.\n", "There...
[ 0, 0 ]
[]
[]
[ "python", "url" ]
stackoverflow_0003961507_python_url.txt
Q: Need help understanding ReferenceProperty Say I have two classes: class A(db.Model): class B(db.Model): a_reference = ReferenceProperty(A) I can now do the following: a = A() a.put() b = B(); b.a_reference = a.key() b.put() The documentation states the following two things: The ReferenceProperty value ca...
Need help understanding ReferenceProperty
Say I have two classes: class A(db.Model): class B(db.Model): a_reference = ReferenceProperty(A) I can now do the following: a = A() a.put() b = B(); b.a_reference = a.key() b.put() The documentation states the following two things: The ReferenceProperty value can be used as if it were a model instance, and t...
[ "A ReferenceProperty will always try to return an instance of the class that the stored key points to. If the referenced object has been deleted, I believe that you get back None. From the docs:\nobj1 = obj2.reference\n\nif not obj1:\n # Referenced entity was deleted.\n\nIf you want to get the key that was origi...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "referenceproperty" ]
stackoverflow_0003961449_google_app_engine_python_referenceproperty.txt
Q: What does this Python code mean? __author__="Sergio.Tapia" __date__ ="$18-10-2010 12:03:29 PM$" if __name__ == "__main__": print("Hello") print(__author__) Where does it get __main__ and __name__? Thanks for the help A: The __name__ variable is made available by the runtime. It's the name of the curre...
What does this Python code mean?
__author__="Sergio.Tapia" __date__ ="$18-10-2010 12:03:29 PM$" if __name__ == "__main__": print("Hello") print(__author__) Where does it get __main__ and __name__? Thanks for the help
[ "The __name__ variable is made available by the runtime. It's the name of the current module, the name under which it was imported. \"__main__\" is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed. \nThe if __name__ == \"__main__\": mechanism is t...
[ 9, 2 ]
[]
[]
[ "python", "python_datamodel" ]
stackoverflow_0003960958_python_python_datamodel.txt
Q: Nested Dictionaries in Python, with implicit creation of non-existing intermediate containers? I want to create a polymorphic structure that can be created on the fly with minimum typing effort and be very readable. For example: a.b = 1 a.c.d = 2 a.c.e = 3 a.f.g.a.b.c.d = cucu a.aaa = bau I do not want to create ...
Nested Dictionaries in Python, with implicit creation of non-existing intermediate containers?
I want to create a polymorphic structure that can be created on the fly with minimum typing effort and be very readable. For example: a.b = 1 a.c.d = 2 a.c.e = 3 a.f.g.a.b.c.d = cucu a.aaa = bau I do not want to create an intermediate container such as: a.c = subobject() a.c.d = 2 a.c.e = 3 My question is similar to ...
[ "I think at a minimum you need to do a check in __getattr__ that the requested attrib doesn't start and end with __. Attributes which match that description implement established Python APIs, so you shouldn't be instantiating those attributes. Even so you'll still end up implementing some API attribs, like for ex...
[ 1, 1 ]
[]
[]
[ "creation", "dictionary", "implicit", "nested", "python" ]
stackoverflow_0003955898_creation_dictionary_implicit_nested_python.txt
Q: What do these arguments refer to? In the method of the class urllib2.HTTPDefaultErrorHandler what so the arguments - self, req, fp, code,msg, hdrs - refer to? A: What does the documentation say? req will be a Request object, fp will be a file-like object with the HTTP error body, code will be the three-digit cod...
What do these arguments refer to?
In the method of the class urllib2.HTTPDefaultErrorHandler what so the arguments - self, req, fp, code,msg, hdrs - refer to?
[ "What does the documentation say?\nreq will be a Request object, fp will be a file-like object with the HTTP error body, code will be the three-digit code of the error, msg will be the user-visible explanation of the code and hdrs will be a mapping object with the headers of the error.\n", "\nReq refers to reques...
[ 3, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003961945_python_urllib2.txt
Q: Python - functions being called inside list bracket. How does it work? I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'. I found this piece of code, which works: list = ['X' if coord == '0' else coord for coord in printready] What I wo...
Python - functions being called inside list bracket. How does it work?
I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'. I found this piece of code, which works: list = ['X' if coord == '0' else coord for coord in printready] What I would like to know is exactly why this works (I understand the logic in the co...
[ "This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be \"infinite\".\n", "\nI'm a...
[ 7, 4 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003961923_list_comprehension_python.txt
Q: How to display an image from web? I have written this simple script in python: import gtk window = gtk.Window() window.set_size_request(800, 700) window.show() gtk.main() now I want to load in this window an image from web ( and not from my PC ) like this: http://www.dailygalaxy.com/photos/uncategorized/2007/05...
How to display an image from web?
I have written this simple script in python: import gtk window = gtk.Window() window.set_size_request(800, 700) window.show() gtk.main() now I want to load in this window an image from web ( and not from my PC ) like this: http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg How can I do that ? P....
[ "This downloads the image from a url, but writes the data into a gtk.gdk.Pixbuf instead of to a file:\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport urllib2\n\nclass MainWin:\n\n def destroy(self, widget, data=None):\n print \"destroy signal occurred\"\n gtk.main_quit()\n\n def __init__...
[ 15, 3, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003962180_gtk_pygtk_python.txt
Q: python 2to3 manual modification Is there a way to change python2.x source code to python 3.x manually. I guess using lib2to3 this can be done but I don't know exactly how to do this ? A: Yes, porting is what you are looking here. Porting is a non-trivial task that requires making various decisions about your cod...
python 2to3 manual modification
Is there a way to change python2.x source code to python 3.x manually. I guess using lib2to3 this can be done but I don't know exactly how to do this ?
[ "Yes, porting is what you are looking here.\nPorting is a non-trivial task that requires making various decisions about your code. For instance, whether or not you want to maintaing backward compatibility. There is no single, universal solution to porting. The way you port depends on your specific requirements.\nTh...
[ 4, 2 ]
[]
[]
[ "python", "python_2to3" ]
stackoverflow_0003950330_python_python_2to3.txt
Q: gtk: why do Gtk::Main::Iteration? What's the point of doing the Gtk::Main::iteration() on the last two lines of the answer to this question? I'm using pygtk, so the equivalent question would be, why do gtk.main_iteration_do()? Isn't the main loop that's running already taking care of this? A: When I wrote that a...
gtk: why do Gtk::Main::Iteration?
What's the point of doing the Gtk::Main::iteration() on the last two lines of the answer to this question? I'm using pygtk, so the equivalent question would be, why do gtk.main_iteration_do()? Isn't the main loop that's running already taking care of this?
[ "When I wrote that answer, I was assuming that the items would be added in a long loop - for example in a callback somewhere. Unless you're explicitly doing the work in a separate thread, then the main loop is in fact not running during that code. The code there tells the window to scroll to the bottom, but the scr...
[ 3, 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003961977_gtk_pygtk_python.txt
Q: Unable to print variables in Python when using def function I am trying to implement a simple neural net. I want to print the initial pattern, weights, activation. I then want it to print the learning process (i.e. every pattern it goes through as it learns). I am as yet unable to do this - it returns the initial ...
Unable to print variables in Python when using def function
I am trying to implement a simple neural net. I want to print the initial pattern, weights, activation. I then want it to print the learning process (i.e. every pattern it goes through as it learns). I am as yet unable to do this - it returns the initial and final pattern (whn I put print p in appropriate places), but ...
[ "You have a problem with the line:\nweights = [[[0]*n]*n]\n\nWhen you use*, you multiply object references. You are using the same n-len array of zeroes every time. This will cause:\n>>> weights[0][1][0] = 8\n>>> weights\n[[[8, 0, 0], [8, 0, 0], [8, 0, 0]]]\n\nThe first item of all the sublists is 8, because they a...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003962163_python.txt
Q: Python: removing a TKinter frame I want to remove a frame from my interface when a specific button is clicked. This is the invoked callback function def removeMyself(self): del self However, it doesn't remove itself. I'm probably just deleting the object in python without updating the interface ? thanks Updat...
Python: removing a TKinter frame
I want to remove a frame from my interface when a specific button is clicked. This is the invoked callback function def removeMyself(self): del self However, it doesn't remove itself. I'm probably just deleting the object in python without updating the interface ? thanks Update self.itemFrame = tk.Frame(parent) se...
[ "To remove, call either frm.pack_forget() or frm.grid_forget() depending on whether the frame was packed or grided.\nThen call frm.destroy() if you aren't going to use it again, or hold onto the reference and repack or regrid when you want to show it again.\n", "del does not delete anything. del something just re...
[ 23, 2, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003962247_python_tkinter.txt
Q: Is there a better way to specify named arguments when calling in Python template.render(current_user=current_user, thread=thread, messages=messages) Is there a dont-repeat-yourself compliant way to do whatever=whatever? Like a magic symbol to prepend the variable name with or something like this ~whatever, ~someth...
Is there a better way to specify named arguments when calling in Python
template.render(current_user=current_user, thread=thread, messages=messages) Is there a dont-repeat-yourself compliant way to do whatever=whatever? Like a magic symbol to prepend the variable name with or something like this ~whatever, ~something, ~etc?
[ "No, there is not.\nFor what it's worth, you can create a dictionary with your parameters and pass it with:\ntemplate.render(**parameters)\n\nNote: You should always favor readability!\n", "If your template.render() method accepts any keyword arguments, and you don't mind passing it extra arguments that it won't ...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003956804_python.txt
Q: Determine if a Python list is 95% the same? This question asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example: >>> ninety_five_same([1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]) Tr...
Determine if a Python list is 95% the same?
This question asks how to determine if every element in a list is the same. How would I go about determining if 95% of the elements in a list are the same in a reasonably efficient way? For example: >>> ninety_five_same([1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]) True >>> ninety_five_same([1,1,1,1,1,1,2,1]) # only...
[ ">>> from collections import Counter\n>>> lst = [1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]\n>>> _, freq = Counter(lst).most_common(1)[0]\n>>> len(lst)*.95 <= freq\nTrue\n\n", "Actually, there's an easy linear solution for similar problem, only with 50% constraint instead of 95%. Check this question, it's just ...
[ 16, 15, 6, 3, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "list", "python" ]
stackoverflow_0003957856_algorithm_list_python.txt
Q: Google App Engine Internationalization Help needed (Python) Has anyone any suggestions on how to use internationalization in app engine / webapp / python. I have seen some posts re - django - translation support but i cant seem to find enough info on how to make it work. What i need is a solution where browser ca...
Google App Engine Internationalization Help needed (Python)
Has anyone any suggestions on how to use internationalization in app engine / webapp / python. I have seen some posts re - django - translation support but i cant seem to find enough info on how to make it work. What i need is a solution where browser can detect language user can override and set strings in templates ...
[ "There are several options to consider. \n\nStandard gettext(). See this code example. The code is outdated: there is a standard way to manage cookies and sessions, so it should be rewritten for the real usage. \n\nSometimes this method fails, see this issue. Usually it's resolved by just reuploading an application...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "internationalization", "python" ]
stackoverflow_0002236153_google_app_engine_internationalization_python.txt
Q: missing messages when reading with non-blocking udp I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem. Here are three scripts used to show the problem. send.py: import socket, sys s ...
missing messages when reading with non-blocking udp
I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem. Here are three scripts used to show the problem. send.py: import socket, sys s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) host = ...
[ "If the datagrams are getting to the host (as your wireshark log shows) then the first place I'd look is the size of your socket recv buffer, make it as big as you can, and run as fast as you can.\nOf course this is completely expected with UDP. You should assume that datagrams can be thrown away at any point and f...
[ 8, 8 ]
[]
[]
[ "nonblocking", "python", "sockets", "udp", "winsock2" ]
stackoverflow_0003960680_nonblocking_python_sockets_udp_winsock2.txt
Q: Is it typical to have more than a dozen django applications in your project root for medium-high scale sites? Does it not feel bloated? I was looking at the INSTALLED_APPS of django-mingus: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.s...
Is it typical to have more than a dozen django applications in your project root for medium-high scale sites? Does it not feel bloated?
I was looking at the INSTALLED_APPS of django-mingus: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.sitemaps', 'django.contrib.flatpages', 'django.contrib.redirects', 'django_extensio...
[ "I think it's quite common to find a lot of apps in your INSTALLED_APPS. To keep some system in your package/directory structure I think it's recommendable to have your apps inside an apps folder within your project root, while keeping other third party apps, that you do not touch somewhere else on your PYTHONPATH....
[ 5, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003962177_django_python.txt
Q: How to display all words that contain these characters? I have a text file and I want to display all words that contains both z and x characters. How can I do that ? A: If you don't want to have 2 problems: for word in file('myfile.txt').read().split(): if 'x' in word and 'z' in word: print word A: ...
How to display all words that contain these characters?
I have a text file and I want to display all words that contains both z and x characters. How can I do that ?
[ "If you don't want to have 2 problems:\nfor word in file('myfile.txt').read().split():\n if 'x' in word and 'z' in word:\n print word\n\n", "Assuming you have the entire file as one large string in memory, and that the definition of a word is \"a contiguous sequence of letters\", then you could do somet...
[ 12, 8, 4, 3, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003962846_python.txt
Q: Problem with Prototype Ajax.Request in Internet Explorer 8 prompting file download Have a set of prototype-enabled ajax code that is working in all browsers other than IE. In IE8 the JSON, that otherwise gets returned to the onSuccess handler function specified in Ajax.Request, gets thrown into a file download str...
Problem with Prototype Ajax.Request in Internet Explorer 8 prompting file download
Have a set of prototype-enabled ajax code that is working in all browsers other than IE. In IE8 the JSON, that otherwise gets returned to the onSuccess handler function specified in Ajax.Request, gets thrown into a file download stream which pops up and prompts for where to download. askForm = $('askForm'); var askUrl...
[ "This problem has been solved. Crazy issue here but it turns out that there was a javascript error that was preventing the script from executing and the standard form submit was occurring thru the browser thus returning AJAX code as a file download prompt. The form was designed in such a way that javascript-disable...
[ 3, 0 ]
[]
[]
[ "ajax", "django", "internet_explorer_8", "prototypejs", "python" ]
stackoverflow_0003956287_ajax_django_internet_explorer_8_prototypejs_python.txt
Q: How to match patterns "begins with A or ends with B" with Python regular expression? r'(^|^A)(\S+)(B$|$)' results to matches everything, which actually equals to ^\S$. How to write one matches "begins with A or ends with B, may both but not neither?" PS: I also need refer to group (\S+) in the substring module. E...
How to match patterns "begins with A or ends with B" with Python regular expression?
r'(^|^A)(\S+)(B$|$)' results to matches everything, which actually equals to ^\S$. How to write one matches "begins with A or ends with B, may both but not neither?" PS: I also need refer to group (\S+) in the substring module. Example: Match Aanything, anythingB, and refer anything group in the replace.
[ "(^A.*B$)|(^A.*$)|(^.*B$)\n\n", "^A|B$ or ^A|.*B$ (depending whether the match function is matching from the beginning)\nUPDATE\nit's difficult to write single regexp for this..\na possibility is:\nmatch = re.match(r'^(?:A(\\S+))|(?:(\\S+)B)$', string)\nif match:\n capture = max(match.groups())\n# because matc...
[ 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003957164_python_regex.txt
Q: What makes some programming languages more powerful than others? I'm going to reveal my ignorance here, but in my defense, I'm an accounting major, and I've never taken a computer science class. I'm about to start a new project, and I'm considering using Python instead of PHP, even though I am much more adept with...
What makes some programming languages more powerful than others?
I'm going to reveal my ignorance here, but in my defense, I'm an accounting major, and I've never taken a computer science class. I'm about to start a new project, and I'm considering using Python instead of PHP, even though I am much more adept with PHP, because I have heard that Python is a more powerful language. Th...
[ "When Paul Graham talked about Lisp being the most powerful language available, he meant most expressive. You can express any program in any turing complete language. That's the whole point. What makes one language better than another (for a particular task) is its ability to define a given program more concisely o...
[ 8, 4, 4, 1, 0, 0 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0003963438_programming_languages_python.txt
Q: python regex question What is the best way to search for matching words inside a string? Right now I do something like the following: if re.search('([h][e][l][l][o])',file_name_tmp, re.IGNORECASE): Which works but its slow as I have probably around 100 different regex statements searching for full words so I'd li...
python regex question
What is the best way to search for matching words inside a string? Right now I do something like the following: if re.search('([h][e][l][l][o])',file_name_tmp, re.IGNORECASE): Which works but its slow as I have probably around 100 different regex statements searching for full words so I'd like to combine several using...
[ "Can you try:\nif 'hello' in longtext:\n\nor\nif 'HELLO' in longtext.upper():\n\nto match hello/Hello/HELLO.\n", ">>> words = ('hello', 'good\\-bye', 'red', 'blue')\n>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)\n>>> sentence = 'SAY HeLLo TO reD, good-bye to Blue.'\n>>> print pattern.findal...
[ 3, 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003962241_python_regex.txt
Q: Accept lowercase or uppercase letter in Python Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase? elif choice == "m": A: One of elif choice in ("m", "M"): elif choice in "mM": ...
Accept lowercase or uppercase letter in Python
Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase? elif choice == "m":
[ "One of\nelif choice in (\"m\", \"M\"):\n\nelif choice in \"mM\": # false positive if choice == ''\n\nelif choice == 'm' or choice == 'M':\n\nelif choice.lower() == 'm':\n\nIn terms of maintainability, the 4th alternative is better when you want to extend to case-insensitive comparison of mult...
[ 14, 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003963161_python.txt
Q: Unable to parse the output from HTTPConnection.debuglevel I am trying to programmability check the output of a tcp stream. I am able to get the results of the tcp stream by turning on debug in HTTPConnection but how do I read the data and evaluate it with say a regular expression. I keep getting "TypeError: expe...
Unable to parse the output from HTTPConnection.debuglevel
I am trying to programmability check the output of a tcp stream. I am able to get the results of the tcp stream by turning on debug in HTTPConnection but how do I read the data and evaluate it with say a regular expression. I keep getting "TypeError: expected string or buffer". Is there a way to convert the result t...
[ "The debug information httplib provides you there, which you see in your terminal, is not actually part of the object returned by urllib2.urlopen(). Instead, it's printed directly to your process's sys.stdout. There's no way to change this behaviour in httplib, unfortunately. It's not entirely clear to me what you'...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003963499_python.txt
Q: Tkinter unexpected behaviour I've been writing a long GUI in Python using Tkinter. One thing that I don't understand is why I can't bind events to widgets in a loop. In the code below, binding works well if I do it manually (commented out code) but not in a for loop. Am I doing something wrong? import Tkinter root...
Tkinter unexpected behaviour
I've been writing a long GUI in Python using Tkinter. One thing that I don't understand is why I can't bind events to widgets in a loop. In the code below, binding works well if I do it manually (commented out code) but not in a for loop. Am I doing something wrong? import Tkinter root = Tkinter.Tk() b1 = Tkinter.Butt...
[ "Your closures (lambdas) are not working as you expect them to. They keep references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.\nHere's an illustration of the behaviour:\n>>> k = []\n>>> for i in range(5):\n... k.append(lambda:...
[ 3, 3 ]
[]
[]
[ "events", "loops", "python", "tkinter", "user_interface" ]
stackoverflow_0003963613_events_loops_python_tkinter_user_interface.txt
Q: QComboBox replacing edit text if case differs from existing item I'm having a problem with QComboBox not allowing me to change the edit text to anything existing item of differing case. Example code is below. What I'd like to do is enter 'one' into a combo box already containing the item 'One' without the side ...
QComboBox replacing edit text if case differs from existing item
I'm having a problem with QComboBox not allowing me to change the edit text to anything existing item of differing case. Example code is below. What I'd like to do is enter 'one' into a combo box already containing the item 'One' without the side effect of the text being changed to 'One'. Currently it's changed bac...
[ "from PyQt4.QtGui import * \nfrom PyQt4.QtCore import SIGNAL, Qt, QEvent\n\n\nclass MyComboBox(QComboBox):\n def __init__(self):\n QComboBox.__init__(self)\n\n def event(self, event):\n if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return:\n self.addItem(self.currentTex...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qcombobox", "qt4" ]
stackoverflow_0003957445_pyqt_pyqt4_python_qcombobox_qt4.txt
Q: How to access Apples iCal-Server via Python I'm trying to access Apples iCal-Server on a Mac OS X Snow Leopard Server via Python. The server is up and running and working with it via the iCal-Application is just fine. Now I need to access this server via Python to use it as backend for resource planning. I have al...
How to access Apples iCal-Server via Python
I'm trying to access Apples iCal-Server on a Mac OS X Snow Leopard Server via Python. The server is up and running and working with it via the iCal-Application is just fine. Now I need to access this server via Python to use it as backend for resource planning. I have already looked at the CalDav-Module (http://package...
[ "[Not a solution but to debug]\nFrom the example given in the caldav module documentation:\nfrom datetime import datetime\nimport caldav\nfrom caldav.elements import dav, cdav\n\n# Principal url\nurl = \"https://user:pass@hostname/user/Calendar\"\n\nclient = caldav.DAVClient(url)\nprincipal = caldav.Principal(clien...
[ 1 ]
[]
[]
[ "caldav", "icalendar", "python" ]
stackoverflow_0003758358_caldav_icalendar_python.txt
Q: Convert File to HEX String Python How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful. A: import binascii filename = 'test.dat' with open(filename, 'rb') as f: content = f.read() print(binascii.hexlify(content))
Convert File to HEX String Python
How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.
[ "import binascii\nfilename = 'test.dat'\nwith open(filename, 'rb') as f:\n content = f.read()\nprint(binascii.hexlify(content))\n\n" ]
[ 68 ]
[]
[]
[ "file", "hex", "python", "string" ]
stackoverflow_0003964245_file_hex_python_string.txt
Q: General convention for python libraries that also have an interface module? Right now I've got a project that has the following layout: foo/ __init__.py __main__.py foo.py In this case, foo.py is actually the main api file, so developers are meant to do "from foo import foo", but I also wanted to make it so...
General convention for python libraries that also have an interface module?
Right now I've got a project that has the following layout: foo/ __init__.py __main__.py foo.py In this case, foo.py is actually the main api file, so developers are meant to do "from foo import foo", but I also wanted to make it so that end users could just run ~$ foo and get an interface. which, when I do a di...
[ "Calling a module __main__.py is a bad idea, since that name has a special meaning. Instead use a main sentinel in __init__.py and create a script that does exec python -m foo.\n", "Combining Ignacio Vazquez-Abrams' answer with some googling that resulted in me finding this article about using _main_.py, I think ...
[ 3, 1 ]
[]
[]
[ "conventions", "distribution", "distutils", "python" ]
stackoverflow_0003962628_conventions_distribution_distutils_python.txt
Q: Are Python functions "compile" and "compiler.parse" safe (sandboxed)? I plan to use those functions in web-environment, so my concern is if those functions can be exploited and used for executing malicious software on the server. Edit: I don't execute the result. I parse the AST tree and/or catch SyntaxError. This...
Are Python functions "compile" and "compiler.parse" safe (sandboxed)?
I plan to use those functions in web-environment, so my concern is if those functions can be exploited and used for executing malicious software on the server. Edit: I don't execute the result. I parse the AST tree and/or catch SyntaxError. This is the code in question: try: #compile the code and check for syntax e...
[ "I think the more interesting question is what are you doing with the compiled functions? Running them is definitely unsafe.\nI've tested the few exploits i could think of seeing as its just a syntax checker (can't redefine classes/functions etc) i don't think there is anyway to get python to execute arbitrary code...
[ 4, 2, 2, 1, 1 ]
[]
[]
[ "python", "security" ]
stackoverflow_0003964077_python_security.txt
Q: Mark File For Removal from Python? In one of my scripts, I need to delete a file that could be in use at the time. I know that I can't remove the file that is in use until it isn't anymore, but I also know that I can mark the file for removal by the Operating System (Windows XP). How would I do this in Python? A:...
Mark File For Removal from Python?
In one of my scripts, I need to delete a file that could be in use at the time. I know that I can't remove the file that is in use until it isn't anymore, but I also know that I can mark the file for removal by the Operating System (Windows XP). How would I do this in Python?
[ "...and another version which doesn't depend on pywin32 binaries.\nimport ctypes\nMOVEFILE_DELAY_UNTIL_REBOOT = 4\n\nctypes.windll.kernel32.MoveFileExA(\"/path/to/lockedfile.ext\", None,\n MOVEFILE_DELAY_UNTIL_REBOOT)\n\n", "import win32file\nimport win32api\nwin32file.MoveFi...
[ 7, 5, 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003964400_file_python.txt
Q: Why this request doesn't work? I want to make a simple stupid twitter app using Twitter API. If I request this page from my browser it does work: http://search.twitter.com/search.atom?q=hello&rpp=10&page=1 but if I request this page from python using urllib or urllib2 most of the times it doesn't work: response =...
Why this request doesn't work?
I want to make a simple stupid twitter app using Twitter API. If I request this page from my browser it does work: http://search.twitter.com/search.atom?q=hello&rpp=10&page=1 but if I request this page from python using urllib or urllib2 most of the times it doesn't work: response = urllib2.urlopen("http://search.twit...
[ "The code seems alright.\nThe following worked. \n>>> import urllib\n>>> import urllib2\n>>> user_agent = 'curl/7.21.1 (x86_64-apple-darwin10.4.0) libcurl/7.21.1'\n>>> url='http://search.twitter.com/search.atom?q=hello&rpp=10&page=1'\n>>> headers = { 'User-Agent' : user_agent }\n>>> req = urllib2.Request(url, None,...
[ 2, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003964519_python_urllib2.txt
Q: is there a limit to the (CSV) filesize that a Python script can read/write? I will be writing a little Python script tomorrow, to retrieve all the data from an old MS Access database into a CSV file first, and then after some data cleansing, munging etc, I will import the data into a mySQL database on Linux. I int...
is there a limit to the (CSV) filesize that a Python script can read/write?
I will be writing a little Python script tomorrow, to retrieve all the data from an old MS Access database into a CSV file first, and then after some data cleansing, munging etc, I will import the data into a mySQL database on Linux. I intend to use pyodbc to make a connection to the MS Access db. I will be running the...
[ "Memory usage for csvfile.reader and csvfile.writer isn't proportional to the number of records, as long as you iterate correctly and don't try to load the whole file into memory. That's one reason the iterator protocol exists. Similarly, csvfile.writer writes directly to disk; it's not limited by available memor...
[ 5, 3, 1, 0 ]
[]
[]
[ "csv", "ms_access", "odbc", "python" ]
stackoverflow_0003964378_csv_ms_access_odbc_python.txt
Q: How can I ensure that my Python regular expression outputs a dictionary? I'm using Beej's Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this: jsonFlickrApi({'photos': 'example'}) I want to access the returned data as a dictionary, so I have: photos = "jsonFlickrApi({'phot...
How can I ensure that my Python regular expression outputs a dictionary?
I'm using Beej's Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this: jsonFlickrApi({'photos': 'example'}) I want to access the returned data as a dictionary, so I have: photos = "jsonFlickrApi({'photos': 'test'})" # to match {'photos': 'example'} response_parser = re.compile(...
[ "If you're using Python 2.6, you can just use the JSON module to parse JSON stuff.\nimport json\njson.loads(dictString)\n\nIf you're using an earlier version of Python, you can download the simplejson module and use that.\nExample:\n>>> json.loads('{\"hello\" : 4}')\n{u'hello': 4}\n\n", "You need to use a JSON pa...
[ 2, 1 ]
[]
[]
[ "json", "python", "regex" ]
stackoverflow_0003964621_json_python_regex.txt
Q: AttributeError Exception raised when trying to bulk delete items in Django I'm trying to bulk delete all of the comments on a dev instance of my Django website and Django is raising an AttributeException. I've got the following code on a python prompt: >>> from django.contrib.comments.models import Comment >>> Com...
AttributeError Exception raised when trying to bulk delete items in Django
I'm trying to bulk delete all of the comments on a dev instance of my Django website and Django is raising an AttributeException. I've got the following code on a python prompt: >>> from django.contrib.comments.models import Comment >>> Comment.objects.all().delete() Traceback (most recent call last): File "<console>...
[ "Edited: Originally I thought you couldn't do delete() on a QuerySet and was going to recommend you iterate over the items, but apparently you can do bulk deletes like that. Trying to iterate over the QuerySet might give you a better clue as to what's wrong, though.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003964687_django_python.txt
Q: How do I calculate the magnitude of the velocity of my mouse cursor, in Python? http://dl.dropbox.com/u/779859/speedCalc_puradata.JPG I achieved it in pure data, have a look at the schematic of what I'm thinking: Recieving Midi Control input from ctlin 20 and 21 Pipe delays whatever signal it recieves Pythagoras ...
How do I calculate the magnitude of the velocity of my mouse cursor, in Python?
http://dl.dropbox.com/u/779859/speedCalc_puradata.JPG I achieved it in pure data, have a look at the schematic of what I'm thinking: Recieving Midi Control input from ctlin 20 and 21 Pipe delays whatever signal it recieves Pythagoras Viola, the speed of the input. The units don't matter, as long as it is absolute. I ...
[ "What you are describing will give you the magnitude of the velocity times the length of the time interval of measurement. The actual velocity will be a vector. You can get its first coordinate as (posX - delayed_posX)/t and its second coordinate as (posY-delayed_posY)/t where t is the time interval between the mea...
[ 2, 0 ]
[]
[]
[ "mouse_cursor", "python" ]
stackoverflow_0003956539_mouse_cursor_python.txt
Q: How do you pass multiple arguments to __setstate__? I am doing deepcopy on a class I designed, which has multiple lists as attributes to it. With a single list, this is solvable by overriding getstate to return that list, and setstate to set that list, but setstate seems unable to take multiple parameters. How is...
How do you pass multiple arguments to __setstate__?
I am doing deepcopy on a class I designed, which has multiple lists as attributes to it. With a single list, this is solvable by overriding getstate to return that list, and setstate to set that list, but setstate seems unable to take multiple parameters. How is this accomplished?
[ "You can have __getstate__ return (and __setstate__ accept) a list of lists, or a dict (if you implement __getstate__ and __setstate__, __getstate__ doesn't have to return a dict)\nimport pickle\n\nclass Example:\n def __init__(self):\n self.list1 = [1]\n self.list2 = [2]\n\n def __getstate__(se...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003964895_python.txt
Q: Image analysis in R I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns. I am aware of relevant packages available in ...
Image analysis in R
I would like to know how I would go about performing image analysis in R. My goal is to convert images into matrices (pixel-wise information), extract/quantify color, estimate the presence of shapes and compare images based on such metrics/patterns. I am aware of relevant packages available in Python (suggestions relev...
[ "I'd start with EBImage - check out the vignette which demonstrates many of the tasks you mention.\n", "Also check out the RASTER package on the R-Forge website:\nhttp://r-forge.r-project.org/projects/raster/\nIt is not released to CRAN yet but it is an excellent package to import, analyse, extract, subset images...
[ 9, 8, 1, 1, 1 ]
[]
[]
[ "analysis", "image", "python", "r" ]
stackoverflow_0003955077_analysis_image_python_r.txt
Q: Python - Function has a list as argument. How to return another list without changing the first? I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do. def do_play(value, slot, board): temp=board (i,j) = slot temp[i][j] ...
Python - Function has a list as argument. How to return another list without changing the first?
I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do. def do_play(value, slot, board): temp=board (i,j) = slot temp[i][j] = value return temp board is a list of lists. value is an integer. slot is and integer tuple. Wha...
[ "temp=board does not make a new board. It makes the temp variable reference the very same list as board. So changing temp[i][j] changes board[i][j] too.\nTo make a copy, use\nimport copy\ntemp=copy.deepcopy(board)\n\n\nNote that temp=board[:] makes temp refer to a new list (different than board, but the contents (t...
[ 10, 5, 2, 2, 0 ]
[]
[]
[ "function_declaration", "python", "return_value" ]
stackoverflow_0003964967_function_declaration_python_return_value.txt
Q: How to convert base 10 to base X? I'm wanting to write a program that asks the user to enter a number in base 10, and to enter the base that they want to convert to. What is the highest base that I can convert to without having my program become incredibly complicated? I'm thinking Base 9, because after 10 (which ...
How to convert base 10 to base X?
I'm wanting to write a program that asks the user to enter a number in base 10, and to enter the base that they want to convert to. What is the highest base that I can convert to without having my program become incredibly complicated? I'm thinking Base 9, because after 10 (which is already given), the bases start to u...
[ "If you put the digit values in a string then the base you can use gets very high very easily.\nradixdigits = '0123456789ABCDEFGHI...'\n\nAnd then you can do divmod() with the length of the string in order to get the current digit, and index the string with that number.\n", "\nWhat is the highest base that I can ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003964926_python.txt
Q: Python: How to export Sympy image to png? Python: How to export Sympy image to png? Who has any idea with this? A: Use the saveimage method: import sympy x, y, z = sympy.symbols('xyz') p = sympy.Plot(x * y ** 3 - y * x ** 3) p.saveimage('/tmp/plot.png', format='png')
Python: How to export Sympy image to png?
Python: How to export Sympy image to png? Who has any idea with this?
[ "Use the saveimage method:\nimport sympy\nx, y, z = sympy.symbols('xyz')\np = sympy.Plot(x * y ** 3 - y * x ** 3)\np.saveimage('/tmp/plot.png', format='png')\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_imaging_library", "sympy" ]
stackoverflow_0003964968_python_python_imaging_library_sympy.txt
Q: Creating a custom file like object python suggestions? Hi i am looking to implement my own custom file like object for an internal binary format we use at work(i don't really want to go into too much detail because i don't know if i can). I am trying to go for a more pythonic way of doing things since currently we...
Creating a custom file like object python suggestions?
Hi i am looking to implement my own custom file like object for an internal binary format we use at work(i don't really want to go into too much detail because i don't know if i can). I am trying to go for a more pythonic way of doing things since currently we have two functions read/write(each ~4k lines of code) which...
[ "What makes up a \"file-like\" actually depends on what you intend to use it for; not all methods are required to be implemented (or to have a sane implementation).\nHaving said that, the file and iterator docs are what you want.\n", "Why not stuff your data in StringIO? Otherwise, you can look at the documentati...
[ 5, 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003965036_file_python.txt
Q: Python: determine length of sequence of equal items in list I have a list as follows: l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2] I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be: [(0, 6), (1, 6), (0, 4), (2, 3)] (or a similar format). I thought about u...
Python: determine length of sequence of equal items in list
I have a list as follows: l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2] I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be: [(0, 6), (1, 6), (0, 4), (2, 3)] (or a similar format). I thought about using a defaultdict but it counts the occurrences of each item and...
[ "You almost surely want to use itertools.groupby:\nl = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]\nanswer = []\nfor key, iter in itertools.groupby(l):\n answer.append((key, len(list(iter))))\n\n# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]\n\nIf you want to make it more memory efficient, yet add more complexity, you...
[ 16, 3 ]
[]
[]
[ "count", "list", "python" ]
stackoverflow_0003964963_count_list_python.txt
Q: Nested SELECT queries sometimes stall I've been using sqlite3 in a python application, and when testing it, my queries sometimes cause the program to freeze up. A rough (from memory) example: SELECT id,name FROM main_table WHERE name IN (SELECT name FROM another_table WHERE another_table.attribute IN ('foo', 'b...
Nested SELECT queries sometimes stall
I've been using sqlite3 in a python application, and when testing it, my queries sometimes cause the program to freeze up. A rough (from memory) example: SELECT id,name FROM main_table WHERE name IN (SELECT name FROM another_table WHERE another_table.attribute IN ('foo', 'bar', 'baz')) Often, the first time I attem...
[ "You didn't mention anything about indexes... name in both tables should be indexed at a minimum.\nHere's an equivalent using JOINs:\nSELECT DISTINCT\n x.id,\n x.name \n FROM main_table x\n JOIN ANOTHER_TABLE y ON y.name = x.name\n AND y.attribute IN ('foo', 'bar', 'baz')\n\nBut m...
[ 1, 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0003965178_python_sql_sqlite.txt
Q: Redis key management So im working with redis in a python app. any advice on key management? i try and keep all redis calls in one location but something seems off with hardcoding keys everywhere. tips? A: I use a set of wrapper classes that handle key generation, something like: public User Get(string username)...
Redis key management
So im working with redis in a python app. any advice on key management? i try and keep all redis calls in one location but something seems off with hardcoding keys everywhere. tips?
[ "I use a set of wrapper classes that handle key generation, something like:\npublic User Get(string username) {\n return redis.Get(\"user:\"+username);\n}\n\nI have an instance of each of these classes globally available, so just need to call\nServer.Users.Get(username);\n\nThat's in .NET of course, but somethin...
[ 2, 1 ]
[]
[]
[ "python", "redis" ]
stackoverflow_0003450027_python_redis.txt
Q: rotating the tires in a car (open gl) Based on the answer i got for the same question earlier, i changed my code, as per the homework i had to use glmultmatrix. But this is not working. Here is the code, what i am doing is that i translate the center of tire to the center of car, rotate the tire, and then translat...
rotating the tires in a car (open gl)
Based on the answer i got for the same question earlier, i changed my code, as per the homework i had to use glmultmatrix. But this is not working. Here is the code, what i am doing is that i translate the center of tire to the center of car, rotate the tire, and then translate back. But it is not placing back the tire...
[ "I'm pretty sure that it is because this line\nC = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x - self.carCenterX , y - self.carCenterY, z - self.carCenterZ, 1)\n\nshould be\nC = self.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -x , -y, -z, 1)\n\nI'm not sure why you were using x - self.carCenterX and s...
[ 1 ]
[]
[]
[ "opengl", "python" ]
stackoverflow_0003965166_opengl_python.txt
Q: Method signature for Jacobian of a least squares function in scipy Can anyone provide an example of providing a Jacobian to a least squares function in scipy? I can't figure out the method signature they want - they say it should be a function, yet it's very hard to figure out what input parameters in what order t...
Method signature for Jacobian of a least squares function in scipy
Can anyone provide an example of providing a Jacobian to a least squares function in scipy? I can't figure out the method signature they want - they say it should be a function, yet it's very hard to figure out what input parameters in what order this function should accept.
[ "Here's the exponential decay fitting that I got to work with this:\nimport numpy as np\nfrom scipy.optimize import leastsq\n\ndef f(var,xs):\n return var[0]*np.exp(-var[1]*xs)+var[2]\n\ndef func(var, xs, ys):\n return f(var,xs) - ys\n\ndef dfunc(var,xs,ys):\n v = np.exp(-var[1]*xs)\n return [v,-var[0]*...
[ 14 ]
[]
[]
[ "least_squares", "numpy", "python", "scipy" ]
stackoverflow_0003965404_least_squares_numpy_python_scipy.txt
Q: How come there's no C# equivalent of python's doctest feature? Seems like it would be a good way to introduce some people to unit testing. A: Well for one thing, the documentation for doctest talks about "interactive Python sessions". There's no equivalent of that in C#... so how would the output be represented?...
How come there's no C# equivalent of python's doctest feature?
Seems like it would be a good way to introduce some people to unit testing.
[ "Well for one thing, the documentation for doctest talks about \"interactive Python sessions\". There's no equivalent of that in C#... so how would the output be represented? How would you perform all the necessary setup?\nI dare say such a thing would be possible, but personally I think that at least for C#, it's ...
[ 6 ]
[]
[]
[ ".net", "c#", "doctest", "python", "unit_testing" ]
stackoverflow_0003965547_.net_c#_doctest_python_unit_testing.txt
Q: How to pass variable arguments from bash script to python script I've been trying to solve this issue for sometime now with no luck. The crust of the situation is that I'm using a bash script to send parameters to a a python script: Example: foo.sh calls bar.py....the call looks like: bar.py $var1 $var2 ... $varn ...
How to pass variable arguments from bash script to python script
I've been trying to solve this issue for sometime now with no luck. The crust of the situation is that I'm using a bash script to send parameters to a a python script: Example: foo.sh calls bar.py....the call looks like: bar.py $var1 $var2 ... $varn The python script then prints all the arguments using the sys.argv arr...
[ "Edit, since code has been posted\nYour code is doing the correct thing - except that the output from your bar.py script is being captured into the array joined. Since it looks like you're not printing out the contents of joined, you never see any output.\nHere's a demonstration:\nFile pybash.sh\n#!/bin/bash\n\ndec...
[ 6, 1 ]
[ "I have pretty much the exact setup that you are describing, and this is how my bash script looks:\nVAR1=...\nVAR2=...\nVAR3=...\n\npython my_script.py $VAR1 $VAR2 $VAR3 \n\n" ]
[ -2 ]
[ "arguments", "bash", "parameters", "python" ]
stackoverflow_0003955571_arguments_bash_parameters_python.txt
Q: about python list step issue when the element is long type In [2]: list=range(627) In [3]: list[::150] Out[3]: [0, 150, 300, 450, 600] the above code is right,but if i use the bellow code,caution:the l means long type, the return result is not like above,what's the hell? In [4]: list=[1323l,123123l,4444l,12312312l...
about python list step issue when the element is long type
In [2]: list=range(627) In [3]: list[::150] Out[3]: [0, 150, 300, 450, 600] the above code is right,but if i use the bellow code,caution:the l means long type, the return result is not like above,what's the hell? In [4]: list=[1323l,123123l,4444l,12312312l] In [5]: list=[1323l,123123l,4444l,12312312l] In [6]: list[::2]...
[ "The step denotes the multiples of indices that are included in the slice, not of the actual values contained in the array. In your second example:\nlist[0] = 1323L\nlist[1] = 123123L\nlist[2] = 4444L\nlist[3] = 12312312L\n\nSince you're using the default argument for the start of the slice, it will start at the fi...
[ 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003965507_list_python.txt
Q: Python Boto S3 to work with Custom Domains in Amazon S3 How do I use the Python Boto library with S3 where the URL's it generate will be my CNAME'd subdomain to the Amazon S3 Server. By default it uses the default format BUCKETNAME.s3.amazonaws.com but S3 supports custom domain aliasing using CNAME (so you can ha...
Python Boto S3 to work with Custom Domains in Amazon S3
How do I use the Python Boto library with S3 where the URL's it generate will be my CNAME'd subdomain to the Amazon S3 Server. By default it uses the default format BUCKETNAME.s3.amazonaws.com but S3 supports custom domain aliasing using CNAME (so you can have custom.domain.com -> CNAME -> custom.domain.com.s3.amazona...
[ "\nYour CNAME records must be already pointing to your S3 bucket.\nYour S3 bucket needs to also be named custom.domain.com\nVerify you are able to access your files from custom.domain.com in your browser.\n\nOnce that's done, the following snippet I wrote will print the URL's to all the files within a key:\nimport ...
[ 2 ]
[]
[]
[ "amazon_s3", "boto", "cname", "python", "subdomain" ]
stackoverflow_0002366093_amazon_s3_boto_cname_python_subdomain.txt
Q: Stock Symbols using python I am looking for some stock symbol look-up API. I could able to query yahoo finance with a symbol & could able to retrieve the stock price & other details. Is there any API for stock symbol searches Any help would be great .. Thanks A: You could use Python's urllib or the mechanise lib...
Stock Symbols using python
I am looking for some stock symbol look-up API. I could able to query yahoo finance with a symbol & could able to retrieve the stock price & other details. Is there any API for stock symbol searches Any help would be great .. Thanks
[ "You could use Python's urllib or the mechanise library to scrape the data from a website which publishes this data. Mechanise would be a better choice if the website requires some interaction before you can get hold of the data (like logging in).\nEDIT - for getting stock quote for BT from Yahoo's UK site:\n>>> i...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002910808_python.txt