content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Can I query Grok's ZODB instance outside the web application scope?
I have a grok-based webapp that persists data using ZODB. Can I query the object db offline i.e. from a python script that would be run on the webserver hosting the grok/paste webapp instance?
And would there be any issues in doing so while the we... | Can I query Grok's ZODB instance outside the web application scope? | I have a grok-based webapp that persists data using ZODB. Can I query the object db offline i.e. from a python script that would be run on the webserver hosting the grok/paste webapp instance?
And would there be any issues in doing so while the web server is interacting with the database simultaneously?
| [
"You can open the ZODB with python and inspect the data, yes. To do so while you also run the web site, you'll need to use a concurrency layer like ZEO or RelStorage; plain FileStorage does not support concurrent access otherwise.\n"
] | [
2
] | [] | [] | [
"grok",
"python",
"zodb",
"zope"
] | stackoverflow_0008696466_grok_python_zodb_zope.txt |
Q:
render latex / mathml with PySide
I have a small program that renders a typed equation on the fly using SymPy's 'pretty-printing' facility. This works fine but doesn't look very professional. As SymPy will produce latex or mml I was wondering whether these could be rendered graphically with a PySide widget? I woul... | render latex / mathml with PySide | I have a small program that renders a typed equation on the fly using SymPy's 'pretty-printing' facility. This works fine but doesn't look very professional. As SymPy will produce latex or mml I was wondering whether these could be rendered graphically with a PySide widget? I would obviously need to change the 'QTextBr... | [
"One hacky way would be to display it in a QWebiew using something like MathJax\nOr, inspired by this question you could use the SVGMath module to convert form MathML to SVG, which can then be displayed in a QSvgWidget\n"
] | [
0
] | [] | [] | [
"latex",
"mathml",
"pyside",
"python",
"sympy"
] | stackoverflow_0005203996_latex_mathml_pyside_python_sympy.txt |
Q:
Writing data so repeatedly in SQLite Database with python
I want to use SQLite for my GUI Python application but I have to update database every 500 MS without effecting the performance of my program.
I'm using PyQt4,So I thought about using QThread but it seems difficult to deal with, so I wondered if it was the ... | Writing data so repeatedly in SQLite Database with python | I want to use SQLite for my GUI Python application but I have to update database every 500 MS without effecting the performance of my program.
I'm using PyQt4,So I thought about using QThread but it seems difficult to deal with, so I wondered if it was the best way before really trying to understand it.
My Question is:... | [
"According to the fact that python implementation rely on the GIL, even with using threads or timer you won't be able to do something (potentially costly) in your program without effecting the global performance of the program.\nI will suggest you to have a look to multiprocessing module to get around of this limit... | [
1
] | [] | [] | [
"database",
"database_performance",
"pyqt4",
"python",
"sqlite"
] | stackoverflow_0008682195_database_database_performance_pyqt4_python_sqlite.txt |
Q:
Using Python to create a Unit Circle calculator?
As a younger programmer, I'm always trying to look for applications of my skills.
Anyways, I'm currently taking trig and we're working on unit circles, the formula for converting from degrees to a coordinate is (sinθ, cosθ) (to the best of my knowledge).
However, th... | Using Python to create a Unit Circle calculator? | As a younger programmer, I'm always trying to look for applications of my skills.
Anyways, I'm currently taking trig and we're working on unit circles, the formula for converting from degrees to a coordinate is (sinθ, cosθ) (to the best of my knowledge).
However, the difficulty I'm having is that I need to keep the val... | [
"It looks like you need a third-party module such as sympy:\n>>> import sympy\n>>> for i in range(0, 360, 15):\n... print i, sympy.sin(sympy.Rational(i, 180) * sympy.pi)\n...\n\n0 0\n15 sin(pi/12)\n30 1/2\n45 2**(1/2)/2\n60 3**(1/2)/2\n75 sin(5*pi/12)\n90 1\n105 sin(5*pi/12)\n120 3**(1/2)/2\n135 2**(1/2)/2\n150... | [
5,
4,
0,
0,
0
] | [] | [] | [
"fractions",
"math",
"python",
"symbolic_math",
"trigonometry"
] | stackoverflow_0008698564_fractions_math_python_symbolic_math_trigonometry.txt |
Q:
Discrete and Continuous Classifier on Sparse Data
I'm trying to classify an example, which contains discrete and continuous features. Also, the example represents sparse data, so even though the system may have been trained on 100 features, the example may only have 12.
What would be the best classifier algorithm ... | Discrete and Continuous Classifier on Sparse Data | I'm trying to classify an example, which contains discrete and continuous features. Also, the example represents sparse data, so even though the system may have been trained on 100 features, the example may only have 12.
What would be the best classifier algorithm to use to accomplish this? I've been looking at Bayes, ... | [
"Support vector machines? libsvm can be used from Python, and is quite speedy.\nHandles sparse vector inputs, and won't mind if some of the features are continuous, where others are just -1/+1. (If you've got an n-way discrete feature, the standard thing to do is expand it into n binary features.)\n",
"Weka (Java... | [
2,
2,
2
] | [] | [] | [
"classification",
"java",
"machine_learning",
"python"
] | stackoverflow_0002500467_classification_java_machine_learning_python.txt |
Q:
Extract Text from a Binary File (using Python 2.7 on Windows 7)
I have a binary file of size about 5MB.. which has lots of interspersed text.. and control characters..
This is actually an equivalent of an outlook .pst file for SITATEX Application (from SITA).
The file contains all the TEXT MESSAGES sent and recei... | Extract Text from a Binary File (using Python 2.7 on Windows 7) | I have a binary file of size about 5MB.. which has lots of interspersed text.. and control characters..
This is actually an equivalent of an outlook .pst file for SITATEX Application (from SITA).
The file contains all the TEXT MESSAGES sent and received to and from outside world...(but the text has to be extracted thr... | [
"Q: How to read the file? binary and text interspersed\nA: Don't bother, just read it as normal text and you'll be able to keep your binary/text dichotomy (otherwise you won't be able to regex it as easily)\nfh = open('/path/to/my/file.ext', 'r')\nfh.read()\n\nJust in case you want to read binary later for some rea... | [
2,
2,
1
] | [] | [] | [
"perl",
"python",
"text_extraction"
] | stackoverflow_0008646940_perl_python_text_extraction.txt |
Q:
proper use of list comprehensions - python
Normally, list comprehensions are used to derive a new list from an existing list. Eg:
>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i > 2]
[3, 4, 5]
Should we use them to perform other procedures? Eg:
>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None,... | proper use of list comprehensions - python | Normally, list comprehensions are used to derive a new list from an existing list. Eg:
>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i > 2]
[3, 4, 5]
Should we use them to perform other procedures? Eg:
>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None, None, None, None, None]
>>> print b
[1, 2, 3, 4... | [
"You should indeed avoid using list comprehensions (along with dictionary comprehensions, set comprehensions and generator expressions) for side effects. Apart from the fact that they'd accumulate a bogus list and thus waste memory, it's also confusing. I expect a list comprehension to generate a (meaningful) value... | [
10,
4,
2,
2,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0008695488_list_comprehension_python.txt |
Q:
How to maintain when Django switches to Python 3?
I am in the process of learning Python and had a question about the future. I know it's not the most pressing thing to think about currently, but I'm curious.
Currently, Django only supports up to Python 2.7. However, in the near future, it will be supporting Pyth... | How to maintain when Django switches to Python 3? | I am in the process of learning Python and had a question about the future. I know it's not the most pressing thing to think about currently, but I'm curious.
Currently, Django only supports up to Python 2.7. However, in the near future, it will be supporting Python 3. In terms of writing code in Python 2.7 and using ... | [
"\n... what happens when the transition to Python 3 actually comes along.\n\nNothing. That's why you're using a framework in the first place. All you need to be responsible for is the small amount of your code that will need to be ported.\n",
"Django (due to the immense amount of code running on it), will not, at... | [
3,
2,
1
] | [] | [] | [
"django",
"python",
"python_3.x"
] | stackoverflow_0008698140_django_python_python_3.x.txt |
Q:
appengine python `PUT/DELETE` working on localhost but not in server
Why my application (appengine+python) PUT/DELETE working on localhost (response status code 200) but not in server (appspot) (respone with status code 0)
Thanks.
app.yaml
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: ... | appengine python `PUT/DELETE` working on localhost but not in server | Why my application (appengine+python) PUT/DELETE working on localhost (response status code 200) but not in server (appspot) (respone with status code 0)
Thanks.
app.yaml
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: guestbook.py
guestbook.py
class MainPage(webapp.RequestHandler):
def ... | [
"It should be a browser issue! It works perfectly for me local/prod\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"restful_url"
] | stackoverflow_0008622491_google_app_engine_python_restful_url.txt |
Q:
checkin python if a list of dictonaries does NOT contain a specific value
This is some what of a supplementary question to my recent query about searching dictionary items in a list:
Check if python dictionary contains value and if so return related value
I have an array containing dictionaries in the format:
file... | checkin python if a list of dictonaries does NOT contain a specific value | This is some what of a supplementary question to my recent query about searching dictionary items in a list:
Check if python dictionary contains value and if so return related value
I have an array containing dictionaries in the format:
fileList = [
{"fileName": "file1.txt", "fileMod": "0000048723"},
... | [
"Perhaps you should use a dictionary rather than a list?\nfiles = {\n 'file1.txt': {'fileMod': '0000048723'},\n 'file2.txt': {'fileMod': '0000048723'}\n}\n\nThis stores the same information as your list, but finding elements is easy:\nmod = None\nif 'file1.txt' in files:\n mod = files['file1.txt']['fileMod... | [
5,
2,
2,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0008699710_dictionary_list_python.txt |
Q:
from binary data to wxbitmap
I have a device which stores a grayscale image as a series of 8 bit unsigned integer values. I want to write a python program to read these images from a file and show them using wxBitmap. I have a code that works, but it seems inefficient due to a lot of conversions between formats.
A... | from binary data to wxbitmap | I have a device which stores a grayscale image as a series of 8 bit unsigned integer values. I want to write a python program to read these images from a file and show them using wxBitmap. I have a code that works, but it seems inefficient due to a lot of conversions between formats.
Any suggestions for a faster code a... | [
"You can get a wxBitmap directly from a numpy array.\nThis is an example from wxPyWiki:\nimport wx, numpy\n\ndef GetBitmap( self, width=32, height=32, colour = (0,0,0) ):\n array = numpy.zeros( (height, width, 3),'uint8')\n array[:,:,] = colour\n image = wx.EmptyImage(width,height)\n ima... | [
1
] | [] | [] | [
"binary",
"image",
"python",
"wxpython"
] | stackoverflow_0008658138_binary_image_python_wxpython.txt |
Q:
How to auto reconnect during IOError in python
I'm doing fetch links using python. and suddenly I lost the connection and display an error as below.
IOError: [Errno socket error] [Errno 110] Connection timed out
how to reconnect with the same link?
for instance
import urllib
a = 'http://anzaholyman.files.wordpre... | How to auto reconnect during IOError in python | I'm doing fetch links using python. and suddenly I lost the connection and display an error as below.
IOError: [Errno socket error] [Errno 110] Connection timed out
how to reconnect with the same link?
for instance
import urllib
a = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif'
image = urllib.URLopener(... | [
"You can simply use the try..except syntax:\nimport urllib\n\na = 'http://anzaholyman.files.wordpress.com/2011/12/zip-it.gif'\nimage = urllib.URLopener()\nwhile True:\n try:\n image.retrieve(a,'1.jpg')\n break\n except IOError:\n pass\n\n",
"If there is an actual problem loading your fi... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008544804_python.txt |
Q:
wxPython: Execute an event function automatically at program startup
There's a combobox event in my code:
self.combobox1.Bind(wx.EVT_COMBOBOX, self.onActionCombobox1)
It executes the function
def onActionCombobox1(self, event):
Is there a way to execute this function automatically everytime when I start my progr... | wxPython: Execute an event function automatically at program startup | There's a combobox event in my code:
self.combobox1.Bind(wx.EVT_COMBOBOX, self.onActionCombobox1)
It executes the function
def onActionCombobox1(self, event):
Is there a way to execute this function automatically everytime when I start my program?
I tried it like this:
self.onActionCombobox1(event)
but it says Undef... | [
"if you do not make use of the event variable you want to do:\nself.onActionCombobox1(None)\n\nThis, set in the __init__ method of your class, will execute the method at class instantiation (not necessarily equivalent to program startup as in wxPython you can have windows/widgets that can be created dynamically at ... | [
1
] | [] | [] | [
"events",
"function",
"python",
"wxpython"
] | stackoverflow_0008700088_events_function_python_wxpython.txt |
Q:
Python: How to import, from two modules, Classes that have same names?
I'm writing a python programm to do granular syncs between different DB.
I'm using SQLAlchemy and a module named sqlautocode for DB inspecting and Schema Classes production.
Having two DB to sync, with same tables name, the Classes written by s... | Python: How to import, from two modules, Classes that have same names? | I'm writing a python programm to do granular syncs between different DB.
I'm using SQLAlchemy and a module named sqlautocode for DB inspecting and Schema Classes production.
Having two DB to sync, with same tables name, the Classes written by sqlautocode results with same names.
I have to import theese Classes with arb... | [
"Just import the modules and don't try to pull the names from them. from X import Y should be used sporadically, anyway.\nimport module_a\nimport module_b\n\nmodule_a.x\nmodule_b.x\n\n",
"You don't have to import classes from modules in this case. Instead import both modules. Like this:\nimport moda, modb\n\nmoda... | [
8,
1
] | [] | [] | [
"class",
"import",
"python"
] | stackoverflow_0008700360_class_import_python.txt |
Q:
Django, nothing saved in STATIC_ROOT folder
The way I read understand the Django documentation, the 'django.contrib.staticfiles' app collects static content from apps, put them in the folder specified by STATIC_ROOT. After that it is able to serve from there.
But this works even when the specified folder is non-e... | Django, nothing saved in STATIC_ROOT folder | The way I read understand the Django documentation, the 'django.contrib.staticfiles' app collects static content from apps, put them in the folder specified by STATIC_ROOT. After that it is able to serve from there.
But this works even when the specified folder is non-existing or empty (if 'manage.py collectstatic' ha... | [
"You don't need to collectstatic for local development, only later when you deploy to production:\n\nFor local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup\n\nSee: \nhttps://docs.djangoproject.com/en/1.3/howto/static-files/#basic-usage\nhttps:... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008700626_django_python.txt |
Q:
Trouble Shoot Ghostscript installation on windows for use with Elaphe Python barcode generator
I would like to use Elaphe to generate barcodes.
I am getting gs failed errors when I run the example codes.
I am working on a 64-bit windows machine. I have python 2.7.1 for win32 installed because win32 was required fo... | Trouble Shoot Ghostscript installation on windows for use with Elaphe Python barcode generator | I would like to use Elaphe to generate barcodes.
I am getting gs failed errors when I run the example codes.
I am working on a 64-bit windows machine. I have python 2.7.1 for win32 installed because win32 was required for certain packages. SO, I installed Ghostscript 9.0.4 win 32. I added the correct path to the PATH v... | [
"You need to capture the Ghostscript output to see what the error message is. This is normally written to stderr, I have no idea where this might be going in the Python library but you really need to see this to figure out why Ghostscript is exiting. \nYou also need to see it to find out if Ghostscript is even bein... | [
1,
1
] | [] | [] | [
"ghostscript",
"python",
"python_imaging_library"
] | stackoverflow_0008178388_ghostscript_python_python_imaging_library.txt |
Q:
Upload pdf file with gdata docs python v3.0 with ocr
I've got the following implementation for uploading a pdf file to google docs (taken from the gdata API samples):
def UploadResourceSample():
"""Upload a document, and convert to Google Docs."""
client = CreateClient()
doc = gdata.docs.data.Resource(type='... | Upload pdf file with gdata docs python v3.0 with ocr | I've got the following implementation for uploading a pdf file to google docs (taken from the gdata API samples):
def UploadResourceSample():
"""Upload a document, and convert to Google Docs."""
client = CreateClient()
doc = gdata.docs.data.Resource(type='document', title='My Sample Doc')
# This is a convenien... | [
"I've managed to get my pdf document OCR'ed using the following code:\ndef UploadResourceSample(filename, filepath, fullpath):\n \"\"\"Upload a document, and convert to Google Docs.\"\"\"\n client = CreateClient()\n doc = gdata.docs.data.Resource(type='document', title=filename)\n\n path = fullpath\n print 'Se... | [
3
] | [] | [] | [
"gdata",
"gdata_api",
"ocr",
"pdf",
"python"
] | stackoverflow_0008689021_gdata_gdata_api_ocr_pdf_python.txt |
Q:
Find statements in a python file that have a chance to get executed
I am working on a opensource project where i implementing searching of "print" statements
and such other statements that are unnecessary in a live production enviroment and can
create a error.
But i dont want to trouble the user if there is a pri... | Find statements in a python file that have a chance to get executed | I am working on a opensource project where i implementing searching of "print" statements
and such other statements that are unnecessary in a live production enviroment and can
create a error.
But i dont want to trouble the user if there is a print statement commmented out or "print"
word in a docstring or a comment.... | [
"Use ast module and NodeVisitor to analyze statically program's code. This way you will have no problems with docstrings or comments.\n",
"For Python 2.6 or later you could probably use the ast module. Read in the code (as a string, use ast.parse() to create an abstract syntax tree of that code, and then walk ov... | [
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008700765_django_python.txt |
Q:
Weighted average of 2 tuples, each having 2 dictionaries (of dictionaries)
What would be the easiest/shortest/most-Pythonic way to get the weighted average of a and b?
a = (
{
0: {'P': 0.3, 'Z': 0.3, 'N': 0.3},
'P': {'P': 0.9, 'Z': 0.1, 'N': 0.0},
'Z': {'P': 0.1, 'Z': 0.9, 'N': ... | Weighted average of 2 tuples, each having 2 dictionaries (of dictionaries) | What would be the easiest/shortest/most-Pythonic way to get the weighted average of a and b?
a = (
{
0: {'P': 0.3, 'Z': 0.3, 'N': 0.3},
'P': {'P': 0.9, 'Z': 0.1, 'N': 0.0},
'Z': {'P': 0.1, 'Z': 0.9, 'N': 0.1},
'N': {'P': 0.0, 'Z': 0.1, 'N': 0.9}
},
{
... | [
"I'd make a function that accepts two inputs and converts them recursively according to their type:\ndef combine(a, b, a_weight, b_weight):\n if isinstance(a, tuple):\n return tuple(combine(x,y,a_weight,b_weight) for x,y in zip(a,b))\n elif isinstance(a, dict):\n return dict((k, combine(a[k],b[k... | [
2
] | [] | [] | [
"dictionary",
"hidden_markov_models",
"python"
] | stackoverflow_0008701102_dictionary_hidden_markov_models_python.txt |
Q:
translate my sequence?
I have to write a script to translate this sequence:
dict = {"TTT":"F|Phe","TTC":"F|Phe","TTA":"L|Leu","TTG":"L|Leu","TCT":"S|Ser","TCC":"S|Ser",
"TCA":"S|Ser","TCG":"S|Ser", "TAT":"Y|Tyr","TAC":"Y|Tyr","TAA":"*|Stp","TAG":"*|Stp",
"TGT":"C|Cys","TGC":"C|Cys","TGA... | translate my sequence? | I have to write a script to translate this sequence:
dict = {"TTT":"F|Phe","TTC":"F|Phe","TTA":"L|Leu","TTG":"L|Leu","TCT":"S|Ser","TCC":"S|Ser",
"TCA":"S|Ser","TCG":"S|Ser", "TAT":"Y|Tyr","TAC":"Y|Tyr","TAA":"*|Stp","TAG":"*|Stp",
"TGT":"C|Cys","TGC":"C|Cys","TGA":"*|Stp","TGG":"W|Trp", "CT... | [
"You can use (Note this would be ridiculously much more easier using biopython translate method):\ndictio = {your dictionary here}\n\ndef translate(seq):\n x = 0\n aaseq = []\n while True:\n try:\n aaseq.append(dicti[seq[x:x+3]])\n x += 3\n except (IndexError, KeyError):... | [
5,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"sequences",
"sorting",
"translation"
] | stackoverflow_0008700920_python_python_3.x_sequences_sorting_translation.txt |
Q:
Separating Words in a List Tkinter Listbox Python
In my source code for a project I am running I have a process that produces a list of strings. I am trying to put this list into a Tkinter listbox for easy sorting, but when I do the list is all inserted into one line and I can't find a way to separate the individu... | Separating Words in a List Tkinter Listbox Python | In my source code for a project I am running I have a process that produces a list of strings. I am trying to put this list into a Tkinter listbox for easy sorting, but when I do the list is all inserted into one line and I can't find a way to separate the individual words into a different line on the listbox. Any idea... | [
"This is how you could do it:\nfrom Tkinter import *\n\napp = Tk()\napp.geometry(\"500x700\")\napp.title(\"ListBox\")\n\nnames = [\"Greg\", \"Earl\", \"Harry\", \"Bob\"]\n\nbox = Listbox(app)\n# Right here is where I am stuck\nfor name in names:\n box.insert(END, name)\n\nbox.pack()\napp.mainloop()\n\n",
"very... | [
1,
1
] | [] | [] | [
"listbox",
"python",
"python_2.7",
"tkinter"
] | stackoverflow_0008701419_listbox_python_python_2.7_tkinter.txt |
Q:
python class instance variables and class variables
I'm having a problem understanding how class / instance variables work in Python. I don't understand why when I try this code the list variable seems to be a class variable
class testClass():
list = []
def __init__(self):
self.list.append('thing')... | python class instance variables and class variables | I'm having a problem understanding how class / instance variables work in Python. I don't understand why when I try this code the list variable seems to be a class variable
class testClass():
list = []
def __init__(self):
self.list.append('thing')
p = testClass()
print p.list
f = testClass()
print f.l... | [
"This is because of the way Python resolves names with the .. When you write self.list the Python runtime tries to resolve the list name first by looking for it in the instance object, and if it is not found there, then in the class instance.\nLet's look into it step by step\nself.list.append(1)\n\n\nIs there a lis... | [
55,
8,
4,
0
] | [] | [] | [
"class",
"instance",
"python",
"variables"
] | stackoverflow_0008701500_class_instance_python_variables.txt |
Q:
Invalid syntax with if statement
I will just paste in the entire function, as it is not that long:
def decideTile():
global tile
global exp
global maxexp
tile += 1
exp += math.ceil(random.randrange(math.ceil((maxexp/2)/2,maxexp/2))
if exp >= maxexp:
levelUp()
else:
tileC... | Invalid syntax with if statement | I will just paste in the entire function, as it is not that long:
def decideTile():
global tile
global exp
global maxexp
tile += 1
exp += math.ceil(random.randrange(math.ceil((maxexp/2)/2,maxexp/2))
if exp >= maxexp:
levelUp()
else:
tileChoices = ['Battle','Loot','Nothing']
... | [
"There's a parenthesis missing in the previous line. To fix the problem just add a closing parenthesis to the end of that line as follows:\nexp += math.ceil(random.randrange(math.ceil((maxexp/2)/2,maxexp/2)))\n\n",
"Unclosed brackets caused the error. The line should be:\nexp += math.ceil(random.randrange(math.ce... | [
10,
0
] | [] | [] | [
"if_statement",
"python",
"python_3.x",
"syntax"
] | stackoverflow_0008698325_if_statement_python_python_3.x_syntax.txt |
Q:
How can I use Python to pipe stdin/stdout to Perl script
This Python code pipes data through Perl script fine.
import subprocess
kw = {}
kw['executable'] = None
kw['shell'] = True
kw['stdin'] = None
kw['stdout'] = subprocess.PIPE
kw['stderr'] = subprocess.PIPE
args = ' '.join(['/usr/bin/perl','-w','/path/script.pe... | How can I use Python to pipe stdin/stdout to Perl script | This Python code pipes data through Perl script fine.
import subprocess
kw = {}
kw['executable'] = None
kw['shell'] = True
kw['stdin'] = None
kw['stdout'] = subprocess.PIPE
kw['stderr'] = subprocess.PIPE
args = ' '.join(['/usr/bin/perl','-w','/path/script.perl','<','/path/mydata'])
subproc = subprocess.Popen(args,**kw)... | [
"Your code is blocking at the line:\nfor line in iter(subproc.stdout.readline, ''):\n\nbecause the only way this iteration can terminate is when EOF (end-of-file) is reached, which will happen when the subprocess terminates. You don't want to wait till the process terminates, however, you only want to wait till its... | [
1,
1,
0
] | [] | [] | [
"pipe",
"python"
] | stackoverflow_0008698280_pipe_python.txt |
Q:
Reverse the content of the file from beginning to end in Python
I am carrying out an investigation on some files I have seen on my family's computer. They are long files of mainly text content but the content appears to be reversed, i.e. instead of www.google.com it is moc.elgoog.www. There are lots of non-ASCII c... | Reverse the content of the file from beginning to end in Python | I am carrying out an investigation on some files I have seen on my family's computer. They are long files of mainly text content but the content appears to be reversed, i.e. instead of www.google.com it is moc.elgoog.www. There are lots of non-ASCII characters in the file as well.
I'm thinking python would be the best ... | [
"Write bytes in reverse order:\nimport os\n\nbufsize = 1 << 15\nwith open('file.in', 'rb') as f, open('file.out', 'wb') as fout:\n f.seek(0, os.SEEK_END) # move to the end of file\n for pos in reversed(xrange(0, f.tell(), bufsize)):\n f.seek(pos, os.SEEK_SET)\n fout.write(f.read(bufsize)[::-1])\... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008701225_python.txt |
Q:
Which optimization packages exist for Python for timetabling?
I am developing a timetabling application which takes into considerations like:
preferred hours for subjects and teachers
minimizing the number of hours per day
compulsory but abstract rules: "do not take back to back hours", "A teacher with 'HOD' or '... | Which optimization packages exist for Python for timetabling? | I am developing a timetabling application which takes into considerations like:
preferred hours for subjects and teachers
minimizing the number of hours per day
compulsory but abstract rules: "do not take back to back hours", "A teacher with 'HOD' or 'asst prof' tag must be present in 3 of these 5 hours"
I loved Dro... | [
"Drools has a Python semantic module that allows to use the Python scripting language to specify rules in our DRL files. I'm not sure if it will help you, but this is the URL that points to more information on it.\nhttp://legacy.drools.codehaus.org/Python+Semantic+Module\nBecause the URL has the \"legacy\" string i... | [
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0008701364_optimization_python.txt |
Q:
Identifying common elements in multiple files
I have 8 files of one column and non uniform number of rows in each column. I need to identify the elements which are common in all of these 8 files.
I can do this task for comparing two files, but I am unable to write workable one liner in shell to do the same.
Any id... | Identifying common elements in multiple files | I have 8 files of one column and non uniform number of rows in each column. I need to identify the elements which are common in all of these 8 files.
I can do this task for comparing two files, but I am unable to write workable one liner in shell to do the same.
Any ideas.....
Thank you in advance.
File 1
Paul
pawan ... | [
"The following one-liner should do (change 3 to 8 to match your case)\n$ sort * | uniq -c | grep 3\n 3 Paul\n\nProbably better to do this in python though, using sets...\n",
"python -c 'import sys;print \"\".join(sorted(set.intersection(*[set(open(a).readlines()) for a in sys.argv[1:]])))' File1 File2 File3\... | [
8,
6,
4,
3,
2,
2
] | [] | [] | [
"perl",
"python",
"shell"
] | stackoverflow_0008700666_perl_python_shell.txt |
Q:
Python - Script execution, locationing errors
Using the ConfigParser module I am attempting to read in a configuration file so I can safely allow users to edit settings for an application and share these configurations between scripts.
This has been working perfectly for the main script. However there is a seconda... | Python - Script execution, locationing errors | Using the ConfigParser module I am attempting to read in a configuration file so I can safely allow users to edit settings for an application and share these configurations between scripts.
This has been working perfectly for the main script. However there is a secondary script that is called and it reads the same conf... | [
"You can prefer to use dirname and __file__:\nfrom os.path import dirname, join\nconfig = ConfigParser.ConfigParser()\nconfig_fn = join(dirname(__file__), '..', 'conf', 'settings.conf')\nconfig.read(config_fn)\n\nDepending how you're launching the app (python bin/app.py, or python app.py), the '..' will be incorrec... | [
1
] | [] | [] | [
"configparser",
"configuration",
"python"
] | stackoverflow_0008702572_configparser_configuration_python.txt |
Q:
using Python to retrieve missing sequences -'split' command does not work
I have a set of (protein)sequences that has been found using a software but they are shorter in length than that of the original ones in the database.I downloaded the entire database ,and now i have these set of incomplete sequences that ha... | using Python to retrieve missing sequences -'split' command does not work | I have a set of (protein)sequences that has been found using a software but they are shorter in length than that of the original ones in the database.I downloaded the entire database ,and now i have these set of incomplete sequences that have been found and the original database from which the sequences have been found... | [
"You can use the index method from BioPython SeqIO. The index method indexes database records by protein id and doesn't load the full database in memory thus allowing efficient search with complete, big databases (alternatively you could use a conventional dbase like sqlite to first store your records and perform ... | [
4
] | [] | [] | [
"biopython",
"python",
"split"
] | stackoverflow_0008702703_biopython_python_split.txt |
Q:
Using raster datasets from a gdb in python
I'm trying to write a script for converting degrees to radians in python. A common task and it would just be useful to have around. The problem I'm getting is that the input raster appears to be being read as a string. See below:
import arcpy
from arcpy import env
from... | Using raster datasets from a gdb in python | I'm trying to write a script for converting degrees to radians in python. A common task and it would just be useful to have around. The problem I'm getting is that the input raster appears to be being read as a string. See below:
import arcpy
from arcpy import env
from arcpy.sa import *
import math
arcpy.CheckOutExt... | [
"Use a raster object from the arcpy module to instantiate the raster:\nfrom arcpy import Raster\n\n...\n\nras = Raster('path_to_raster') \nPythonRad = ras * degrad\n\nAlso, don't forget to check your spatial analyst extension back in when you are done.\n",
"First: When you want to use the \\ character in your str... | [
2,
1
] | [] | [] | [
"arcpy",
"floating_point",
"gis",
"python",
"raster"
] | stackoverflow_0008702876_arcpy_floating_point_gis_python_raster.txt |
Q:
binary to string, better than a dictionary?
Objective: Convert binary to string
Example: 0111010001100101011100110111010001100011011011110110010001100101 -> testCode (without space)
I use a dictionary and my function, i search a better way and more efficient
from textwrap import wrap
DICO = {'\x00': '00', '\x04':... | binary to string, better than a dictionary? | Objective: Convert binary to string
Example: 0111010001100101011100110111010001100011011011110110010001100101 -> testCode (without space)
I use a dictionary and my function, i search a better way and more efficient
from textwrap import wrap
DICO = {'\x00': '00', '\x04': '0100', '\x08': '01000', '\x0c': '01100',
'\x10... | [
"''.join([ chr(int(p, 2)) for p in wrap(binstr, 8) ])\n\nWhat this does: wrap first splits your string up into chunks of 8. Then, I iterate through each one, and convert it to an integer (base 2). Each of those converted integer now get covered to a character with chr. Finally I wrap it all up with a ''.join to sma... | [
14,
3,
2
] | [] | [] | [
"binary",
"dictionary",
"python",
"string"
] | stackoverflow_0008702060_binary_dictionary_python_string.txt |
Q:
Usage of pickle.dump in Python
I'm trying to learn how to use the pickle module in Python:
import pickle
x = 123
f = open('data.txt','w')
pickle.dump(x,f)
Here's what I get:
Traceback (most recent call last):
File "D:\python\test.py", line 5, in <module>
pickle.dump(x,f)
TypeError: must be str, not bytes
H... | Usage of pickle.dump in Python | I'm trying to learn how to use the pickle module in Python:
import pickle
x = 123
f = open('data.txt','w')
pickle.dump(x,f)
Here's what I get:
Traceback (most recent call last):
File "D:\python\test.py", line 5, in <module>
pickle.dump(x,f)
TypeError: must be str, not bytes
However, this code works just fine:
i... | [
"The problem is that you're opening the file in text mode. You need to use binary here:\n>>> f = open('data.txt','w')\n>>> pickle.dump(123,f)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: must be str, not bytes\n>>> \n>>> f = open('data.txt','wb')\n>>> pickle.dump(123,f)\... | [
43,
2
] | [] | [] | [
"pickle",
"python",
"python_3.2",
"serialization"
] | stackoverflow_0008703366_pickle_python_python_3.2_serialization.txt |
Q:
CMS or Wiki for creating XHTML ebook + blog
For a long time I have been wanting to start a blog. But knowing myself, I know I won't update it often. So, I would like to club my blog with an "ebook". I'd like to write some beginner level ebook/course on Biostatistics.
Here are some examples of other blogs (+ebooks)... | CMS or Wiki for creating XHTML ebook + blog | For a long time I have been wanting to start a blog. But knowing myself, I know I won't update it often. So, I would like to club my blog with an "ebook". I'd like to write some beginner level ebook/course on Biostatistics.
Here are some examples of other blogs (+ebooks) that follow this approach:
A Byte of Python: ht... | [
"http://www.swaroopch.com/notes/Python uses MediaWiki, which is okay for writing books. If you want to publish in several formats, a sophisticated markup language like Markdown or reStructuredText might be more appropriate. You can use different utilities to create static web pages using those, like Sphinx, Hyde or... | [
0
] | [] | [] | [
"content_management_system",
"docbook",
"python",
"wiki",
"wordpress"
] | stackoverflow_0008703139_content_management_system_docbook_python_wiki_wordpress.txt |
Q:
How do you get the directory name from the error object on IOError in python 2.3.4?
When trying to open a directory, an exception is thrown:
>>> try:
... open( '/' )
... except IOError, e:
... print e.filename
None
Is it possible (preferrably in python 2.3.4) for the handler of the exception to get the name ... | How do you get the directory name from the error object on IOError in python 2.3.4? | When trying to open a directory, an exception is thrown:
>>> try:
... open( '/' )
... except IOError, e:
... print e.filename
None
Is it possible (preferrably in python 2.3.4) for the handler of the exception to get the name of the directory from the exception object?
| [
"This is a bug in older versions of Python: http://bugs.python.org/issue4764\nSupplying the open function with a mode, open('/', 'r'), might allow you to retrieve the filename via e.filename.\n"
] | [
1
] | [] | [] | [
"python",
"python_2.3"
] | stackoverflow_0008702671_python_python_2.3.txt |
Q:
Set picture as background in python in turtle module
I am a beginner at programming at can't seem to figure out how to use bgpic('photo.gif') in turtle.
I have enclosed the 'photo.gif' in the same folder as the script. Every time I execute the program with bgpic, the turtle window crashes. Do I have to resize the ... | Set picture as background in python in turtle module | I am a beginner at programming at can't seem to figure out how to use bgpic('photo.gif') in turtle.
I have enclosed the 'photo.gif' in the same folder as the script. Every time I execute the program with bgpic, the turtle window crashes. Do I have to resize the picture? Change its format?
| [
"bgpic only accepts gif images. \nYou should convert your image to gif format with photoshop or another similar tool or alternatively use for example python PIL to make the conversion programmatically \n"
] | [
2
] | [] | [] | [
"module",
"python",
"turtle_graphics"
] | stackoverflow_0008703505_module_python_turtle_graphics.txt |
Q:
Models missing error while migrating Django project from dev to production
I have setup a Django project on my laptop and build my first app. I have setup all the necessary software on a second server and I want to migrate my project to that one.
After uploading my files, I have tried a couple of things, but I sti... | Models missing error while migrating Django project from dev to production | I have setup a Django project on my laptop and build my first app. I have setup all the necessary software on a second server and I want to migrate my project to that one.
After uploading my files, I have tried a couple of things, but I still get errors like:
ImportError at /
No module named myapp.models
Request Method... | [
"You may need to move/create an __init__.py file in your app directory. \n",
"It seems your PYTHONPATH doesn't include /var/www/wsgi/myproject. Can you show your WSGI config file?\n"
] | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008703629_django_python.txt |
Q:
python SimpleCookie distinguish error
When i use python SimpleCookie object to pick up cookie from http headers, some exception occurs:
cookiestr = "a_em=[BU]co|12345678-901234567[DG]; Expires=Sat, 31 Dec 2016 17:09:50 GMT; Domain=.somesite.com; Path=/"
C = Cookie.SimpleCookie()
C.load(cookiestr)
print C
the outp... | python SimpleCookie distinguish error | When i use python SimpleCookie object to pick up cookie from http headers, some exception occurs:
cookiestr = "a_em=[BU]co|12345678-901234567[DG]; Expires=Sat, 31 Dec 2016 17:09:50 GMT; Domain=.somesite.com; Path=/"
C = Cookie.SimpleCookie()
C.load(cookiestr)
print C
the output is:
Set-Cookie: a_em=; Domain=.somesite.... | [
"RFC format for expires should be:\nExpires=Sat, 31-Dec-2016 17:09:50 GMT\n\nThe full string should be (note quotes)\ncookiestr = 'a_em=\"[BU]co|12345678-901234567[DG]\"; Expires=Sat, 31-Dec-2016 17:09:50 GMT; Domain=.somesite.com; Path=/'\n\n"
] | [
1
] | [] | [] | [
"cookielib",
"cookies",
"python"
] | stackoverflow_0008703561_cookielib_cookies_python.txt |
Q:
Duplicate Entries in Binary Search Tree
I have a very simple question regarding BSTs. I have seen multiple definitions of BSTs regarding duplicate entries. Some define BSTs as not allowing duplicate entries, others that node's left child is <= to the nodes value and the right child is greater than the node's value... | Duplicate Entries in Binary Search Tree | I have a very simple question regarding BSTs. I have seen multiple definitions of BSTs regarding duplicate entries. Some define BSTs as not allowing duplicate entries, others that node's left child is <= to the nodes value and the right child is greater than the node's value, and some definitions are the opposite of th... | [
"One of the well-known books in the algorithm and data structure area is the CLRS book, also known as the bible of data structures and algorithms:\n\nAccording to the definition of this book, the duplicate entries are placed in the right tree of the node that contains the same key. As an example, take a look at the... | [
6,
3
] | [] | [] | [
"binary_search_tree",
"c#",
"java",
"python"
] | stackoverflow_0008703971_binary_search_tree_c#_java_python.txt |
Q:
Download a file from a site (partly written in Javascript) using Python
I'm trying to use Python to download a voice file (mp3) from this site:
I've tried to use mechanize and twill but I haven't got the proper result. I've heard about selenium as well. Anyway, I don't even know if it makes sense technically (mech... | Download a file from a site (partly written in Javascript) using Python | I'm trying to use Python to download a voice file (mp3) from this site:
I've tried to use mechanize and twill but I haven't got the proper result. I've heard about selenium as well. Anyway, I don't even know if it makes sense technically (mechanize + Javascript).
I was looking for an answer and finally I've found this ... | [
"(Moving to answer to get more space)\nThanks for pointing me to selenium, I didn't know that and it looks cool; anyways: I had a quick look and the js seems to fire an ajax request, that yields no apparent result -- I guess the audio transfer is done some way in the background via flash or so; anyways: what about ... | [
1
] | [] | [] | [
"download",
"javascript",
"python",
"selenium"
] | stackoverflow_0008703945_download_javascript_python_selenium.txt |
Q:
Populate list or tuple from callable or lambda in python
This is a problem I've come across a lot lately. Google doesn't seem to have an answer so I bring it to the good people of stack overflow.
I am looking for a simple way to populate a list with the output of a function. Something like this:
fill(random.random... | Populate list or tuple from callable or lambda in python | This is a problem I've come across a lot lately. Google doesn't seem to have an answer so I bring it to the good people of stack overflow.
I am looking for a simple way to populate a list with the output of a function. Something like this:
fill(random.random(), 3) #=> [0.04095623, 0.39761869, 0.46227642]
Here are othe... | [
"How about a list comprehension?\n[random.random() for x in xrange(3)]\n\nAlso, in many cases, you need the values just once. In these cases, a generator expression which computes the values just-in-time and does not require a memory allocation is preferable:\nresults = (random.random() for x in xrange(3))\nfor r i... | [
12,
2,
0,
0,
0
] | [] | [] | [
"arrays",
"callable",
"list",
"python",
"tuples"
] | stackoverflow_0008703999_arrays_callable_list_python_tuples.txt |
Q:
Deploy issues with Django / Python application on Heroku Cedar
On following the tutorial outlined here:
http://devcenter.heroku.com/articles/django#prerequisites
I get this error:
http://pastie.org/3113885
I'm checking through a few things, but would anyone have a guess as to whats happening here?
My first guess w... | Deploy issues with Django / Python application on Heroku Cedar | On following the tutorial outlined here:
http://devcenter.heroku.com/articles/django#prerequisites
I get this error:
http://pastie.org/3113885
I'm checking through a few things, but would anyone have a guess as to whats happening here?
My first guess would be its something in my local configuration, as this is the "hel... | [
"There are issues with pushing to the Cedar stack at the moment which I believe the engineers are looking into.\nMore information can be found here: https://status.heroku.com/incident/279\n"
] | [
0
] | [] | [] | [
"django",
"heroku",
"python"
] | stackoverflow_0008704317_django_heroku_python.txt |
Q:
python mysqldb, for loop not deleting records
Somewhere in here lies a problem. http://paste.pocoo.org/show/528559/
Somewhere between lines 32 and 37. As you can see the DELETE FROM is inside a for loop.
Running the script just makes the program go through the loop and exit, without actually removing any recor... | python mysqldb, for loop not deleting records | Somewhere in here lies a problem. http://paste.pocoo.org/show/528559/
Somewhere between lines 32 and 37. As you can see the DELETE FROM is inside a for loop.
Running the script just makes the program go through the loop and exit, without actually removing any records.
Any help would be greatly appreciated! Thanks!... | [
"the problem is python-msyqldb specific.:\nStarting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of yo... | [
2,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0008695457_mysql_python.txt |
Q:
PHP script can't get output from Python script
I'm having an issue executing a Python script from a PHP script. My client uses Bluehost, so I installed a third party module (numpy) for Python with the easy_install method described here: https://my.bluehost.com/cgi/help/530?step=530
To demonstrate my issue, I've cr... | PHP script can't get output from Python script | I'm having an issue executing a Python script from a PHP script. My client uses Bluehost, so I installed a third party module (numpy) for Python with the easy_install method described here: https://my.bluehost.com/cgi/help/530?step=530
To demonstrate my issue, I've created two python scripts and a PHP script.
hello.py ... | [
"If PHP gets a return status of 1, that indicates that the process you ran encountered an error. (An nonzero exit status usually indicates an error on Unix style systems. A couple programs are different, e.g., diff.) Try examining the stderr produced by the subprocess to see what error messages are printed there... | [
5
] | [] | [] | [
"apache",
"numpy",
"php",
"python"
] | stackoverflow_0008704519_apache_numpy_php_python.txt |
Q:
python solving differential equation with complex variables
folks,
Is it possible to solve ODE with complex variable in python? The equation I have has the following form
dx/dt = -a x -i y(t)
where y(t) is a known function, a is a known number and i is the root of -1.
I tried to use odeint() but it gives many err... | python solving differential equation with complex variables | folks,
Is it possible to solve ODE with complex variable in python? The equation I have has the following form
dx/dt = -a x -i y(t)
where y(t) is a known function, a is a known number and i is the root of -1.
I tried to use odeint() but it gives many error messages.
I am guessing odeint() does not work with complex v... | [
"I'd suggest using scipy.integrate.complex_ode instead of scipy.integrate.odeint which performs the conversion automatically.\n"
] | [
4
] | [] | [] | [
"complex_numbers",
"differential_equations",
"python"
] | stackoverflow_0008703708_complex_numbers_differential_equations_python.txt |
Q:
How to pass information using an HTTP redirect (in Django)
I have a view that accepts a form submission and updates a model.
After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.
How can I "pass" this message to the other p... | How to pass information using an HTTP redirect (in Django) | I have a view that accepts a form submission and updates a model.
After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.
How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this don... | [
"This is a built-in feature of Django, called \"messages\"\nSee http://docs.djangoproject.com/en/dev/topics/auth/#messages\nFrom the documentation:\n\nA message is associated with a User.\n There's no concept of expiration or\n timestamps.\nMessages are used by the Django admin\n after successful actions. For ex... | [
12,
8,
5,
4,
3,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0000599280_django_http_python.txt |
Q:
Python AppEngine Sort By Referenced Property
I have a model Entry
class Entry(db.Model):
year = db.StringProperty()
.
.
.
and for whatever reason the last name field is stored in a different model LastName:
class LastName(db.Model):
entry = db.ReferenceProperty(Entry, collection_name='last_nam... | Python AppEngine Sort By Referenced Property | I have a model Entry
class Entry(db.Model):
year = db.StringProperty()
.
.
.
and for whatever reason the last name field is stored in a different model LastName:
class LastName(db.Model):
entry = db.ReferenceProperty(Entry, collection_name='last_names')
last_name = db.StringProperty()
If I que... | [
"A few issues here.\nThere's no way to do this sorting directly in the datastore API, either in Python or Java - as you no doubt know, the datastore is non-relational, and indirect lookups like this aren't supported.\nIf this was just a straight one-to-one relationship, which gave you an accessor from the Entry ent... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"sorting"
] | stackoverflow_0008704323_google_app_engine_google_cloud_datastore_python_sorting.txt |
Q:
Switch first and last elements of two lists in Python
In Python, I have two lists that either have equal number of elements (e.g. 8 and 8) or one less than the other (e.g. 7 and 8; 3 and 4):
list1 = ['A', 'B', 'C', 'D']
list2 = ['E', 'F', 'G', 'H']
or
list3 = ['A', 'B', 'C']
list4 = ['D', 'E', 'F', 'G']
I'm try... | Switch first and last elements of two lists in Python | In Python, I have two lists that either have equal number of elements (e.g. 8 and 8) or one less than the other (e.g. 7 and 8; 3 and 4):
list1 = ['A', 'B', 'C', 'D']
list2 = ['E', 'F', 'G', 'H']
or
list3 = ['A', 'B', 'C']
list4 = ['D', 'E', 'F', 'G']
I'm trying to figure out the best way to build an algorithm that w... | [
"list1 = ['A', 'B', 'C']\nlist2 = ['D', 'E', 'F', 'G']\n\nnlist1 = len(list1)/2\nnlist2 = len(list2)/2\n\nnew1 = list1[:nlist1] + list2[:nlist2]\nnew2 = list1[nlist1:] + list2[nlist2:]\n\nprint new1\nprint new2\n\nproduces\n['A', 'D', 'E']\n['B', 'C', 'F', 'G']\n\n",
">>> def StrangeSwitch(list1,list2):\n retu... | [
3,
2
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0008704633_algorithm_python.txt |
Q:
Eliminate for-loop in Python and Numpy construct
I'm looking for a method in Python and/or Numpy vectorization to eliminate use of a for-loop for the following:
for i in list_range_values:
v[list_list_values[i]] += list_comp_values[i]
where:
list_range_values is a Python list of integer values eg. [1, 3, 5],... | Eliminate for-loop in Python and Numpy construct | I'm looking for a method in Python and/or Numpy vectorization to eliminate use of a for-loop for the following:
for i in list_range_values:
v[list_list_values[i]] += list_comp_values[i]
where:
list_range_values is a Python list of integer values eg. [1, 3, 5], drawn from the range(0, R-1, 1)
list_comp_values is a... | [
"While it often results in a massive speedup to eliminate for loops and take advantage of numpy built-ins/vectorization. I would just point out that it is not always the case. Timing the simple for loop vs the much more involved vectorization, does not give you a large speedup and is much more verbose. Just somethi... | [
6,
2,
1
] | [] | [] | [
"for_loop",
"numpy",
"python"
] | stackoverflow_0008701167_for_loop_numpy_python.txt |
Q:
Rake:task equivalent in Django
I have a django application where i'll like to have a script that i'll run once a day to validate the models in the database, and delete some objects. How cand i make it ? I want something equivalent to rake:task in rails.
A:
Also look at setting up a custom subcommand for your man... | Rake:task equivalent in Django | I have a django application where i'll like to have a script that i'll run once a day to validate the models in the database, and delete some objects. How cand i make it ? I want something equivalent to rake:task in rails.
| [
"Also look at setting up a custom subcommand for your manage.py.\n",
"Try this: django-tasks \n",
"May be celery would be better in this case.\nBecause as stated in django-tasks page:\n\nDjango-tasks is for a different usage\n from most other tasks frameworks\n (Celery, Cue...): this is not for\n numerous, q... | [
9,
2,
1,
0
] | [] | [] | [
"django",
"django_models",
"python",
"rake"
] | stackoverflow_0003212337_django_django_models_python_rake.txt |
Q:
how to avoid logging multiple number of times while using python threads
In a single thread.run() i am finding a couple of strings in their corresponding webpages
if found, I am logging a text to a log file.
lets say 4 strings in their corresponding 4 webpages.
when i run the a single thread, the log file shows ... | how to avoid logging multiple number of times while using python threads | In a single thread.run() i am finding a couple of strings in their corresponding webpages
if found, I am logging a text to a log file.
lets say 4 strings in their corresponding 4 webpages.
when i run the a single thread, the log file shows 4 logs for each string in corresponding webpage
altogether i am getting 16 log... | [
"you can use a Queue, and have all threads write data to the queue instance. Then read from that queue from another thread and log there. The queue takes care of locking/synchronization. (multi-producer/single-consumer model)\n"
] | [
0
] | [] | [] | [
"logging",
"multithreading",
"python"
] | stackoverflow_0008704721_logging_multithreading_python.txt |
Q:
Python PIL: Modifying images using PIL, Flush() doesn't work
from PIL import Image
import webbrowser, aggdraw
im = Image.open('Background.png')
# Drawing cross on top of PIL image
d = aggdraw.Draw(im)
p = aggdraw.Pen("black", 0.5)
d.line((0, 0, 500, 500), p)
d.line((0, 500, 500, 0), p)
d.flush()
webbrowser.open('... | Python PIL: Modifying images using PIL, Flush() doesn't work | from PIL import Image
import webbrowser, aggdraw
im = Image.open('Background.png')
# Drawing cross on top of PIL image
d = aggdraw.Draw(im)
p = aggdraw.Pen("black", 0.5)
d.line((0, 0, 500, 500), p)
d.line((0, 500, 500, 0), p)
d.flush()
webbrowser.open('Background.png')
The above is the code I'm running. I use web-bro... | [
"flush doesn't write back out to a file - it simply assures that all internal operations are completed. You need to use the im.save function to write the results back to a file.\n"
] | [
6
] | [] | [] | [
"aggdraw",
"python",
"python_imaging_library"
] | stackoverflow_0008704991_aggdraw_python_python_imaging_library.txt |
Q:
How to convert a tuple to a string in Python?
After a MySQL select statement, I am left with the following:
set([('1@a.com',), ('2@b.net',), ('3@c.com',), ('4@d.com',), ('5@e.com',), ('6@f.net',), ('7@h.net',), ('8@g.com',)])
What I would like to have is a
emaillist = "\n".join(queryresult)
to in the end, have ... | How to convert a tuple to a string in Python? | After a MySQL select statement, I am left with the following:
set([('1@a.com',), ('2@b.net',), ('3@c.com',), ('4@d.com',), ('5@e.com',), ('6@f.net',), ('7@h.net',), ('8@g.com',)])
What I would like to have is a
emaillist = "\n".join(queryresult)
to in the end, have a string:
1@a.com
2@b.net
3@c.com
etc
What would b... | [
"As long as you're sure you have just one element per tuple:\n'\\n'.join(elem[0] for elem in queryresult)\n\n",
"Try this and see\n>>> something=set([('1@a.com',), ('2@b.net',), ('3@c.com',), ('4@d.com',), ('5@e.com',), ('6@f.net',), ('7@h.net',), ('8@g.com',)])\n>>> print '\\n'.join(''.join(s) for s in something... | [
15,
2,
2,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0008704952_python_tuples.txt |
Q:
how to change list and tuple into dict in python?
how join tuple list a dict?
this is what i have:
[('a','b'),('c','d'),('e','f')]
and this is what i want:
{'a':'b','c':'d','e':'f'}
thanks!
A:
Just pass the list into the dict constructor. As they are tuples, it will know how to create the dictionary.
l = [('... | how to change list and tuple into dict in python? | how join tuple list a dict?
this is what i have:
[('a','b'),('c','d'),('e','f')]
and this is what i want:
{'a':'b','c':'d','e':'f'}
thanks!
| [
"Just pass the list into the dict constructor. As they are tuples, it will know how to create the dictionary.\nl = [('a','b'),('c','d'),('e','f')]\nd = dict(l)\n\n",
"dict([('a','b'),('c','d'),('e','f')]\n\nshould do it\n"
] | [
8,
4
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0008705156_list_python_tuples.txt |
Q:
Creating command line tools in python
i want to create some command line utilities to manage many wordpress site, allowing me to create, clone , move , wordpress sites.
Anyways, while i have the idea and how it will work, i wanted to know what will you recommend mind to start creating those, or any framework that ... | Creating command line tools in python | i want to create some command line utilities to manage many wordpress site, allowing me to create, clone , move , wordpress sites.
Anyways, while i have the idea and how it will work, i wanted to know what will you recommend mind to start creating those, or any framework that i can use.
UPDATE:
Here are some more deta... | [
"In terms of managing wordpress one of the following libraries might be useful:\nhttp://rufuspollock.org/2011/12/29/ann-pywordpress-python-wordpress-library-using-the-wordpress-xml-rpc-api/\nhttp://www.blackbirdblog.it/programmazione/progetti/28\n"
] | [
3
] | [] | [] | [
"command_line",
"python",
"wordpress"
] | stackoverflow_0008705314_command_line_python_wordpress.txt |
Q:
Submit virtual pageview to google analytics server-side
I'm trying to submit a virtual pageview to track events within application, that may not be associated with user visiting a page, and therefore will not allow for execution of javascript. The project is in python on GAE.
So far, I've tried to submit a pagevie... | Submit virtual pageview to google analytics server-side | I'm trying to submit a virtual pageview to track events within application, that may not be associated with user visiting a page, and therefore will not allow for execution of javascript. The project is in python on GAE.
So far, I've tried to submit a pageview via an image API via a GET request, but that does't seem to... | [
"You can use this lib that sends the required request to Google Analytics to mimic a page view event.\n"
] | [
4
] | [] | [] | [
"google_analytics",
"google_analytics_api",
"google_app_engine",
"python"
] | stackoverflow_0008705453_google_analytics_google_analytics_api_google_app_engine_python.txt |
Q:
NumPy for windows python 2.7
I can't find NumPy for windows python 2.7 although I found an OS X version of it.
A:
A Google search would tell you that its here .
A:
numpy-1.5.1-win32-superpack-python2.7.exe works for Python 2.7. I just installed and tested it with:
>>> from numpy import *
>>> a = arange(10).res... | NumPy for windows python 2.7 | I can't find NumPy for windows python 2.7 although I found an OS X version of it.
| [
"A Google search would tell you that its here .\n",
"numpy-1.5.1-win32-superpack-python2.7.exe works for Python 2.7. I just installed and tested it with:\n>>> from numpy import *\n>>> a = arange(10).reshape(2,5)\n>>> a\n\nOutput: \n>>> array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9]])\n\n"
] | [
21,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004554277_numpy_python.txt |
Q:
Using virtualenv in Pycharm as Django IDE
Please help me on this. I am doing this on Fedora 16.
My virtual environment is /home/username/Desktop/.pythonenv
Now, notice the dot. Because it is a hidden directory, I had to make a symbolic link in order to for Pycharm to "enter" the directory.
sudo ln -s /home/yeukhon... | Using virtualenv in Pycharm as Django IDE | Please help me on this. I am doing this on Fedora 16.
My virtual environment is /home/username/Desktop/.pythonenv
Now, notice the dot. Because it is a hidden directory, I had to make a symbolic link in order to for Pycharm to "enter" the directory.
sudo ln -s /home/yeukhon/Desktop/.pythonenv /home/yeukhon/Desktop/sypyt... | [
"First, no need to create a symlink, as the add interpreter dialog has a button 'show hidden files and directores', and you can manually type in the path too.\nEach virtualenv is, since version 1.7, an isolated environment by default . That means you have to explicitly pass the --system-site-packages ENV if you wan... | [
4
] | [] | [] | [
"django",
"pycharm",
"python"
] | stackoverflow_0008696681_django_pycharm_python.txt |
Q:
Checking if a value is in a list based on indexes
If I have a list that is made up of indexes from a list of lists, how would I use an index collected from a value in that list and find out which list it is in?
Here is an example:
listolists = [
[0, 8, 4, 0, 7],
[3, 6, 0, 9, 0],
[4, 0, 3, 7, 0],
[... | Checking if a value is in a list based on indexes | If I have a list that is made up of indexes from a list of lists, how would I use an index collected from a value in that list and find out which list it is in?
Here is an example:
listolists = [
[0, 8, 4, 0, 7],
[3, 6, 0, 9, 0],
[4, 0, 3, 7, 0],
[7, 0, 7, 0, 6]
]
section1 = [listolists[0][0], list... | [
"I have fixed up some typoes, avoided the scroll bar, shown the contents of section and section2, and added a print statement:\ntable = [\n [0, 8, 4, 0, 7],\n [3, 6, 0, 9, 0],\n [4, 0, 3, 7, 0],\n [7, 0, 7, 0, 6]\n ]\nsection1 = [table[0][0], table[0][1], table[1][0], table[1][1]]\nprint \"section1:\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008704919_python.txt |
Q:
python 2 division
#this works in python 3
def pi_sum(n):
total, k = 0,1
while k <= n:
total, k = total +8 /(k *(k+2)), k + 4
return total
#this is how i tried to fix it for python 2
def pi_sum2(n):
total, k = 0,1
while k <= n:
total, k = float(total +8) /(k *(k+2)), k + 4
r... | python 2 division | #this works in python 3
def pi_sum(n):
total, k = 0,1
while k <= n:
total, k = total +8 /(k *(k+2)), k + 4
return total
#this is how i tried to fix it for python 2
def pi_sum2(n):
total, k = 0,1
while k <= n:
total, k = float(total +8) /(k *(k+2)), k + 4
return total
In python ... | [
"You need to define your variables explicitly as floats to avoid some type coersion:\ndef pi_sum(n):\n total, k = 0.0, 1.0\n while k <= n:\n total, k = total + 8.0 /(k *(k+2)), k + 4\n return total\n\nshould do the trick\n"
] | [
1
] | [] | [] | [
"division",
"python",
"python_2.x"
] | stackoverflow_0008705780_division_python_python_2.x.txt |
Q:
python UnicodeEncodeError > How can I simply remove troubling unicode characters?
Heres what I did..
>>> soup = BeautifulSoup (html)
>>> soup
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 96953: ordinal not in r... | python UnicodeEncodeError > How can I simply remove troubling unicode characters? | Heres what I did..
>>> soup = BeautifulSoup (html)
>>> soup
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 96953: ordinal not in range(128)
>>>
>>> soup.find('div')
Traceback (most recent call last):
File "<stdin>"... | [
"Try this way:\nsoup = BeautifulSoup (html.decode('utf-8', 'ignore'))\n",
"The error you see is due to repr(soup)tries to mix Unicode and bytestrings. Mixing Unicode and bytestrings frequently leads to errors.\nCompare:\n>>> u'1' + '©'\nTraceback (most recent call last):\n File \"<input>\", line 1, in <module>\n... | [
10,
2,
1,
0
] | [] | [] | [
"html_parsing",
"parsing",
"python",
"unicode"
] | stackoverflow_0005236437_html_parsing_parsing_python_unicode.txt |
Q:
django media hook not picking up the right directory
I have setup the following in my urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})
and my settings are:
MEDIA_ROOT = 'd:/~Sasha/Portman/media/'
MEDIA_URL = 'http://localhost:8000/media/'
and the following ... | django media hook not picking up the right directory | I have setup the following in my urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})
and my settings are:
MEDIA_ROOT = 'd:/~Sasha/Portman/media/'
MEDIA_URL = 'http://localhost:8000/media/'
and the following url:
http://localhost:8000/media/icons/151.png
returns:
"... | [
"The problem was that settings.ADMIN_MEDIA_PREFIX and MEDIA_ROOT were pointing to the same /media/ ending so r'^media/' was mixing them. Changed ADMIN_MEDIA_PREFIX to /admin-media/ and it all works now.\n",
"You should have a project directory setting in settings.py that other settings use.\nMy setup:\nBASE_PATH ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008703767_django_python.txt |
Q:
I Don't Understand This Use of Recursion
I was reading through the answers earning a "reversal" badge and I found a question regarding recursion where the OP didn't bother to do much of their homework assignment up front. Aside from some really funny answers, @machielo posted an answer in python that I had to run ... | I Don't Understand This Use of Recursion | I was reading through the answers earning a "reversal" badge and I found a question regarding recursion where the OP didn't bother to do much of their homework assignment up front. Aside from some really funny answers, @machielo posted an answer in python that I had to run on my machine to get a grip on. I'm still not ... | [
"I think that adding a few print statements it's really helpful:\ndef recursive(x):\n print '[start] recursive({0})'.format(x)\n if x > 10:\n print recursive(x/10)\n print '[return] recursive({0}) = {1}'.format(x, x%10)\n return x%10\n\nprint recursive(2678)\n\nThe output is:\n[start] recursive(2678)\n[start... | [
11,
5,
3,
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0008706191_python_recursion.txt |
Q:
Integer with ASCII values to string
I have an integer containing four ASCII codes for four chars:
0x31323334
I need to convert this integer to a string:
"1234" ~ "\x31\x32\x33\x34"
Is there better solution than this?
mystring = '%0*x' % (8, 0x31323334) # "31323334"
mystring.decode('hex') # "1234"
A:
Not sure i... | Integer with ASCII values to string | I have an integer containing four ASCII codes for four chars:
0x31323334
I need to convert this integer to a string:
"1234" ~ "\x31\x32\x33\x34"
Is there better solution than this?
mystring = '%0*x' % (8, 0x31323334) # "31323334"
mystring.decode('hex') # "1234"
| [
"Not sure it's better, but :)\n>>> import struct\n>>> struct.pack('>L', 0x31323334)\n'1234'\n\n",
"I don't think you'll get simpler than a format string and then a decode (needs Python 2.6+):\n>>> \"{0:08x}\".format(0x31323334).decode('hex')\n'1234'\n\n"
] | [
1,
1
] | [] | [] | [
"ascii",
"python",
"string"
] | stackoverflow_0008705371_ascii_python_string.txt |
Q:
Python 2.6 optimize nested loops
I have a function that has a dictionary as input and a value n.
Each item in the dictionary is a set with one or more values.
The function should sort the dictionary keys and it should extract and return "n"values.
This function will be executed very often therefore I am trying to... | Python 2.6 optimize nested loops | I have a function that has a dictionary as input and a value n.
Each item in the dictionary is a set with one or more values.
The function should sort the dictionary keys and it should extract and return "n"values.
This function will be executed very often therefore I am trying to optimize it. Any suggestions?
def sel... | [
"Here's my first attempt (see select_items_faster), which almost doubles the speed:\nIn [12]: print _11\nimport itertools\n\ndef select_items_original(temp_dict, n):\n \"\"\"Select n items from the dictionary\"\"\"\n res = []\n sort_keys = sorted(temp_dict.keys())\n count = 0\n\n for key in sort_keys:\n for... | [
6,
2,
2,
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0008704666_optimization_python.txt |
Q:
How do I get my small python program to quit when the user enters 'q' or 'quit'?
I tried flushing stdout with sys.stdout.flush() but it's still not working. It works fine until the user only enters C or F which breaks the code. Suffix is the first function called
so I make sure that if the user only enters one ch... | How do I get my small python program to quit when the user enters 'q' or 'quit'? | I tried flushing stdout with sys.stdout.flush() but it's still not working. It works fine until the user only enters C or F which breaks the code. Suffix is the first function called
so I make sure that if the user only enters one character then an error is returned. But once the error is returned the user is no longe... | [
"The problem is that temperature is being called recursively in different places when an error happens and to exit from the program the user has to enter q/quit as many times as temperature was called.\nTo fix the problem, I suggest to remove all recursive calls and handle the errors in a different way. For example... | [
6,
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008706458_python_python_3.x.txt |
Q:
Can python SWIG bind a library in the absence of the library's source code?
The software tool SWIG can be used to create a programming interface (bindings) to C/C++ software for other languages.
Interfacing to a C library works fine when the original C source code is available, from which one compiles .so files. T... | Can python SWIG bind a library in the absence of the library's source code? | The software tool SWIG can be used to create a programming interface (bindings) to C/C++ software for other languages.
Interfacing to a C library works fine when the original C source code is available, from which one compiles .so files. The sample commands are listed in the SWIG python documentation: http://www.swig.o... | [
"For SWIG, header files are enough to generate the interface files. Though I haven't worked on MacOS, so not sure on how to link those libraries. But regarding your first question, you dont need the source code of a library to swig it to c/c++. \n"
] | [
1
] | [] | [] | [
"c",
"python",
"swig"
] | stackoverflow_0008706631_c_python_swig.txt |
Q:
wxPython: Event method in different module
I have two modules like this (very very simplified):
main.py:
from window import *
class MyApp(wx.Frame):
def __init__(self, parent, label, pos, size):
wx.Frame.__init__(self, parent = parent, title = label, pos = pos, size = size)
self.Centre()
... | wxPython: Event method in different module | I have two modules like this (very very simplified):
main.py:
from window import *
class MyApp(wx.Frame):
def __init__(self, parent, label, pos, size):
wx.Frame.__init__(self, parent = parent, title = label, pos = pos, size = size)
self.Centre()
create_window(self)
self.Bind(wx.EV... | [
"I am not sure what you want. If this is about general behavior you want to implement in your classes (like a particular way of closing them, report state, adding a balloontip system, etc), then one way is to create a class with the corresponding methods and to inherit from her.\nclass BehaviorPack(object):\n de... | [
0,
0
] | [] | [] | [
"events",
"methods",
"module",
"python",
"wxpython"
] | stackoverflow_0008706645_events_methods_module_python_wxpython.txt |
Q:
Ensuring __init__ is only called once when class instance is created by constructor or __new__
I'm trying to understand how new instances of a Python class should be created when the creation process can either be via the constructor or via the __new__ method. In particular, I notice that when using the constructo... | Ensuring __init__ is only called once when class instance is created by constructor or __new__ | I'm trying to understand how new instances of a Python class should be created when the creation process can either be via the constructor or via the __new__ method. In particular, I notice that when using the constructor, the __init__ method will be automatically called after __new__, while when invoking __new__ direc... | [
"First, some basic facts about __new__ and __init__:\n\n__new__ is a constructor.\n__new__ typically returns an instance of cls, its first argument. \nBy __new__ returning an instance of cls, __new__ causes Python to call __init__.\n__init__ is an initializer. It modifies the instance (self)\nreturned by __new__. I... | [
11,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008633959_python.txt |
Q:
Add pickle to a Python extension written in C++
I have written a Python extension in C. It works, no issues. Now I'd want to use pickle with it. From the documentation I'm confused. I wrote a test __reduce__ function as suggested here for "extensions":
http://docs.python.org/library/pickle.html#the-pickle-protocol... | Add pickle to a Python extension written in C++ | I have written a Python extension in C. It works, no issues. Now I'd want to use pickle with it. From the documentation I'm confused. I wrote a test __reduce__ function as suggested here for "extensions":
http://docs.python.org/library/pickle.html#the-pickle-protocol
what I miss is what the "callable object" should be.... | [
"If you call __new__ and you're using type as your metaclass, __init__ will be called if the result of __new__ is a subtype of your type. Put another way, Let's say you have a class Foo. If you call the result of PyObject_Type(self), that is the same as calling Foo(). This means that Foo.__new__ will be called ... | [
2
] | [] | [] | [
"c",
"c++",
"pickle",
"python"
] | stackoverflow_0008706416_c_c++_pickle_python.txt |
Q:
simple python sort over csv
I have two csv files: one is 98 mb and the other one is 152 kb. the smaller file is a random subset of the bigger one, and I want to write a third file from the big csv such that the rows correspond to each line in the smaller csv file.
Big file (excerpt):
ZINC_ID MWT LogP Desolv_ap... | simple python sort over csv | I have two csv files: one is 98 mb and the other one is 152 kb. the smaller file is a random subset of the bigger one, and I want to write a third file from the big csv such that the rows correspond to each line in the smaller csv file.
Big file (excerpt):
ZINC_ID MWT LogP Desolv_apolar Desolv_polar HBD HBA tP... | [
"The CSV readers can be iterated just once. After the first inner iteration is done, the underlying file object reaches the end of the file. Once you try to iterate over the reference reader for the second time there is nothing more to read.\nI'd recommend that you first read the small file to a dictionary, and the... | [
2,
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008706896_csv_python.txt |
Q:
Python: extra assignments in functions
Considering the following as two versions of a very simple function in Python, the question is which one is preferred over another and why?
Is there any extra memory usage and or CPU usage for case 1 compared to case 2 in which additional assignment has been used?
case 1:
... | Python: extra assignments in functions | Considering the following as two versions of a very simple function in Python, the question is which one is preferred over another and why?
Is there any extra memory usage and or CPU usage for case 1 compared to case 2 in which additional assignment has been used?
case 1:
def f(x):
y = x*x
return y
case 2:
... | [
"If you want to know what Python style is preferred, look at the code in the standard library:\n$ grep return Lib/*py\n\nYou will see that the case 2 style is the most common.\nI personally use the assignment form only when the variable name is needed to add clarity to the code:\nnormalized_query = query.replace(' ... | [
7,
3,
3
] | [] | [] | [
"assign",
"cpu_usage",
"memory_management",
"python"
] | stackoverflow_0008706661_assign_cpu_usage_memory_management_python.txt |
Q:
Using Dropbox's python API to detect changes
How would I go about detecting if a file changed, using Dropbox's python API? I can't simply check the file on disk because it won't be updated if it's in use.
A:
The best way to do this would be to use the files hash that you get from the Metadata call of the API. Y... | Using Dropbox's python API to detect changes | How would I go about detecting if a file changed, using Dropbox's python API? I can't simply check the file on disk because it won't be updated if it's in use.
| [
"The best way to do this would be to use the files hash that you get from the Metadata call of the API. You should then store this hash locally.\nThe Metadata API call can also take a metadata parameter which will make it return a 304 (Not Modified) status if the file has not changed. (more info: https://www.dropbo... | [
2
] | [] | [] | [
"dropbox",
"python"
] | stackoverflow_0006701220_dropbox_python.txt |
Q:
How can I use Ruby to create an "EXE" like DropBox used Python?
I have a project which is similar to DropBox. I need to automatically push certain folders up to S3 from both Windows and Mac machines. DropBox won't do exactly what I need so I can't really use it. Plus, I would like for this to be a neat learning... | How can I use Ruby to create an "EXE" like DropBox used Python? | I have a project which is similar to DropBox. I need to automatically push certain folders up to S3 from both Windows and Mac machines. DropBox won't do exactly what I need so I can't really use it. Plus, I would like for this to be a neat learning experience in the joys of file synchronization. :-)
Anyway, after d... | [
"For Python, the most popular solution is Py2App.\nWith Ruby, there is MacRuby and Platypus. MacRuby is a Mac-specific Ruby implementation, so it would be better suited for projects that use MacOS features, written from scratch. Platypus would likely be better for packaging up existing scripts as an app.\n"
] | [
1
] | [] | [] | [
"distribution",
"dropbox",
"executable",
"python",
"ruby"
] | stackoverflow_0008707163_distribution_dropbox_executable_python_ruby.txt |
Q:
Python and Unicode
I'm learning Django through the tutorials on their website and I'm running into a weird problem. At this step when I get to the part where I enter the unicode snippets so that
>>> Poll.objects.all()
will return not this
[<Poll: Poll object>]
but something like this
[<Poll: What's up?>]
for ... | Python and Unicode | I'm learning Django through the tutorials on their website and I'm running into a weird problem. At this step when I get to the part where I enter the unicode snippets so that
>>> Poll.objects.all()
will return not this
[<Poll: Poll object>]
but something like this
[<Poll: What's up?>]
for some reason the code onl... | [
"Must be caused by mixed tab/space indentation...\nYour code pasted in the comment was messed up but I had a look at the HTML source code and found that the lines you typed in (around the __unicode__ methods, specifically) were indented using mixed tabs/spaces. Maybe you're using an editor where you configured the ... | [
1,
1
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0007170171_django_python_unicode.txt |
Q:
Mapping a texture to a mayavi mesh
I'm using mayavi in python to visualize some data. I have a surface in 3D space and I want to map an image to it. I have looked at mayavi documentation and all I could find was this, which really doesn't help me much. Has anybody done something like this before?
A:
I found that... | Mapping a texture to a mayavi mesh | I'm using mayavi in python to visualize some data. I have a surface in 3D space and I want to map an image to it. I have looked at mayavi documentation and all I could find was this, which really doesn't help me much. Has anybody done something like this before?
| [
"I found that the mesh function actually does take a scalars argument, which then colors the corresponding point on the surface in accordance to the chosen colormap. I still however don't know how to map an arbitrary RGB image to the surface.\n",
"I guess you didn't saw the chapter \"Python scripting for 3D plott... | [
2,
1
] | [] | [] | [
"mayavi",
"numpy",
"python",
"texture_mapping",
"visualization"
] | stackoverflow_0008610482_mayavi_numpy_python_texture_mapping_visualization.txt |
Q:
Why is my nested while loop not working
Working on a program in python to print out the first 1000 prime numbers (except 2). all i can get for the output is the number 3. don't understand where or when my loop is ending. very new at programming. can anybody help?
primeCounter = 1
candidate = 3
while primeCounter ... | Why is my nested while loop not working | Working on a program in python to print out the first 1000 prime numbers (except 2). all i can get for the output is the number 3. don't understand where or when my loop is ending. very new at programming. can anybody help?
primeCounter = 1
candidate = 3
while primeCounter < 1000:
isPrime = True
counter = 2
... | [
"primeCounter = 1\ncandidate = 3\n\nwhile primeCounter < 1000:\n isPrime = True\n counter = 2\n while counter < candidate:\n if candidate%counter == 0:\n isPrime = False\n break # <<<<<<<<<<<<<<<<< break here, or the loop will go infinite\n else:\n counter =... | [
3,
2,
0
] | [] | [] | [
"nested",
"python",
"while_loop"
] | stackoverflow_0008707665_nested_python_while_loop.txt |
Q:
Shared Non-Contiguous-Access Numpy Array
I have a numpy array that I would like to share between a bunch of python processes in a way that doesn't involve copies. I create a shared numpy array from an existing numpy array using the sharedmem package.
import sharedmem as shm
def convert_to_shared_array(A):
sha... | Shared Non-Contiguous-Access Numpy Array | I have a numpy array that I would like to share between a bunch of python processes in a way that doesn't involve copies. I create a shared numpy array from an existing numpy array using the sharedmem package.
import sharedmem as shm
def convert_to_shared_array(A):
shared_array = shm.shared_empty(A.shape, A.dtype,... | [
"Fancy indexing induces a copy, so you need to avoid fancy indexing if you want to avoid copies there is no way around it.\n"
] | [
1
] | [] | [] | [
"multiprocessing",
"numpy",
"python",
"shared_memory"
] | stackoverflow_0008525705_multiprocessing_numpy_python_shared_memory.txt |
Q:
How to install Python 2.7 bindings for OpenCV using MacPorts
When trying to "import cv" in python I get: "ImportError: No module named cv". This question has appeared in many forms, but I haven't found the answer that helps.
On my Mac OS X Lion, among many other ports, I have run:
sudo port install python27
and
s... | How to install Python 2.7 bindings for OpenCV using MacPorts | When trying to "import cv" in python I get: "ImportError: No module named cv". This question has appeared in many forms, but I haven't found the answer that helps.
On my Mac OS X Lion, among many other ports, I have run:
sudo port install python27
and
sudo port install opencv +python27
Running:
port select python
I ... | [
"I had this same problem. It looks like a (maybe?) bug with the OpenCV install script for 2.3.1a. It will not create the Python bindings unless NumPy is already installed.\nTo fix it:\nsudo port uninstall opencv\nsudo port install py27-numpy\nsudo port install opencv +python27\n\nThat worked for me! I found this ... | [
20,
2
] | [
"I was wondering if you have installed opencv to the OSX version of the python instead of macports.\nhave you tried easy install, I normally use easy_install to install the packages.\n/opt/local/bin/easy_install-2.7 opencv\n\n"
] | [
-2
] | [
"macports",
"opencv",
"osx_lion",
"python"
] | stackoverflow_0008410443_macports_opencv_osx_lion_python.txt |
Q:
opencv macport python bindings
using the MacPorts install of OpenCV does not seem to install the python bindings anywhere. Are they included, where do they go?
A:
Have you selected the +python26 variant for the MacPorts port?
$ sudo port install opencv +python26
A:
I experienced this same issue. It seems the O... | opencv macport python bindings | using the MacPorts install of OpenCV does not seem to install the python bindings anywhere. Are they included, where do they go?
| [
"Have you selected the +python26 variant for the MacPorts port?\n$ sudo port install opencv +python26\n\n",
"I experienced this same issue. It seems the OpenCV Python bindings are built and installed, but they are not referenced in the \"site-packages\" directory. I have found a solution by adding a symbolic link... | [
10,
7,
1,
1
] | [
"Here is what I had to do:\nSTEP ONE\nUse Macports to install opencv.\nSTEP TWO\nPut these two files somewhere on your PYTHONPATH (for example in your site-packages):\n\nhttps://github.com/jonmrodriguez/opencv-2.3-new-python-bindings/blob/master/cv.py\nhttps://github.com/jonmrodriguez/opencv-2.3-new-python-bindings... | [
-1
] | [
"macports",
"opencv",
"python"
] | stackoverflow_0003681496_macports_opencv_python.txt |
Q:
How can I get inputed text from a textctrl to output an answer in wxpython
what i really need help with is the function on line 112. I am trying to create a GUI calculator the only part i am having trouble with is when the person enters a problem like 5+5 it isnt able to store that in a varible. So how would i sol... | How can I get inputed text from a textctrl to output an answer in wxpython | what i really need help with is the function on line 112. I am trying to create a GUI calculator the only part i am having trouble with is when the person enters a problem like 5+5 it isnt able to store that in a varible. So how would i solve the problem and then output it to the text box.
thank you
import math
import ... | [
"I think your problem is here:\ndef eenter(self,e):\n a=self.box.GetValue()\n answer=int(a)\n ans=str(answer)\n self.box.SetValue(ans)\n\nIt doesn't work because a is a string that can not be converted to an integer directly.\nYou can see here an example of a wxPython calculator. It takes less than 50 l... | [
1
] | [] | [] | [
"calculator",
"math",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0008708052_calculator_math_python_user_interface_wxpython.txt |
Q:
Generating IDs how to make IDs same length using zeroes?
Update: The requirement is "fixed length 9 digits" so 460 000 000 138 should be 460 000 138
I want to generate IDs on a special form such as 460 000 000 138 where 46 is the country code and the rest is the ID and this number always(?) has the same number of ... | Generating IDs how to make IDs same length using zeroes? | Update: The requirement is "fixed length 9 digits" so 460 000 000 138 should be 460 000 138
I want to generate IDs on a special form such as 460 000 000 138 where 46 is the country code and the rest is the ID and this number always(?) has the same number of digits ie four pairs of threes.
My input is this ID that can b... | [
"string.zfill() serves exactly this purpose.\n>>> \"1138\".zfill(10)\n0000001138\n\nafter that you just need to format the string to prepend the country code and then insert spaces wherever you require\n",
"def makeid(countrycode, n):\n countrycode = str(countrycode)\n n = str(n)\n return \"%s%s%s\" % (c... | [
4,
3,
1
] | [] | [] | [
"google_cloud_datastore",
"python"
] | stackoverflow_0008706850_google_cloud_datastore_python.txt |
Q:
Application of the dynamic/functional features of Python
I'm learning Python and it seems to be too dynamic to me. Application of some of the dynamic/functional features I understand. For example, you can use dynamic typing to write functions that behave the same for complex and real numbers. But application of ot... | Application of the dynamic/functional features of Python | I'm learning Python and it seems to be too dynamic to me. Application of some of the dynamic/functional features I understand. For example, you can use dynamic typing to write functions that behave the same for complex and real numbers. But application of others seems obscure to me.
So here is my question. Please give ... | [
"Lack of private variables: you don't have to waste time declaring every variable public or private. Most of the stuff is usually public. If you think that a directly variable accessed without getter/setters will break things, you can use the convention of naming it with underscore: e.g. self._metadata.\nAbility to... | [
1
] | [] | [] | [
"dynamic",
"functional_programming",
"python"
] | stackoverflow_0008708820_dynamic_functional_programming_python.txt |
Q:
Code to login to remote directory and search a file and download in Python over FTP
I've a package with .gz and filename as (xxxxxxxxxxxx_PARSERxxxxx.tar.gz) extension placed in a remote directory say 1.1.1.1(Should be a input as a variable), i'm currently running the script from machine say 2.2.2.2, i need to pla... | Code to login to remote directory and search a file and download in Python over FTP | I've a package with .gz and filename as (xxxxxxxxxxxx_PARSERxxxxx.tar.gz) extension placed in a remote directory say 1.1.1.1(Should be a input as a variable), i'm currently running the script from machine say 2.2.2.2, i need to place the package in machine 3.3.3.3 (Should be input as avariable), prepared a script for t... | [
"It would really help if you told us how the program is not working. \nBy glancing quickly over it, I'd say you perserfile bit and filenm usage are wrong. \n\nos.system returns an integer, so filenm is not a file name, but the exist status of the find command. You want to use pipe = subprocess.Popen(['find', '.', '... | [
0
] | [] | [] | [
"ftp",
"ftplib",
"operating_system",
"python",
"telnetlib"
] | stackoverflow_0008708889_ftp_ftplib_operating_system_python_telnetlib.txt |
Q:
Python IP Check
Given the range xxx.xxx.xxx.(195-223)
Is that correct to write it in xxx.xxx.xxx.196/29 and check whether an IP is in the given network by doing
from ipaddr import IP, CIDR
#if IP('xxx.xxx.xxx.xxx') in IP('xxx.xxx.xxx.196/29') or
#if IP('xxx.xxx.xxx.xxx') in CIDR('xxx.xxx.xxx.196/29')
A:
I didn'... | Python IP Check | Given the range xxx.xxx.xxx.(195-223)
Is that correct to write it in xxx.xxx.xxx.196/29 and check whether an IP is in the given network by doing
from ipaddr import IP, CIDR
#if IP('xxx.xxx.xxx.xxx') in IP('xxx.xxx.xxx.196/29') or
#if IP('xxx.xxx.xxx.xxx') in CIDR('xxx.xxx.xxx.196/29')
| [
"I didn't see IP in ipaddr, only IPAddress.\nMay be like this?\nfrom ipaddr import IPAdddress, IPNetwork\n\nif IPAddress('10.0.0.195') in IPNetwork('10.0.0.196/29'):\n pass\n\n",
"I haven't used the ipaddr module, but note that /29 means that your network mask is 255.255.255.248 and that you only have the late... | [
2,
1
] | [] | [] | [
"ip",
"python"
] | stackoverflow_0008708950_ip_python.txt |
Q:
Python: Given a Date and Weekday find the date of the next occurrence of a given weekday
This is a bit difficult to explain, so I apologize if this doesn't make much sense.
I have a program where I am doing some scheduling. One of the settings it has is to run a task weekly on certain days. For example, weekly on ... | Python: Given a Date and Weekday find the date of the next occurrence of a given weekday | This is a bit difficult to explain, so I apologize if this doesn't make much sense.
I have a program where I am doing some scheduling. One of the settings it has is to run a task weekly on certain days. For example, weekly on Monday, Wednesday and Friday.
Consider the example where the current task is scheduled for 1/2... | [
"Use dateutil.relativedelta:\nfrom dateutil import relativedelta\nimport datetime\n\ntoday = datetime.date.today()\n# datetime.date(2012, 1, 3)\n\ntoday + relativedelta.relativedelta(weekday=2) # 2 is Wednesday\n# datetime.date(2012, 1, 4)\n\ntoday + relativedelta.relativedelta(weekday=6) # 6 is Sunday\n# datetime.... | [
14,
8,
0,
0
] | [] | [] | [
"datetime",
"python",
"timedelta"
] | stackoverflow_0008708058_datetime_python_timedelta.txt |
Q:
How to speed up HTTP Response receiving using jQuery Ajax in large data posting?
Issue:
python webapp2 + jQuery Ajax perfroms extremely bad in receiving large text data response (takes more than 10 minutes in a 1.7MB payload roundtrip)
Question:
what's the reason? how to improve it? could I use any well-proved tec... | How to speed up HTTP Response receiving using jQuery Ajax in large data posting? | Issue:
python webapp2 + jQuery Ajax perfroms extremely bad in receiving large text data response (takes more than 10 minutes in a 1.7MB payload roundtrip)
Question:
what's the reason? how to improve it? could I use any well-proved techniques to divide the big text trunk into small payloads to avoid the 'browser hung' i... | [
"Consider using a combination of HTML5 WebSockets & Worker API to asynchronously send/receive data from the server without affecting the UI thread performance.\nhttp://dev.w3.org/html5/websockets/\nhttp://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/ (the tutorial assumes PHP to be ... | [
1
] | [] | [] | [
"ajax",
"jquery",
"python",
"web_applications",
"wysiwyg"
] | stackoverflow_0008005042_ajax_jquery_python_web_applications_wysiwyg.txt |
Q:
Easiest way to exit from menu
I finished all my homework but i forgot to put a cancel option under submenu. I do not want to change all my files, it took 2 days to do this. What will the easiest way to add a cancel and return to main menu option on sub_menu.py
this is the sub_menu.py
#!/usr/bin/python
## sub_menu... | Easiest way to exit from menu | I finished all my homework but i forgot to put a cancel option under submenu. I do not want to change all my files, it took 2 days to do this. What will the easiest way to add a cancel and return to main menu option on sub_menu.py
this is the sub_menu.py
#!/usr/bin/python
## sub_menu.py
#=========#=========#=========... | [
"You can do it in 2 lines of codes. \nin sub_menu.py you should add \"0\" handling like so \n...\ntry:\n shape_num = int(shape_num)\n if ( shape_num == 0):\n return None\n if (1 <= shape_num <= 5):\n print \" Number \", shape_num ,\" is OK.\"\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008709453_python.txt |
Q:
config driven path for sprites in css
I use a lot of sprites in my css and all the location to the images has been hardcoded within the css. Now i am planning to move all images to a CDN. Its very hard to change the path in each and every place. Is there a way, to place the location as a variable in config file so... | config driven path for sprites in css | I use a lot of sprites in my css and all the location to the images has been hardcoded within the css. Now i am planning to move all images to a CDN. Its very hard to change the path in each and every place. Is there a way, to place the location as a variable in config file so that i need not change the path at all pla... | [
"You might consider to use LESS stylesheets which would allow you to use variables, in this case you still need to update the PATH config your own (or write a simple script that does that for you).\n@SPRITE_LOCATION: '..path/to/sprites/'\n#header .topriglogin .telephone{background:url(@SPRITE_LOCATION'sprites.gif')... | [
0
] | [] | [] | [
"css",
"django",
"python"
] | stackoverflow_0008708443_css_django_python.txt |
Q:
wxpython capture keyboard events in a wx.Frame
I'm trying to capture keyboard events that happen inside a wx.Frame, and I would expect the following code to capture those events. However, the handler OnKeyDown is never called when I run the code:
import logging as log
import wx
class MainWindow(wx.Frame):
def... | wxpython capture keyboard events in a wx.Frame | I'm trying to capture keyboard events that happen inside a wx.Frame, and I would expect the following code to capture those events. However, the handler OnKeyDown is never called when I run the code:
import logging as log
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__i... | [
"I figured out that I can add a panel to the frame, and a panel is much more receptive of keyboard events. \nimport wx\n\nclass MainWindow(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=(200,100))\n\n self.panel = wx.Panel(self, wx.ID_ANY)\n ... | [
10,
3
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0008707160_python_wxpython_wxwidgets.txt |
Q:
How to check if a function exist (but not inherited) in python?
Kind of related to this question:
https://stackoverflow.com/questions/8708525/how-to-check-if-mako-function-exist
I want to check if a function exists for a given class, but not inherited, so that the parent can called the child's function, since othe... | How to check if a function exist (but not inherited) in python? | Kind of related to this question:
https://stackoverflow.com/questions/8708525/how-to-check-if-mako-function-exist
I want to check if a function exists for a given class, but not inherited, so that the parent can called the child's function, since otherwise it would result in an infinite recursion..
edit:
it actually gi... | [
"\nI want to check if a function exists for a given class, but not inherited\n\nYes, you can check the class dictionary directly. Either use the __dict__ attribute or the built-in vars() function::\n>>> class A(object):\n def f(x):\n pass\n\n>>> class B(A):\n def g(x):\n pass\n\... | [
11,
2
] | [] | [] | [
"python"
] | stackoverflow_0008708917_python.txt |
Q:
BeautifulSoup Malformed Start Tag?
I am trying to convert a Wordpress XML to Octopress, using in part BeautifulSoup to do the migration.
When I run exitwp, I get the following output:
writing......................................................Traceback (most recent call last):
File "exitwp.py", line 293, in <mo... | BeautifulSoup Malformed Start Tag? | I am trying to convert a Wordpress XML to Octopress, using in part BeautifulSoup to do the migration.
When I run exitwp, I get the following output:
writing......................................................Traceback (most recent call last):
File "exitwp.py", line 293, in <module>
write_jekyll(data, target_for... | [
"modify your code like this (in html2text.py):\ntry:\n HTMLParser.HTMLParser.feed(self, data)\nexcept:\n print 'malformed data: %r' % data\n raise\n\nI guess you will see, that 'data' contains something strange. If not, please add the data to your question.\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0008707343_beautifulsoup_python.txt |
Q:
Why some class variables seem to act as static while others don't?
Dictionaries and lists defined directly under the class definition act as static (e.g. this question)
How come other variables such as integer do not?
>>> class Foo():
bar=1
>>> a=Foo()
>>> b=Foo()
>>> a.bar=4
>>> b.bar
1
>>> class Foo():
... | Why some class variables seem to act as static while others don't? | Dictionaries and lists defined directly under the class definition act as static (e.g. this question)
How come other variables such as integer do not?
>>> class Foo():
bar=1
>>> a=Foo()
>>> b=Foo()
>>> a.bar=4
>>> b.bar
1
>>> class Foo():
bar={}
>>> a=Foo()
>>> b=Foo()
>>> a.bar[7]=8
>>> b.bar
{7: 8}
... | [
"They are all class variables. Except for when you assigned a.bar=4 creating an instance variable. Basically Python has a lookup order on attributes. It goes:\ninstance -> class -> parent classes in MRO order (left to right)\n\nSo if you have\nclass Foo(object):\n bar = 1\n\nThis is a variable on the class Foo. ... | [
15,
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0008709542_python.txt |
Q:
Having some ModelForms at the same page with some similar Field Name
I've put forms of these model(via ModelForm) at the same page but similar Field Names have made some problem for me:
class Transfer(models.Model):
ServiceProvider=models.ForeignKey(ServiceProvider)
Vehicle=models.ForeignKey(Vehicle)
From... | Having some ModelForms at the same page with some similar Field Name | I've put forms of these model(via ModelForm) at the same page but similar Field Names have made some problem for me:
class Transfer(models.Model):
ServiceProvider=models.ForeignKey(ServiceProvider)
Vehicle=models.ForeignKey(Vehicle)
From=models.ForeignKey(Location,related_name='FromLocation')
To=models.Fore... | [
"You can pass the forms a prefix e.g. \ntransfer = TransferForm(prefix=\"transfer\")\nvisit = VisitForm(prefix=\"visit\")\naccommodate = AccommodateForm(prefix=\"accommodate\")\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008709834_django_python.txt |
Q:
Error while using urllib.request.urlopen in Python
What's wrong with this code?
>>> from urllib.request import urlopen
>>> for line in urlopen("http://google.com/"):
print(line.decode("utf-8"))
<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=windows-1251"><title>Googl... | Error while using urllib.request.urlopen in Python | What's wrong with this code?
>>> from urllib.request import urlopen
>>> for line in urlopen("http://google.com/"):
print(line.decode("utf-8"))
<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=windows-1251"><title>Google</title><script>window.google={kEI:"XMECT7XyDcGn0AWFk7... | [
"Google sends you text in windows-1251 encoding, it says it in meta tag. This will work:\n>>> from urllib.request import urlopen\n>>> for line in urlopen(\"http://google.com/\"):\n print(line.decode(\"cp1251\"))\n\n",
"That's your failing line (last part of it):\n>>> line\nb'<a class=gb1 href=\"http://www.g... | [
6,
2
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0008709810_python_urllib_urlopen.txt |
Q:
Using object variable as a recursive method argument in a Python class
I am trying to write a recursive function within a class, but have some trouble using an object var as a method argument:
class nonsense(object):
def __init__(self, val):
self.val = val
def factorial(self, n=self.val):
if n<=1: retu... | Using object variable as a recursive method argument in a Python class | I am trying to write a recursive function within a class, but have some trouble using an object var as a method argument:
class nonsense(object):
def __init__(self, val):
self.val = val
def factorial(self, n=self.val):
if n<=1: return 1
return n*self.factorial(n=n-1)
The code above generates the follow... | [
"Default parameters are evaluated when the method is defined. Thus, it's essentially \"too late\" to use a member value defined in __init__. What you should do is set the default value to None and test for this in the body of the function:\nclass nonsense(object):\n def __init__(self, val):\n self.val = v... | [
6,
3,
1,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0008707155_python_recursion.txt |
Q:
Overwrite {} in python
I want to make a dict int which you can access like that:
>>> my_dict["property'] = 3
>>> my_dict.property
3
So I've made this one:
class DictAsMember(dict):
def __getattr__(self, name):
return self[name]
This works fine, but if you have nested dicts it doesn't work, e.g:
my_di... | Overwrite {} in python | I want to make a dict int which you can access like that:
>>> my_dict["property'] = 3
>>> my_dict.property
3
So I've made this one:
class DictAsMember(dict):
def __getattr__(self, name):
return self[name]
This works fine, but if you have nested dicts it doesn't work, e.g:
my_dict = DictAsMember()
my_dict[... | [
"One workaround to the problem is wrapping default dictionaries using DictAsMember before returning them in the __getattr__ method:\nclass DictAsMember(dict):\n def __getattr__(self, name):\n value = self[name]\n if isinstance(value, dict):\n value = DictAsMember(value)\n elif isi... | [
7,
2
] | [] | [] | [
"dictionary",
"overwrite",
"python"
] | stackoverflow_0008709975_dictionary_overwrite_python.txt |
Q:
Unable to post attachment(with an image) to facebook page via python's Facebook Graph API
My django website requires regular posting to the website's fb page. I am able to post content to the fb page(as an attachment) via a custom app. using python's facebook graph api.
However, when I try to post an attachment a... | Unable to post attachment(with an image) to facebook page via python's Facebook Graph API | My django website requires regular posting to the website's fb page. I am able to post content to the fb page(as an attachment) via a custom app. using python's facebook graph api.
However, when I try to post an attachment alongwith an image, the image does not appear.
Here is the code(except image I can see everythi... | [
"You using media while you should use picture instead.\nAnd you doesn't need to provide anything except the url of an image.\nattachment['picture'] = {{FILE_URL}}\n\n"
] | [
1
] | [] | [] | [
"django",
"facebook_graph_api",
"python"
] | stackoverflow_0008710159_django_facebook_graph_api_python.txt |
Q:
ImportError exception encountered while trying to use Fabric
I am using Ubuntu and virtualenv, and I am having this recurring problem, while attempting to use Fabric to create a deployment script. Fabric depends on paramiko, which depends on PyCrypto.
Each time I try to use Fabric, or PyCrypto directly, I get this... | ImportError exception encountered while trying to use Fabric | I am using Ubuntu and virtualenv, and I am having this recurring problem, while attempting to use Fabric to create a deployment script. Fabric depends on paramiko, which depends on PyCrypto.
Each time I try to use Fabric, or PyCrypto directly, I get this error:
ImportError: cannot import name Random
I have tried reins... | [
"It's possible that there's a file name collision in your the directory from which you're running Fabric. Do you have a file called Crypto.py in your project? \nCan you get Crypto.Random to import from outside of your project directory? (but still using your virtualenv. Ipython is a big help here.) \n",
"I've ... | [
0,
0
] | [] | [] | [
"fabric",
"paramiko",
"pycrypto",
"python",
"ubuntu_10.10"
] | stackoverflow_0006876150_fabric_paramiko_pycrypto_python_ubuntu_10.10.txt |
Q:
Using virtualenv in VMWare with shared Windows folder
I currently use a linux VM in VMWare running on a Windows machine. I have a shared Windows folder for my projects that I access in linux via /mnt/hgfs/
When I try to use virtualenv for my python projects I get an 'Operation not supported' error:
joe@myserver:/m... | Using virtualenv in VMWare with shared Windows folder | I currently use a linux VM in VMWare running on a Windows machine. I have a shared Windows folder for my projects that I access in linux via /mnt/hgfs/
When I try to use virtualenv for my python projects I get an 'Operation not supported' error:
joe@myserver:/mnt/hgfs/winwww/envtest# virtualenv env
Traceback (most rece... | [
"The virtualenv does not need to be located next to your code, so even if you can't create it within your shared folder this shouldn't affect your ability to edit the code on windows and run it on your host platform. It sounds to me like a bad idea anyway to attempt to share platform-specific files with multiple pl... | [
5
] | [] | [] | [
"linux",
"python",
"virtualenv",
"vmware"
] | stackoverflow_0008710867_linux_python_virtualenv_vmware.txt |
Q:
How to get the length of the current line (or the offset of the end of the line) in a Gedit plugin
In a Gedit plugin written in Python, I can get the offset of the beginning of the current line with
document = window.get_active_document()
offset = document.get_iter_at_mark(document.get_insert())
How could I get ... | How to get the length of the current line (or the offset of the end of the line) in a Gedit plugin | In a Gedit plugin written in Python, I can get the offset of the beginning of the current line with
document = window.get_active_document()
offset = document.get_iter_at_mark(document.get_insert())
How could I get the offset of the end of this same line? For now I am using a workaround: I get the offset of the next l... | [
"A bit late, I know, but better late than never. I am running gedit 3.2.3 and I don't know how much these things change from one version to another, but this works for me:\nline_types = {\"cr-lf\": '\\r\\n',\n \"lf\": '\\n',\n \"cr\": '\\r'}\ndocument = window.get_active_document()\nnewlin... | [
1
] | [] | [] | [
"gedit",
"gtk",
"pygtk",
"python"
] | stackoverflow_0008176983_gedit_gtk_pygtk_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.