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:
Dynamic array of dynamic (array of struct)
I have a struct named person as follows:
struct person {
int height, weight;
};
I also created an array of person as follows:
struct Arrayofperson {
int len; //indicates the length of this array(its supposed to be dynamic)
person *p; //this is supposed to b... | Dynamic array of dynamic (array of struct) | I have a struct named person as follows:
struct person {
int height, weight;
};
I also created an array of person as follows:
struct Arrayofperson {
int len; //indicates the length of this array(its supposed to be dynamic)
person *p; //this is supposed to be the dynamic array of person.
};
And I ... | [
"The problem here is that python does not know how to handle your struct. Check the documentation for ctypes, it has a list of supported python types that you can pass to C functions, and documentation on how to make it handle some more types.\nThe way you've written it, python thinks that all your functions return... | [
1,
0,
0
] | [] | [] | [
"c++",
"dll",
"python"
] | stackoverflow_0008485664_c++_dll_python.txt |
Q:
aplication auto-deploy to WebLogic poduce "Warning"
I've prepared simple deployment script that deploy my EJB Application to WebLogic 10.3 server.
application packed as ear file.
connect(username, password, "t3://" + wlHost + ":" + wlPort)
deploy('myApp','/path/to/ear/myApp.ear',targets='ADMIN')
startApplicatio... | aplication auto-deploy to WebLogic poduce "Warning" | I've prepared simple deployment script that deploy my EJB Application to WebLogic 10.3 server.
application packed as ear file.
connect(username, password, "t3://" + wlHost + ":" + wlPort)
deploy('myApp','/path/to/ear/myApp.ear',targets='ADMIN')
startApplication('MyApp')
exit()
After succsesfull deploy message I se... | [
"I'll answer my question because I don't like to keep unanswered questions. The problem was in deployment target . I targeted ADMIN but need to target one of the cluster memebers that have jms/MyAppResponseQueue resource. \n"
] | [
0
] | [] | [] | [
"python",
"weblogic",
"weblogic_10.x",
"wlst"
] | stackoverflow_0008491292_python_weblogic_weblogic_10.x_wlst.txt |
Q:
optimization tool
I wonder there are any tool to optimize my program in term of loop unrolling, and how can I use it?
I have the following python code:
for i in range(0, 1000):
a = a * 10 + a%4 + i
for j in range(0, 1000):
j = j + a
for b in range(0, 1000):
result = j + b
I want to optimize t... | optimization tool | I wonder there are any tool to optimize my program in term of loop unrolling, and how can I use it?
I have the following python code:
for i in range(0, 1000):
a = a * 10 + a%4 + i
for j in range(0, 1000):
j = j + a
for b in range(0, 1000):
result = j + b
I want to optimize this code segment so tha... | [
"a = 30\nfor i in range ( 0,1000 ) :\n a = a * 10 + a%4 + i\n\ncan be rewritten as:\na = reduce(lambda a,b: a * 10 + a%4 + b, xrange(1000), 30)\n\ntakes about the same time (~4ms on my computer).\n\nfor j in range ( 0, 1000 ) :\n j = j + a\n\ndoesn't make much sense. You are iterating j over 0-999, and eac... | [
4,
3,
2
] | [] | [] | [
"loop_unrolling",
"loops",
"optimization",
"python"
] | stackoverflow_0008505417_loop_unrolling_loops_optimization_python.txt |
Q:
How to crawl folders to index files?
I'm searching a possibility to crawl through a filesystem (similar to the 'tree' CMD command) to find every *.R3D file in all the folders/sub folders and index them. What's the most effective way to do that, while the load should be as small as possible?
A:
You may want to us... | How to crawl folders to index files? | I'm searching a possibility to crawl through a filesystem (similar to the 'tree' CMD command) to find every *.R3D file in all the folders/sub folders and index them. What's the most effective way to do that, while the load should be as small as possible?
| [
"You may want to use a helper function that wraps os.walk, like this:\nimport os\n\ndef filesByPattern(directory, matchFunc):\n for path,dirs,files in os.walk(directory):\n for f in filter(matchFunc, path):\n yield os.path.join(path, f)\n\ncertainFolder = '.'\nallR3DFiles = filesByPattern(certainFolder, la... | [
6,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0008505457_python.txt |
Q:
subprocess piping output on Windows
I've got this piece of code that works fine on Linux but fails on Windows. Process is created fine, but I get an error and nothing is read from pipe:
p = subprocess.Popen(['python', '-u', self.file_to_run,
'-s', '-g', '-i', self.input_file]... | subprocess piping output on Windows | I've got this piece of code that works fine on Linux but fails on Windows. Process is created fine, but I get an error and nothing is read from pipe:
p = subprocess.Popen(['python', '-u', self.file_to_run,
'-s', '-g', '-i', self.input_file],
univ... | [
"try using sys.executable instead of 'python' in your subprocess args. I think this is because Python is not in the PATH on Windows. \nAlso check the value of self.file_to_run and self.input_file which must be strings and not None or strange stuff, but this probably won't cause an OSError. \n"
] | [
0
] | [] | [] | [
"python",
"stdout",
"subprocess"
] | stackoverflow_0008505513_python_stdout_subprocess.txt |
Q:
Compiling django project with Pyrex
I was wondering if someone was able to compile Django based projects (into shared object libs for instance) with pyrex (or anything similar) and still maintain the flexibility using normal Django projects with python.
We have to be able to use the project with apache so it cann... | Compiling django project with Pyrex | I was wondering if someone was able to compile Django based projects (into shared object libs for instance) with pyrex (or anything similar) and still maintain the flexibility using normal Django projects with python.
We have to be able to use the project with apache so it cannot be compiled into a standalone binary. ... | [
"Pyrex and its sucessor - cython - are not fully python compatible - they are rather another language, although Python based.\nDjango is a very complex project, and would require strict Python compliance to run - i doubt it would be possible without some months of work to make Django work directly in cython or Pyre... | [
7
] | [] | [] | [
"cython",
"django",
"pyrex",
"python"
] | stackoverflow_0008505059_cython_django_pyrex_python.txt |
Q:
Python - creating dictionary for each key given file
I'm working on a text-parsing algorithm (open-source side project). I'd be very appreciative for any advice.
I have a tab-delimited txt file which is sorted by the first column (sample dataset below). Duplicate entries exist within this column.
Ultimately, I wou... | Python - creating dictionary for each key given file | I'm working on a text-parsing algorithm (open-source side project). I'd be very appreciative for any advice.
I have a tab-delimited txt file which is sorted by the first column (sample dataset below). Duplicate entries exist within this column.
Ultimately, I would like to use a hash to point to all values of which have... | [
"Use itertools.groupby, passing it the file as an iterator:\nfrom itertools import groupby\nfrom cStringIO import StringIO\n\nsourcedata = StringIO(\"\"\"\\\nA ... 23.4421\nA ... -23.442\nA ... 76.2224\nB ... 32.1232\nB ... -23.001\nC ... 652.123\"\"\")\n\n# or sourcedata = open(\... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"file",
"python"
] | stackoverflow_0008500732_dictionary_file_python.txt |
Q:
Project structure for desktop applications using SQLAlchemy and wxPython
I want to create a desktop application using SQLAlchemy and wxPython, but I'd like to structure the project in a way similar to django projects, using django app-like packages (related models, views and tests in the same package) and settings... | Project structure for desktop applications using SQLAlchemy and wxPython | I want to create a desktop application using SQLAlchemy and wxPython, but I'd like to structure the project in a way similar to django projects, using django app-like packages (related models, views and tests in the same package) and settings and main module in the root directory.
I'd like to know if that is a good str... | [
"You can certainly do it that way. I recently started a project with another fellow to demonstrate one way to do just this sort of thing. You're welcome to take a look at how we separate all this stuff out here: https://github.com/driscollis/MediaLocker\nIt's gotten a little abstract, but I think you can still use ... | [
4
] | [] | [] | [
"desktop",
"project_structure",
"python",
"sqlalchemy",
"wxpython"
] | stackoverflow_0008469160_desktop_project_structure_python_sqlalchemy_wxpython.txt |
Q:
How do I index n sets of 4 columns to plot multiple plots using matplotlib?
I want to know how I should index / access some data programmatically in python.
I have columnar data: depth, temperature, gradient, gamma, for a set of boreholes. There are n boreholes. I have a header, which lists the borehole name and ... | How do I index n sets of 4 columns to plot multiple plots using matplotlib? | I want to know how I should index / access some data programmatically in python.
I have columnar data: depth, temperature, gradient, gamma, for a set of boreholes. There are n boreholes. I have a header, which lists the borehole name and numeric ID. Example:
Bore_name,Bore_ID,,,Bore_name,Bore_ID,,,, ...
<a row of hea... | [
"You could put your data into a dict for each borehole, keyed by the borehole id, and values as dicts with headers as keys. Roughly like this:\ndata = {boreid1:{\"temp\":temparray, ...}, boreid2:{\"temp\":temparray}}\n\nProbably reading from files will be a little bit more cumbersome with these approach, but for pl... | [
1,
1,
1
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0008470539_matplotlib_numpy_python_scipy.txt |
Q:
Like FourWaySplitter but different
Using Python 2.6, wx.Python:
Wonder if someone might know how to build a four panel window w/o using FourWaySplitter. (Unless I am wrong FourWaySplitter will do what I am about to describe. With FourWaySplitter any change of the size of any sub-panel changes the size of ALL sub... | Like FourWaySplitter but different | Using Python 2.6, wx.Python:
Wonder if someone might know how to build a four panel window w/o using FourWaySplitter. (Unless I am wrong FourWaySplitter will do what I am about to describe. With FourWaySplitter any change of the size of any sub-panel changes the size of ALL sub-panels.)
Here is what I need:
ONE verti... | [
"This was pretty confusing for me too. Fortunately, I wanted to write an article on the subject and I finally figured it out after a couple of hours a month or three ago. I still haven't written the article, but I paired down my example a little for this answer. Hopefully you can follow it:\nimport random\nimport w... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008459880_python_wxpython.txt |
Q:
defining and accessing a list of custom objects
I have an object
class Car:
def __init__(self):
price = float(0)
Then another
class Day:
def __init__(self):
self.carList = [Car() for each in range(100)]
self.createPriceList()
def createPriceList(self):
tempCar = Car()
for i in range(100... | defining and accessing a list of custom objects | I have an object
class Car:
def __init__(self):
price = float(0)
Then another
class Day:
def __init__(self):
self.carList = [Car() for each in range(100)]
self.createPriceList()
def createPriceList(self):
tempCar = Car()
for i in range(100):
tempCar.price = function_giving_a_value() # ... | [
"The most likely explanation is that you don't actually call createPriceList() before calling showPriceList(). [edit: now that you've edited the code in your question, we can eliminate this possibility]\nAlso, createPriceList() has an error whereby you assign references to the same Car object to all elements of the... | [
4,
0,
0
] | [] | [] | [
"list",
"object",
"python"
] | stackoverflow_0008506239_list_object_python.txt |
Q:
Using Django Gargoyle how do I create my own condition set?
I'm using Django's sites framework and would like to use Gargoyle to enable/disable functionality on a site-by-site basis. This would involve creating my own condition set for Site.
I've read the Condition Set API reference and had a look at the built in ... | Using Django Gargoyle how do I create my own condition set? | I'm using Django's sites framework and would like to use Gargoyle to enable/disable functionality on a site-by-site basis. This would involve creating my own condition set for Site.
I've read the Condition Set API reference and had a look at the built in sets which come with Gargoyle, but I'm still at a loss as to how ... | [
"I've not used Gargoyle yet (though it's on my list of things I'd like to play with), and I agree - the documentation for ConditionSet doesn't look too helpful. Maybe looking at the source for builtins.py, which has the built-in ConditionSets, might help.\n",
"It's not very difficult to create a new condition set... | [
1,
1
] | [] | [] | [
"django",
"gargoyle",
"python"
] | stackoverflow_0008505562_django_gargoyle_python.txt |
Q:
Var(x) and cov(x, x) don't give the same result in numpy
A property of the covariance is, that cov(x, x) = var(x)
However, in numpy I don't get the same result.
from numpy import var, cov
x = range(10)
y = var(x)
z = cov(x, x)[0][1]
print y, z
Am I doing something wrong here? How can I obtain the correct result?... | Var(x) and cov(x, x) don't give the same result in numpy | A property of the covariance is, that cov(x, x) = var(x)
However, in numpy I don't get the same result.
from numpy import var, cov
x = range(10)
y = var(x)
z = cov(x, x)[0][1]
print y, z
Am I doing something wrong here? How can I obtain the correct result?
| [
"You must use z=cov(x,bias=1) in order to normalize by N ,because var is also norm by N\n(according to this\n",
"The default ddof of cov (None) and var (0) are different. Try specifying the ddof (or bias):\n>>> cov(x, x, ddof=0)\narray([[ 8.25, 8.25],\n [ 8.25, 8.25]])\n>>> var(x)\n8.25\n\n"
] | [
24,
12
] | [] | [] | [
"covariance",
"numpy",
"python",
"variance"
] | stackoverflow_0008506325_covariance_numpy_python_variance.txt |
Q:
Python Pip vs Ruby Gems
I mostly do work in Python, but I have been using some of the Ruby stuff for Server Configuration Management (ie Puppet and Chef). I also use Ubuntu/Debian as my primary Linux distro for servers.
Why is there a weird Debian/Ruby conflict over Gems, and not a similar showdown between Debian... | Python Pip vs Ruby Gems | I mostly do work in Python, but I have been using some of the Ruby stuff for Server Configuration Management (ie Puppet and Chef). I also use Ubuntu/Debian as my primary Linux distro for servers.
Why is there a weird Debian/Ruby conflict over Gems, and not a similar showdown between Debian/Python over Pip?
Personally,... | [
"I think you should raise your problem about gem/debian and what are you going to do with it specially.\nI am using pip and debian now and still no problem by now.\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"ruby",
"rubygems"
] | stackoverflow_0008433881_pip_python_ruby_rubygems.txt |
Q:
beginning and ending sign in regular expression in python
'[A-Za-z0-9-_]*'
'^[A-Za-z0-9-_]*$'
I want to check if a string only contains the sign in the above expression, just want to make sure no more weird sign like #%&/() are in the strings.
I am wondering if there's any difference between these two regular exp... | beginning and ending sign in regular expression in python | '[A-Za-z0-9-_]*'
'^[A-Za-z0-9-_]*$'
I want to check if a string only contains the sign in the above expression, just want to make sure no more weird sign like #%&/() are in the strings.
I am wondering if there's any difference between these two regular expression? Did the beginning and ending sign matter? Will it affe... | [
"Python regular expressions are anchored at the beginning of strings (like in many other languages): hence the ^ sign at the beginning doesn’t make any difference. However, the $ sign does very much make one: if you don’t include it, you’re only going to match the beginning of your string, and the end could contai... | [
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008507081_python_regex.txt |
Q:
how to remove "TypeError: can't multiply sequence by non-int of type 'float' "?
I am a python learner. I'm trying to find a retirement funds simulator that takes three arguments: a salary (salary), a percentage of your salary to save (save), and a list of annual growth percentages on investments (growthRates). The... | how to remove "TypeError: can't multiply sequence by non-int of type 'float' "? | I am a python learner. I'm trying to find a retirement funds simulator that takes three arguments: a salary (salary), a percentage of your salary to save (save), and a list of annual growth percentages on investments (growthRates). The length of the last argument defines the
number of years you plan to work; growthRat... | [
"The statement float(i) does nothing. Either use i=float(i), or substitute i in your formula with float(i), since it appears only once.\nDepending on what the user enters, input() will return a corresponding object. If you enter 0.0, 1.0, 2e10, 99 you already get a tuple of float and integer values, so there is no ... | [
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008507054_python_python_3.x.txt |
Q:
Checking user input using isnan function of NumPy
I'm trying to use NumPy to check if user input is numerical. I've tried using:
import numpy as np
a = input("\n\nInsert A: ")
if np.isnan(a):
print 'Not a number...'
else:
print "Yep,that's a number"
On its own t works fine, however when I embed it into ... | Checking user input using isnan function of NumPy | I'm trying to use NumPy to check if user input is numerical. I've tried using:
import numpy as np
a = input("\n\nInsert A: ")
if np.isnan(a):
print 'Not a number...'
else:
print "Yep,that's a number"
On its own t works fine, however when I embed it into a function such as in this case:
import numpy as np
de... | [
"\"Not a Number\" or \"NaN\" is a special kind of floating point value according to the IEEE-754 standard. The functions numpy.isnan() and math.isnan() test if a given floating point number has this special value (or one of several \"NaN\" values). Passing anything else than a floating point number to one of thes... | [
11,
2,
0
] | [] | [] | [
"input",
"notimplementedexception",
"numpy",
"python",
"python_2.x"
] | stackoverflow_0008507509_input_notimplementedexception_numpy_python_python_2.x.txt |
Q:
pyparsing example
It is my first attempt to use pyparsing and I'd like to ask
how to filter this sample line:
survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''
to get output like: 1,52.125133215643,21.031048525561,116.898812
In general I have problem with understanding pyparsing logic so any... | pyparsing example | It is my first attempt to use pyparsing and I'd like to ask
how to filter this sample line:
survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''
to get output like: 1,52.125133215643,21.031048525561,116.898812
In general I have problem with understanding pyparsing logic so any help with this
example... | [
"You could start with something like this:\nfrom pyparsing import *\n\nsurvey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''\n\nnumber = Word(nums+'.').setParseAction(lambda t: float(t[0]))\nseparator = Suppress(',')\nlatitude = Suppress('LA') + number\nlongitude = Suppress('LN') + number\nelevati... | [
27
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0008507694_pyparsing_python.txt |
Q:
using data from a txt file in python
I'm learning python and now I'm having some problems with reading and analyzing txt files. I want to open in python a .txt file that contains many lines and in each line I have one fruit and it's price.
I would like to know how to make python recognize their prices as a number ... | using data from a txt file in python | I'm learning python and now I'm having some problems with reading and analyzing txt files. I want to open in python a .txt file that contains many lines and in each line I have one fruit and it's price.
I would like to know how to make python recognize their prices as a number (since it recognizes as a string when I us... | [
"If the name and the price are separated by a comma:\nwith open('data.txt') as f:\n for line in f:\n name, price = line.rstrip().split(',')\n price = float(price)\n print name, price\n\n",
"Assuming your values are space-separated, you can read in your file into a list of tuples using:\n# generator to r... | [
1,
1,
0
] | [] | [] | [
"python",
"string",
"text_files"
] | stackoverflow_0008508167_python_string_text_files.txt |
Q:
python greenlet segmentation fault
I use ubuntu 11.10 with Python 2.7.2
I try to use eventlet or Concurrence, but simple examples fails with "segmentation fault"
I read this is a greenlet problem, but don't know how to fix this? plese help.
A:
Try greenlet from https://bitbucket.org/snaury/greenlet
Update: The f... | python greenlet segmentation fault | I use ubuntu 11.10 with Python 2.7.2
I try to use eventlet or Concurrence, but simple examples fails with "segmentation fault"
I read this is a greenlet problem, but don't know how to fix this? plese help.
| [
"Try greenlet from https://bitbucket.org/snaury/greenlet\nUpdate: The fixes from the above repo are included in the new 0.3.2 release of greenlet: http://pypi.python.org/pypi/greenlet\n"
] | [
2
] | [] | [] | [
"concurrency",
"eventlet",
"python",
"ubuntu"
] | stackoverflow_0008502101_concurrency_eventlet_python_ubuntu.txt |
Q:
python processes increases memory usage day by day
Scenario:
I have a python process which runs continuously ( until we stop manually - infinitely ) and collects data by reading certain system files every 1 minute. When it is started it occupies around 25 MB. But day by day the amount of memory occupied is increas... | python processes increases memory usage day by day | Scenario:
I have a python process which runs continuously ( until we stop manually - infinitely ) and collects data by reading certain system files every 1 minute. When it is started it occupies around 25 MB. But day by day the amount of memory occupied is increasing and after 15 days, it is more than 500 MB.
I am a p... | [
"use Dowser to help track memory leaks. It uses CherryPy as a web server and even if you're not developing a Web application, it can provide a view of memory allocations to you from your browser.\nSee also this post, which you may find of interest. With Dowser, you should be able to see what unexpected objects are ... | [
3,
1
] | [] | [] | [
"memory",
"memory_leaks",
"performance",
"python"
] | stackoverflow_0005069494_memory_memory_leaks_performance_python.txt |
Q:
How to perform an action when a process has finished, whilst there are multiple processes are running
I'm making a scan server for my company, which will be used to launch scans from tools such as nessus, nmap, nikto etc. I've written the pages in php, so once the scan is launched it backgrounds the process and re... | How to perform an action when a process has finished, whilst there are multiple processes are running | I'm making a scan server for my company, which will be used to launch scans from tools such as nessus, nmap, nikto etc. I've written the pages in php, so once the scan is launched it backgrounds the process and returns the PID. Part of the design spec is that once a scan has finished, the results are then emailed to th... | [
"When I face this kind of problem, I usually do a Python daemon that does the whole job, and have the PHP just sending messages to this Python daemon. These messages can be something very simple, like a bunch of files in a directory that is constantly checked, or registers in database.\nHow good this implmeentation... | [
2,
2
] | [] | [] | [
"php",
"process",
"python"
] | stackoverflow_0008508457_php_process_python.txt |
Q:
requestloop(loopCondition) doesn't release even after loopCondition is False
I have some issues with the requestLoop methode of the Pyro4.Daemon object.
What I want is to call remotely a "stop()" method for releasing the requestLoop function and shutdown my daemon.
This small exemple doesn't work
SERVER
#!/usr/bin... | requestloop(loopCondition) doesn't release even after loopCondition is False | I have some issues with the requestLoop methode of the Pyro4.Daemon object.
What I want is to call remotely a "stop()" method for releasing the requestLoop function and shutdown my daemon.
This small exemple doesn't work
SERVER
#!/usr/bin/python
# -*- coding: utf-8 -*-
from daemon import Pyro4
class Audit(object):
... | [
"If you look at the examples/callback/client.py in the sources you'll see the following comment:\n# We need to set either a socket communication timeout,\n# or use the select based server. Otherwise the daemon requestLoop\n# will block indefinitely and is never able to evaluate the loopCondition.\nPyro4.config.COMM... | [
4
] | [] | [] | [
"pyro",
"python"
] | stackoverflow_0008508112_pyro_python.txt |
Q:
Can I use tornado web server on windows without pycurl installed?
I am looking on how to use Tornado on Windows. From my recent searches I saw that to use the full capabilities of Tornado, one needs to install pycurl which is not supported on windows since python 2.6.
Does anyone know which can be the impacts if T... | Can I use tornado web server on windows without pycurl installed? | I am looking on how to use Tornado on Windows. From my recent searches I saw that to use the full capabilities of Tornado, one needs to install pycurl which is not supported on windows since python 2.6.
Does anyone know which can be the impacts if Tornado is installed without pycurl and which functionality will be lost... | [
"tornado provides a couple of asynchronous HTTP clients, one of which is pure python, and another that uses pycurl. In recent versions of tornado (2.0+) the pure python version is the default, and pycurl is only necessary if you explicitly try to use the CurlAsyncHTTPClient. \n(The curl client is supposed to be fas... | [
2
] | [] | [] | [
"pycurl",
"python",
"tornado",
"windows"
] | stackoverflow_0008504632_pycurl_python_tornado_windows.txt |
Q:
WxPython - building a directory tree based on file availability
I do atomistic modelling, and use Python to analyze simulation results. To simplify work with a whole bunch of Python scripts used for different tasks, I decided to write simple GUI to run scripts from it.
I have a (rather complex) directory structur... | WxPython - building a directory tree based on file availability | I do atomistic modelling, and use Python to analyze simulation results. To simplify work with a whole bunch of Python scripts used for different tasks, I decided to write simple GUI to run scripts from it.
I have a (rather complex) directory structure beginning from some root (say ~/calc), and I want to populate wx.Tr... | [
"First of all the hacks:\n\nTo get the path seperator for whatever os your using you can use os.sep. \nUse str.endswith() and use the fact that in Python the empty list [] evaluates to False:\nif [ file for file in filenames if file.endswith('.EXT') ]:\n\nIn terms of getting them all nicely nested you're best off ... | [
2
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0008504493_python_user_interface_wxpython.txt |
Q:
Bit masking in Python
I have a byte (from some other vendor) where the potential bit masks are as follows:
value1 = 0x01
value2 = 0x02
value3 = 0x03
value4 = 0x04
value5 = 0x05
value6 = 0x06
value7 = 0x40
value8 = 0x80
I can count on ONE of value1 through value6 being present. And then value7 may or may not be se... | Bit masking in Python | I have a byte (from some other vendor) where the potential bit masks are as follows:
value1 = 0x01
value2 = 0x02
value3 = 0x03
value4 = 0x04
value5 = 0x05
value6 = 0x06
value7 = 0x40
value8 = 0x80
I can count on ONE of value1 through value6 being present. And then value7 may or may not be set. value8 may or may not b... | [
"Most of your value* constants aren't actually bit masks, only value7 and value8 are. I'd define another bit mask to extract the lower bits, so I would have three bit masks in total:\nmask0 = 0x07\nmask1 = 0x40\nmask2 = 0x80\n\nNow your function becomes\ndef parse_byte(byte):\n return byte & mask2, byte & mask1... | [
18,
10,
4,
3
] | [] | [] | [
"bit_manipulation",
"python"
] | stackoverflow_0008508799_bit_manipulation_python.txt |
Q:
Python unit testing specifics
I have a fairly complex system that I want to test using python. My test code will interact with the system using a Python module I've already written. There are a few things however, that I haven't been able to figure out, regarding the testing framework. I haven't selected one ye... | Python unit testing specifics | I have a fairly complex system that I want to test using python. My test code will interact with the system using a Python module I've already written. There are a few things however, that I haven't been able to figure out, regarding the testing framework. I haven't selected one yet, but obviously I feel directed to... | [
"As for #2, it seems that setUpClass() and tearDownClass() are designed for this. The documentation even shows an example of using it to createExpensiveConnectionObject().\n",
"I use tox to run my tests across multiple configurations. Some of my unittests skip certain tests if an optional module isn't there, whic... | [
1,
1
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0008507709_python_testing.txt |
Q:
looking for SQL insert syntax for informix via python informixdb
Cant find the correct syntax for INSERT query with python informixdb
python 2.6.6
python INFORMIXDB version 2.5
driver name : IBM Informix-ESQL
driver version : 3.50.FC8
on debian squeeze
here's the doc - http://informixdb.sourceforge.net/manual.ht... | looking for SQL insert syntax for informix via python informixdb | Cant find the correct syntax for INSERT query with python informixdb
python 2.6.6
python INFORMIXDB version 2.5
driver name : IBM Informix-ESQL
driver version : 3.50.FC8
on debian squeeze
here's the doc - http://informixdb.sourceforge.net/manual.html#binding-parameters
>>> cursor.execute('INSERT INTO names VALUES(:fi... | [
"You should list the columns explicitely that you want to populate:\nINSERT INTO names (firstname, lastname, age) VALUES (:first,:last,:age)\nApperently your table has more columns than you supply, or they are in a different order.\nNot stating the columns for an INSERT statement is a bad programming habit, that yo... | [
2,
0
] | [] | [] | [
"informix",
"python",
"sql"
] | stackoverflow_0008507994_informix_python_sql.txt |
Q:
Is it possible to stream a windows (7 / vista / xp) webcams via Gstreamer
I very new to the world of gstreamer. I was wondering, if it's possible to stream windows webcam via gstreamer? The only package i have seen so far is for linux. v4l2 (video for linux).
Is there also a package for windows webcams? what is th... | Is it possible to stream a windows (7 / vista / xp) webcams via Gstreamer | I very new to the world of gstreamer. I was wondering, if it's possible to stream windows webcam via gstreamer? The only package i have seen so far is for linux. v4l2 (video for linux).
Is there also a package for windows webcams? what is the correct python syntax?
DJ
| [
"Install on windows from http://code.google.com/p/ossbuild/\nthen use below command \ngst-launch ksvideosrc device-index=0 ! ffmpegcolorspace ! autovideosink\n\n",
"For Windows streaming, I would suggest VLC.\n"
] | [
5,
1
] | [] | [] | [
"gstreamer",
"python",
"streaming",
"windows"
] | stackoverflow_0003659382_gstreamer_python_streaming_windows.txt |
Q:
Matching and merging text files programmatically
I would like to merge an EDL (edit decision list) text file with another text file that contains subtitles. The EDL is generated from a video editing program, Final Cut Pro, while the text file is just regular text. While this particular request is for a specific en... | Matching and merging text files programmatically | I would like to merge an EDL (edit decision list) text file with another text file that contains subtitles. The EDL is generated from a video editing program, Final Cut Pro, while the text file is just regular text. While this particular request is for a specific end-use, I would like to learn the general method one ca... | [
"Roughly this should be the plan. \n\nRead the files\nMake parser for each type of files\nStore the data in useful data structures/objects\nOutput in appropriate format\n\nBreak up each step until, it is just a matter of writing down in code. Test at each step.\n",
"This is a 1 to 1 matching from 1 file to the ot... | [
2,
0
] | [] | [] | [
"merging_data",
"python",
"text_parsing"
] | stackoverflow_0004776440_merging_data_python_text_parsing.txt |
Q:
filling up a list python
THanks for looking into my post. I guess I have a probably a pretty simple doubt by this community standards.. but pardon me if it is too simple. I am trying to learn python.
So anyways.. I have an object which can have five attributes.
So lets say when i am initializing the class its like... | filling up a list python | THanks for looking into my post. I guess I have a probably a pretty simple doubt by this community standards.. but pardon me if it is too simple. I am trying to learn python.
So anyways.. I have an object which can have five attributes.
So lets say when i am initializing the class its like this
class Foo:
def __ini... | [
"def getFeatures(self):\n return [field for field in (self._argA, ..., self._argE) if field is not None]\n\n",
"Keep a dictionary of feature name to boolean enabled/disabled. That's much better than having all these variables floating around.\ndef __init__(self, **kwargs):\n self.features = kwargs\n\ndef ge... | [
6,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0008509635_python.txt |
Q:
How to get id of lastest uploaded video on youtube channel
How can I get the id of latest uploaded video in a specific youtube Channel using Python?
A:
You can request JSON and parse it. The following code gives you the first (most recent) result and stores it in first.
import urllib, json
author = 'Google'
in... | How to get id of lastest uploaded video on youtube channel | How can I get the id of latest uploaded video in a specific youtube Channel using Python?
| [
"You can request JSON and parse it. The following code gives you the first (most recent) result and stores it in first.\nimport urllib, json\n\nauthor = 'Google'\ninp = urllib.urlopen(r'http://gdata.youtube.com/feeds/api/videos?max-results=1&alt=json&orderby=published&author=' + author)\nresp = json.load(inp)\ninp... | [
2
] | [] | [] | [
"python",
"youtube",
"youtube_api"
] | stackoverflow_0008509332_python_youtube_youtube_api.txt |
Q:
Python Class Variable Initialization
I'd like to store some information about a class as class (static) variables. However, I can't figure out how these things get initialized. Here is a basic, dumb example:
class A(object):
clsVar = 'a'
@classmethod
def clsMeth(cls):
print 'changing clsVar'
... | Python Class Variable Initialization | I'd like to store some information about a class as class (static) variables. However, I can't figure out how these things get initialized. Here is a basic, dumb example:
class A(object):
clsVar = 'a'
@classmethod
def clsMeth(cls):
print 'changing clsVar'
cls.clsVar = 'b'
A.clsMeth()
# p... | [
"The call to A.clsMeth() in the definition of A will not run, as A does not exist at that point:\n>>> class A(object):\n... clsVar = 'a'\n... @classmethod\n... def clsMeth(cls):\n... print 'changing clsVar'\n... cls.clsVar = 'b'\n... A.clsMeth()\n... \nTraceback (most recent call las... | [
5
] | [] | [] | [
"class_variables",
"initialization",
"python"
] | stackoverflow_0008509787_class_variables_initialization_python.txt |
Q:
CURL and urlopen giving conflicting results
So I'm retrieving some JSON data from a website and using the standard urlopen() from urllib2:
Code:
url = 'http://api.nytimes.com/svc/politics/v3/us/legislative/congress/senate/votes/2011-12-14/2011-12-14.json?api-key=%s' % (api_key,)
print urlopen(url).read()
Result... | CURL and urlopen giving conflicting results | So I'm retrieving some JSON data from a website and using the standard urlopen() from urllib2:
Code:
url = 'http://api.nytimes.com/svc/politics/v3/us/legislative/congress/senate/votes/2011-12-14/2011-12-14.json?api-key=%s' % (api_key,)
print urlopen(url).read()
Result: ... | [
"It looks like you have to have 'Accept-Encoding' header set in your request.\nJust in case, you can set like this:\nrequest = urllib2.Request(your_url)\nrequest.add_header('Accept-Encoding',whatever_in_this_case)\nopener = urllib2.build_opener()\nprint opener.open(request).read()\n\n"
] | [
1
] | [] | [] | [
"curl",
"python",
"urllib2",
"urlopen"
] | stackoverflow_0008509714_curl_python_urllib2_urlopen.txt |
Q:
python asynchat: how to store information on individual connections, and how to know when a client disconnects
For fun, I'm writing a minimal IRC server with asynchat. I'm trying to clear up a few fundamentals (my specific questions follow the code). I've decided not to use anything in Twisted just so I can implem... | python asynchat: how to store information on individual connections, and how to know when a client disconnects | For fun, I'm writing a minimal IRC server with asynchat. I'm trying to clear up a few fundamentals (my specific questions follow the code). I've decided not to use anything in Twisted just so I can implement a little more myself. First, the code I have:
import asyncore,asynchat
import socket
class Connection(asynchat.... | [
"to handle client side closed connections check the handle_error method, does your client issue a clean close connection?\nhandle_error() :Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.\nhope it helps.\n"
] | [
0
] | [] | [] | [
"asyncore",
"irc",
"python"
] | stackoverflow_0006818360_asyncore_irc_python.txt |
Q:
Getting started with pylons on a VPS with Apache
I currently have Apache setup on my VPS and I'm wondering what would be the best way to handle Pylons development.
I have the directory structure with public_html in my home directory which includes separate website directories to which I map the IP to the DNS prov... | Getting started with pylons on a VPS with Apache | I currently have Apache setup on my VPS and I'm wondering what would be the best way to handle Pylons development.
I have the directory structure with public_html in my home directory which includes separate website directories to which I map the IP to the DNS provided by my name registrar.
Is there a way to get past... | [
"It's usually more practical to develop first your application locally using pserve, the builtin HTTP server in Pyramid (it used to be paster before Pyramid 1.3 but pserve behaves similarly). This HTTP server comes quite handy when developing for debugging, but you don't usually expose your web application publicly... | [
1
] | [] | [] | [
"apache",
"pylons",
"pyramid",
"python"
] | stackoverflow_0008263423_apache_pylons_pyramid_python.txt |
Q:
Web service that returns any http status code you specify for API testing purposes?
A few months ago I remember reading about a useful little web service somebody put together for API testing purposes. Basically, you just did a call like this, e.g.:
http://www.someAPItestingtool.com/status/405
And the server woul... | Web service that returns any http status code you specify for API testing purposes? | A few months ago I remember reading about a useful little web service somebody put together for API testing purposes. Basically, you just did a call like this, e.g.:
http://www.someAPItestingtool.com/status/405
And the server would respond with a 405 / Method Not Allowed.
It was basically just a handy little utility y... | [
"Over a year later, I at last re-stumbled upon the service I was thinking about:\nhttp://httpstat.us/\n",
"I'm still quite positive someone put something like this together, but it was quicker for me to just whip up something using Flask:\nfrom flask import Flask, make_response\napp = Flask(__name__)\n\n@app.rout... | [
6,
5
] | [] | [] | [
"api",
"python",
"testing",
"web_services"
] | stackoverflow_0004391020_api_python_testing_web_services.txt |
Q:
How do you create an Nx1 dimensional Array where each element is a function of another array?
import math as m
import numpy as np
i = np.mgrid[1:21:1]
N = [1,1,0]
def G1(i):
H1 = i**2
H2 = 2*H1
return H2
def G2(i):
H1 = i**3
H2 = 3*H1
return H2
def G3(i):
H1 = i**4
H2 = 4*H1
ret... | How do you create an Nx1 dimensional Array where each element is a function of another array? | import math as m
import numpy as np
i = np.mgrid[1:21:1]
N = [1,1,0]
def G1(i):
H1 = i**2
H2 = 2*H1
return H2
def G2(i):
H1 = i**3
H2 = 3*H1
return H2
def G3(i):
H1 = i**4
H2 = 4*H1
return H2
Gc = []
for a in xrange(1,21):
K1 = [G1(i)[i[a]], G2(i)[i[a]], G3(i)[i[a]]]
K2 = np.... | [
"You question is very ambiguous. Without going into the details of understanding and proposing a solution to what you exactly wan't, I will try to resolve the problems I can see in your code\n\nK3 is not a list but a scalar. You cannot pass it to a list through the extend method. You would probably want something l... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008510905_python.txt |
Q:
Python: 2.6:Trying to build a statement like exec('if' + varname + '< 1.0:')
My goal here is to have the same if statement in a for loop were the variable name changes
Those statements are in a function in a different file: the appropriate Import scheme
as been set.
Examples:
for i in range(0,10):
myvar = ''... | Python: 2.6:Trying to build a statement like exec('if' + varname + '< 1.0:') | My goal here is to have the same if statement in a for loop were the variable name changes
Those statements are in a function in a different file: the appropriate Import scheme
as been set.
Examples:
for i in range(0,10):
myvar = ''
myvar = myvar + str(i)
exec('if' + myvar + '< 0:')
`do something`
It say... | [
"You are passing the string \"if 0 < 0:\" to the exec() function. This is not a syntactically valid construct -- it's missing the controlled suite. You might consider instead:\nif eval(myvar) < 0:\n do_something()\n\nAs a more general point, however, dynamic evaluation of variable names is almost invariably the ... | [
3,
1,
0
] | [] | [] | [
"exec",
"if_statement",
"python"
] | stackoverflow_0008511299_exec_if_statement_python.txt |
Q:
Filter a User list using a UserProfile field in Django Admin
I'm trying to filter the User list in Django using a UserProfile Field... I need to implement a queue system where new users are put in a queue until an Admin approves them.
I simply added a is_in_queue boolean field to my UserProfile model... However, w... | Filter a User list using a UserProfile field in Django Admin | I'm trying to filter the User list in Django using a UserProfile Field... I need to implement a queue system where new users are put in a queue until an Admin approves them.
I simply added a is_in_queue boolean field to my UserProfile model... However, when displaying the user list in my Admin area, I realized that you... | [
"Django 1.3 fixed that - list_filter now allows to span relations:\nhttps://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter\n",
"You may want to take a look in to using a custom manager for the admin_objects of your model.\nclass UserAdminManager(models.AdminManager):\... | [
3,
1,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0001609241_django_django_admin_python.txt |
Q:
Python - search for string, copy until end of doc
I am using python to open EML files one at a time, process them then move them to another folder. EML file contains an email message including the headers.
The first 35-40 lines of the EML are header info, followed by the actual email message. Since the amount of ... | Python - search for string, copy until end of doc | I am using python to open EML files one at a time, process them then move them to another folder. EML file contains an email message including the headers.
The first 35-40 lines of the EML are header info, followed by the actual email message. Since the amount of lines of the header changes, I cant just convert my EML... | [
"You can probably avoid regex. How about:\nmsg = data.split('X-OriginalArrivalTime', 1)[1].split('\\n', 1)[1]\n\n",
"The re module is not very good at counting lines. What's more, you probably don't need it to check for the contents of the start of a line. The following function takes the filename of the EML file... | [
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008496673_python_regex.txt |
Q:
ggplot2 no plot becase ggsave no save
I have a python script using the pyper library (pipes to R), and I am trying to get some output out of ggplot2. I have tried both the 'ggsave' method and the 'device(...); dev.off()' methods and nothing is output.
I have to use pyper because of using 64 bits everywere (python... | ggplot2 no plot becase ggsave no save | I have a python script using the pyper library (pipes to R), and I am trying to get some output out of ggplot2. I have tried both the 'ggsave' method and the 'device(...); dev.off()' methods and nothing is output.
I have to use pyper because of using 64 bits everywere (python and R), so rpy[2] isn't an option for me.
... | [
"So this all turns out to be an issue with libraries and environment variables. Some of the loaded libraries, like ggplot2, don't load all dependencies, like the digest library. This error only occurs on the \"print(p)\" portion of the code.\nIn addition, there are differences in the x64 library locations that ne... | [
2
] | [] | [] | [
"ggplot2",
"python",
"r",
"windows_7_x64"
] | stackoverflow_0008497428_ggplot2_python_r_windows_7_x64.txt |
Q:
Discrepancy Between Matlab and Numpy+Python FFT2?
So I was doing some homework on diffraction in Python with Numpy. My results simply wouldn't turn out how they should have, and I was confused.
The code I used to generate the FFTs is as follows:
Python:
aperaturearray = np.array(im) # Turn image into numpy array
... | Discrepancy Between Matlab and Numpy+Python FFT2? | So I was doing some homework on diffraction in Python with Numpy. My results simply wouldn't turn out how they should have, and I was confused.
The code I used to generate the FFTs is as follows:
Python:
aperaturearray = np.array(im) # Turn image into numpy array
Ta = np.fft.fftshift(np.fft.fft2(aperaturearray))
### I... | [
"To add to mor22's answer:\nIn Matlab you can use fftshift to move the lowest frequencies to the center. It essentialy just swaps the upper-left with the lower-right quadrant (and upper-right with lower-left).\n",
"To begin with, in Matlab, the values returned from fft2 are complex. I'm not sure how imwrite will... | [
2,
1
] | [] | [] | [
"fft",
"matlab",
"numpy",
"python"
] | stackoverflow_0005415113_fft_matlab_numpy_python.txt |
Q:
Sorting a hand of cards accoring to rank and suit in python
I'm tying to make a card game and at the moment I'm working on the beginning of it. What I am confused on is sorting the cards in a hand by their rank then suit and pretty much how to cut down on repetition. At the moment I could probably make a for loop ... | Sorting a hand of cards accoring to rank and suit in python | I'm tying to make a card game and at the moment I'm working on the beginning of it. What I am confused on is sorting the cards in a hand by their rank then suit and pretty much how to cut down on repetition. At the moment I could probably make a for loop for organizing the cards and then have 52 different if for each p... | [
"I'd probably simplify this a bit:\nfrom random import shuffle\n\nclass Hand(list):\n pass\n\nclass Deck(object):\n\n rank = '23456789TJQKA'\n suit = 'CSHD'\n\n def deal(self, n):\n deck = [r+s for r in Deck.rank for s in Deck.suit]\n shuffle(deck)\n return [Hand(sorted(deck[i::n], key=Deck.cmpkey)) fo... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0008511745_python.txt |
Q:
How to capture all http requests of apache by mod_wsgi?
I need to capture all request of apache web server with mod_wsgi. Checking attacks of GET request.
A:
You cant use mod_wsgi to capture any request to Apache. All you could do it use a WSGI middleware to capture details for requests going into a specific WS... | How to capture all http requests of apache by mod_wsgi? | I need to capture all request of apache web server with mod_wsgi. Checking attacks of GET request.
| [
"You cant use mod_wsgi to capture any request to Apache. All you could do it use a WSGI middleware to capture details for requests going into a specific WSGI application. See:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Tracking_Request_and_Response\nBTW, your requirement is vague as to what exactly ... | [
0
] | [] | [] | [
"apache",
"mod_wsgi",
"php",
"python",
"xss"
] | stackoverflow_0008509269_apache_mod_wsgi_php_python_xss.txt |
Q:
Setting values in nested dictionary
I have nested dict like:
tdict = {folder': {'file0.txt': 222, 'subfolder': {'file1.txt': 333}}, 'file00.txt': 111}
and it can go deeper
How to iterate throw existing dict and add for ex. new item 'file2', described by list:
path_list = ['folder', 'subfolder', 'file2']
A:
This... | Setting values in nested dictionary | I have nested dict like:
tdict = {folder': {'file0.txt': 222, 'subfolder': {'file1.txt': 333}}, 'file00.txt': 111}
and it can go deeper
How to iterate throw existing dict and add for ex. new item 'file2', described by list:
path_list = ['folder', 'subfolder', 'file2']
| [
"This function will add a file if value isn't None, but will add a new directory otherwise:\ndef add_path(parent, path, value=None):\n end = len(path) - 1\n for index, component in enumerate(path):\n if index < end or value is None:\n parent = parent.setdefault(component, {})\n else:\... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008511537_dictionary_python.txt |
Q:
Python style: more concise way to rename a variable while checking it is not null
In Python, I often find myself writing the following slightly unwieldy bit of code:
if data['name'] is not None:
name = data['name']
# do stuff with 'name' over many lines
# hence bothering to rename it at all!
$('#my... | Python style: more concise way to rename a variable while checking it is not null | In Python, I often find myself writing the following slightly unwieldy bit of code:
if data['name'] is not None:
name = data['name']
# do stuff with 'name' over many lines
# hence bothering to rename it at all!
$('#myname').text(name)...
Can the first two lines be collapsed into one, perhaps all inside... | [
"in some cases e.g. string names you can simply do something like this\nname = data['name'] or ''\n\nA generic way is it to use if-else shorthand e.g.\nname = data['name'] if data['name'] is not None else ''\n\nor if you prefer (i prefer above one as main assignment is at start and exceptional case at end)\nname = ... | [
3,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0008510245_python.txt |
Q:
Python module for the image processing
Possible Duplicate:
Image Processing, In Python?
There is a Python module for image processing?
I would like to analyze, modify and create other images.
A:
check the Image Module
http://effbot.org/imagingbook/image.htm
next time, try to google it :) unless you have some s... | Python module for the image processing |
Possible Duplicate:
Image Processing, In Python?
There is a Python module for image processing?
I would like to analyze, modify and create other images.
| [
"check the Image Module\nhttp://effbot.org/imagingbook/image.htm\nnext time, try to google it :) unless you have some special requirement\n",
"Try the Python Image Library:\nhttp://www.pythonware.com/library/\nSome of it is a bit abstract (like the methods for manipulating image statistics) but in general it supp... | [
6,
0
] | [] | [] | [
"image",
"python"
] | stackoverflow_0008512582_image_python.txt |
Q:
Combining Code from two programs in Python
My question is kinda complicated as I run it through my head but I will try to explain it as best I can. I have 2 python codes, one that I created with Python for a Mastermind game and then the other in Pygame for a Mastermind board to play it on. My question is simply th... | Combining Code from two programs in Python | My question is kinda complicated as I run it through my head but I will try to explain it as best I can. I have 2 python codes, one that I created with Python for a Mastermind game and then the other in Pygame for a Mastermind board to play it on. My question is simply this: How can I combine both of these codes into 1... | [
"As I'm sure you know, you can't just put it all in one file and have it run. You need to encapsulate the Mastermind game so you can run/update it from the pygame loop. It'd be cleaner if you keep the Mastermind game logic in a separate file and just import it, but it's not required.\nHere's some semi-psuedocode:... | [
1,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008511967_pygame_python.txt |
Q:
Favorite Django Tips & Features?
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
Please, include only one tip per answer.
Add Django version requirements if there are any.
A:
I'm just going to start w... | Favorite Django Tips & Features? | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
Please, include only one tip per answer.
Add Django version requirements if there are any.
| [
"I'm just going to start with a tip from myself :)\nUse os.path.dirname() in settings.py to avoid hardcoded dirnames.\nDon't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Dja... | [
221,
128,
119,
101,
96,
87,
81,
79,
66,
58,
46,
43,
41,
40,
37,
37,
36,
35,
34,
27,
21,
20,
19,
19,
19,
18,
16,
16,
14,
14,
13,
12,
12,
11,
11,
9,
7,
7,
6,
5,
5,
5,
5,
4,
4,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"hidden_features",
"python"
] | stackoverflow_0000550632_django_hidden_features_python.txt |
Q:
Is there a better way to delete files that are a month old in python?
I have built a script that generates files daily and names them by the date that they are generated. However, I then need to delete these files after 1 month, and have found it to be a bit confusing. I believe that the following will work, but... | Is there a better way to delete files that are a month old in python? | I have built a script that generates files daily and names them by the date that they are generated. However, I then need to delete these files after 1 month, and have found it to be a bit confusing. I believe that the following will work, but I would like to know if Python has a built in feature that allows for this... | [
"Take a look at Python's datetime module, it has some classes that should simplify this a lot. You should be able to create a datetime.datetime object from your file name using datetime.datetime.strptime(), and another for the current time using datetime.datetime.now(). You can then subtract one from the other to... | [
5,
4
] | [] | [] | [
"date",
"python"
] | stackoverflow_0008511950_date_python.txt |
Q:
How to prevent a deadlock when using named pipes?
I have a capture process which writes raw video data and audio data to files. Something like this will capture 100 frames of data.
./capture -n 100 -f video_file -a audio_file
Giving me a 768000 bytes audio_file and a 414720000 bytes video_file. These seems to ... | How to prevent a deadlock when using named pipes? | I have a capture process which writes raw video data and audio data to files. Something like this will capture 100 frames of data.
./capture -n 100 -f video_file -a audio_file
Giving me a 768000 bytes audio_file and a 414720000 bytes video_file. These seems to add up as expected:
414720000 == 1920x1080 (pixels/fra... | [
"In Linux, the pipe buffer is limited to 65k, it's possible that you are ending up with a deadlock where capture won't write more audio until it can write more video, and ffmpeg won't read more video until it gets more audio. \n",
"In the end, I couldn't get ffmpeg to read without blocking from the FIFOs, so the... | [
1,
1
] | [] | [] | [
"blocking",
"named_pipes",
"popen",
"python",
"streaming"
] | stackoverflow_0007976053_blocking_named_pipes_popen_python_streaming.txt |
Q:
Generating RSS feed under Google App Engine
I want to provide rss feed under google app engine/python.
I've tried to use usual request handler and generate xml response. When I access the feed url directly, I can see the feed correctly, however, when I'm trying to subscribe to the feed in google reader, it says th... | Generating RSS feed under Google App Engine | I want to provide rss feed under google app engine/python.
I've tried to use usual request handler and generate xml response. When I access the feed url directly, I can see the feed correctly, however, when I'm trying to subscribe to the feed in google reader, it says that
'The feed being requested cannot be found.'
... | [
"There're 2 solutions I suggest:\n\nGAE-REST you can just add to your project and configure and it will make RSS for you but the project is old and no longer maintained.\nDo like I do, use a template to write a list to and like this I could succeed generating RSS (GeoRSS) that can be read via google reader where te... | [
6,
2,
2
] | [] | [] | [
"google_app_engine",
"python",
"rss"
] | stackoverflow_0008507301_google_app_engine_python_rss.txt |
Q:
Best approach to filter a large dataset depending on the datastore
I'm currently implementing a web service providing the social features of a game. One of this game feature is the ability to manage a friends list. The friends the user can add depends on the contacts he's having on an external social network of hi... | Best approach to filter a large dataset depending on the datastore | I'm currently implementing a web service providing the social features of a game. One of this game feature is the ability to manage a friends list. The friends the user can add depends on the contacts he's having on an external social network of his choice (currently Facebook or Twitter).
The current behavior of the sy... | [
"I assume it's so slow because you're doing a query for each user you're looking up. You can avoid the need to do this with good use of key names.\nFor each user in your database, insert entities with their key name set to the unique identifier for the social network. These can be the same entities you're already u... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008508346_google_app_engine_python.txt |
Q:
asyncore python hangs
I try to do simple async http client with asyncore:
This code works fine and output is (fast enought):
www.gmail.com : recv http code: 301
www.yandex.ru : recv http code: 200
www.python.org : recv http code: 200
www.google.ru : recv http code: 200
www.gravatar.com : recv http co... | asyncore python hangs | I try to do simple async http client with asyncore:
This code works fine and output is (fast enought):
www.gmail.com : recv http code: 301
www.yandex.ru : recv http code: 200
www.python.org : recv http code: 200
www.google.ru : recv http code: 200
www.gravatar.com : recv http code: 302
www.com.com : re... | [
"You invoke a blocking name-resolution when you do self.connect((host, port)). Combined with your local DNS configuration, this is why your program has a long delay at startup.\nAn alternative to asyncore and figuring out how to do non-blocking name resolution yourself, you might think about using Twisted. Twiste... | [
4
] | [] | [] | [
"asyncore",
"python"
] | stackoverflow_0008504518_asyncore_python.txt |
Q:
Memory reduction
I am not a programmer but am facing a programming problem. I need to reduce the memory consumption of a Python code. One option is to reduce the variable precision. In this regard:
Identify Floating points (as I think the data types are assigned on the fly)?
Python uses 64-bit or 32-bit floating ... | Memory reduction | I am not a programmer but am facing a programming problem. I need to reduce the memory consumption of a Python code. One option is to reduce the variable precision. In this regard:
Identify Floating points (as I think the data types are assigned on the fly)?
Python uses 64-bit or 32-bit floating points?
Any function t... | [
"If you are already using numpy you can set the dtype field to the type that you want (documentation). You'll get a little more flexibility there for typing, but in general you aren't going to get a lot of control over variable precision in Python. You might also have some luck if you want to go through the struct... | [
1,
0
] | [] | [] | [
"floating_point",
"memory",
"python"
] | stackoverflow_0008511166_floating_point_memory_python.txt |
Q:
Comet connection timing out
I have a simple comet server in written in Twisted. It prints out time stamps. I also have a small static webserver running on the same port. The javascript on the page served tries to update the page by appending the timestamps from the comet server.
But nothing is displayed from the c... | Comet connection timing out | I have a simple comet server in written in Twisted. It prints out time stamps. I also have a small static webserver running on the same port. The javascript on the page served tries to update the page by appending the timestamps from the comet server.
But nothing is displayed from the comet server. Using the developer ... | [
"You can't rely on getting response data in JavaScript until the response is fully delivered to the client. This behavior varies from browser to browser, so you will see it work as you want sometimes, and not work at all other times.\nYou also can't rely on connections remaining open indefinitely, largely due to H... | [
0
] | [] | [] | [
"comet",
"javascript",
"jquery",
"python",
"twisted"
] | stackoverflow_0008511678_comet_javascript_jquery_python_twisted.txt |
Q:
Multiple mismatches in DNA search sequence regex
I have written this barbaric script to create permutations of a string of characters that contain n (up to n=4) $'s in all possible combinations of positions within the string. I will eventually .replace('$','(\\w)') to use for mismatches in a dna search sequence. ... | Multiple mismatches in DNA search sequence regex | I have written this barbaric script to create permutations of a string of characters that contain n (up to n=4) $'s in all possible combinations of positions within the string. I will eventually .replace('$','(\\w)') to use for mismatches in a dna search sequence. Because of the way I wrote the script, some of the pe... | [
"We can do away with questions 2 and 3 by answering question 1, but understanding question 3 is important so I'll do that first and then show how you can avoid it entirely:\nQuestion 3\nAs to question 3, it's because when you loop over a list in python and make changes to it within the loop, the list that you loop ... | [
3
] | [] | [] | [
"biopython",
"dna_sequence",
"python",
"regex"
] | stackoverflow_0008509259_biopython_dna_sequence_python_regex.txt |
Q:
How to search and replace text from one file to another using Python?
I have a file file1.txt :
I Show more flower you can see by link
All is Beautyfull.You Can View Here !
Link View :
http://lincoln.com/view/12432134/flower1.jpg
http://lincoln.com/view/34645645/flower3456.jpg
http://lincoln.com/view/7563... | How to search and replace text from one file to another using Python? | I have a file file1.txt :
I Show more flower you can see by link
All is Beautyfull.You Can View Here !
Link View :
http://lincoln.com/view/12432134/flower1.jpg
http://lincoln.com/view/34645645/flower3456.jpg
http://lincoln.com/view/75634534/flower56.jpg
http://lincoln.com/view/86764454/flower2.jpg
and ano... | [
"Try this\nimport urlparse\nimport os\n\ndef file_merge(file1name,file2name):\n\n file1contents = list()\n file2contents = list()\n\n file1 = open(file1name, 'U')\n file1contents = file1.readlines()\n file1.close()\n\n file2 = open(file2name, 'U')\n file2contents = file2.readlines()\n file2.... | [
2,
2,
1
] | [] | [] | [
"python",
"replace",
"text_files"
] | stackoverflow_0008499739_python_replace_text_files.txt |
Q:
Python execute HTTP commands
To be brief, I've basically found that executing certain strings in the address bar in my browser causes good things to happen for me.
For instance: http://myip:myport/?CreateOrder=Create+New+Order creates a new order in my database.
I've used python to set the variables I want passed ... | Python execute HTTP commands | To be brief, I've basically found that executing certain strings in the address bar in my browser causes good things to happen for me.
For instance: http://myip:myport/?CreateOrder=Create+New+Order creates a new order in my database.
I've used python to set the variables I want passed into that string, but don't know t... | [
"While I am not sure that I entirely understand the context of your question you can make URL requests in python using the urllib2 module, specifically look at the urlopen function.\nHere is an example of how you could make the request you showed:\nimport urllib2\n\nurl_response = urllib2.urlopen('http://myip:mypor... | [
2,
1
] | [] | [] | [
"http",
"python"
] | stackoverflow_0008513184_http_python.txt |
Q:
Finding a certain link in a webpage, using BeautifulSoup
from BeautifulSoup import BeautifulSoup
import urllib2
import re
user = raw_input('begin here!: ')
base = ("http://1337x.org/search/")
print (base + user)
add_on = "/0/"
total_link = (base + user + add_on)
html_data = urllib2.urlopen(total_link, 'r').read()... | Finding a certain link in a webpage, using BeautifulSoup | from BeautifulSoup import BeautifulSoup
import urllib2
import re
user = raw_input('begin here!: ')
base = ("http://1337x.org/search/")
print (base + user)
add_on = "/0/"
total_link = (base + user + add_on)
html_data = urllib2.urlopen(total_link, 'r').read()
soup = BeautifulSoup(html_data)
announce = soup.find('a', at... | [
"The problem is in your regular expression. You are trying to use the ^ character to negate the regex, but it does not work in your situation. The ^ only negates a set of characters (a set of chars inside []); even in this case it only negates if it is the first char. For example, [^aeiou] means \"any character exc... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"scraper"
] | stackoverflow_0008504738_beautifulsoup_python_scraper.txt |
Q:
python xml ElementTree exception for tag not found
I'm using ElementTree to successfully pull values from specific tags in an xml file. To add some level of protection I'd like to throw and exception if a required tag is not present.
I found that ElementTree returns a value of "None" in place of a missing tag. But... | python xml ElementTree exception for tag not found | I'm using ElementTree to successfully pull values from specific tags in an xml file. To add some level of protection I'd like to throw and exception if a required tag is not present.
I found that ElementTree returns a value of "None" in place of a missing tag. But I can't even get that to work to my advantage :(
value ... | [
"\"None\" (a string) is not the same as None (a constant representing the absense of a value).\n"
] | [
5
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0008513395_elementtree_python.txt |
Q:
Upload from Android on Python AppEngine and read the file
I want to send a csv file from Android to Python AppEngine. I'm using the Blobstore API and to send the file, I use MultipartEntity, HttpPost and HttpGet.
So, according to the Blobstore API, you must call the method create_upload_url('/upload') to generate ... | Upload from Android on Python AppEngine and read the file | I want to send a csv file from Android to Python AppEngine. I'm using the Blobstore API and to send the file, I use MultipartEntity, HttpPost and HttpGet.
So, according to the Blobstore API, you must call the method create_upload_url('/upload') to generate the url to upload the file and you use this url as the action t... | [
"\nWhen I send the file to the url the AppEngine returned, this will\n automatically call the server method UploadHandler?\n\nCorrect.\n\nWhen I send the file to the url the AppEngine returned, this will\n automatically call the server method UploadHandler?\n\nShow us your server logs - what URL are you getting t... | [
0
] | [] | [] | [
"android",
"google_app_engine",
"python"
] | stackoverflow_0008467745_android_google_app_engine_python.txt |
Q:
How to display milliseconds instead of microseconds with Django
In Django template language I can display a time with microseconds using :
{{ player.time_to_display|time:"i:s:u" }}
I would like to display only milliseconds instead of the full microsecond value. I am not able to locate a way to do that in the docu... | How to display milliseconds instead of microseconds with Django | In Django template language I can display a time with microseconds using :
{{ player.time_to_display|time:"i:s:u" }}
I would like to display only milliseconds instead of the full microsecond value. I am not able to locate a way to do that in the documentation, is there a simple mean to do that ?
| [
"There is no built in support for displaying milliseconds in Django, or in Python for that matter. Your best bet would be to implement a custom filter that accepts a datetime instance and do the conversion yourself.\n",
"What about dividing your microseconds by 1000 (and maybe round the new value off)?\n1000 micr... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003683623_django_django_templates_python.txt |
Q:
AppEngine -> "AttributeError: 'unicode' object has no attribute 'has_key'" when using blobstore
There have been a number of other questions on AttributeErrors here, but I've read through them and am still not sure what's causing the type mismatch in my specific case.
Thanks in advance for any thoughts on this.
My ... | AppEngine -> "AttributeError: 'unicode' object has no attribute 'has_key'" when using blobstore | There have been a number of other questions on AttributeErrors here, but I've read through them and am still not sure what's causing the type mismatch in my specific case.
Thanks in advance for any thoughts on this.
My model:
class Object(db.Model):
notes = db.StringProperty(multiline=False)
other_item = db.Referen... | [
"You're passing in o as the value of other_item (in your sample code, you call it other, but I presume that's a typo). o is a string fetched from the request, though, and the model definition specifies that it's a ReferenceProperty, so it should either be an instance of the Other class, or a db.Key object.\nIf o is... | [
2,
1,
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0004060834_blobstore_google_app_engine_python.txt |
Q:
pygame vs. VPython for visualizing PyODE
I made a program similar to the second PyODE tutorial but using VPython instead of pygame and I removed the coord function for changing coordinates. It works but the locating of the spheres and joints isn't correct. I am guessing that it is because I am using the PyODE worl... | pygame vs. VPython for visualizing PyODE | I made a program similar to the second PyODE tutorial but using VPython instead of pygame and I removed the coord function for changing coordinates. It works but the locating of the spheres and joints isn't correct. I am guessing that it is because I am using the PyODE world coordinates within VPython. Would this in th... | [
"There is a reimplementation of pyode tutorial #2 which marries pyode with VPython included in the visualpyode library available at mission cognition. The solution used by that library is to use the ode coordinate system and orientations and copy them to the visual objects/frames (pos, axis, up) for each iteration... | [
0
] | [] | [] | [
"coordinates",
"pygame",
"pyode",
"python",
"vpython"
] | stackoverflow_0003277786_coordinates_pygame_pyode_python_vpython.txt |
Q:
Setting properties from CSV file using eval (Python)
I have CSV files that contain numerous values that I want to reference. I wanted to parse them succinctly using eval. Here's what I tried:
line = fileHandle.readline()
while line != "":
if line != "\n":
parameter = line.split(',')[0]
value = line.split... | Setting properties from CSV file using eval (Python) | I have CSV files that contain numerous values that I want to reference. I wanted to parse them succinctly using eval. Here's what I tried:
line = fileHandle.readline()
while line != "":
if line != "\n":
parameter = line.split(',')[0]
value = line.split(',')[2].replace("\n", "")
eval("%s = \"%s\"" % (param... | [
"As per S.Lott's suggestion, here is how I would solve this issue. I might be simplifying a little bit. If so, I apologize, but I haven't seen your data.\nimport csv\nmy_dict = {}\nwith open('my/data.csv') as f:\n my_reader = csv.reader(f)\n for row in my_reader:\n my_dict[row[0]] = row[2]\n\nAs you ca... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0008513340_python.txt |
Q:
How to characterize fitness of Least Squares Estimation
I am working on a localization project and using a least squares estimation to determine the location of a transmitter. I need a way to statistically characterize the "fitness" of my solution within my program, which could be used to tell me if I have a good ... | How to characterize fitness of Least Squares Estimation | I am working on a localization project and using a least squares estimation to determine the location of a transmitter. I need a way to statistically characterize the "fitness" of my solution within my program, which could be used to tell me if I have a good answer, or I need additional measurements, or have bad data. ... | [
"The closer R-squared is to 1.0, the better your fit is. Choose your own \"good enough\" threshold, I think typical thresholds are in the .92-.98 range.\n"
] | [
3
] | [] | [] | [
"numpy",
"optimization",
"python",
"scipy",
"statistics"
] | stackoverflow_0008512312_numpy_optimization_python_scipy_statistics.txt |
Q:
pip freeze captures the package name as if it was on python index site, but it is not. full path is needed
I installed a package from git hub:
pip install -e git+http://github.com/un33k/django-uuslug.git#egg=django-uuslug
Then I did:
pip freeze > req.txt
I get:
django-uuslug==0.1
Now if I do a pip install -r r... | pip freeze captures the package name as if it was on python index site, but it is not. full path is needed | I installed a package from git hub:
pip install -e git+http://github.com/un33k/django-uuslug.git#egg=django-uuslug
Then I did:
pip freeze > req.txt
I get:
django-uuslug==0.1
Now if I do a pip install -r req.txt, I get a package not found error, which due to the fact that django-uuslug is not on pypi.
Why is freeze ... | [
"I fixed it, don't know how, but I had to change the setup.py\npip install -e git+http://github.com/un33k/django-uuslug.git#egg=django-uuslug\n\nIf you find similar issue, and find yourself on this question, just look at the setup.py in the above package. Perhaps you can tell me how I fixed it. I just moved things ... | [
1,
1
] | [] | [] | [
"distutils",
"freeze",
"pip",
"python",
"setuptools"
] | stackoverflow_0006645676_distutils_freeze_pip_python_setuptools.txt |
Q:
PyQt: new API with Python 2
PyQt has two different API's: the old and the new.
By default you get the old API with Python 2 and the new API with Python 3.
Is it possible to enable the new PyQt API with Python 2? How?
A:
From this reddit comment,
import sip
API_NAMES = ["QDate", "QDateTime", "QString", "QTextStre... | PyQt: new API with Python 2 | PyQt has two different API's: the old and the new.
By default you get the old API with Python 2 and the new API with Python 3.
Is it possible to enable the new PyQt API with Python 2? How?
| [
"From this reddit comment,\nimport sip\nAPI_NAMES = [\"QDate\", \"QDateTime\", \"QString\", \"QTextStream\", \"QTime\", \"QUrl\", \"QVariant\"]\nAPI_VERSION = 2\nfor name in API_NAMES:\n sip.setapi(name, API_VERSION)\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtSvg import *\nfrom PyQt4.Qt... | [
13,
9,
4
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0006238193_pyqt_python.txt |
Q:
Speedy lookups from some kind of table (for graphics collisions)
What is the fastest or most efficient way of maintaining some sort of array for pixels on a screen in Python ? I don't want to use game libraries, just a simple array as I already have parts of it done without any libraries.
I'm developing a program ... | Speedy lookups from some kind of table (for graphics collisions) | What is the fastest or most efficient way of maintaining some sort of array for pixels on a screen in Python ? I don't want to use game libraries, just a simple array as I already have parts of it done without any libraries.
I'm developing a program which moving random stuff around the screen and i need to know whether... | [
"Since you're going to be bouncing off these boundaries, use a range of values to indicate the angle of the surface rather than just 0 or 1. Keep the array the same way you're storing the image pixels.\n"
] | [
0
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0008513821_graphics_python.txt |
Q:
Scan through sliding window looking for certain combination of letters in a string. Count occurrences . Python
If you have a sequence and you create a a list of window size 4. In each of those windows your looking for particular arrangement.
#Example:
count=0
test='abcdaecdagcd'
windows=['abcd','bcda','cdae','dae... | Scan through sliding window looking for certain combination of letters in a string. Count occurrences . Python | If you have a sequence and you create a a list of window size 4. In each of those windows your looking for particular arrangement.
#Example:
count=0
test='abcdaecdagcd'
windows=['abcd','bcda','cdae','daec','aecd','ecda','cdag','dagc','agcd']
I'm looking for a particular motif which is a-[b or e]-*-d within the sequen... | [
"A string 'a(b or e)*d' can't begin in a string 'a(b or e)*d'. Hence strings of this kind present in a long string can't overlap, and then a regex is usable to find what you need:\nimport re\n\nss = 'abcdaecdagcd'\n\nregx = re.compile('a[be].d')\n\nprint regx.findall(ss)\nprint len(regx.findall(ss))\n\nresult\n['ab... | [
1
] | [] | [] | [
"count",
"python",
"string",
"window"
] | stackoverflow_0008513963_count_python_string_window.txt |
Q:
jira SOAP and XMLRPC
I was wondering if there are urls for the various calls that can be made to jira. get issues, get users. what format are they in xml? json?
I want to write a wrapper class in python. I see the SOAP api exsists but no methods definitions in python anywhere I can find. I found the java one fairl... | jira SOAP and XMLRPC | I was wondering if there are urls for the various calls that can be made to jira. get issues, get users. what format are they in xml? json?
I want to write a wrapper class in python. I see the SOAP api exsists but no methods definitions in python anywhere I can find. I found the java one fairly easy.
Your help is appre... | [
"the Atlassian site has samples right on it.\nusing SOAP client to interact with Jira: \nhttp://confluence.atlassian.com/display/JIRA/Creating+a+SOAP+Client\nand using xml-rpc to interact with Jira:\nhttp://confluence.atlassian.com/display/JIRA/Creating+a+XML-RPC+Client\nalso check out the documentation they have f... | [
3,
3,
0
] | [] | [] | [
"api",
"jira",
"json",
"python",
"xml"
] | stackoverflow_0003339914_api_jira_json_python_xml.txt |
Q:
django phileo like app template problems
I am trying in use the django phileo(liking app) on my project but I keep running into template "TemplateSyntaxError" errors.
example: TemplateSyntaxError: Invalid block tag: 'phileo_css'
What I'm doing is inserting {% phileo_css %} in my header tags within my base.html. I... | django phileo like app template problems | I am trying in use the django phileo(liking app) on my project but I keep running into template "TemplateSyntaxError" errors.
example: TemplateSyntaxError: Invalid block tag: 'phileo_css'
What I'm doing is inserting {% phileo_css %} in my header tags within my base.html. I extends this base.html in another html file b... | [
"I figured out what my problem was. I was using version 0.2 of the app. I upgraded to version 0.3.dev1 and my problem was solved. Thanks to \"linux-warrior\" for pointing out that the version could be a problem.\nIt is important to note that pip install -U phileo does not install the latest version. So instead I do... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"python",
"reusability"
] | stackoverflow_0008498624_django_django_templates_python_reusability.txt |
Q:
Twisted Longpoll Server: request loop persists after disconnecting
I'm trying to write a longpolling server with Twisted, but I'm afraid I'm not understanding the request management.
When the client navigates away from the page, I can see it continue to loop in the console. I thought the instance would just destro... | Twisted Longpoll Server: request loop persists after disconnecting | I'm trying to write a longpolling server with Twisted, but I'm afraid I'm not understanding the request management.
When the client navigates away from the page, I can see it continue to loop in the console. I thought the instance would just destroy itself when the client disconnects.
And that is my goal, I want to run... | [
"\nWhen the client navigates away from the page, I can see it continue to loop in the console. I thought the instance would just destroy itself when the client disconnects.\n\nIt doesn't. First, instances are only destroyed when they are no longer \"reachable\" (just like any other kind of object you might have).\... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0008421959_python_twisted.txt |
Q:
Is there a significant difference between: if not a == 'bar' and if a != 'bar'?
Is this just two ways to write the same code? Is there any functional difference I should be aware of?
>>> a = 'foo'
>>> if not a == 'bar':
... 'its not'
...
'its not'
>>> if a != 'bar':
... 'its not'
...
'its not'
A:
In p... | Is there a significant difference between: if not a == 'bar' and if a != 'bar'? | Is this just two ways to write the same code? Is there any functional difference I should be aware of?
>>> a = 'foo'
>>> if not a == 'bar':
... 'its not'
...
'its not'
>>> if a != 'bar':
... 'its not'
...
'its not'
| [
"In python, to check whether or not an object is equal or not equal to another object, special functions are called. __eq__ is called to check ==, while __ne__ is called to check !=\nIn general, an object could define __ne__ differently than __eq__.\nE.g.\nclass Junk(object):\n def __ne__(self, other):\n ... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0008514427_python.txt |
Q:
Proper installation script for a small Python program (Not module) under Linux
I have a small program in python that consists in one .py file plus a directory of data files used by the program.
I would like to know the proper way to create an installation procedure for a user with admin rights on Linux so that he ... | Proper installation script for a small Python program (Not module) under Linux | I have a small program in python that consists in one .py file plus a directory of data files used by the program.
I would like to know the proper way to create an installation procedure for a user with admin rights on Linux so that he can install the program on his system and use it from the command line, with options... | [
"\nAm I wrong that the setup.py method (ie: python setup.py install), is only for installing modules, later to be used from within the interpreter or other scripts? \n\nYes. You're wrong.\nYou can install into Python's scripts directory. Keep reading up on all the things setup.py can do. http://docs.python.org/d... | [
12,
2,
0
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0008514471_installation_python.txt |
Q:
PyObjC issue with NSString method
I'm still a little new to the bridge , I'm playing around with the new shadow hash on Lion (Mac OS 10.7) and ran into a snag. The script snippet below, when run as root shows me the nested shadow hash as a dictionary, but I want to use this NSData as a string later in the script.... | PyObjC issue with NSString method | I'm still a little new to the bridge , I'm playing around with the new shadow hash on Lion (Mac OS 10.7) and ran into a snag. The script snippet below, when run as root shows me the nested shadow hash as a dictionary, but I want to use this NSData as a string later in the script. I should be able to convert it using t... | [
"This is correct if ShadowHashData[key] is a UTF-8-encoded string:\nvalue = NSString.alloc().initWithData_encoding_(ShadowHashData[key],NSUTF8StringEncoding)\n\nBut it returns None if ShadowHashData[key] is not. And none of the values of ShadowHashData is a UTF-8-encoded string. All of them are just arbitrary bin... | [
1
] | [] | [] | [
"nsdata",
"nsstring",
"pyobjc",
"python"
] | stackoverflow_0008426971_nsdata_nsstring_pyobjc_python.txt |
Q:
random module doesn't have randint() function
When I call random.randint(), I get the following error. Can anyone please explain what's happening?
$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import rand... | random module doesn't have randint() function | When I call random.randint(), I get the following error. Can anyone please explain what's happening?
$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
Traceback (most recent call last):
File "<stdi... | [
"You've called a script \"random.py\". Rename it so that it isn't shadowing the stdlib module of the same name.\n"
] | [
13
] | [] | [] | [
"python"
] | stackoverflow_0008515288_python.txt |
Q:
Do you know of any effort to integrate PySide/PyQt development in Qt Creator?
I would love to program in python using only QtCreator. I have already used QtCreator to teach GUI programming to undergraduate students and they loved it. We have discussed several times the possibility of switching to python, but the l... | Do you know of any effort to integrate PySide/PyQt development in Qt Creator? | I would love to program in python using only QtCreator. I have already used QtCreator to teach GUI programming to undergraduate students and they loved it. We have discussed several times the possibility of switching to python, but the lack of a good IDE to develop PySide/PyQt applications has refrained us to do so.
| [
"Have a look at https://github.com/PySide/QtCreator\n",
"I think it all depends on how you treat Qt Creator while you are developing Qt programs. There are lots of cool stuff in Qt Creator but if we focus on 2 major parts: Code Editor & UI Designer, the situation is much easier to realize.\nI think it's easier to... | [
5,
1
] | [] | [] | [
"ide",
"pyqt",
"pyside",
"python",
"qt_creator"
] | stackoverflow_0004977922_ide_pyqt_pyside_python_qt_creator.txt |
Q:
Need help programming with multiple files in Python
I'm making an RPG, and am trying to split things up into multiple files to organize things better. (I mean, character creation alone was over 2000 lines.) But this is something that I've never done, and I'm really not sure how to do it. So, if I could get some ge... | Need help programming with multiple files in Python | I'm making an RPG, and am trying to split things up into multiple files to organize things better. (I mean, character creation alone was over 2000 lines.) But this is something that I've never done, and I'm really not sure how to do it. So, if I could get some general advice on how to set things up efficiently, etc. I ... | [
"here is a mini example to get you going.. you can initialize base values with something like randrange and so on. each of these classes can be put into a file and imported as a module, whatever keeps you organized. good luck\nimport random\n\nclass PlayerAttributes(object):\n\n def __init__(self):\n se... | [
3,
0
] | [] | [] | [
"file",
"function",
"import",
"list",
"python"
] | stackoverflow_0008514608_file_function_import_list_python.txt |
Q:
lambda to function conversion in python
I am trying to convert a labda function in normal function but unable to understand it.
def closest(u):
return min(updated_unique_list, key=lambda v: len(set(u) ^ set(v)))
how this labda and min works?
I tried to understand from docs but I want to understand with thi... | lambda to function conversion in python | I am trying to convert a labda function in normal function but unable to understand it.
def closest(u):
return min(updated_unique_list, key=lambda v: len(set(u) ^ set(v)))
how this labda and min works?
I tried to understand from docs but I want to understand with this example and to create a normal function ins... | [
"min find the minimum value of an iterable with respect to a function. min(lst, key=func) in Python can be roughly considered as (ignoring details like calling f as little as possible or walking through the list only once)\nretval = lst[0]\nfor item in lst:\n if func(item) < func(retval):\n retval = item\nretu... | [
4
] | [] | [] | [
"lambda",
"min",
"python"
] | stackoverflow_0008515692_lambda_min_python.txt |
Q:
Reading and editing a font file and using a dictionary
I have to take the values from a text file which contains the co-ordinates to draw characters out in TurtleWorld, an example of the text file is the following:
<character=B, width=21, code=66>
4 21
4 0
-1 -1
4 21
13 21
16 20
17 19
18 17
18 15
17 13
16 12
13 11... | Reading and editing a font file and using a dictionary | I have to take the values from a text file which contains the co-ordinates to draw characters out in TurtleWorld, an example of the text file is the following:
<character=B, width=21, code=66>
4 21
4 0
-1 -1
4 21
13 21
16 20
17 19
18 17
18 15
17 13
16 12
13 11
-1 -1
4 11
13 11
16 10
17 9
18 7
18 4
17 2
16 1
13 0
4 0
</... | [
"take a look at http://oreilly.com/catalog/pythonxml/chapter/ch01.html :: specifically, hit up the example titled :: Example 1-1: bookhandler.py \nyou can more or less credit/copy that and tweak it to read your particular xml. once you get the 'guts'(your coords), you can split it into a list of x/y coords really... | [
0
] | [] | [] | [
"dictionary",
"fonts",
"python"
] | stackoverflow_0008514814_dictionary_fonts_python.txt |
Q:
Apache won't run Py_Initialize(); function
How to run python functions into Apache module?
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
#include "python2.7/Python.h"
static char* a(){
Py_Initialize();
PyRun_SimpleString("f = open('/tmp/workfile', 'w+')")
... | Apache won't run Py_Initialize(); function | How to run python functions into Apache module?
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
#include "python2.7/Python.h"
static char* a(){
Py_Initialize();
PyRun_SimpleString("f = open('/tmp/workfile', 'w+')")
"f.write('0123456789abcdef'... | [
"This is so hard way !!. \nUse python and mod_wsgi. It is very easy.\ntry this guide. \nhttp://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide\n"
] | [
2
] | [] | [] | [
"apache2",
"c",
"python"
] | stackoverflow_0008493245_apache2_c_python.txt |
Q:
how to prevent python from printing the binary sign
I need to print the comments of files inside a zip file :
import zipfile
def info_zip(archive_name):
with zipfile.ZipFile(archive_name) as challenge:
for info in challenge.infolist():
print(info.comment)
but the results i am get aren't pre... | how to prevent python from printing the binary sign | I need to print the comments of files inside a zip file :
import zipfile
def info_zip(archive_name):
with zipfile.ZipFile(archive_name) as challenge:
for info in challenge.infolist():
print(info.comment)
but the results i am get aren't pretty:
b'G'
b' '
b'E'
b' '
b' '
b'*'
b'*'
b' '
b'E'
How t... | [
"The bindicates that it is a bytes-object that is printed. To get from bytes to string you have to decode the bytes object (Encode is transform a string to a bytes object).\nIn order to decode a bytes object you'' have to know the used character encoding.\nMy guess is that the zip-file header is simply ASCII encode... | [
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008515869_python_python_3.x.txt |
Q:
Django design patterns - models with ForeignKey references to multiple classes
I'm working through the design of a Django inventory tracking application, and have hit a snag in the model layout. I have a list of inventoried objects (Assets), which can either exist in a Warehouse or in a Shipment. I want to store d... | Django design patterns - models with ForeignKey references to multiple classes | I'm working through the design of a Django inventory tracking application, and have hit a snag in the model layout. I have a list of inventoried objects (Assets), which can either exist in a Warehouse or in a Shipment. I want to store different lists of attributes for the two types of locations, e.g.:
For Warehouses, ... | [
"what about having a generic foreign key on Assets?\n",
"I think its perfectly reasonable to create a \"through\" table such as location, which associates an asset, a content (foreign key) and a content_type (warehouse or shipment) . And you could set a unique constraint on the asset_fk so thatt it can only exist... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008274664_django_django_models_python.txt |
Q:
lxml.html.tostring re-ordered doctype and xml tags when printing
Imagine I have a file test.html with content,
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><tit... | lxml.html.tostring re-ordered doctype and xml tags when printing | Imagine I have a file test.html with content,
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Components of the SDK</title><link rel="stylesheet" href="core.css"... | [
"Short Answer\nDo this instead (assuming your documents are all well-formed XML)\netx = lxml.etree.parse('test.html')\nprint lxml.etree.tostring(etx, xml_declaration=True, encoding=etx.docinfo.encoding, standalone=etx.docinfo.standalone)\n\nExplanation\ntest.html is not actually valid html. It has empty elements an... | [
6
] | [] | [] | [
"lxml",
"python",
"xhtml",
"xml_parsing"
] | stackoverflow_0008513814_lxml_python_xhtml_xml_parsing.txt |
Q:
bsddb.open additional arguments
The bsddb module has three ways to open a db-file:
bsddb.hashopen(filename[, flag[, mode[, pgsize[, ffactor[, nelem[, cachesize[, lorder[, hflags]]]]]]]])
bsddb.btopen(filename[, flag[, mode[, btflags[, cachesize[, maxkeypage[, minkeypage[, pgsize[, lorder]]]]]]]])
bsddb.rnopen(file... | bsddb.open additional arguments | The bsddb module has three ways to open a db-file:
bsddb.hashopen(filename[, flag[, mode[, pgsize[, ffactor[, nelem[, cachesize[, lorder[, hflags]]]]]]]])
bsddb.btopen(filename[, flag[, mode[, btflags[, cachesize[, maxkeypage[, minkeypage[, pgsize[, lorder]]]]]]]])
bsddb.rnopen(filename[, flag[, mode[, rnflags[, caches... | [
"Looking at the C API reference I see some documentation (but indeed it's hard to find). For example, for bsddb.hashopen:\n\nmode: DB->open()\npgsize: DB->set_pagesize(), DB->get_pagesize()\nffactor: DB->set_h_ffactor(), DB->get_h_ffactor()\nnelem: DB->set_h_nelem(), DB->get_h_nelem()\ncachesize: DB->set_cachesize(... | [
3
] | [] | [] | [
"bsddb",
"python"
] | stackoverflow_0008515087_bsddb_python.txt |
Q:
Dictionary changing many values to many keys
I was just wondering if in the wonderful world of Python there is any way to go from something like this:
dict1 = {'a': [1,2,3], 'b': [4,5,6]}
to
dict2 = {'a':1, 'a':2, 'a':3,'b':4, 'b': 5, 'b': 6]
or equivalent, the order is irrelevant but I need some way of decompos... | Dictionary changing many values to many keys | I was just wondering if in the wonderful world of Python there is any way to go from something like this:
dict1 = {'a': [1,2,3], 'b': [4,5,6]}
to
dict2 = {'a':1, 'a':2, 'a':3,'b':4, 'b': 5, 'b': 6]
or equivalent, the order is irrelevant but I need some way of decomposing dict1 into something in which I can assign the... | [
"Your dict2 makes no sense because dictionary keys must be unique. \nI am pretty sure you can get what you want by iterating over dict1.items(), but I need some more clarification on what the expected output list looks like... in your example a and b are undefined and I don't know what the 0 at the start is repres... | [
5,
2
] | [] | [] | [
"dictionary",
"key",
"python"
] | stackoverflow_0008516181_dictionary_key_python.txt |
Q:
Testing a Django app in many separate threads
I'd like to run my Django app's tests in several threads (possibly dozens) in parallel. This is because my app spends almost all of its time waiting for remote requests, and I reckon that if I run the tests in parallel, they would all work at the same time without slow... | Testing a Django app in many separate threads | I'd like to run my Django app's tests in several threads (possibly dozens) in parallel. This is because my app spends almost all of its time waiting for remote requests, and I reckon that if I run the tests in parallel, they would all work at the same time without slowing each other down, and the whole suite would be o... | [
"use uWSGI\npip install uwsgi\n\nCreate .ini for your project:\n[uwsgi]\n# set the http port\nhttp = :8000\n# change to django project directory\nchdir = /var/www/myapp\n# add /var/www to the pythonpath, in this way we can use the project.app format\npythonpath = /var/www\n# set the project settings name\nenv = DJA... | [
0
] | [
"I've recently began delving into django-celery which is an asynchronous task queue for django. It allows you to queue up tasks to run asynchronously so that you don't have to wait for responses. It's simple to install and get started and it would allow your application to utilize asynchronous queueing instead of j... | [
-1
] | [
"django",
"multithreading",
"python",
"testing"
] | stackoverflow_0008510830_django_multithreading_python_testing.txt |
Q:
Trouble with Python lists
The following code is intended to dump a long list of numbers from a csv into stat_by_symbol[symbol] so that I can call the list of numbers using each symbol as a key. For some reason, the code only seems to work for the first symbol. Can someone help me fix the code to work as intended? ... | Trouble with Python lists | The following code is intended to dump a long list of numbers from a csv into stat_by_symbol[symbol] so that I can call the list of numbers using each symbol as a key. For some reason, the code only seems to work for the first symbol. Can someone help me fix the code to work as intended? Many thanks.
with open('zzdata.... | [
"The problem is that you can iterate over reader just once (therefore just the first symbol match).\nTry this:\nstat_by_symbol = {}\nwith open('zzdata.csv', 'rb') as f:\n reader = csv.reader(f)\n reader.next()\n for row in reader:\n for symbol in symbols:#symbols in a list\n if symbol in ... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008516669_list_python.txt |
Q:
Identity management and authentication for REST APIs
We have built a Python based REST API. We are planning to give to other developers as well. Is there a Python library which could manage authentication keep track of API calls made be each client etc?
A:
Well, ideally you'll be using public-key cryptography, s... | Identity management and authentication for REST APIs | We have built a Python based REST API. We are planning to give to other developers as well. Is there a Python library which could manage authentication keep track of API calls made be each client etc?
| [
"Well, ideally you'll be using public-key cryptography, supplying the developers with an API key and secret both. If the service is accessible via HTTPS to a limited number of consumers, you might be tempted to defer to issuing a simple API key alone, but your committing yourself to remain a small, closed and insec... | [
1
] | [] | [] | [
"python",
"rest",
"restful_authentication"
] | stackoverflow_0008515751_python_rest_restful_authentication.txt |
Q:
how to send email in django?
Possible Duplicate:
Django - [Errno 111] Connection refused
I have found a a link on how to send email with django : https://docs.djangoproject.com/en/dev/topics/email/
i followed the example and i got this:
>>> from django.core.mail import send_mail
>>> send_mail('dfdf', 'dfdfdf', '... | how to send email in django? |
Possible Duplicate:
Django - [Errno 111] Connection refused
I have found a a link on how to send email with django : https://docs.djangoproject.com/en/dev/topics/email/
i followed the example and i got this:
>>> from django.core.mail import send_mail
>>> send_mail('dfdf', 'dfdfdf', 'logadrinab@agile.com.ph', ['ddcah... | [
"In your settings.py for your project, make sure you set your EMAIL_HOST, EMAIL_PORT and other settings (like a username or password if your host requires authentication).\nAlso, make sure you are running the console using the manage.py shell command, and not your normal python shell, so django loads the settings c... | [
3,
0,
0,
0
] | [] | [] | [
"django",
"python",
"sendmail"
] | stackoverflow_0008516903_django_python_sendmail.txt |
Q:
find elements for list in string
I have a string, 'RTKLOANGMSTTTS' and a list of tuples, [(2,5),(8,9)], that returns a string containing the letters 2-5 and 8-9 both inclusive, that is 'TKLOGM'.
I was thinking something like:
def f(string, lst):
for element in lst:
if element in string:
pri... | find elements for list in string | I have a string, 'RTKLOANGMSTTTS' and a list of tuples, [(2,5),(8,9)], that returns a string containing the letters 2-5 and 8-9 both inclusive, that is 'TKLOGM'.
I was thinking something like:
def f(string, lst):
for element in lst:
if element in string:
print string
But it does not return anyt... | [
"Try this:\ndef f(source, lst):\n return \"\".join(source[start - 1:end] for start, end in lst)\n\nWhat this will do is iterate over the lst, extracting the tuple into start and end on every iteration. Then it will create a new string as a slice from the source string, from start - 1 to end (we use start - 1 bec... | [
4,
2,
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0008517072_list_python_string.txt |
Q:
Loop to append multiple lists to a single list in Python
In the following code, row[8], row[9], ..., row[27] each contain many numbers. I need all of the numbers in row[8], row[9], etc. to append to stat_by_symbol as separate lists within within stat_by_symbol. However, the code below appends all of the numbers ac... | Loop to append multiple lists to a single list in Python | In the following code, row[8], row[9], ..., row[27] each contain many numbers. I need all of the numbers in row[8], row[9], etc. to append to stat_by_symbol as separate lists within within stat_by_symbol. However, the code below appends all of the numbers across all rows within a single list.
As an example of what I ne... | [
"stat_by_symbol = dict((symbol, [[] for i in xrange(8,28)]) for symbol in symbols)\nwith open('zzdata.csv', 'rb') as f:\n reader = csv.reader(f)\n reader.next()\n for row in reader:\n for symbol, symbol_list in stat_by_symbol.iteritems():\n if symbol in row:\n for symbol_li... | [
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0008517246_list_loops_python.txt |
Q:
Tkinter.StringVar() throws an exception
I have python 2.7.2-4 (Archlinux), and from
import Tkinter
Tkinter.StringVar()
results
Traceback (most recent call last):
File "/tmp/foo.py", line 3, in <module>
foo = Tkinter.StringVar()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 251, in __init__
Variabl... | Tkinter.StringVar() throws an exception | I have python 2.7.2-4 (Archlinux), and from
import Tkinter
Tkinter.StringVar()
results
Traceback (most recent call last):
File "/tmp/foo.py", line 3, in <module>
foo = Tkinter.StringVar()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 251, in __init__
Variable.__init__(self, master, value, name)
File ... | [
"Call tk.Tk() before tk.StringVar():\nimport Tkinter as tk\n\nroot=tk.Tk() \ntk.StringVar()\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008517906_python_tkinter.txt |
Q:
python json binding: why write code like this?
I am using some open SNS webiste's API, the python version is a binding to its JSON version, but I really can't understand below, why do things like this?
def mentions(self):
comments = self.api.mentions()
for comment in comments:
self.obj = comment
... | python json binding: why write code like this? | I am using some open SNS webiste's API, the python version is a binding to its JSON version, but I really can't understand below, why do things like this?
def mentions(self):
comments = self.api.mentions()
for comment in comments:
self.obj = comment
mid = self.getAtt("id")
text = self.ge... | [
"Perhaps comment isn't amenable to direct attribute access. If so...\nIt looks like the API was designed by a Java programmer. A more Pythonic solution — assuming you can't access the attributes of comment directly — would be to rename the getAtt method to __getattr__ and write, e.g., mid = self.id.\nBut even then ... | [
1
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0008518488_python_twitter.txt |
Q:
Eclipse removing entries from the global easy_install.pth?
We are having some annoying problems with Eclipse, which apparently have been always there, on Windows 7 + a custom python installation + Eclipse 3.7 and the latest Pydev.
The problem is basically that if when setting up the python interpreter you add all ... | Eclipse removing entries from the global easy_install.pth? | We are having some annoying problems with Eclipse, which apparently have been always there, on Windows 7 + a custom python installation + Eclipse 3.7 and the latest Pydev.
The problem is basically that if when setting up the python interpreter you add all the libraries too, then Eclipse or Pydev or who knows what delet... | [
"Ok, I must say I haven't been able to reproduce this so far in PyDev... do you know if that's only happening in your machine (or some other colleague also has the same problem)? \nTo try to reproduce it, can you give more details on your toolchain: what's your python version and what's your setuptools version? Whi... | [
3,
2,
0
] | [] | [] | [
"eclipse",
"pydev",
"python",
"windows"
] | stackoverflow_0008448330_eclipse_pydev_python_windows.txt |
Q:
How do you get "some Text" from some Text with python?
I'm using python & mindom module.
I'd like to extract abc from
<someTag>abc</someTag>.
Suppose I can get to someTag, how do I retrieve the abc from there?
A:
>>> from xml.dom.minidom import parseString
>>> x = parseString('<abc>foo</abc>')
>>> x.getElement... | How do you get "some Text" from some Text with python? | I'm using python & mindom module.
I'd like to extract abc from
<someTag>abc</someTag>.
Suppose I can get to someTag, how do I retrieve the abc from there?
| [
">>> from xml.dom.minidom import parseString\n>>> x = parseString('<abc>foo</abc>')\n>>> x.getElementsByTagName('abc')[0].firstChild.nodeValue\nu'foo'\n\n",
"If you have the someTag\nyou can get it's data by calling tag.data\nf.ex. by \nfrom xml.dom.minidom import parseString\ndom = parseString(\"<someTag>abc</s... | [
5,
1
] | [] | [] | [
"dom",
"python",
"xml"
] | stackoverflow_0008518623_dom_python_xml.txt |
Q:
Using ElementTree to parse an XML string with a namespace
I have Googled my pants off to no avail. What I am trying to do is very simple: I'd like to access the UniqueID value in the following XML contained in a string using ElementTree.
from xml.etree.ElementTree import fromstring
xml_string = """<ListObject... | Using ElementTree to parse an XML string with a namespace | I have Googled my pants off to no avail. What I am trying to do is very simple: I'd like to access the UniqueID value in the following XML contained in a string using ElementTree.
from xml.etree.ElementTree import fromstring
xml_string = """<ListObjectsResponse xmlns='http://www.example.com/dir/'>
<Item>
... | [
"The following should get you going:\n>>> tree.findall('*/*')\n[<Element '{http://www.example.com/dir/}UniqueID' at 0x10899e450>]\n\nThis lists all the elements that are two levels below the root of your tree (the UniqueID element, in your case). You can, alternatively, find only the first element at this level, w... | [
5,
4
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0008511208_elementtree_python_xml.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.