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:
im looking for a simple game lobby built in python
I'm looking for a simple game lobby in python. I have made a small game and want to implement a lobby but have never done this. Are there any examples I can hack at?
A:
A lobby is little more than a glorified chat room. I would look into a chat room module in p... | im looking for a simple game lobby built in python | I'm looking for a simple game lobby in python. I have made a small game and want to implement a lobby but have never done this. Are there any examples I can hack at?
| [
"A lobby is little more than a glorified chat room. I would look into a chat room module in python and integrate into your game client. That would serve as a makeshift lobby.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007032357_python.txt |
Q:
get the modules locally for django project
Is there a way to import all the modules in the django project itself instead of setting up again and again in all the systems.
I would have used gem freeze or something like that in a rails project.
A:
There's a bit of a terminology confusion here: "modules" refers to ... | get the modules locally for django project | Is there a way to import all the modules in the django project itself instead of setting up again and again in all the systems.
I would have used gem freeze or something like that in a rails project.
| [
"There's a bit of a terminology confusion here: \"modules\" refers to individual .py files within a Python package. And importing is what you do within code, to bring modules into the current namespace.\nI think what you're asking is how to install Python packages on deployment. The answer to that is, use pip with ... | [
3,
1,
1,
0
] | [] | [] | [
"django",
"python",
"python_module"
] | stackoverflow_0007023369_django_python_python_module.txt |
Q:
python regex to remove comments
How would I write a regex that removes all comments that start with the # and stop at the end of the line -- but at the same time exclude the first two lines which say
#!/usr/bin/python
and
#-*- coding: utf-8 -*-
A:
You can remove comments by parsing the Python code with token... | python regex to remove comments | How would I write a regex that removes all comments that start with the # and stop at the end of the line -- but at the same time exclude the first two lines which say
#!/usr/bin/python
and
#-*- coding: utf-8 -*-
| [
"You can remove comments by parsing the Python code with tokenize.generate_tokens. The following is a slightly modified version of this example from the docs:\nimport tokenize\nimport io\nimport sys\nif sys.version_info[0] == 3:\n StringIO = io.StringIO\nelse:\n StringIO = io.BytesIO\n\ndef nocomment(s):\n ... | [
5,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007032031_python_regex.txt |
Q:
Are Python's bytes objects also known as strings?
This is a section from Dive Into Python 3 regarding strings:
In Python 3, all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in utf-8, or a Python string encoded as CP-1252. “Is this string utf-8?” is an invalid ques... | Are Python's bytes objects also known as strings? | This is a section from Dive Into Python 3 regarding strings:
In Python 3, all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in utf-8, or a Python string encoded as CP-1252. “Is this string utf-8?” is an invalid question. utf-8 is a way of encoding characters as a sequen... | [
"In Python 2 and 3, str was used both for strings of characters as well as bytes. In Fact, until Python 2.6, there wasn't even a bytes type (and in 2.6 and 2.7, bytes is str).\nThe mentioned inconsistencies in the hashlib documentation are an artifact of this history.\n",
"Probably the help is left over from Pyth... | [
6,
5
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007032427_python_string.txt |
Q:
problem debugging with conditional breakpoint python
When I try to run the following bit of code, I get the error TypeError: object of type 'NoneType' has no len() (referring to the variable stringConverted). I've tested different values and it works for the ones I've tested. I was thinking that the best way to ... | problem debugging with conditional breakpoint python | When I try to run the following bit of code, I get the error TypeError: object of type 'NoneType' has no len() (referring to the variable stringConverted). I've tested different values and it works for the ones I've tested. I was thinking that the best way to debug this is to figure out what value of i causes a 'None... | [
"You should use if stringConverted is None instead of checking the type to see if it is NoneType.\n",
"def main():\n totalChars = 0\n for i in range(1,500):\n stringConverted = stringConvert(i)\n if stringConverted is None:\n print i\n break\n totalChars = totalCha... | [
0,
0
] | [] | [] | [
"conditional_breakpoint",
"debugging",
"python"
] | stackoverflow_0007032288_conditional_breakpoint_debugging_python.txt |
Q:
Defining and Calling Functions in Python
I am diving into defining and calling functions, but I'm not sure if I have grasped the concept. I have an if/else statement in a python that loops through a folder containing XML documents. In my script below, I have a block of code that I have to re-type after each if xml... | Defining and Calling Functions in Python | I am diving into defining and calling functions, but I'm not sure if I have grasped the concept. I have an if/else statement in a python that loops through a folder containing XML documents. In my script below, I have a block of code that I have to re-type after each if xmlfilename == condition.
I'm thinking that if I... | [
"If the functionality is exactly the same for \"Soil\" and \"Tree\" you can just modify the if statement to the following:\nif xmlfilename == \"Soil\" or xmlfilename == \"Tree\":\n # The rest of your code\n\nAlthough you may choose to put your code block in a function to organize your code a bit better:\ndef rea... | [
2
] | [] | [] | [
"function",
"python"
] | stackoverflow_0007032443_function_python.txt |
Q:
how to do regex search in Mongodb using pymongo?
I want to do a regex mongodb query using pymongo.
cond = {'date':'/.*2011-8-11.*/'}
coll.find(cond).count() return 0;
but I do this query directly on Mongodb return 25;
Is there any problem in my query?
A:
To search with regular expressions from pymongo, you need... | how to do regex search in Mongodb using pymongo? | I want to do a regex mongodb query using pymongo.
cond = {'date':'/.*2011-8-11.*/'}
coll.find(cond).count() return 0;
but I do this query directly on Mongodb return 25;
Is there any problem in my query?
| [
"To search with regular expressions from pymongo, you need to use a python regular expression object, not a string with slashes. For your query above, the pymongo syntax would be:\nimport re\n# assume connection is set up, and db\n# is a pymongo.database.Database instance\ndate_re = re.compile(r'2011-8-11')\ndb.col... | [
6
] | [] | [] | [
"mongodb",
"pymongo",
"python",
"regex"
] | stackoverflow_0007024137_mongodb_pymongo_python_regex.txt |
Q:
How to run application with parameters in Python?
I need to run an application (binary file) and pass arguments using a Python code. Some arguments represent strings got during Python file processing.
for i in range ( len ( files ) ) :
subprocess.call(["test.exe", files[i]]) //How to pass the argument files[i]... | How to run application with parameters in Python? | I need to run an application (binary file) and pass arguments using a Python code. Some arguments represent strings got during Python file processing.
for i in range ( len ( files ) ) :
subprocess.call(["test.exe", files[i]]) //How to pass the argument files[i]
Thanks...
Updated question:
Maybe I do not understan... | [
"args = ['test. exe']\nsubprocess.call(args, '-f') #gives Error\n\nshould be:\nargs = ['test.exe', '-f']\nsubprocess.call(args) \n\nThe command line argument should all be inside a single list for the first parameter of subprocess.call. The second argument to call is bufsize, which is supposed to be an integer (th... | [
20,
3,
2
] | [] | [] | [
"command_line_arguments",
"process",
"python",
"python_3.x"
] | stackoverflow_0007032212_command_line_arguments_process_python_python_3.x.txt |
Q:
what are the mercurial hgweb.cgi and python matching versions
Mercurial version is 1.9.1
C:\Inetpub\hgweb>hg version
Mercurial Distributed SCM (version 1.9.1)
(see http://mercurial.selenic.com for more information)
Copyright (C) 2005-2011 Matt Mackall and others
This is free software; see the source for copying c... | what are the mercurial hgweb.cgi and python matching versions | Mercurial version is 1.9.1
C:\Inetpub\hgweb>hg version
Mercurial Distributed SCM (version 1.9.1)
(see http://mercurial.selenic.com for more information)
Copyright (C) 2005-2011 Matt Mackall and others
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FI... | [
"You will need to run this under the version of Python that Mercurial is built against. Unfortunately the FAQ doesn't mention what this is and I can't open a .msi on my current system so you will need to check for a \"pythonXX.dll\" or some such library installed with TortoiseHG and use it with that minor version o... | [
3
] | [] | [] | [
"mercurial",
"python"
] | stackoverflow_0007032178_mercurial_python.txt |
Q:
Controlling my output
Here is the code:
#!/usr/bin/env python
import json
import sys
import os
import parser
sys.path.append('Z:\_protomotion\Prog\HelperScripts')
import GetDir
sys.path.append('Z:/Blender_Roto')
filename = 'diving_board.shape4ae'
infile = 'Z:/Blender_Roto/'
#import bpy
#from mathutils import Vecto... | Controlling my output | Here is the code:
#!/usr/bin/env python
import json
import sys
import os
import parser
sys.path.append('Z:\_protomotion\Prog\HelperScripts')
import GetDir
sys.path.append('Z:/Blender_Roto')
filename = 'diving_board.shape4ae'
infile = 'Z:/Blender_Roto/'
#import bpy
#from mathutils import Vector
#below are taken from mo... | [
"That looks like a tuple, in which case, the python statement for what you want is:\npoint1x, point1y, point1z, point1w = (0.793803,0.136326,0,0.5,0)\n\n",
"Once you have points, if you know it will always be a comma-seperated list of decimal numbers, simply do something like this:\npoints = points.split(\",\")\n... | [
2,
1
] | [] | [] | [
"list",
"pyparsing",
"python",
"string",
"tuples"
] | stackoverflow_0007032002_list_pyparsing_python_string_tuples.txt |
Q:
What is the typical workflow for development of a Zenoss ZenPack?
ZenPack development seems to involve the creation of a variety of persistent state. There are model classes which represent explicitly persistent state. There are skins which are associated with model objects. There are organizers and instances o... | What is the typical workflow for development of a Zenoss ZenPack? | ZenPack development seems to involve the creation of a variety of persistent state. There are model classes which represent explicitly persistent state. There are skins which are associated with model objects. There are organizers and instances of persistent classes (data sources, graphs, etc).
Considering that duri... | [
"I don't know anything about Zenoss specifically, but this situations are common for any syste that have persistent configuration in one form or another, like Zope and Plone for example.\nAnd the workflow is that you create a test environment that you can delete and replicate, but in parts and in whole. For a typic... | [
2,
2
] | [] | [] | [
"database",
"python",
"zenoss"
] | stackoverflow_0001573166_database_python_zenoss.txt |
Q:
Map reduce execute failed with pymongo but success in mongo shell
I got a problem about mongo map reduce, my map reduce can execute success in mongo shell but when i try to execute use pymongo i got the following errors.
The following json is my Collections JSON format sample
{ "_id" : ObjectId( "4e41661ecacbd10e0... | Map reduce execute failed with pymongo but success in mongo shell | I got a problem about mongo map reduce, my map reduce can execute success in mongo shell but when i try to execute use pymongo i got the following errors.
The following json is my Collections JSON format sample
{ "_id" : ObjectId( "4e41661ecacbd10e00012600" ),
"timestamp" : "20110809",
"variants" : { "407" : { "num... | [
"The problem is you are passing 'scope' as 'fields'.\nThis works:\ndb.variant_daily_collection.map_reduce(m, r, out=\"myoutput\", query={\"site_name\": {'$in':['julie2.com','julie3.com','radiotiempo.com']}, 'timestamp': {'$gte':'20110601','$lte':'20110809'}}, scope={'variant_ids': ['4519','4518']})\n\nWhere m is yo... | [
3,
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0007012236_mongodb_pymongo_python.txt |
Q:
Django sidebar form
Im trying to build a sidebar form on a website in order to search some stuff, kind of like this http://cl.ly/0e0R1T0G3B1x0c451F22 where a person can search for something given certain parameters in any part of the website, meaning that the form must be displayed everywhere, and thats where I ha... | Django sidebar form | Im trying to build a sidebar form on a website in order to search some stuff, kind of like this http://cl.ly/0e0R1T0G3B1x0c451F22 where a person can search for something given certain parameters in any part of the website, meaning that the form must be displayed everywhere, and thats where I have the problem.
it seems ... | [
"You can either include the form html directly (without using django forms for rendering):\n<form action = '{% url search %}' method='GET'>\n <label>Query: <input type='search' name='query'></label>\n <input type='submit' value='Go'>\n</form>\n\nor pass the form instance to all views using context processor:\... | [
0
] | [] | [] | [
"django",
"python",
"sidebar"
] | stackoverflow_0007032264_django_python_sidebar.txt |
Q:
Python: modeling one-to-one relationship in datastore
Let's assume we have two models: User and Token. A user may have only one Token, and a Token can belong to only one user.
Coming from relational databases, the following seems like the way to do it:
class User(db.Model):
name = db.StringProperty()
class To... | Python: modeling one-to-one relationship in datastore | Let's assume we have two models: User and Token. A user may have only one Token, and a Token can belong to only one user.
Coming from relational databases, the following seems like the way to do it:
class User(db.Model):
name = db.StringProperty()
class Token(db.Model):
name = db.StringProperty()
owner = d... | [
"this is the appengine data store. it's not sql. you should group together data as it is used by your system. presumably you have places where users and tokens are used together, and since there are no issues with many-to-one these can go in the same model instance. this will give you better performance (much s... | [
4,
1
] | [] | [] | [
"data_structures",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006996504_data_structures_google_app_engine_google_cloud_datastore_python.txt |
Q:
connecting to a website using proxies and urllib?
If the proxy is 200.217.241.76 and the port is 80 how can i connect to google.com and read the html code using that proxy?
My problem is to establish the connection i know how to read the html file when i get it,
i want to automate a script that keep on reading di... | connecting to a website using proxies and urllib? | If the proxy is 200.217.241.76 and the port is 80 how can i connect to google.com and read the html code using that proxy?
My problem is to establish the connection i know how to read the html file when i get it,
i want to automate a script that keep on reading different html files and save the data.
what i have now :... | [
"urllib honors the system proxy settings:\n\nThe urlopen() function works transparently with proxies which do not\n require authentication. In a Unix or Windows environment, set the\n http_proxy, or ftp_proxy environment variables to a URL that\n identifies the proxy server before starting the Python interpreter... | [
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0007032359_python_urllib_urllib2.txt |
Q:
Python - Method to operate on a class attribute, where the attribute is dynamically specified in a class method
Apologize if this is duplicate - not sure how to word what I"m trying to accomplish.
I have two class' of interest here (in brief):
class Patient:
...
self.weight = (some float)
self.medic... | Python - Method to operate on a class attribute, where the attribute is dynamically specified in a class method | Apologize if this is duplicate - not sure how to word what I"m trying to accomplish.
I have two class' of interest here (in brief):
class Patient:
...
self.weight = (some float)
self.medicationDays = (some float)
self.AverageWeightChange = (some float)
etc.
class PtAnalyzer:
...
self.ptL... | [
"You want getattr(); pass the metric to use as a string.\n"
] | [
4
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0007033343_jython_python.txt |
Q:
One frustrating error in a conditional statement in Python
like the title says, I have a single bug in a script for a game I'm making. I have, inside a defined function, an if statement that is supposed to run only if a variable is less than one. But when the function runs, even if this variable is equal to or gre... | One frustrating error in a conditional statement in Python | like the title says, I have a single bug in a script for a game I'm making. I have, inside a defined function, an if statement that is supposed to run only if a variable is less than one. But when the function runs, even if this variable is equal to or greater than one, the if statement still runs, and doesn't go to el... | [
"This statement does not increment death_toll:\ndeath_toll == death_toll + 1\n\nIt is a comparison that returns False. You want:\ndeath_toll = death_toll +1\n\nEdit:\nIf I understand your various comments, etc., what you want is for the program to offer, throughout the entire runtime, one chance to \"cheat death\"... | [
4,
2,
0,
0
] | [] | [] | [
"if_statement",
"python",
"variables"
] | stackoverflow_0007032856_if_statement_python_variables.txt |
Q:
How can I find where a specific string is on an image?
I was wondering if anyone knew of a way that I could feed an image file to a Python, C or Java program and get back the coordinates of where a specific string appears on the image?
A:
What you're talking about is called Optical Character Recognition, or OCR.... | How can I find where a specific string is on an image? | I was wondering if anyone knew of a way that I could feed an image file to a Python, C or Java program and get back the coordinates of where a specific string appears on the image?
| [
"What you're talking about is called Optical Character Recognition, or OCR.\nOCR isn't easy to implement from scratch, but there are libraries out there. OpenCV can be used for OCR.\n",
"I looked into this a bit more. It turns out that sikuli does exactly what I needed.\n"
] | [
4,
0
] | [] | [] | [
"c",
"image",
"image_processing",
"java",
"python"
] | stackoverflow_0006658415_c_image_image_processing_java_python.txt |
Q:
Difference between a[:] = b and a = b[:]? (Python)
I was asked this for a coding test and didn't know the answer. Anyone have any ideas?
A:
[:] is the slice operator.
When it's on the left side, it overwrites the contents of the list without creating a new reference.
When it's on the right side, it creates a c... | Difference between a[:] = b and a = b[:]? (Python) | I was asked this for a coding test and didn't know the answer. Anyone have any ideas?
| [
"[:] is the slice operator. \nWhen it's on the left side, it overwrites the contents of the list without creating a new reference.\nWhen it's on the right side, it creates a copy of the list with the same contents.\n",
"a = b[:] calls either __getslice__ or __getitem__ on b and assigns the result to a. In nearl... | [
10,
3,
2
] | [] | [] | [
"python",
"sequence",
"slice"
] | stackoverflow_0007033499_python_sequence_slice.txt |
Q:
Using Matplotlib to add text along with a plot in a pdf file
Possible Duplicate:
Is there a way of drawing a caption box in matplotlib
I am trying to add a text description of a graph that I draw with matplotlib. I was wondering if there was a way to add a small description that is not in the frame of the graph... | Using Matplotlib to add text along with a plot in a pdf file |
Possible Duplicate:
Is there a way of drawing a caption box in matplotlib
I am trying to add a text description of a graph that I draw with matplotlib. I was wondering if there was a way to add a small description that is not in the frame of the graph (ie. either below it or above it).
I saw this link add text to e... | [
"@Jim, if I understand your question correctly, you're looking for a text area to use as a caption or description below a figure in matplotlib. \nIf so, you may find your answer through this duplicate question.\n"
] | [
2
] | [] | [] | [
"matplotlib",
"pdf",
"python"
] | stackoverflow_0007033386_matplotlib_pdf_python.txt |
Q:
How can I "hook into" Python from C++ when it executes a function? My goal is to profile
I'm implementing a profiler in an application and I'm a little flummoxed about how to implement Python profiling such that the results can be displayed in my existing tool. The application allows for Python scripting via commu... | How can I "hook into" Python from C++ when it executes a function? My goal is to profile | I'm implementing a profiler in an application and I'm a little flummoxed about how to implement Python profiling such that the results can be displayed in my existing tool. The application allows for Python scripting via communication with the python interpreter.
I was wondering if anyone has ideas on how to profile Py... | [
"Well not sure what your goal is, but I'd personally not start from zero but use the existing modules for profiling. The cprofile module was written in C and should be easily extensible if the documentation is to be believed: http://docs.python.org/release/3.2/library/profile.html#extensions-deriving-better-profile... | [
1,
0
] | [] | [] | [
"c++",
"profiling",
"python"
] | stackoverflow_0007033612_c++_profiling_python.txt |
Q:
pyparsing optional subfield
This is a continuation of pyparsing, Each, results name . I've been having great success with pyparsing, but I'm stuck when parsing SQL order by clauses. The problem is that any of the fields can be set to ascending or descending order.
So, a SQL query might look like:
SELECT a FROM x ... | pyparsing optional subfield | This is a continuation of pyparsing, Each, results name . I've been having great success with pyparsing, but I'm stuck when parsing SQL order by clauses. The problem is that any of the fields can be set to ascending or descending order.
So, a SQL query might look like:
SELECT a FROM x WHERE a = b ...
ORDER BY c, d
ORD... | [
"Each orderBy column has a column name, and an optional order direction. There can be multiple columns, separated by commas. You should group each column-direction pair so that the column name and order direction are kept together. Lists of things separated by commas are a natural for pyparsing's delimitedList.\... | [
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0007032676_pyparsing_python.txt |
Q:
How to sanitize username that would be in urls
What is a good regex filter for usernames? [A-Za-z0-9 ] okay, or is that too inflexible? What other things should I look for? (Trimming whitespaces?)
A:
That is fine for a un, but you might want to let them use -, _, %, @ and .. (Basically, [a-zA-Z0-9._%+-]). Man... | How to sanitize username that would be in urls | What is a good regex filter for usernames? [A-Za-z0-9 ] okay, or is that too inflexible? What other things should I look for? (Trimming whitespaces?)
| [
"That is fine for a un, but you might want to let them use -, _, %, @ and .. (Basically, [a-zA-Z0-9._%+-]). Many people will like using their email for a username and that covers well over 99% of them. In low security situations, I say let'em.\n",
"Just encode the username when you are using it in a URL.\n",
"Y... | [
3,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007033210_python_regex.txt |
Q:
python regex problem
s = re.sub(r"<style.*?</style>", "", s)
Isn't this code supposed to remove styles in the s string? Why does it not work? I am trying to remove the following code:
<style type="text/css">
body { ... }
</style>
Any suggestion?
A:
No it's the re.DOTALL flag that is necessary !
re.DOTALL
Make ... | python regex problem | s = re.sub(r"<style.*?</style>", "", s)
Isn't this code supposed to remove styles in the s string? Why does it not work? I am trying to remove the following code:
<style type="text/css">
body { ... }
</style>
Any suggestion?
| [
"No it's the re.DOTALL flag that is necessary !\nre.DOTALL\nMake the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.\nhttp://docs.python.org/library/re.html#re.DOTALL\nEdit\nIn some cases, it may be necessary to have a dot matching ... | [
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007033883_python_regex.txt |
Q:
how to get USB guitar interface data with (preferably) python
I am wondering if anyone out there knows how I might go about getting audio data with a programming language from an M-Audio USB guitar interface? I would prefer to use python. I would like to get into live audio processing programming and am just curio... | how to get USB guitar interface data with (preferably) python | I am wondering if anyone out there knows how I might go about getting audio data with a programming language from an M-Audio USB guitar interface? I would prefer to use python. I would like to get into live audio processing programming and am just curious where to start.
If anyone knows or has experience in getting dat... | [
"If you can record from the device by using common audio recorder, such as Audacity, then you can use pyaudio.\npyaudio is a python library binds for PortAudio. If you use C, you can use PortAudio directly.\n",
"For Python, I might recommend SndObj. I haven't used it myself, but it seems to allow you to use ASIO... | [
3,
1
] | [] | [] | [
"audio",
"guitar",
"python",
"usb"
] | stackoverflow_0007033599_audio_guitar_python_usb.txt |
Q:
Run executable from script with conditions python2.6
I am looking for a way to execute ABAQUS (a program) automatically from a python script with certain conditions. In Linux's command (terminal) line I type in
abq683 cae script=XX.py
and it will have ABAQUS run the script. I am aware of the python module 'subp... | Run executable from script with conditions python2.6 | I am looking for a way to execute ABAQUS (a program) automatically from a python script with certain conditions. In Linux's command (terminal) line I type in
abq683 cae script=XX.py
and it will have ABAQUS run the script. I am aware of the python module 'subprocess' and it can run the basic program, which is the 'ab... | [
"import subprocess\nretcode = subprocess.call(['abq684', 'cae', 'script=XX.py'])\n\n"
] | [
0
] | [] | [] | [
"python",
"terminal"
] | stackoverflow_0007034408_python_terminal.txt |
Q:
Python and XML Processing
I have used urllib to get the following data:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<videos xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:www="http://www.www.com"">
<video type="cl">
<cd>
<src lang="music">http://www.google.com/ </src>
</cd>
... | Python and XML Processing | I have used urllib to get the following data:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<videos xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:www="http://www.www.com"">
<video type="cl">
<cd>
<src lang="music">http://www.google.com/ </src>
</cd>
</video>
</videos>
I want to... | [
"Remove the first forward-slash from the path: video/cd/src:\nimport xml.etree.ElementTree as etree\ndata='''<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><videos xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:www=\"http://www.www.com\"><video type=\"cl\"><cd><src lang=\"music\">http://www.googl... | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0007034379_python_xml.txt |
Q:
Converting 16-bit integer to 32-bit floating-point
I am trying to port a portion of a code written in a different language (an obscure one called Igor Pro by Wavemetrics for those of you have heard of it) to Python.
In this code, there is a conversion of a data type from a 16-bit integer (read in from a 16-bit, bi... | Converting 16-bit integer to 32-bit floating-point | I am trying to port a portion of a code written in a different language (an obscure one called Igor Pro by Wavemetrics for those of you have heard of it) to Python.
In this code, there is a conversion of a data type from a 16-bit integer (read in from a 16-bit, big endian binary file) to single-precision (32-bit) float... | [
"import numpy\ntmp=numpy.array([-24160,18597,-24160,18597,-24160, 0], numpy.int16)\ntmp.dtype = numpy.float32\nprint tmp\n\nResult:\n[ 3.39213000e+05 3.39213000e+05 5.79801253e-41]\n\nI had to add a zero to the list of value because there are an odd number of values. It cannot interpret those as 32 bit floats ... | [
6,
2,
1
] | [] | [] | [
"floating_point",
"integer",
"python"
] | stackoverflow_0007034404_floating_point_integer_python.txt |
Q:
calling a method from a python interpreter
per Voo's advice on this thread:
How can I "hook into" Python from C++ when it executes a function? My goal is to profile
I have opened up a new thread for a new question, which is, in C++, how can I initialize a PythonInterpreter and then call a method from it. Specifica... | calling a method from a python interpreter | per Voo's advice on this thread:
How can I "hook into" Python from C++ when it executes a function? My goal is to profile
I have opened up a new thread for a new question, which is, in C++, how can I initialize a PythonInterpreter and then call a method from it. Specifically, I'd like to be able to call cProfile's meth... | [
"Okay that'll be a bit longer. Note that I pretty much ignore all \"usual\" error checking - pretty much any python method may return NULL in which case you should handle that gracefully. I show the \"unusual\" part checking if the given object is callable. Note that PyDECREF fails if the object pointer is NULL, Py... | [
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0007034334_c++_python.txt |
Q:
os.path.exists does not recognize a subdirectory under C:\Windows\system32\drivers
Can anyone tell me why this behaviour is exhibited:
C:\...>dir C:\Windows\System32\drivers\subdir\0xDEADBEEF.008
Volume in drive C is Win7HPx64
Volume Serial Number is 04BF-EE2E
Directory of C:\Windows\System32\drivers\subdir\0x... | os.path.exists does not recognize a subdirectory under C:\Windows\system32\drivers | Can anyone tell me why this behaviour is exhibited:
C:\...>dir C:\Windows\System32\drivers\subdir\0xDEADBEEF.008
Volume in drive C is Win7HPx64
Volume Serial Number is 04BF-EE2E
Directory of C:\Windows\System32\drivers\subdir\0xDEADBEEF.008
08/11/2011 04:21 PM <DIR> .
08/11/2011 04:21 PM <DIR> ... | [
"If you're using a 32-bit Python build on 64-bit Windows, then accesses to C:\\WINDOWS\\SYSTEM32 will be transparently redirected to C:\\WINDOWS\\SYSWOW64. On 64-bit systems, SYSTEM32 contains 64-bit DLLs and SYSWOW64 contains 32-bit DLLs.\nTo access the real SYSTEM32 directory from a 32-bit Python, use C:\\WINDOW... | [
4
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0007034475_python_windows.txt |
Q:
Pre-hashed string keys for faster Python dictionaries lookup?
How can I instruct python to store, internally, a pre-hashed version of my strings, so that it will use that value when I perform dict/set lookups using my string as a key?
I remember reading about it some weeks ago, but can't find it in python docs at... | Pre-hashed string keys for faster Python dictionaries lookup? | How can I instruct python to store, internally, a pre-hashed version of my strings, so that it will use that value when I perform dict/set lookups using my string as a key?
I remember reading about it some weeks ago, but can't find it in python docs at the moment :-/
| [
"String interning is probably what you're thinking of.\nSee sys.intern in Python 3\nSee intern in Python 2\n"
] | [
3
] | [] | [] | [
"dictionary",
"hash",
"optimization",
"python",
"string"
] | stackoverflow_0007034755_dictionary_hash_optimization_python_string.txt |
Q:
Handling Group4 TIFF images in python
PIL doesn't natively support G4 images, is there some other python package that does? I need to read multi-page TIFF images and pull convert them into gif/png on the fly to serve up in a web page. (I'm not converting them all on the fly, but cherry picking them for display).... | Handling Group4 TIFF images in python | PIL doesn't natively support G4 images, is there some other python package that does? I need to read multi-page TIFF images and pull convert them into gif/png on the fly to serve up in a web page. (I'm not converting them all on the fly, but cherry picking them for display).
I've considered using ImageMagick which ha... | [
"See this post about a patch against PIL, this project to wrap FreeImage, and this project to wrap libtiff.\n",
"Using PythonMagick:\nfrom PythonMagick import Image\nImage('CCITT_4.TIF[0]').write(\"PNG8:CCITT_4.PNG\")\n\n"
] | [
2,
1
] | [] | [] | [
"libtiff",
"python",
"tiff"
] | stackoverflow_0007034015_libtiff_python_tiff.txt |
Q:
python cocoa shared application with a timer
I would like to have an interval timer within a cocoa "shared application". I have a python cocoa application (not sure it is the right terminology) using PyObjCTools.
app = App.sharedApplication()
ticker=Ticker()
timer=NSTimer.timerWithTimeInterval_target_selector_use... | python cocoa shared application with a timer | I would like to have an interval timer within a cocoa "shared application". I have a python cocoa application (not sure it is the right terminology) using PyObjCTools.
app = App.sharedApplication()
ticker=Ticker()
timer=NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats(0.1, ticker, 'tick', None, False)
##... | [
"You don't associate the timer with the shared application. You associate the timer with the run loop. Do\nNSRunLoop.currentRunLoop.addTimer_forMode(timer,NSRunLoopCommonModes)\n\n(sorry if the syntax is not correct as a Python code... ) See the documentation.\n"
] | [
0
] | [] | [] | [
"cocoa",
"macos",
"python"
] | stackoverflow_0007034998_cocoa_macos_python.txt |
Q:
CSS won't display in Django Admin area after schema evolution and 'manage syncdb'
How do I keep Django Admin media from breaking every time the db schema changes? Apparently something gets corrupted after I change the models and sync them to the db, because that's when it stops displaying Admin area CSS. I wish I... | CSS won't display in Django Admin area after schema evolution and 'manage syncdb' | How do I keep Django Admin media from breaking every time the db schema changes? Apparently something gets corrupted after I change the models and sync them to the db, because that's when it stops displaying Admin area CSS. I wish I knew what was being corrupted.
The problem is not in Django itself, because when I try... | [
"Do you have an app called media in your site? It is probably conflicting with the urls that django uses for its admin madia.\nCould you post the list of apps and models?\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007034958_django_python.txt |
Q:
Build Automation for Django
I'm pretty new to doing sysadmin stuff for my development and to the django framework. I want to have a different username/password for my local dev station and to my production environment.
I'm using dotcloud as the server. I can write a post install script (in python, bash, whatever) ... | Build Automation for Django | I'm pretty new to doing sysadmin stuff for my development and to the django framework. I want to have a different username/password for my local dev station and to my production environment.
I'm using dotcloud as the server. I can write a post install script (in python, bash, whatever) and it will execute it on every n... | [
"The django standard way is to use an environmanet variable DJANGO_SETTINGS_MODULE. Point it to different settings and let both import a common settings module for common things:\n# settings_production.py\n\nfrom settings_common import *\nDEBUG = False\nDATABASES = {...}\n\n\n# settings_development.py\n\nfrom setti... | [
3,
1
] | [] | [] | [
"build",
"build_automation",
"django",
"python"
] | stackoverflow_0007033846_build_build_automation_django_python.txt |
Q:
Forcing Elements in a Numpy Array to be Within a Specified Range
I have a numpy array and I want to force every element that is less than zero to be zero and every element above 255 will be forced down to 255.
eg. x = (-1,7,255,299) => (0,7,255,255)
Is there a not too complicated one-liner that can accomplish thi... | Forcing Elements in a Numpy Array to be Within a Specified Range | I have a numpy array and I want to force every element that is less than zero to be zero and every element above 255 will be forced down to 255.
eg. x = (-1,7,255,299) => (0,7,255,255)
Is there a not too complicated one-liner that can accomplish this?
| [
"The answer is numpy.clip\nnumpy.clip(x, 0, 255)\n\nRegarding the question posted in your title: don't. You can apply the lambda function to every element, using vectorize but that's rarely the best choice.\n"
] | [
8
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007035175_numpy_python.txt |
Q:
Algorithm: Stop invalid entries into a Competition in python script
I have an Android Mobile App that is really just a calendar & you can click a certain date & a secret code pops up. The user uses that code to enter a competition - they follow the link to the competition HTML page(python script really) & enter th... | Algorithm: Stop invalid entries into a Competition in python script | I have an Android Mobile App that is really just a calendar & you can click a certain date & a secret code pops up. The user uses that code to enter a competition - they follow the link to the competition HTML page(python script really) & enter their details to enter the competition. There are 100 minor prizes & 3 majo... | [
"Use an HMAC to generate the code based on a secret you share between the Android app and the site. As the text for the HMAC, you can use a random value, which you include in the resulting code, or something unique to the user, such as their email address (meaning that each user can only have one valid code). If th... | [
1
] | [] | [] | [
"algorithm",
"android",
"computer_science",
"python"
] | stackoverflow_0007034870_algorithm_android_computer_science_python.txt |
Q:
django templatetag, get posts related to current post's taggit-tags
I am writing a blog with django, and at the bottom of a blog entry i want to display the 5 latest entries relative to the tags i have attached using django-taggit.
So i figured i needed to pass the current blog entry (the one we are viewing) to a ... | django templatetag, get posts related to current post's taggit-tags | I am writing a blog with django, and at the bottom of a blog entry i want to display the 5 latest entries relative to the tags i have attached using django-taggit.
So i figured i needed to pass the current blog entry (the one we are viewing) to a templatetag that would retrieve entries with the same taggit-tags, or clo... | [
"You can pass the list directly in the context. If you are using class-based generic views, pass an\ndef get_context_data(self, **kwargs):\n context_data = super(EntryView, self).get_context_data(**kwargs)\n related_entries = Entry.objects.filter(\n tags__name__in=list(self.object.tags.values_list('nam... | [
2
] | [] | [] | [
"django",
"django_taggit",
"django_templates",
"python"
] | stackoverflow_0007032503_django_django_taggit_django_templates_python.txt |
Q:
How to use the hashtags on twitter using python?
Can anyone tell me how to use retrieve hashtags from Twitter in Python? I have tried using:
test = api.GetUserTimeline()
for i in test:
text = i.text
hashtag = i.hashtags
print text
print "\n" + hashtag
It returns hashtag as None, while in the text ... | How to use the hashtags on twitter using python? | Can anyone tell me how to use retrieve hashtags from Twitter in Python? I have tried using:
test = api.GetUserTimeline()
for i in test:
text = i.text
hashtag = i.hashtags
print text
print "\n" + hashtag
It returns hashtag as None, while in the text it is "life is #wonderful"
| [
"As far as I can tell, the underlying Twitter API doesn't actually parse out hashtags for you, and neither does the python-twitter wrapper. (Of course, I didn't look very hard ;))\nFortunately, it's pretty easy to do this yourself. Hashtags are words that start with '#'; so we ask Python for each word that starts w... | [
3
] | [] | [] | [
"hashtag",
"python"
] | stackoverflow_0007034880_hashtag_python.txt |
Q:
Confused by python package scoping
I'm new to python, and confused by certain behavior.
I have a directory called d. In this directory, I have two files:
__init__.py:
from d import *
and
d.py:
var = None
def printVar():
global var
print "from d: var=%s" % `var`
From the directory above d, I get this intera... | Confused by python package scoping | I'm new to python, and confused by certain behavior.
I have a directory called d. In this directory, I have two files:
__init__.py:
from d import *
and
d.py:
var = None
def printVar():
global var
print "from d: var=%s" % `var`
From the directory above d, I get this interaction within python:
>>> import d
>>> d.... | [
"When you say:\nimport d\n\nyou're importing the package, not the module.\nJust import the module d within the package:\n>>> from d import d\n>>> d.var = 5\n>>> d.printVar()\nfrom d: var=5\n\n",
"I think the actual name of the global var should be d.d.var (because it is in module d in package d)\nSo you could\n1)... | [
2,
0,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0007035646_package_python.txt |
Q:
Change default python version from 2.6.6 to 2.7 and also configure django
I am new to linux (Ubuntu) and python (Django). By default there is python 2.6.6 in my linux, I installed python 2.7. In the command prompt when I type python it goes to python 2.6.6, I want to change my default python to 2.7.
A:
Ubuntu mi... | Change default python version from 2.6.6 to 2.7 and also configure django | I am new to linux (Ubuntu) and python (Django). By default there is python 2.6.6 in my linux, I installed python 2.7. In the command prompt when I type python it goes to python 2.6.6, I want to change my default python to 2.7.
| [
"Ubuntu might have a Python2.7 package. If so, install that then use that to create a virtualenv and put Django inside that. \n",
"I recommend to use pythonbrew which can install and switch between multi Python interpreters in your $HOME without touch your system directories.\nBTW, when install python, use the co... | [
3,
2,
0,
0
] | [] | [] | [
"linux",
"python",
"ubuntu"
] | stackoverflow_0007035986_linux_python_ubuntu.txt |
Q:
Parse syslog and only match entries within the last x minutes
I need to create a script that will run every 5 minutes via cron and parse syslog, but only match the entries within the last 5 minutes of the execution time.
If there a module I can leverage for part of this? If so, will it work when running at midn... | Parse syslog and only match entries within the last x minutes | I need to create a script that will run every 5 minutes via cron and parse syslog, but only match the entries within the last 5 minutes of the execution time.
If there a module I can leverage for part of this? If so, will it work when running at midnight when the date is one day ahead? The date format of my log is:... | [
"You can use datetime's strptime function:\n>>> datetime.strptime(\"Jun 20 14:04:47\", \"%b %d %H:%M:%S\")\n# => datetime.datetime(1900, 6, 20, 14, 4, 47)\n\nYou can then use simple operators like < to compare datetimes. (You'll have to be aware that if a year is not specified, it will default to 1900.)\n",
"I ha... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0007035967_python.txt |
Q:
Problem with python curl while submitting file
#!/usr/bin/python
import pycurl
import re
import StringIO
#CONSTANTS
URL = "http://www.imagehost.org"
FILE = "/datos/poop1.jpg"
POST_DATA = [("a", "upload"), ("file[]", (pycurl.FORM_FILE, FILE))]
buffer = StringIO.StringIO()
c = pycurl.Curl()
c.setopt( c.URL, URL )... | Problem with python curl while submitting file | #!/usr/bin/python
import pycurl
import re
import StringIO
#CONSTANTS
URL = "http://www.imagehost.org"
FILE = "/datos/poop1.jpg"
POST_DATA = [("a", "upload"), ("file[]", (pycurl.FORM_FILE, FILE))]
buffer = StringIO.StringIO()
c = pycurl.Curl()
c.setopt( c.URL, URL )
c.setopt( c.POST, 1 )
c.setopt( c.POSTFIELDS, P... | [
"The pycurl documentation is not so clear on this, but the HTTPPOST option can take a list of tuples, each exactly two elements long. Each tuple's first argument is the form field name, the second is the value.\nHowever, the value may be a tuple as well. This tuple must contains pairs of data relating to that field... | [
6,
2,
1
] | [] | [] | [
"curl",
"python",
"upload"
] | stackoverflow_0000679966_curl_python_upload.txt |
Q:
os.exec on Windows
I have a script that calls os.execvp into another Python instance. After doing this, I appear to be attached to a cmd.exe instance, not the Python instance I just created. The Python instance responds to Ctrl+C however.
H:\bin>Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500
32 bit (In... | os.exec on Windows | I have a script that calls os.execvp into another Python instance. After doing this, I appear to be attached to a cmd.exe instance, not the Python instance I just created. The Python instance responds to Ctrl+C however.
H:\bin>Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500
32 bit (Intel)] on win32
Type "hel... | [
"On Unix executing binaries is split into two stages - fork(3) to clone current process and exec(3) to load executable into address space. On windows there is only CreateProcess which does the same thing as fork+exec.\nFor portability your best bet is to use subprocess.Popen (which also does proper filename quoting... | [
4
] | [] | [] | [
"exec",
"python",
"python_3.x",
"windows",
"windows_xp"
] | stackoverflow_0007004687_exec_python_python_3.x_windows_windows_xp.txt |
Q:
How to optimize edit distance code?
How to optimize this edit distance code i.e. finding the number of bits changed between 2 values! e.g. word1 = '010000001000011111101000001001000110001'
word2 = '010000001000011111101000001011111111111'
When i tried to run on Hadoop it takes ages to complete?
How ... | How to optimize edit distance code? | How to optimize this edit distance code i.e. finding the number of bits changed between 2 values! e.g. word1 = '010000001000011111101000001001000110001'
word2 = '010000001000011111101000001011111111111'
When i tried to run on Hadoop it takes ages to complete?
How to reduce the for loop and comparsions ?
... | [
"I looked for a bit counting algorithm online, and I found this page, which has several good algorithms. My favorite there is a one-line function which claims to work for Python 2.6 / 3.0:\nreturn sum( b == '1' for b in bin(word1 ^ word2)[2:] )\n\nI don't have Python, so I can't test, but if this one doesn't work, ... | [
4,
3,
0
] | [] | [] | [
"edit",
"hadoop",
"loops",
"optimization",
"python"
] | stackoverflow_0007036277_edit_hadoop_loops_optimization_python.txt |
Q:
how to align qtableview row at the right side in pyqt4?
How to align the content of the qtable view in the right? I use this class in making my table.
class MyTableModel(QAbstractTableModel):
def __init__(self, datain, headerdata, parent=None, *args):
""" datain: a list of lists
headerdat... | how to align qtableview row at the right side in pyqt4? | How to align the content of the qtable view in the right? I use this class in making my table.
class MyTableModel(QAbstractTableModel):
def __init__(self, datain, headerdata, parent=None, *args):
""" datain: a list of lists
headerdata: a list of strings
"""
QAbstractTableModel.... | [
"Take a look to the Qt::ItemDataRole enum (especially the TextAlignmentRole).\nYou can do something like this:\ndef data(self, index, role): \n if index.isValid():\n return QVariant()\n\n if role == Qt.DisplayRole:\n return QVariant(self.arraydata[index.row()][index.column()])\n elif role == ... | [
4
] | [] | [] | [
"pyqt4",
"python",
"qtableview"
] | stackoverflow_0007035849_pyqt4_python_qtableview.txt |
Q:
change django from python2.6 to python2.7
I am new Linux (Ubuntu) and Python,my Ubuntu come with python2.6.6 installed in it.I newly install python 2.7, and again installed django.
I want to configure django with python2.7. But now it configured with python2.6. I am totally confused since a new Linux user.I expec... | change django from python2.6 to python2.7 | I am new Linux (Ubuntu) and Python,my Ubuntu come with python2.6.6 installed in it.I newly install python 2.7, and again installed django.
I want to configure django with python2.7. But now it configured with python2.6. I am totally confused since a new Linux user.I expect all your help,Thanks in advance
| [
"Use virtualenvwrapper. To install:\npip install virtualenvwrapper\n\nand then modify your .bashrc as described in http://www.doughellmann.com/docs/virtualenvwrapper/\nTo use:\nmkvirtualenv ENV_NAME --python=python2.7 --no-site-packages\nworkon ENV_NAME\npip install whatever packages you need\n# or\npip install -r ... | [
4
] | [] | [] | [
"django",
"linux",
"python",
"ubuntu"
] | stackoverflow_0007036690_django_linux_python_ubuntu.txt |
Q:
Redirect stdout to a text widget
I have searched and found some answers on redirecting the sys.stdout to a text widget in python, but I can't apply them to my specific needs.
I have coded a simple GUI with tkinter for a downloader found here and I want the stdout messages to appear on a text widget, which after m... | Redirect stdout to a text widget | I have searched and found some answers on redirecting the sys.stdout to a text widget in python, but I can't apply them to my specific needs.
I have coded a simple GUI with tkinter for a downloader found here and I want the stdout messages to appear on a text widget, which after much effort I couldn't achieve.
So let'... | [
"You would need to open it as a subprocess and then pipe the stdout from there to a writeable source.\ne.g.\nimport subprocess\nmy_frame = your_gui_code_here()\nprocess = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nmy_frame.add_text(process.communicate()[0]) #or however you add text.\n\n... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007037121_python.txt |
Q:
How to define a class with a variable property
I am working with 2 classes defined as zone and system. The system is supposed to contain several zones, but the number can vary. So, I have defined for example the class zone as such:
class zone(object):
def __init__ (self,
nameZone = None,
height... | How to define a class with a variable property | I am working with 2 classes defined as zone and system. The system is supposed to contain several zones, but the number can vary. So, I have defined for example the class zone as such:
class zone(object):
def __init__ (self,
nameZone = None,
height = None,
width = None):
self.nameZo... | [
"You can use the variable args features.\nclass system(object):\n def __init__(self, SystemName, *zones):\n self.SystemName = SystemName\n self.zones = list(zones)\n\n # The number of zones is the length of the zones list.\n\nThen you can just put any number, without even having to specify how m... | [
0,
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0007037261_class_python.txt |
Q:
SQLAlchemy intricacies with relationships and uncommitted objects
I am using SQLAlchemy via Flask, and I want to add simple personal messaging to my webapp. The model has a User class, a PersonalMessage class and a PersonalMessageUser association class, with the latter setting up relationships to the former two—n... | SQLAlchemy intricacies with relationships and uncommitted objects | I am using SQLAlchemy via Flask, and I want to add simple personal messaging to my webapp. The model has a User class, a PersonalMessage class and a PersonalMessageUser association class, with the latter setting up relationships to the former two—nothing fancy. Here is a stripped down version:
import collections
impo... | [
"When you call\nself._pm_users.append(PersonalMessageUser(\n message=self, user_type='From', user=from_,\n))\n\nyou have twice append object to _pm_users list\nThis should work for you:\nPersonalMessageUser(\n message=self, user_type='From', user=from_,\n)\n\nor\nself._pm_users.append(\n PersonalMessageUse... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007017058_python_sqlalchemy.txt |
Q:
Good Python programs for beginning CS student to write?
I plan on learning CS from my Python book before class starts (next semester though).
I am learning computer science from a Python Programming book. My question is, can I get some examples of good programs to write to begin learning programming? Once I finish... | Good Python programs for beginning CS student to write? | I plan on learning CS from my Python book before class starts (next semester though).
I am learning computer science from a Python Programming book. My question is, can I get some examples of good programs to write to begin learning programming? Once I finish the book, I want to start writing my own programs. I'm aware... | [
"If you're interested in algorithmical and mathematical problems to solve, Project Euler has quite a few. At least a lot of other people have found them both entertaining and educational to solve, and Python is certainly a good language for the kind of problems.\n",
"Google Code has a great coarse for python: Goo... | [
7,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007036801_python.txt |
Q:
How to separate the elements from a nested list? Eg;- [1,[2,3]], I need to get 1,2,3 printed..?
Possible Duplicate:
Flatten (an irregular) list of lists in Python
Hi I was working out with nested lists in python and found this to be a big problem. I know we should go with recursive functions but unable to procee... | How to separate the elements from a nested list? Eg;- [1,[2,3]], I need to get 1,2,3 printed..? |
Possible Duplicate:
Flatten (an irregular) list of lists in Python
Hi I was working out with nested lists in python and found this to be a big problem. I know we should go with recursive functions but unable to proceed..
| [
"If you have list of list -e.g max depth is 1 then you can use the following code:\nlVals = [1,[2,3]]\n\nres = []\nfor i in lVals:\n if isinstance(i, list):\n res.extend(i)\n else:\n res.append(i)\n\nprint res\n>>> [1,2,3]\n\n",
"def flatten(li):\n if not isinstance(li, list):\n retu... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007037552_python.txt |
Q:
Inheritence and polymorphism properties
In the following code i am trying to implement inheritance and polymorphism properties,My question is obj1.hello3("1param","2param") obj1.hello3("11param") are these statements not correct what would be the correct way of doing this
#!/usr/bin/python
class test1:
... | Inheritence and polymorphism properties | In the following code i am trying to implement inheritance and polymorphism properties,My question is obj1.hello3("1param","2param") obj1.hello3("11param") are these statements not correct what would be the correct way of doing this
#!/usr/bin/python
class test1:
c,d = ""
def __init__(self,n):
... | [
"You are trying to implement method overloading rather than inheritance and polymorphism. \nPython does not support overloading in the way that C++, Java, C# etc. do. Instead, to achieve what you want in Python, you need to use optional parameters.\ndef hello3(self,a,b=None):\n if b is None:\n print \"He... | [
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007036668_python.txt |
Q:
lookahead assertions
I'm trying to match a label within a valid domain name using a regular expression in Python:
DOMAIN_LABEL_RE = """
\A(
(?<![\d\-]) # cannot start with digit or hyphen, looking behind
([a-zA-Z\d\-]*?)
([a-zA-Z]+)# need at least 1 letter
([a-zA-Z\d\-]*?)
(?!\-) # cannot end with a hyphen, lookin... | lookahead assertions | I'm trying to match a label within a valid domain name using a regular expression in Python:
DOMAIN_LABEL_RE = """
\A(
(?<![\d\-]) # cannot start with digit or hyphen, looking behind
([a-zA-Z\d\-]*?)
([a-zA-Z]+)# need at least 1 letter
([a-zA-Z\d\-]*?)
(?!\-) # cannot end with a hyphen, looking ahead
)\Z
"""
I'm tryin... | [
"\\A matches the start of the string and the following lookbehind matches if there is no hyphen before that position. \nYou are at the beginning of the string, of course there is no character before it!\nUse a negative lookahead instead: (?![\\d\\-]).\nSimilar for the end of the string. You have to use a negative l... | [
3
] | [] | [] | [
"python",
"regex",
"regex_lookarounds"
] | stackoverflow_0007037799_python_regex_regex_lookarounds.txt |
Q:
Django prepopulated_fields like method
Please forgive my naiveté with Django.
I want to create my own method which works much like prepopulated_fields for my custom admin page. Basically, when you put the url of an image in one field, I'd like to populate another field with the name of the image, height and width... | Django prepopulated_fields like method | Please forgive my naiveté with Django.
I want to create my own method which works much like prepopulated_fields for my custom admin page. Basically, when you put the url of an image in one field, I'd like to populate another field with the name of the image, height and width via javascript.
What would be the best appr... | [
"Using Javascript would be a probable move, if for some reason you want to show the attributes of the image. \nSee Javascript - Get Image height for an example of doing this. \nIf there's no need to show it at the form level but to simply populate the usually prefer to do this at the model level, such as\nfrom PIL... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0007036519_django_django_admin_django_forms_python.txt |
Q:
PYTHON- Given a starting word, which sequence of letters will allow you to maximize the number of valid words that can be spelled
Edit: New question. Given that I suspect this question is more difficult than I originally thought-- potentially NP-complex, I have a different question: what is useful algorithm that... | PYTHON- Given a starting word, which sequence of letters will allow you to maximize the number of valid words that can be spelled | Edit: New question. Given that I suspect this question is more difficult than I originally thought-- potentially NP-complex, I have a different question: what is useful algorithm that can get close to maximizing the number of letters used?
I was inspired to write a program based on the card game Scrabble Slam! I'm n... | [
"@Parseltongue\nYou might find out that although, there is an optimal solution for the given task, yet there is no known way to solve it in optimal way. This task is one of the NP-class problems. \nConsider this: \nsand --> [?]and \n\nat this point you have to iterate through ALL possible combinations of [?]and to ... | [
3,
0
] | [] | [] | [
"algorithm",
"python",
"trie"
] | stackoverflow_0007037464_algorithm_python_trie.txt |
Q:
Python: Effective replacing of substring
I have code like this:
def escape_query(query):
special_chars = ['\\','+','-','&&','||','!','(',')','{','}','[',']',
'^','"','~','*','?',':']
for character in special_chars:
query = query.replace(character, '\\%s' % character)
return... | Python: Effective replacing of substring | I have code like this:
def escape_query(query):
special_chars = ['\\','+','-','&&','||','!','(',')','{','}','[',']',
'^','"','~','*','?',':']
for character in special_chars:
query = query.replace(character, '\\%s' % character)
return query
This function should escape all occurr... | [
"Using reduce:\ndef escape_query(query):\n special_chars = ['\\\\','+','-','&&','||','!','(',')','{','}','[',']',\n '^','\"','~','*','?',':']\n return reduce(lambda q, c: q.replace(c, '\\\\%s' % c), special_chars, query)\n\n",
"The following code has exactly the same principle than the stev... | [
2,
2,
1,
0
] | [] | [] | [
"python",
"replace",
"substring"
] | stackoverflow_0007034695_python_replace_substring.txt |
Q:
xlwt: Is it possible to adjust the style of a cell after creating it?
After you do:
sheet.write(0, 1, 'whatevs')
Is it still possible to adjust the style of cell 0,1. The reason I am asking is that I have a list of errors I loop and I would like to color all the cells red that have an error.
I could do it when I... | xlwt: Is it possible to adjust the style of a cell after creating it? | After you do:
sheet.write(0, 1, 'whatevs')
Is it still possible to adjust the style of cell 0,1. The reason I am asking is that I have a list of errors I loop and I would like to color all the cells red that have an error.
I could do it when I write the cell but it will make my code a little more complex.
| [
"There is no API exposed to do it, you could look at the source code and come up with a way:\nrows = ws.get_rows()\nrows[0]._Row_cells[0].xf_idx = styleindex \n\nYou can get the styleindex by adding a style you created. \nstyle0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',\n ... | [
4
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0007037758_python_xlwt.txt |
Q:
Extending an existing web2py database
I have an existing web2py application. Now I need to create a new registration form using a db Table that includes a Field that requires a Row from a different Table.
This should be similar to what you commonly see with Country Fields in registration forms, except I want peop... | Extending an existing web2py database | I have an existing web2py application. Now I need to create a new registration form using a db Table that includes a Field that requires a Row from a different Table.
This should be similar to what you commonly see with Country Fields in registration forms, except I want people to be able to add values to the 'Country... | [
"Making a small improvement to the previous response:\n# create auth\nauth = Auth(db)\n# create the country table\ndb.define_table('country',\n Field('name'),\n Field('desc'),\n format = '%(name)s')\n# say you want to add it to auth_user table (not yet created)\nauth.set... | [
4,
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0007037421_python_web2py.txt |
Q:
Non greedy parsing with pyparsing
I'm trying to parse a line with pyparsing. This line is composed of a number of (key, values). What I'd like to get is a list of (key, values). A simple example:
ids = 12 fields = name
should result in something like: [('ids', '12'), ('fields', 'name')]
A more complex example:
i... | Non greedy parsing with pyparsing | I'm trying to parse a line with pyparsing. This line is composed of a number of (key, values). What I'd like to get is a list of (key, values). A simple example:
ids = 12 fields = name
should result in something like: [('ids', '12'), ('fields', 'name')]
A more complex example:
ids = 12, 13, 14 fields = name, title
s... | [
"The first problem lies in this line:\nval = ~key_equal + P.Word(P.alphanums+', ')\n\nIt suggests that the part matches any alphanumeric sequence, followed by the literal ', ', but instead it matches any sequence of alphanumeric characters, ',' and ' '.\nWhat you'd want instead is:\nval = ~key_equal + P.delimitedLi... | [
7
] | [] | [] | [
"grammar",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0007037451_grammar_parsing_pyparsing_python.txt |
Q:
How to capture events for each key press in wxPropertyGrid
In wxPython I'm trying to update an existing UI to use wxPropertyGrid instead of an array of individual UI elements. Currently the underlying object model is updated and validation is applied after each key press and I want to do the same with the Propert... | How to capture events for each key press in wxPropertyGrid | In wxPython I'm trying to update an existing UI to use wxPropertyGrid instead of an array of individual UI elements. Currently the underlying object model is updated and validation is applied after each key press and I want to do the same with the PropertyGrid.
The problem I'm having is that there doesn't seem to exis... | [
"Turns out you can capture EVT_CHAR events by binding directly to the text ctrl. As the text ctrl is only created when the property is selected however you can't do this when setting up the grid, rather you have to bind it following a EVT_PG_SELECTED event. \n"
] | [
0
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0007011416_python_wxpython_wxwidgets.txt |
Q:
Exported Selenium Script Throws Exception
I recorded an action using the Selenium IDE and used the File->Export Test Cases as Python 2 (Remote Control) format.
I am using Selenium RC 2.3.0
I then ran the script from command prompt but it throws an exception.
The exported Python 2 RC code is:
from selenium import s... | Exported Selenium Script Throws Exception | I recorded an action using the Selenium IDE and used the File->Export Test Cases as Python 2 (Remote Control) format.
I am using Selenium RC 2.3.0
I then ran the script from command prompt but it throws an exception.
The exported Python 2 RC code is:
from selenium import selenium
import unittest, time, re
class login(... | [
"Try using an XPath such as:\nsel.click('//a[contains(text(),\"Home\")]')\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0007038291_python_selenium_selenium_rc.txt |
Q:
Quickest way to read geometry data from a custom file
I'm trying to create a custom point cache format for Houdini and 3D Max. I have managed to send geometry data between both programs using a custom ascii and xml file. The file is just a list of vectors for every frame of animation. I am basically looping throug... | Quickest way to read geometry data from a custom file | I'm trying to create a custom point cache format for Houdini and 3D Max. I have managed to send geometry data between both programs using a custom ascii and xml file. The file is just a list of vectors for every frame of animation. I am basically looping throught the vectors from the file and setting the objects positi... | [
"c++ is extremely fast compared to maxscript.\nIf you ask me that is the only way to go.\nI've written several exporters \\ importers that works with ascii\\xlm, both in maxscript and c++, and c++ plugin for this is the way to go if you want speed.\nAlso writing to\\ reading as binary makes it even faster.\n"
] | [
0
] | [] | [] | [
"animation",
"caching",
"export",
"maxscript",
"python"
] | stackoverflow_0007030159_animation_caching_export_maxscript_python.txt |
Q:
order of words in python
I have a code like:
class <name>
{
public:
...
private:
...
};
I want to ensure that the public section is declared before the private section and not after that.One way of doing this in Python is by comparing the line numbers where these words occur.However,am not sure if this would work... | order of words in python | I have a code like:
class <name>
{
public:
...
private:
...
};
I want to ensure that the public section is declared before the private section and not after that.One way of doing this in Python is by comparing the line numbers where these words occur.However,am not sure if this would work when I have several such sect... | [
"This problem is, in general, much harder than you think. Not all classes are laid out like that.\n\nSome won't have private sections and rely on the default visibility.\nSome might not have public sections.\nSome might have multiple private and/or public sections.\nHow will you know when the class declaration has ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007038058_python.txt |
Q:
Creating a dynamic "variable layout" for split() in Python
I have a script that parses IIS logs and at the moment it fetches log lines one by one using split to put IIS field values into multiple variables like this:
date, time, sitename, ip, uri_stem, whatever = log_line.split(" ")
And, it works fine for the def... | Creating a dynamic "variable layout" for split() in Python | I have a script that parses IIS logs and at the moment it fetches log lines one by one using split to put IIS field values into multiple variables like this:
date, time, sitename, ip, uri_stem, whatever = log_line.split(" ")
And, it works fine for the default setup. But, if someone else uses a different log field layo... | [
"Changing the log line layout is a pretty big deal, but something that gets done from time to time because new items are added or existing items deleted. Rarely does someone simply shuffle around existing items just for the heck of it.\nThese kinds of changes do not happen every day; they should be pretty rare. A... | [
1,
1
] | [] | [] | [
"dynamic",
"python",
"split"
] | stackoverflow_0007036984_dynamic_python_split.txt |
Q:
Python: testing for None, testing for boolean value
Is there any low-level, implementation-related difference (performance-ish) between these approaches..?
# check if string is empty
# the preferred way it seems [1]
if string:
print string
else:
print "It's empty."
# versus [2]
if string is '':
# or [3]
... | Python: testing for None, testing for boolean value | Is there any low-level, implementation-related difference (performance-ish) between these approaches..?
# check if string is empty
# the preferred way it seems [1]
if string:
print string
else:
print "It's empty."
# versus [2]
if string is '':
# or [3]
if string == '':
For example, when testing for None, I s... | [
"Never use is for (value) equality testing. Only use it to test for object identity. It may work for the example if string is '', but this is implementation dependent, and you can't rely on it.\n>>> a = \"hi\"\n>>> a is \"hi\"\nTrue\n>>> a = \"hi there!\"\n>>> a is \"hi there!\"\nFalse\n\nOther than that, use whate... | [
8,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0007038681_python.txt |
Q:
Debugging python script executed in chroot environment
Is there a way to debug python script which is executed inside chroot by eclipse which is installed on my machine and chroot doesn't see it? I am not allowed to install eclipse inside chroot.
A:
You could always use the python debugger. Docs for PDB This all... | Debugging python script executed in chroot environment | Is there a way to debug python script which is executed inside chroot by eclipse which is installed on my machine and chroot doesn't see it? I am not allowed to install eclipse inside chroot.
| [
"You could always use the python debugger. Docs for PDB This allows you to create breakpoints in your programs. Poke variables and also generally have a look at the internals.\n"
] | [
0
] | [] | [] | [
"chroot",
"eclipse",
"linux",
"pydev",
"python"
] | stackoverflow_0007038541_chroot_eclipse_linux_pydev_python.txt |
Q:
How to get all indices for the maximum value in a numpy array?
I have an array of numbers, and the maximum value might occurrence more than once.
How can we get a collection of indices of all the occurrences of the maximum value in the array?
For example, for the following array:
import numpy as np
a = np.array((... | How to get all indices for the maximum value in a numpy array? | I have an array of numbers, and the maximum value might occurrence more than once.
How can we get a collection of indices of all the occurrences of the maximum value in the array?
For example, for the following array:
import numpy as np
a = np.array((1,2,3,2,3,2,1,3))
the result should be [2, 4, 7] (or an equivalent ... | [
"import numpy as np\n\na = np.array((1,2,3,2,3,2,1,3))\n\noccurences = np.where(a == a.max())\n\n# occurences == array([2, 4, 7])\n\n"
] | [
11
] | [] | [] | [
"arrays",
"indexing",
"list",
"numpy",
"python"
] | stackoverflow_0007038975_arrays_indexing_list_numpy_python.txt |
Q:
Python: exe file from script, significant performance decrese
I am testing a C++ code compiled to exe (O errors, 0 warnings). The code represents a console application. I run the apllication in the following ways:
a) from the windows7 command line: average time 497sec
b) from Python script using
subprocess.call ()... | Python: exe file from script, significant performance decrese | I am testing a C++ code compiled to exe (O errors, 0 warnings). The code represents a console application. I run the apllication in the following ways:
a) from the windows7 command line: average time 497sec
b) from Python script using
subprocess.call ()
with the average time 1201 sec!
Results:
The application runs alm... | [
"Are you measuring from the point that subprocess.call() is executed or from the point that you load the Python script? I would imagine that a large portion of that time arises from waiting for the Python interpreter to load, the subprocess module to load, any other modules you import, etc. If your Python script wh... | [
2
] | [] | [] | [
"performance",
"python",
"slowdown"
] | stackoverflow_0007038770_performance_python_slowdown.txt |
Q:
Conditional compilation in python
Hi I am trying to implement conditional compilation in python similar to this in C,I have seen this thread and this thread.
But this is not working. I am relatively new to python,how can we fix this ?
A:
Looks like you are trying to use this to submit solutions to an online judg... | Conditional compilation in python | Hi I am trying to implement conditional compilation in python similar to this in C,I have seen this thread and this thread.
But this is not working. I am relatively new to python,how can we fix this ?
| [
"Looks like you are trying to use this to submit solutions to an online judge. For gcc, the judge machine supplies a paramater -D ONLINE_JUDGE. This has the same effect as having the following in your code:\n#define ONLINE_JUDGE\n\nPython does not have a preprocessor. So there is no way of defining a macro (in the ... | [
2,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005295442_python.txt |
Q:
Translate Perl to Python: do this or die
I am moving a Perl (of which I have very little knowledge) script to python.
$path = $ENV{ 'SOME_NAME' } || die " SOME_NAME ENV VARIABLE NOT FOUND\n";
I can (hopefully) see what this line does, either set the variable 'path' to the environment variable 'SOME_NAME' or faili... | Translate Perl to Python: do this or die | I am moving a Perl (of which I have very little knowledge) script to python.
$path = $ENV{ 'SOME_NAME' } || die " SOME_NAME ENV VARIABLE NOT FOUND\n";
I can (hopefully) see what this line does, either set the variable 'path' to the environment variable 'SOME_NAME' or failing that then print an error message to the use... | [
"try:\n path = os.environ['SOME_NAME']\n var2 = os.environ['VAR2']\n var3 = os.environ['VAR3']\n var4 = os.environ['VAR4']\nexcept KeyError,e:\n print \"Not found: \", e\n\nYou can put more than one statement into a try block.\n",
"What you have there is actually pretty common idiom, and arguably t... | [
11,
6
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0007039274_perl_python.txt |
Q:
python logging how to create logfile as html
I read in wikipedia that python logging module was inspired by log4j .In log4j ,there is an HTMLLayout with which one can create the log file as html.Is there any such facility in python logging? Or do anyone know how I can format the log output into an html file ?
A:
... | python logging how to create logfile as html | I read in wikipedia that python logging module was inspired by log4j .In log4j ,there is an HTMLLayout with which one can create the log file as html.Is there any such facility in python logging? Or do anyone know how I can format the log output into an html file ?
| [
"the python logging module uses a http://docs.python.org/library/logging.html#logging.Formatter to format the output.\nYou can set your own formatter to output html. (see this other question How can I color Python logging output? for details on how to define a formatter)\n",
"I would not recommend storing logs as... | [
3,
3
] | [] | [] | [
"format",
"html",
"logging",
"python"
] | stackoverflow_0007039343_format_html_logging_python.txt |
Q:
building python tkinter+pmw with cx_freez failed
Hi. I have created a program in python which uses tkinter and pmw, I have build it with the cx_freez, every thing fine, it completes the building process, but when I try to run the exe file I got some path error, but that path is correct don't know why still I am ge... | building python tkinter+pmw with cx_freez failed | Hi. I have created a program in python which uses tkinter and pmw, I have build it with the cx_freez, every thing fine, it completes the building process, but when I try to run the exe file I got some path error, but that path is correct don't know why still I am getting the error, please any one can help me I have to ... | [
"Based on my first rule of debugging (\"assume the error message it telling the literal truth\"), it says it can't find a path with the literal name *.*. Do you have such a file with the actual three-byte name *.*? My guess is, no. I've never used cx_freeze, but I'm wondering if it's possible you used it wrong and ... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007038598_python_tkinter.txt |
Q:
Efficient data migration on a large django table
I need to add a new column to a large (5m row) django table. I have a south schemamigration that creates the new column. Now I'm writing a datamigration script to populate the new column. It looks like this. (If you're not familiar with south migrations, just ign... | Efficient data migration on a large django table | I need to add a new column to a large (5m row) django table. I have a south schemamigration that creates the new column. Now I'm writing a datamigration script to populate the new column. It looks like this. (If you're not familiar with south migrations, just ignore the orm. prefixing the model name.)
print "Migrati... | [
"Ensure settings.DEBUG is set to False. DEBUG=True fills memory especially with database intensive operations, since it stores all queries sent to the RDBMS within a view.\nWith Django 1.8 out, it should not be necessary since a hardcoded max of 9000 queries are now stored, instead of an infinite number before.\n",... | [
7,
2,
2,
2,
1
] | [] | [] | [
"django",
"django_models",
"django_south",
"performance",
"python"
] | stackoverflow_0006271911_django_django_models_django_south_performance_python.txt |
Q:
Why is my file getting closed if I don't do anything with it for a while?
Original situation:
The application I'm working on at the moment will receive notification from another application when a particular file has had data added and is ready to be read. At the moment I have something like this:
class Foo(object... | Why is my file getting closed if I don't do anything with it for a while? | Original situation:
The application I'm working on at the moment will receive notification from another application when a particular file has had data added and is ready to be read. At the moment I have something like this:
class Foo(object):
def __init__(self):
self.myFile = open("data.txt", "r")
... | [
"* Initial, Partial Answer (Added to Question) *\nI think I just figured this out. After foo = Foo(), with no code left to keep the module busy, it would appear that the object ceases to exist, despite the fact that the application is still running, with a Swing window doing stuff. \nIf I do this:\nfoo = Foo()\nwhi... | [
4,
2
] | [] | [] | [
"file",
"jvm",
"jython",
"python",
"swing"
] | stackoverflow_0006991878_file_jvm_jython_python_swing.txt |
Q:
Parameter passing in Oauth1 - google API
I have authenticated the the user with scope of Google mail and Google contacts using Oauth1. Fetching mail is working perfectly fine with imaplib
While calling contacts API I'm getting the responds but when I make parametrized call i'm getting an error like "Authorization ... | Parameter passing in Oauth1 - google API | I have authenticated the the user with scope of Google mail and Google contacts using Oauth1. Fetching mail is working perfectly fine with imaplib
While calling contacts API I'm getting the responds but when I make parametrized call i'm getting an error like "Authorization required"
eg:The user is authenticated for the... | [
"I have identified the problem:\nThe problem was I was not including the parameters of the URL before generating signature for oAuth 1.0\n"
] | [
1
] | [] | [] | [
"authentication",
"google_contacts_api",
"oauth",
"python"
] | stackoverflow_0007022314_authentication_google_contacts_api_oauth_python.txt |
Q:
In python, how to have a 'run' subpackage in a directory?
I would prefer to have the structure to look like:
Overall_Package/
__init__.py
run_package/{
__init__.py
run__subpackage1.py
run_subpackage2.py
run_subpackage3.py
...
}
code package/ {
Basic_code_package_that_is_used_in_many_if_not_all_the_sub_package... | In python, how to have a 'run' subpackage in a directory? | I would prefer to have the structure to look like:
Overall_Package/
__init__.py
run_package/{
__init__.py
run__subpackage1.py
run_subpackage2.py
run_subpackage3.py
...
}
code package/ {
Basic_code_package_that_is_used_in_many_if_not_all_the_sub_packages
Sub_package1
subpackage2
....
}
I cannot use relative import... | [
"I'm not quite sure I follow your question and what is it exactly you want. Do you need to distribute this and would like it to have that structure? If so you can always use setuptools or distutils and install your package with it's structure to python's site-packages directory.\n"
] | [
0
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0007039607_import_package_python.txt |
Q:
Inputting the time and comparing it with user input
I'm trying to make a function run within a Python script at a certain time given by the user. To do this I'm using the datetime module.
This is part of the code so far:
import os
import subprocess
import shutil
import datetime
import time
def process():
pa... | Inputting the time and comparing it with user input | I'm trying to make a function run within a Python script at a certain time given by the user. To do this I'm using the datetime module.
This is part of the code so far:
import os
import subprocess
import shutil
import datetime
import time
def process():
path = os.getcwd()
outdir = os.getcwd() + '\Output'
... | [
"I can see various things to be commented in the code you propose, but main one is on selected_time = selected_hour + ..., because I think you are adding integers with different units. You should maybe start with selected_time = selected_hour * 3600 + ....\nSecond one is when you try to check the validity of the in... | [
0,
0
] | [] | [] | [
"compare",
"datetime",
"input",
"python",
"time"
] | stackoverflow_0007039512_compare_datetime_input_python_time.txt |
Q:
Python - "\" character
I'm newbie in Python. I'm trying to insert in a string a "\" character, but if i declare it like this, it takes \" as a " character.
I also tried to declare, e.g. fname='\\'
but it does not work.
What I mean to do is to add to a path e:\\Others\Contacts the string \<filename>.
May anyone hel... | Python - "\" character | I'm newbie in Python. I'm trying to insert in a string a "\" character, but if i declare it like this, it takes \" as a " character.
I also tried to declare, e.g. fname='\\'
but it does not work.
What I mean to do is to add to a path e:\\Others\Contacts the string \<filename>.
May anyone help me?
| [
"backslash = '\\\\'\n\nYou can also use raw string literals. Note that there's no way to have a backslash at the end of a raw string literal though.\npath = r'e:\\Others\\Contacts'\n\nHowever, instead of fiddling with backslashes, you should use os.path.join to concatenate paths:\nimport os.path\np = os.path.join('... | [
11,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007039931_python.txt |
Q:
kilo (K) and mega (M) suffixes on matplotlib's axes
I would like to print values on axes not as 30000 or 7000000 but as 30K or 7M. It means to add K (kilo) suffix for x < 10^6 and M (mega) suffix for x >= 10^6. How can I do that?
Current code snippet:
ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatt... | kilo (K) and mega (M) suffixes on matplotlib's axes | I would like to print values on axes not as 30000 or 7000000 but as 30K or 7M. It means to add K (kilo) suffix for x < 10^6 and M (mega) suffix for x >= 10^6. How can I do that?
Current code snippet:
ax = pylab.gca()
formatter = matplotlib.ticker.FormatStrFormatter('%.f')
ax.xaxis.set_major_formatter(formatter)
| [
"The best code to which I've come so far is:\nax = matplotlib.pyplot.gca()\nmkfunc = lambda x, pos: '%1.1fM' % (x * 1e-6) if x >= 1e6 else '%1.1fK' % (x * 1e-3) if x >= 1e3 else '%1.1f' % x\nmkformatter = matplotlib.ticker.FuncFormatter(mkfunc)\nax.yaxis.set_major_formatter(mkformatter)\n\n",
"You will need to wr... | [
15,
8
] | [] | [] | [
"formatter",
"matplotlib",
"python",
"ticker"
] | stackoverflow_0006557282_formatter_matplotlib_python_ticker.txt |
Q:
Sphinx Search - Multi-index search vs Client Program Aggregation
Looking for insight into the best approach to implementing a python client for Sphinx Search.
The dataset I am searching through is made up of profile content. All the profiles are organized geographically as locations using latitude and longitude. ... | Sphinx Search - Multi-index search vs Client Program Aggregation | Looking for insight into the best approach to implementing a python client for Sphinx Search.
The dataset I am searching through is made up of profile content. All the profiles are organized geographically as locations using latitude and longitude. The profiles have many different attributes all stored in the databas... | [
"If I understand your clearly when it could work faster if you extend your DESCRIPTION_INDEX with latitude and longitude attributes. \nInstead of two queries you will have only one to description index.\n"
] | [
0
] | [] | [] | [
"full_text_search",
"indexing",
"python",
"search",
"sphinx"
] | stackoverflow_0007015012_full_text_search_indexing_python_search_sphinx.txt |
Q:
Accessing app_globals from a separate thread
I'd like to create a separate thread for heavy computations in my Pylons project interacting with it through python Queue object. The problem is that I need to get to the app_globals object. When I try to do that, i get a
TypeError: No object (name: app_globals) has be... | Accessing app_globals from a separate thread | I'd like to create a separate thread for heavy computations in my Pylons project interacting with it through python Queue object. The problem is that I need to get to the app_globals object. When I try to do that, i get a
TypeError: No object (name: app_globals) has been registered for this thread
I also tried to acc... | [
"May be you must pass app_globals to thread as a start parameter or pass it through a queue? I not shure, but I think that app_globals implemented as threading.local\nEg. \nclass MyWorker(threading.Thread):\n def __init__(self, local_app_globals, *args, **kwargs):\n self.app_globals=local_app_globals\n ... | [
0
] | [] | [] | [
"multithreading",
"pylons",
"python"
] | stackoverflow_0007039662_multithreading_pylons_python.txt |
Q:
gdata internal error
Since yesterday a working Python gdata program has stopped working after I changed the IP address used.
I receive the following stack trace:
Traceback (most recent call last):
File "C:\prod\googleSite\googleSite2.py", line 23, in
feed = client.GetContentFeed()
File "C:\Python27... | gdata internal error | Since yesterday a working Python gdata program has stopped working after I changed the IP address used.
I receive the following stack trace:
Traceback (most recent call last):
File "C:\prod\googleSite\googleSite2.py", line 23, in
feed = client.GetContentFeed()
File "C:\Python27\lib\site-packages\gdata\s... | [
"Since you're not passing anything in GetContentFeed, it's using CONTENT_FEED_TEMPLATE % (self.domain, self.site) as the URI. I'm not sure if the IP change had an impact on what the self.domain/self.site values should be, but it might be worth checking those out.\n"
] | [
1
] | [] | [] | [
"gdata",
"google_sites",
"python"
] | stackoverflow_0007039603_gdata_google_sites_python.txt |
Q:
Python Tk Multiple Buttons Creation Problem
I'm creating ten buttons and the button texts are labelled 1 to 10. The following code creates 10 buttons and labels correctly. But it's printing 9 as the output for all the buttons. What I expect it to do is to print the corresponding number of the Button to screen, So... | Python Tk Multiple Buttons Creation Problem | I'm creating ten buttons and the button texts are labelled 1 to 10. The following code creates 10 buttons and labels correctly. But it's printing 9 as the output for all the buttons. What I expect it to do is to print the corresponding number of the Button to screen, So for Example if the user presses Button 2 then i... | [
"Try this (note the named argument to the lambda):\ndef create():\n for i in range (1,10):\n lst.insert(i,Button(text=i,command=lambda i=i : prnt(i)).pack())\n\nThis passes the value of i to the lambda as a local variable. Without this, you are using a reference to the original variable which will, of cou... | [
2
] | [] | [] | [
"button",
"python",
"tk_toolkit",
"tkinter",
"user_interface"
] | stackoverflow_0007040172_button_python_tk_toolkit_tkinter_user_interface.txt |
Q:
Convert string into datetime type
Possible Duplicate:
Convert Date String to DateTime Object in Python
Is there an easy way to convert the string the string 10/22/1984 into a datetime.date object?
A:
You can use datetime.strptime method for this purpose:
from datetime import datetime
dVal = datetime.strptime(... | Convert string into datetime type |
Possible Duplicate:
Convert Date String to DateTime Object in Python
Is there an easy way to convert the string the string 10/22/1984 into a datetime.date object?
| [
"You can use datetime.strptime method for this purpose:\nfrom datetime import datetime\n\ndVal = datetime.strptime('10/22/1984', '%m/%d/%Y')\n\nYou can read more using the following link that describes python strptime behavior.\n",
"Yes. \n>>> datetime.datetime.strptime(\"10/22/1984\", \"%m/%d/%Y\")\ndatetime.dat... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007040450_python.txt |
Q:
How to trap a copy/move-file operation in a custom filesystem based on Fuse?
I`m implementing a custom filesystem on Ubuntu using Fuse, but I need to trap when a copy or move operation occur. Right now all I see are when some file are opened for writing or reading, but I need to see these operations in context so ... | How to trap a copy/move-file operation in a custom filesystem based on Fuse? | I`m implementing a custom filesystem on Ubuntu using Fuse, but I need to trap when a copy or move operation occur. Right now all I see are when some file are opened for writing or reading, but I need to see these operations in context so I can see what file are being copied or moved.
Any hints?
| [
"What you want to do is probably not easily done, considering that a \"copy\" or \"move\" program could do just what you see - open a file and write to it. That's a perfectly good way of copying a file.\nEven if you can see what actual binary is doing it, that wouldn't give you enough information to know if this wa... | [
0,
0,
-1
] | [] | [] | [
"fuse",
"python"
] | stackoverflow_0003091166_fuse_python.txt |
Q:
How to check every request in pyramid for redirect?
I want to redirect users to a change password page when their password expired. I already setup a RequestFactory that takes the user. Where do I put the redirecting part in Pyramid?
A:
I'm not sure to understand your question, but the usual way to redirect in... | How to check every request in pyramid for redirect? | I want to redirect users to a change password page when their password expired. I already setup a RequestFactory that takes the user. Where do I put the redirecting part in Pyramid?
| [
"I'm not sure to understand your question, but the usual way to redirect in Pyramid is to return an HTTPFound instance in your view function. I think you could also just raise it since it's an exception.\nfrom pyramid.httpexceptions import HTTPFound\n\ndef my_view(request):\n return HTTPFound('/new/location/to/r... | [
4
] | [] | [] | [
"pyramid",
"python",
"redirect"
] | stackoverflow_0007034025_pyramid_python_redirect.txt |
Q:
Check if a field is present in an entity
I have updated my model in Datastore so now it has an additional field. Now I have entities with and without that field but I need to add this field to all entities that don't yet have it. Idea is to get entities in a function without that field and add it. So, I wonder how... | Check if a field is present in an entity | I have updated my model in Datastore so now it has an additional field. Now I have entities with and without that field but I need to add this field to all entities that don't yet have it. Idea is to get entities in a function without that field and add it. So, I wonder how I can filter such entities in Datastore reque... | [
"It might not be so easy, but I guess it's possible.\nYou cannot get the entities without a property:\n\nNo Use of Filters That Match Entities Missing a Property\nIt is not possible to query for entities that are missing a given property. One alternative is to create a fixed (modeled) property with a default value ... | [
1,
1
] | [] | [] | [
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0007037269_datastore_google_app_engine_python.txt |
Q:
Running a C++ Qt application through a boost python module
Is it possible to run a Qt gui application as a boost module through python? It was working as a standard C++ executable, but now I'm compiling it down to a shared library and trying to launch it from python. Right now it just goes into the python interp... | Running a C++ Qt application through a boost python module | Is it possible to run a Qt gui application as a boost module through python? It was working as a standard C++ executable, but now I'm compiling it down to a shared library and trying to launch it from python. Right now it just goes into the python interpreter every time I run simpleMain() from the interpreter. As in... | [
"You can write your application setup in PyQt, which is as simple as\nimport sys\nfrom PyQt4 import QtGui \nQtGui.QApplication(sys.argv)\n\nat the beginning of your script. Then can call c++ code in your modules which can open/close/... windows. (I have code which works this way)\nI think it is illegal to call m... | [
0,
0
] | [] | [] | [
"boost_python",
"c++",
"extend",
"python",
"qt"
] | stackoverflow_0007011779_boost_python_c++_extend_python_qt.txt |
Q:
Tuples, checking for a letter in a string
I have this code:
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
if letter in ("O", "Q"):
print letter + "u" + suffix
else:
print letter + suffix
It works fine but I have problem understanding one thing. I assume that:
if letter i... | Tuples, checking for a letter in a string | I have this code:
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
if letter in ("O", "Q"):
print letter + "u" + suffix
else:
print letter + suffix
It works fine but I have problem understanding one thing. I assume that:
if letter in ("O", "Q"):
creates new tuple with 2 letters... | [
"All these do the same thing: \nif letter == \"O\" or letter == \"Q\":\nif letter in (\"O\", \"Q\"):\nif letter in \"OQ\":\n\nYour line if letter == \"O\" or \"Q\": is evaluated like if (letter == \"O\") or \"Q\":, and \"Q\" evaluates to True, so this expression always returns True.\n",
"Equality comparison takes... | [
6,
2,
1,
1,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0007039665_python_tuples.txt |
Q:
Python: copying objects with copy.deepcopy or writing my own copy
Currently I am using the copy module to create a copy of some object that I have.
Under certain conditions (that occur frequently), I will need to create possibly several copies of the original object, and then modify each of them individually (henc... | Python: copying objects with copy.deepcopy or writing my own copy | Currently I am using the copy module to create a copy of some object that I have.
Under certain conditions (that occur frequently), I will need to create possibly several copies of the original object, and then modify each of them individually (hence why I am using copy).
The object has several instances of various dat... | [
"Not trying to be glib, but have you considered profiling your code? Documentation here. Compare copy.deepcopy with with your own custom copy method. That way you'll have hard data on your particular situation and can make the best decision--and back it up if anyone asks why you did it that way!\n"
] | [
2
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0007041162_deep_copy_python.txt |
Q:
PHP to Python: Moovrelocator
I've found library in php called moovrelocator.
Description from it's site:
MOOV Relocator is a well documented small library written in PHP to relocate (or move) the MOOV-Atom of MP4-Files from the end to the beginning of a file.
And it works pretty well with php.
Unfortunally I ha... | PHP to Python: Moovrelocator | I've found library in php called moovrelocator.
Description from it's site:
MOOV Relocator is a well documented small library written in PHP to relocate (or move) the MOOV-Atom of MP4-Files from the end to the beginning of a file.
And it works pretty well with php.
Unfortunally I haven't found such library in python... | [
"Quicktime/MP4 Fast Start\nEnable streaming and pseudo-streaming of Quicktime and MP4 files by\nmoving metadata and offset information to the front of the file.\nUsage\n\n$ qtfaststart.py infile [outfile]\n\n"
] | [
3
] | [] | [] | [
"php",
"python",
"video_streaming"
] | stackoverflow_0007040904_php_python_video_streaming.txt |
Q:
lookahead and non-capturing regular expressions
I'm trying to match the local part of an email address before the @ character with:
LOCAL_RE_NOTQUOTED = """
((
\w # alphanumeric and _
| [!#$%&'*+-/=?^_`{|}~] # special chars, but no dot at beginning
)
(
\w # alphanumeric and _
| [!#$%&'*+-/... | lookahead and non-capturing regular expressions | I'm trying to match the local part of an email address before the @ character with:
LOCAL_RE_NOTQUOTED = """
((
\w # alphanumeric and _
| [!#$%&'*+-/=?^_`{|}~] # special chars, but no dot at beginning
)
(
\w # alphanumeric and _
| [!#$%&'*+-/=?^_`{|}~] # special characters
| ([.](?![.]... | [
"You're confusing non-capturing groups (?:...) and lookahead assertions (?=...).\nThe former do participate in the match (and are thus part of match.group() which contains the overall match), they just don't generate a backreference ($1 etc. for later use).\nThe second problem (Why is the double dot matched?) is a ... | [
10
] | [] | [] | [
"python",
"regex",
"regex_lookarounds"
] | stackoverflow_0007040829_python_regex_regex_lookarounds.txt |
Q:
python: I need to understand better imports and packages
My application has a structure similar to this one:
myapp.py
basemod.py
[pkg1]
__init__.py
mod1.py
[pkg2]
__init__.py
mod2.py
myapp.py:
import pkg1
import pkg2
if __name__ == '__main__':
pkg1.main()
pkg2.main()
basemod.py:
import p... | python: I need to understand better imports and packages | My application has a structure similar to this one:
myapp.py
basemod.py
[pkg1]
__init__.py
mod1.py
[pkg2]
__init__.py
mod2.py
myapp.py:
import pkg1
import pkg2
if __name__ == '__main__':
pkg1.main()
pkg2.main()
basemod.py:
import pkg1
def get_msg():
return pkg1.msg
pkg1/__init__.py:
im... | [
"Took me a while to read through all that code, but it looks like your problem is in pkg2/mod2.py. The line foo = basemod.get_msg() is executed the first time that file is imported, and never again. So by the time you change the value of mod1.bar, this has already executed, and foo is None.\nThe solution should sim... | [
5
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0007041436_import_package_python.txt |
Q:
How to disable noisy debug?
I have simple example:
def __call__(self):
d = client.getPage('www.google.com', timeout = 1 )
d.addCallback(self.a)
d.addCallback(self.b)
return d
How to disable "noisy" debug for Factory class, using in getPage method ?
A:
When using getPage, the factory object is n... | How to disable noisy debug? | I have simple example:
def __call__(self):
d = client.getPage('www.google.com', timeout = 1 )
d.addCallback(self.a)
d.addCallback(self.b)
return d
How to disable "noisy" debug for Factory class, using in getPage method ?
| [
"When using getPage, the factory object is not exposed to you, so there is no simple way to disable the logging it does.\nYou can disable this logging for all uses of getPage by setting noisy on the factory class:\nfrom twisted.web.client import HTTPClientFactory\nHTTPClientFactory.noisy = False\n\n"
] | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0007016602_python_twisted.txt |
Q:
Smallest possible windows executable from python script
I've looked at some projects like py2exe and a couple other ones. But I want really small under 1mb would be cool but under 300kb would be ideal. Are there any project to possibly extern python into a C compiler or even convert python to C?
Maybe there is jus... | Smallest possible windows executable from python script | I've looked at some projects like py2exe and a couple other ones. But I want really small under 1mb would be cool but under 300kb would be ideal. Are there any project to possibly extern python into a C compiler or even convert python to C?
Maybe there is just a really small python interpreter that I could add only the... | [
"The Shedskin solution in Is it feasible to compile Python to machine code? is what you look for however it is not compile an arbitrary python code. And it is not compile to C but to C++.\n",
"I mean the closest you will get with python is py2exe and UPX Create the exe but don't bundle anything to it instead make... | [
1,
0
] | [] | [] | [
"compilation",
"compression",
"python"
] | stackoverflow_0007038664_compilation_compression_python.txt |
Q:
ZeroDivisionError: float division
I have got this code to solve Newton's method. But it gives a zero division error. I cannot figure out what is wrong. Thank you.
import copy
tlist = [0.0, 0.12, 0.16, 0.2, 0.31, 0.34] # list of start time for the phonemes
w = w1 = w2 = w3 = w = 5
def time() :
frame = ... | ZeroDivisionError: float division | I have got this code to solve Newton's method. But it gives a zero division error. I cannot figure out what is wrong. Thank you.
import copy
tlist = [0.0, 0.12, 0.16, 0.2, 0.31, 0.34] # list of start time for the phonemes
w = w1 = w2 = w3 = w = 5
def time() :
frame = 0.04
for i, start_time in enumerate... | [
"You have a basic bug here:\nfor i, start_time in enumerate(tlist):\n end_time = tlist[i]\n\nBecause of the nature of enumerate, start_time and end_time have the same value. This means that poly_coeff will return [[0,3], [0,2], [0,1], [0,0]] every time. When this result is passed (through Newton) into poly_dif... | [
6,
3,
0
] | [] | [] | [
"newtons_method",
"python"
] | stackoverflow_0007041712_newtons_method_python.txt |
Q:
javascript/python time processing fails in chrome
I am writing a timer web app,which records start time and stop time.It uses javascript,jquery1.4.2 for the front end and python for backend code.When a start button is clicked ,start time is saved in a javascript variable.when the button is clicked again, stop time... | javascript/python time processing fails in chrome | I am writing a timer web app,which records start time and stop time.It uses javascript,jquery1.4.2 for the front end and python for backend code.When a start button is clicked ,start time is saved in a javascript variable.when the button is clicked again, stop time is saved in another variable.These values are passed a... | [
"You don't want the string of the time in locale, using the toString method you can provide your own format, or use toUTCString().\ntoLocaleTimeString is especially meant to display the time as the user is used to, you want it in a set format.\nSo instead of start_date.toLocaleTimeString(), you want to use start_da... | [
1,
1
] | [] | [] | [
"javascript",
"python",
"time"
] | stackoverflow_0007041860_javascript_python_time.txt |
Q:
Getting exif data from an image online with python
Hi Is there a way to read exif data from a online image given its url without downloading the image? Right now I'm doing something like:
import urllib, pyexiv2
urllib.urlretrieve(url, File)
exif_info = pyexiv2.ImageMetadata(File)
exif_info.read()
print exif_info.e... | Getting exif data from an image online with python | Hi Is there a way to read exif data from a online image given its url without downloading the image? Right now I'm doing something like:
import urllib, pyexiv2
urllib.urlretrieve(url, File)
exif_info = pyexiv2.ImageMetadata(File)
exif_info.read()
print exif_info.exif_keys
but I'd like to do it without the download ste... | [
"Actually, the statement \"read directly from the internet\" is called download.\nIf you were able to download only some part of the file, it would be possible. But I don't think it's possible, specially because you can't determine where the EXIF DATA is in the file.\n",
"Unless the website exposes that metadata,... | [
3,
1
] | [] | [] | [
"exif",
"python",
"urllib"
] | stackoverflow_0007041956_exif_python_urllib.txt |
Q:
Add line on top of each Python file in current and sub directories
I'm on an Ubuntu platform and have a directory containing many .py files and subdirectories (also containing .py files). I would like to add a line of text to the top of each .py file. What's the easiest way to do that using Perl, Python, or shell ... | Add line on top of each Python file in current and sub directories | I'm on an Ubuntu platform and have a directory containing many .py files and subdirectories (also containing .py files). I would like to add a line of text to the top of each .py file. What's the easiest way to do that using Perl, Python, or shell script?
| [
"find . -name \\*.py | xargs sed -i '1a Line of text here'\n\nEdit: from tchrist's comment, handle filenames with spaces.\nAssuming you have GNU find and xargs (as you specified the linux tag on the question)\nfind . -name \\*.py -print0 | xargs -0 sed -i '1a Line of text here'\n\nWithout GNU tools, you'd do someth... | [
6,
5,
4,
4,
4,
1
] | [] | [] | [
"linux",
"perl",
"python",
"shell"
] | stackoverflow_0007039809_linux_perl_python_shell.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.