content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to avoid repetitive if statements in python dictionaries
I am trying to create a new dictionary out of html form data that was submitted by the user. I end up writing repetitive if statements, checking if xyz key is in the dictionary in the form data. I know this is a quite suboptimal approach though I am not ... | How to avoid repetitive if statements in python dictionaries | I am trying to create a new dictionary out of html form data that was submitted by the user. I end up writing repetitive if statements, checking if xyz key is in the dictionary in the form data. I know this is a quite suboptimal approach though I am not quite sure how to implement this using python.
This is the form da... | [
"The standard answer to how to avoid repeated code applies here --- extract the repeated code to a function:\ndef extract_field(form_data, clean, fieldname, optional=('info', 'instruction')):\n if fieldname+'field' in form_data:\n infofield = { 'field': fieldname }\n for opt in optional:\n o... | [
4,
1
] | [] | [] | [
"dictionary",
"dynamic",
"if_statement",
"python",
"repeat"
] | stackoverflow_0007511294_dictionary_dynamic_if_statement_python_repeat.txt |
Q:
Django database API (model layer) without installing django?
I'm starting a new Python project where I'd love to have Django-like control over my database using models and SQLite, but I don't need all of Django. Also I don't want users to have to install any dependencies before using my product.
Are there any smal... | Django database API (model layer) without installing django? | I'm starting a new Python project where I'd love to have Django-like control over my database using models and SQLite, but I don't need all of Django. Also I don't want users to have to install any dependencies before using my product.
Are there any smaller projects out there that deliver Django-like database models, o... | [
"It's not currently possible to just install Django's ORM without the rest of it. You can install the whole lot and just use the ORM, though.\nAlternatively you might like to look into one of the standalone Python db wrappers/ORMs. The big one is SQLAlchemy, and there's also the smaller SQLObject.\n"
] | [
1
] | [] | [] | [
"django",
"model_view_controller",
"models",
"python",
"sqlite"
] | stackoverflow_0007510511_django_model_view_controller_models_python_sqlite.txt |
Q:
Pythonic way to replace text with xml nodes
I'm wondering if anyone can come up with a more 'pythonic' solution to the problem I'm currently trying to solve.
I've got a source XML file that I'm writing an XSLT generator for. The relevant part of the source XML looks like this:
...
<Notes>
<Note>
<Code>... | Pythonic way to replace text with xml nodes | I'm wondering if anyone can come up with a more 'pythonic' solution to the problem I'm currently trying to solve.
I've got a source XML file that I'm writing an XSLT generator for. The relevant part of the source XML looks like this:
...
<Notes>
<Note>
<Code>ABC123</Code>
<Text>Note text contents</T... | [
"note_nodes=re.split(r'\\{(.*?)\\}',details['text'])\n# ['', 'Code', ' - ', 'Text', '']\nnote_nodes=[n if i%2==0 else XSL('value-of',select=n) \n for i,n in enumerate(note_nodes)]\n\n"
] | [
1
] | [] | [] | [
"lxml",
"python",
"regex"
] | stackoverflow_0007511968_lxml_python_regex.txt |
Q:
converting variable like string content to real variable in python
I have string variable which contains "variable" like content as shown below.
str1="type=gene; loc=scaffold_12875; ID=FBgn0207418; name=Dvir\GJ20278;MD5=4c62b751ec045ac93306ce7c08d254f9; length=2088; release=r1.2; species=Dvir;"
I need to make var... | converting variable like string content to real variable in python | I have string variable which contains "variable" like content as shown below.
str1="type=gene; loc=scaffold_12875; ID=FBgn0207418; name=Dvir\GJ20278;MD5=4c62b751ec045ac93306ce7c08d254f9; length=2088; release=r1.2; species=Dvir;"
I need to make variables out of the string such that the variables name and values goes li... | [
"Don't do this. You could, but don't.\nInstead make a dictionary whose keys are the names:\nresult_dict = {}\nitems = str1.split(';')\nfor item in items:\n key, value = item.strip().split('=')\n result_dict[key] = value\n\n",
"Or you could do this\nclass Namespace(object):\n pass\n\nfor item in str1.spli... | [
3,
0
] | [] | [] | [
"python",
"split",
"string",
"variables"
] | stackoverflow_0007511865_python_split_string_variables.txt |
Q:
Transparent PNG in PIL turns out not to be transparent
I have been hitting my head against the wall for a while with this, so maybe someone out there can help.
I'm using PIL to open a PNG with transparent background and some random black scribbles, and trying to put it on top of another PNG (with no transparency),... | Transparent PNG in PIL turns out not to be transparent | I have been hitting my head against the wall for a while with this, so maybe someone out there can help.
I'm using PIL to open a PNG with transparent background and some random black scribbles, and trying to put it on top of another PNG (with no transparency), then save it to a third file.
It comes out all black at the... | [
"I think what you want to use is the paste mask argument.\nsee the docs, (scroll down to paste)\nfrom PIL import Image\nimg = Image.open(basefile)\nlayer = Image.open(layerfile) # this file is the transparent one\nprint layer.mode # RGBA\nimg.paste(layer, (xoff, yoff), mask=layer) \n# the transparancy layer will be... | [
53
] | [] | [] | [
"png",
"python",
"python_imaging_library",
"transparent"
] | stackoverflow_0007510313_png_python_python_imaging_library_transparent.txt |
Q:
What is the right method of escaping string before using it as json object
I have to create JSON string from database values and push it back to database again. My Python code is:
json = "{"
for row in cursor_mysql:
#mainkey = row[0]
#name = row[1]
#value = row[2]
mainkey = """" " \n \ / """ #... | What is the right method of escaping string before using it as json object | I have to create JSON string from database values and push it back to database again. My Python code is:
json = "{"
for row in cursor_mysql:
#mainkey = row[0]
#name = row[1]
#value = row[2]
mainkey = """" " \n \ / """ #for testing only
name = """ {} " \r \t """ #for testing only
valu... | [
"import json\n\ndata = json.dumps(BIG_STRUCTURE_GOES_HERE)\nquery = \"\"\"UPDATE table SET json = %s WHERE id = %s RETURNING id\"\"\"\ncursor_postgres.execute(query, (data, rowId))\nconn_postgres.commit()\n\n",
"http://docs.python.org/library/json.html\nhttp://pypi.python.org/pypi/simplejson/\ndjango.utils.simple... | [
3,
0,
0
] | [] | [] | [
"json",
"python",
"serialization"
] | stackoverflow_0007512493_json_python_serialization.txt |
Q:
Regular expressions in python : don't split when a specific substring is found
I found a bug in a regex in one of python-scripts and I need help to solve it.
The problem is that the script splits a string with re.split('(V[A-Z])', string) but I don't want a split if the specific substring SVD is found.
example:
"A... | Regular expressions in python : don't split when a specific substring is found | I found a bug in a regex in one of python-scripts and I need help to solve it.
The problem is that the script splits a string with re.split('(V[A-Z])', string) but I don't want a split if the specific substring SVD is found.
example:
"ACD VU LSF VMSUGH VIJ SVD HJV DVO" -> "ACD ", "U LSF ","MSUGH ", "IJ SVD HJV D", "O"
... | [
"Hmm...\nif 'SVD' not in string:\n result = re.split('(V[A-Z])', string)\nelse:\n result = string\n\n",
"If I understand your question correctly, you should use lookbehind assertion in regex. \nhttp://docs.python.org/library/re.html\n>>>x = 'ACD VU LSF VMSUGH VIJ SVD HJV DVO'\n>>>result = re.split('V[A-Z](?... | [
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007512073_python_regex.txt |
Q:
How to quantize image color from RGB 24 bit to RGB 6 bit (64 colors)?
I'm trying to deploy BIC algorithm (border/interior pixel classify) and using PIL (python imaging library) to process image . But i don't know how to quantize RGB color from 24bit (8bit per color) to 6 bit (2bit per color) by using PIL .
Anyon... | How to quantize image color from RGB 24 bit to RGB 6 bit (64 colors)? | I'm trying to deploy BIC algorithm (border/interior pixel classify) and using PIL (python imaging library) to process image . But i don't know how to quantize RGB color from 24bit (8bit per color) to 6 bit (2bit per color) by using PIL .
Anyone can tell me how to do it by PIL or another python library such as Opencv ... | [
"the PIL ImageOps posterize (scroll down to posterize) function should do this for you.\n"
] | [
1
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0007512304_image_processing_python_python_imaging_library.txt |
Q:
How to extend a C++ class by adding a new attribute with swig (Python)?
I have a C++ class that I need to extend by adding a new private attribute. I also need this to not be tied to a specific class so I'm using define. I've tried to do it the same way I add new methods, but it doesn't seem to have any effect:
%d... | How to extend a C++ class by adding a new attribute with swig (Python)? | I have a C++ class that I need to extend by adding a new private attribute. I also need this to not be tied to a specific class so I'm using define. I've tried to do it the same way I add new methods, but it doesn't seem to have any effect:
%define add_new_attribute(cls)
%extend MyClass {
int new_attribute;
... | [] | [] | [
"Not sure why you are using %define. Just appending this to your swig interface file should work (I have not tested it for member variables, but I have used this for member function definitions):\n %extend MyClass {\n int new_attribute;\n }\n\nNote that the last semicolon was redundant.\n"
] | [
-1
] | [
"c++",
"python",
"swig"
] | stackoverflow_0007482270_c++_python_swig.txt |
Q:
simplejson in Python throws value error
I've got a JSON string that I'm posting to my Python script. This is an example string:
{"uid":"1111111","method":"check_user"}
In my Python code I simply call simplejson.loads( str ) where str is the JSON string from the request. The JSON string seems fine as when I print ... | simplejson in Python throws value error | I've got a JSON string that I'm posting to my Python script. This is an example string:
{"uid":"1111111","method":"check_user"}
In my Python code I simply call simplejson.loads( str ) where str is the JSON string from the request. The JSON string seems fine as when I print it at request time it's intact. However I get... | [
"You've got some unprintable character in your string. I get the same error if I append a null byte to the end of the string, and printing it doesn't show the problem:\n>>> import json\n>>> string = '{\"uid\":\"1111111\",\"method\":\"check_user\"}\\x00'\n>>> print string\n{\"uid\":\"1111111\",\"method\":\"check_use... | [
6
] | [] | [] | [
"decode",
"google_app_engine",
"json",
"python"
] | stackoverflow_0007512934_decode_google_app_engine_json_python.txt |
Q:
Output of urllib.urlopen doesn't display when render to a template
I'm using Python 2.7 - how can I convert the output of urllib.urlopen to a string?
data = urllib.urlopen('http://www.google.com').read()
test = "testone"
return render_to_response('home.html', locals())
home.html:
{{data}}
<br/>
{{test}}
Only 't... | Output of urllib.urlopen doesn't display when render to a template | I'm using Python 2.7 - how can I convert the output of urllib.urlopen to a string?
data = urllib.urlopen('http://www.google.com').read()
test = "testone"
return render_to_response('home.html', locals())
home.html:
{{data}}
<br/>
{{test}}
Only 'testone' displays in the browser.
| [
"On my system it's already a string, so no conversion is required:\nIn [4]: type(urllib.urlopen('http://www.google.com').read())\nOut[4]: <type 'str'>\n\n",
">>> import urllib\n>>> data = urllib.urlopen('http://www.google.com').read()\n>>> type(data)\n<type 'str'>\n\nIt's already a string.\n",
"when I change th... | [
1,
1,
1
] | [] | [] | [
"django_templates",
"django_views",
"python"
] | stackoverflow_0007512660_django_templates_django_views_python.txt |
Q:
matplotlib large set of colors for plots
I have a lot of graphs I want to plot in one plot. I've just started with matplotlib and can't find a good way to generate a lot of distinguishable colors :( Maybe cycling over HSV with SV at maximum?
I'm thinking of something like
args=[]
for i,(x,y) in enumerate(data):
... | matplotlib large set of colors for plots | I have a lot of graphs I want to plot in one plot. I've just started with matplotlib and can't find a good way to generate a lot of distinguishable colors :( Maybe cycling over HSV with SV at maximum?
I'm thinking of something like
args=[]
for i,(x,y) in enumerate(data):
args.extend([x,y,hsv(i)])
plot(*args)
Any s... | [
"I think you have the right idea, except that the colors will be more distinguishable if you pass the colormap hsv numbers which are spread out over the range (0,1):\nhsv = plt.get_cmap('hsv')\nhsv(float(i)/(len(data)-1))\n\nor, using NumPy:\ncolors = hsv(np.linspace(0, 1.0, len(kinds)))\n\nFor example:\nimport dat... | [
32
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0007513262_matplotlib_plot_python.txt |
Q:
image segmentation using pil/any package of python
i need to segment an image into regions .i'm using pil.i found no module to segment image in pil. I need this segmented regions as a list or dictionary.
Actually i'm trying to compare the images for similarity in content aware fashion.for that i need to segment th... | image segmentation using pil/any package of python | i need to segment an image into regions .i'm using pil.i found no module to segment image in pil. I need this segmented regions as a list or dictionary.
Actually i'm trying to compare the images for similarity in content aware fashion.for that i need to segment the image. i tried segwin tool but it is drawing another i... | [
"The easiest way to segment an image into regions is creating an other image called labelmap. The \"region 1\" is represented by all the 1 valued pixels within the labelmap, and so on. If you need the pixels of the \"region 3\" you just binarize the labelmap with a thershold equal to 3 and multiply the result with... | [
2,
1,
0
] | [
"You might want to try the python bindings for ITK, a segmentation tool in C++.\n"
] | [
-2
] | [
"image",
"imaging",
"python",
"python_imaging_library"
] | stackoverflow_0002616584_image_imaging_python_python_imaging_library.txt |
Q:
Python: lxml.etree.tostring(with_comments=False)
I call the following command and get the following error:
>>>lxml.etree.tostring([tree].getroot(), with_comments=False)
ValueError: Can only discard comments in C14N serialisation
I don't know what C14N is, but I would appreciate an explanation of how I can achieve... | Python: lxml.etree.tostring(with_comments=False) | I call the following command and get the following error:
>>>lxml.etree.tostring([tree].getroot(), with_comments=False)
ValueError: Can only discard comments in C14N serialisation
I don't know what C14N is, but I would appreciate an explanation of how I can achieve it and run the foregoing command with with_comments=... | [
"You can remove the comments at parsing time:\nparser = etree.XMLParser(remove_comments=True)\ntree = etree.parse(xmlfile, parser=parser)\n\nOr when using objectify (took me hell of a time to find this out):\nparser = objectify.makeparser(remove_comments=True)\ntree = objectify.parse(xmlfile, parser=parser)\n\n",
... | [
9,
3
] | [] | [] | [
"python",
"xml",
"xml_serialization"
] | stackoverflow_0006539035_python_xml_xml_serialization.txt |
Q:
adding new pair in dictionary why the last added 'mynewkey': 'mynewvalue' came first in dictionary
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
why the last added 'mynewkey': 'mynewvalue' came first in dictionary
A:
... | adding new pair in dictionary why the last added 'mynewkey': 'mynewvalue' came first in dictionary | >>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
why the last added 'mynewkey': 'mynewvalue' came first in dictionary
| [
"Python dictionaries are not ordered. If you iterate over the items of a dict object you will not get them in the order you inserted them. The reason is the internal data structure behind it.\nIf you use Python 2.7 or Python 3.3 you can resort to http://docs.python.org/dev/library/collections.html#collections.Order... | [
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007513754_dictionary_python.txt |
Q:
Twisted under windows
Twisted located at C:\Python26\Lib\site-packages\Twisted-11.0.0-py2.6-win32.egg\twisted
but
C:\projects\webmorda>twistd -n morda_server
Traceback (most recent call last):
File "C:\Python26\Scripts\twistd.py", line 4, in <module>
import pkg_resources
File "C:\Python27\lib\site-packages... | Twisted under windows | Twisted located at C:\Python26\Lib\site-packages\Twisted-11.0.0-py2.6-win32.egg\twisted
but
C:\projects\webmorda>twistd -n morda_server
Traceback (most recent call last):
File "C:\Python26\Scripts\twistd.py", line 4, in <module>
import pkg_resources
File "C:\Python27\lib\site-packages\pkg_resources.py", line 26... | [
"It looks like you have installed Twisted in a Python 2.6 environment but are using Python 2.7 to run it. I think the following command should work:\nC:\\Python26\\python.exe C:\\Python26\\Scripts\\twistd.py -n morda_server\n\n(It looks like the twistd.py script is being run by the python.exe binary associated with... | [
6
] | [] | [] | [
"python",
"twisted",
"windows"
] | stackoverflow_0007513626_python_twisted_windows.txt |
Q:
lambda function don't closure the parameter in Python?
Code talks more:
from pprint import pprint
li = []
for i in range(5):
li.append(lambda : pprint(i))
for k in li:
k()
yield:
4
4
4
4
4
why not
0
1
2
3
4
??
Thanks.
P.S. If I write the complete decorator, it works as expected:
from ppri... | lambda function don't closure the parameter in Python? | Code talks more:
from pprint import pprint
li = []
for i in range(5):
li.append(lambda : pprint(i))
for k in li:
k()
yield:
4
4
4
4
4
why not
0
1
2
3
4
??
Thanks.
P.S. If I write the complete decorator, it works as expected:
from pprint import pprint
li = []
#for i in range(5):
#li.... | [
"you need to do:\nlambda i=i: pprint(i)\n\ninstead to capture the current value of i\n",
"It does properly reference i, only the thing is, that by the time your list gets populated, i would have the value assigned form the last item in the sequence when the iteration ended, so that's why your seeing 4 all over.\n... | [
12,
3,
3,
0,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0007514093_lambda_python.txt |
Q:
google app engine is detecting python25 as default
hi i am trying to install Google app engine with windows MSI i have two python version on my windows one is python25 and other is python26, and i have python26 path set in my environmental variables, but Google app engine is detecting python25 as default prerequis... | google app engine is detecting python25 as default | hi i am trying to install Google app engine with windows MSI i have two python version on my windows one is python25 and other is python26, and i have python26 path set in my environmental variables, but Google app engine is detecting python25 as default prerequisite, what should i do which makes Google app engine to d... | [
"At present, Google App Engine's production servers only run Python 2.5.2. You should be using Python 2.5 on the development server as well, as having a different environment for testing and production leads to scenarios where, for example, you use syntax that's valid in 2.6 which passes your tests fine, and the un... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007514577_google_app_engine_python.txt |
Q:
From a python module, called from a pl/python function, how to get the return value?
Is there any reason this function call would not return 'result'?
CREATE OR REPLACE FUNCTION myfunction (input int, OUT result int) AS $$
result = mymodule.object(input,plpy)
plpy.info(" ========= EXTRA-module result: ===",result... | From a python module, called from a pl/python function, how to get the return value? | Is there any reason this function call would not return 'result'?
CREATE OR REPLACE FUNCTION myfunction (input int, OUT result int) AS $$
result = mymodule.object(input,plpy)
plpy.info(" ========= EXTRA-module result: ===",result)
$$ LANGUAGE plpythonu;
=== Content of mymodule ============
def object(input,plpy):
... | [
"I'm not to familiar with plpython, but if it is throwing an error and that isn't getting printed out or passed further up the chain you would never know.\nI don't know if you are testing with a command line or not but try putting a print statement in your except blocks to see if it is just erroring out instead of ... | [
1,
1
] | [] | [] | [
"plpython",
"postgresql",
"python"
] | stackoverflow_0007503572_plpython_postgresql_python.txt |
Q:
Easy to setup, multi-threaded server for my Django Piston API
I am writing an API that reads from MySQL and Solr (which can give latencies of 150ms) to provide formatted output. I will be hosting this on a VPS, and I need to choose a web server for this application. It will be used only within localhost (and local... | Easy to setup, multi-threaded server for my Django Piston API | I am writing an API that reads from MySQL and Solr (which can give latencies of 150ms) to provide formatted output. I will be hosting this on a VPS, and I need to choose a web server for this application. It will be used only within localhost (and local LAN in future).
I have these concerns:
Launches multiple worker t... | [
"Gunicorn is very simple to deploy and manage. It has no built-in reloading capability but you could easily use an external utility such as watchdog to monitor a directory and reload gunicorn using kill -HUP <pid>.\n"
] | [
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0007514212_django_django_piston_python.txt |
Q:
Entry selection list with tkinter
How can I generate a normal selection list (like the "State" field in any HTML form for postal addresses) using Python tkinter? As illustrated below, the Listbox widget displays all the selections in a large box all the time, and if you reduce the height to 1, it does not expand ... | Entry selection list with tkinter | How can I generate a normal selection list (like the "State" field in any HTML form for postal addresses) using Python tkinter? As illustrated below, the Listbox widget displays all the selections in a large box all the time, and if you reduce the height to 1, it does not expand the list when selected. The OptionMenu... | [
"You're looking for a combo box widget, TTK provides this widget:\nhttp://docs.python.org/dev/library/tkinter.ttk.html\nhttp://www.tkdocs.com/widgets/combobox.html\n",
"What you are asking for is called a combobox. If you are using an old version of python (<2.7) you can use tix.ComboBox. For python 2.7 and beyon... | [
2,
1
] | [] | [] | [
"forms",
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0007514626_forms_python_tkinter_tkinter_entry.txt |
Q:
Generate audio bell in terminal using Python
How can I generate audio bell in xterm type terminal?
A:
Simple, print the bell character. In Python:
print('\a')
From bash shell:
echo $'\a'
Note that on some terminals, the bell can be disabled. In others, the bell can be replaced with a visual bell in the shape ... | Generate audio bell in terminal using Python | How can I generate audio bell in xterm type terminal?
| [
"Simple, print the bell character. In Python:\nprint('\\a')\n\nFrom bash shell:\necho $'\\a'\n\nNote that on some terminals, the bell can be disabled. In others, the bell can be replaced with a visual bell in the shape of a flashing screen background.\n",
"print(\"\\a\") # Python 3\n\nor \nprint \"\\a\" # Python... | [
16,
3,
2
] | [] | [] | [
"python",
"xterm"
] | stackoverflow_0007514925_python_xterm.txt |
Q:
Get the locale from a string
if have a problem getting the locale out of a string like:
menu_title_en_US
menu_title_en
The locale in this string would be "en_US". The string that i have to deal with only have alphanumeric characters and underscores. Like variable names in Python.
I have tried the following regex ... | Get the locale from a string | if have a problem getting the locale out of a string like:
menu_title_en_US
menu_title_en
The locale in this string would be "en_US". The string that i have to deal with only have alphanumeric characters and underscores. Like variable names in Python.
I have tried the following regex so far:
re.compile(r'_(?P<base_cod... | [
"If you know the locale is always en, en_us, or en_US (stated in a comment), then you don't need a regex at all:\nlocale = the_string[-6:]\nif not locale.startswith('_en_'):\n locale = locale[3:]\nlocale = locale[1:]\n\nor\nlocale = the_string[-3:]\nfor code in '_en', '_en_us', '_en_US':\n if code.endswith(lo... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007514747_python_regex.txt |
Q:
unsupported operand type(s) for *: 'NoneType' and 'Decimal'
I have a django app that manages VAT. For instance, it can calculate the VAT for all sales from the European Union.
vat = purchases[0].vat.vat
eu_sales = Sale.objects.filter(country_type='2')
eu_amount = (eu_sales.aggregate(price = Sum('amount'))['pri... | unsupported operand type(s) for *: 'NoneType' and 'Decimal' | I have a django app that manages VAT. For instance, it can calculate the VAT for all sales from the European Union.
vat = purchases[0].vat.vat
eu_sales = Sale.objects.filter(country_type='2')
eu_amount = (eu_sales.aggregate(price = Sum('amount'))['price']) * vat/100
However, today I copyied my files to another ma... | [
"You could try to use a default value like this.\neu_amount = (eu_sales.aggregate(price = Sum('amount'))['price']) or 0 * vat/100\n\nBut the cleanest way is probably to test if your Sum returns nothing, then to display some kind of warning message, because this should'nt happen.\n",
"Change the line\nvat = purch... | [
5,
0,
0
] | [] | [] | [
"django",
"null",
"python",
"tags"
] | stackoverflow_0007514943_django_null_python_tags.txt |
Q:
controlling mouse with pyusb
I have to make a application, that do the followings:
disable that the given usb mouse move the pointer in the screen (just the given, not all mouses).
get the coordinates of the mouse pointer
change the y coordinate of the mouse pointer
I've tried out pyusb, but i've never found an... | controlling mouse with pyusb | I have to make a application, that do the followings:
disable that the given usb mouse move the pointer in the screen (just the given, not all mouses).
get the coordinates of the mouse pointer
change the y coordinate of the mouse pointer
I've tried out pyusb, but i've never found any examples for any of the 3 proble... | [
"I don't know enough pyusb but you can deal with the second issue with Tkinter (one of the most used GUI with Python). Here is a sample of code (found here):\n# show mouse position as mouse is moved and create a hot spot\n\nimport Tkinter as tk\n\nroot = tk.Tk()\n\ndef showxy(event):\n xm = event.x\n ym = eve... | [
1
] | [] | [] | [
"mouse",
"python",
"pyusb",
"usb"
] | stackoverflow_0007514515_mouse_python_pyusb_usb.txt |
Q:
Rounding Problem with Python
Possible Duplicate:
Python rounding error with float numbers
I have a rounding Problem in Python. If i calculate
32.50 * 0.19 = 6.1749999999999998
But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.
But if i... | Rounding Problem with Python |
Possible Duplicate:
Python rounding error with float numbers
I have a rounding Problem in Python. If i calculate
32.50 * 0.19 = 6.1749999999999998
But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.
But if i calculate this:
32.50 * 0.19 * 3... | [
"What Every Computer Scientist Should Know About Floating-Point Arithmetic.\nIn short - you should not rely on precise values of float numbers because of the way they are stored in the memory. \nSee also python docs about it - Floating Point Arithmetic: Issues and Limitations. It contains the next passage:\n\nFor e... | [
7,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"rounding"
] | stackoverflow_0007515266_python_rounding.txt |
Q:
Making 'isinstance' work with decorators
How does the Python isinstance function work internally? Is there anything I can do to alter its results, like define a special function inside a class or something? Here's my use case:
class Decorator:
def __init__(self, decorated):
self._decorated = decorated
... | Making 'isinstance' work with decorators | How does the Python isinstance function work internally? Is there anything I can do to alter its results, like define a special function inside a class or something? Here's my use case:
class Decorator:
def __init__(self, decorated):
self._decorated = decorated
def __call__(self):
return self._... | [
"How about the following:\ndef Decorator(decorated):\n class Dec(decorated):\n def __call__(self):\n print 'in decorated __call__'\n return decorated.__call__(self)\n return Dec\n\n@Decorator\nclass Foo(object):\n def __call__(self):\n print 'in original __call__'\n\nf =... | [
6,
1,
0
] | [
"You can't get type of the object that Foo returns without calling Foo.\nisinstance complains about its second argument because it is an instance - in you case instance of Decorated. Although you think of Foo like a class but actually it is just a callable object and it is not a class.\nMaybe the next will help yo... | [
-1
] | [
"decorator",
"isinstance",
"python"
] | stackoverflow_0007514968_decorator_isinstance_python.txt |
Q:
Evaluating math expression on dictionary variables
I'm doing some work evaluating log data that has been saved as JSON objects to a file.
To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
Now I'd ... | Evaluating math expression on dictionary variables | I'm doing some work evaluating log data that has been saved as JSON objects to a file.
To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
Now I'd like to be able to evaluate simple mathematical operatio... | [
"eval optionally takes a globals and locals dictionaries. You can therefore do this:\nnamespace = dict(foo=5, bar=6)\nprint eval('foo*bar', namespace)\n\nKeep in mind that eval is \"evil\" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.\nFor completne... | [
2,
1
] | [] | [] | [
"evaluation",
"logging",
"math",
"python"
] | stackoverflow_0007515397_evaluation_logging_math_python.txt |
Q:
Re-evaluating a var in python
Consider the following pseudo-code:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
lambda var: return var+1
1) myFunc = func(Attribute().get())
2) myFunc()
3) myFunc()
Now, when I call myFunc() in... | Re-evaluating a var in python | Consider the following pseudo-code:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
lambda var: return var+1
1) myFunc = func(Attribute().get())
2) myFunc()
3) myFunc()
Now, when I call myFunc() in line 2 I get a random value from 0... | [
"Yes, there is:\nimport random\n\nclass Attribute(object):\n def __init__(self):\n self.value = 0\n def get(self):\n self.value = random.random() * 10\n return self.value\n\ndef func(fn):\n return lambda: fn() + 1\n\natt = Attribute()\nmyFunc = func(att.get)\nprint myFunc()\nprint myFunc()\n... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007515499_python.txt |
Q:
Trouble executing JQuery Flot from CGI script
I'm currently testing a webservice on my local machine using Apache (on Windows XP). I have a Python CGI script that calls the services and generates html output that can be viewed in a browser. I recently came across Flot, which would enable me to plot my web servic... | Trouble executing JQuery Flot from CGI script | I'm currently testing a webservice on my local machine using Apache (on Windows XP). I have a Python CGI script that calls the services and generates html output that can be viewed in a browser. I recently came across Flot, which would enable me to plot my web service results.
So, I downloaded all the Flot librari... | [
"I figured it out... the problem was that the javascript libraries had to be put in the 'htdocs' folder. Then, the javascript path in the html had to be adjusted such that it is relative to the 'htdocs' directory.\ne.g.\n<script language=\"javascript\" type=\"text/javascript\" src=\"/js/jquery.flot.js\"></script>\... | [
0
] | [] | [] | [
"cgi",
"flot",
"jquery",
"python"
] | stackoverflow_0007502212_cgi_flot_jquery_python.txt |
Q:
Exchange Web Services (EWS) - Exchange 2010 soap calls via suds
Im trying to send an email via Exchange Web Services using suds 0.4.1:
import suds
from suds.client import Client
from suds.transport.https import WindowsHttpAuthenticated
url = "file:///C:/Services.wsdl"
user = 'domain\\user'
password = "hardtog... | Exchange Web Services (EWS) - Exchange 2010 soap calls via suds | Im trying to send an email via Exchange Web Services using suds 0.4.1:
import suds
from suds.client import Client
from suds.transport.https import WindowsHttpAuthenticated
url = "file:///C:/Services.wsdl"
user = 'domain\\user'
password = "hardtoguess"
ntlm = WindowsHttpAuthenticated(username=user,password=passwor... | [
"I've also been experiencing this issue. However, I only get this error intermittently. I found another post referring to a possible solution, and it helps some (I get the error less) but it hasn't fixed the issue completely.\nThe problem seems to be that the Exchange server closes the connection before sending a v... | [
1
] | [] | [] | [
"exchange_server",
"exchangewebservices",
"httplib",
"python",
"suds"
] | stackoverflow_0007505653_exchange_server_exchangewebservices_httplib_python_suds.txt |
Q:
Can obj.__dict__ be inspected if the class has a __dict__ variable?
I am interested in whether there is a way to introspect a Python instance infallibly to see its __dict__ despite any obstacles that the programmer might have thrown in the way, because that would help me debug problems like unintended reference lo... | Can obj.__dict__ be inspected if the class has a __dict__ variable? | I am interested in whether there is a way to introspect a Python instance infallibly to see its __dict__ despite any obstacles that the programmer might have thrown in the way, because that would help me debug problems like unintended reference loops and dangling resources like open files.
A simpler example is: how can... | [
"I'm not sure I'm happy with how simple this is:\n>>> class DunderDictHider(object):\n... __dict__ = {'fake': 'dict'}\n... \n>>> ddh = DunderDictHider()\n>>> ddh.a = 1\n>>> ddh.b = 2\n>>> \n>>> print ddh.a\n1\n>>> print ddh.__dict__\n{'fake': 'dict'}\n\nThe problem is that the class is cheating? Fix that!\n>>>... | [
1,
0
] | [] | [] | [
"class",
"inheritance",
"internals",
"introspection",
"python"
] | stackoverflow_0007511664_class_inheritance_internals_introspection_python.txt |
Q:
Tuple Numpy Data Type
I currently am reading in colors from a sqlite database in the following way:
import numpy as np, apsw
connection = apsw.Connection(db_name)
cursor = connection.cursor()
desc = {'names':('name','R','G','B'),'formats':('a3','float','float','float')}
colorlist = np.array(cursor.execute("SELECT ... | Tuple Numpy Data Type | I currently am reading in colors from a sqlite database in the following way:
import numpy as np, apsw
connection = apsw.Connection(db_name)
cursor = connection.cursor()
desc = {'names':('name','R','G','B'),'formats':('a3','float','float','float')}
colorlist = np.array(cursor.execute("SELECT name, R, G, B FROM Colors")... | [
"Do you literally need a tuple? Or do you just want the values to be grouped? You can create a numpy record array with arbitrary shapes for each of the fields...\n>>> np.array([('ABC', (1, 2, 3)), ('CBA', (3, 2, 1))], dtype='3a, 3i')\narray([('ABC', [1, 2, 3]), ('CBA', [3, 2, 1])], \n dtype=[('f0', '|S3'), ('f... | [
6
] | [] | [] | [
"numpy",
"python",
"sqlite"
] | stackoverflow_0007515659_numpy_python_sqlite.txt |
Q:
Calling class function from module?
I am just writing some dummy code for pygame.
The first sample of code has a function in the menus.py file. I wanted to practice using import. This works fine. I then wanted to put the function in a class so I can get up and running with classes. This is the second block of code... | Calling class function from module? | I am just writing some dummy code for pygame.
The first sample of code has a function in the menus.py file. I wanted to practice using import. This works fine. I then wanted to put the function in a class so I can get up and running with classes. This is the second block of code. Unfortunately the second block of code ... | [
"That is not problem with import. Since color_switcher is not static method, you must first create class instance, and only then call a member function:\nif event.type == pygame.MOUSEBUTTONDOWN:\n menus.Menu().color_switcher(counter, screen)\n\nAlternatively, you can declare your class as \nclass Menu:\n @st... | [
2,
2,
1,
1
] | [] | [] | [
"class_method",
"python"
] | stackoverflow_0007515901_class_method_python.txt |
Q:
Referencing a related object in Pyramids/Python/SQLAlchemy
I'm not sure how to title this question. I've also simplified my code so it's easier to ask. Say I have the following code in myproject.models in Pyramid:
class Links(Base):
__tablename__ = 'links'
id = Column(Integer, primary_key=True)
link = ... | Referencing a related object in Pyramids/Python/SQLAlchemy | I'm not sure how to title this question. I've also simplified my code so it's easier to ask. Say I have the following code in myproject.models in Pyramid:
class Links(Base):
__tablename__ = 'links'
id = Column(Integer, primary_key=True)
link = Column(Text)
def __init__(self, link):
self.link = ... | [
"In your example, you are missing the .all() after your .query(). You can check in your view if your submissions are really loaded by doing something like\nfor submission in submissions:\n print submission.id, submission.title\n\nand then watch your console when loading the page.\nThen, when you confirmed you re... | [
2,
0
] | [] | [] | [
"chameleon",
"pyramid",
"python",
"sqlalchemy",
"template_tal"
] | stackoverflow_0007507108_chameleon_pyramid_python_sqlalchemy_template_tal.txt |
Q:
Python:JS: How to parse multiple kml node in one xml file?
<xml>
<mapshape title="Bar" extras="">
<kml></kml>
</mapshape>
<mapshape title="Foo" extras="">
<kml></kml>
</mapshape>
</xml>
I've got a xml doc like that, multiple mapshape nodes in one xml, and each contains one valid kml file.... | Python:JS: How to parse multiple kml node in one xml file? | <xml>
<mapshape title="Bar" extras="">
<kml></kml>
</mapshape>
<mapshape title="Foo" extras="">
<kml></kml>
</mapshape>
</xml>
I've got a xml doc like that, multiple mapshape nodes in one xml, and each contains one valid kml file. I need to plot them all on google maps.
I have tried libraries ... | [
"You can use lxml to extract the kml sections and then pass them on to the other library:\ndoc = \"\"\"<xml>\n <mapshape title=\"Bar\" extras=\"\">\n <kml></kml>\n </mapshape>\n\n <mapshape title=\"Foo\" extras=\"\">\n <kml></kml>\n </mapshape>\n</xml>\"\"\"\n\nimport lxml.etree as etree\n\nxml = ... | [
0
] | [] | [] | [
"google_maps_api_3",
"python"
] | stackoverflow_0007515718_google_maps_api_3_python.txt |
Q:
ØMQ multithreaded REQ/REP
I'm trying to write an application that will allow the user to start long-running calculation processes which will receive commands from a web server using ØMQ. I use standart request-reply architecture: server has a REQ socket connected to a worker processes REP socket. When a new comman... | ØMQ multithreaded REQ/REP | I'm trying to write an application that will allow the user to start long-running calculation processes which will receive commands from a web server using ØMQ. I use standart request-reply architecture: server has a REQ socket connected to a worker processes REP socket. When a new command is received from a user, it i... | [
"For REQ/REP, the second command must not be sent until the first one has been acknowledged; ZMQ enforces the correct ordering of messages in the protocol.\nYou might want to use PUSH/PULL instead - the messages will then be queued up automatically without requiring replies in between (as an aside, I think this als... | [
4
] | [] | [] | [
"python",
"zeromq"
] | stackoverflow_0007516139_python_zeromq.txt |
Q:
Extra variables on a custom 404 template
I want to be able to use extra variables on a custom 404 template.
#404.html
{{ extra_var }}
I have already tried:
#urls.py
from myproject.myapp import views
handler404 = views.handler404
#views.py
from django.template import RequestContext, loader
from django import http... | Extra variables on a custom 404 template | I want to be able to use extra variables on a custom 404 template.
#404.html
{{ extra_var }}
I have already tried:
#urls.py
from myproject.myapp import views
handler404 = views.handler404
#views.py
from django.template import RequestContext, loader
from django import http
def handler404(request):
extra_var = 'my_... | [
"I had a similar problem.\nhandler404 should be set in the urls.py file, but you also have to import it, and that's not in the docs.\n\nadd handler404 to your imports\nfrom django.conf.urls.defaults import patterns, include, url, handler404\n\nset handler404=\"string.of.the.view.to.load\"\nhandler404=\"myApp.views.... | [
3,
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002086715_django_django_templates_python.txt |
Q:
sequentially send stdout from subprocess.Popen via socket
I know this has been anwered many times before, but I haven't find a working way to do this in my scenario... I hope you will help.
I want to output the data from stdout and/or stderr from a Popen call in real time, to a socket connection, not to stdout. So... | sequentially send stdout from subprocess.Popen via socket | I know this has been anwered many times before, but I haven't find a working way to do this in my scenario... I hope you will help.
I want to output the data from stdout and/or stderr from a Popen call in real time, to a socket connection, not to stdout. So sys.stdout.flush() don't work for me.
data=sok.recv(512) #the... | [
"p.poll() indicates whether the process is executing. So it returns false as soon as the program exits. So that's not what you should be checking.\nyour code:\nfor i in p.stdout.readline():\n\nreads a single line and then iterates over each letter in that line. Not what you wanted. Use:\nfor i in p.stdout.readlines... | [
3
] | [] | [] | [
"popen",
"python",
"sockets",
"subprocess"
] | stackoverflow_0007516672_popen_python_sockets_subprocess.txt |
Q:
Python - single vs multiline REGEX
Considering the following text pattern,
#goals: the process report timestamp, eg. 2011-09-21 15:45:00 and the first two stats in succ. statistics line, eg: 1438 1439
input_text = '''
# Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n
som... | Python - single vs multiline REGEX | Considering the following text pattern,
#goals: the process report timestamp, eg. 2011-09-21 15:45:00 and the first two stats in succ. statistics line, eg: 1438 1439
input_text = '''
# Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other line... | [
"Use re.DOTALL so . will match any character, including newlines:\nimport re\n\ndata = '''\n# Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\\n\nsome line 1\\n\nsome line 2\\n\nsome other lines\\n\nsucc. statistics | 1438 1439 99 | 3782245 3797376 99 |\\n\nsome li... | [
13
] | [] | [] | [
"multiline",
"pattern_matching",
"python",
"regex"
] | stackoverflow_0007517227_multiline_pattern_matching_python_regex.txt |
Q:
Python 2.5 time.time() as decimal
Is it possible to receive the output of time.time() in Python 2.5 as a Decimal?
If not (and it has to be a float), then is it possible to guarantee that inaccuracy will always be more than (rather than less than) the original value. In other words:
>>> repr(0.1)
'0.100000000000000... | Python 2.5 time.time() as decimal | Is it possible to receive the output of time.time() in Python 2.5 as a Decimal?
If not (and it has to be a float), then is it possible to guarantee that inaccuracy will always be more than (rather than less than) the original value. In other words:
>>> repr(0.1)
'0.10000000000000001' # More than 0.1 which is what I wan... | [
"You could simply multiple time.time() by some value to get the precision you want (note that many calls can't guarantee sub-second accuracy anyways). So,\nstartTime = int(time.time() * 100)\n#...\nendTime = int(time.time() * 100)\n\nWill satisfy your condition that endTime - startTime >= sleepTime\n",
"You coul... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007517380_python.txt |
Q:
How to search for words containg certain letters in a txt file with Python?
Look at the code below. This finds the letter 'b' containing in the text file and prints all the words containing the letter 'b' right?
x = open("text file", "r")
for line in x:
if "b" and in line: print line
searchfile.close()
Now h... | How to search for words containg certain letters in a txt file with Python? | Look at the code below. This finds the letter 'b' containing in the text file and prints all the words containing the letter 'b' right?
x = open("text file", "r")
for line in x:
if "b" and in line: print line
searchfile.close()
Now here is my problem. I would like to search with not only one, but several letters.... | [
"No, your code (apart from the fact that it's syntactically incorrect), will print every line that has a \"b\", not the words.\nIn order to do what you want to do, we need more information about the text file. Suppossing words are separated by single spaces, you could do something like this\nx = open(\"file\", \"r\... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007517221_python.txt |
Q:
How does Remember the Milk's string matching work?
I'm interested in developing a similar solution to RTM's Smart Add Feature.
For those who don't know Remember the Milk here's how it works: Adding tasks is done by means of an input box that accepts strings and parses out different parameters like task name, due ... | How does Remember the Milk's string matching work? | I'm interested in developing a similar solution to RTM's Smart Add Feature.
For those who don't know Remember the Milk here's how it works: Adding tasks is done by means of an input box that accepts strings and parses out different parameters like task name, due date, priority, tags, etc. The parameters are usually pr... | [
"I assume they have some grammars for parsing input sentece. Those grammar can express variety of NLP structures, such es entity extraction. For those grammar one can use GATE JAPE(http://gate.ac.uk/sale/tao/splitch8.html#chap:jape) or Gexp(http://code.google.com/p/graph-expression/)\n"
] | [
2
] | [] | [] | [
"matching",
"nlp",
"python",
"regex"
] | stackoverflow_0007508487_matching_nlp_python_regex.txt |
Q:
How can i print a list contents in a stderr statement in python
Here is the scenario:
I want to be able to print the C Style statement:
print >> sys.stderr, ("%s does not exist"%m_args)
either inside the function, or in __main__
but I am getting Exception :
print >> sys.stderr, ("%m_args[1] does not exist"%m_args... | How can i print a list contents in a stderr statement in python | Here is the scenario:
I want to be able to print the C Style statement:
print >> sys.stderr, ("%s does not exist"%m_args)
either inside the function, or in __main__
but I am getting Exception :
print >> sys.stderr, ("%m_args[1] does not exist"%m_args[1])
IndexError: list index out of range
Code:
#!/usr/bin/env pytho... | [
"Look at this line:\nprint >> sys.stderr, (\"%s does not exist\"%m_args)\n\nfrom the verify_commit_text() function. \nNow, look at the line causing the error in __main__:\nprint >> sys.stderr, (\"%m_args[0] does not exist\"%m_args[0])\n\nYou need to replace the %m_args[0] inside the string with %s.\nAlso, you're us... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007517756_python.txt |
Q:
Python : Check if IRC connection is lost (PING PONG?)
So my question is, how would i get my bot to listen if there is a PING and if there's no ping in an interval of a minute, it will react as though the connection has been lost. How would one go about doing that?
EDIT:
This is the working code for registering th... | Python : Check if IRC connection is lost (PING PONG?) | So my question is, how would i get my bot to listen if there is a PING and if there's no ping in an interval of a minute, it will react as though the connection has been lost. How would one go about doing that?
EDIT:
This is the working code for registering the connection fallout (although having trouble with reconnec... | [
"last_ping = time.time()\nthreshold = 5 * 60 # five minutes, make this whatever you want\nwhile connected:\n data = irc.recv ( 4096 )\n # If Nick is in use\n if data.find ( 'Nickname is already in use' ) != -1:\n NICK = NICK + str(time.time())\n Connection()\n # Ping Pong so we don't get d... | [
6,
3,
2,
0
] | [] | [] | [
"irc",
"python"
] | stackoverflow_0006853071_irc_python.txt |
Q:
How to decode bitmap images using python's email class
Hello I have python script that takes apart an email from a string. I am using the get_payload(decode=True) function from the email class and it works great for pdf's and jpg's but it does not decode bmp files. The file is still encoded base64 when I write it ... | How to decode bitmap images using python's email class | Hello I have python script that takes apart an email from a string. I am using the get_payload(decode=True) function from the email class and it works great for pdf's and jpg's but it does not decode bmp files. The file is still encoded base64 when I write it to disk.
Has anyone come across this issue themselves?
| [
"OK so I finally found the problem and it was not related to the python mail class at all. I was reading from a named pipe using the .read() function and it was not reading the entire email from the pipe. I had to pass the read function a size argument and then it was able to read the entire email. So ultimately th... | [
0
] | [] | [] | [
"email",
"mime",
"python"
] | stackoverflow_0007505410_email_mime_python.txt |
Q:
expat for IronPython 2.7.1 beta 2
I'm trying to get NLTK working with IronPython 2.7.1. The installation works so far, but I tried some sample code and the expat module is missing. Any hint how to get that up and running for IronPython? I found some hints on the web, but they are quite outdated (IronPython 2.0) an... | expat for IronPython 2.7.1 beta 2 | I'm trying to get NLTK working with IronPython 2.7.1. The installation works so far, but I tried some sample code and the expat module is missing. Any hint how to get that up and running for IronPython? I found some hints on the web, but they are quite outdated (IronPython 2.0) and are using python projects which seem ... | [
"The version from the old FePy project (here) should still work, but it's incomplete and might not have all of the capabilities NLTK needs.\n"
] | [
2
] | [] | [] | [
"ironpython",
"nltk",
"python"
] | stackoverflow_0007511538_ironpython_nltk_python.txt |
Q:
Automating a directory diff while ignoring some particular lines in files
I need to compare two directories, and produce some sort of structured output (text file is fine) of the differences. That is, the output might looks something like this:
file1 exists only in directory2
file2 exists only in directory1
file3... | Automating a directory diff while ignoring some particular lines in files | I need to compare two directories, and produce some sort of structured output (text file is fine) of the differences. That is, the output might looks something like this:
file1 exists only in directory2
file2 exists only in directory1
file3 is different between directory1 and directory2
I don't care about the format,... | [
"To some extent, the plain old diff command can do just that, i.e. compare directory contents and ignoring changes that match a certain regex pattern (Using the -I option).\nFrom man bash:\n-I regexp\n Ignore changes that just insert or delete lines that match regexp.\n\nQuick demo:\n[me@home]$ diff images/ i... | [
1
] | [] | [] | [
"araxis",
"diff",
"python",
"regex"
] | stackoverflow_0007517850_araxis_diff_python_regex.txt |
Q:
New error in supervisord on Ubuntu
This error seems to have shown up in the latest set of upgrades on ubuntu
Traceback (most recent call last):
File "/usr/local/bin/supervisord", line 9, in <module>
load_entry_point('supervisor==3.0a10', 'console_scripts', 'supervisord')()
File "/usr/local/lib/python2.6/dis... | New error in supervisord on Ubuntu | This error seems to have shown up in the latest set of upgrades on ubuntu
Traceback (most recent call last):
File "/usr/local/bin/supervisord", line 9, in <module>
load_entry_point('supervisor==3.0a10', 'console_scripts', 'supervisord')()
File "/usr/local/lib/python2.6/dist-packages/supervisor-3.0a10-py2.6.egg/s... | [
"_get_default_tempdir just checks access to the temp dirs by writing and deleting a random file into temp dir. So you might want to check permissions on your temp dirs: '/tmp', '/var/tmp', '/usr/tmp', '/usr/lib/python2.6'\n",
"As it turns out, the disk was full. \n"
] | [
4,
4
] | [] | [] | [
"node.js",
"python",
"supervisord",
"ubuntu"
] | stackoverflow_0007518297_node.js_python_supervisord_ubuntu.txt |
Q:
error :: UnicodeDecodeError
I am getting
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 104: ordinal not in range(128)
I am using intgereproparty, stringproparty, datetimeproparty
A:
That's because 0xb0 (decimal 176) is not a valid character code in ASCII (which defines only values betwee... | error :: UnicodeDecodeError | I am getting
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 104: ordinal not in range(128)
I am using intgereproparty, stringproparty, datetimeproparty
| [
"That's because 0xb0 (decimal 176) is not a valid character code in ASCII (which defines only values between 0 and 127).\nCheck where you got that string from and use the proper encoding.\nIf you need further help, post the code.\n",
"You are trying to put Unicode data (probably text with accents) into an ASCII s... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002462166_python.txt |
Q:
Python text search question
I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
An... | Python text search question | I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
And the letter 'a' always has to be... | [
"Let's see...\nreturn [x for x in document.split()\n if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3]\n\nsplit with no parameters acts as a \"words\" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' i... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007518255_python.txt |
Q:
Convert url encoded string into python unicode string
I have strings encoded in the following form: La+Cit%C3%A9+De+la+West that I stored in a SQLite VARCHAR field in python.
These are apparently UTF-8 encoded binary strings converted to urlencoded strings.
The question is how to convert it back to a unicode stri... | Convert url encoded string into python unicode string | I have strings encoded in the following form: La+Cit%C3%A9+De+la+West that I stored in a SQLite VARCHAR field in python.
These are apparently UTF-8 encoded binary strings converted to urlencoded strings.
The question is how to convert it back to a unicode string.
s = 'La+Cit%C3%A9+De+la+West'
I used the urllib.unquote... | [
"As we discussed, it looks like the problem was that you were starting with a unicode object, not a string. You want a string:\n>>> import urllib\n>>> s1 = u'La+Cit%C3%A9+De+la+West'\n>>> type(s1)\n<type 'unicode'>\n>>> print urllib.unquote_plus(s1)\nLa Cité De la West\n\n>>> s2 = str(s1)\n>>> type(s2)\n<type 'st... | [
6
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0007519109_python_unicode.txt |
Q:
Using Ctypes to wrap .LIB files
I need to control a device in python using Ctypes. However, the libraries that come with the device are compiled .LIB files, not .DLLs. Is it still possible to use Ctypes?
A:
No. Not directly anyway. CTypes uses the dynamic linker (LoadLibrary, GetProcAddress) to work. You could w... | Using Ctypes to wrap .LIB files | I need to control a device in python using Ctypes. However, the libraries that come with the device are compiled .LIB files, not .DLLs. Is it still possible to use Ctypes?
| [
"No. Not directly anyway. CTypes uses the dynamic linker (LoadLibrary, GetProcAddress) to work. You could wrap the LIB file in your own DLL possibly, but you won't be able to use Ctypes directly with the lib file.\n"
] | [
2
] | [] | [] | [
"ctypes",
"dll",
"python"
] | stackoverflow_0007519152_ctypes_dll_python.txt |
Q:
python3: list() from generator: strange behaviour when yielding item-changed lists
I have a generator defined like this:
def gen():
r = [0]
yield r
r[0] = 1
yield r
r[0] = 2
yield r
it will yield three lists of one element going from 0 to 2:
>>> a = gen()
>>> next(a)
[0]
>>> next(a)
[1]
>>... | python3: list() from generator: strange behaviour when yielding item-changed lists | I have a generator defined like this:
def gen():
r = [0]
yield r
r[0] = 1
yield r
r[0] = 2
yield r
it will yield three lists of one element going from 0 to 2:
>>> a = gen()
>>> next(a)
[0]
>>> next(a)
[1]
>>> next(a)
[2]
>>> next(a)
Traceback (most recent call last):
File "<pyshell#313>", lin... | [
"It's not a bug, it does exactly what you told it to do. You're yielding the very same object several times, so you get several references to that object. The only reason you don't see three [2]s in your first snippet is that Python won't go back in time and change previous output to match when objects are mutated.... | [
2,
0
] | [] | [] | [
"generator",
"python",
"python_3.x"
] | stackoverflow_0007503639_generator_python_python_3.x.txt |
Q:
python function to break a message in n lines
Hy everyone, i want to do something like this but my logic is not so goog. I have a message, that must be 80 chars in every line: I can do this like this:
msg = ''
msg_list = []
for i in dict['msg']:
if len(msg) >= 80 and i.isspace():
msg_list.append(msg)
... | python function to break a message in n lines | Hy everyone, i want to do something like this but my logic is not so goog. I have a message, that must be 80 chars in every line: I can do this like this:
msg = ''
msg_list = []
for i in dict['msg']:
if len(msg) >= 80 and i.isspace():
msg_list.append(msg)
msg = ""
msg += i
The problem here is when m... | [
"import textwrap\nmsg_list = textwrap.wrap(dict['msg'], 80)\n\n",
"import re\n\ninput = \"put your text in here\"\ntokens = re.split('\\s', input)\n\nw = []\ns = \"\"\nfor token in tokens:\n if len(s) + len(token) < 80:\n s = \" \".join([s,token])\n else:\n w.append(s)\n s = \"\"\nprint... | [
9,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007518432_python.txt |
Q:
Python regex gotcha
Could you explain me why the first regex doesn't match?
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>
A:
r... | Python regex gotcha | Could you explain me why the first regex doesn't match?
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>
| [
"re.match() tries to match from the beginning of the string.\nUse re.search() instead if you want to locate a match anywhere in the string.\nPS: You might want to escape the ., because it's a metacharacter that matches any1 character (so x0 would match your second example).\n>>> re.match(r'\\.\\d', 'x0')\n>>> re.ma... | [
8,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007519493_python_regex.txt |
Q:
How do I make a query where it filters everything that starts with a number in Django?
I have a model called Book with a Title Field.
class Book(models.Model):
title = models.CharField(null = False,blank=False)
Now I need a filter to get all books with titles starting with a number.
This works but how will I ... | How do I make a query where it filters everything that starts with a number in Django? | I have a model called Book with a Title Field.
class Book(models.Model):
title = models.CharField(null = False,blank=False)
Now I need a filter to get all books with titles starting with a number.
This works but how will I extend the queryset?
b = Book.objects.filter(title__startswith = 1).order_by('title')
This ... | [
"You can use a regular expression as a query parameter to check that the a value starts with a number:\nBook.objects.filter(title__regex=r'^\\d')\n\n"
] | [
8
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0007519419_django_django_queryset_python.txt |
Q:
Creating a screenshot of a gtk.Window
For testing and documentation purposes I would like to create a screenshot of a gtk.Window object. I'm following a basic pygtk sample at the moment. The example with my modifications looks like the following:
import gtk
def main():
button = gtk.Button("Hello")
scroll_... | Creating a screenshot of a gtk.Window | For testing and documentation purposes I would like to create a screenshot of a gtk.Window object. I'm following a basic pygtk sample at the moment. The example with my modifications looks like the following:
import gtk
def main():
button = gtk.Button("Hello")
scroll_win = gtk.ScrolledWindow()
scroll_win.a... | [
"The key difference to understand is that gtk.gdk.Window isn't a \"window\" in the sense that most people think of. It's not a GUI element, it's just a section of the screen that acts as a logical display area, as explained in the documentation. In that way, it is more of a low-level object.\nA gtk.Window object (t... | [
11
] | [] | [] | [
"gtk",
"pygtk",
"python",
"screenshot"
] | stackoverflow_0007518376_gtk_pygtk_python_screenshot.txt |
Q:
PyGTK Spacing in an HBox
I'm new to GTK, I'm trying to figure out how to accomplish something like this:
+---+------+---+
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
+---+------+---+
I want this done in an HBox. How would I accomplish this? Thanks.
A:
It... | PyGTK Spacing in an HBox | I'm new to GTK, I'm trying to figure out how to accomplish something like this:
+---+------+---+
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
+---+------+---+
I want this done in an HBox. How would I accomplish this? Thanks.
| [
"It is done with \"packing\".\nI always keep the class reference under my pillow : http://www.pygtk.org/docs/pygtk/gtk-class-reference.html\nSamples in the good tutorial found here :\nhttp://www.pygtk.org/pygtk2tutorial/sec-DetailsOfBoxes.html\nAnd finally, this shows up something like your drawing :\nimport gtk as... | [
0,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0007508651_gtk_pygtk_python.txt |
Q:
How to break down a number with another from list?
I'm a bit confused on how to approach this problem. I know what I want to do but can't wrap my head on how to logically solve this problem.
say I have a list:
numlist = [10,4]
and I have the following values in another list:
datalist = [10,5,4,2,1]
how do I brea... | How to break down a number with another from list? | I'm a bit confused on how to approach this problem. I know what I want to do but can't wrap my head on how to logically solve this problem.
say I have a list:
numlist = [10,4]
and I have the following values in another list:
datalist = [10,5,4,2,1]
how do I break down the numbers in numlist using only numbers from da... | [
"This problem is very similar to Problem 31 of Project Euler: \"How many different ways can £2 be made using any number of coins?\". Only in your example, you are asking to enumerate all the ways you can add up numbers to get 10 and 4. \nThe best way to approach the problem is to first try breaking up only a single... | [
3
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0007519259_algorithm_python.txt |
Q:
Most efficient way to build a 1-d array/list/vector of unknown length using Cython? Or should this never be done?
I have a time-critical model that I wrote in Cython. The main function of my Cython extension has one loop, and according to the Cython profiler (where it shows the amount of Python calls in shades of ... | Most efficient way to build a 1-d array/list/vector of unknown length using Cython? Or should this never be done? | I have a time-critical model that I wrote in Cython. The main function of my Cython extension has one loop, and according to the Cython profiler (where it shows the amount of Python calls in shades of yellow) the only 'yellow' part is currently where I'm appending to a Python list. (I have to output a Python object as ... | [
"build1darray.pyx:\n\nspecifies types for index variables\nturns off safety checks\ncan uses multiple cpus (it is useful for large t and v.size())\n\n\n#cython: boundscheck=False, wraparound=False\nfrom libc.math cimport log\n\nfrom cython.parallel cimport prange\n\nimport numpy as pynp\ncimport numpy as np\n\n# co... | [
4,
3,
0
] | [] | [] | [
"c",
"cython",
"python"
] | stackoverflow_0007403966_c_cython_python.txt |
Q:
Help me understanding python's logging module and its handlers
I really miss something basic about python's logging module.
In the following code, I create a logger object (log) and add to it two handlers. One with
'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect ... | Help me understanding python's logging module and its handlers | I really miss something basic about python's logging module.
In the following code, I create a logger object (log) and add to it two handlers. One with
'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect that calling to log.info(msg)
will result in one copy of msg in my s... | [
"There are two things you need to know:\n\nThe root logger is initialized with a level of WARNING.\nAny log message that reaches a logger is discarded if its level is below the logger's level. If a logger's level is not set, it will take its \"effective level\" from its parent logger. So if the root logger has a le... | [
7,
3
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0007519351_logging_python.txt |
Q:
Merge multiple *.csv, *.txt, or *.ascii files based on a common field using python
I want to merge about 8 *.csv files into one.
An example file:
ID, Average
34, 4.5
35, 5.6
36, 3.4
Another file could be:
ID, Max
34, 6
35, 7
36, 4
And I need the output to be:
ID, Average, Max
34, 4.5, 6
35, 5.6, 7
36, 3.4, 4
Th... | Merge multiple *.csv, *.txt, or *.ascii files based on a common field using python | I want to merge about 8 *.csv files into one.
An example file:
ID, Average
34, 4.5
35, 5.6
36, 3.4
Another file could be:
ID, Max
34, 6
35, 7
36, 4
And I need the output to be:
ID, Average, Max
34, 4.5, 6
35, 5.6, 7
36, 3.4, 4
This only half works.... it appends all the data into the same two columns.
import glob, s... | [
"You have three problems here.\n\nRead in each of the csv files\nMerge on a common field\nWrite the merged data to a new csv file\n\nCode\n#!/usr/bin/env python\nimport argparse, csv\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='merge csv files on field', version='%(prog)s 1.0')\n... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007519412_python.txt |
Q:
Translating pysnmp numerical oid output into symbolic names
I wrote a script (below) to test how well I could use pysnmp in one of my applications. I need to be able to mib-walk network elements with names like ifDescr, and my output needs to reference the same name I queried with...
from pysnmp.smi import builde... | Translating pysnmp numerical oid output into symbolic names | I wrote a script (below) to test how well I could use pysnmp in one of my applications. I need to be able to mib-walk network elements with names like ifDescr, and my output needs to reference the same name I queried with...
from pysnmp.smi import builder, view, error
from pysnmp.entity.rfc3413.oneliner import cmdgen
... | [
"Generally speaking, to convert between OIDs and symbolic names you are to use a MIB viewer component.\nWhen you use pysnmp \"oneliner\" API, this conversion is invoked implicitly for your input OIDs/symbols. However it needs to be performed explicitly for your output OIDs (and possibly for values as well).\nSee th... | [
2,
0
] | [] | [] | [
"pysnmp",
"python",
"snmp"
] | stackoverflow_0007473467_pysnmp_python_snmp.txt |
Q:
missing lines while appending files
I am new to both stackoverflow and python, so this might look obvious:
In this procedure I want to create a new file named database out of a list of files generated by a previous procedure. The files in the list are quite big (around 13.6 MB). The goal is to have a single file w... | missing lines while appending files | I am new to both stackoverflow and python, so this might look obvious:
In this procedure I want to create a new file named database out of a list of files generated by a previous procedure. The files in the list are quite big (around 13.6 MB). The goal is to have a single file with lines from all other:
database = ope... | [
"I'm going to use my psychic debugging skills, and guess that you don't have a database.close().\nIf you don't close the file when writing to it, there may still be data in the Python output buffers that hasn't been written to the OS yet. If your program exits at that point, then the data is not written to disk and... | [
5
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0007520473_file_io_python.txt |
Q:
syntax error with KeyError in python 3.2
I'm a beginner using python 3.2 and i have a book whos code is all in python 2.6. i wrote part of a program and keep getting:
Syntax Error: invalid syntax
Then python's IDLE highlights the comma after KeyError in my code:
from tank import Tank
tanks = { "a":Tank("Alice"), ... | syntax error with KeyError in python 3.2 | I'm a beginner using python 3.2 and i have a book whos code is all in python 2.6. i wrote part of a program and keep getting:
Syntax Error: invalid syntax
Then python's IDLE highlights the comma after KeyError in my code:
from tank import Tank
tanks = { "a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol")}
alive_tank... | [
"Instead of\nexcept KeyError, name:\n\ntry\nexcept KeyError as name:\n\nIts a difference between Python 2.x and Python 3.x. The first form is no longer supported.\n"
] | [
20
] | [] | [] | [
"python",
"python_3.x",
"syntax"
] | stackoverflow_0007520690_python_python_3.x_syntax.txt |
Q:
Python subprocess.Popen slow under uWSGI
I've set up a development server running Cherokee on Fedora 14, using uWSGI to interface with my WSGI application.
When the application is hit with the first request, I spawn a process like so:
from subprocess import Popen
Popen(['bash']) # bash is just an example; the pro... | Python subprocess.Popen slow under uWSGI | I've set up a development server running Cherokee on Fedora 14, using uWSGI to interface with my WSGI application.
When the application is hit with the first request, I spawn a process like so:
from subprocess import Popen
Popen(['bash']) # bash is just an example; the problem happens with all programs
The first requ... | [
"--close-on-exec\nOtherwise your new process will inherit the socket\n(this is a UNIX standard behaviour)\n",
"If you prefer to handle this in your python code, you have the option to pass close_fds=True to Popen() then any sockets will not be inherited by the forked process.\n"
] | [
10,
3
] | [] | [] | [
"performance",
"popen",
"python",
"uwsgi"
] | stackoverflow_0005131700_performance_popen_python_uwsgi.txt |
Q:
How do I get days between dates
I need to remove files that are older than 14 days from a directory that stores our backups. I can get the time of an individual file by using something like this:
start = (os.path.getmtime(join(dirpath, name))/3600*24)
But I'm getting confused with how I use timedelta to find ... | How do I get days between dates | I need to remove files that are older than 14 days from a directory that stores our backups. I can get the time of an individual file by using something like this:
start = (os.path.getmtime(join(dirpath, name))/3600*24)
But I'm getting confused with how I use timedelta to find the difference between this and the c... | [
"Try:\nif time.time() - os.path.getmtime(filename) > 14 * 24 * 3600:\n print 'the file is older than 14 days'\n\n",
"a timedelta is the result of subtracting a datetime from another datetime. in this example i show that my /bin/bash is 1168 days and some older than my /dev/null:\n>>> import datetime\n>>> import ... | [
4,
2,
0,
0
] | [] | [] | [
"python",
"timedelta"
] | stackoverflow_0007520634_python_timedelta.txt |
Q:
How do I use the same variable in one function with another function, without making that variable Global?
How can I take one variable from one function and use it in another function without having to make that variable global?
A:
You have basically two choices.
One is to pass it to the second function as a par... | How do I use the same variable in one function with another function, without making that variable Global? | How can I take one variable from one function and use it in another function without having to make that variable global?
| [
"You have basically two choices.\nOne is to pass it to the second function as a parameter. (If you want the first function to see changes to the value, it needs to be a reference type (e.g. a dict/list) and you have to not overwrite the object, only modify it (e.g. a.append(b) rather than a = a + [b]).\nThe second ... | [
4,
2,
0,
0
] | [] | [] | [
"global",
"python",
"variables"
] | stackoverflow_0007519527_global_python_variables.txt |
Q:
which similarity function of nltk.corpus.wordnet is Appropriate for find similarity of two words?
which similarity function in nltk.corpus.wordnet is Appropriate for find similarity of two words?
path_similarity()?
lch_similarity()?
wup_similarity()?
res_similarity()?
jcn_similarity()?
lin_sim... | which similarity function of nltk.corpus.wordnet is Appropriate for find similarity of two words? | which similarity function in nltk.corpus.wordnet is Appropriate for find similarity of two words?
path_similarity()?
lch_similarity()?
wup_similarity()?
res_similarity()?
jcn_similarity()?
lin_similarity()?
I want use a function for word clustering and yarowsky algorightm for find similar collocat... | [
"These measure are actually for word senses (or concepts) not words. That distinction might matter. In other words, the word \"train\" can mean \"locomotive\" or \"being taught to do something\". To use these measures you'd need to know which sense was intended. \nIf you want to do word clustering, these measures m... | [
7,
3
] | [] | [] | [
"corpus",
"nlp",
"nltk",
"python",
"wordnet"
] | stackoverflow_0007400533_corpus_nlp_nltk_python_wordnet.txt |
Q:
How to uninstall IronPython Tools?
I wish to install Python Tools for Visual Studio from here.
The setup complains about "IronPython Tools feature of IronPython 2.7" and asks me to remove it.
Problem is I cannot find any way to uninstall this feature.
Any ideas?
A:
There are two folders in the extension fo... | How to uninstall IronPython Tools? | I wish to install Python Tools for Visual Studio from here.
The setup complains about "IronPython Tools feature of IronPython 2.7" and asks me to remove it.
Problem is I cannot find any way to uninstall this feature.
Any ideas?
| [
"There are two folders in the extension folder (mine is at C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Extensions\\Microsoft) namely \"IronPython Tools for Visual Studio\" and IronStudio delete these and it should work. - Rotimi\n",
"Re-run the IronPython installer and click the Change... | [
4,
1,
1
] | [] | [] | [
"ironpython",
"python",
"visual_studio",
"visual_studio_2010"
] | stackoverflow_0005314686_ironpython_python_visual_studio_visual_studio_2010.txt |
Q:
Is there a simple way to launch a background task from a Python CGI script without waiting around for it to terminate?
In Windows, that is.
I think the answer to this question is that I need to create a Windows service. This seems ludicrously heavyweight for what I am trying to do.
I'm just trying to slap togeth... | Is there a simple way to launch a background task from a Python CGI script without waiting around for it to terminate? | In Windows, that is.
I think the answer to this question is that I need to create a Windows service. This seems ludicrously heavyweight for what I am trying to do.
I'm just trying to slap together a little prototype here for my manager, I'm not going to be responsible for productizing it... in fact, it may never even... | [
"Simplest, but not most efficient way would be to just run another python executable\nfrom subprocess import Popen \nPopen(\"python somescript.py\")\n\n",
"You can just use a system call using the \"start\" windows command. This way your python script will not wait for the completion of the started program.\n",
... | [
1,
1,
1,
0
] | [] | [] | [
"cgi",
"python",
"windows"
] | stackoverflow_0007503554_cgi_python_windows.txt |
Q:
sorting by a related item with ming on mongodb
setup
A TurboGears2 project using ming as an ORM for mongodb. I'm used to working with relational databases and the Django ORM.
question
Ming claims to let to interact with mongodb like it's a relational database and a common thing to do in a relational database is so... | sorting by a related item with ming on mongodb | setup
A TurboGears2 project using ming as an ORM for mongodb. I'm used to working with relational databases and the Django ORM.
question
Ming claims to let to interact with mongodb like it's a relational database and a common thing to do in a relational database is sort a query by a property of a foreign key. With the ... | [
"I have never used ming, but they seem to have a sort method that you can add to a query, check it out here, not much in the form of documentation\nI use mongoengine, it has great documentation and its very similar to the django ORM\n"
] | [
1
] | [] | [] | [
"ming",
"mongodb",
"orm",
"python",
"turbogears2"
] | stackoverflow_0007521297_ming_mongodb_orm_python_turbogears2.txt |
Q:
graph of linked tags
Hi I have a list of lists of linked tag, like this:
some_tags = [[u'art', u'interactive', u'media', u'berlin', u'gallery'], [u'event', u'art', u'Istanbul', u'experimental', u'newmedia', u'bioart'], [u'seriousgames', u'installation', u'interaction', u'design', u'art', u'london', u'people'], [u'... | graph of linked tags | Hi I have a list of lists of linked tag, like this:
some_tags = [[u'art', u'interactive', u'media', u'berlin', u'gallery'], [u'event', u'art', u'Istanbul', u'experimental', u'newmedia', u'bioart'], [u'seriousgames', u'installation', u'interaction', u'design', u'art', u'london', u'people'], [u'event', u'art', u'newmedia... | [
"Take a \"Map Reduce\" approach:\nfrom itertools import product, groupby\nfrom operator import itemgetter\n\ndef generate_pairs(some_tags):\n for linked_tags in some_tags:\n for left,right in product(linked_tags, linked_tags):\n if left != right:\n yield (left, right)\n\n_d=dict(... | [
0
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0007519420_graph_python.txt |
Q:
Loss of precision with very small numbers in Python arrays
I have two arrays in float64 type and when I assign the value of the first to the second it rounds the value. The following simple code illustrates the problem and excludes the possibility of just a mere number representation thing. (I've schematized a fra... | Loss of precision with very small numbers in Python arrays | I have two arrays in float64 type and when I assign the value of the first to the second it rounds the value. The following simple code illustrates the problem and excludes the possibility of just a mere number representation thing. (I've schematized a fragment of my code to be more readable, but it is in essence the s... | [
"Are you absolutely certain that X is a float64 array? If it were, I'd expect X[0,0] to be 0.0, but you see 0 instead, which looks to me like an integer..\n>>> Xf = arange(10,dtype=float64)\n>>> Xi = arange(10)\n>>> Xf[0]\n0.0\n>>> Xi[0]\n0\n>>> Yf = Xf*0.0\n>>> Yf[0]\n0.0\n>>> \n>>> Yf[0] = 1.90897e-14\n>>> Yf[0]... | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007521120_numpy_python.txt |
Q:
'ascii' codec can't decode byte (problem when using django)
I wrote a simple html parsing class in python and it seems to work fine and then I try to use it with django and I get this error:
'ascii' codec can't decode byte 0xc2 in position 54465: ordinal not in range(128)
which is strange because I added this: # ... | 'ascii' codec can't decode byte (problem when using django) | I wrote a simple html parsing class in python and it seems to work fine and then I try to use it with django and I get this error:
'ascii' codec can't decode byte 0xc2 in position 54465: ordinal not in range(128)
which is strange because I added this: # encoding: utf-8 to the top of my class. I don't really know much... | [
"Try putting that line at the top of your file. According to PEP 263, it has to be in the top two lines.\n",
"okay, I got it. All I needed to do was include # -*- coding: utf-8 -*- in the django view as well and that solved it!\n"
] | [
1,
1
] | [] | [] | [
"character_encoding",
"django",
"encoding",
"python"
] | stackoverflow_0007520882_character_encoding_django_encoding_python.txt |
Q:
Python re module's cache clearing
While reading the documentation on Python re module I decided to have a look on re.py source code.
When I opened it, I found this:
_cache = {}
_MAXCACHE = 100
def _compile(*key):
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
retur... | Python re module's cache clearing | While reading the documentation on Python re module I decided to have a look on re.py source code.
When I opened it, I found this:
_cache = {}
_MAXCACHE = 100
def _compile(*key):
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p
#...Here I skip some part of i... | [
"Here is a quote from one of the developers of a new regex module scheduled for 3.3 regarding the caching, this is part of a list of features that separates the new module from the current re module.\n\n7) Modify the re compiled expression cache to better handle the\n thrashing condition. Currently, when regular ... | [
5,
3,
1
] | [] | [] | [
"caching",
"python",
"regex"
] | stackoverflow_0007520622_caching_python_regex.txt |
Q:
How to access a static file in controller in turbogears
I have an XML file in /my_project/public/xml/file.xml, that I want to read and parse it in one method in controller. The file can be easily accessed through a template, but I have no experience with accessing files in controller.
A:
the more simple I know :... | How to access a static file in controller in turbogears | I have an XML file in /my_project/public/xml/file.xml, that I want to read and parse it in one method in controller. The file can be easily accessed through a template, but I have no experience with accessing files in controller.
| [
"the more simple I know : \njest get the diname of base of the project\nfilename = os.path.join(os.path.dirname(myproject.__file__), 'public', 'xml', 'file.xml')\n"
] | [
0
] | [] | [] | [
"python",
"turbogears",
"turbogears2"
] | stackoverflow_0007417964_python_turbogears_turbogears2.txt |
Q:
Pointing to another object's attributes and adding your own
Suppose I have a class:
class Car(object):
def __init__(self, name, tank_size=10, mpg=30):
self.name = name
self.tank_size = tank_size
self.mpg = mpg
I put together a list of the cars I'm looking at:
cars = []
cars.append(Car(... | Pointing to another object's attributes and adding your own | Suppose I have a class:
class Car(object):
def __init__(self, name, tank_size=10, mpg=30):
self.name = name
self.tank_size = tank_size
self.mpg = mpg
I put together a list of the cars I'm looking at:
cars = []
cars.append(Car("Toyota", 11, 29))
cars.append(Car("Ford", 15, 12))
cars.append(C... | [
"This is easiest to do for your example, without changing Car, and changing as little else as possible, with __getattr__:\nclass Car(object):\n def __init__(self, name, tank_size=10, mpg=30):\n self.name = name\n self.tank_size = tank_size\n self.mpg = mpg\n\nclass Favorite(object):\n def... | [
6,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0007520031_design_patterns_oop_python.txt |
Q:
How to get the data returned by the previous query in the method of custom class manager?
I developing a custom manager class with chainable method. Got a problem. I need to randomize filtered query. To get a random record I need a count of filtered and distinct records. But I don't know how to get it. On the cont... | How to get the data returned by the previous query in the method of custom class manager? | I developing a custom manager class with chainable method. Got a problem. I need to randomize filtered query. To get a random record I need a count of filtered and distinct records. But I don't know how to get it. On the contrary, I have a count of all records.
class RandomQueryset(models.query.QuerySet):
def rand... | [
"You've asked me to post one of my questions as an answer, so here goes.\nThis looks like you need to use Django's built-in count() function docs.djangoproject.com/en/dev/ref/models/querysets\nI do not see its use in your code. \n"
] | [
1
] | [] | [] | [
"django",
"django_managers",
"oop",
"python"
] | stackoverflow_0007475258_django_django_managers_oop_python.txt |
Q:
How to pass a Bash variable to Python?
Eventually I understand this and it works.
bash script:
#!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G
c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
FILENAME=`head -$c testlist|tail -1`
python testpython.py $FILENAME
pyt... | How to pass a Bash variable to Python? | Eventually I understand this and it works.
bash script:
#!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G
c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
FILENAME=`head -$c testlist|tail -1`
python testpython.py $FILENAME
python script:
#!/bin/python
import sys,os
p... | [
"Exported bash variables are actually environment variables. You get at them through the os.environ object with a dictionary-like interface. Note that there are two types of variables in Bash: those local to the current process, and those that are inherited by child processes. Your Python script is a child proce... | [
22,
1,
1,
0
] | [] | [] | [
"bash",
"python",
"variables"
] | stackoverflow_0007521061_bash_python_variables.txt |
Q:
Python Distance Formula Calculator
My assignment is to make a distance calculator that finds the distance between two locations, and I chose to use Python.
I've put all the locations into coordinate points, but I need to know how to pick two of these by name, then apply the distance formula to them:
(sqrt ((x[2]-... | Python Distance Formula Calculator | My assignment is to make a distance calculator that finds the distance between two locations, and I chose to use Python.
I've put all the locations into coordinate points, but I need to know how to pick two of these by name, then apply the distance formula to them:
(sqrt ((x[2]-x[1])**2+(y[2]-[y1])**2)
Anyways, I do... | [
"You just need to put them in a dictionary, like:\npoints = {\n 'fort sullivan': (22.2, 27.2),\n 'Fort william and mary': (20.2, 23.4)\n}\n\nand then select from the dictionary and run your thing\nx = points['fort sullivan']\ny = points['Fort william and mary']\n\n# And then run math code\n\n",
"Use a dict to sto... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0007522294_python.txt |
Q:
How to make `help` act the same as `--help` in argparse
I want the help option act the same as --help.
sidenote: I have created a program with the same command line behavior as svn or hg. I managed to do this with subparsers. However I want to make things consistent. That's why I want help to work.
A:
You can do... | How to make `help` act the same as `--help` in argparse | I want the help option act the same as --help.
sidenote: I have created a program with the same command line behavior as svn or hg. I managed to do this with subparsers. However I want to make things consistent. That's why I want help to work.
| [
"You can do the following to create an alias and make program help act the same as program --help\nimport argparse\n\ndef help(args):\n args.parser.print_help()\n\nparser = argparse.ArgumentParser(description='my program')\nsubparsers = parser.add_subparsers()\np_help = subparsers.add_parser('help')\np_help.set_... | [
4,
0
] | [] | [] | [
"alias",
"argparse",
"python"
] | stackoverflow_0007498416_alias_argparse_python.txt |
Q:
How can I turn a string into a list in Python?
How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?
A:
The list() function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already be... | How can I turn a string into a list in Python? | How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?
| [
"The list() function [docs] will convert a string into a list of single-character strings.\n>>> list('hello')\n['h', 'e', 'l', 'l', 'o']\n\nEven without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using ... | [
46
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0007522533_list_python_string.txt |
Q:
Accessing Vlookup Macro Code in Excel?
I wish to manually code VLOOKUP in python, so is it possible to see the VBA code behind VLOOKUP?
I remember a presentation in my school by a guest speaker showing that the Excel Functions are just macro/vba codes. Can someone please show me the way to view the code for Excel ... | Accessing Vlookup Macro Code in Excel? | I wish to manually code VLOOKUP in python, so is it possible to see the VBA code behind VLOOKUP?
I remember a presentation in my school by a guest speaker showing that the Excel Functions are just macro/vba codes. Can someone please show me the way to view the code for Excel Worksheet functions?
| [
"I do not know of a way to view the XL code for VLOOKUP (its almost certainly written in C). The basic algorithms used in VLOOKUP are Linear Search for unsorted data, and Binary Search for sorted data. There are many examples available on the web of implementing these algorithms.\n",
"Excel functions i dont' know... | [
0,
0
] | [] | [] | [
"excel",
"python",
"worksheet_function"
] | stackoverflow_0004130199_excel_python_worksheet_function.txt |
Q:
Word Play Question
I created a function that takes a word and a string of 'forbidden' letters, and returns True if the word doesn't use any of the letter.
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
else:
return True
I want to modify thi... | Word Play Question | I created a function that takes a word and a string of 'forbidden' letters, and returns True if the word doesn't use any of the letter.
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
else:
return True
I want to modify this so instead of using 'f... | [
"My guess...\nYou are python 2.x\nWhen you ran the program you typed in:\n'a','b','c','d'\n\nOn python 2.x, you want to use raw_input not input. That'll give a string of exactly what you type in. As it is python will try to interpret whatever you right as a python expression which is dangerous and generally a bad i... | [
2,
2,
1,
1
] | [] | [] | [
"file",
"for_loop",
"python"
] | stackoverflow_0007522569_file_for_loop_python.txt |
Q:
python-sybase how to connect remote server
I host use the "ip:port",but it throws exception:
Sybase.DatabaseError: Layer: 6, Origin: 8 ct_connect(): directory service layer: internal directory control layer error
py-sybase:0.40pre1
sybase-open_client:15
Any idea? Thanks
Ford
A:
>>> import Sybase
>>> help(Sybase.... | python-sybase how to connect remote server | I host use the "ip:port",but it throws exception:
Sybase.DatabaseError: Layer: 6, Origin: 8 ct_connect(): directory service layer: internal directory control layer error
py-sybase:0.40pre1
sybase-open_client:15
Any idea? Thanks
Ford
| [
">>> import Sybase\n>>> help(Sybase.connect)\nHelp on function connect in module Sybase:\n\nconnect(dsn, user, passwd, database=None, strip=0, auto_commit=0, delay_connect=0, locking=1, datetime=None, bulkcopy=0, locale=None, inputmap=None, outputmap=None)\n\nThe first argument is a DSN, not a hostname.\nSo, config... | [
1
] | [] | [] | [
"python",
"sybase"
] | stackoverflow_0006096263_python_sybase.txt |
Q:
Django Multiple Caches - How to choose which cache the session goes in?
I have a Django app set up to use multiple caches (I hope). Is there a way to set the session to use a specific cache, or is it stuck on 'default'?
Here's what i have now:
CACHES = {
'default': {
'BACKEND': 'util.backends.SmartMem... | Django Multiple Caches - How to choose which cache the session goes in? | I have a Django app set up to use multiple caches (I hope). Is there a way to set the session to use a specific cache, or is it stuck on 'default'?
Here's what i have now:
CACHES = {
'default': {
'BACKEND': 'util.backends.SmartMemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 300,
... | [
"The cached_db and cache backends don't support it, but it's easy to create your own:\nfrom django.contrib.sessions.backends.cache import SessionStore as CachedSessionStore\nfrom django.core.cache import get_cache\nfrom django.conf import settings\n\nclass SessionStore(CachedSessionStore):\n \"\"\"\n A cache-... | [
3
] | [] | [] | [
"caching",
"django",
"python",
"session"
] | stackoverflow_0007522721_caching_django_python_session.txt |
Q:
Python Interpreter Not Reading Indents Properly After Turning on VIM Auto-Indenting
I'm not entirely sure what has happened.
I was debugging a script that worked "fine" (except for said intermittent bugs) and all of a sudden the module cannot be imported anymore. I undid all changes and still the problem exists.
... | Python Interpreter Not Reading Indents Properly After Turning on VIM Auto-Indenting | I'm not entirely sure what has happened.
I was debugging a script that worked "fine" (except for said intermittent bugs) and all of a sudden the module cannot be imported anymore. I undid all changes and still the problem exists.
Well, problemS. Plural.
Once I got an "unexpected indent" error, even though all the line... | [
"You've got an indentation problem.\nThe self.session = session line, and everything below, isn't inside your __init__ method, it's just inside the class body.\nsession isn't defined in the class body, only inside __init__, as you mention in your question, so you get the error.\nIF you remove that line, the first t... | [
1
] | [] | [] | [
"interpreter",
"python"
] | stackoverflow_0007522869_interpreter_python.txt |
Q:
Federated identity on Google App Engine
I am successful with the both methods below, to log on using federated log in for my site on Google App Engine (Python)
users.create_login_url("\", "google", "https://www.google.com/accounts/o8/id")
users.create_login_url("\", "yahoo", "http://open.login.yahooapis.com/open... | Federated identity on Google App Engine | I am successful with the both methods below, to log on using federated log in for my site on Google App Engine (Python)
users.create_login_url("\", "google", "https://www.google.com/accounts/o8/id")
users.create_login_url("\", "yahoo", "http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds")
I wish to provide ... | [
"Google documentation mentions following direct providers of federated identities ...\n\ngoogle.com/accounts/o8/id (shorter alternative: gmail.com)\nyahoo.com\nmyspace.com\naol.com\nmyopenid.com\n\n... as well as username provider federated identities:\n\nflickr.com/USERNAME\nUSERNAME.wordpress.com\nUSERNAME.blogsp... | [
11,
2,
1
] | [] | [] | [
"federated_identity",
"google_app_engine",
"openid",
"python"
] | stackoverflow_0003590335_federated_identity_google_app_engine_openid_python.txt |
Q:
Is Google App Engine's Webapp Framework Open Source? Is it available outside GAE?
Google App Engine includes this minimal framework called "webapp". Google Code does not list a project page for webapp. The only documentation/information from Google on webapp is in the Google App Engine documentation. Is webapp not... | Is Google App Engine's Webapp Framework Open Source? Is it available outside GAE? | Google App Engine includes this minimal framework called "webapp". Google Code does not list a project page for webapp. The only documentation/information from Google on webapp is in the Google App Engine documentation. Is webapp not usable outside GAE?
| [
"You could use webapp outside App Engine - there's very little that's App Engine specific - but it's not designed for it, and thus isn't packaged or documented separately. If you want a webapp-like framework you can use anywhere, check out webapp2. It's a very close copy of webapp, with a lot of improvements and ex... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"web_applications",
"wsgi"
] | stackoverflow_0007520739_google_app_engine_python_web_applications_wsgi.txt |
Q:
How to print out ascii characters from 0 to 255 in C, displayed in a webpage through Django?
I'm working on a C assignment for school. Here's the exact wording of the assignment:
"Write a program that prints a list of the integers 0 through 255 and the corresponding ASCII cha... | How to print out ascii characters from 0 to 255 in C, displayed in a webpage through Django? | I'm working on a C assignment for school. Here's the exact wording of the assignment:
"Write a program that prints a list of the integers 0 through 255 and the corresponding ASCII character. "
The actual code was simple enough:
#include <stdio.h>
int main() {
int i;
for ... | [
"Ha, found a way for it to at least render it to the page, the characters don't display correctly but at least it renders something to the page.\nThe code is simply this:\nmystring = unicode(mystring, errors='replace')\n\nEDIT: Found an even better way\nimport chardet\nchartype = chardet.detect(mystring)\n\n# perha... | [
1,
0,
0,
0,
0
] | [] | [] | [
"c",
"django",
"encoding",
"python"
] | stackoverflow_0007522742_c_django_encoding_python.txt |
Q:
Equivalent of named tuple in NumPy?
Is it possible to create a NumPy object that behaves very much like a collections.namedtuple, in the sense that elements can be accessed like so:
data[1] = 42
data['start date'] = '2011-09-20' # Slight generalization of what is possible with a namedtuple
I tried to use a compl... | Equivalent of named tuple in NumPy? | Is it possible to create a NumPy object that behaves very much like a collections.namedtuple, in the sense that elements can be accessed like so:
data[1] = 42
data['start date'] = '2011-09-20' # Slight generalization of what is possible with a namedtuple
I tried to use a complex data type:
>>> data = numpy.empty(shap... | [
"You can do something like this using the numpy.rec module. What you need is the record class from this module, but I don't know how to directly create an instance of such a class. One indrect way is to first create a recarray with a single entry:\n>>> a = numpy.recarray(1, names=[\"start date\", \"n\"], formats=... | [
3,
2,
2,
2
] | [] | [] | [
"collections",
"namedtuple",
"numpy",
"python"
] | stackoverflow_0007489956_collections_namedtuple_numpy_python.txt |
Q:
Best practices for dependent fields in a django model
For database indexing purposes, the email field on a model needs to be stored in reverse. I end up needing access to both the reversed and forward version of the email field. I'm curious as to which of the following methods would be considered best practice.
... | Best practices for dependent fields in a django model | For database indexing purposes, the email field on a model needs to be stored in reverse. I end up needing access to both the reversed and forward version of the email field. I'm curious as to which of the following methods would be considered best practice.
Method A
Override the save method on the model. This metho... | [
"The Model:\nclass Foo(models.Model):\n email = models.CharField(max_length=320)\n\n def _get_email_reversed(self):\n return self.email[::-1]\n\n def _set_email_reversed(self, value):\n self.email = value[::-1]\n\n email_reversed=property(_get_email_reversed, _set_email_reversed)\n\nAnd th... | [
1
] | [] | [] | [
"django",
"django_models",
"getter_setter",
"python"
] | stackoverflow_0007521704_django_django_models_getter_setter_python.txt |
Q:
Make a twister server take initiative
I have a server in twisted, implementing a LineReceiver protocol.
When I call sendLine in response to a client message, it writes the line to the client immediately, as one would expect.
But say the client asks the server to do a lengthy calculation. I want the server to perio... | Make a twister server take initiative | I have a server in twisted, implementing a LineReceiver protocol.
When I call sendLine in response to a client message, it writes the line to the client immediately, as one would expect.
But say the client asks the server to do a lengthy calculation. I want the server to periodically send a progress message to the clie... | [
"Use deferreds if you perform calculation asynchronously.\nOther way if it's some long calculation in separate Thread, started by lets say deferrToThread(), use reactor.callFromThread()\n(I assume we don't do heavy calculation in main loop - that's very, very wrong :))\nlittle example:\ndef some_long_foo(data_array... | [
2,
1,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0007488266_python_twisted.txt |
Q:
AttributeError: 'function' object has no attribute 'my_args'
How can I get access to my_args list data type in __main__?
test1.py
#!/usr/bin/env python
def main():
print 'main function'
one()
def one():
print 'one function'
my_args = ["QA-65"]
def two():
print 'two function'
if __name__ == ... | AttributeError: 'function' object has no attribute 'my_args' | How can I get access to my_args list data type in __main__?
test1.py
#!/usr/bin/env python
def main():
print 'main function'
one()
def one():
print 'one function'
my_args = ["QA-65"]
def two():
print 'two function'
if __name__ == "__main__":
main()
getattr(my_args, pop)
| [
"You can if you return them from one():\n#!/usr/bin/env python\n\ndef main():\n print 'main function'\n args = one() # returns my_args, which i'm assigning to args\n print 'i got args from one():', args\n print args.pop()\n\ndef one():\n print 'one function'\n my_args = [\"QA-65\"]\n return my_... | [
3,
0
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0007523835_python_python_2.x.txt |
Q:
How do you create a n by n box of X's in python using string manipulation? (eg. replace, count, find, len, etc.)
Get a number from the user (n) and create an n x n box of "X"es on the screen. Without using loops yet.
e.g. If they entered 12:
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXX... | How do you create a n by n box of X's in python using string manipulation? (eg. replace, count, find, len, etc.) | Get a number from the user (n) and create an n x n box of "X"es on the screen. Without using loops yet.
e.g. If they entered 12:
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
The point of this assignment is t... | [
"You can \"multiply\" strings. For example, 'x' * 3 gives you xxx. So:\nsize = int(input()) # convert whatever you have to int\nprint(size * (size * 'X' + '\\n')) # print the whole thing\n\nThis isn't very intuitive (very few languages will let you do that), but getting the input should be straightforward enough.... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007523669_python.txt |
Q:
Converting a parent child relationship into Json in python
I have a list of list like the below. The first column is the parent, second is the child, and the third are node attributes. I need to convert the below to a JSON format like the following.
0 0 "flair" 1000
0 1 "analytics" 1000
1 2 "cluster" 1000
2 3 "... | Converting a parent child relationship into Json in python | I have a list of list like the below. The first column is the parent, second is the child, and the third are node attributes. I need to convert the below to a JSON format like the following.
0 0 "flair" 1000
0 1 "analytics" 1000
1 2 "cluster" 1000
2 3 "AgglomerativeCluster" 1000
2 4 "CommunityStructure" 1000
1 5 "G... | [
"A little change to your input, for a root node \"flair\", I use '-1' as its parent id instead of '0'.\nimport json\npc = []\npc.append([-1, 0 ,\"flair\", 1000])\npc.append([0,1, \"analytics\", 1000])\npc.append([1, 2, \"cluster\", 1000])\npc.append([2 ,3, \"AgglomerativeCluster\", 1000])\npc.append([2 ,4, \"Commun... | [
3,
1
] | [] | [] | [
"json",
"parent",
"python"
] | stackoverflow_0007523920_json_parent_python.txt |
Q:
Python performance vs PHP
I am an experienced PHP developer, and I would want to know what of both languages is better for web development.
I understand that there are a lot of factors to evaluate; but focusing in execution time, in your own experience making connections to a MySQL server, parsing and concatenatin... | Python performance vs PHP | I am an experienced PHP developer, and I would want to know what of both languages is better for web development.
I understand that there are a lot of factors to evaluate; but focusing in execution time, in your own experience making connections to a MySQL server, parsing and concatenating strings, and making several e... | [
"Even if things aren't specifically integer comparison or string comparison problems, looking at those computations is a decent indication of how the language will perform in more complex tasks. Keep in mind, though, that web development isn't all about computation speed. Unless you're doing some fancy backend data... | [
10
] | [] | [] | [
"php",
"python"
] | stackoverflow_0007524139_php_python.txt |
Q:
Slicing objects in Python/Django question
I want to retrieve the 13 latest objects, which shows this in my shell:
>>> last_13_issues = Issue.objects.order_by('-id').order_by('-pub_date')[:13]
>>> print last_13_issues
[<Issue: X-Men v2 #18>, <Issue: Uncanny X-Men #543>, **<Issue: Herc #7>**, <Issue: X-Men: Schism #... | Slicing objects in Python/Django question | I want to retrieve the 13 latest objects, which shows this in my shell:
>>> last_13_issues = Issue.objects.order_by('-id').order_by('-pub_date')[:13]
>>> print last_13_issues
[<Issue: X-Men v2 #18>, <Issue: Uncanny X-Men #543>, **<Issue: Herc #7>**, <Issue: X-Men: Schism #4>, <Issue: X-Men v2 #17>, <Issue: X-Men First ... | [
"Use [3:] instead of [4:] for your more_latest_appearances.\nEnd index is non-inclusive for slicing:\n>>> \"abcdef\"[:3]\n'abc'\n>>> \"abcdef\"[4:]\n'ef'\n>>> \"abcdef\"[3:]\n'def'\n\nIn order to clarify things more, I'd suggest rewriting your code a little to look like this:\nappearances = Issue.objects.order_by('... | [
1
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0007524213_django_django_views_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.