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:
Usage of python logging module in c-extension
I'm working on a python script and I'm using the python logging module for writing some information into a log file (see http://docs.python.org/howto/logging.html).
Here is a small example (also from the mentioned page):
import logging
import logging.config
logging.co... | Usage of python logging module in c-extension | I'm working on a python script and I'm using the python logging module for writing some information into a log file (see http://docs.python.org/howto/logging.html).
Here is a small example (also from the mentioned page):
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
lo... | [
"The \"very high-level C API\" has a number of tools for executing pure python code from C. Start by looking at http://docs.python.org/c-api/veryhigh.html#PyRun_String .\n"
] | [
2
] | [] | [] | [
"python",
"python_c_api",
"python_c_extension"
] | stackoverflow_0007826505_python_python_c_api_python_c_extension.txt |
Q:
How to combine lines of a single text file in python?
I've searched, but found nothing to help.. This is an example:
List.txt
a
b
c
d
I want to be able to get an output like this:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
A:
Pretty straightforwa... | How to combine lines of a single text file in python? | I've searched, but found nothing to help.. This is an example:
List.txt
a
b
c
d
I want to be able to get an output like this:
Output.txt
ab
ac
ad
ba
bc
bd
ca
cb
cd
etc...
| [
"Pretty straightforward...\nfrom itertools import permutations\n\nwith open('List.txt') as f: \n letters = (l.strip() for l in f if l.strip()) \n for p in permutations(letters, 2):\n print ''.join(p)\n\nOutput: \nab\nac\nad\nba\nbc\nbd\nca\ncb\ncd\nda\ndb\ndc\n\nSome notes:\nThe with statement en... | [
2,
0,
0
] | [
"You can first read the file into an array:\nlines=[]\nfor line in file:\n lines.append(line)\n\nand then iterate over it to get the desired output.\nfor line1 in lines:\n for line2 in lines:\n print line1+line2\n\nor print it to a file instead.\n"
] | [
-1
] | [
"combinatorics",
"python",
"python_itertools"
] | stackoverflow_0007826303_combinatorics_python_python_itertools.txt |
Q:
how to show first 50 words of a text field in django template
I have a field like this in my Django template:
<p>{{news.description}}<p>
I wanna show the first 50 words of this field. How can I do it?
A:
From the documentation:
{{ news.description|truncatewords:50 }}
| how to show first 50 words of a text field in django template | I have a field like this in my Django template:
<p>{{news.description}}<p>
I wanna show the first 50 words of this field. How can I do it?
| [
"From the documentation:\n{{ news.description|truncatewords:50 }}\n\n"
] | [
54
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007826955_django_python.txt |
Q:
python math, numpy modules different results?
I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?
import math
math.cos(60.0/180.0*math.pi)
-> 0.5000000000000001
import numpy
numpy.cos(60.0/180.0*numpy.pi)
-> 0.50000000000000011
A:
... | python math, numpy modules different results? | I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?
import math
math.cos(60.0/180.0*math.pi)
-> 0.5000000000000001
import numpy
numpy.cos(60.0/180.0*numpy.pi)
-> 0.50000000000000011
| [
"The difference seems to be caused by the formatting routines only:\n>>> '%.30f' % math.cos(60./180.*math.pi)\n'0.500000000000000111022302462516'\n>>> '%.30f' % np.cos(60./180.*np.pi)\n'0.500000000000000111022302462516'\n\nNote that np.cos returns np.float64 rather than float, and apparently that type is printed di... | [
16,
5,
3
] | [] | [] | [
"floating_point",
"numpy",
"python"
] | stackoverflow_0007825543_floating_point_numpy_python.txt |
Q:
Fun with Signal Handlers in Python Interrupting Select
I'm working on a programming project--writing a basic P2P filesharing application in Python. I'm using two threads: a main one to call select and wait for input from a list of sockets and sys.stdin (to receive typed commands) and a helper thread that takes sta... | Fun with Signal Handlers in Python Interrupting Select | I'm working on a programming project--writing a basic P2P filesharing application in Python. I'm using two threads: a main one to call select and wait for input from a list of sockets and sys.stdin (to receive typed commands) and a helper thread that takes status update messages off a queue and prints them. (It is the ... | [
"I'm not sure about using signal handlers to catch this case, but I've found a recipe for handling this case on *nix based systems here: http://code.activestate.com/recipes/496735-workaround-for-missed-sigint-in-multithreaded-prog/\nIn a nutshell (If I undertand correctly):\nBefore you start any new threads, fork a... | [
0,
0
] | [] | [] | [
"multithreading",
"python",
"signals"
] | stackoverflow_0007775368_multithreading_python_signals.txt |
Q:
Python None variables usage
Is there any way to simplify the following code:
def get_or_create_user(id, photo=None, first_name=None, last_name=None, nickname=None, organization=None, city=None, country=None):
... # save user in the datastore
class UserCreationHandler(webapp.RequestHandler):
def get(self):... | Python None variables usage | Is there any way to simplify the following code:
def get_or_create_user(id, photo=None, first_name=None, last_name=None, nickname=None, organization=None, city=None, country=None):
... # save user in the datastore
class UserCreationHandler(webapp.RequestHandler):
def get(self):
id = self.request.get('i... | [
"Something like:\ndef get(self):\n id = self.request.get('id')\n user_details = {}\n if something:\n # assign user_details['id'], user_details['photo'], user_details['first_name'] etc. values\n get_or_create_user(id, **user_details)\n\n",
"Seeing that get_or_create_user uses default arguments s... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0007827330_python.txt |
Q:
Import of main script from stub script causing freezing
I am building an application to distribute with py2app. As I don't want the source to be extracted from the .app file, I have a stub file, named run.py, which then runs the code in mainapp.py:
import mainapp
Running this directly in a terminal (no py2app inv... | Import of main script from stub script causing freezing | I am building an application to distribute with py2app. As I don't want the source to be extracted from the .app file, I have a stub file, named run.py, which then runs the code in mainapp.py:
import mainapp
Running this directly in a terminal (no py2app involvement) gives a freezing in a gevent dependent part of the ... | [
"When you import a module in Python, that module is executed. Make sure that in mainapp there is no \"free code\" that can freeze your python VM (like infinite loop).\n\"Free code\" is the set of the instructions that are outside function or class definition.\nFor example in\nimport one_module\n\nwhile(true) :\n ... | [
0
] | [] | [] | [
"gevent",
"py2app",
"python"
] | stackoverflow_0007827196_gevent_py2app_python.txt |
Q:
Python django form processing and execution behavior skipping execution
I am having some problems with processing my form in python django. There is some unusual behavior when processing the form. Below is my form and part of the function that processing the form in the view. I am fairly new to python and django, ... | Python django form processing and execution behavior skipping execution | I am having some problems with processing my form in python django. There is some unusual behavior when processing the form. Below is my form and part of the function that processing the form in the view. I am fairly new to python and django, so any help will be much appreciated.
class SearchForm(forms.Form):
pr_n... | [
"can it be that in your source you have spaces and tabs mixed and the block of code that you think should be executed is actually not executed because it is inside an \"if\" statement?\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"django_views",
"forms",
"python"
] | stackoverflow_0007816786_django_django_forms_django_views_forms_python.txt |
Q:
Array of colors in python
What's the quickest way to get an array of colors in python? Something I can index and pass to as the "color=" argument plotting in pylab.
The best I can come up with is:
colors = [(random(),random(),random()) for i in range(10)]
but a solution that can generate well-spaced colors (inter... | Array of colors in python | What's the quickest way to get an array of colors in python? Something I can index and pass to as the "color=" argument plotting in pylab.
The best I can come up with is:
colors = [(random(),random(),random()) for i in range(10)]
but a solution that can generate well-spaced colors (interpolated?) would be preferable.
| [
"from random import randint\ncolors = []\n\nfor i in range(10):\n colors.append('#%06X' % randint(0, 0xFFFFFF))\n\nResult Example:\n['#37AB65', '#3DF735', '#AD6D70', '#EC2504', '#8C0B90', '#C0E4FF', '#27B502', '#7C60A8', '#CF95D7', '#145JKH']\nps: thanks to @Inerdia\n",
"It seems like matplotlib comes with sev... | [
18,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0007827530_python.txt |
Q:
Http POST Curl in python
I'm having trouble understanding how to issue an HTTP POST request using curl from inside of python.
I'm tying to post to facebook open graph. Here is the example they give which I'd like to replicate exactly in python.
curl -F 'access_token=...' \
-F 'message=Hello, Arjun. I like th... | Http POST Curl in python | I'm having trouble understanding how to issue an HTTP POST request using curl from inside of python.
I'm tying to post to facebook open graph. Here is the example they give which I'd like to replicate exactly in python.
curl -F 'access_token=...' \
-F 'message=Hello, Arjun. I like this new API.' \
https://gr... | [
"You can use httplib to POST with Python or the higher level urllib2\nimport urllib\n\nparams = {}\n\nparams['access_token'] = '*****'\nparams['message'] = 'Hello, Arjun. I like this new API.'\n\nparams = urllib.urlencode(params)\nf = urllib.urlopen(\"https://graph.facebook.com/arjun/feed\", params)\nprint f.read()... | [
16,
1
] | [] | [] | [
"curl",
"facebook_opengraph",
"http",
"post",
"python"
] | stackoverflow_0007827696_curl_facebook_opengraph_http_post_python.txt |
Q:
How to store recipe information with Python
I'm very new to Python and I'm trying to write a sort of recipe organizer to get acquainted with the language. Basically, I am unsure how how I should be storing the recipes.
For now, the information I want to store is:
Recipe name
Ingredient names
Ingredient quantiti... | How to store recipe information with Python | I'm very new to Python and I'm trying to write a sort of recipe organizer to get acquainted with the language. Basically, I am unsure how how I should be storing the recipes.
For now, the information I want to store is:
Recipe name
Ingredient names
Ingredient quantities
Preparation
I've been thinking about how to d... | [
"\nYes, SQLite3 is sufficient for the task.\nEach ingredient/quantity pair does not need its own table.\n\nOne quick way to pick up the basics of SQL is to fiddle with the Command Line Shell for SQLite and knock around some data interactively before you start writing Python. SQL isn't too difficult. It can be dif... | [
3,
2,
0,
0
] | [] | [] | [
"database",
"database_design",
"python"
] | stackoverflow_0007827859_database_database_design_python.txt |
Q:
Converting string into an object instance name - python
I'm probably going about this all wrong but...
I am trying to populate a QTreeView from SQL data - using QAbstractItemModel (and having a great deal of trouble understanding it tbh). One of the tutorials I am following (the simplest) populates the Tree by si... | Converting string into an object instance name - python | I'm probably going about this all wrong but...
I am trying to populate a QTreeView from SQL data - using QAbstractItemModel (and having a great deal of trouble understanding it tbh). One of the tutorials I am following (the simplest) populates the Tree by simply calling new instances of the 'Node' and generating the m... | [
"Are the strings the names of global variables? If so, you can access the value refenced by the global variable with globals()['name'], (replacing 'name' with the string name of the variable of course.)\nOr, better yet, instead of littering variable names all over your global namespace\nyou could use a dict:\nnode=... | [
2
] | [] | [] | [
"object",
"python",
"qt",
"string",
"tree"
] | stackoverflow_0007828216_object_python_qt_string_tree.txt |
Q:
Trouble initiating a TCP connection in Python--blocking and timing out
For a class project I'm trying to do some socket programming Python but running into a very basic issue. I can't create a TCP connection from my laptop to a lab machine. (Which I'm hoping to use as the "server") Without even getting into the sc... | Trouble initiating a TCP connection in Python--blocking and timing out | For a class project I'm trying to do some socket programming Python but running into a very basic issue. I can't create a TCP connection from my laptop to a lab machine. (Which I'm hoping to use as the "server") Without even getting into the scripts I have written, I've been simply trying interpreter line commands with... | [
"A good way to confirm whether it's a firewall issue or not is to perform a telnet from the command-line to the destination host in question:\n% telnet kh4250-39.cselabs.umn.edu 8353\nTrying 128.101.38.44... \n\nAnd then sometime later:\ntelnet: connect to address 128.101.38.44: Connection timed out\n\nIf it just h... | [
1,
0
] | [] | [] | [
"python",
"sockets",
"tcp"
] | stackoverflow_0007827340_python_sockets_tcp.txt |
Q:
Is there a quick way to get an XML element from a path?
Is there a quick way to take this block of XML and extract the value of "version"?
<xml>
<creator version='1.0'>
<program>BULK_EXTRACTOR</program>
<version>1.0.3</version>
<build_environment>
<compiler>GCC 4.2</compiler>
<c... | Is there a quick way to get an XML element from a path? | Is there a quick way to take this block of XML and extract the value of "version"?
<xml>
<creator version='1.0'>
<program>BULK_EXTRACTOR</program>
<version>1.0.3</version>
<build_environment>
<compiler>GCC 4.2</compiler>
<compilation_date>2011-09-27T11:56:35</compilation_date>
... | [
"Assuming you are looking for the version element, not the version attributes,\nusing lxml:\nimport lxml.etree as ET\n\ncontent='''\\\n <xml>\n <creator version='1.0'>\n <program>BULK_EXTRACTOR</program>\n <version>1.0.3</version>\n <build_environment>\n <compiler>GCC 4.2</compiler>\n <c... | [
4,
2
] | [] | [] | [
"python",
"xml_parsing"
] | stackoverflow_0007827992_python_xml_parsing.txt |
Q:
Getting error message when trying to attach a class to an object
i have a little problem when i try to attach a class to an object in python. I have a textfile 'file', which is seperated into a list for each line. The program will read every line and print a name and a longname. Imagine that the textfile look like... | Getting error message when trying to attach a class to an object | i have a little problem when i try to attach a class to an object in python. I have a textfile 'file', which is seperated into a list for each line. The program will read every line and print a name and a longname. Imagine that the textfile look like this:
"John '\n' John Travolta" (...)
Here's my bit of code:
class Na... | [
"You need to assign something to name and longname before you can use them:\nname = 'foo'\nlongname = 'foo bar'\nc=Name(name, longname)\nc.func()\n\n\n\nbut I did this with my function?\n\nNo.\n\nFirstly, you didn't call your function yet. The function call is after the line that gives the error.\nSecondly, the fun... | [
1
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0007828374_class_methods_python.txt |
Q:
How to display only triangle boundaries on textured surface in vtk?
I want to display a surface which is textured. I want the triangles boundaries to be visible over the surface in a different color (lets say red). I have found the following code from the vtk code samples but it does not display the triangle bound... | How to display only triangle boundaries on textured surface in vtk? | I want to display a surface which is textured. I want the triangles boundaries to be visible over the surface in a different color (lets say red). I have found the following code from the vtk code samples but it does not display the triangle boundaries but the filled triangles.
import vtk
# create a rendering wi... | [
"You need to extract the edges from your vtkPolyData object:\nedges = vtk.vtkExtractEdges()\nedges.SetInput(trianglePolyData)\nedge_mapper = vtk.vtkPolyDataMapper()\nedge_mapper.SetInput(edges.GetOutput())\n\nedge_actor = vtk.vtkActor()\nedge_actor.SetMapper(edge_mapper)\nedge_actor.GetProperty().SetColor(1,0,0)\n\... | [
4
] | [] | [] | [
"graphics",
"python",
"visualization",
"vtk"
] | stackoverflow_0007548966_graphics_python_visualization_vtk.txt |
Q:
Seeing exceptions from methods registered to SimpleXMLRPCServer
I'm writing an xmlrpc-based python 2.7 program, using SimpleXMLRPCServer. I import the class with all our logic and register it with:
server = SimpleXMLRPCServer(("0.0.0.0", 9001))
server.register_instancce(classWithAllTheLogic())
server.serve_forever... | Seeing exceptions from methods registered to SimpleXMLRPCServer | I'm writing an xmlrpc-based python 2.7 program, using SimpleXMLRPCServer. I import the class with all our logic and register it with:
server = SimpleXMLRPCServer(("0.0.0.0", 9001))
server.register_instancce(classWithAllTheLogic())
server.serve_forever()
When running this in console I can see the log messages from Simp... | [
"I am unable to reproduce this.\nTest script test.py\nfrom xmlrpc.server import SimpleXMLRPCServer\nclass classWithAllTheLogic:\n def __init__(self):\n print(\"Hi\")\n raise Exception(\"INIT Exception\")\n\n def hello(self):\n print(\"hello\")\n raise Exception(\"Hello Exception\")... | [
0
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0007779910_python_xml_rpc.txt |
Q:
initializing python class globally?
I have two files, one of the test.py is
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
and new.py
class New:
def __init__(self):
one.run()
New()
Now wh... | initializing python class globally? | I have two files, one of the test.py is
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
and new.py
class New:
def __init__(self):
one.run()
New()
Now when i run python test.py I get this error,... | [
"If you want your New class to use the instance of Test you created, you have to pass it in as part of the constructor.\nnew.py\nclass New:\n def __init__(self, one):\n one.run()\n\ntest.py\nimport new\n\nclass Test:\n def __init__(self):\n return\n def run(self):\n return 1\n\n\nif __... | [
5,
0
] | [
"one is defined inside the if __name__=='__main__' block.\nConsequently, one will get defined only if test.py is run as a script (rather than imported). \nFor the module new to access one from the test module, you'll need to pull one out of the if __name__ block:\ntest.py:\nclass Test:\n def __init__(self):\n ... | [
-1
] | [
"class",
"initialization",
"python"
] | stackoverflow_0007828717_class_initialization_python.txt |
Q:
Youtube API - Set the Thumbnail of Video (python)
Is it possible to specify your own thumbnail for a video that has been uploaded via the YouTube API?
Using the most recent version of the Python Library, it appears that I can create and set the thumbnail of my media group before inserting a video entry to YouTube ... | Youtube API - Set the Thumbnail of Video (python) | Is it possible to specify your own thumbnail for a video that has been uploaded via the YouTube API?
Using the most recent version of the Python Library, it appears that I can create and set the thumbnail of my media group before inserting a video entry to YouTube - however the thumbnail specified does NOT get set on t... | [
"No. Using the standard YouTube API, you cannot programatically set a thumbnail for your video.\nHowever, if you are a content partner and have access the YouTube CMS (which your partner manager can enable), you can apparently set your video artwork from there. I'll post details as I run through this process.\n"
] | [
1
] | [] | [] | [
"python",
"youtube",
"youtube_api"
] | stackoverflow_0007654719_python_youtube_youtube_api.txt |
Q:
Multiprocessing a dictionary in python
I have two dictionaries of data and I created a function that acts as a rules engine to analyze entries in each dictionaries and does things based on specific metrics I set(if it helps, each entry in the dictionary is a node in a graph and if rules match I create edges betwee... | Multiprocessing a dictionary in python | I have two dictionaries of data and I created a function that acts as a rules engine to analyze entries in each dictionaries and does things based on specific metrics I set(if it helps, each entry in the dictionary is a node in a graph and if rules match I create edges between them).
Here's the code I use(its a for loo... | [
"What I've done in the past is to create a \"worker class\" that processes data entries. Then I'll spin up X number of threads that each run a copy of the worker class. Each item in the dataset gets pushed into a queue that the worker threads are watching. When there are no more items in the queue, the threads spin... | [
2,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0007828433_multiprocessing_python.txt |
Q:
Can I embed CPython inside PyPy?
I'd like to write a performance-sensitive application in Python, so executing it under PyPy is a natural choice. However, a significant portion of my code depends on numpy, scipy, and scikit-learn. Would it be possible to embed a CPython instance within a running PyPy program in or... | Can I embed CPython inside PyPy? | I'd like to write a performance-sensitive application in Python, so executing it under PyPy is a natural choice. However, a significant portion of my code depends on numpy, scipy, and scikit-learn. Would it be possible to embed a CPython instance within a running PyPy program in order to call array-oriented code? If no... | [
"Your best bet for the time-being is Cython rather than PyPy. It has c-level performance, if you add type declarations, and excellent integration with numpy, et al. \nPeople are currently working on getting it to work well with PyPy, but that's a ways off yet.\n",
"No, you can't embed CPython inside PyPy AFAIK.... | [
4,
2
] | [] | [] | [
"cpython",
"cython",
"numpy",
"pypy",
"python"
] | stackoverflow_0007824934_cpython_cython_numpy_pypy_python.txt |
Q:
ImportError; and zipimporters disappeared from pkgutil.iter_importers()
I have a Django instance that's mysteriously incapable of import memcache ... after (some unknown event that happens after a period of running just fine.)
LAMP configuration:
RHEL 5.7
Apache 2.2.3
mod_wsgi 2.3 (dynamically linked to Python2.5... | ImportError; and zipimporters disappeared from pkgutil.iter_importers() | I have a Django instance that's mysteriously incapable of import memcache ... after (some unknown event that happens after a period of running just fine.)
LAMP configuration:
RHEL 5.7
Apache 2.2.3
mod_wsgi 2.3 (dynamically linked to Python2.5.4 .so)
Python 2.5.4
Django 1.2
memcache sits in: /usr/local/lib/python2.5/s... | [
"Okay. I found the answer. There is a bug in Python 2.5's os.listdir C implementation on 64-bit computers. When I applied the patch, everything works permanently.\n"
] | [
0
] | [] | [] | [
"egg",
"import",
"python",
"python_import"
] | stackoverflow_0007535179_egg_import_python_python_import.txt |
Q:
pyparsing - parse xml comment
I need to parse a file containing xml comments. Specifically it's a c# file using the MS /// convention.
From this I'd need to pull out foobar, or /// foobar would be acceptable, too. (Note - this still doesn't work if you make the xml all on one line...)
testStr = """
///<summa... | pyparsing - parse xml comment | I need to parse a file containing xml comments. Specifically it's a c# file using the MS /// convention.
From this I'd need to pull out foobar, or /// foobar would be acceptable, too. (Note - this still doesn't work if you make the xml all on one line...)
testStr = """
///<summary>
/// foobar
///</summary... | [
"I think Literal('\\n') is your problem. You don't want to build a Literal with whitespace characters (since Literals by default skip over whitespace before trying to match). Try using LineEnd() instead.\nEDIT 1:\nJust because you get an infinite loop with LineEnd doesn't mean that Literal('\\n') is any better. T... | [
3,
2,
1
] | [] | [] | [
"grammar",
"pyparsing",
"python",
"xml_comments"
] | stackoverflow_0007825030_grammar_pyparsing_python_xml_comments.txt |
Q:
paster quickstart not an option
I am just installing TurboGears2 on Windows 7 running a virtual environment (python 2.7). I am not seeing the paster quickstart option when I run
paster --help
Instead, here's that output:
(VirtualEnv_1) C:\VirtualEnv_1\Scripts>paster --help
Usage: paster-script.py [paster_options... | paster quickstart not an option | I am just installing TurboGears2 on Windows 7 running a virtual environment (python 2.7). I am not seeing the paster quickstart option when I run
paster --help
Instead, here's that output:
(VirtualEnv_1) C:\VirtualEnv_1\Scripts>paster --help
Usage: paster-script.py [paster_options] COMMAND [command_options]
Options:... | [
"You get into this situation when you've installed the package required to run a TurboGears app (TurboGears2), but not the one required to develop a TurboGears app (tg.devtools).\nRunning the following command while in your virtualenv should install the correct package:\neasy_install -i http://www.turbogears.org/2.... | [
1
] | [] | [] | [
"paster",
"python",
"turbogears2",
"windows_7"
] | stackoverflow_0007829200_paster_python_turbogears2_windows_7.txt |
Q:
Retriving Youtube playlist information trough You Tube API (python)
I have a bit of a problem with using the Python YouTube API to get the title of the videos in the playlist. I have the enviroment configured correctly, also when I copied the example from the API documentation it works for the added playlist id, b... | Retriving Youtube playlist information trough You Tube API (python) | I have a bit of a problem with using the Python YouTube API to get the title of the videos in the playlist. I have the enviroment configured correctly, also when I copied the example from the API documentation it works for the added playlist id, but when I try to use one from an other playlist I get an error.
Here is s... | [
"Remove PL in your request URI:\nplaylist_uri = \"http://gdata.youtube.com/feeds/api/playlists/CD939C4D974A5815\"\n\nI'm not sure why YouTube needs it to be in that format, but it needs to be.\nYou can also just do a .replace('playlists/PL', 'playlists/') on your string.\n"
] | [
4
] | [] | [] | [
"api",
"python",
"youtube_api"
] | stackoverflow_0007829279_api_python_youtube_api.txt |
Q:
Why does subprocess.Popen not work
I tried a lot of things but for some reason I could not get things working. I am trying to run dumpbin utility of MS VS using a Python script.
Here are what I tried (and what did not work for me)
1.
tempFile = open('C:\\Windows\\temp\\tempExports.txt', 'w')
command = '"C:/Program... | Why does subprocess.Popen not work | I tried a lot of things but for some reason I could not get things working. I am trying to run dumpbin utility of MS VS using a Python script.
Here are what I tried (and what did not work for me)
1.
tempFile = open('C:\\Windows\\temp\\tempExports.txt', 'w')
command = '"C:/Program Files/Microsoft Visual Studio 8/VC/bin/... | [
"The argument pattern for Popen expect a list of strings for non-shell calls and a string for shell calls. This is easy to fix. Given:\n>>> command = '\"C:/Program Files/Microsoft Visual Studio 8/VC/bin/dumpbin\" /EXPORTS ' + dllFilePath\n\nEither call subprocess.Popen with shell=True:\n>>> process = subprocess.... | [
8,
2
] | [] | [] | [
"dumpbin",
"python",
"subprocess"
] | stackoverflow_0007823910_dumpbin_python_subprocess.txt |
Q:
Difference between two "contains" operations for python lists
I'm fairly new to python and have found that I need to query a list about whether it contains a certain item.
The majority of the postings I have seen on various websites (including this similar stackoverflow question) have all suggested something along... | Difference between two "contains" operations for python lists | I'm fairly new to python and have found that I need to query a list about whether it contains a certain item.
The majority of the postings I have seen on various websites (including this similar stackoverflow question) have all suggested something along the lines of
for i in list
if i == thingIAmLookingFor
... | [
"In your simple example it is of course better to use in.\nHowever... in the question you link to, in doesn't work (at least not directly) because the OP does not want to find an object that is equal to something, but an object whose attribute n is equal to something.\nOne answer does mention using in on a list com... | [
4,
2,
1,
1
] | [] | [] | [
"contains",
"list",
"python"
] | stackoverflow_0007829188_contains_list_python.txt |
Q:
Python 2.x - ConfigParser stripping blank lines in multiline value
The following is the file parsed by ConfigParser:
[Ticket]
description = This is a multiline string.
1
2
4
5
7
As described by the official Python wiki for ConfigParser examples, here is the helper function:
def ConfigSectionMap(section):
... | Python 2.x - ConfigParser stripping blank lines in multiline value | The following is the file parsed by ConfigParser:
[Ticket]
description = This is a multiline string.
1
2
4
5
7
As described by the official Python wiki for ConfigParser examples, here is the helper function:
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in o... | [
"Update: The link I gave you below was to Python 3.0, my apologies I forgot your tag.\nThe 2.7 docs do not mention blank lines in values, so I suspect they are not supported at all.\nSee also this SO question (which looks like Python 3): How to read multiline .properties file in python\n\nFrom the documentation:\n\... | [
1,
0
] | [] | [] | [
"blank_line",
"configparser",
"python"
] | stackoverflow_0007829007_blank_line_configparser_python.txt |
Q:
Evaluating C function on a numpy grid using Cython
The example in Simple wrapping of C code with cython describes nicely how to evaluate a function written in C on an array passed from numpy and return the result in a numpy array.
How would one go about doing the same thing but returning a 2D array? I.e. I'd like ... | Evaluating C function on a numpy grid using Cython | The example in Simple wrapping of C code with cython describes nicely how to evaluate a function written in C on an array passed from numpy and return the result in a numpy array.
How would one go about doing the same thing but returning a 2D array? I.e. I'd like to evaluate a C function on a grid defined by two numpy ... | [
"You can use a normal array for a 2D Matrix. You need only give the length of the dimension to the function.\nIn the C file do something as that: \n(z is now an array of length N*N)\nint fc( int N, const double a[], const double b[], double z[] )\n{\n for( int i = 0; i < N; i++ ){\n for( int j = 0; j <... | [
1
] | [] | [] | [
"cython",
"numpy",
"python"
] | stackoverflow_0007829212_cython_numpy_python.txt |
Q:
What Is ** In Python?
I read the following python code:
a=2**b
I know several languages like c,c++,c#,java... i even googled ** operator without any results.
so what does 2**b means?
A:
It is the exponentiation operator. In your example, a will have the result of 2 to the bth power.
Check out the last ent... | What Is ** In Python? | I read the following python code:
a=2**b
I know several languages like c,c++,c#,java... i even googled ** operator without any results.
so what does 2**b means?
| [
"It is the exponentiation operator. In your example, a will have the result of 2 to the bth power.\nCheck out the last entry in the table in this section.\n",
"it's simple ** means power, so 2**b means 2 to the power of b\n",
"It's python's power operator. You can write this as a = pow(2, b)\n",
"In that exa... | [
12,
10,
7,
5,
5,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0007794009_python.txt |
Q:
Inverting Dictionaries in Python
I want to know which would be an efficient method to invert dictionaries in python. I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared. Here is inverting a dictionary:
inverted = dict([[v,k] for k,... | Inverting Dictionaries in Python | I want to know which would be an efficient method to invert dictionaries in python. I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared. Here is inverting a dictionary:
inverted = dict([[v,k] for k,v in d.items()])
| [
"To remove duplicates by using the largest key, sort your dictionary iterator by value. The call to dict will use the last key inserted:\nimport operator\ninverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1)))\n\n",
"Here is a simple and direct implementation of inverting a dictionar... | [
8,
0
] | [] | [] | [
"dictionary",
"maps",
"python"
] | stackoverflow_0007829674_dictionary_maps_python.txt |
Q:
Python's multiprocessing.Queue + Process: Properly terminating both programs
Given this Python program:
# commented out code are alternatives I tried that don't work.
from multiprocessing import Process, Queue
#from multiprocessing import Process, JoinableQueue as Queue
def start_process(queue):
# queue.canc... | Python's multiprocessing.Queue + Process: Properly terminating both programs | Given this Python program:
# commented out code are alternatives I tried that don't work.
from multiprocessing import Process, Queue
#from multiprocessing import Process, JoinableQueue as Queue
def start_process(queue):
# queue.cancel_join_thread()
while True:
print queue.get()
if __name__ == '__main... | [
"A solution is to send a specific message (eg 'exit' string in my sample) via queue, to terminate the worker(child process) normal. As the CTRL-C signal is send to all children, we need to ignored it.\nHere is sample code:\nfrom multiprocessing import Process, Queue\n\ndef start_process(queue):\n while True:\n ... | [
3
] | [] | [] | [
"multiprocessing",
"process",
"python",
"queue"
] | stackoverflow_0007827290_multiprocessing_process_python_queue.txt |
Q:
Using hashlib to compute md5 digest of a file in Python 3
With python 2.7 the following code computes the mD5 hexdigest of the content of a file.
(EDIT: well, not really as answers have shown, I just thought so).
import hashlib
def md5sum(filename):
f = open(filename, mode='rb')
d = hashlib.md5()
for ... | Using hashlib to compute md5 digest of a file in Python 3 | With python 2.7 the following code computes the mD5 hexdigest of the content of a file.
(EDIT: well, not really as answers have shown, I just thought so).
import hashlib
def md5sum(filename):
f = open(filename, mode='rb')
d = hashlib.md5()
for buf in f.read(128):
d.update(buf)
return d.hexdiges... | [
"I think you wanted the for-loop to make successive calls to f.read(128). That can be done using iter() and functools.partial():\nimport hashlib\nfrom functools import partial\n\ndef md5sum(filename):\n with open(filename, mode='rb') as f:\n d = hashlib.md5()\n for buf in iter(partial(f.read, 128)... | [
37,
10,
2
] | [] | [] | [
"hashlib",
"python",
"python_3.x"
] | stackoverflow_0007829499_hashlib_python_python_3.x.txt |
Q:
C# command-line argument with newline fails in C# but not in python. Need to make the c# work
Env: .NET 3.5 Visual Studio 2008 SP1, on Win XP SP3, Python 2.7. Corporate image, no admin rights.
In C# 3.5, I want to pass a parameter to a command-line program, and this parameter contains newlines. It works in Python ... | C# command-line argument with newline fails in C# but not in python. Need to make the c# work | Env: .NET 3.5 Visual Studio 2008 SP1, on Win XP SP3, Python 2.7. Corporate image, no admin rights.
In C# 3.5, I want to pass a parameter to a command-line program, and this parameter contains newlines. It works in Python 2.7 but not in C#.
When body contains newline, c# truncates the result, but python passes it correc... | [
"Sorry but I think it is the process you call that does not take the arguments correctly; it is not the C# that is involved, and as a proof of that:\n\nCreate a new windows form application\nMake sure that the Main signature looks like this:\nstatic void Main(string[] args)\n\nMake sure that the call of your Main F... | [
2
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0007829760_c#_python.txt |
Q:
Import contacts from yahoo in python
Is there are official way to import contacts from user address book from yahoo?
For google it's really simple as:
import gdata
contacts_service = gdata.contacts.service.ContactsService()
contacts_service.email = email
contacts_service.password = password
contacts_service.Progr... | Import contacts from yahoo in python | Is there are official way to import contacts from user address book from yahoo?
For google it's really simple as:
import gdata
contacts_service = gdata.contacts.service.ContactsService()
contacts_service.email = email
contacts_service.password = password
contacts_service.ProgrammaticLogin()
query = gdata.contacts.serv... | [
"The Contacts REST API is pretty straight-forward. The URL that you're after is\nhttp://social.yahooapis.com/v1/user/{guid}/contacts.json\n\nHere is a script that will extract things for you. You can expand this to include authentication.\nimport urllib2\nimport json\n\ndef get_contacts(guid):\n url = 'http://so... | [
4,
2
] | [] | [] | [
"django",
"python",
"yahoo",
"yahoo_api"
] | stackoverflow_0007686750_django_python_yahoo_yahoo_api.txt |
Q:
Monkey-patch Python class
I've got a class, located in a separate module, which I can't change.
from module import MyClass
class ReplaceClass(object)
...
MyClass = ReplaceClass
This doesn't change MyClass anywhere else but this file. However if I'll add a method like this
def bar():
print 123
MyClass.foo ... | Monkey-patch Python class | I've got a class, located in a separate module, which I can't change.
from module import MyClass
class ReplaceClass(object)
...
MyClass = ReplaceClass
This doesn't change MyClass anywhere else but this file. However if I'll add a method like this
def bar():
print 123
MyClass.foo = bar
this will work and foo m... | [
"import module\nclass ReplaceClass(object):\n ....\nmodule.MyClass = ReplaceClass\n\n",
"Avoid the from ... import (horrid;-) way to get barenames when what you need most often are qualified names. Once you do things the right Pythonic way:\nimport module\n\nclass ReplaceClass(object): ...\n\nmodule.MyClass =... | [
76,
34,
17,
2
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0003765222_monkeypatching_python.txt |
Q:
Does GeoDjango 1.0.2 support django.contrib.messages?
I am wondering if GeoDjango 1.0.2 supports django.contrib.messages because when I execute 'python manage.py syncdb', I am receiving the below error messages.
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(setting... | Does GeoDjango 1.0.2 support django.contrib.messages? | I am wondering if GeoDjango 1.0.2 supports django.contrib.messages because when I execute 'python manage.py syncdb', I am receiving the below error messages.
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Program Files\GeoDjango\Django-1.0.2-final\dj... | [
"The messaging framework was added in Django 1.2, so the answer to your question is probably 'no.' (See https://docs.djangoproject.com/en/dev/ref/contrib/messages/.)\n"
] | [
0
] | [] | [] | [
"geodjango",
"python"
] | stackoverflow_0007829918_geodjango_python.txt |
Q:
Error passing a list to a function via multiprocessing queue module
I'm getting an weird error using queues/multiprocessing. I basically have a function that takes a list then parses it.
I have to do this many times so I thought it would be a good idea to spread it over the cores I have and I tried to setup a que... | Error passing a list to a function via multiprocessing queue module | I'm getting an weird error using queues/multiprocessing. I basically have a function that takes a list then parses it.
I have to do this many times so I thought it would be a good idea to spread it over the cores I have and I tried to setup a queue but its not working. Here's my code:
# Establish communication queues... | [
"This line TypeError: 'Queue' object does not support indexing is indicating that your dict variable is of type Queue (which you probably dont want it to be). Double check lines 191 and up to make sure you are properly assigning the dict variable properly.\n\nAlso, NEVER use a type name as a variable name. dict i... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007830563_python.txt |
Q:
Python: Check if file from list exists, execute function only if it exists
Python noob... please be gentle. In my current program, I have a list of 3 files which may or may not reside in my current directory. If they do reside in my directory, I want to be able to assign them values to be later used in other funct... | Python: Check if file from list exists, execute function only if it exists | Python noob... please be gentle. In my current program, I have a list of 3 files which may or may not reside in my current directory. If they do reside in my directory, I want to be able to assign them values to be later used in other functions. If the file does not reside in the directory, it should not be assigned va... | [
"Of course it stops after first match, because you are doing return from a function. Instead, you should either populate some array in the loop and return it in the end, or create a generator using yield on each iteration and raise StopIteration in case of nothing is found. The first approach is simpler and closer ... | [
2,
2,
1
] | [] | [] | [
"csv",
"for_loop",
"function",
"python"
] | stackoverflow_0007782691_csv_for_loop_function_python.txt |
Q:
A simple setup for Python + Cairo + GTK/GDK pixel buffer
For my own benefit and possibly for educational use, I would like to make a pygame-like API for Python and Cairo. But I don't want it to be exactly pygame. I would instead like to make it a semi-static drawing platform that display one or more images using... | A simple setup for Python + Cairo + GTK/GDK pixel buffer | For my own benefit and possibly for educational use, I would like to make a pygame-like API for Python and Cairo. But I don't want it to be exactly pygame. I would instead like to make it a semi-static drawing platform that display one or more images using GTK/GDK, and I would like to imitate the excellent API princi... | [
"As this was too big for a comment I have added this as a response.\nThe question is not quite clear. Do you mean to ask how to use cairo drawing to draw onto Gtk Widgets? Firstly, there is nothing called GTK Pixbuf, I think you are referring to GDK Pixbuf. Most the drawing stuff in GTK is done at GDK layer. If you... | [
2
] | [] | [] | [
"pycairo",
"pygtk",
"python"
] | stackoverflow_0007830145_pycairo_pygtk_python.txt |
Q:
OS X Get info via Terminal
is there a way to get the information of the application using a terminal command? or python
eg. application QuickTime Player then hit Ctrl + I
A:
You can do this through Applescript, like:
osascript -e 'tell application "Finder" to open information window of alias "Macintosh HD:Applic... | OS X Get info via Terminal | is there a way to get the information of the application using a terminal command? or python
eg. application QuickTime Player then hit Ctrl + I
| [
"You can do this through Applescript, like:\nosascript -e 'tell application \"Finder\" to open information window of alias \"Macintosh HD:Applications:QuickTime Player.app\"'\n\nThere's a post here that shows some really good examples.\nHowever, if there's particular information from that window that you want (rath... | [
1
] | [] | [] | [
"osx_lion",
"python"
] | stackoverflow_0007830967_osx_lion_python.txt |
Q:
inotify_add_watch fails with errno ESUCCESS
On Linux 2.6.16, inotify_add_watch fails and sets errno to ESUCCESS (0) if the path does not exist. Where is this documented?
A:
There was an error in my ctypes wrapper, and errno was not being saved. The solution is to pass use_errno=True to CFUNCTYPE.
| inotify_add_watch fails with errno ESUCCESS | On Linux 2.6.16, inotify_add_watch fails and sets errno to ESUCCESS (0) if the path does not exist. Where is this documented?
| [
"There was an error in my ctypes wrapper, and errno was not being saved. The solution is to pass use_errno=True to CFUNCTYPE.\n"
] | [
0
] | [] | [] | [
"ctypes",
"errno",
"inotify",
"linux",
"python"
] | stackoverflow_0007816996_ctypes_errno_inotify_linux_python.txt |
Q:
Is there a way to get the name of the file only from tkFileDialog?
I have this code:
filename = tkFileDialog.askopenfilename(initialdir="lists/custom/", filetypes=(("Word list",
"*.tldr"), ("All files", "*.*")))
If I had a file called "dog.tldr", is there a way to get only ... | Is there a way to get the name of the file only from tkFileDialog? | I have this code:
filename = tkFileDialog.askopenfilename(initialdir="lists/custom/", filetypes=(("Word list",
"*.tldr"), ("All files", "*.*")))
If I had a file called "dog.tldr", is there a way to get only the file name of it instead of having a directory in front of it? Right ... | [
"os.path.split:\nIn [83]: full_path = \"/dir/blah/dog.tldr\"\n\nIn [84]: os.path.split(full_path)\nOut[84]: ('/dir/blah', 'dog.tldr')\n\nIn [85]: os.path.split(full_path)[1]\nOut[85]: 'dog.tldr'\n\n"
] | [
1
] | [] | [] | [
"file",
"python",
"tkinter"
] | stackoverflow_0007831045_file_python_tkinter.txt |
Q:
swig mysql: undefined symbol: mysql_init'
I am trying to create a swig package for python that offers mysql connectivity. But when I try to import the package in python I get the following error:
-> _mod = imp.load_module('_IMysqlConnection', fp, pathname, description)
(Pdb) s
ImportError: './_IMysqlConnection.so:... | swig mysql: undefined symbol: mysql_init' | I am trying to create a swig package for python that offers mysql connectivity. But when I try to import the package in python I get the following error:
-> _mod = imp.load_module('_IMysqlConnection', fp, pathname, description)
(Pdb) s
ImportError: './_IMysqlConnection.so: undefined symbol: mysql_init'
I am creating t... | [
"You can use\nhttp://sourceforge.net/projects/mysql-python/\nThis does not exactly answer your connection though.\n",
"Solved: I was missing mysql_config --cflags mysql_config --libs while creating the shared library _IMysqlConnection.so\ng++ -shared CMysqlConnection_wrap.o CMysqlConnection.o -o _CMysqlConnection... | [
1,
0
] | [] | [] | [
"c++",
"mysql",
"python",
"swig"
] | stackoverflow_0007821316_c++_mysql_python_swig.txt |
Q:
How do I extract a column from text using Python?
I am a newbie in python programing. Wrote this script by searching in python docs from internet.
Could anybody please help me to get only the second column as output of "ps aux" command(ie only the PID Column).
#script to print the processid
import os
import comman... | How do I extract a column from text using Python? | I am a newbie in python programing. Wrote this script by searching in python docs from internet.
Could anybody please help me to get only the second column as output of "ps aux" command(ie only the PID Column).
#script to print the processid
import os
import commands
out=commands.getoutput('ps aux') # to get the proces... | [
"Use split() and splitlines() (to convert the string into a list of lines, and the list of lines into a list of columns that you can then index as needed):\n>>> for line in out.splitlines():\n... fields = line.split()\n... if len(fields) >= 2:\n... print fields[1]\n\n\nPID\n1\n2\n3\n4\n5\n6\n\n",
... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0007831285_python.txt |
Q:
Python go to next line and save/edit content
This code was established in a previous post. I'm trying to adapt it to fit our data. But it doesn't work .. Here is an example of our file :
read:1424:2165 TGACCA/1:2165 TGACCA/2
1..100 +chr1:3033296..3033395 #just this line
1..100 -chr1:3127494..3127395
1..100 +... | Python go to next line and save/edit content | This code was established in a previous post. I'm trying to adapt it to fit our data. But it doesn't work .. Here is an example of our file :
read:1424:2165 TGACCA/1:2165 TGACCA/2
1..100 +chr1:3033296..3033395 #just this line
1..100 -chr1:3127494..3127395
1..100 +chr1:3740372..3740471
1 concordant read:1483... | [
"Your big mistake is that you need to include readlines before you can iterate over 'in_f':\nwith open(infile, mode='r') as in_f, open(outfile, mode='w') as out_f:\n for line in in_f.readlines():\n ...\n\nHowever, that whole section of code can probably be tidied up quite a bit.\nwith open(infile, mode='r... | [
1
] | [] | [] | [
"line",
"next",
"python",
"string"
] | stackoverflow_0007831451_line_next_python_string.txt |
Q:
python logging into file as well as wxpython txt ctrl
How can I log into a file as well as to to wxpython txt ctrl ?
Background I have wxpython GUI based application which enumerates python test files and executes them. With the help of http://broadcoder.blogspot.com/2009/10/redirecting-python-logging-to.html I wa... | python logging into file as well as wxpython txt ctrl | How can I log into a file as well as to to wxpython txt ctrl ?
Background I have wxpython GUI based application which enumerates python test files and executes them. With the help of http://broadcoder.blogspot.com/2009/10/redirecting-python-logging-to.html I was able to redirect python logging messages to the txtctrl. ... | [
"One Logger can have multiple handlers ! so you can achieve this easily.\nexample \nimport logging\nlogger = logging.getLogger('myapp')\nhdlr = logging.FileHandler('var/myapp.log')\nhdlr2 = logging.FileHandler('var/myapp2.log')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr.setFormatt... | [
5
] | [] | [] | [
"logging",
"python",
"wxpython"
] | stackoverflow_0007817117_logging_python_wxpython.txt |
Q:
Scope issues with for loops in python
In the following code, when I print the row in the first loop after doing a bunch of manipulations with it I see the results that I want. However, after I exit the first loop, I find that I get a different result in the variable Dataset. I know this is a scoping issue but I ca... | Scope issues with for loops in python | In the following code, when I print the row in the first loop after doing a bunch of manipulations with it I see the results that I want. However, after I exit the first loop, I find that I get a different result in the variable Dataset. I know this is a scoping issue but I cannot figure out what the problem is and how... | [
"\nPython has reference semantics. Your original Dataset contains multiple references to the common [0, 0] and [1, 0] sublists. (I'm also at a loss to understand why you're making the initialization so complex.)\n\nYou could fix this by using [[0, 0] for i in xrange(5)] + [[1, 0] for i in xrange(5)].\n\nThe rest of... | [
3,
2,
0,
0
] | [] | [] | [
"for_loop",
"python",
"scope"
] | stackoverflow_0007831772_for_loop_python_scope.txt |
Q:
IO completion port key confusion
I'm writing an IO completion port based server (source code here) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.
As I understand the document... | IO completion port key confusion | I'm writing an IO completion port based server (source code here) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.
As I understand the documentation for CreateIoCompletionPort, you ... | [
"What I've found in everyday practice is that it is best to simply focus on the OVERLAPPED result, as that will be unchanged. One way that you can use it effectively is to have something like the following:\nstruct CompletionHandler\n{\n OVERLAPPED dummy_ovl;\n /* Stuff that actually means something to you h... | [
4,
2,
1,
0,
0,
0
] | [] | [] | [
"ctypes",
"iocp",
"python",
"windows",
"winsock"
] | stackoverflow_0001176477_ctypes_iocp_python_windows_winsock.txt |
Q:
How to run DDL script with kinterbasdb
Is there way to execute DDL script from Python with kinterbasdb library for Firebird database?
Basically I'd like to replicate 'isql -i myscript.sql' command.
A:
It has been a while since I used kinterbasdb, but as far as I know you should be able to do this with any query ... | How to run DDL script with kinterbasdb | Is there way to execute DDL script from Python with kinterbasdb library for Firebird database?
Basically I'd like to replicate 'isql -i myscript.sql' command.
| [
"It has been a while since I used kinterbasdb, but as far as I know you should be able to do this with any query command which can also be used for INSERT, UPDATE and DELETE (ie nothing that produces a resultset). So Connection.execute_immediate and Cursor.execute should work.\nDid you actually try this.\nBTW: With... | [
2
] | [] | [] | [
"ddl",
"firebird",
"kinterbasdb",
"python"
] | stackoverflow_0007825066_ddl_firebird_kinterbasdb_python.txt |
Q:
is there a way to get a (static) method to be called when a class (not an instance) is created?
once again, a bit surprised not to find an answer to this one...
the real-world reason for my asking is:
I have a dictionary of constants in a class
class MySQLConstants():
DECIMAL = 0
TINY = 1
SHORT = 2
LONG =... | is there a way to get a (static) method to be called when a class (not an instance) is created? | once again, a bit surprised not to find an answer to this one...
the real-world reason for my asking is:
I have a dictionary of constants in a class
class MySQLConstants():
DECIMAL = 0
TINY = 1
SHORT = 2
LONG = 3
FLOAT = 4
DOUBLE = 5
... etc.
and I want a dictionary so I can find the constant if given ... | [
"Here is a solution that uses a metaclass:\nclass ConstantDictMeta(type):\n def __new__(cls, name, bases, dct):\n fieldTypeDic = dict((v, k) for k, v in dct.items() if k.isupper())\n dct[\"fieldTypeDic\"] = fieldTypeDic\n return type.__new__(cls, name, bases, dct)\n\nclass MySQLConstants():\... | [
3,
2,
1,
1
] | [] | [] | [
"class",
"methods",
"python",
"static"
] | stackoverflow_0007826651_class_methods_python_static.txt |
Q:
Including docstring in Sphinx Documentation
I'd like to include just the docstring of a specific function in my Sphinx documentation. However there seem to be no options to just display these details without associated class and function definitions using http://www.sphinx-doc.org/en/master/usage/extensions/autodo... | Including docstring in Sphinx Documentation | I'd like to include just the docstring of a specific function in my Sphinx documentation. However there seem to be no options to just display these details without associated class and function definitions using http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
I've tried creating a class as outlined in... | [
"After looking through the source and experimenting - here is how to do it in Sphinx 1.1.\nIn your conf.py file create a new MethodDocumenter subclass. Here you can set a new \"objtype\", make sure the docstring is not indented, and remove the title. \nfrom sphinx.ext import autodoc\n\nclass SimpleDocumenter(autodo... | [
14
] | [] | [] | [
"autodoc",
"python",
"python_sphinx"
] | stackoverflow_0007825263_autodoc_python_python_sphinx.txt |
Q:
how to generate and print documents (python)
I need to allow users edit and print client-related documents (invoices and another).
User fill print form (select clients, month, how much copies of each of 4 types of documents he/she needs) and click to print button.
Next my system should do (algorithm):
result = cre... | how to generate and print documents (python) | I need to allow users edit and print client-related documents (invoices and another).
User fill print form (select clients, month, how much copies of each of 4 types of documents he/she needs) and click to print button.
Next my system should do (algorithm):
result = create new word-friendly file # because user may man... | [
"If using a template is not absolutely required, or if you are willing to recreate the template with code, use reportlab for python to generate a PDF, then print it.\nSee this example on how to make tables:\nhttp://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/\nAlso che... | [
5
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0007831328_printing_python.txt |
Q:
Python Classes in Tkinter's Grid Manager
I am having a problem with either Tkinter's GRID geometry manager or custom classes or both. Most likely both. Here's the code:
import sys
from tkinter import
def main():
app = App()
app.master.title("Sample application")
app.mainloop()
class App(Frame):
... | Python Classes in Tkinter's Grid Manager | I am having a problem with either Tkinter's GRID geometry manager or custom classes or both. Most likely both. Here's the code:
import sys
from tkinter import
def main():
app = App()
app.master.title("Sample application")
app.mainloop()
class App(Frame):
def __init__(self, master=None):
Frame... | [
"The Frame.__init__ needs to be passed the parent:\nclass myTestFrame( tk.Frame ):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\nRunnable example:\nimport sys\nimport Tkinter as tk\nE=tk.E\nW=tk.W\nN=tk.N\nS=tk.S\ndef main():\n app = App()\n app.master.title(\"Sample application\")\n app.mainloo... | [
5
] | [] | [] | [
"class",
"grid",
"python",
"resize",
"tkinter"
] | stackoverflow_0007831655_class_grid_python_resize_tkinter.txt |
Q:
generic CRUD views on django
I'm trying to create generic views for my models and I'm stuck at creating a modelform dynamically. It's there a way of creating a modelform just by having the model's name as string?
A:
You could do this by simply defining the class for the model form in the view's local scope and t... | generic CRUD views on django | I'm trying to create generic views for my models and I'm stuck at creating a modelform dynamically. It's there a way of creating a modelform just by having the model's name as string?
| [
"You could do this by simply defining the class for the model form in the view's local scope and then create an instance of it directly after. You just need to make sure you receive the class of the model according to its name. Use django's get_model function. Simple example:\ndef my_view(request):\n model_name ... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007830632_django_python.txt |
Q:
Fast conversion of large (2.1gb+) binary file (lat/long/altitude to ECEF)
Right now, I'm trying to convert a large quantity of binary files of points in latitude longitude altitude format to text based ECEF cartesian format (x, y, z). The problem right now is that the process is very very very slow.
I have over 1... | Fast conversion of large (2.1gb+) binary file (lat/long/altitude to ECEF) | Right now, I'm trying to convert a large quantity of binary files of points in latitude longitude altitude format to text based ECEF cartesian format (x, y, z). The problem right now is that the process is very very very slow.
I have over 100 gigabytes of this stuff to run through, and more data could be coming in. I ... | [
"To more precisely attack the problem, I suggest measuring the file read operation by making 'convertXYZ' a no-op function and timing the result. And measuring the convert function, by changing the 'read' to always return a simple point, but calling the conversion and output the same number of times as if you were... | [
2,
0,
0
] | [] | [] | [
"file",
"io",
"performance",
"python"
] | stackoverflow_0007828891_file_io_performance_python.txt |
Q:
except block does not catch the exception in python
my code is like below
class Something(models.Model)
def exception(self)
try:
Something.objects.all()
except Exception():
raise Exception()
called this method from testcases ,its working but i need to raise exception ,it does not catch... | except block does not catch the exception in python | my code is like below
class Something(models.Model)
def exception(self)
try:
Something.objects.all()
except Exception():
raise Exception()
called this method from testcases ,its working but i need to raise exception ,it does not catch the exception
and here is my test case
def test_except... | [
"This line:\nexcept Exception():\n\nshould be:\nexcept Exception:\n\n",
"def exception(self)\n try:\n Something.objects.all()\n except Exception, err:\n #print err.message (if you want)\n raise err\n\nThis will catch the error and print the exact msg if required.\n",
"Why catch the Ex... | [
8,
2,
0
] | [] | [] | [
"exception",
"python",
"try_catch"
] | stackoverflow_0007832866_exception_python_try_catch.txt |
Q:
Stretch columns to pair matched cells in rows
Example table:
A | B | C | ...
-----+-----+-----+----
3 | 2 | 2 |
5 | 3 | 4 |
7 | 4 | 6 |
9 | 5 | 8 |
I would like somehow to temper it with Gnumeric and produce matching cells across columns:
A | B | C | ...
-... | Stretch columns to pair matched cells in rows | Example table:
A | B | C | ...
-----+-----+-----+----
3 | 2 | 2 |
5 | 3 | 4 |
7 | 4 | 6 |
9 | 5 | 8 |
I would like somehow to temper it with Gnumeric and produce matching cells across columns:
A | B | C | ...
-----+-----+-----+----
- | 2 | 2 |
3 |... | [
"It's quite easy to do in Python:\na = [3, 5, 7, 9]\nb = [2, 3, 4, 5]\nc = [2, 4, 6, 8]\n\na_ex, b_ex, c_ex = zip(*(\n [elem if elem in col else None\n for col in a, b, c] \n for elem in set(a).union(b, c)\n ))\n\n... | [
1
] | [] | [] | [
"gnumeric",
"python"
] | stackoverflow_0007833533_gnumeric_python.txt |
Q:
Filtering on an indexed value in a CommaSeparatedIntegerField
I have a model class which has a comma separated integer field which maps to a Postgres integer array field.
class Observation(models.Model):
frequencies = models.CommaSeparatedIntegerField(max_length=200)
What I want to be able to do is use the fi... | Filtering on an indexed value in a CommaSeparatedIntegerField | I have a model class which has a comma separated integer field which maps to a Postgres integer array field.
class Observation(models.Model):
frequencies = models.CommaSeparatedIntegerField(max_length=200)
What I want to be able to do is use the filter (or something else suitable) interface to do a comparison on a... | [
"If you find yourself needing to search particular entities within a comma-separated field, you should probably consider whether that's the correct format for your data. Perhaps a foreign key to a separate table might be more appropriate.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0007832248_django_python_sql.txt |
Q:
Python Deleting Certain File Extensions
I'm fairly new to Python, but I have gotten this code to work, and in fact, do what it's intended to do.
However, I'm wondering if there is a more efficient way to code this, perhaps to enhance the processing speed.
import os, glob
def scandirs(path):
for currentFile i... | Python Deleting Certain File Extensions | I'm fairly new to Python, but I have gotten this code to work, and in fact, do what it's intended to do.
However, I'm wondering if there is a more efficient way to code this, perhaps to enhance the processing speed.
import os, glob
def scandirs(path):
for currentFile in glob.glob( os.path.join(path, '*') ):
... | [
"Since you are recursing through subdirectories, use os.walk:\nimport os\n\ndef scandirs(path):\n for root, dirs, files in os.walk(path):\n for currentFile in files:\n print \"processing file: \" + currentFile\n exts = ('.png', '.jpg')\n if currentFile.lower().endswith(ext... | [
20,
2
] | [] | [] | [
"delete_file",
"file_extension",
"logic",
"python"
] | stackoverflow_0007833715_delete_file_file_extension_logic_python.txt |
Q:
In Python, how do I join two arrays by key column?
Suppose I have two arrays (after import numpy as np),
a=np.array([['a',1],['b',2]],dtype=object)
and
b=np.array([['b',3],['c',4]],dtype=object)
How do I get:
c=np.array([['a',1,None],['b',2,3],['c',None,4]],dtype=object)
Basically, an join using the first colu... | In Python, how do I join two arrays by key column? | Suppose I have two arrays (after import numpy as np),
a=np.array([['a',1],['b',2]],dtype=object)
and
b=np.array([['b',3],['c',4]],dtype=object)
How do I get:
c=np.array([['a',1,None],['b',2,3],['c',None,4]],dtype=object)
Basically, an join using the first column as key.
Thanks
| [
"A pure Python approach to do this would be\nda = dict(a)\ndb = dict(b)\nc = np.array([(k, da.get(k), db.get(k))\n for k in set(da.iterkeys()).union(db.iterkeys())])\n\nBut if you are using NumPy, your arrays are probably big, and you are looking for a solution with a better performance. In this case,... | [
6,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004287582_arrays_numpy_python.txt |
Q:
Python re.finditer(): concisely detect "A or :B or C:D"
I am looking for a regexp that returns only three matched groups for the string "A :B C:D"
where A,B,C,D are words examples (\w+)
The following Python code prints unwanted (None,None).
I just want ('A',None) (None,'B') and ('C','D') using one regexp (No add... | Python re.finditer(): concisely detect "A or :B or C:D" | I am looking for a regexp that returns only three matched groups for the string "A :B C:D"
where A,B,C,D are words examples (\w+)
The following Python code prints unwanted (None,None).
I just want ('A',None) (None,'B') and ('C','D') using one regexp (No added python code for filtering).
for m in re.compile(r'(?:(\w+)... | [
"This might do the trick:\n(?=[\\w:])(\\w*)(?::(\\w*))?\n\n(\\w*)(?::(\\w*))? describes the structure you want, but it has a problem that it also matches empty string; thus we have to assure that there is at least one non-space character at the start (which will get matched by the greedy operators), and the lookahe... | [
4,
0
] | [] | [] | [
"iteration",
"python",
"regex"
] | stackoverflow_0007833919_iteration_python_regex.txt |
Q:
Python DateUtil Converting string to a date and time
I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:0... | Python DateUtil Converting string to a date and time | I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or... | [
"The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.\nparser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with\nprint dt.strft... | [
8,
4
] | [] | [] | [
"pyodbc",
"python",
"python_dateutil"
] | stackoverflow_0007834520_pyodbc_python_python_dateutil.txt |
Q:
Query Expired Time Difference in Django ORM
I have a simple model to describe a task and a period between executions of the task:
class Task(models.Model):
last_check_timestamp = models.DateTimeField(blank=True, null=True, db_index=True)
class TaskSchedule(models.Model):
task = models.OneToOneField(Task, ... | Query Expired Time Difference in Django ORM | I have a simple model to describe a task and a period between executions of the task:
class Task(models.Model):
last_check_timestamp = models.DateTimeField(blank=True, null=True, db_index=True)
class TaskSchedule(models.Model):
task = models.OneToOneField(Task, blank=False, null=False, related_name='schedule')... | [
"I had to do a similar query recently. I was hoping to do it using F() objects, but I don't think this is possible, because the timedelta relies on a db column (it would be possible if schedule_interval_seconds was a constant).\nIn the end, I did the query using the ORM with extra(), and wrote SQL for the where cla... | [
3
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0007824864_django_django_orm_python.txt |
Q:
How to display an SQL string that has been constructed by MySQLDB cursor?
I would like to verify for myself how this MySQL string is translated by the cursor:
cursor.execute("SELECT * from elements where id = %s", (element_id))
Is there a way to get at the computed SQL string and print it out, preferably before e... | How to display an SQL string that has been constructed by MySQLDB cursor? | I would like to verify for myself how this MySQL string is translated by the cursor:
cursor.execute("SELECT * from elements where id = %s", (element_id))
Is there a way to get at the computed SQL string and print it out, preferably before execution? (the latter is not absolutely necessary - I'm just doing this because... | [
"Yes. As Ferdinand has pointed out, there is a MySQLdb/cursors.py containing an execute(), which in turn calls _query().\nThis puts the executed query into self._executed.\nSo you can get it from cursor._executed.\n",
"MySQL-Python does nothing special, it just encodes each argument to prevent SQL injections and ... | [
6,
1
] | [] | [] | [
"mysql_python",
"python"
] | stackoverflow_0007834746_mysql_python_python.txt |
Q:
Extract information from XML
I'm using etree module. I'm trying to extract the information around <text ...> tag. Here is my XML file. I want if <text ...">{{Infobox film start with Infobox film then copy all the text between {{ }}. Is it possible? thanks
Update: XML file updated
A:
The following snippet should ... | Extract information from XML | I'm using etree module. I'm trying to extract the information around <text ...> tag. Here is my XML file. I want if <text ...">{{Infobox film start with Infobox film then copy all the text between {{ }}. Is it possible? thanks
Update: XML file updated
| [
"The following snippet should do what you want:\nimport re\nfrom xml.etree import ElementTree \n\nwith open('films.xml') as f: \n xml = ElementTree.parse(f) \n\nfor t ... | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0007834907_python_xml.txt |
Q:
Numbers related query
What's the meaning of "L" behind any number(e.g 153L=?,648L=?)
I am getting the value 2432902008176640000L while i am typing math.factorial(20) in python2.7 interpreter.
May be some ppl find it a silly question but i dont know anything about this "L" thing.So please help me to increase my kno... | Numbers related query | What's the meaning of "L" behind any number(e.g 153L=?,648L=?)
I am getting the value 2432902008176640000L while i am typing math.factorial(20) in python2.7 interpreter.
May be some ppl find it a silly question but i dont know anything about this "L" thing.So please help me to increase my knowledge.
| [
"It means that the number is a long Integer, and can store larger numbers.\n",
"It 's a Long integer. More about it, in the Python docs: 5.4. Numeric Types\n",
"That means the number is a Long, meaning it is stored using more bytes and can contain larger values\n"
] | [
2,
1,
0
] | [] | [] | [
"numbers",
"python"
] | stackoverflow_0007835250_numbers_python.txt |
Q:
The best way recognizing similarity of list lengths
I have a dict containing lists under its keys:
dct = {'a': [1, 2, 3],
'b': [1, 2, 3, 4],
'c': [1, 2]}
What is the best way to recognize whether the length of the lists are the same or not?
This is my solution:
import itertools
len(set(itertools.ima... | The best way recognizing similarity of list lengths | I have a dict containing lists under its keys:
dct = {'a': [1, 2, 3],
'b': [1, 2, 3, 4],
'c': [1, 2]}
What is the best way to recognize whether the length of the lists are the same or not?
This is my solution:
import itertools
len(set(itertools.imap(len, dct.viewvalues()))) == 1
True if similar and Fal... | [
"Your solution looks fine.\nIf you want to tweek it a bit, use itertools.imap() instead of map(). That will collapse the memory footprint to O(1) instead of O(n).\n",
"First, I would stick with itervalues, which uses easy evaluation.\nSecond, I would be wary of relying on using set since it performs looking up t... | [
6,
5,
2,
1
] | [] | [] | [
"algorithm",
"list",
"python"
] | stackoverflow_0007826428_algorithm_list_python.txt |
Q:
Django Generic List/Detail Class based views
I have a Generic ListView, each item in my html list links to a DetailView.
Now I'd like to increment the MyModel(DetailView) object "views"-field (integerfield) on each click.
All I seem to have at hand in the DetailView is get_context_data? So how do I update my model... | Django Generic List/Detail Class based views | I have a Generic ListView, each item in my html list links to a DetailView.
Now I'd like to increment the MyModel(DetailView) object "views"-field (integerfield) on each click.
All I seem to have at hand in the DetailView is get_context_data? So how do I update my model on this action?
n.b. Thinking out loud, should th... | [
"You can indeed do it in get_object method, like this:\nclass YourView(DetailView):\n\n queryset = YourModel.objects.all()\n\n def get_object(self):\n object = super(YourView, self).get_object()\n object.views = object.views + 1\n object.save()\n return object\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007835616_django_python.txt |
Q:
How to update data in django table from csv file while keeping the primary key value as it is.?
I have a table which already contains some data in it. Now i want to upload new data from a csv file and want to update some of the previous values of that table. I am using django 1.3 and sqlite3 as database. But i am ... | How to update data in django table from csv file while keeping the primary key value as it is.? | I have a table which already contains some data in it. Now i want to upload new data from a csv file and want to update some of the previous values of that table. I am using django 1.3 and sqlite3 as database. But i am not able to update the table.
| [
"If you do not want to change Primay key values or do not to add new objects to the table, which could be duplicate of the old info - then you need some kind of data which you can use as lookup parameters in your database. \nIf you have model which represents this data, then its really easy using \nm = Model.object... | [
0
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0007833668_django_python_sqlite.txt |
Q:
Python: finding an element in a list
What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.
Is there a way to specify what comparison operator to use?
A:
From Dive Into Python:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>... | Python: finding an element in a list | What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.
Is there a way to specify what comparison operator to use?
| [
"From Dive Into Python:\n>>> li\n['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']\n>>> li.index(\"example\")\n5\n\n",
"If you just want to find out if an element is contained in the list or not:\n>>> li\n['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']\n>>> 'example' ... | [
309,
173,
71,
57,
19,
8,
6,
4,
2,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0000604802_list_python.txt |
Q:
Python: Maintaining code in modules
I'm building a project and I have run into the following problem:
I have implemented several subclasses, each of them having about 250 lines of code. Semantically, they should go together in the same module and I want to import them with
from mymodule import SubclassA, SubclassB... | Python: Maintaining code in modules | I'm building a project and I have run into the following problem:
I have implemented several subclasses, each of them having about 250 lines of code. Semantically, they should go together in the same module and I want to import them with
from mymodule import SubclassA, SubclassB
But then my module file has thousands o... | [
"You can always put the from subclassa ... imports into your package's __init__.py as you showed in your second listing. Then, they will be available directly off of your package as you wrote in your first listing.\n",
"I prefer the second solution, with separate files. The imports are not that awful.\nIf they b... | [
5,
1,
0
] | [] | [] | [
"code_organization",
"coding_style",
"python"
] | stackoverflow_0007835975_code_organization_coding_style_python.txt |
Q:
What information depicts the quantitative difference between two large given files of the same size?
Usually, in order to find how two binary files are different, I use diff and hexdump tools. But in some situations if two large binary files of the same size are given, I would like to see only their quantitative d... | What information depicts the quantitative difference between two large given files of the same size? | Usually, in order to find how two binary files are different, I use diff and hexdump tools. But in some situations if two large binary files of the same size are given, I would like to see only their quantitative differences, like number of regions of differences, cumulative difference.
Example: 2 Files A and B. They ... | [
"For everything but the regions thing you can use numpy. Something like this (untested):\nimport numpy as np\na = np.fromfile(\"file A\", dtype=\"uint8\")\nb = np.fromfile(\"file B\", dtype=\"uint8\")\n\n# Compute the number of bytes that are different\ndifferent_bytes = np.sum(a != b)\n\n# Compute the sum of the d... | [
1,
0
] | [] | [] | [
"bash",
"hexdump",
"linux",
"python",
"statistics"
] | stackoverflow_0007834123_bash_hexdump_linux_python_statistics.txt |
Q:
Blocking Thrift calls with Twisted
I have a Twisted/Thrift server that uses the TTwisted protocol. I want to keep connections from clients open until a given event happens (I am notified of this event by the Twisted reactor via a callback).
class ServiceHandler(object):
interface.implements(Service.Iface)
... | Blocking Thrift calls with Twisted | I have a Twisted/Thrift server that uses the TTwisted protocol. I want to keep connections from clients open until a given event happens (I am notified of this event by the Twisted reactor via a callback).
class ServiceHandler(object):
interface.implements(Service.Iface)
def listenForEvent(self):
"""
... | [
"You should be able to return a Deferred from listenForEvent. Later handleEvent should fire that returned Deferred (or those returned Deferreds) to actually generate the response.\n",
"The error you're seeing seems to indicate that the transport is not framed (Twisted needs it to be so it can know the length of ... | [
2,
1
] | [] | [] | [
"python",
"thrift",
"twisted"
] | stackoverflow_0007816202_python_thrift_twisted.txt |
Q:
Color Themes For Eclipse Python Development
I am looking for Eclipse themes that are similar to the following and support Python/xhtml/css/js by default.
A:
Here's a dark theme and instructions on making it.
And another.
There was some discussion of this on SO already.
A:
There is a whole website dedicated to ... | Color Themes For Eclipse Python Development | I am looking for Eclipse themes that are similar to the following and support Python/xhtml/css/js by default.
| [
"Here's a dark theme and instructions on making it.\nAnd another.\nThere was some discussion of this on SO already.\n\n",
"There is a whole website dedicated to color schemes in Eclipse\nhttp://www.eclipsecolorthemes.org/\nThe color schemes on this site can be imported as an EPF preference file directly or altern... | [
5,
2,
1
] | [] | [] | [
"eclipse",
"python",
"themes"
] | stackoverflow_0001685079_eclipse_python_themes.txt |
Q:
Passing Parameters to Stored Procedures using PyODBC
I'm using pyODBC to connect to a SQL Server 2005 express database. I've created a stored procedure in SQLServer express that takes 2 string parameters e.g stored_proc(inpu1, input2) these parameters are of type datetime. I have tested the stored proc using manag... | Passing Parameters to Stored Procedures using PyODBC | I'm using pyODBC to connect to a SQL Server 2005 express database. I've created a stored procedure in SQLServer express that takes 2 string parameters e.g stored_proc(inpu1, input2) these parameters are of type datetime. I have tested the stored proc using management studio and it does return an appropriate result. How... | [
"I finally got it, to work without crashing \n\nlocal_cursor.execute(\"{call dbo.GetAlarmEventHistoryFrequency_TimeRange(tstart,tend)}\") \n\nis the wrong syntax. It should be\n\nlocal_cursor.execute(\"{call dbo.GetAlarmEventHistoryFrequency_TimeRange(?,?)}\",(tstart),(tend))\n\nSpecial attention should be made to ... | [
4
] | [] | [] | [
"pyodbc",
"python",
"sql_server_2005"
] | stackoverflow_0007824161_pyodbc_python_sql_server_2005.txt |
Q:
Python matching the input with a xml attribute
I have a XML and a code. But I can't figure out how to do the part.
XML:
<settings>
<plugin id="1" name="Send Mail" execute="func/sendmail.py">
<param name="towhere" value="To Where?" />
<param name="mailsub" value="Mail Subject" />
<param name="mailcont" ... | Python matching the input with a xml attribute | I have a XML and a code. But I can't figure out how to do the part.
XML:
<settings>
<plugin id="1" name="Send Mail" execute="func/sendmail.py">
<param name="towhere" value="To Where?" />
<param name="mailsub" value="Mail Subject" />
<param name="mailcont" value="Mail Content" />
<param name="senderid" v... | [
"When the for loop that prints the values is over, plugin equals the third object (whose id is 3). So every use of plugin after that point will always refer to the server reboot option. Instead, you need:\n[...]\nselection = raw_input(\"Enter your choice: \")\nplugin = yXML.getElementsByTagName('plugin')[int(select... | [
2
] | [] | [] | [
"input",
"match",
"python",
"xml"
] | stackoverflow_0007837312_input_match_python_xml.txt |
Q:
How to have a change list in django that filters by a field having a relation?
Suppose I have two models:
class Blog(models.Model):
pass
class Article(models.Model):
blog = models.ForeignKey(Blog, related_name="articles")
I want to filter only blogs that have an article. The filter would be something lik... | How to have a change list in django that filters by a field having a relation? | Suppose I have two models:
class Blog(models.Model):
pass
class Article(models.Model):
blog = models.ForeignKey(Blog, related_name="articles")
I want to filter only blogs that have an article. The filter would be something like this:
Blog.objects.annotate(article_count=models.Count('articles')).filter(article... | [
"There's currently no way, aside from some very painful hacks, to accomplish that. Django 1.4 will ship with the ability to create custom filterspecs (see: https://code.djangoproject.com/ticket/5833), which will allow you to do stuff like this.\nSince this seems to be kind of an edge case (really, how many blogs wi... | [
0
] | [] | [] | [
"admin",
"django",
"filter",
"python"
] | stackoverflow_0007836710_admin_django_filter_python.txt |
Q:
How-To - Update Live Running Python Application
I have a python application , to be more precise a Network Application that can't go down this means i can't kill the PID since it actually talks with other servers and clients and so on ... many € per minute of downtime , you know the usual 24/7 system.
Anyway in my... | How-To - Update Live Running Python Application | I have a python application , to be more precise a Network Application that can't go down this means i can't kill the PID since it actually talks with other servers and clients and so on ... many € per minute of downtime , you know the usual 24/7 system.
Anyway in my hobby projects i also work a lot with WSGI framework... | [
"It's safe to call reload(handler).\nDepends where you initialize your connections. If you make the connections inside handler(), then yes, they'll be garbage collected when the handler() object falls out of scope. But you wouldn't be connecting inside your main loop, would you? I'd highly recommend something like:... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007836820_python.txt |
Q:
How would you improve the performance of this function?
import numpy
def euclideanClassification(punto1, punto2):
return (numpy.dot(punto2, punto1) - ((1.0/2.0) * numpy.dot(punto1, punto1)))
I'm trying to improve the performance of this function, but I don't know how.
This function is a variant of the Euclid... | How would you improve the performance of this function? | import numpy
def euclideanClassification(punto1, punto2):
return (numpy.dot(punto2, punto1) - ((1.0/2.0) * numpy.dot(punto1, punto1)))
I'm trying to improve the performance of this function, but I don't know how.
This function is a variant of the Euclidean distance used in pattern recognition.
| [
"If I'm not mistaken, that formula should be equivalent to this:\nnumpy.dot(punto2 - 0.5 * punto1, punto1)\n\nbut if you write it like this you save three multiplications, so in theory it should be slightly faster.\n",
"You could use Cython for that task.\n\n[Cython] is a programming language based on Python, wit... | [
3,
0
] | [] | [] | [
"distance",
"numpy",
"performance",
"python"
] | stackoverflow_0007837099_distance_numpy_performance_python.txt |
Q:
How to use PyBrain?
PyBrain is a Python-based library for creating neural networks. I've looked at the tutorials on their site but they don't seem to help me very much. The simulation I plan to do is have a car that drives on a track, equipped with 5 rangefinders showing the current distance between it and the w... | How to use PyBrain? | PyBrain is a Python-based library for creating neural networks. I've looked at the tutorials on their site but they don't seem to help me very much. The simulation I plan to do is have a car that drives on a track, equipped with 5 rangefinders showing the current distance between it and the walls, ranging between 0.0... | [
"It seems that this is a supervised learning problem. In this type of problem you NEED to provide some answers BEFORE to train your NN.\nYou can try following approach \n\nCreate a simple maze for your car. \nDrive your car manually in this maze.\nCollect your turning information\n\nLets assume you have following c... | [
9
] | [] | [] | [
"neural_network",
"python"
] | stackoverflow_0007786737_neural_network_python.txt |
Q:
How can I force IPython to only give me a new prompt when all threads have finished
I'm using IPython to develop a multi-threaded socket based client-server type thing. The problem is IPython tries to give it's command prompt prompt before some of my threads have finished running. The debug text output of the thre... | How can I force IPython to only give me a new prompt when all threads have finished | I'm using IPython to develop a multi-threaded socket based client-server type thing. The problem is IPython tries to give it's command prompt prompt before some of my threads have finished running. The debug text output of the thread is then lost.
Is there any way to have IPython only give me a new prompt when all the ... | [
"Try\nthreads = [threading.Thread(target=myFunc) for i in range(n)]\nfor t in threads:\n t.start()\n...\nfor t in threads:\n t.join()\n\nwhere threads is a list of your threading.Thread instances. This will cause the main thread to wait until all worker threads are done.\n",
"Instead of waiting for the thre... | [
2,
0
] | [] | [] | [
"ipython",
"multithreading",
"python"
] | stackoverflow_0007836156_ipython_multithreading_python.txt |
Q:
How can request.method == None in Django
I am trying to figure out this issue related to Django from https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1
Under what conditions can request.method == None in Django?
A:
TL;DR: request.method is never None in real use, but for your partic... | How can request.method == None in Django | I am trying to figure out this issue related to Django from https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/issues/1
Under what conditions can request.method == None in Django?
| [
"TL;DR: request.method is never None in real use, but for your particular case, you're looking at the wrong thing.\nGeneric HttpRequest\ndjango/http/__init__.py:\nclass HttpRequest(object):\n ...\n def __init__(self):\n ...\n self.method = None\n ...\n\nWhen a plain HttpRequest is instant... | [
7,
0
] | [] | [] | [
"django",
"httprequest",
"python"
] | stackoverflow_0007836834_django_httprequest_python.txt |
Q:
Trouble understanding passing values and references in Python
Having issues with when objects are changed and when they aren't in Python. Here is my poorly contrived example below:
class person:
age = 21
class bar:
def __init__(self, arg1):
self.foo = arg1
self.foo.age = 23
def baz(arg1):... | Trouble understanding passing values and references in Python | Having issues with when objects are changed and when they aren't in Python. Here is my poorly contrived example below:
class person:
age = 21
class bar:
def __init__(self, arg1):
self.foo = arg1
self.foo.age = 23
def baz(arg1):
arg1.age = 27
def teh(arg1):
arg1 = [3,2,1]
Person1 = pe... | [
"I can see three fundamental Python concepts that can shine some light on the question:\n1) First, an assignment from a mutable object like in\nself.foo = arg1\n\nis like copying a pointer (and not the value pointed to): self.foo and arg1 are the same object. That's why the line that follows,\nself.foo.age = 23\n\... | [
8,
6,
0
] | [] | [] | [
"oop",
"pass_by_reference",
"python",
"reference"
] | stackoverflow_0007838005_oop_pass_by_reference_python_reference.txt |
Q:
How do I save a binary buffer allocated via ctype malloc to a file in Python?
I have the following code
import ctypes
pBuf = ctypes.cdll.msvcrt.malloc(nBufSize)
# wrote something into the buffer
How do I save the content of the buffer to a file using Python 2.5?
As you may already know, this is not going to work,... | How do I save a binary buffer allocated via ctype malloc to a file in Python? | I have the following code
import ctypes
pBuf = ctypes.cdll.msvcrt.malloc(nBufSize)
# wrote something into the buffer
How do I save the content of the buffer to a file using Python 2.5?
As you may already know, this is not going to work, giving TypeError: argument 1 must be string or read-only buffer, not int:
f = open... | [
"Maybe it would better to have the buffer allocated with ctypes.create_string_buffer() instead of malloc(). In this case, you have access to the data via buf.raw.\nIf you need access to malloc()ed data, you can do so with ctypes.string_at(address, size), mybe combined with a cast to ctypes.c_void_p or ctypes.c_char... | [
4,
3
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0007837852_python_windows.txt |
Q:
Regarding regular expressions and XML
I have data in XML format. Example is shown as follow. I want to extract data from <text> tag.
Here is my XML data.
<text>
The 40-Year-Old Virgin is a 2005 American buddy comedy
film about a middle-aged man's journey to finally have sex.
<h1>The plot</h1>
... | Regarding regular expressions and XML | I have data in XML format. Example is shown as follow. I want to extract data from <text> tag.
Here is my XML data.
<text>
The 40-Year-Old Virgin is a 2005 American buddy comedy
film about a middle-aged man's journey to finally have sex.
<h1>The plot</h1>
Andy Stitzer (Steve Carell) is the eponymo... | [
"Use an XML parser to parse XML. Using lxml:\nimport lxml.etree as ET\n\ncontent='''\\\n<text>\n The 40-Year-Old Virgin is a 2005 American buddy comedy\n film about a middle-aged man's journey to finally have sex.\n\n <h1>The plot</h1>\n Andy Stitzer (Steve Carell) is the eponymous 40-year-old virgin.\n... | [
4,
2,
2,
2,
1
] | [] | [] | [
"python",
"regex",
"xml"
] | stackoverflow_0007838290_python_regex_xml.txt |
Q:
Python non linear equation with lagrangian multipliers estimation
i 've been struggling for days on this thing....but to no avail. I'm not very good at difficult math let alone this kind of level of difficulty.
I was trying to implement the maximum entropy application for the lottery in python for my graduation as... | Python non linear equation with lagrangian multipliers estimation | i 've been struggling for days on this thing....but to no avail. I'm not very good at difficult math let alone this kind of level of difficulty.
I was trying to implement the maximum entropy application for the lottery in python for my graduation assignment, altough the focus of the project was to implement a number of... | [
"You need to use equations 7 through 9 in combination. The only things that are unknown in the equations are the Lagrange multipliers, the lambdas. Everything else depends on the empirical data available, and are thus just numbers. \nGiven a set of values for the lambdas, you can calculate the G(j,r) and the Jacobi... | [
4
] | [] | [] | [
"math",
"newtons_method",
"probability",
"python"
] | stackoverflow_0007821669_math_newtons_method_probability_python.txt |
Q:
how to compile or run a python program in fedora?
How do I run a simple python program in fedora?
I am very much new to fedora and i don't know how exactly to start in fedora. Do we need to install any software in fedora to make python programs work? Please tell me step by step how to do it. I am familiar with ID... | how to compile or run a python program in fedora? | How do I run a simple python program in fedora?
I am very much new to fedora and i don't know how exactly to start in fedora. Do we need to install any software in fedora to make python programs work? Please tell me step by step how to do it. I am familiar with IDLE but not in fedora.
| [
"Put \n#!/usr/bin/env python\n\nat the top of your file. Then on the command line do \n$ chmod u+x your_python_file.py\n\n(I use $ to indicate a shell prompt, don't type that.) \nYou can run the file with\n$ ./yourpythonfile.py\n\nYou can also just do\n$ python yourpythonfile.py\n\nand don't need the #!/usr.... or ... | [
7,
1
] | [] | [] | [
"fedora",
"python"
] | stackoverflow_0007838758_fedora_python.txt |
Q:
Can I deploy a django app which uses sqlite3 as backend on google app engine?
I created a simple bookmarking app using django which uses sqlite3 as the database backend.
Can I upload it to appengine and use it? What is "Django-nonrel"?
A:
Unfortunately, no you can't. Google App Engine does not allow you to write... | Can I deploy a django app which uses sqlite3 as backend on google app engine? | I created a simple bookmarking app using django which uses sqlite3 as the database backend.
Can I upload it to appengine and use it? What is "Django-nonrel"?
| [
"Unfortunately, no you can't. Google App Engine does not allow you to write files, and that is needed by SQLite.\nUntil recently, it had no support of SQL at all, preferring a home-grown solution (see the \"CAP theorem\" as for why). This motivated the creation of projects like \"Django-nonrel\" which is a version ... | [
5
] | [] | [] | [
"django",
"google_app_engine",
"python",
"sqlite",
"web_applications"
] | stackoverflow_0007838667_django_google_app_engine_python_sqlite_web_applications.txt |
Q:
Python: Files downloading into the wrong location
I'm using the code below to create a folder and then download the assocated PDBs with that protein. The problem I'm having is the PDBs are downloaded into the wrong location. They are downloaded into the loaction with the python script and not into the Cytochrome_C... | Python: Files downloading into the wrong location | I'm using the code below to create a folder and then download the assocated PDBs with that protein. The problem I'm having is the PDBs are downloaded into the wrong location. They are downloaded into the loaction with the python script and not into the Cytochrome_C folder.
pdb = [
['Cytochrome_C']
['1giw','TITLE']
['1l... | [
"os.popen is unnecessary for every one of those tasks. Use shutil and urllib2:\npdb = [\n['Cytochrome_C']\n['1giw','TITLE']\n['1lc1','TITLE']\n['1lc2','TITLE']\n]\ncwd = os.path.abspath(os.getcwd())\n\nfor pdb in pdbs:\n if pdb[0] == 'Cytochrome_C':\n shutil.mkdir(os.path.join(cwd, pdb[0]))\n\n if len(... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007838885_python.txt |
Q:
How to quit a pygtk application after last window is closed/destroyed
Is there a way I can tell gtk to automatically call gtk.main_quit() when the last open window of the application is closed/destroyed?
If there is no direct feature offering this functionality, I could think of the following:
In the window's dest... | How to quit a pygtk application after last window is closed/destroyed | Is there a way I can tell gtk to automatically call gtk.main_quit() when the last open window of the application is closed/destroyed?
If there is no direct feature offering this functionality, I could think of the following:
In the window's destroy method: get a list of open windows in the process, if its empty quit. I... | [
"the destroy signal of the main window must be connected to gtk main_quit :\nwindow.connect(\"destroy\", gtk.main_quit)\n\n",
"Use the method gtk.main_level() to get the current nesting level of the main loop. The nesting level is increased by calling the gtk.main() function and reduced by calling the gtk.main_qu... | [
6,
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"quit",
"window"
] | stackoverflow_0007567707_gtk_pygtk_python_quit_window.txt |
Q:
Are there any working examples of Zolera SOAP Infrastructure (ZSI)?
i have looked at examples :
http://pywebsvcs.svn.sourceforge.net/viewvc/pywebsvcs/trunk/wstools/
http://pywebsvcs.sourceforge.net/cookbook.pdf
and googled, but could not find a single usable example.
A:
reference: (Thanks to Doug Hellmann ) b... | Are there any working examples of Zolera SOAP Infrastructure (ZSI)? | i have looked at examples :
http://pywebsvcs.svn.sourceforge.net/viewvc/pywebsvcs/trunk/wstools/
http://pywebsvcs.sourceforge.net/cookbook.pdf
and googled, but could not find a single usable example.
| [
"reference: (Thanks to Doug Hellmann ) building soap service\nThe Zolera Soap Infrastucture (ZSI), is a part of the pywebsvcs project. It provides complete server and client libraries for working with SOAP. To use it, a developer writes the WSDL file (by hand or using a WSDL editor), and then generates Python sourc... | [
11
] | [] | [] | [
"python",
"soap",
"zsi"
] | stackoverflow_0007796440_python_soap_zsi.txt |
Q:
Python - How to build and access a large collection of data without maxing out memory or slowing processing to a halt
I am writing a script in Python to QC data in a proprietary ESRI database table. The purpose of the script is not to modify invalid data, but simply to report invalid data to the user via a csv f... | Python - How to build and access a large collection of data without maxing out memory or slowing processing to a halt | I am writing a script in Python to QC data in a proprietary ESRI database table. The purpose of the script is not to modify invalid data, but simply to report invalid data to the user via a csv file. I am using ESRI's ArcPy package to access each individual record with arcpy.SearchCursor. The SearchCursor is the onl... | [
"If you store hashes in (compressed) files, you could stream through them to compare hashes to look for duplicates. Streaming usually has very low memory requirements — you can set the buffer you want, say, one line per hashed record. The tradeoff is generally time, particularly if you add compression, but if you o... | [
0,
0
] | [] | [] | [
"collections",
"containers",
"memory",
"persistence",
"python"
] | stackoverflow_0007836672_collections_containers_memory_persistence_python.txt |
Q:
Comet-like behaviour with Python-Django
My possibilities are limited, as I do have a nice host but can just use the normal server plan. Which means, only a normal server on port 80.
I have tried to read up some on WebSockets and/or Comet, and they mostly seem to require a second server running on another port.
Is ... | Comet-like behaviour with Python-Django | My possibilities are limited, as I do have a nice host but can just use the normal server plan. Which means, only a normal server on port 80.
I have tried to read up some on WebSockets and/or Comet, and they mostly seem to require a second server running on another port.
Is there a way to get a stable Comet-like behavi... | [
"I've had some success using socket.io for asynchronous web stuff (comet). For Django in particular, I don't have any personal experience, but I found a nice article about combining Gevent, Socket.io, and Django. Some other resources on Socket.io and Gevent can be found on my in a couple of my blog articles as well... | [
4
] | [] | [] | [
"comet",
"django",
"python",
"websocket"
] | stackoverflow_0007838629_comet_django_python_websocket.txt |
Q:
Obtaining Client IP address from a WSGI app using Eventlet
I'm currently writing a basic dispatch model server based on the Python Eventlet library (http://eventlet.net/doc/). Having looked at the WSGI docs on Eventlet (http://eventlet.net/doc/modules/wsgi.html), I can see that the eventlet.wsgi.server function lo... | Obtaining Client IP address from a WSGI app using Eventlet | I'm currently writing a basic dispatch model server based on the Python Eventlet library (http://eventlet.net/doc/). Having looked at the WSGI docs on Eventlet (http://eventlet.net/doc/modules/wsgi.html), I can see that the eventlet.wsgi.server function logs the x-forwarded-for header in addition to the client IP addre... | [
"What you want is in the wsgi environ, specifically environ['REMOTE_ADDR']. \nHowever, if there is a proxy involved, then REMOTE_ADDR will be the address of the proxy, and the client address will be included (most likely) in HTTP_X_FORWARDED_FOR. \nHere's a function that should do what you want, for most cases (all... | [
16
] | [] | [] | [
"eventlet",
"python",
"wsgi"
] | stackoverflow_0007835030_eventlet_python_wsgi.txt |
Q:
how to has n images for each item
I have 2 models named Tour and Agency
each Tour and each Agency can have n images
how can I implement this?
should I define a model like this:
class Gallery(models.Model):
Image=models.ImageField(upload_to="gallery")
and add this field to Tour and Agency models?like this:
Gal... | how to has n images for each item | I have 2 models named Tour and Agency
each Tour and each Agency can have n images
how can I implement this?
should I define a model like this:
class Gallery(models.Model):
Image=models.ImageField(upload_to="gallery")
and add this field to Tour and Agency models?like this:
Gallery=models.ForeignKey(Gallery)
If I d... | [
"There are several different ways to do this, depending on whether you want to re-use images between Tours and Agencies, and whether it makes sense to have one Image class or two. Without knowing more about your use case, I might do it like this:\nclass Gallery(models.Model):\n \"Represents a set of images.\"\n ... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007839433_django_python.txt |
Q:
Parse unstructured text for dictionary terms to include a link to term
I am working on a django project, and have a model that has a list of things. Throughout the site, I may have unstructured text entered in other models. On display of a page, I would like to parse the unstructured text, for any reference to t... | Parse unstructured text for dictionary terms to include a link to term | I am working on a django project, and have a model that has a list of things. Throughout the site, I may have unstructured text entered in other models. On display of a page, I would like to parse the unstructured text, for any reference to thing.slug, and include a link to thing.get_absolute_url.
I would assume an a... | [
"urls = dict((thing.slug, thing.get_absolute_url) for thing in things)\nfor word in object.text.split():\n if word in urls:\n result.append('<a href=\"'+urls[words]+'\">'+word+'</a> ')\n else\n result.append(word+' ')\n\n",
"The re module has a sub() function that is designed for this kind of search and... | [
1,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007837467_django_django_templates_python.txt |
Q:
Is there a generic update notification/pub sub system for GTK?
I'm building a PyGTK application with several widgets that when changed, need to notify other widgets about the change. I would like to avoid code like this:
def on_entry_color_updated(self, widget):
self.paint_tools_panel.current_color_pane.update... | Is there a generic update notification/pub sub system for GTK? | I'm building a PyGTK application with several widgets that when changed, need to notify other widgets about the change. I would like to avoid code like this:
def on_entry_color_updated(self, widget):
self.paint_tools_panel.current_color_pane.update_color()
self.main_window.status_bar.update_color()
self.cur... | [
"For one, you could create a custom subclass of GObject, which provides some custom signals. The following example is a slightly adapted version of the one given in the linked article:\nimport pygtk\npygtk.require('2.0')\nimport gobject\n\nclass Car(gobject.GObject):\n\n __gsignals__ = {\n 'engine-started... | [
1,
1
] | [] | [] | [
"architecture",
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0007838241_architecture_gtk_pygtk_python_user_interface.txt |
Q:
Compile 64-bit Mac app with py2app
I've compiled a Python screen saver on my Mac OS X 10.7 using py2app 0.6.3, but when I open the screen saver in System Preferences i get the following message:
You cannot use the Silly Balls screen saver on this computer.
I've read that this message means it needs to be compile... | Compile 64-bit Mac app with py2app | I've compiled a Python screen saver on my Mac OS X 10.7 using py2app 0.6.3, but when I open the screen saver in System Preferences i get the following message:
You cannot use the Silly Balls screen saver on this computer.
I've read that this message means it needs to be compiled for 64-bit.
I'm running Python 2.7.1 6... | [
"Something like this - note 'LSArchitecturePriority' : 'x86_64',\n#cat ./setup.py \n\"\"\"\nThis is a setup.py script generated by py2applet\n\nUsage:\n python setup.py py2app\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\nAPP = ['YourApp.py']\nDATA_FILES = []\nOPTIONS = {\n 'argv_emulation': False... | [
3
] | [] | [] | [
"64_bit",
"macos",
"py2app",
"python",
"screensaver"
] | stackoverflow_0007821589_64_bit_macos_py2app_python_screensaver.txt |
Q:
Opening socket to outside computer with Python
I am using the following code to open a socket on my computer. When I go to my_ip:5000 on my computer the program responds. However, when I use another computer, nothing happens.
HOST = 'my_ip' # Symbolic name meaning the local host
PORT = 8000 ... | Opening socket to outside computer with Python | I am using the following code to open a socket on my computer. When I go to my_ip:5000 on my computer the program responds. However, when I use another computer, nothing happens.
HOST = 'my_ip' # Symbolic name meaning the local host
PORT = 8000 # Arbitrary non-privileged port
s = socket... | [
"By setting HOST to 'my_ip', you may listen to a private IP that only resolves to your computer for your computer. The best-known example is 127.0.0.1. Instead, pass an empty string (HOST='') to listen to any requests coming in at the specified port. Make sure to use the same port number, i.e. either 5000 or 8000, ... | [
8,
0
] | [] | [] | [
"network_programming",
"networking",
"python",
"sockets"
] | stackoverflow_0007840525_network_programming_networking_python_sockets.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.