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: Making a PythonCard File Dialog single select? I'm working on a python application and have chosen to build the gui with PythonCard. I have need to have the user select a file to open, and in the context, selecting more than 1 file doesn't make sense. I can successfully create a file dioalog with dialog.fileDialog(self, 'Open Input File', '', '') And I would imagine I need to use the optional style parameter in order to get a sinlge select dialog, but I can't find an example or documentation of what I need to pass to the fifth param in order to get a single select file dialog. A: Try setting the last line to wx.OPEN - that should be it. It seems that PythonCard specifies a dialog's main style as wx.OPEN | wx.MULTIPLE, so overriding it to just open should do the trick. A: Here's a reference for PythonCard dialogs: pythoncard.sourceforge.net/dialogs It provides an explanation of the arguments for each dialog type along with examples.
Making a PythonCard File Dialog single select?
I'm working on a python application and have chosen to build the gui with PythonCard. I have need to have the user select a file to open, and in the context, selecting more than 1 file doesn't make sense. I can successfully create a file dioalog with dialog.fileDialog(self, 'Open Input File', '', '') And I would imagine I need to use the optional style parameter in order to get a sinlge select dialog, but I can't find an example or documentation of what I need to pass to the fifth param in order to get a single select file dialog.
[ "Try setting the last line to wx.OPEN - that should be it. It seems that PythonCard specifies a dialog's main style as wx.OPEN | wx.MULTIPLE, so overriding it to just open should do the trick.\n", "Here's a reference for PythonCard dialogs:\npythoncard.sourceforge.net/dialogs\nIt provides an explanation of the ar...
[ 1, 0 ]
[]
[]
[ "python", "pythoncard" ]
stackoverflow_0002065934_python_pythoncard.txt
Q: ctypes behaving strangely in Python interpreter I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> libc = CDLL("libc.so.6") >>> libc.printf("Test") Test4 >>> int = 55 >>> libc.printf("Test %d", int) Test 557 >>> int = c_int(55) >>> libc.printf("Test %d", int) Test 557 Does anyone know why this happens? A: From the printf(3) man page: Upon successful return, these functions return the number of characters printed (not including the trailing ’\0’ used to end output to strings). The python interpreter is displaying the return code of printf() after you call it. Since you don't have a newline \n at the end of your strings the length is getting printed immediately after the printout. Note that this won't happen in a script, only when you use python interactively. You could hide this with an assignment: ret = libc.printf("Test\n")
ctypes behaving strangely in Python interpreter
I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> libc = CDLL("libc.so.6") >>> libc.printf("Test") Test4 >>> int = 55 >>> libc.printf("Test %d", int) Test 557 >>> int = c_int(55) >>> libc.printf("Test %d", int) Test 557 Does anyone know why this happens?
[ "From the printf(3) man page:\n\nUpon successful return, these functions return the number of characters printed (not including the trailing ’\\0’ used to end output to strings).\n\nThe python interpreter is displaying the return code of printf() after you call it. Since you don't have a newline \\n at the e...
[ 8 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003568867_ctypes_python.txt
Q: How to I determine the default value for a given function parameter at runtime? Using python 2.4, I'm attempting to identify, at runtime, which of an arbitrary function's arguments have default values. Unfortunately, although I can find what the default values are, I can't seem to get a handle on which parameters they correspond to. For example: def foo(a, b, c=5): return a + b + c import inspect inspect.getargspec(foo) # output is: (['a', 'b', 'c'], None, None, (5,)) The output of getargspec is clearer in python 2.6, which returns a named tuple: ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=(5,)) Python obviously has enough information to accomplish the task during execution. How can I get at it? A: Arguments with default values must follow arguments without default values. So if there are any defaults, they must correspond to the arguments at the tail end of args. In your case, args=['a','b','c'], and defaults=(5,). So the default must correspond to c. import inspect def foo(a, b, c=5): return a + b + c def show_defaults(f): args, varargs, varkw, defaults = inspect.getargspec(f) if defaults: for arg, default in zip(args[-len(defaults):], defaults): print('{a} = {d}'.format(a=arg,d=default)) show_defaults(foo) # c = 5 A: From the documentation, it discusses the value for defaults: if this tuple has n elements, they correspond to the last n elements listed in args. In your case defaults contains one value and corresponds to the last element listed in args, which is c.
How to I determine the default value for a given function parameter at runtime?
Using python 2.4, I'm attempting to identify, at runtime, which of an arbitrary function's arguments have default values. Unfortunately, although I can find what the default values are, I can't seem to get a handle on which parameters they correspond to. For example: def foo(a, b, c=5): return a + b + c import inspect inspect.getargspec(foo) # output is: (['a', 'b', 'c'], None, None, (5,)) The output of getargspec is clearer in python 2.6, which returns a named tuple: ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=(5,)) Python obviously has enough information to accomplish the task during execution. How can I get at it?
[ "Arguments with default values must follow arguments without default values.\nSo if there are any defaults, they must correspond to the arguments at the tail end of args.\nIn your case, args=['a','b','c'], and defaults=(5,). So the default must correspond to c.\nimport inspect\n\ndef foo(a, b, c=5):\n return a +...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003568844_python.txt
Q: Calculating e (base of the natural log) to high precision in Python? Is it possible to calculate the value of the mathematical constant, e with high precision (2000+ decimal places) using Python? I am particularly interested in a solution either in or that integrates with NumPy or SciPy. A: You can set the precision you want with the decimal built-in module: from decimal import * getcontext().prec = 40 Decimal(1).exp() This returns: Decimal('2.718281828459045235360287471352662497757') A: This can also be done with sympy using numerical evaluation: import sympy print sympy.N(sympy.E, 100) A: Using a series sum you could calculate it: getcontext().prec = 2000 e = Decimal(0) i = 0 while True: fact = math.factorial(i) e += Decimal(1)/fact i += 1 if fact > 10**2000: break But that's not really necessary, as what Mermoz did agrees just fine with it: >>> e Decimal('2.7182818284590452353602874713526624977572470936999595749669676 277240766303535475945713821785251664274274663919320030599218174135966290 435729003342952605956307381323286279434907632338298807531952510190115738 341879307021540891499348841675092447614606680822648001684774118537423454 424371075390777449920695517027618386062613313845830007520449338265602976 067371132007093287091274437470472306969772093101416928368190255151086574 637721112523897844250569536967707854499699679468644549059879316368892300 987931277361782154249992295763514822082698951936680331825288693984964651 058209392398294887933203625094431173012381970684161403970198376793206832 823764648042953118023287825098194558153017567173613320698112509961818815 930416903515988885193458072738667385894228792284998920868058257492796104 841984443634632449684875602336248270419786232090021609902353043699418491 463140934317381436405462531520961836908887070167683964243781405927145635 490613031072085103837505101157477041718986106873969655212671546889570350 354021234078498193343210681701210056278802351930332247450158539047304199 577770935036604169973297250886876966403555707162268447162560798826517871 341951246652010305921236677194325278675398558944896970964097545918569563 802363701621120477427228364896134225164450781824423529486363721417402388 934412479635743702637552944483379980161254922785092577825620926226483262 779333865664816277251640191059004916449982893150566047258027786318641551 956532442586982946959308019152987211725563475463964479101459040905862984 967912874068705048958586717479854667757573205681288459205413340539220001 137863009455606881667400169842055804033637953764520304024322566135278369 511778838638744396625322498506549958862342818997077332761717839280349465 014345588970719425863987727547109629537415211151368350627526023264847287 039207643100595841166120545297030236472549296669381151373227536450988890 313602057248176585118063036442812314965507047510254465011727211555194866 850800368532281831521960037356252794495158284188294787610852639810') >>> Decimal(1).exp() Decimal('2.7182818284590452353602874713526624977572470936999595749669676 277240766303535475945713821785251664274274663919320030599218174135966290 435729003342952605956307381323286279434907632338298807531952510190115738 341879307021540891499348841675092447614606680822648001684774118537423454 424371075390777449920695517027618386062613313845830007520449338265602976 067371132007093287091274437470472306969772093101416928368190255151086574 637721112523897844250569536967707854499699679468644549059879316368892300 987931277361782154249992295763514822082698951936680331825288693984964651 058209392398294887933203625094431173012381970684161403970198376793206832 823764648042953118023287825098194558153017567173613320698112509961818815 930416903515988885193458072738667385894228792284998920868058257492796104 841984443634632449684875602336248270419786232090021609902353043699418491 463140934317381436405462531520961836908887070167683964243781405927145635 490613031072085103837505101157477041718986106873969655212671546889570350 354021234078498193343210681701210056278802351930332247450158539047304199 577770935036604169973297250886876966403555707162268447162560798826517871 341951246652010305921236677194325278675398558944896970964097545918569563 802363701621120477427228364896134225164450781824423529486363721417402388 934412479635743702637552944483379980161254922785092577825620926226483262 779333865664816277251640191059004916449982893150566047258027786318641551 956532442586982946959308019152987211725563475463964479101459040905862984 967912874068705048958586717479854667757573205681288459205413340539220001 137863009455606881667400169842055804033637953764520304024322566135278369 511778838638744396625322498506549958862342818997077332761717839280349465 014345588970719425863987727547109629537415211151368350627526023264847287 039207643100595841166120545297030236472549296669381151373227536450988890 313602057248176585118063036442812314965507047510254465011727211555194866 850800368532281831521960037356252794495158284188294787610852639814') A: The excellent pure-python library, Mpmath, will certainly do the trick. The sole focus of this library is multi-precision floating-point arithmetic. E.g., Mpath can evaluate e to arbitrary precision: In [2]: from mpmath import * # set the desired precision on the fly In [3]: mp.dps=20; mp.pretty=True In [4]: +e Out[4]: 2.7182818284590452354 # re-set the precision (50 digits) In [5]: mp.dps=50; mp.pretty=True In [6]: +e Out[6]: 2.7182818284590452353602874713526624977572470937 As an aside, Mpmath is also tightly integrated with Matplotlib. A: I would think you could combine the info from these webpages: http://en.wikipedia.org/wiki/Taylor_series This gives you the familiar power series. Since you're working with large factorial numbers you should then probably work with gmpy which implements multi-precision arithmetic. A: Using Sage: N(e, digits=2000)
Calculating e (base of the natural log) to high precision in Python?
Is it possible to calculate the value of the mathematical constant, e with high precision (2000+ decimal places) using Python? I am particularly interested in a solution either in or that integrates with NumPy or SciPy.
[ "You can set the precision you want with the decimal built-in module:\nfrom decimal import *\ngetcontext().prec = 40\nDecimal(1).exp()\n\nThis returns:\nDecimal('2.718281828459045235360287471352662497757')\n\n", "This can also be done with sympy using numerical evaluation:\nimport sympy\n\nprint sympy.N(sympy.E, ...
[ 22, 9, 7, 5, 3, 1 ]
[]
[]
[ "floating_point", "math", "numpy", "python", "scipy" ]
stackoverflow_0003559548_floating_point_math_numpy_python_scipy.txt
Q: A better way to do this? I am writing a python function with the following: class myObj(object): def __init__(self, args): # there is code here def newO(self, name, description): if type(name)==str: self.oname.append(name) self.o.append(description) elif type(name)==list: for n in name: self.oname.append(n) self.o.append(description) However I am led to believe this is not the best way to accomplish this. Whats a better way? I want to be able to call newO with a string or a list. A: Never check type(x) == foo, use isinstance(x, foo) — the former will break if there is a subclass, for instance. You appear to be maintaining parallel lists. If the order matters, it might make more sense to use a list of tuples instead, so self.values.append((name, description)). If the order does not matter, a dictionary would be better: self.values[name] = description (with the assumption that you don't want duplicate names). Single letter variables are a no-no. If you want to call newO with a string or a list, what would the disadvantage be of splitting it into two functions? Perhaps (and I might be wrong) you come from a language with compile-time polymorphism, where a string and a list would be dispatched differently. In reality they are treated as different functions, so in a dynamic language you might split them up like this: def add(self, name, description): ... def add_many(self, name_list, description): for name in name_list: self.add(name, description) It's possible that you don't know a priori whether you have a string or a list, but I hope that's not the case. Is the case of a single string really different from the case of a list of strings? Why not just use a one-element list, to remove the conditional? You could use varargs as well, to make the syntax more bulletproof: def add_names(self, description, *name_list): for name in name_list: self.add(name, description)
A better way to do this?
I am writing a python function with the following: class myObj(object): def __init__(self, args): # there is code here def newO(self, name, description): if type(name)==str: self.oname.append(name) self.o.append(description) elif type(name)==list: for n in name: self.oname.append(n) self.o.append(description) However I am led to believe this is not the best way to accomplish this. Whats a better way? I want to be able to call newO with a string or a list.
[ "\nNever check type(x) == foo, use isinstance(x, foo) — the former will break if there is a subclass, for instance.\nYou appear to be maintaining parallel lists. If the order matters, it might make more sense to use a list of tuples instead, so self.values.append((name, description)). If the order does not matter, ...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003569093_python.txt
Q: Problem with Django/Dajaxice and international characters I am having a problem using Djajaxice with international characters... I have a django template...in that template is the following select: <select name="region" id="id" onchange="Dajaxice.crc.regions('my_callback',{'data':this.value});"> <option value="" selected="selected" ></option> {% for region in regions %} <option value="{{ region.region }}">{{ region.region }}</option> {% endfor %} </select> As you can see on the onchange of the select I am calling the regions function and passing it two parameters. The name of the call back and the selected value Here is the function in the ajax.py file def regions(request, data): CityList = City.objects.filter(region__exact=data) out = "".join(['<option value="%s">%s</option>' % (c.city,c.city) for c in CityList]) return simplejson.dumps(out) dajaxice_functions.register(regions) This works ok and calls, with the relevant data, my JavaScript function in the template with no problems when the name of the region does not have any international characters in it. Say 'Antalya' for example. However when a region such as 'Muğla' comes along, it doesn't work. On close inspection the variable data contains 'Mu%u011Fla' and I can't seem to get it back to what I assume is the necessary format so that Django can access the model data correctly. I have used the magic quotes at the top of the page, I have tried using unescaping it with data.decode('string-escape') and shoving it between utf-8 and back..but nothing I try seems to work... Is this a Dajaxice, Django or python issue...or am I missing something really simple here? I have been at it two days now, trying to figure this out....so many thanks in advance for any help you may be able to provide. Cheers A: Ok, fixed this... So for anyone else using Dajaxice, and using international characters you should change line 10 in the Dajaxice.core.js file from the following: send_data.push('argv='+escape(JSON.stringify(argv))); to this: send_data.push('argv='+encodeURIComponent(JSON.stringify(argv))); and all works well. Phew two days and a few hours of life slipped into the murky waters of code.... ... help us all!
Problem with Django/Dajaxice and international characters
I am having a problem using Djajaxice with international characters... I have a django template...in that template is the following select: <select name="region" id="id" onchange="Dajaxice.crc.regions('my_callback',{'data':this.value});"> <option value="" selected="selected" ></option> {% for region in regions %} <option value="{{ region.region }}">{{ region.region }}</option> {% endfor %} </select> As you can see on the onchange of the select I am calling the regions function and passing it two parameters. The name of the call back and the selected value Here is the function in the ajax.py file def regions(request, data): CityList = City.objects.filter(region__exact=data) out = "".join(['<option value="%s">%s</option>' % (c.city,c.city) for c in CityList]) return simplejson.dumps(out) dajaxice_functions.register(regions) This works ok and calls, with the relevant data, my JavaScript function in the template with no problems when the name of the region does not have any international characters in it. Say 'Antalya' for example. However when a region such as 'Muğla' comes along, it doesn't work. On close inspection the variable data contains 'Mu%u011Fla' and I can't seem to get it back to what I assume is the necessary format so that Django can access the model data correctly. I have used the magic quotes at the top of the page, I have tried using unescaping it with data.decode('string-escape') and shoving it between utf-8 and back..but nothing I try seems to work... Is this a Dajaxice, Django or python issue...or am I missing something really simple here? I have been at it two days now, trying to figure this out....so many thanks in advance for any help you may be able to provide. Cheers
[ "Ok, fixed this...\nSo for anyone else using Dajaxice, and using international characters you should change line 10 in the Dajaxice.core.js file from the following:\nsend_data.push('argv='+escape(JSON.stringify(argv)));\nto this:\nsend_data.push('argv='+encodeURIComponent(JSON.stringify(argv)));\nand all works well...
[ 1 ]
[]
[]
[ "django", "python", "unicode", "unicode_string" ]
stackoverflow_0003567388_django_python_unicode_unicode_string.txt
Q: Querying for not None I have a model with a reference property, eg: class Data(db.Model): x = db.IntegerProperty() class Details(db.Model): data = db.ReferenceProperty(reference_class = Data) The data reference can be None. I want to fetch all Details entities which have valid data, ie for which the reference property is not None. The following works: Details.all().filter('data !=', None).fetch(1000) However, according to the documentation on queries, a != query will actually perform two queries, which seems unnecessary in this case. Is != optimised to only perform one query when used with None? Alternatively, this post mentions that NULL always sorts before valid values. Therefore the following also appears to work: Details.all().filter('data >', None).fetch(1000) Although this would only do one query, using > instead of != makes the intent of what it is doing less obvious. As a third option, I could add an extra field to the model: class Details(db.Model): data = db.ReferenceProperty(reference_class = Data) has_data = db.BooleanProperty() As long as I keep has_data synchronised with data, I could do: Details.all().filter('has_data =', True).fetch(1000) Which way would be best? Thanks. A: I would advise you to use the extra model field. This is more flexible, since it also allows you to query for Details that have no Data references. In addition, queries can only have one inequality filter, so you're better off saving this inequality filter for another property where inequality makes more sense, such as integer properties. To make sure the flag is always updated, you can add a convenience function to Details, like so: class Details(db.Model): data = db.ReferenceProperty(reference_class=Data) has_data = db.BooleanProperty(default=False) def add_data(self, data): """ Adds data""" if not data: return self.has_data = True self.data = data return self.put()
Querying for not None
I have a model with a reference property, eg: class Data(db.Model): x = db.IntegerProperty() class Details(db.Model): data = db.ReferenceProperty(reference_class = Data) The data reference can be None. I want to fetch all Details entities which have valid data, ie for which the reference property is not None. The following works: Details.all().filter('data !=', None).fetch(1000) However, according to the documentation on queries, a != query will actually perform two queries, which seems unnecessary in this case. Is != optimised to only perform one query when used with None? Alternatively, this post mentions that NULL always sorts before valid values. Therefore the following also appears to work: Details.all().filter('data >', None).fetch(1000) Although this would only do one query, using > instead of != makes the intent of what it is doing less obvious. As a third option, I could add an extra field to the model: class Details(db.Model): data = db.ReferenceProperty(reference_class = Data) has_data = db.BooleanProperty() As long as I keep has_data synchronised with data, I could do: Details.all().filter('has_data =', True).fetch(1000) Which way would be best? Thanks.
[ "I would advise you to use the extra model field. This is more flexible, since it also allows you to query for Details that have no Data references. In addition, queries can only have one inequality filter, so you're better off saving this inequality filter for another property where inequality makes more sense, su...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003568553_google_app_engine_python.txt
Q: Parsing HTML with Lxml I need help parsing out some text from a page with lxml. I tried beautifulsoup and the html of the page I am parsing is so broken, it wouldn't work. So I have moved on to lxml, but the docs are a little confusing and I was hoping someone here could help me. Here is the page I am trying to parse, I need to get the text under the "Additional Info" section. Note, that I have a lot of pages on this site like this to parse and each pages html is not always exactly the same (might contain some extra empty "td" tags). Any suggestions as to how to get at that text would be very much appreciated. Thanks for the help. A: import lxml.html as lh import urllib2 def text_tail(node): yield node.text yield node.tail url='http://bit.ly/bf1T12' doc=lh.parse(urllib2.urlopen(url)) for elt in doc.iter('td'): text=elt.text_content() if text.startswith('Additional Info'): blurb=[text for node in elt.itersiblings('td') for subnode in node.iter() for text in text_tail(subnode) if text and text!=u'\xa0'] break print('\n'.join(blurb)) yields For over 65 years, Carl Stirn's Marine has been setting new standards of excellence and service for boating enjoyment. Because we offer quality merchandise, caring, conscientious, sales and service, we have been able to make our customers our good friends. Our 26,000 sq. ft. facility includes a complete parts and accessories department, full service department (Merc. Premier dealer with 2 full time Mercruiser Master Tech's), and new, used, and brokerage sales. Edit: Here is an alternate solution based on Steven D. Majewski's xpath which addresses the OP's comment that the number of tags separating 'Additional Info' from the blurb can be unknown: import lxml.html as lh import urllib2 url='http://bit.ly/bf1T12' doc=lh.parse(urllib2.urlopen(url)) blurb=doc.xpath('//td[child::*[text()="Additional Info"]]/following-sibling::td/text()') blurb=[text for text in blurb if text != u'\xa0'] print('\n'.join(blurb))
Parsing HTML with Lxml
I need help parsing out some text from a page with lxml. I tried beautifulsoup and the html of the page I am parsing is so broken, it wouldn't work. So I have moved on to lxml, but the docs are a little confusing and I was hoping someone here could help me. Here is the page I am trying to parse, I need to get the text under the "Additional Info" section. Note, that I have a lot of pages on this site like this to parse and each pages html is not always exactly the same (might contain some extra empty "td" tags). Any suggestions as to how to get at that text would be very much appreciated. Thanks for the help.
[ "import lxml.html as lh\nimport urllib2\n\ndef text_tail(node):\n yield node.text\n yield node.tail\n\nurl='http://bit.ly/bf1T12'\ndoc=lh.parse(urllib2.urlopen(url))\nfor elt in doc.iter('td'):\n text=elt.text_content()\n if text.startswith('Additional Info'):\n blurb=[text for node in elt.iters...
[ 16 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003569152_html_lxml_parsing_python.txt
Q: Indentation Error python I'm using twisted API and was going through this example. I inserted one print statement print "in getdummydata" with correct indentation. code is as below: from twisted.internet import reactor, defer def getDummyData(x): """ This function is a dummy which simulates a delayed result and returns a Deferred which will fire with that result. Don't try too hard to understand this. """ print "in getdummydata" d = defer.Deferred() # simulate a delayed result by asking the reactor to fire the # Deferred in 2 seconds time with the result x * 3 reactor.callLater(2, d.callback, x * 3) return d def printData(d): """ Data handling function to be added as a callback: handles the data by printing the result """ print d d = getDummyData(3) d.addCallback(printData) # manually set up the end of the process by asking the reactor to # stop itself in 4 seconds time reactor.callLater(4, reactor.stop) # start up the Twisted reactor (event loop handler) manually reactor.run() But when I run the code it gives the indentation error below: File "C:\Python26\programs\twisttest.py", line 9 print "in getdummydata" ^ IndentationError: unexpected indent Please can anyone explain why? A: It looks like the "def" for all your functions have one blank space in front of them. By my eye, "def" falls under the "r" in the "from" above rather than the "f". Perhaps if you remove those spaces the problem will go away. Whitespace is important to Python. A: Check that you aren't mixing spaces and tabs. A: This error can only come from wrong indentation. This means that the docstring before and the print statement have different indentation. Even if they look properly aligned there might be a mix of tabs and spaces. Just redo the indentation or copy the code from your question - SO fixed it by itself ;-)
Indentation Error python
I'm using twisted API and was going through this example. I inserted one print statement print "in getdummydata" with correct indentation. code is as below: from twisted.internet import reactor, defer def getDummyData(x): """ This function is a dummy which simulates a delayed result and returns a Deferred which will fire with that result. Don't try too hard to understand this. """ print "in getdummydata" d = defer.Deferred() # simulate a delayed result by asking the reactor to fire the # Deferred in 2 seconds time with the result x * 3 reactor.callLater(2, d.callback, x * 3) return d def printData(d): """ Data handling function to be added as a callback: handles the data by printing the result """ print d d = getDummyData(3) d.addCallback(printData) # manually set up the end of the process by asking the reactor to # stop itself in 4 seconds time reactor.callLater(4, reactor.stop) # start up the Twisted reactor (event loop handler) manually reactor.run() But when I run the code it gives the indentation error below: File "C:\Python26\programs\twisttest.py", line 9 print "in getdummydata" ^ IndentationError: unexpected indent Please can anyone explain why?
[ "It looks like the \"def\" for all your functions have one blank space in front of them. By my eye, \"def\" falls under the \"r\" in the \"from\" above rather than the \"f\".\nPerhaps if you remove those spaces the problem will go away. Whitespace is important to Python.\n", "Check that you aren't mixing spaces...
[ 1, 0, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003569490_python_twisted.txt
Q: Command Line Arguments in Imported Python Modules This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or the filenames are invalid, so I have to introduce a try/except here. Problem is, someone may want to import my module in the future. But, I don't know what command line arguments that program may require. Also, if an error is thrown when my module access the command-line argument, it seems like it would be better handled by the script that is importing my module. However, my script still needs to be able to cope as a stand-alone if an error is thrown. Is there a smart way around this problem, or is the best solution just to abandon command-line arguments altogether? A: The usual procedure: import sys def main(*files): # your program's logic goes here if __name__ == "__main__": #i.e. run directly try: main(*sys.argv[1:]) except IOError: handle_error() If imported, __name__ will be != "__main__", thus nothing actually happens and the importer can call main(file1, file2). But if this script is the main script (i.e. not imported), it will just do what it does now, only in main. A: Check if your file is being run or if it's imported thus: def myFunction(file): #do stuff to file if __name__ == '__main__': #I have not been imported! try: file = sys.argv[1] except: print "Usage: myFile.py file" sys.exit() myFunction(file)
Command Line Arguments in Imported Python Modules
This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or the filenames are invalid, so I have to introduce a try/except here. Problem is, someone may want to import my module in the future. But, I don't know what command line arguments that program may require. Also, if an error is thrown when my module access the command-line argument, it seems like it would be better handled by the script that is importing my module. However, my script still needs to be able to cope as a stand-alone if an error is thrown. Is there a smart way around this problem, or is the best solution just to abandon command-line arguments altogether?
[ "The usual procedure:\nimport sys\n\ndef main(*files):\n # your program's logic goes here\n\nif __name__ == \"__main__\": #i.e. run directly\n try:\n main(*sys.argv[1:])\n except IOError:\n handle_error()\n\nIf imported, __name__ will be != \"__main__\", thus nothing actually happens and the ...
[ 5, 2 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0003569523_command_line_python.txt
Q: how to replicate parts of code in python into C to execution faster? i have prepared a project in python language ie a TEXT TO SPEECH synthesizer. Which took a total on 1500 lines of code. But there few parts of code due to which it is taking so much time to run the code, i want to replace that parts of code in C/c++ lang so that it runs faster. So i want to know how can i run these parts of code in C++ or improve its speed in any other way?? please suggest, A: You could write them in Cython, it's pretty easy. Alternatively, you can try using numpy, which is already written in C and may have most of the operations you need. A: You have a few options: As Radomir mentioned, Cython might be a good choice: it's essentially a restricted Python with type declarations, automatically translated into C then compiled for execution. If you want to use pure C, you can write a Python extension module using the Python C API. This is a good way to go if you need to manipulate Python data structures in your C code. Using the Python C API, you write in C, but with full access to the Python types and methods. Or, you can write a pure C dll, then invoke it with ctypes. This is a good choice if you don't need any access to Python data structures in your C code. With this technique, your C code only deals with C types, and your Python code has to understand how to use ctypes to get at that C data. A: You can write a Python extension module in C or C++. A: You could also try effect of psyco module to your code's running time (Python 2.6 or earlier) or pypy (python JIT written in subset python). There is also C++ compiler shedskin, Windows is not supported in latest versions though.
how to replicate parts of code in python into C to execution faster?
i have prepared a project in python language ie a TEXT TO SPEECH synthesizer. Which took a total on 1500 lines of code. But there few parts of code due to which it is taking so much time to run the code, i want to replace that parts of code in C/c++ lang so that it runs faster. So i want to know how can i run these parts of code in C++ or improve its speed in any other way?? please suggest,
[ "You could write them in Cython, it's pretty easy.\nAlternatively, you can try using numpy, which is already written in C and may have most of the operations you need.\n", "You have a few options:\nAs Radomir mentioned, Cython might be a good choice: it's essentially a restricted Python with type declarations, au...
[ 5, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003568371_python.txt
Q: FTP Detect if active or passive modes are enabled Specifically for Twisted, I would like to be able to determine whether the server I am connected to supports active or passive mode. See API. If somebody could explain or give example in FTP protocol how you can determine whether the server supports active or passive modes. A: Passive mode is enabled by issuing the PASV command to the server. If it responds with an error code (should be 500 Unknown command) upon issuing that command, then you know that it is not supported. If it responds with a 227 Entering Passive Mode, then you know that passive is supported. Example using command line telnet and FTP commands: % telnet ftp.mozilla.org 21 Trying 63.245.208.138... Connected to dm-ftp01.mozilla.org. Escape character is '^]'. 220- [greeting omitted] USER anonymous 331 Please specify the password. PASS jathanism@ 230- [banner omitted] 230 Login successful. Good command (passive mode is supported): PASV 227 Entering Passive Mode (63,245,208,138,202,53) Bad command (500 error thrown): FART 500 Unknown command.
FTP Detect if active or passive modes are enabled
Specifically for Twisted, I would like to be able to determine whether the server I am connected to supports active or passive mode. See API. If somebody could explain or give example in FTP protocol how you can determine whether the server supports active or passive modes.
[ "Passive mode is enabled by issuing the PASV command to the server. If it responds with an error code (should be 500 Unknown command) upon issuing that command, then you know that it is not supported. If it responds with a 227 Entering Passive Mode, then you know that passive is supported.\nExample using command l...
[ 5 ]
[]
[]
[ "ftp", "python", "twisted" ]
stackoverflow_0003569604_ftp_python_twisted.txt
Q: Overloading List Comprehension Behavior? I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card. I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0", etc. This would allow my users to query the model via simple list comprehensions. For example: for card in cards: print card.name My users, which are not sophisticated Python users, will be interacting with the model in real-time, so it is not practical to have the list index not correspond to a populated card. In other words, if the user removes a card, I need to do something that will indicate that the card is not populated—my first impulse was to set the list item to None. The Bossman likes this scheme, but he's not crazy about the list comprehension above failing if there is a card missing. (Which it currently does.) He's even less supportive of requiring the users to learn enough Python to create list comprehension expressions that will ignore None. My thought was to sub-class the list class, to create a newclass. It would work exactly like a list, except for card in cards would only return members not set to None. Will someone please demonstrate how to overload the list class so that list comprehensions called on the subclass will ignore None? (My Python skills have so far begun to break down when I attempt this.) Can anyone suggest a better approach? A: >>> class MyList(list): ... def __iter__(self): ... return (x for x in list.__iter__(self) if x is not None) ... >>> >>> ml = MyList(["cat", "dog", None, "fox"]) >>> for item in ml: ... print item ... cat dog fox >>> [x for x in ml] ['cat', 'dog', 'fox'] >>> list(ml) ['cat', 'dog', 'fox'] A: You could provide a generator/iterator for this. def installed(cage): for card in cage: if card: yield card cards = ["Adaptec RAID", "Intel RAID", None, "Illudium Q-36 Explosive Space Modulator"] # print list of cards for card in installed(cards): print card A: You can do something like this to get the names if you're using 2.6 or newer: names = [x.name for x in cards if x is not None] That should get close to what you're after I think. A: Perhaps define a function (assuming cards is a global variable?!?): def pcards(): for card in cards: if card: print card.name so your users can simply type pcards() to get a listing.
Overloading List Comprehension Behavior?
I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card. I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0", etc. This would allow my users to query the model via simple list comprehensions. For example: for card in cards: print card.name My users, which are not sophisticated Python users, will be interacting with the model in real-time, so it is not practical to have the list index not correspond to a populated card. In other words, if the user removes a card, I need to do something that will indicate that the card is not populated—my first impulse was to set the list item to None. The Bossman likes this scheme, but he's not crazy about the list comprehension above failing if there is a card missing. (Which it currently does.) He's even less supportive of requiring the users to learn enough Python to create list comprehension expressions that will ignore None. My thought was to sub-class the list class, to create a newclass. It would work exactly like a list, except for card in cards would only return members not set to None. Will someone please demonstrate how to overload the list class so that list comprehensions called on the subclass will ignore None? (My Python skills have so far begun to break down when I attempt this.) Can anyone suggest a better approach?
[ ">>> class MyList(list):\n... def __iter__(self):\n... return (x for x in list.__iter__(self) if x is not None)\n... \n>>> \n>>> ml = MyList([\"cat\", \"dog\", None, \"fox\"])\n>>> for item in ml:\n... print item\n... \ncat\ndog\nfox\n\n>>> [x for x in ml]\n['cat', 'dog', 'fox']\n>>> list(ml)\n['cat...
[ 8, 2, 1, 0 ]
[]
[]
[ "list", "list_comprehension", "overloading", "python" ]
stackoverflow_0003569945_list_list_comprehension_overloading_python.txt
Q: Crash in development server clears datastore? I'm testing my app with the development server. When I manually interrupt a request, it sometimes clears the datastore. This clears even models that are not modified by my request, like users, etc. Any idea why is this? Thanks A: I would recommend using the SQLite stub, instead of the default file-based stub, in your SDK; read all about it in this blog entry by Nick Johnson, who made it. Just pass flag --use_sqlite=true to dev_appserver.py to gain all of SQLite goodness (including, at least in design intent, no datastore wiping on crashes). A: The GAE development data store is only functionally equivalent to the production data store. It's really just a file (or set of files) on your local disk simulating BigTable. So if you abort it in the middle of doing something important, it could end up in an inconsistent state. If you're concerned about this, you can easily back up your local data store and restore it if this happens.
Crash in development server clears datastore?
I'm testing my app with the development server. When I manually interrupt a request, it sometimes clears the datastore. This clears even models that are not modified by my request, like users, etc. Any idea why is this? Thanks
[ "I would recommend using the SQLite stub, instead of the default file-based stub, in your SDK; read all about it in this blog entry by Nick Johnson, who made it. Just pass flag --use_sqlite=true to dev_appserver.py to gain all of SQLite goodness (including, at least in design intent, no datastore wiping on crashes...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003570111_google_app_engine_python.txt
Q: How do I set the transaction isolation level in SQLAlchemy for PostgreSQL? We're using SQLAlchemy declarative base and I have a method that I want isolate the transaction level for. To explain, there are two processes concurrently writing to the database and I must have them execute their logic in a transaction. The default transaction isolation level is READ COMMITTED, but I need to be able to execute a piece of code using SERIALIZABLE isolation levels. How is this done using SQLAlchemy? Right now, I basically have a method in our model, which inherits from SQLAlchemy's declarative base, that essentially needs to be transactionally invoked. from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE class OurClass(SQLAlchemyBaseModel): @classmethod def set_isolation_level(cls, level=ISOLATION_LEVEL_SERIALIZABLE): cls.get_engine().connect().connection.set_isolation_level(level) @classmethod def find_or_create(cls, **kwargs): try: return cls.query().filter_by(**kwargs).one() except NoResultFound: x = cls(**kwargs) x.save() return x I am doing this to invoke this using a transaction isolation level, but it's not doing what I expect. The isolation level still is READ COMMITTED from what I see in the postgres logs. Can someone help identify what I'm doing anythign wrong? I'm using SQLAlchemy 0.5.5 class Foo(OurClass): def insert_this(self, kwarg1=value1): # I am trying to set the isolation level to SERIALIZABLE try: self.set_isolation_level() with Session.begin(): self.find_or_create(kwarg1=value1) except Exception: # if any exception is thrown... print "I caught an expection." print sys.exc_info() finally: # Make the isolation level back to READ COMMITTED self.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED) A: From Michael Bayer, the maintainer of SQLAlchemy: Please use the "isolation_level" argument to create_engine() and use the latest tip of SQLAlchemy until 0.6.4 is released, as there was a psycopg2-specific bug fixed recently regarding isolation level. The approach you have below does not affect the same connection which is later used for querying - you'd instead use a PoolListener that sets up set_isolation_level on all connections as they are created.
How do I set the transaction isolation level in SQLAlchemy for PostgreSQL?
We're using SQLAlchemy declarative base and I have a method that I want isolate the transaction level for. To explain, there are two processes concurrently writing to the database and I must have them execute their logic in a transaction. The default transaction isolation level is READ COMMITTED, but I need to be able to execute a piece of code using SERIALIZABLE isolation levels. How is this done using SQLAlchemy? Right now, I basically have a method in our model, which inherits from SQLAlchemy's declarative base, that essentially needs to be transactionally invoked. from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE class OurClass(SQLAlchemyBaseModel): @classmethod def set_isolation_level(cls, level=ISOLATION_LEVEL_SERIALIZABLE): cls.get_engine().connect().connection.set_isolation_level(level) @classmethod def find_or_create(cls, **kwargs): try: return cls.query().filter_by(**kwargs).one() except NoResultFound: x = cls(**kwargs) x.save() return x I am doing this to invoke this using a transaction isolation level, but it's not doing what I expect. The isolation level still is READ COMMITTED from what I see in the postgres logs. Can someone help identify what I'm doing anythign wrong? I'm using SQLAlchemy 0.5.5 class Foo(OurClass): def insert_this(self, kwarg1=value1): # I am trying to set the isolation level to SERIALIZABLE try: self.set_isolation_level() with Session.begin(): self.find_or_create(kwarg1=value1) except Exception: # if any exception is thrown... print "I caught an expection." print sys.exc_info() finally: # Make the isolation level back to READ COMMITTED self.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED)
[ "From Michael Bayer, the maintainer of SQLAlchemy:\n\nPlease use the \"isolation_level\"\n argument to create_engine()\n and use the latest tip of SQLAlchemy\n until 0.6.4 is released, as there was\n a psycopg2-specific bug fixed recently\n regarding isolation level. \nThe approach you have below does not\n...
[ 15 ]
[ "The isolation level is set within a transaction, e.g.\ntry:\n Session.begin()\n Session.execute('set transaction isolation level serializable')\n self.find_or_create(kwarg1=value1)\nexcept:\n ...\n\nFrom PostgreSQL doc:\n\nIf SET TRANSACTION is executed without a prior START TRANSACTION or BEGIN, it wi...
[ -4 ]
[ "isolation_level", "postgresql", "python", "sqlalchemy", "transactions" ]
stackoverflow_0003518863_isolation_level_postgresql_python_sqlalchemy_transactions.txt
Q: Updating a For Each Loop in Python The below python code takes a list of files and zips them up. The only File Geodatabase (File based database) that I need to have is called "Data" so how can I modify the loop to only include the File based database called Data? To be more specific a File Geodatabase is stored as a system folder that contains binary files that store and manage spatial data. So I need the entire system folder called Data.gdb. Many Thanks #********************************************************************** # Description: # Zips the contents of a folder, file geodatabase or ArcInfo workspace # containing coverages into a zip file. # Parameters: # 0 - Input workspace # 1 - Output zip file. It is assumed that the caller (such as the # script tool) added the .zip extension. # #********************************************************************** # Import modules and create the geoprocessor import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files def zipws(path, zip): isdir = os.path.isdir # Check the contents of the workspace, if it the current # item is a directory, gets its contents and write them to # the zip file, otherwise write the current file item to the # zip file # for each in os.listdir(path): fullname = path + "/" + each if not isdir(fullname): # If the workspace is a file geodatabase, avoid writing out lock # files as they are unnecessary # if not each.endswith('.lock'): # gp.AddMessage("Adding " + each + " ...") # Write out the file and give it a relative archive path # try: zip.write(fullname, each) except IOError: None # Ignore any errors in writing file else: # Branch for sub-directories # for eachfile in os.listdir(fullname): if not isdir(eachfile): if not each.endswith('.lock'): # gp.AddMessage("Adding " + eachfile + " ...") # Write out the file and give it a relative archive path # try: zip.write(fullname + "/" + eachfile, \ os.path.basename(fullname) + "/" + eachfile) except IOError: None # Ignore any errors in writing file if __name__ == '__main__': try: # Get the tool parameter values # inworkspace = sys.argv[1] outfile = sys.argv[2] # Create the zip file for writing compressed data # zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(inworkspace, zip) zip.close() # Set the output derived parameter value for models # gp.setparameterastext(1, outfile) gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + \ str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs) A: The best way to walk over a directory tree is os.walk -- does the file/dir separation for you, and also does the recursion down to subdirectories for you. So: def zipws(path, zip, filename='Data.gdb'): for root, dirs, files in os.walk(path): if filename in files: zip.write(os.path.join(root, filename), os.path.join(os.path.basename(root), filename)) return I'm not certain I've captured the entire logic with which you want to determine the two arguments to zip.write (it's not obvious to me from your code), but, if not, that should be easy to adjust. Also, I'm not sure if you want that return at the end: the effect is zipping only one file named that way, as opposed to zipping all files named that way that may occur in the tree (in their respective subdirectories). If you know there's only one such file, may as well leave the return in (it will just speed things up a bit). If you want all such files when there's more than one, remove the return. Edit: turns out that the "one thing" the OP wants is a directory, not a file. In that case, I would suggest, as the simplest solution: def zipws(path, zip, dirname='Data.gdb'): for root, dirs, files in os.walk(path): if os.path.basename(root) != dirname: continue for filename in files: zip.write(os.path.join(root, filename), os.path.join(dirname, filename)) return again with a similar guess wrt the total mystery of what exactly it is that you want to use for your archive-name. A: Start at this line: zipws(inworkspace, zip) You don't want to use this this function to build the zip file from multiple files. It appears you want to build a zip file with just one member. Replace it with this. try: zip.write(os.path.join('.', 'Data.gdb')) except IOError: pass # Ignore any errors in writing file Throw away the zipws function which you -- apparently -- don't want to use. Read this, it may help: http://docs.python.org/library/zipfile.html
Updating a For Each Loop in Python
The below python code takes a list of files and zips them up. The only File Geodatabase (File based database) that I need to have is called "Data" so how can I modify the loop to only include the File based database called Data? To be more specific a File Geodatabase is stored as a system folder that contains binary files that store and manage spatial data. So I need the entire system folder called Data.gdb. Many Thanks #********************************************************************** # Description: # Zips the contents of a folder, file geodatabase or ArcInfo workspace # containing coverages into a zip file. # Parameters: # 0 - Input workspace # 1 - Output zip file. It is assumed that the caller (such as the # script tool) added the .zip extension. # #********************************************************************** # Import modules and create the geoprocessor import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files def zipws(path, zip): isdir = os.path.isdir # Check the contents of the workspace, if it the current # item is a directory, gets its contents and write them to # the zip file, otherwise write the current file item to the # zip file # for each in os.listdir(path): fullname = path + "/" + each if not isdir(fullname): # If the workspace is a file geodatabase, avoid writing out lock # files as they are unnecessary # if not each.endswith('.lock'): # gp.AddMessage("Adding " + each + " ...") # Write out the file and give it a relative archive path # try: zip.write(fullname, each) except IOError: None # Ignore any errors in writing file else: # Branch for sub-directories # for eachfile in os.listdir(fullname): if not isdir(eachfile): if not each.endswith('.lock'): # gp.AddMessage("Adding " + eachfile + " ...") # Write out the file and give it a relative archive path # try: zip.write(fullname + "/" + eachfile, \ os.path.basename(fullname) + "/" + eachfile) except IOError: None # Ignore any errors in writing file if __name__ == '__main__': try: # Get the tool parameter values # inworkspace = sys.argv[1] outfile = sys.argv[2] # Create the zip file for writing compressed data # zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(inworkspace, zip) zip.close() # Set the output derived parameter value for models # gp.setparameterastext(1, outfile) gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + \ str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs)
[ "The best way to walk over a directory tree is os.walk -- does the file/dir separation for you, and also does the recursion down to subdirectories for you.\nSo:\ndef zipws(path, zip, filename='Data.gdb'):\n for root, dirs, files in os.walk(path):\n if filename in files:\n zip.write(os.path.join(root, filen...
[ 1, 0 ]
[]
[]
[ "arcgis", "gis", "python" ]
stackoverflow_0003569516_arcgis_gis_python.txt
Q: Eclipse PyDev bug when trying to comment out 300+ lines with """docstring""" I don't know if you guys are having the same problem, but when I'm trying to use """ and """ for multi-lines comments in eclipse pydev, it sometimes does not work. Anybody can suggest me some better IDE? Sorry. I will try to make this clearer. It happens every time when I try to comment off looong multi lines like 300 or so. Just type whatever expression such as Bug = "This is a bug", and copy paste this single line to make the whole script 300 lines, now if you want to comment off these 300 lines, normally you would add """ before all these lines, and then add """ in the end. You will find that these lines do not get comment-off aka coloring problem. """ Bug = "This is a bug" Bug = "This is a bug" ... ... Bug = "This is a bug" """ A: I prefer pyDev plugin with Eclipse. But if you feel its problem checkout following: NetBeans python ide check features from their wiki page PyCharm from JetBrains A: I have this problem as well. It has been around for so long, I have become used to it. It tends to happen to me most when I am writing epydoc for functions. I do not think it is an actual bug that affects the code, but it makes typing comments more annoying. A quick fix that I have found is to: Put the cursor before the initial ''', press enter, press ctrl+z. That tends to fix it for me. Hope that helps.
Eclipse PyDev bug when trying to comment out 300+ lines with """docstring"""
I don't know if you guys are having the same problem, but when I'm trying to use """ and """ for multi-lines comments in eclipse pydev, it sometimes does not work. Anybody can suggest me some better IDE? Sorry. I will try to make this clearer. It happens every time when I try to comment off looong multi lines like 300 or so. Just type whatever expression such as Bug = "This is a bug", and copy paste this single line to make the whole script 300 lines, now if you want to comment off these 300 lines, normally you would add """ before all these lines, and then add """ in the end. You will find that these lines do not get comment-off aka coloring problem. """ Bug = "This is a bug" Bug = "This is a bug" ... ... Bug = "This is a bug" """
[ "I prefer pyDev plugin with Eclipse. \nBut if you feel its problem checkout following:\n\nNetBeans python ide check\nfeatures from their wiki page\nPyCharm from JetBrains\n\n", "I have this problem as well. It has been around for so long, I have become used to it. It tends to happen to me most when I am writing e...
[ 1, 0 ]
[]
[]
[ "eclipse", "eclipse_plugin", "multiline", "python", "wxpython" ]
stackoverflow_0003512788_eclipse_eclipse_plugin_multiline_python_wxpython.txt
Q: In wxPython how do you bind a EVT_KEY_DOWN event to the whole window? I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus. NOT WORKING: wx.EVT_KEY_DOWN(self, self.OnKeyDown) WORKING: self.NudgeTxt = wx.TextCtrl(self.panel, size=(40,20), value=str(5)) wx.EVT_KEY_DOWN(self.NudgeTxt, self.OnKeyDown) I am pretty sure I am missing something easy. However am a bit stuck. A: Instead try binding to wx.EVT_CHAR_HOOK e.g.. self.Bind(wx.EVT_CHAR_HOOK, self.onKey) ... def onKey(self, evt): if evt.GetKeyCode() == wx.WXK_DOWN: print "Down key pressed" else: evt.Skip() A: You could use EVT_CHAR_HOOK, self.Bind(wx.EVT_CHAR_HOOK, self.hotkey) def hotkey(self, event): code = event.GetKeyCode() if code == wx.WXK_LEFT: # or whatever... ... or use an accelerator table ac = [(wx.ACCEL_NORMAL, wx.WXK_LEFT, widget.GetId())] tbl = wx.AcceleratorTable(ac) self.SetAcceleratorTable(tbl) you'll need to use a button or widgets' ID in the accelerator table, and pressing the button will trigger the widgets' event handler. If you have no widgets that you'd like their events to be triggered, and would rather some kind of "invisible" widget that has event bindings, then you can do this: ac = [] keys = [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN] for key in keys: _id = wx.NewId() ac.append((wx.ACCEL_NORMAL, key, _id)) self.Bind(wx.EVT_MENU, self.your_function_to_call, id=_id) tbl = wx.AcceleratorTable(ac) self.SetAcceleratorTable(tbl) I iterate over the interested keys to bind to, and create new widgets IDs for them. I then use these IDs to bind menu items to (which accelerator keys trigger) and use these IDs in the accelerator table's list of tuples.
In wxPython how do you bind a EVT_KEY_DOWN event to the whole window?
I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus. NOT WORKING: wx.EVT_KEY_DOWN(self, self.OnKeyDown) WORKING: self.NudgeTxt = wx.TextCtrl(self.panel, size=(40,20), value=str(5)) wx.EVT_KEY_DOWN(self.NudgeTxt, self.OnKeyDown) I am pretty sure I am missing something easy. However am a bit stuck.
[ "Instead try binding to wx.EVT_CHAR_HOOK\ne.g..\nself.Bind(wx.EVT_CHAR_HOOK, self.onKey)\n\n ...\n\ndef onKey(self, evt):\n if evt.GetKeyCode() == wx.WXK_DOWN:\n print \"Down key pressed\"\n else:\n evt.Skip()\n\n", "You could use EVT_CHAR_HOOK,\n self.Bind(wx.EVT_CHAR_HOOK, self.hotkey)\n...
[ 21, 4 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003570254_python_user_interface_wxpython.txt
Q: Python definitions relying on other undefined definitions? I didn't know what to title this, so if anyone wants to edit it: Go ahead. def Function_A() print "We're going to function B!" Function_B() def Function_B() print "We made it!' This is a beginner question, but the solution hasn't occurred to me as I've been spoiled by compiled languages. You can see here, Function_A leads to Function_B. At runtime, Function_B will not be defined when Function_A is called, so it can't happen. How do I get around this? A: In Python, functions do not need to be defined in order of use. As long as it's defined somewhere before the function is called at runtime it should work. This is because Function_A() is not actually evaluated until it's called, which in this is case is at the bottom of the this test.py file at which point Function_B() is already defined. test.py: def Function_A(): print "We're going to function B!" Function_B() def Function_B(): print "We made it!!" Function_A() Example run: mahmoud:~$ python test.py We're going to function B! We made it!! A: Function names are resolved at runtime. So when Function_A calls Function_B, the name "Function_B" is not looked up until Function_A actually makes the call. So everything works fine as long as Function_B is defined by the time Function_A is actually called. This, for example, would not work: def Function_A(): print "Function A entered" Function_B() Function_A() def Function_B(): print "Function B entered" ... because the call to Function_A is before Function_B's definition. A: As written, both functions are being defined, but neither of the functions is called. If you call Function_A before the definition of Function_B you will get an error: def Function_A(): print "We're going to function B!" Function_B() Function_A() # will fail def Function_B(): print "We made it!" If you call Function_A after the definition of Function_B everything will work fine: def Function_A(): print "We're going to function B!" Function_B() def Function_B(): print "We made it!" Function_A() # will succeed The interpreter executes the file from beginning to end, defining and calling functions as they come along. The function bodies will only be closely looked at when the function is called. When executing Function_A and reaching its second line, the interpreter will look in the global namespace to find something called Function_B. In the first example there hasn't been anything defined yet, while in the second example there is a Function_B that can be called. A: As others have said, Function_B is looked up when Function_A is called. Here is an example that shows Function_B can even be redefined and still work properly. def Function_A(): print "We're going to function B!" Function_B() # Function_A() # This would cause a NameError def Function_B(): print "We made it!" Function_A() def Function_B(): print "Function B has been redefined!" Function_A() output: We're going to function B! We made it! We're going to function B! Function B has been redefined! A: You have two problems I can see. One, you need colons after def. Two: You've mixed up the open / close quotes on your final string. def Function_A(): print "We're going to function B!" Function_B() def Function_B(): print "We made it!" Otherwise, this code works as posted. I have no problems running these functions.
Python definitions relying on other undefined definitions?
I didn't know what to title this, so if anyone wants to edit it: Go ahead. def Function_A() print "We're going to function B!" Function_B() def Function_B() print "We made it!' This is a beginner question, but the solution hasn't occurred to me as I've been spoiled by compiled languages. You can see here, Function_A leads to Function_B. At runtime, Function_B will not be defined when Function_A is called, so it can't happen. How do I get around this?
[ "In Python, functions do not need to be defined in order of use. As long as it's defined somewhere before the function is called at runtime it should work. This is because Function_A() is not actually evaluated until it's called, which in this is case is at the bottom of the this test.py file at which point Functio...
[ 5, 2, 2, 2, 1 ]
[]
[]
[ "definition", "function", "python" ]
stackoverflow_0003570532_definition_function_python.txt
Q: Something quite tricky in a python exercise I wrote a python script test1.py in which I import a module called test2, then in test2, I did import test1; when I run test1, it works correctly; to my very big suprise, when I try to run test2, it outputs exactlly the same result as I run test1, despite these two files have very very different contents. but when I remove import test2, they work differently. So why this happened? import test2 class test1(): # do this Well, test1 works nicely up to here! import test1 class test2(): # do some other sharply different stuff test2 does work exactly the same as what test1 does! BUT, when import test1 is removed from class2, class2 will work fine. WHY??? thanks!!! A: This is why.
Something quite tricky in a python exercise
I wrote a python script test1.py in which I import a module called test2, then in test2, I did import test1; when I run test1, it works correctly; to my very big suprise, when I try to run test2, it outputs exactlly the same result as I run test1, despite these two files have very very different contents. but when I remove import test2, they work differently. So why this happened? import test2 class test1(): # do this Well, test1 works nicely up to here! import test1 class test2(): # do some other sharply different stuff test2 does work exactly the same as what test1 does! BUT, when import test1 is removed from class2, class2 will work fine. WHY??? thanks!!!
[ "This is why.\n" ]
[ 2 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003570726_import_module_python.txt
Q: Rotate an image about a specific pixel in python How can I rotate an image about a specific pixel in Python? I am trying to de-rotate a set of images of the night sky. Since the stars rotate around Polaris, I could define Polaris as the center of rotation and rotate each image to line up the stars. A: In phadej's answer the transformation between the old and new coordinates of a point on the image is an affine transformation. PIL (Python Imaging Library) has an image method called transform which can perform an affine transformation of an image. The documentation for transform is near the bottom of this page. A: With a little math: if each image's pixel position is vector a, and position of Polaris is p, then new position new_p is new_p = a + R * (a-p) where R is Rotation matrix. There will be problem, as new_p is probably not an integer valued position-vector. You can do it backwards. For each pixel of rotated image apply the inverse of above transform, than you will get pixel from original image. As it could be not integer also, sample the neighbor pixels like in wu-pixels (the amount of dot spread around can be used as the sampling weight).
Rotate an image about a specific pixel in python
How can I rotate an image about a specific pixel in Python? I am trying to de-rotate a set of images of the night sky. Since the stars rotate around Polaris, I could define Polaris as the center of rotation and rotate each image to line up the stars.
[ "In phadej's answer the transformation between the old and new coordinates of a point on the image is an affine transformation.\nPIL (Python Imaging Library) has an image method called transform which can perform an affine transformation of an image.\nThe documentation for transform is near the bottom of this page....
[ 2, 0 ]
[]
[]
[ "astronomy", "image", "image_rotation", "python" ]
stackoverflow_0003570782_astronomy_image_image_rotation_python.txt
Q: Need some help with PyQt and QGridLayout I'm having an annoyingly stubborn problem here, and I would appreciate it if anyone could give me some insight into what I'm doing wrong. I have a PyQt app that is supposed to display a table of numbers. So, naturally, I am using QTableWidget. Right now, it's extremely simple: all I do is create a window with a Table Widget and a button and display it. I am not populating the table at all yet. I want the table to be able to resize automatically with the window, and eventually I am going to add other widgets to this form, so I am using QGridLayout. And when I preview the form in Qt Designer, it looks and behaves correctly. The Table takes up all of the form except for the space used by the button, and when I resize the window they both resize correctly along with it. But when I try to run the generated Python code, it's all screwed up. The Table Widget and the button are both scrunched up together, on top of each other, in the top left corner of the window. I created the .ui file using Qt Designer 4, and generated the Python code using pyuic4. I haven't edited either of the files manually at all. So I assume that there are no basic syntax errors in either. My guess is that I am somehow misunderstanding the relationship between the widgets, the window and the layout manager. But I cannot figure out how. Here is the code for my .ui file: <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>TableWindow</class> <widget class="QWidget" name="TableWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>586</width> <height>383</height> </rect> </property> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="windowTitle"> <string/> </property> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="0"> <widget class="QTableWidget" name="tableWidget"/> </item> <item row="1" column="0"> <widget class="QPushButton" name="btnSave"> <property name="text"> <string>Save to File</string> </property> </widget> </item> </layout> </widget> <resources/> <connections/> </ui> And here is the Python code generated from the .ui file by pyuic4: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_table_window.ui' # # Created: Mon Apr 19 23:47:43 2010 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_TableWindow(object): def setupUi(self, TableWindow): TableWindow.setObjectName("TableWindow") TableWindow.resize(586, 383) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(TableWindow.sizePolicy().hasHeightForWidth()) TableWindow.setSizePolicy(sizePolicy) self.gridLayout = QtGui.QGridLayout(TableWindow) self.gridLayout.setObjectName("gridLayout") self.tableWidget = QtGui.QTableWidget(TableWindow) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(0) self.tableWidget.setRowCount(0) self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1) self.btnSave = QtGui.QPushButton(TableWindow) self.btnSave.setObjectName("btnSave") self.gridLayout.addWidget(self.btnSave, 1, 0, 1, 1) self.retranslateUi(TableWindow) QtCore.QMetaObject.connectSlotsByName(TableWindow) def retranslateUi(self, TableWindow): self.btnSave.setText(QtGui.QApplication.translate("TableWindow", "Save to File", None, QtGui.QApplication.UnicodeUTF8)) Can anyone see what I might be doing wrong? A: What you have works perfectly, so it must be in your setup. The following should work for you: from PyQt4 import QtCore, QtGui from Ui_TableWindow import Ui_TableWindow # adjust accordingly class TableWindow(QtGui.QWidget, Ui_TableWindow): def __init__(self, parent): QtGui.QWidget.__init__(self, parent) self.setupUi(self) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = TableWindow(None) window.show() app.exec_() A: I would like to know the answer to this question also. "It must be in your setup" is zero help. SOLVED! Addendum: The tasks and statements below are legitimate. However they apply if you have created your dialog/UI as a dialog and/or widget. That in itself is where the probelem lies For the proper layout to work and give you the desired form layout, you must start your ui project as a "MainWindow" app. Not the Dialog with buttons or Widget app. The MainWindow template comes prepared with a "centralWidget", thus giving your layout option. So if you did not, below will help you change that It does seem pyuic4 falls short on this one aspect. A way to give the over all ui a wrapper to hook into the main window is to finalize all your widgets by setting them into an over-all layout. QGridLayout, QVerticalLayout, it doesn't matter, just so that all the contents of the UI are "handled" by a top-level layout. Do NOT apply a layout to the form. Note: You may want to temporarily just to be able to use the "preview" in the QT Designer. However this is where the py conversion is broken. You will need to break/remove the form's layout before saving/converting Once you save the .ui file and convert it to your .py file using pyuic4, you will need to add/change a line or two from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(625, 448) <create a "holder" central widget> self.widget = QtGui.QWidget() <set the overall QLayout with the widget as the> <parent rather than the "Dialog" that the> <generated code gives you> self.gridLayout_2 = QtGui.QGridLayout(self.widget) self.gridLayout_2.setObjectName("gridLayout_2") .... .... Now in the normal modules you will call this UI objects.setCentralWidget() function to set that widget if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() < set the widget inside the form to it's cetral widget > myapp.setCentralWidget( myapp.ui.widget ) myapp.show() sys.argv[1] = myapp.unUNCPath( sys.argv[1] ) os.chdir( sys.argv[1] ) myapp.setRootDir( sys.argv[1] ) myapp.processDirectory() sys.exit(app.exec_())
Need some help with PyQt and QGridLayout
I'm having an annoyingly stubborn problem here, and I would appreciate it if anyone could give me some insight into what I'm doing wrong. I have a PyQt app that is supposed to display a table of numbers. So, naturally, I am using QTableWidget. Right now, it's extremely simple: all I do is create a window with a Table Widget and a button and display it. I am not populating the table at all yet. I want the table to be able to resize automatically with the window, and eventually I am going to add other widgets to this form, so I am using QGridLayout. And when I preview the form in Qt Designer, it looks and behaves correctly. The Table takes up all of the form except for the space used by the button, and when I resize the window they both resize correctly along with it. But when I try to run the generated Python code, it's all screwed up. The Table Widget and the button are both scrunched up together, on top of each other, in the top left corner of the window. I created the .ui file using Qt Designer 4, and generated the Python code using pyuic4. I haven't edited either of the files manually at all. So I assume that there are no basic syntax errors in either. My guess is that I am somehow misunderstanding the relationship between the widgets, the window and the layout manager. But I cannot figure out how. Here is the code for my .ui file: <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>TableWindow</class> <widget class="QWidget" name="TableWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>586</width> <height>383</height> </rect> </property> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="windowTitle"> <string/> </property> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="0"> <widget class="QTableWidget" name="tableWidget"/> </item> <item row="1" column="0"> <widget class="QPushButton" name="btnSave"> <property name="text"> <string>Save to File</string> </property> </widget> </item> </layout> </widget> <resources/> <connections/> </ui> And here is the Python code generated from the .ui file by pyuic4: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_table_window.ui' # # Created: Mon Apr 19 23:47:43 2010 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_TableWindow(object): def setupUi(self, TableWindow): TableWindow.setObjectName("TableWindow") TableWindow.resize(586, 383) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(TableWindow.sizePolicy().hasHeightForWidth()) TableWindow.setSizePolicy(sizePolicy) self.gridLayout = QtGui.QGridLayout(TableWindow) self.gridLayout.setObjectName("gridLayout") self.tableWidget = QtGui.QTableWidget(TableWindow) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(0) self.tableWidget.setRowCount(0) self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1) self.btnSave = QtGui.QPushButton(TableWindow) self.btnSave.setObjectName("btnSave") self.gridLayout.addWidget(self.btnSave, 1, 0, 1, 1) self.retranslateUi(TableWindow) QtCore.QMetaObject.connectSlotsByName(TableWindow) def retranslateUi(self, TableWindow): self.btnSave.setText(QtGui.QApplication.translate("TableWindow", "Save to File", None, QtGui.QApplication.UnicodeUTF8)) Can anyone see what I might be doing wrong?
[ "What you have works perfectly, so it must be in your setup. The following should work for you:\nfrom PyQt4 import QtCore, QtGui\nfrom Ui_TableWindow import Ui_TableWindow # adjust accordingly\n\nclass TableWindow(QtGui.QWidget, Ui_TableWindow):\n def __init__(self, parent):\n QtGui.QWidget.__init__(self...
[ 1, 1 ]
[]
[]
[ "designer", "pyqt", "python", "qt_designer" ]
stackoverflow_0002676369_designer_pyqt_python_qt_designer.txt
Q: show linux process [Python] Guy how i can read all process work in my computer and print it i want process read then print ? A: one of the possible ways is to parse the output of some specialized system process "viewer" application like: import commands cmd = 'ps ax' for line in commands.getoutput(cmd).splitlines(): # process the line
show linux process [Python]
Guy how i can read all process work in my computer and print it i want process read then print ?
[ "one of the possible ways is to parse the output of some specialized system process \"viewer\" application\nlike:\nimport commands\ncmd = 'ps ax'\nfor line in commands.getoutput(cmd).splitlines():\n # process the line\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003571194_python.txt
Q: UnicodeDecodeError when passing GET data in Python/AppEngine This feels like a really basic question, but I haven't been able to find an answer. I would like to read data from an url, for example GET data from a querystring. I am using the webapp framework in Python. I tried the following code, but since I've a total beginner at Python/appengine, I've certainly done something wrong. class MainPage(webapp.RequestHandler): def get(self): self.response.out.write(self.request.get('data')) application = webapp.WSGIApplication([('/', MainPage),('/search', Search),('/next', Next)],debug=False) def main(): run_wsgi_app(application) if __name__ == "__main__": main() When testing in my test environment, the URL http://localhost/?data=test just returns this error message below. Without the querystring, it just displays a blank page as expected. UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position 40: ordinal not in range(128) What am I doing wrong and what should I do instead? A: You try to e.g. print an ASCII coded string actually containing data of a different charset. This can happen e.g. with Latin-1 encoded data. Try converting your input to unicode using unicoded = unicode(non_unicode_string, source_encoding) where source_encoding is something like 'cp1252', 'iso-8859-1' etc., and sending this to output. Have a look at this HOWTO. For a list of encodings supported by Python, see this A: Check out this blog post on how to do unicode right in Python. In a nutshell, you're trying to decode a byte string (implicitly) as ASCII, and it contains a byte that isn't valid in that codec. Your string is probably in UTF-8.
UnicodeDecodeError when passing GET data in Python/AppEngine
This feels like a really basic question, but I haven't been able to find an answer. I would like to read data from an url, for example GET data from a querystring. I am using the webapp framework in Python. I tried the following code, but since I've a total beginner at Python/appengine, I've certainly done something wrong. class MainPage(webapp.RequestHandler): def get(self): self.response.out.write(self.request.get('data')) application = webapp.WSGIApplication([('/', MainPage),('/search', Search),('/next', Next)],debug=False) def main(): run_wsgi_app(application) if __name__ == "__main__": main() When testing in my test environment, the URL http://localhost/?data=test just returns this error message below. Without the querystring, it just displays a blank page as expected. UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position 40: ordinal not in range(128) What am I doing wrong and what should I do instead?
[ "You try to e.g. print an ASCII coded string actually containing data of a different charset. This can happen e.g. with Latin-1 encoded data. Try converting your input to unicode using\nunicoded = unicode(non_unicode_string, source_encoding)\n\nwhere source_encoding is something like 'cp1252', 'iso-8859-1' etc., an...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003570434_google_app_engine_python_web_applications.txt
Q: Customizing matplotlib image display to add copy/paste I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks! A: If you're using the wx backend, FigureCanvasWxAgg has a Copy_to_Clipboard method you can use. You could bind the CTRL+C key event to call this method. For an example, see this sample code. A: import matplotlib import matplotlib.pyplot as plt if not globals().has_key('__figure'): __figure = matplotlib.pyplot.figure def on_key(event): print event if event.key=='c': #print event.canvas.__dict__#.Copy_to_Clipboard(event=event) # print event.canvas._tkphoto.__dict__ plt.savefig("/tmp/fig.png") def my_figure(): fig = __figure() fig.canvas.mpl_connect('key_press_event',on_key) return fig matplotlib.pyplot.figure = my_figure This works for tk backend, but i have no clue how to copy an image to a clipboard. For text, i can use xclip, but images dont work! And for some reason the wx backend doesnt work too well on ubuntu...
Customizing matplotlib image display to add copy/paste
I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks!
[ "If you're using the wx backend, FigureCanvasWxAgg has a Copy_to_Clipboard method you can use. You could bind the CTRL+C key event to call this method. For an example, see this sample code.\n", "import matplotlib\nimport matplotlib.pyplot as plt\nif not globals().has_key('__figure'):\n __figure = matplotlib...
[ 5, 2 ]
[]
[]
[ "copy", "excel", "matplotlib", "paste", "python" ]
stackoverflow_0003571117_copy_excel_matplotlib_paste_python.txt
Q: Psycopg2 under osx works on commandline but fails in Aptana studio I have been developing under Python/Snowleopard happily for the part 6 months. I just upgraded Python to 2.6.5 and a whole bunch of libraries, including psycopg2 and Turbogears. I can start up tg-admin and run some queries with no problems. Similarly, I can run my web site from the command line with no problems. However, if I try to start my application under Aptana Studio, I get the following exception while trying to import psychopg2: ('dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID\n Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so\n Expected in: flat namespace\n in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so',) This occurs after running the following code: try: import psycopg2 as psycopg except ImportError as ex: print "import failed :-( xxxxxxxx = " print ex.args I have confirmed that the same version of python is being run as follows: import sys print "python version: ", sys.version_info Does anyone have any ideas? I've seem some references alluding to this being a 64-bit issue. - dave A: Problem solved (to a point). I was running 64 bit python from Aptana Studio and 32 bit python on the command line. By forcing Aptana to use 32 bit python, the libraries work again and all is happy.
Psycopg2 under osx works on commandline but fails in Aptana studio
I have been developing under Python/Snowleopard happily for the part 6 months. I just upgraded Python to 2.6.5 and a whole bunch of libraries, including psycopg2 and Turbogears. I can start up tg-admin and run some queries with no problems. Similarly, I can run my web site from the command line with no problems. However, if I try to start my application under Aptana Studio, I get the following exception while trying to import psychopg2: ('dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID\n Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so\n Expected in: flat namespace\n in /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/psycopg2/_psycopg.so',) This occurs after running the following code: try: import psycopg2 as psycopg except ImportError as ex: print "import failed :-( xxxxxxxx = " print ex.args I have confirmed that the same version of python is being run as follows: import sys print "python version: ", sys.version_info Does anyone have any ideas? I've seem some references alluding to this being a 64-bit issue. - dave
[ "Problem solved (to a point). I was running 64 bit python from Aptana Studio and 32 bit python on the command line. By forcing Aptana to use 32 bit python, the libraries work again and all is happy.\n" ]
[ 0 ]
[]
[]
[ "psycopg", "python", "turbogears" ]
stackoverflow_0003571495_psycopg_python_turbogears.txt
Q: Django and dynamically generated images I have a view in my Django application that automatically creates an image using the PIL, stores it in the Nginx media server, and returns a html template with a img tag pointing to it's url. This works fine, but I notice an issue. For every 5 times I access this view, in 1 of them the image doesn't render. I did some investigation and I found something interesting, this is the HTTP response header when the image renders properly: Accept-Ranges:bytes Connection:keep-alive Content-Length:14966 Content-Type:image/jpeg Date:Wed, 18 Aug 2010 15:36:16 GMT Last-Modified:Wed, 18 Aug 2010 15:36:16 GMT Server:nginx/0.5.33 and this is the header when the image doesn't load: Accept-Ranges:bytes Connection:keep-alive Content-Length:0 Content-Type:image/jpeg Date:Wed, 18 Aug 2010 15:37:47 GMT Last-Modified:Wed, 18 Aug 2010 15:37:46 GMT Server:nginx/0.5.33 Notice the Content-Lenth equals to zero. What could have caused this? Any ideas on how could I further debug this problem? Edit: When the view is called, it calls this "draw" method of the model. This is basically what it does (I removed the bulk of the code for clarity): def draw(self): # Open/Creates a file if not self.image: (fd, self.image) = tempfile.mkstemp(dir=settings.IMAGE_PATH, suffix=".jpeg") fd2 = os.fdopen(fd, "wb") else: fd2 = open(os.path.join(settings.SITE_ROOT, self.image), "wb") # Creates a PIL Image im = Image.new(mode, (width, height)) # Do some drawing ..... # Saves im = im.resize((self.get_size_site(self.width), self.get_size_site(self.height))) im.save(fd2, "JPEG") fd2.close() Edit2: This is website: http://xxxcnn7979.hospedagemdesites.ws:8000/cartao/99/ if you keep hitting F5 the image on the right will eventually render. A: We had this problem a while back when writing HTML pages out to disk. The solution for us was to write to a temporary file and then atomically rename the file. You might also want to consider using fsync. The full source is available here: staticgenerator/__init__.py, but here are the useful bits: import os import stat import tempfile ... f, tmpname = tempfile.mkstemp(dir=directory) os.write(f, content) # See http://docs.python.org/library/os.html#os.fsync f.flush() os.fsync(f.fileno()) os.close(f) # Ensure it is webserver readable os.chmod(tmpname, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) # Rename is an atomic operation in POSIX # See: http://docs.python.org/library/os.html#os.rename os.rename(tmpname, fn)
Django and dynamically generated images
I have a view in my Django application that automatically creates an image using the PIL, stores it in the Nginx media server, and returns a html template with a img tag pointing to it's url. This works fine, but I notice an issue. For every 5 times I access this view, in 1 of them the image doesn't render. I did some investigation and I found something interesting, this is the HTTP response header when the image renders properly: Accept-Ranges:bytes Connection:keep-alive Content-Length:14966 Content-Type:image/jpeg Date:Wed, 18 Aug 2010 15:36:16 GMT Last-Modified:Wed, 18 Aug 2010 15:36:16 GMT Server:nginx/0.5.33 and this is the header when the image doesn't load: Accept-Ranges:bytes Connection:keep-alive Content-Length:0 Content-Type:image/jpeg Date:Wed, 18 Aug 2010 15:37:47 GMT Last-Modified:Wed, 18 Aug 2010 15:37:46 GMT Server:nginx/0.5.33 Notice the Content-Lenth equals to zero. What could have caused this? Any ideas on how could I further debug this problem? Edit: When the view is called, it calls this "draw" method of the model. This is basically what it does (I removed the bulk of the code for clarity): def draw(self): # Open/Creates a file if not self.image: (fd, self.image) = tempfile.mkstemp(dir=settings.IMAGE_PATH, suffix=".jpeg") fd2 = os.fdopen(fd, "wb") else: fd2 = open(os.path.join(settings.SITE_ROOT, self.image), "wb") # Creates a PIL Image im = Image.new(mode, (width, height)) # Do some drawing ..... # Saves im = im.resize((self.get_size_site(self.width), self.get_size_site(self.height))) im.save(fd2, "JPEG") fd2.close() Edit2: This is website: http://xxxcnn7979.hospedagemdesites.ws:8000/cartao/99/ if you keep hitting F5 the image on the right will eventually render.
[ "We had this problem a while back when writing HTML pages out to disk. The solution for us was to write to a temporary file and then atomically rename the file. You might also want to consider using fsync.\nThe full source is available here: staticgenerator/__init__.py, but here are the useful bits:\nimport os\nimp...
[ 5 ]
[]
[]
[ "django", "http_headers", "nginx", "python", "python_imaging_library" ]
stackoverflow_0003514569_django_http_headers_nginx_python_python_imaging_library.txt
Q: Getting Django to work with Eclipse I'm new to python and django but wanted to start following some tutorials. I installed python, then django, and then the pydev plugin for eclipse. I created a new django project and tried running it. In eclipse I set up a run configuration for manage.py with argument runserver and it said "Validating Models" but never said anything else. I tried running via command line also but got some errors that I didn't see in eclipse: C:\Users\JP\workspace\mysite\src\mysite>python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x02851E30> Traceback (most recent call last): File "c:\Python27\lib\site-packages\django\core\management\commands\runserver. py", line 48, in inner_run self.validate(display_num_errors=True) File "c:\Python27\lib\site-packages\django\core\management\base.py", line 245, in validate num_errors = get_validation_errors(s, app) File "c:\Python27\lib\site-packages\django\core\management\validation.py", lin e 22, in get_validation_errors from django.db import models, connection File "c:\Python27\lib\site-packages\django\db\__init__.py", line 75, in <modul e> connection = connections[DEFAULT_DB_ALIAS] File "c:\Python27\lib\site-packages\django\db\utils.py", line 91, in __getitem __ backend = load_backend(db['ENGINE']) File "c:\Python27\lib\site-packages\django\db\utils.py", line 32, in load_back end return import_module('.base', backend_name) File "c:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im port_module __import__(name) File "c:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 14 , in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No mo dule named MySQLdb I assume it has something to do with my sql setup, but I'm not sure since it's a blank project and I haven't written any code yet. I'm more concerned with why nothing showed up in eclipse. A: I'm just starting myself. Apparently there's a MySQLdb plugin (sorry if that's not the right term) that you need to use in addition to a standard MySQL install. This is so Python can communicate with MySQL. A: It sounds like that you need to include the module in Eclipse System PYTHONPATH. Go to Windows -> Preference -> Pydev -> Interpreter - Python. After Select your desired python interpreters (if you have a virtual env), include your MySQL egg and all your other dependencies in your library. A: It seems you don't have mysql installed. If you're only trying out django, you could use sqlite which ships with python. You can change the db backend in your settings.py file.
Getting Django to work with Eclipse
I'm new to python and django but wanted to start following some tutorials. I installed python, then django, and then the pydev plugin for eclipse. I created a new django project and tried running it. In eclipse I set up a run configuration for manage.py with argument runserver and it said "Validating Models" but never said anything else. I tried running via command line also but got some errors that I didn't see in eclipse: C:\Users\JP\workspace\mysite\src\mysite>python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x02851E30> Traceback (most recent call last): File "c:\Python27\lib\site-packages\django\core\management\commands\runserver. py", line 48, in inner_run self.validate(display_num_errors=True) File "c:\Python27\lib\site-packages\django\core\management\base.py", line 245, in validate num_errors = get_validation_errors(s, app) File "c:\Python27\lib\site-packages\django\core\management\validation.py", lin e 22, in get_validation_errors from django.db import models, connection File "c:\Python27\lib\site-packages\django\db\__init__.py", line 75, in <modul e> connection = connections[DEFAULT_DB_ALIAS] File "c:\Python27\lib\site-packages\django\db\utils.py", line 91, in __getitem __ backend = load_backend(db['ENGINE']) File "c:\Python27\lib\site-packages\django\db\utils.py", line 32, in load_back end return import_module('.base', backend_name) File "c:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im port_module __import__(name) File "c:\Python27\lib\site-packages\django\db\backends\mysql\base.py", line 14 , in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No mo dule named MySQLdb I assume it has something to do with my sql setup, but I'm not sure since it's a blank project and I haven't written any code yet. I'm more concerned with why nothing showed up in eclipse.
[ "I'm just starting myself. Apparently there's a MySQLdb plugin (sorry if that's not the right term) that you need to use in addition to a standard MySQL install. This is so Python can communicate with MySQL.\n", "It sounds like that you need to include the module in Eclipse System PYTHONPATH.\nGo to Windows -> ...
[ 1, 1, 0 ]
[]
[]
[ "django", "eclipse", "pydev", "python" ]
stackoverflow_0003398631_django_eclipse_pydev_python.txt
Q: Does Windows 7 Automatically Use Multiple Processors for Python 3 Code? I have windows 7 and I wrote a python program that loops ("for loops", i.e., "for key in dict") over multiple databases, checks for various conditions (e.g., if x in dict, y += 1) and then tallies the results. I didn't do anything to parralelize the proceesing. I have 8 CPU cores on my computer. When I start Windows task manager while running the program, it shows substantial activity on all 8 cores. Is windows executing the for loops in parralel on multiple proceesors without me doing anything? The code executes fast. A: No. The C implementation of Python only allows one thread to interpret one bytecode at a time. The only way to take advantage of multiple cores is with multiple threads or multiple processes. It is completely possible that you will see multiple core activity related to your script however. Let's say you open several files for reading or writing. The OS will buffer the read / write calls that Python is making (on behalf of your script) and will return control to the next statement before that statement is complete in some cases. This is the OS rather than Python making that optimization however. The Java implementation of Python will do what ever the native version of Java will do on your OS. Here is a more complete discussion of the same topic. A: The answer to your question is "no" -- whatever's happening on 7 of your 8 cores, it's Windows doing its things (services and whatnot) "in the background". When you do want to parallelize over multiple cores, you'll need to use Python standard library's multiprocessing module (there are other ways, but none quite as convenient as simple as this).
Does Windows 7 Automatically Use Multiple Processors for Python 3 Code?
I have windows 7 and I wrote a python program that loops ("for loops", i.e., "for key in dict") over multiple databases, checks for various conditions (e.g., if x in dict, y += 1) and then tallies the results. I didn't do anything to parralelize the proceesing. I have 8 CPU cores on my computer. When I start Windows task manager while running the program, it shows substantial activity on all 8 cores. Is windows executing the for loops in parralel on multiple proceesors without me doing anything? The code executes fast.
[ "No. The C implementation of Python only allows one thread to interpret one bytecode at a time. The only way to take advantage of multiple cores is with multiple threads or multiple processes. \nIt is completely possible that you will see multiple core activity related to your script however. Let's say you open sev...
[ 4, 2 ]
[]
[]
[ "parallel_processing", "python", "windows_7" ]
stackoverflow_0003571906_parallel_processing_python_windows_7.txt
Q: Python code flow does not work as expected? I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a slight problem. Firstly, here is my code flow: Enter a sentence as input -this is called trigger string, is assigned to a variable- Get longest word in trigger string Search all Project Gutenberg database for sentences that contain this word -regardless of uppercase lowercase- Return the longest sentence that has the word I spoke about in step 3 Append the sentence in Step 1 and Step4 together Assign the sentence in Step 4 as the new 'trigger' sentence and repeat the process. Note that I have to get the longest word in second sentence and continue like that and so on- So far, I have been able to do this only once. When I try to keep this to continue, the program only keeps printing the first sentence my search yields. It should actually look for the longest word in this new sentence and keep applying my code flow described above. Below is my code along with a sample input/output : Sample input "Thane of code" Sample output "Thane of code Norway himselfe , with terrible numbers , Assisted by that most disloyall Traytor , The Thane of Cawdor , began a dismall Conflict , Till that Bellona ' s Bridegroome , lapt in proofe , Confronted him with selfe - comparisons , Point against Point , rebellious Arme ' gainst Arme , Curbing his lauish spirit : and to conclude , The Victorie fell on vs" Now this should actually take the sentence that starts with 'Norway himselfe....' and look for the longest word in it and do the steps above and so on but it doesn't. Any suggestions? Thanks. import nltk from nltk.corpus import gutenberg triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str split_str = triggerSentence.split()#split the sentence into words longestLength = 0 longestString = "" montyPython = 1 while montyPython: #code to find the longest word in the trigger sentence input for piece in split_str: if len(piece) > longestLength: longestString = piece longestLength = len(piece) listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format- listOfWords = gutenberg.words()# all words in gutenberg books -list format- # I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way. longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len) #get longest sentence -list format with every word of sentence being an actual element- longestSent=[longestSentence] for word in longestSent:#convert the list longestSentence to an actual string sstr = " ".join(word) print triggerSentence + " "+ sstr triggerSentence = sstr A: How about this? You find longest word in trigger You find longest word in the longest sentence containing word found in 1. The word of 1. is the longest word of the sentence of 2. What happens? Hint: answer starts with "Infinite". To correct the problem you could find set of words in lower case to be useful. BTW when you think MontyPython becomes False and the program finish? A: Rather than searching the entire corpus each time, it may be faster to construct a single map from word to the longest sentence containing that word. Here's my (untested) attempt to do this. import collections from nltk.corpus import gutenberg def words_in(sentence): """Generate all words in the sentence (lower-cased)""" for word in sentence.split(): word = word.strip('.,"\'-:;') if word: yield word.lower() def make_sentence_map(books): """Construct a map from words to the longest sentence containing the word.""" result = collections.defaultdict(str) for book in books: for sentence in book: for word in words_in(sentence): if len(sentence) > len(result[word]): result[word] = sent return result def generate_random_text(sentence, sentence_map): while True: yield sentence longest_word = max(words_in(sentence), key=len) sentence = sentence_map[longest_word] sentence_map = make_sentence_map(gutenberg.sents()) for sentence in generate_random_text('Thane of code.', sentence_map): print sentence A: You are assigning "split_str" outside of the loop, so it gets the original value and then keeps it. You need to assign it at the beginning of the while loop, so it changes each time. import nltk from nltk.corpus import gutenberg triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str longestLength = 0 longestString = "" montyPython = 1 while montyPython: #so this is run every time through the loop split_str = triggerSentence.split()#split the sentence into words #code to find the longest word in the trigger sentence input for piece in split_str: if len(piece) > longestLength: longestString = piece longestLength = len(piece) listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format- listOfWords = gutenberg.words()# all words in gutenberg books -list format- # I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way. longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len) #get longest sentence -list format with every word of sentence being an actual element- longestSent=[longestSentence] for word in longestSent:#convert the list longestSentence to an actual string sstr = " ".join(word) print triggerSentence + " "+ sstr triggerSentence = sstr A: Mr. Hankin's answer is more elegant, but the following is more in keeping with the approach you began with: import sys import string import nltk from nltk.corpus import gutenberg def longest_element(p): """return the first element of p which has the greatest len()""" max_len = 0 elem = None for e in p: if len(e) > max_len: elem = e max_len = len(e) return elem def downcase(p): """returns a list of words in p shifted to lower case""" return map(string.lower, p) def unique_words(): """it turns out unique_words was never referenced so this is here for pedagogy""" # there are 2.6 million words in the gutenburg corpus but only ~42k unique # ignoring case, let's pare that down a bit for word in gutenberg.words(): words.add(word.lower()) print 'gutenberg.words() has', len(words), 'unique caseless words' return words print 'loading gutenburg corpus...' sentences = [] for sentence in gutenberg.sents(): sentences.append(downcase(sentence)) trigger = sys.argv[1:] target = longest_element(trigger).lower() last_target = None while target != last_target: matched_sentences = [] for sentence in sentences: if target in sentence: matched_sentences.append(sentence) print '===', target, 'matched', len(matched_sentences), 'sentences' longestSentence = longest_element(matched_sentences) print ' '.join(longestSentence) trigger = longestSentence last_target = target target = longest_element(trigger).lower() Given your sample sentence though, it reaches fixation in two cycles: $ python nltkgut.py Thane of code loading gutenburg corpus... === target thane matched 24 sentences norway himselfe , with terrible numbers , assisted by that most disloyall traytor , the thane of cawdor , began a dismall conflict , till that bellona ' s bridegroome , lapt in proofe , confronted him with selfe - comparisons , point against point , rebellious arme ' gainst arme , curbing his lauish spirit : and to conclude , the victorie fell on vs === target bridegroome matched 1 sentences norway himselfe , with terrible numbers , assisted by that most disloyall traytor , the thane of cawdor , began a dismall conflict , till that bellona ' s bridegroome , lapt in proofe , confronted him with selfe - comparisons , point against point , rebellious arme ' gainst arme , curbing his lauish spirit : and to conclude , the victorie fell on vs Part of the trouble with the response to the last problem is that it did what you asked, but you asked a more specific question than you wanted an answer to. Thus the response got bogged down in some rather complicated list expressions that I'm not sure you understood. I suggest that you make more liberal use of print statements and don't import code if you don't know what it does. While unwrapping the list expressions I found (as noted) that you never used the corpus wordlist. Functions are a help also.
Python code flow does not work as expected?
I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a slight problem. Firstly, here is my code flow: Enter a sentence as input -this is called trigger string, is assigned to a variable- Get longest word in trigger string Search all Project Gutenberg database for sentences that contain this word -regardless of uppercase lowercase- Return the longest sentence that has the word I spoke about in step 3 Append the sentence in Step 1 and Step4 together Assign the sentence in Step 4 as the new 'trigger' sentence and repeat the process. Note that I have to get the longest word in second sentence and continue like that and so on- So far, I have been able to do this only once. When I try to keep this to continue, the program only keeps printing the first sentence my search yields. It should actually look for the longest word in this new sentence and keep applying my code flow described above. Below is my code along with a sample input/output : Sample input "Thane of code" Sample output "Thane of code Norway himselfe , with terrible numbers , Assisted by that most disloyall Traytor , The Thane of Cawdor , began a dismall Conflict , Till that Bellona ' s Bridegroome , lapt in proofe , Confronted him with selfe - comparisons , Point against Point , rebellious Arme ' gainst Arme , Curbing his lauish spirit : and to conclude , The Victorie fell on vs" Now this should actually take the sentence that starts with 'Norway himselfe....' and look for the longest word in it and do the steps above and so on but it doesn't. Any suggestions? Thanks. import nltk from nltk.corpus import gutenberg triggerSentence = raw_input("Please enter the trigger sentence: ")#get input str split_str = triggerSentence.split()#split the sentence into words longestLength = 0 longestString = "" montyPython = 1 while montyPython: #code to find the longest word in the trigger sentence input for piece in split_str: if len(piece) > longestLength: longestString = piece longestLength = len(piece) listOfSents = gutenberg.sents() #all sentences of gutenberg are assigned -list of list format- listOfWords = gutenberg.words()# all words in gutenberg books -list format- # I tip my hat to Mr.Alex Martelli for this part, which helps me find the longest sentence lt = longestString.lower() #this line tells you whether word list has the longest word in a case-insensitive way. longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len) #get longest sentence -list format with every word of sentence being an actual element- longestSent=[longestSentence] for word in longestSent:#convert the list longestSentence to an actual string sstr = " ".join(word) print triggerSentence + " "+ sstr triggerSentence = sstr
[ "How about this?\n\nYou find longest word in trigger\nYou find longest word in the longest sentence containing word found in 1.\nThe word of 1. is the longest word of the sentence of 2.\n\nWhat happens? Hint: answer starts with \"Infinite\". To correct the problem you could find set of words in lower case to be use...
[ 1, 1, 0, 0 ]
[]
[]
[ "nltk", "parsing", "python", "text" ]
stackoverflow_0003571887_nltk_parsing_python_text.txt
Q: Django can't find my non-python files! I can't, for the life of me, get Django to find my JavaScript files! I am trying to plug in a custom widget to the admin page, like so: class MarkItUpWidget(forms.Textarea): class Media: js = ( 'js/jquery.js', 'js/markitup/jquery.markitup.js', 'js/markitup/sets/markdown/set.js', 'js/markitup.init.js', ) css = { 'screen': ( 'js/markitup/skins/simple/style.css', 'js/markitup/sets/markdown/style.css', ) } However, when this code is inserted on my admin page, all of the links are broken, I can't get to any of my JavaScript files. My settings file looks like this: http://pastebin.com/qFVqUXyG Is there something I am doing wrong? I'm somewhat new to Django. A: I guess you're using django-admin runserver to test your website. In that case, have a look at "How to serve static files" (but don't ignore the big fat disclaimer). Once you're ready to deploy, this chapter contains all the information (provided you go the standard route of Apache/mod_wsgi) A: I don't know what the "django way" to include js files is, but I just use a simple regular include in the template, its great since you can dynamically generate the location / filename for these.. oh and if you are using django's test server I don't know how to get it to recognize these or if it even can but all you need is to run an apache server on your local machine and then put the files in the localhost directory and you can include them through localhost by including their full path in the template (i.e., http://localhost/myfiledirectory/myfile.js), also something I do is use amazon s3 to host files since you then get a url for them on there (not that you asked about this but its a quick way to host files if you don't have apache running locally) Basically, my understanding of Django is that it works differently than a PHP framework, for example, as the files for Django don't sit (or don't need to at least) in the web path (i.e. they do not need to be accessible through the host path but can be anywhere on the machine) this is good for providing extra security, etc but it also means, that to give files a url to download them they need to be in the web hosting path, others may know how to make django do this directly but my quick and dirty method of putting them on the localhost path will work if thats all you're after.
Django can't find my non-python files!
I can't, for the life of me, get Django to find my JavaScript files! I am trying to plug in a custom widget to the admin page, like so: class MarkItUpWidget(forms.Textarea): class Media: js = ( 'js/jquery.js', 'js/markitup/jquery.markitup.js', 'js/markitup/sets/markdown/set.js', 'js/markitup.init.js', ) css = { 'screen': ( 'js/markitup/skins/simple/style.css', 'js/markitup/sets/markdown/style.css', ) } However, when this code is inserted on my admin page, all of the links are broken, I can't get to any of my JavaScript files. My settings file looks like this: http://pastebin.com/qFVqUXyG Is there something I am doing wrong? I'm somewhat new to Django.
[ "I guess you're using django-admin runserver to test your website. In that case, have a look at \"How to serve static files\" (but don't ignore the big fat disclaimer).\nOnce you're ready to deploy, this chapter contains all the information (provided you go the standard route of Apache/mod_wsgi)\n", "I don't know...
[ 3, 0 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0003572032_django_django_admin_django_forms_python.txt
Q: An optional dict in the structure with MongoKit I've got MongoKit structure like this: structure = { ... 'plugin': { 'id': unicode, 'title': unicode, 'description': unicode, ... } However, not all documents will have the plugin key. If they do, I'd like it to be validated against the structure. required_fields does not include plugin. (plugin isn't a required key.) I've tried 'plugin': OR(None, {...}), but OR doesn't like None as a value. Any ideas? A: Looks like a bug in 0.5: http://bitbucket.org/namlook/mongokit/issue/78/not-required-fields-wrongly-validates#comment-234872 Discussion and temporary workaround here: http://groups.google.com/group/mongokit/browse_thread/thread/18fe4081a306e93e
An optional dict in the structure with MongoKit
I've got MongoKit structure like this: structure = { ... 'plugin': { 'id': unicode, 'title': unicode, 'description': unicode, ... } However, not all documents will have the plugin key. If they do, I'd like it to be validated against the structure. required_fields does not include plugin. (plugin isn't a required key.) I've tried 'plugin': OR(None, {...}), but OR doesn't like None as a value. Any ideas?
[ "Looks like a bug in 0.5:\n\nhttp://bitbucket.org/namlook/mongokit/issue/78/not-required-fields-wrongly-validates#comment-234872\n\nDiscussion and temporary workaround here:\n\nhttp://groups.google.com/group/mongokit/browse_thread/thread/18fe4081a306e93e\n\n" ]
[ 0 ]
[]
[]
[ "mongodb", "mongokit", "python" ]
stackoverflow_0003429527_mongodb_mongokit_python.txt
Q: Static method vs module function in python So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the class). Is there any benefit for doing it either way? The class is being imported by from module import class so I'm not worried about having those modules pulled in as well. But should I just make them class methods so that from module import * is safer or something? A: Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *. Another technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__.py file) __all__ = ['my_class_name'] This is more of a whitelist approach, so you can have full control over what gets imported without using leading underscores. So unless your methods logically belong in the class, and from your description they don't, I would leave them as module level functions and use one of these two approaches to make them private. A: Make them module-level functions, and prefix them with a single underscore so that consumers understand that they are for private use. A: If they are not useful outside of the class, what is the motivation to make them module methods? Keeping them as static method makes the name space cleaner. The only advantage to move it outside maybe so that people can reference them without using qualified them the class name. Say you have a log method that got reference in a ton of places, this may make sense as a stylistic choice.
Static method vs module function in python
So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the class). Is there any benefit for doing it either way? The class is being imported by from module import class so I'm not worried about having those modules pulled in as well. But should I just make them class methods so that from module import * is safer or something?
[ "Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *.\nAnother technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__....
[ 8, 3, 3 ]
[]
[]
[ "global", "python", "static_methods" ]
stackoverflow_0003570823_global_python_static_methods.txt
Q: Python: Why should 'from import *' be prohibited? If you happen to have from <module> import * in the middle of your program (or module), you would get the warning: /tmp/foo:100: SyntaxWarning: import * only allowed at module level I understand why import * is discouraged in general (namespace invisibility), but there are many situations where it would prove convenient, especially where code is not shared with anyone. So, can anyone explain precisely in detail why from <module> import * should be prohibited in all possible cases? A: I believe by "in the middle of your program" you are talking about an import inside a function definition: def f(): from module import * # not allowed This is not allowed because it would make optimizing the body of the function too hard. The Python implementation wants to know all of the names of function-local variables when it byte-compiles a function, so that it can optimize variable references into operations on the (CPython) virtual machine's operand stack, or at least to local variable-slot operations rather than lookups in outer namespaces. If you could dump the entire contents of a module into a function's local namespace, then the compiler would have to assume that any name in the function might possibly refer to a module global, because the list of names brought in by from module import * is only known at runtime. Putting from module import * in between top-level declarations is poor style, but it's allowed: def f(): ... from module import * def g(): ... EDIT April 2013: While looking into something else, I discovered that this restriction was introduced in Python 2.1, as a consequence of the "Nested Scopes" feature (PEP 227). Quoting from the link: One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception. This clarifies the Python 3.x vs 2.x behavior discussed in the comments. It is always contrary to the language specification, but CPython 2.1 through 2.7 only issue an error for from module import * within a function if it might affect the compiler's ability to know whether a variable binds locally or in a containing scope. In 3.x it has been promoted to an unconditional error. SON OF EDIT: ... and apparently flashk pointed this out years ago in another answer, quoting the same paragraph of "What's New in Python 2.1" yet. Y'all go upvote that now. A: At any lexical level, from amodule import * is a "seemed a good idea at the time" design decision that has proven a real disaster in real life, with the possible exception of handy exploration at the interactive interpreter prompt (even then, I'm not too hot on it -- import module as m forces only two extra characters to use qualified names instead [[just an m. prefix]], and qualified names are always sharper and more flexible than barenames, not to mention the great usefulness in exploratory interactive situations of having m available for help(m), reload(m), and the like!). This bedraggled construct makes it very hard, for the poor person reading the code (often in a doomed attempt to help debug it) to understand where mysteriously-appearing names are coming from -- impossible, if the construct is used more than once on a lexical level; but even when used just once, it forces laborious re-reading of the whole module every time before one can convince oneself that, yep, that bedraggled barename must come from the module. Plus, module authors usually don't go to the extreme trouble needed to "support" the horrid construct in question. If somewhere in your code you have, say, a use of sys.argv (and an import sys at the very top of your module, of course), how do you know that sys is the module it should be... or some completely different one (or a non-module) coming from the ... import *?! Multiply that by all the qualified names you're using, and misery is the only end result -- that, and mysterious bugs requiring long, laborious debugging (usually with the reluctant help of somebody who does "get" Python...!-). Within a function, a way to add and override arbitrary local names would be even worse. As an elementary but crucial optimization, the Python compiler looks around the function's body for any assignment or other binding statements on each barename, and deems "local" those names it sees thus assigned (the others must be globals or built-ins). With an import * (just like with an exec somestring without explicit dicts to use as namespaces), suddenly it becomes a total mystery which names are local, which names are global -- so the poor compiler would have to resort to the slowest possible strategy for each name lookup, using a dict for local variables (instead of the compact "vector" it normally uses) and performing up to three dict look-ups for each barename referenced, over and over. Go to any Python interactive prompt. Type import this. What do you see? The Zen of Python. What's the last and probably greatest bit of wisdom in that text...? Namespaces are one honking great idea -- let's do more of those! By forcing the use of barenames where qualified names are so vastly preferable, you're essentially doing the very opposite of this wise recommendation: instead of admiring the greatness and honkingtude of namespaces, and doing more of those, you're breaking down two perfectly good and ready-to-use namespaces (that of the module you're importing, and that of the lexical scope you're importing it in) to make a single, unholy, buggy, slow, rigid, unusable mess. If I could go back and change one early design decision in Python (it's a hard choice, because the use of def and especially lambda for what Javascript so much more readably calls function is a close second;-), I would retroactively wipe out the import * idea from Guido's mind. No amount of alleged convenience for exploration at the interactive prompt can balance the amount of evil it's wrought...!-) A: The release notes for Python 2.1 seem to explain why this limitation exists: One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception. A: It's not prohibited, because... ... it's handy for quick scripts and shell exploring. ...but you should not keep it in any serious code it can lead in importing names you don't know about and erase local names you can't know what's in use in your code, it's hard to know a script dependencies code completions won't work correctly anymore IDE convenient checks like "this var has not been declared" can't work anymore it make easier to create circular imports A: It's not prohibited at all. It works fine, but you get a warning because it's generally a bad idea (for reasons others have gone into). You can, if you like, suppress the warning; the warnings module is what you want for that. A: others have given in-depth answers, I'll give a short overview answer of my understanding.. when using from you are making it so you can directly call any function in that module you imported without doing modulename.functioname (you can just call "functionname") this creates problems if you have 2 functions of the same name in different modules and also can create confusion when dealing with a lot of functions as you don't know what object/module it belongs to (from point of view of someone looking over already written code that isn't familiar with it)
Python: Why should 'from import *' be prohibited?
If you happen to have from <module> import * in the middle of your program (or module), you would get the warning: /tmp/foo:100: SyntaxWarning: import * only allowed at module level I understand why import * is discouraged in general (namespace invisibility), but there are many situations where it would prove convenient, especially where code is not shared with anyone. So, can anyone explain precisely in detail why from <module> import * should be prohibited in all possible cases?
[ "I believe by \"in the middle of your program\" you are talking about an import inside a function definition:\ndef f():\n from module import * # not allowed\n\nThis is not allowed because it would make optimizing the body of the function too hard. The Python implementation wants to know all of the names of f...
[ 30, 17, 14, 4, 1, 0 ]
[]
[]
[ "module", "namespaces", "python", "python_import" ]
stackoverflow_0003571514_module_namespaces_python_python_import.txt
Q: Why doesn't this Boost ASIO code work with this python client? This code is identical to the original udp async echo server, but with a different socket. The response is transmitted and showing in wireshark, but then an ICMP Port Unreachable error is sent back to the server. I'm trying to understand why because everything looks correct. You can copy this code directly into a source file e.g. server.cpp. and then compile with gcc server.cpp -lboost_system Run it with a command like: ./a.out 35200 #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::udp; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), port)), socket2_(io_service, udp::endpoint(udp::v4(),0)) { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd) { if (!error && bytes_recvd > 0) { // use a different socket... random source port. socket2_.async_send_to( boost::asio::buffer(data_, bytes_recvd), sender_endpoint_, boost::bind(&server::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void handle_send_to(const boost::system::error_code& /*error*/, size_t /*bytes_sent*/) { // error_code shows success when checked here. But wireshark shows // an ICMP response with destination unreachable, port unreachable when run on // localhost. Haven't tried it across a network. socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: boost::asio::io_service& io_service_; udp::socket socket_; udp::socket socket2_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } The reason I need this is because I have multiple threads receiving data from an input queue that is fed with a UDP server. Now I want those threads to be able to send responses directly but I can't get it working. If I use the original socket (i.e. socket_) in the async_send_to call then it works. Ok... here is the test client that doesn't work with the code above (but works with the original version from the asio examples). #!/usr/bin/python import socket, sys, time, struct textport = "35200" host = "localhost" if len(sys.argv) > 1: host = sys.argv[1] print "Sending Data" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = int(textport) s.connect((host, port)) s.sendall("Hello World") #s.shutdown(1) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: buf = s.recv(1200) if not len(buf): break print "Received: %s" % buf It's got me baffled. But at least I can use the C++ UDP client and it works. A: You shouldn't pend an asynchronous send and then close the socket. The destructor for socket runs at the end of the block, closing the socket, which prevents the send from ever occurring. A: Ok, a completely different possibility. Are you running netfilter? Do you have a conntrack rule? A reply from the same port would match CONNECTED in the conntrack module, while a reply from a new port would appear to be a new connection. If incoming UDP packets which don't match CONNECTED have a REJECT action, it would explain the behavior, as well as why the exact same code could work for Sam. A: Here we go. I'm answering my own question again. The problem relates to my python code which was a sample I grabbed from someone else. This version works a whole heap better and reads the result correctly. And, is using the correct API sendto recvfrom which is what you would normally use with udp packets. #!/usr/bin/python import socket, sys, time, struct textport = "35200" host = "localhost" if len(sys.argv) > 1: host = sys.argv[1] print "Sending Data" port = int(textport) addr = (host, port) buf = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto("hello World", addr) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: data,addr = s.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived: '", data,"'" # Close socket s.close() The other thing is, that the as Ben has pointed out in his answer that at one point I was creating a socket that was later being deleted as the function went out of scope and it still had pending I/O. I have decided that there is little benefit in my case to use asynchronous I/O as it unnecessarily complicates the code and won't affect performance much.
Why doesn't this Boost ASIO code work with this python client?
This code is identical to the original udp async echo server, but with a different socket. The response is transmitted and showing in wireshark, but then an ICMP Port Unreachable error is sent back to the server. I'm trying to understand why because everything looks correct. You can copy this code directly into a source file e.g. server.cpp. and then compile with gcc server.cpp -lboost_system Run it with a command like: ./a.out 35200 #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::udp; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), port)), socket2_(io_service, udp::endpoint(udp::v4(),0)) { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd) { if (!error && bytes_recvd > 0) { // use a different socket... random source port. socket2_.async_send_to( boost::asio::buffer(data_, bytes_recvd), sender_endpoint_, boost::bind(&server::handle_send_to, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void handle_send_to(const boost::system::error_code& /*error*/, size_t /*bytes_sent*/) { // error_code shows success when checked here. But wireshark shows // an ICMP response with destination unreachable, port unreachable when run on // localhost. Haven't tried it across a network. socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: boost::asio::io_service& io_service_; udp::socket socket_; udp::socket socket2_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } The reason I need this is because I have multiple threads receiving data from an input queue that is fed with a UDP server. Now I want those threads to be able to send responses directly but I can't get it working. If I use the original socket (i.e. socket_) in the async_send_to call then it works. Ok... here is the test client that doesn't work with the code above (but works with the original version from the asio examples). #!/usr/bin/python import socket, sys, time, struct textport = "35200" host = "localhost" if len(sys.argv) > 1: host = sys.argv[1] print "Sending Data" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = int(textport) s.connect((host, port)) s.sendall("Hello World") #s.shutdown(1) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: buf = s.recv(1200) if not len(buf): break print "Received: %s" % buf It's got me baffled. But at least I can use the C++ UDP client and it works.
[ "You shouldn't pend an asynchronous send and then close the socket. The destructor for socket runs at the end of the block, closing the socket, which prevents the send from ever occurring.\n", "Ok, a completely different possibility.\nAre you running netfilter? Do you have a conntrack rule?\nA reply from the sa...
[ 3, 0, 0 ]
[ "Edit\nYour python client code looks suspicious, I don't think you should be doing a connect or a send using a UDP socket. Try this:\n#!/usr/bin/python\n\nimport socket, sys, time, struct\n\nport = 10000\nhost = \"localhost\"\naddr = (host,port)\n\nif len(sys.argv) > 1:\n host = sys.argv[1]\n\nprint \"Sending D...
[ -1 ]
[ "boost_asio", "c++", "python" ]
stackoverflow_0003571156_boost_asio_c++_python.txt
Q: Python: How to be notified when the subprocess is ended opened by Popen I am using Popen to run a command but I don't know how I can write a callback that gets called once the command is finished. Any idea? Thanks. Bin A: You can call communicate(): p = subprocess.Popen('find . -name "*.txt"', stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() You can also call wait(), but this might cause problems if the child process fills its output buffer. A: You could use p.poll() method of the Popen object. http://docs.python.org/library/subprocess.html#subprocess.Popen.poll
Python: How to be notified when the subprocess is ended opened by Popen
I am using Popen to run a command but I don't know how I can write a callback that gets called once the command is finished. Any idea? Thanks. Bin
[ "You can call communicate():\n p = subprocess.Popen('find . -name \"*.txt\"', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n\nYou can also call wait(), but this might cause problems if the child process fills its output buffer.\n", "You could use p.poll() method of the Popen ...
[ 2, 2 ]
[]
[]
[ "popen", "python" ]
stackoverflow_0003571784_popen_python.txt
Q: Pasting image to clipboard in python in linux Ive tried the gtk method, but it is very slow and doesn't work for a 'large' image (120 kb) import pygtk pygtk.require('2.0') import gtk import os def copy_image(f): assert os.path.exists(f), "file does not exist" clipboard = gtk.clipboard_get() img = gtk.Image() img.set_from_file(f) clipboard.set_image(img.get_pixbuf()) clipboard.store() Ive tried xclip and it only does text, so what other options are there? What does ubuntu use ? A: One way of getting text from/to the clipboard is using XSel. It's not pretty and requires you to communicate with an external program. But it works and is quite fast. Not sure if it's the best solution but I know it works :) [edit]You're right, it seems that xsel does not support images. In that case, how about a slightly modified GTK version. def copy_image(f): assert os.path.exists(f), "file does not exist" image = gtk.gdk.pixbuf_new_from_file(f) clipboard = gtk.clipboard_get() clipboard.set_image(image) clipboard.store() Do note that you might have to change the owner if your program exits right away because of how X keeps track of the clipboard. A: You might want to use the set_with_data method instead, but that's slightly more work (the image data is only sent when an application requests it, so it needs callback-functions). This has also advantages when you paste in the same application instead of to another application.
Pasting image to clipboard in python in linux
Ive tried the gtk method, but it is very slow and doesn't work for a 'large' image (120 kb) import pygtk pygtk.require('2.0') import gtk import os def copy_image(f): assert os.path.exists(f), "file does not exist" clipboard = gtk.clipboard_get() img = gtk.Image() img.set_from_file(f) clipboard.set_image(img.get_pixbuf()) clipboard.store() Ive tried xclip and it only does text, so what other options are there? What does ubuntu use ?
[ "One way of getting text from/to the clipboard is using XSel. It's not pretty and requires you to communicate with an external program. But it works and is quite fast.\nNot sure if it's the best solution but I know it works :)\n[edit]You're right, it seems that xsel does not support images.\nIn that case, how about...
[ 3, 1 ]
[]
[]
[ "copy", "image", "python" ]
stackoverflow_0003571855_copy_image_python.txt
Q: Is there any way to get ps output programmatically? I've got a webserver that I'm presently benchmarking for CPU usage. What I'm doing is essentially running one process to slam the server with requests, then running the following bash script to determine the CPU usage: #! /bin/bash for (( ;; )) do echo "`python -c 'import time; print time.time()'`, `ps -p $1 -o '%cpu' | grep -vi '%CPU'`" sleep 5 done It would be nice to be able to do this in Python so I can run it in one script instead of having to run two. I can't seem to find any platform independent (or at least platform independent to linux and OS X) way to get the ps output in Python without actually launching another process to run the command. I can do that, but it would be really nice if there were an API for doing this. Is there a way to do this, or am I going to have to launch the external script? A: You could check out this question about parsing ps output using Python. One of the answers suggests using the PSI python module. It's an extension though, so I don't really know how suitable that is for you. It also shows in the question how you can call a ps subprocess using python :) A: My preference is to do something like this. collection.sh for (( ;; )) do date; ps -p $1 -o '%cpu' done Then run collection.sh >someFile while you "slam the server with requests". Then kill this collection.sh operation after the server has been slammed. At the end, you'll have file with your log of date stamps and CPU values. analysis.py import datetime with( "someFile", "r" ) as source: for line in source: if line.strip() == "%CPU": continue try: date= datetime.datetime.strptime( line, "%a %b %d %H:%M:%S %Z %Y" ) except ValueError: cpu= float(line) print date, cpu # or whatever else you want to do with this data. A: You could query the CPU usage with PySNMP. This has the added benefit of being able to take measurements from a remote computer. For that matter, you could install a VM of Zenoss or its kin, and let it do the monitoring for you. A: if you don't want to invoke PS then why don't you try with /proc file system.I think you can write you python program and read the files from /proc file system and extract the data you want.I did this using perl,by writing inlined C code in perl script.I think you can find similar way in python as well.I think its doable,but you need to go through /prof file system and need to figure out what you want and how you can get it. http://www.faqs.org/docs/kernel/x716.html above URL might give some initial push.
Is there any way to get ps output programmatically?
I've got a webserver that I'm presently benchmarking for CPU usage. What I'm doing is essentially running one process to slam the server with requests, then running the following bash script to determine the CPU usage: #! /bin/bash for (( ;; )) do echo "`python -c 'import time; print time.time()'`, `ps -p $1 -o '%cpu' | grep -vi '%CPU'`" sleep 5 done It would be nice to be able to do this in Python so I can run it in one script instead of having to run two. I can't seem to find any platform independent (or at least platform independent to linux and OS X) way to get the ps output in Python without actually launching another process to run the command. I can do that, but it would be really nice if there were an API for doing this. Is there a way to do this, or am I going to have to launch the external script?
[ "You could check out this question about parsing ps output using Python.\nOne of the answers suggests using the PSI python module. It's an extension though, so I don't really know how suitable that is for you.\nIt also shows in the question how you can call a ps subprocess using python :)\n", "My preference is to...
[ 3, 3, 1, 1 ]
[]
[]
[ "linux", "macos", "ps", "python", "unix" ]
stackoverflow_0003559157_linux_macos_ps_python_unix.txt
Q: Finding out how many lines can be displayed in wx.richtext.RichTextCtrl without scrolling I'm writing an e-book reader in Python + wxPython, and I'd like to find out how many lines of text can be displayed in a given RichTextCtrl with the current formatting without scrolling. I thought of using and dividing the control's height by RichTextCtrl.GetFont().GetPixelSize(), but it appears that the pixel size parameter of wx.Font is only specified on Windows and GTK. In addition, this won't cover any additional vertical spacing between lines/paragraphs. I could of course get the font size in points, attempt to get the display's resolution in ppi, and do it that way, but 1) the line spacing problem still remains and 2) this is far too low a level of abstraction for something like this. Is there a sane way of doing this? EDIT: The objective is, to divide the ebook up into pages, so the scrolling unit is a whole page, as opposed to a line. A: Source code of PageDown method suggest that there is not a sane way to do this... Here is my insane proposition (which breaks widget content, caret, displayed position...) which scroll one page and measure how long this scroll is... def GetLineHeight(rtc): tallString = "\n".join([str(i) for i in xrange(200)]) rtc.SetValue(tallString) rtc.SetInsertionPoint(0) rtc.PageDown() pos = rtc.GetInsertionPoint() end = tallString.find("\n",pos) lineHeight=int(tallString[pos:end]) return lineHeight A: Did you try calling the GetNumberOfLines() method? According to Robin Dunn, that should work, although it doesn't take wrapped lines into account.
Finding out how many lines can be displayed in wx.richtext.RichTextCtrl without scrolling
I'm writing an e-book reader in Python + wxPython, and I'd like to find out how many lines of text can be displayed in a given RichTextCtrl with the current formatting without scrolling. I thought of using and dividing the control's height by RichTextCtrl.GetFont().GetPixelSize(), but it appears that the pixel size parameter of wx.Font is only specified on Windows and GTK. In addition, this won't cover any additional vertical spacing between lines/paragraphs. I could of course get the font size in points, attempt to get the display's resolution in ppi, and do it that way, but 1) the line spacing problem still remains and 2) this is far too low a level of abstraction for something like this. Is there a sane way of doing this? EDIT: The objective is, to divide the ebook up into pages, so the scrolling unit is a whole page, as opposed to a line.
[ "Source code of PageDown method suggest that there is not a sane way to do this...\nHere is my insane proposition (which breaks widget content, caret, displayed position...) which scroll one page and measure how long this scroll is...\ndef GetLineHeight(rtc):\n tallString = \"\\n\".join([str(i) for i in xrange(2...
[ 2, 0 ]
[]
[]
[ "python", "resolution_independence", "wxpython" ]
stackoverflow_0003504383_python_resolution_independence_wxpython.txt
Q: Debug a python script used with nmake I have a Visual Studio project which uses nmake to call a Python file for clean, build, or rebuild. For ex. in VS project properties->Configuration Properties->NMake, for the Build Command Line I would have ....\blah\tools\myBuildFile.py build -arg1 -arg2 There are several python files used with lots of variables and routines so I would like a tool which I could use to step through them. Can anyone suggest a plug-in to Visual Studio which I could use to debug the Python make files? Thanks A: Install winpdb Change your command to: ...\blah\winpdb.py ...\blah\tools\myBuildFile.py build -arg1 -arg2
Debug a python script used with nmake
I have a Visual Studio project which uses nmake to call a Python file for clean, build, or rebuild. For ex. in VS project properties->Configuration Properties->NMake, for the Build Command Line I would have ....\blah\tools\myBuildFile.py build -arg1 -arg2 There are several python files used with lots of variables and routines so I would like a tool which I could use to step through them. Can anyone suggest a plug-in to Visual Studio which I could use to debug the Python make files? Thanks
[ "\nInstall winpdb\nChange your command to: ...\\blah\\winpdb.py ...\\blah\\tools\\myBuildFile.py build -arg1 -arg2\n\n" ]
[ 0 ]
[]
[]
[ "makefile", "python", "visual_studio" ]
stackoverflow_0003574911_makefile_python_visual_studio.txt
Q: Function Names for sending and receiving RPCs? I'm using twisted. I have my protocols set up so that, to send an RPC, I do protocol.send("update_status", data). To document which RPCs I've implemented, I make a separate function call for each one, so in this case I'd call REQUEST_UPDATE_STATUS(data) to send that RPC. When a protocol receives an RPC, a function gets called based on its name, in this case, CMD_UPDATE_STATUS. The problem is that REQUEST and CMD are a bit awkward. I can mistake REQUEST as part of the command, for example, REQUEST_NEW_DATA, and that would end up triggering an RPC called 'new_data'. However, REQUEST_REQUEST_NEW_DATA is just silly. CMD is also awkward, as a REQUEST_SEND_NEW_DATA will become CMD_SEND_NEW_DATA, which is a bit awkward. Any tips? A: First tip: Use PB... it's well designed and does exactly that Second Tip: If the first tip isn't going to work for you, just do what PB does. On the client end a "callRemote("foo_func")" asks the server ot invoke the "foo_func" function on the server object. The server will then use "getattr(server_obj, "remote_" + "foo_func")" to find the remote method. If the method exists, it's called. Otherwise an error is returned. The nice thing about this design is that it completely does away with your REQUEST... CMD... constants.
Function Names for sending and receiving RPCs?
I'm using twisted. I have my protocols set up so that, to send an RPC, I do protocol.send("update_status", data). To document which RPCs I've implemented, I make a separate function call for each one, so in this case I'd call REQUEST_UPDATE_STATUS(data) to send that RPC. When a protocol receives an RPC, a function gets called based on its name, in this case, CMD_UPDATE_STATUS. The problem is that REQUEST and CMD are a bit awkward. I can mistake REQUEST as part of the command, for example, REQUEST_NEW_DATA, and that would end up triggering an RPC called 'new_data'. However, REQUEST_REQUEST_NEW_DATA is just silly. CMD is also awkward, as a REQUEST_SEND_NEW_DATA will become CMD_SEND_NEW_DATA, which is a bit awkward. Any tips?
[ "First tip: Use PB... it's well designed and does exactly that\nSecond Tip: If the first tip isn't going to work for you, just do what PB does. On the client end a \"callRemote(\"foo_func\")\" asks the server ot invoke the \"foo_func\" function on the server object. The server will then use \"getattr(server_obj, \"...
[ 1 ]
[]
[]
[ "naming_conventions", "python", "rpc", "twisted" ]
stackoverflow_0003575119_naming_conventions_python_rpc_twisted.txt
Q: python+twisted+gtk: KeyboardInterrupt causes free variable? I'm using twisted with GTK, and the following code runs when a connection could not be established: def connectionFailed(self, reason): #show a "connect failed" dialog dlg = gtk.MessageDialog( type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format="Could not connect to server:\n%s" % ( reason.getErrorMessage())) responseDF = defer.Deferred() dlg.set_title("Connection Error") def response(dialog, rid): dlg.hide_all() responseDF.callback(rid) dlg.connect("response", response) dlg.show_all() self.shutdownDeferreds.append(responseDF) self.shutdownDeferreds is a list of deferreds that is set up so that the reactor does not stop until they are all called. Now, I happened to press CTRL+C at the same time as the connection failed. The dialog did pop up, but when I press Close, I get: Traceback (most recent call last): File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response dlg.hide_all() NameError: free variable 'dlg' referenced before assignment in enclosing scope Traceback (most recent call last): File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response dlg.hide_all() NameError: free variable 'dlg' referenced before assignment in enclosing scope Any ideas why that might happen? A: Shouldn't that be: def response(dialog, rid): dialog.hide_all() responseDF.callback(rid) or really, for clarity, def response(self, rid): self.hide_all() responseDF.callback(rid) (I might be wrong about this, I've done barely any GTK.) If so, the problem is that you are referencing dlg in the function, which makes it a closure (it captures dlg from its surrounding scope). The KeyboardInterrupt will cause weird and wonderful behaviour, because it could destroy that scope.
python+twisted+gtk: KeyboardInterrupt causes free variable?
I'm using twisted with GTK, and the following code runs when a connection could not be established: def connectionFailed(self, reason): #show a "connect failed" dialog dlg = gtk.MessageDialog( type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format="Could not connect to server:\n%s" % ( reason.getErrorMessage())) responseDF = defer.Deferred() dlg.set_title("Connection Error") def response(dialog, rid): dlg.hide_all() responseDF.callback(rid) dlg.connect("response", response) dlg.show_all() self.shutdownDeferreds.append(responseDF) self.shutdownDeferreds is a list of deferreds that is set up so that the reactor does not stop until they are all called. Now, I happened to press CTRL+C at the same time as the connection failed. The dialog did pop up, but when I press Close, I get: Traceback (most recent call last): File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response dlg.hide_all() NameError: free variable 'dlg' referenced before assignment in enclosing scope Traceback (most recent call last): File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response dlg.hide_all() NameError: free variable 'dlg' referenced before assignment in enclosing scope Any ideas why that might happen?
[ "Shouldn't that be:\ndef response(dialog, rid):\n dialog.hide_all()\n responseDF.callback(rid)\n\nor really, for clarity,\ndef response(self, rid):\n self.hide_all()\n responseDF.callback(rid)\n\n(I might be wrong about this, I've done barely any GTK.) If so, the problem is that you are referencing dlg ...
[ 1 ]
[]
[]
[ "gtk", "python", "scope", "twisted", "variables" ]
stackoverflow_0003575200_gtk_python_scope_twisted_variables.txt
Q: Parse html with ajax json inside I have such files to parse (from scrapping) with Python: some HTML and JS here... SomeValue = { 'calendar': [ { 's0Date': new Date(2010, 9, 12), 'values': [ { 's1Date': new Date(2010, 9, 17), 'price': 9900 }, { 's1Date': new Date(2010, 9, 18), 'price': 9900 }, { 's1Date': new Date(2010, 9, 19), 'price': 9900 }, { 's1Date': new Date(2010, 9, 20), 'price': 9900 }, { 's1Date': new Date(2010, 9, 21), 'price': 9900 }, { 's1Date': new Date(2010, 9, 22), 'price': 9900 }, { 's1Date': new Date(2010, 9, 23), 'price': 9900 }] }, 'data': [{ index: 0, serviceClass: 'Economy', prices: [9900, 320.43, 253.27], eTicketing: true, segments: [{ indexSegment: 0, stopsCount: 1, flights: [{ index: 0, ... and a lot of nested data and again HTML and JS... I need to parse it and extract all json data. Now I use regex with cleaning all '\n' and '\t' and eval() function to convert it to Python dictionary.. I really don't like this solution, eval() especially. But I looked at BeautifulSoup and lxml, and didn't find something that will help to parse it. Can you suggest something better than regex and eval() for this task? Page example: http://codepaste.ru/3830/ A: aarrghhh no regex dont use regex no regex no no nooooooo Use the json module to handle JSON data: import json json.loads( <string> ) Use BeautifulSoup or lxml to handle parsing the html page: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup( <string> ) If you want specific help, you'll need to provide specific data e.g. the class of the tags in which this data is enclosed. You could soup.findAll the script tags, for instance, then strip some lines to get to the JSON, then feed that into json.loads.
Parse html with ajax json inside
I have such files to parse (from scrapping) with Python: some HTML and JS here... SomeValue = { 'calendar': [ { 's0Date': new Date(2010, 9, 12), 'values': [ { 's1Date': new Date(2010, 9, 17), 'price': 9900 }, { 's1Date': new Date(2010, 9, 18), 'price': 9900 }, { 's1Date': new Date(2010, 9, 19), 'price': 9900 }, { 's1Date': new Date(2010, 9, 20), 'price': 9900 }, { 's1Date': new Date(2010, 9, 21), 'price': 9900 }, { 's1Date': new Date(2010, 9, 22), 'price': 9900 }, { 's1Date': new Date(2010, 9, 23), 'price': 9900 }] }, 'data': [{ index: 0, serviceClass: 'Economy', prices: [9900, 320.43, 253.27], eTicketing: true, segments: [{ indexSegment: 0, stopsCount: 1, flights: [{ index: 0, ... and a lot of nested data and again HTML and JS... I need to parse it and extract all json data. Now I use regex with cleaning all '\n' and '\t' and eval() function to convert it to Python dictionary.. I really don't like this solution, eval() especially. But I looked at BeautifulSoup and lxml, and didn't find something that will help to parse it. Can you suggest something better than regex and eval() for this task? Page example: http://codepaste.ru/3830/
[ "aarrghhh no regex dont use regex no regex no no nooooooo\n\nUse the json module to handle JSON data:\nimport json\njson.loads( <string> )\n\nUse BeautifulSoup or lxml to handle parsing the html page:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup( <string> )\n\nIf you want specific help, you'll nee...
[ 5 ]
[]
[]
[ "html_parsing", "json", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0003575515_html_parsing_json_python_screen_scraping_web_scraping.txt
Q: Get object created in child thread back in main thread Assume i want to create 500 wxWidget like (some panels , color buttons and text ctrl etc), I have to create all this at single time but this will freeze my main thread, so i put this creation part in child thread and show some gif anim in main thread. But i was not able to get all these wxWidget object those created on my frame in child thread. Can i get that wxWidgets (created in child thread) back in main thread. simply just consider a case where i have to create children of a frame in child thread and main thread show animation. once child thread finish the all child created in child thread should available in main thread. Any help is really appreciable. I am using python 2.5, wxpython 2.8 on windowsxp. A: You could use pubsub which is included with wxpython -- wx.lib.pubsub. See my answer here for a basic example of usage for inter-thread comms. For an alternative: An example of how you could use wx.Yield to keep your window updated. import wx class GUI(wx.Frame): def __init__(self, parent, title=""): wx.Frame.__init__(self, parent=parent, title=title, size=(340,380)) self.SetMinSize((140,180)) self.creating_widgets = False self.panel = wx.Panel(id=wx.ID_ANY, parent=self) self.startButton = wx.Button(self.panel, wx.ID_ANY, 'Start') self.stopButton = wx.Button(self.panel, wx.ID_ANY, 'Stop') self.messageBox = wx.TextCtrl(self.panel, wx.ID_ANY, '', size=(75, 20)) self.Bind(wx.EVT_BUTTON, self.onStart, self.startButton) self.Bind(wx.EVT_BUTTON, self.onStop, self.stopButton) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.startButton, 0, wx.ALL, 10) self.sizer.Add(self.stopButton, 0, wx.ALL, 10) self.sizer.Add(self.messageBox, 0, wx.ALL, 10) self.panel.SetSizerAndFit(self.sizer) def onStart(self, event): self.creating_widgets = True count = 0 self.startButton.Disable() while self.creating_widgets: count += 1 #Create your widgets here #just for simulations sake... wx.MilliSleep(100) self.messageBox.SetLabel(str(count)) #Allow the window to update, #You must call wx.yield() frequently to update your window wx.Yield() def onStop(self, message): self.startButton.Enable() self.creating_widgets = False if __name__ == "__main__": app = wx.PySimpleApp() frame = GUI(None) frame.Show() app.MainLoop() A: You can send them back over a queue, or this all takes place in one instance of a class, assign the widgets to some known place in the instance for the main thread to pick them up. Signal via semaphore.
Get object created in child thread back in main thread
Assume i want to create 500 wxWidget like (some panels , color buttons and text ctrl etc), I have to create all this at single time but this will freeze my main thread, so i put this creation part in child thread and show some gif anim in main thread. But i was not able to get all these wxWidget object those created on my frame in child thread. Can i get that wxWidgets (created in child thread) back in main thread. simply just consider a case where i have to create children of a frame in child thread and main thread show animation. once child thread finish the all child created in child thread should available in main thread. Any help is really appreciable. I am using python 2.5, wxpython 2.8 on windowsxp.
[ "You could use pubsub which is included with wxpython -- wx.lib.pubsub.\nSee my answer here for a basic example of usage for inter-thread comms.\n\nFor an alternative: An example of how you could use wx.Yield to keep your window updated.\nimport wx\n\nclass GUI(wx.Frame):\n def __init__(self, parent, title=\"\")...
[ 2, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003574714_python_wxpython.txt
Q: Preserving subelement namespace serialization with lxml I have a few different XML documents that I'm trying to combine into one using lxml. The problem is that I need the result to preserve the namespaces on each of the sub-documents' root nodes. Lxml seems to want to push any namespace declarations used more than once to the root of the new document, which breaks in my application (it is an acknowledged bug). So for example, I have document A: <dc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</title> </dc> and document B: <mods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <titleInfo> <nonSort>La</nonSort> <title>difesa della razza</title> <subTitle>scienza, documentazione, polemica</subTitle> <partNumber>anno 1:n. 1</partNumber> </titleInfo> </mods> I want to wrap them in a element that also uses an xsi:schemaLocation, but I need the namespace declaration (xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance") to appear in all three nodes, like this: <wrap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org" xmlns:dc="http://www.foo.org" xmlns:mods="http://www.bar.org"> <dc:dc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <dc:title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</dc:title> </dc:dc> <mods:mods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <mods:titleInfo> <mods:nonSort>La</mods:nonSort> <mods:title>difesa della razza</mods:title> <mods:subTitle>scienza, documentazione, polemica</mods:subTitle> <mods:partNumber>anno 1:n. 1</mods:partNumber> </mods:titleInfo> </mods:mods> </wrap> However, when I append these two documents using Python/lxml wrap.append(dc) wrap.append(mods) I get the declaration pushed up to the highest level node that uses it. Unfortunately, this is a problem for my application. Like this: <wrap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org" xmlns:dc="http://www.foo.org" xmlns:mods="http://www.bar.org"> <dc:dc xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <dc:title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</dc:title> </dc:dc> <mods:mods xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <mods:titleInfo> <mods:nonSort>La</mods:nonSort> <mods:title>difesa della razza</mods:title> <mods:subTitle>scienza, documentazione, polemica</mods:subTitle> <mods:partNumber>anno 1:n. 1</mods:partNumber> </mods:titleInfo> </mods:mods> </wrap> Any ideas how I can force the behavior I want? THanks A: You could try inserting XInclude elements first, and then resolving them with the .xinclude() method (see docs). That seems to preserve the namespace declarations (lxml keeps them when they originate from the parser, but not when you create elements yourself, or move elements from one document to another) Note that in your case, you would still need to change the tag name of the elements: they will be included as they are in the original documents, without any namespace, while you seem to have changed them to namespaced element names in your output. You might have to use a custom resolver, contrary to what the docs might seem to say about .xinclude() not supporting this (it does use resolvers from the parser used to parse the containing document, it just doesn't support passing a specific resolver or parser to the XInclude processing). The other option would probably be an xslt-based solution.
Preserving subelement namespace serialization with lxml
I have a few different XML documents that I'm trying to combine into one using lxml. The problem is that I need the result to preserve the namespaces on each of the sub-documents' root nodes. Lxml seems to want to push any namespace declarations used more than once to the root of the new document, which breaks in my application (it is an acknowledged bug). So for example, I have document A: <dc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</title> </dc> and document B: <mods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <titleInfo> <nonSort>La</nonSort> <title>difesa della razza</title> <subTitle>scienza, documentazione, polemica</subTitle> <partNumber>anno 1:n. 1</partNumber> </titleInfo> </mods> I want to wrap them in a element that also uses an xsi:schemaLocation, but I need the namespace declaration (xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance") to appear in all three nodes, like this: <wrap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org" xmlns:dc="http://www.foo.org" xmlns:mods="http://www.bar.org"> <dc:dc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <dc:title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</dc:title> </dc:dc> <mods:mods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <mods:titleInfo> <mods:nonSort>La</mods:nonSort> <mods:title>difesa della razza</mods:title> <mods:subTitle>scienza, documentazione, polemica</mods:subTitle> <mods:partNumber>anno 1:n. 1</mods:partNumber> </mods:titleInfo> </mods:mods> </wrap> However, when I append these two documents using Python/lxml wrap.append(dc) wrap.append(mods) I get the declaration pushed up to the highest level node that uses it. Unfortunately, this is a problem for my application. Like this: <wrap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org" xmlns:dc="http://www.foo.org" xmlns:mods="http://www.bar.org"> <dc:dc xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/"> <dc:title>La difesa della razza: scienza, documentazione, polemica. anno 1:n. 1</dc:title> </dc:dc> <mods:mods xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd"> <mods:titleInfo> <mods:nonSort>La</mods:nonSort> <mods:title>difesa della razza</mods:title> <mods:subTitle>scienza, documentazione, polemica</mods:subTitle> <mods:partNumber>anno 1:n. 1</mods:partNumber> </mods:titleInfo> </mods:mods> </wrap> Any ideas how I can force the behavior I want? THanks
[ "You could try inserting XInclude elements first, and then resolving them with the .xinclude() method (see docs). That seems to preserve the namespace declarations (lxml keeps them when they originate from the parser, but not when you create elements yourself, or move elements from one document to another)\nNote th...
[ 0 ]
[]
[]
[ "lxml", "namespaces", "python", "serialization", "xml_namespaces" ]
stackoverflow_0003569712_lxml_namespaces_python_serialization_xml_namespaces.txt
Q: Pseudo-dicts as properties I have a Python class C which should have two pseudo-dicts a and b. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed. In pseudocode this would look like this: class C: def a.__getitem__(self, key): return 'a' def b.__getitem__(self, key): return 'b' >>> c = C() >>> c.a['foo'] 'a' >>> c.b['bar'] 'b' I could implement a class for a and b, but since both have just a few short methods, I wonder whether there is a more elegant and compact way to do this. A: Why not just define your own class? class PseudoDict(object): def __init__(self, c): self.c = c def __getitem__(self, key): return self.c.somethingmagical() class C(object): def __init__(self): self.a = PseudoDict(self) self.b = PseudoDict(self) c = C() print c.a['foo'] print c.b['bar'] I'm not sure where the values for these 'pseudo-dicts' are coming from, so you'll have to update the __getitem__ method. A: Like this? from collections import defaultdict class C: a = defaultdict(lambda:'a') b = defaultdict(lambda:'b') c=C() print c.a['foo'] print c.b['bar'] Or maybe like this for real calculation functions? from collections import defaultdict class C: def __init__(self): self.a = defaultdict(self.geta) self.b = defaultdict(self.getb) def geta(self): return 'a' def getb(self): return 'b' c=C() print c.a['foo'] print c.b['bar']
Pseudo-dicts as properties
I have a Python class C which should have two pseudo-dicts a and b. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed. In pseudocode this would look like this: class C: def a.__getitem__(self, key): return 'a' def b.__getitem__(self, key): return 'b' >>> c = C() >>> c.a['foo'] 'a' >>> c.b['bar'] 'b' I could implement a class for a and b, but since both have just a few short methods, I wonder whether there is a more elegant and compact way to do this.
[ "Why not just define your own class?\nclass PseudoDict(object):\n def __init__(self, c):\n self.c = c\n\n def __getitem__(self, key):\n return self.c.somethingmagical()\n\nclass C(object):\n def __init__(self):\n self.a = PseudoDict(self)\n self.b = PseudoDict(self)\n\nc = C()\n...
[ 1, 1 ]
[]
[]
[ "methods", "nested", "nested_attributes", "nested_class", "python" ]
stackoverflow_0003572526_methods_nested_nested_attributes_nested_class_python.txt
Q: python pythonpath modules Ok a short question: Is there any SIMPLE software with a GUI, that lets me manage my pythonpath, path python version in mac? So I could set my Python, pythonpath and python version i want to use. Thanks! @ katrielalex and S.Lott : I had a very nightmare with installing modules in python and as pointed out correctly in another question the reason is that I have a Mac with 2 Pythons installed: One preinstalled by Apple in /usr/bin One from python.org in /Library/Frameworks/Python.framework/Versions/x.y So now every time I hit easy_install It installs it to Apples pre installed. And I really came close to the solution, but now I figured out (again!) it wont work. I just would like to have a simple solution. Where I can say: Which is my main python I am using (.org or buildin). The one that if I run any code will be used. Be able to tell easy_install where to install my modules (preferably in both, just in case) Thats why a texteditor did not work for me until now. And I really like python, but got really, really annoyed by dealing with that basic problem every time. If you could tell me step-by-step explanation what I have to do to achieve this. This would be a great day in my year. Thanks again! A: This is a bit of a niche market! If you're technically competent enough to know what a PYTHONPATH is, you should probably be able to Google how to set environment variables on OSX. It requires editing a text file. http://adammechtley.com/2009/10/setting-up-your-pythonpath-environment-variable-globally-on-osx/
python pythonpath modules
Ok a short question: Is there any SIMPLE software with a GUI, that lets me manage my pythonpath, path python version in mac? So I could set my Python, pythonpath and python version i want to use. Thanks! @ katrielalex and S.Lott : I had a very nightmare with installing modules in python and as pointed out correctly in another question the reason is that I have a Mac with 2 Pythons installed: One preinstalled by Apple in /usr/bin One from python.org in /Library/Frameworks/Python.framework/Versions/x.y So now every time I hit easy_install It installs it to Apples pre installed. And I really came close to the solution, but now I figured out (again!) it wont work. I just would like to have a simple solution. Where I can say: Which is my main python I am using (.org or buildin). The one that if I run any code will be used. Be able to tell easy_install where to install my modules (preferably in both, just in case) Thats why a texteditor did not work for me until now. And I really like python, but got really, really annoyed by dealing with that basic problem every time. If you could tell me step-by-step explanation what I have to do to achieve this. This would be a great day in my year. Thanks again!
[ "This is a bit of a niche market! If you're technically competent enough to know what a PYTHONPATH is, you should probably be able to Google how to set environment variables on OSX. It requires editing a text file.\nhttp://adammechtley.com/2009/10/setting-up-your-pythonpath-environment-variable-globally-on-osx/\n" ...
[ 1 ]
[]
[]
[ "python", "pythonpath" ]
stackoverflow_0003575840_python_pythonpath.txt
Q: Is this a known DES cipher? What DES cipher is it? DES-CTR? import Crypto.Cipher.DES import struct def rol32(x, y): ret = ((x<<y)&0xFFFFFFFF)|((x>>(32-y))&0xFFFFFFFF) #print 'rol32', hex(x), hex(y), hex(ret) return ret def sub32(x, y): ret = (x & 0xFFFFFFFF) - (y & 0xFFFFFFFF) if ret < 0: ret += 0x100000000 #print 'sub32', hex(x), hex(y), hex(ret) return ret def mul32(x, y): ret = (x * y) & 0xFFFFFFFF #print 'mul32', x, y return ret d = Crypto.Cipher.DES.new('\xcd\x67\x98\xf2\xa4\xb6\x70\x76', Crypto.Cipher.DES.MODE_ECB) def decrypt(offset, f): out_buf = [] b = f.read(16) buf = d.decrypt(b) buf = buf[8:] + buf[:8] for i in range(0,4): val = struct.unpack('<I', buf[i*4:i*4+4])[0] val = sub32((sub32(0x8927462, mul32(offset, 0x3210789B)) ^ rol32(val, offset % 32)), 0x12345678) tmp = struct.pack('<I', val) out_buf.append(ord(tmp[0])) out_buf.append(ord(tmp[1])) out_buf.append(ord(tmp[2])) out_buf.append(ord(tmp[3])) for i in range(len(out_buf)-1,len(out_buf)-16,-1): out_buf[i] ^= out_buf[i-1] out_buf[len(out_buf)-16] ^= (offset & 0xFF) ^ ((offset >> 14) & 0xFF) return out_buf A: No. It is certainly not CTR-mode. It looks like a disc encryption mode. In particular the encryption mode has some slight resemblance with LRW. The main idea is to tweak the input depending on the block number, so that encrypting the same block multiple times does not result in the same ciphertext. It allows to re-encrypt a message partially, but an attacker will notice, which parts of the plaintext changes. Hence there is some small information leakage. Since I also don't see any authentication, I don't think I like this encryption mode.
Is this a known DES cipher? What DES cipher is it? DES-CTR?
import Crypto.Cipher.DES import struct def rol32(x, y): ret = ((x<<y)&0xFFFFFFFF)|((x>>(32-y))&0xFFFFFFFF) #print 'rol32', hex(x), hex(y), hex(ret) return ret def sub32(x, y): ret = (x & 0xFFFFFFFF) - (y & 0xFFFFFFFF) if ret < 0: ret += 0x100000000 #print 'sub32', hex(x), hex(y), hex(ret) return ret def mul32(x, y): ret = (x * y) & 0xFFFFFFFF #print 'mul32', x, y return ret d = Crypto.Cipher.DES.new('\xcd\x67\x98\xf2\xa4\xb6\x70\x76', Crypto.Cipher.DES.MODE_ECB) def decrypt(offset, f): out_buf = [] b = f.read(16) buf = d.decrypt(b) buf = buf[8:] + buf[:8] for i in range(0,4): val = struct.unpack('<I', buf[i*4:i*4+4])[0] val = sub32((sub32(0x8927462, mul32(offset, 0x3210789B)) ^ rol32(val, offset % 32)), 0x12345678) tmp = struct.pack('<I', val) out_buf.append(ord(tmp[0])) out_buf.append(ord(tmp[1])) out_buf.append(ord(tmp[2])) out_buf.append(ord(tmp[3])) for i in range(len(out_buf)-1,len(out_buf)-16,-1): out_buf[i] ^= out_buf[i-1] out_buf[len(out_buf)-16] ^= (offset & 0xFF) ^ ((offset >> 14) & 0xFF) return out_buf
[ "No. It is certainly not CTR-mode.\nIt looks like a disc encryption mode. In particular the encryption mode has some slight resemblance with LRW. The main idea is to tweak the input depending on the block number, so that encrypting the same block multiple times does not result in the same ciphertext.\nIt allows to ...
[ 0 ]
[]
[]
[ "algorithm", "cryptography", "encryption", "python" ]
stackoverflow_0003557803_algorithm_cryptography_encryption_python.txt
Q: How can I get pointer type behaviour in python I want to write a test case which will test a list of functions. Here is an example of what I want to do: from mock import Mock def method1 (): pass def method2 (): pass ## The testcase will then contain: for func in method_list: func = Mock() # continue to setup the mock and do some testing What I want to achieve is as follows: Step 1) Assign my local method variable to each item in method_list Step 2) Monkeypatch the method. In this example I am using a mock.Mock object What actually occurs is: Step 1) method is successfully assigned to an item from method_list - OK Step 2) method is then assigned to the object Mock() - NOK What I wanted in step 2 was to get the item from method_list e.g. method1 to be assigned to the Mock() object. The end result would be that both method and method1 would point to the same Mock() object I realise that what I am essentially doing is a = b a = c and then expecting c==b ! I guess this is not really possible with out somehow getting a pointer to b ? A: Um, how about simply modifiying method_list? for i in range(len(method_list)): # xrange in Python 2 method_list[i] = Mock() What you describe is closer to C++ references than to pointers. Few languages have such semantics (a few provide a special keyword for pass-by-reference), including Python. A: If I understand you correctly, you want to change what the variable method1 points to? Is that right? You can do this by modifying its entry in the dictionary of local variables: for method_name in [ 'method1', 'method2' ]: locals()[ method_name ] = Mock( ) The reason your previous code doesn't do what you want is that func is a reference to the function method1. By assigning to is, you simply change what it points to. Are you sure you want to do this? Monkeypatching is nasty and can cause many problems. A: Something like this? from mock import Mock def method1 (): pass def method2 (): pass method_list=list(f for f in globals() if hasattr(globals()[f],'__call__') and f.startswith('method')) print method_list ## The testcase will then contain: for func in method_list: globals()[func] = Mock(func) # continue to setup the mock and do some testing I am not so sure this is sensible thing to do, though. Looks like something to do with decorators.
How can I get pointer type behaviour in python
I want to write a test case which will test a list of functions. Here is an example of what I want to do: from mock import Mock def method1 (): pass def method2 (): pass ## The testcase will then contain: for func in method_list: func = Mock() # continue to setup the mock and do some testing What I want to achieve is as follows: Step 1) Assign my local method variable to each item in method_list Step 2) Monkeypatch the method. In this example I am using a mock.Mock object What actually occurs is: Step 1) method is successfully assigned to an item from method_list - OK Step 2) method is then assigned to the object Mock() - NOK What I wanted in step 2 was to get the item from method_list e.g. method1 to be assigned to the Mock() object. The end result would be that both method and method1 would point to the same Mock() object I realise that what I am essentially doing is a = b a = c and then expecting c==b ! I guess this is not really possible with out somehow getting a pointer to b ?
[ "Um, how about simply modifiying method_list?\nfor i in range(len(method_list)): # xrange in Python 2\n method_list[i] = Mock()\n\nWhat you describe is closer to C++ references than to pointers. Few languages have such semantics (a few provide a special keyword for pass-by-reference), including Python.\n", "If...
[ 1, 1, 1 ]
[]
[]
[ "monkeypatching", "python" ]
stackoverflow_0003575639_monkeypatching_python.txt
Q: Mercurial http interface under Ubuntu Hardy. Doesn't work I am trying to deploy mercurial under Ubuntu 8.04. Mercurial packages were installed correctly, but when I've configured http interface I always get 500 error. I enabled outputting debug info to error.log and got: mod_wsgi (pid=21159): Exception occurred within WSGI script '/home/hg/rep/hgwebdir.wsgi'. Traceback (most recent call last): File "/home/hg/rep/hgwebdir.wsgi", line 67, in <module> wsgicgi.launch(application) File "/var/lib/python-support/python2.5/mercurial/hgweb/wsgicgi.py", line 64, in launch result = application(environ, start_response) TypeError: 'hgwebdir' object is not callable My desktop is with Ubuntu 10.04, and home server with ubuntu 9.10, and configuration is the same, and works like a charm. I compiled python 2.6, and in hgwebdir.wsgi put path to this library - import sys sys.path.insert(0, "/path/to/python/lib") But it doesn't work anyways. What shall I do?? Thanks. A: Which version of mercurial are you using? If you're still using the 1.0.x that ubuntu ships update to the PPAs from launchpad: https://launchpad.net/~mercurial-ppa/+archive/stable-snapshots In 1.6 hgwebdir has been renamed to just 'hgweb' which will alter your config slightly. Also what are you using the launch the wsgi stuff? Apache?
Mercurial http interface under Ubuntu Hardy. Doesn't work
I am trying to deploy mercurial under Ubuntu 8.04. Mercurial packages were installed correctly, but when I've configured http interface I always get 500 error. I enabled outputting debug info to error.log and got: mod_wsgi (pid=21159): Exception occurred within WSGI script '/home/hg/rep/hgwebdir.wsgi'. Traceback (most recent call last): File "/home/hg/rep/hgwebdir.wsgi", line 67, in <module> wsgicgi.launch(application) File "/var/lib/python-support/python2.5/mercurial/hgweb/wsgicgi.py", line 64, in launch result = application(environ, start_response) TypeError: 'hgwebdir' object is not callable My desktop is with Ubuntu 10.04, and home server with ubuntu 9.10, and configuration is the same, and works like a charm. I compiled python 2.6, and in hgwebdir.wsgi put path to this library - import sys sys.path.insert(0, "/path/to/python/lib") But it doesn't work anyways. What shall I do?? Thanks.
[ "Which version of mercurial are you using? If you're still using the 1.0.x that ubuntu ships update to the PPAs from launchpad: https://launchpad.net/~mercurial-ppa/+archive/stable-snapshots\nIn 1.6 hgwebdir has been renamed to just 'hgweb' which will alter your config slightly.\nAlso what are you using the launch...
[ 1 ]
[]
[]
[ "mercurial", "python", "ubuntu" ]
stackoverflow_0003575783_mercurial_python_ubuntu.txt
Q: Extracting Text from Parsed HTML with Python I'm new to Python and I have been trying to search through html with regular expressions that has been parsed with BeautifulSoup. I haven't had any success and I think the reason is that I don't completely understand how to set up the regular expressions properly. I've looked at older questions about similar problems but I still haven't figured it out. If somebody could extract the "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" as well as a detailed expression of how the regular expression works, it would be really helpful. <td class="name"> <a href="/torrent/32726/0/"> Slackware Linux 13.0 [x86 DVD ISO] </a> </td> Edit: What I meant to say is, I am trying to extract "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" using BeautifulSoups functions to search the parse tree. I've been trying various things after searching and reading the documentation, but I'm still not sure on how to go about it. A: BeautifulSoup could also extract node values from your html. from BeautifulSoup import BeautifulSoup html = ('<html><head><title>Page title</title></head>' '<body>' '<table><tr>' '<td class="name"><a href="/torrent/32726/0/">Slackware Linux 13.0 [x86 DVD ISO]</a></td>' '<td class="name"><a href="/torrent/32727/0/">Slackware Linux 14.0 [x86 DVD ISO]</a></td>' '<td class="name"><a href="/torrent/32728/0/">Slackware Linux 15.0 [x86 DVD ISO]</a></td>' '</tr></table>' 'body' '</html>') soup = BeautifulSoup(html) links = [td.find('a') for td in soup.findAll('td', { "class" : "name" })] for link in links: print link.string Output: Slackware Linux 13.0 [x86 DVD ISO] Slackware Linux 14.0 [x86 DVD ISO] Slackware Linux 15.0 [x86 DVD ISO] A: You could use lxml.html to parse the html document: from lxml import html doc = html.parse('http://example.com') for a in doc.cssselect('td a'): print a.get('href') print a.text_content() You will have to look at how the document is structured to find the best way of determining the links you want (there might be other tables with links in them that you do not need etc...): you might first want to find the right table element for instance. There are also options besides css selectors (xpath for example) to search the document/the element. If you need, you can turn the links into absolute links with .make_links_absolute() method (do it on the document after parsing, and all the url's will be absolute, very convenient)
Extracting Text from Parsed HTML with Python
I'm new to Python and I have been trying to search through html with regular expressions that has been parsed with BeautifulSoup. I haven't had any success and I think the reason is that I don't completely understand how to set up the regular expressions properly. I've looked at older questions about similar problems but I still haven't figured it out. If somebody could extract the "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" as well as a detailed expression of how the regular expression works, it would be really helpful. <td class="name"> <a href="/torrent/32726/0/"> Slackware Linux 13.0 [x86 DVD ISO] </a> </td> Edit: What I meant to say is, I am trying to extract "/torrent/32726/0/" and "Slackware Linux 13.0 [x86 DVD ISO]" using BeautifulSoups functions to search the parse tree. I've been trying various things after searching and reading the documentation, but I'm still not sure on how to go about it.
[ "BeautifulSoup could also extract node values from your html.\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = ('<html><head><title>Page title</title></head>'\n '<body>'\n '<table><tr>'\n '<td class=\"name\"><a href=\"/torrent/32726/0/\">Slackware Linux 13.0 [x86 DVD ISO]</a></td>'\n '<td ...
[ 3, 2 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003575359_html_python_regex.txt
Q: Urllib2 authentication with API key I am trying to connect to radian6 api, which requires the auth_appkey, auth_user and auth_pass as md5 encryption. When I am trying to connect using telnet I can get the response xml successfully telnet sandboxapi.radian6.com 80 Trying 142.166.170.31... Connected to sandboxapi.radian6.com. Escape character is '^]'. GET /socialcloud/v1/auth/authenticate HTTP/1.1 host: sandboxapi.radian6.com auth_appkey: 123456789 auth_user: xxx@xxx.com auth_pass: 'md5encryptedpassword' HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Date: Thu, 26 Aug 2010 14:17:52 GMT Content-Type: application/xml Content-Length: 471 But when I am trying the same in python with the following code, import urllib import urllib2 user = 'xxx@xxx.com' password = 'md5encryptedpasswrod' base_url = 'http://sandboxapi.radian6.com/' api_key = '123456789' pwman = urllib2.HTTPPasswordMgrWithDefaultRealm() pwman.add_password(None, base_url, user, password) auth_handler = urllib2.HTTPBasicAuthHandler(pwman) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) req = urllib2.Request('http://sandboxapi.radian6.com/socialcloud/v1/auth/authenticate') req.add_header('auth_appkey', api_key) xml = urllib2.urlopen(req).read() it is throwing the following error trace, Traceback (most recent call last): File "connectapi.py", line 17, in <module> xml = urllib2.urlopen(req).read() File"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 397, in open response = meth(req, response) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 510, in http_response 'http', request, response, code, msg, hdrs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 435, in error return self._call_chain(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 518, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized I don't know what I am missing. Is it the API key or md5 encrypted password that is why I am being unauthorized? Your wisdom will be much appreciated to save my day. A: In your telnet session, you're not setting the Authorization: header, but that's what HTTPBasicAuthHandler uses. (You could listen in on this using wireshark or similar.) Presumably the API doesn't use HTTP Basic Authentication but its home-brew variant. You probably want to drop that line and set the HTTP headers manually.
Urllib2 authentication with API key
I am trying to connect to radian6 api, which requires the auth_appkey, auth_user and auth_pass as md5 encryption. When I am trying to connect using telnet I can get the response xml successfully telnet sandboxapi.radian6.com 80 Trying 142.166.170.31... Connected to sandboxapi.radian6.com. Escape character is '^]'. GET /socialcloud/v1/auth/authenticate HTTP/1.1 host: sandboxapi.radian6.com auth_appkey: 123456789 auth_user: xxx@xxx.com auth_pass: 'md5encryptedpassword' HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Date: Thu, 26 Aug 2010 14:17:52 GMT Content-Type: application/xml Content-Length: 471 But when I am trying the same in python with the following code, import urllib import urllib2 user = 'xxx@xxx.com' password = 'md5encryptedpasswrod' base_url = 'http://sandboxapi.radian6.com/' api_key = '123456789' pwman = urllib2.HTTPPasswordMgrWithDefaultRealm() pwman.add_password(None, base_url, user, password) auth_handler = urllib2.HTTPBasicAuthHandler(pwman) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) req = urllib2.Request('http://sandboxapi.radian6.com/socialcloud/v1/auth/authenticate') req.add_header('auth_appkey', api_key) xml = urllib2.urlopen(req).read() it is throwing the following error trace, Traceback (most recent call last): File "connectapi.py", line 17, in <module> xml = urllib2.urlopen(req).read() File"/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 397, in open response = meth(req, response) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 510, in http_response 'http', request, response, code, msg, hdrs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 435, in error return self._call_chain(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 518, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized I don't know what I am missing. Is it the API key or md5 encrypted password that is why I am being unauthorized? Your wisdom will be much appreciated to save my day.
[ "In your telnet session, you're not setting the Authorization: header, but that's what HTTPBasicAuthHandler uses. (You could listen in on this using wireshark or similar.) Presumably the API doesn't use HTTP Basic Authentication but its home-brew variant. You probably want to drop that line and set the HTTP headers...
[ 1 ]
[]
[]
[ "api_key", "authentication", "python", "urllib2" ]
stackoverflow_0003576201_api_key_authentication_python_urllib2.txt
Q: Problem with 2D interpolation in SciPy, non-rectangular grid I've been trying to use scipy.interpolate.bisplrep() and scipy.interpolate.interp2d() to find interpolants for data on my (218x135) 2D spherical-polar grid. To these I pass 2D arrays, X and Y, of the Cartesian positions of my grid nodes. I keep getting errors like the following (for linear interp. with interp2d): "Warning: No more knots can be added because the additional knot would coincide with an old one. Probably cause: s too small or too large a weight to an inaccurate data point. (fp>s) kx,ky=1,1 nx,ny=4,5 m=29430 fp=1390609718.902140 s=0.000000" I get a similar result for bivariate splines with the default value of the smoothing parameter s etc. My data are smooth. I've attached my code below in case I'm doing something obviously wrong. Any ideas? Thanks! Kyle class Field(object): Nr = 0 Ntheta = 0 grid = np.array([]) def __init__(self, Nr, Ntheta, f): self.Nr = Nr self.Ntheta = Ntheta self.grid = np.empty([Nr, Ntheta]) for i in range(Nr): for j in range(Ntheta): self.grid[i,j] = f[i*Ntheta + j] def calculate_lines(filename): ri,ti,r,t,Br,Bt,Bphi,Bmag = np.loadtxt(filename, skiprows=3,\ usecols=(1,2,3,4,5,6,7,9), unpack=True) Nr = int(max(ri)) + 1 Ntheta = int(max(ti)) + 1 ### Initialise coordinate grids ### X = np.empty([Nr, Ntheta]) Y = np.empty([Nr, Ntheta]) for i in range(Nr): for j in range(Ntheta): indx = i*Ntheta + j X[i,j] = r[indx]*sin(t[indx]) Y[i,j] = r[indx]*cos(t[indx]) ### Initialise field objects ### Bradial = Field(Nr=Nr, Ntheta=Ntheta, f=Br) ### Interpolate the fields ### intp_Br = interpolate.interp2d(X, Y, Bradial.grid, kind='linear') #rbf_0 = interpolate.Rbf(X,Y, Bradial.grid, epsilon=2) return A: Added 27Aug: Kyle followed this up on a scipy-user thread. 30Aug: @Kyle, it looks as though there's a mixup between Cartesion X,Y and polar Xnew,Ynew. See "polar" in the too-long notes below. # griddata vs SmoothBivariateSpline # http://stackoverflow.com/questions/3526514/ # problem-with-2d-interpolation-in-scipy-non-rectangular-grid # http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data # http://en.wikipedia.org/wiki/Natural_neighbor # http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html from __future__ import division import sys import numpy as np from scipy.interpolate import SmoothBivariateSpline # $scipy/interpolate/fitpack2.py from matplotlib.mlab import griddata __date__ = "2010-10-08 Oct" # plot diffs, ypow # "2010-09-13 Sep" # smooth relative def avminmax( X ): absx = np.abs( X[ - np.isnan(X) ]) av = np.mean(absx) m, M = np.nanmin(X), np.nanmax(X) histo = np.histogram( X, bins=5, range=(m,M) ) [0] return "av %.2g min %.2g max %.2g histo %s" % (av, m, M, histo) def cosr( x, y ): return 10 * np.cos( np.hypot(x,y) / np.sqrt(2) * 2*np.pi * cycle ) def cosx( x, y ): return 10 * np.cos( x * 2*np.pi * cycle ) def dipole( x, y ): r = .1 + np.hypot( x, y ) t = np.arctan2( y, x ) return np.cos(t) / r**3 #............................................................................... testfunc = cosx Nx = Ny = 20 # interpolate random Nx x Ny points -> Newx x Newy grid Newx = Newy = 100 cycle = 3 noise = 0 ypow = 2 # denser => smaller error imclip = (-5., 5.) # plot trierr, splineerr to same scale kx = ky = 3 smooth = .01 # Spline s = smooth * z2sum, see note # s is a target for sum (Z() - spline())**2 ~ Ndata and Z**2; # smooth is relative, s absolute # s too small => interpolate/fitpack2.py:580: UserWarning: ier=988, junk out # grr error message once only per ipython session seed = 1 plot = 0 exec "\n".join( sys.argv[1:] ) # run this.py N= ... np.random.seed(seed) np.set_printoptions( 1, threshold=100, suppress=True ) # .1f print 80 * "-" print "%s Nx %d Ny %d -> Newx %d Newy %d cycle %.2g noise %.2g kx %d ky %d smooth %s" % ( testfunc.__name__, Nx, Ny, Newx, Newy, cycle, noise, kx, ky, smooth) #............................................................................... # interpolate X Y Z to xnew x ynew -- X, Y = np.random.uniform( size=(Nx*Ny, 2) ) .T Y **= ypow # 1d xlin ylin -> 2d X Y Z, Ny x Nx -- # xlin = np.linspace( 0, 1, Nx ) # ylin = np.linspace( 0, 1, Ny ) # X, Y = np.meshgrid( xlin, ylin ) Z = testfunc( X, Y ) # Ny x Nx if noise: Z += np.random.normal( 0, noise, Z.shape ) # print "Z:\n", Z z2sum = np.sum( Z**2 ) xnew = np.linspace( 0, 1, Newx ) ynew = np.linspace( 0, 1, Newy ) Zexact = testfunc( *np.meshgrid( xnew, ynew )) if imclip is None: imclip = np.min(Zexact), np.max(Zexact) xflat, yflat, zflat = X.flatten(), Y.flatten(), Z.flatten() #............................................................................... print "SmoothBivariateSpline:" fit = SmoothBivariateSpline( xflat, yflat, zflat, kx=kx, ky=ky, s = smooth * z2sum ) Zspline = fit( xnew, ynew ) .T # .T ?? splineerr = Zspline - Zexact print "Zspline - Z:", avminmax(splineerr) print "Zspline: ", avminmax(Zspline) print "Z: ", avminmax(Zexact) res = fit.get_residual() print "residual %.0f res/z2sum %.2g" % (res, res / z2sum) # print "knots:", fit.get_knots() # print "Zspline:", Zspline.shape, "\n", Zspline print "" #............................................................................... print "griddata:" Ztri = griddata( xflat, yflat, zflat, xnew, ynew ) # 1d x y z -> 2d Ztri on meshgrid(xnew,ynew) nmask = np.ma.count_masked(Ztri) if nmask > 0: print "info: griddata: %d of %d points are masked, not interpolated" % ( nmask, Ztri.size) Ztri = Ztri.data # Nans outside convex hull trierr = Ztri - Zexact print "Ztri - Z:", avminmax(trierr) print "Ztri: ", avminmax(Ztri) print "Z: ", avminmax(Zexact) print "" #............................................................................... if plot: import pylab as pl nplot = 2 fig = pl.figure( figsize=(10, 10/nplot + .5) ) pl.suptitle( "Interpolation error: griddata - %s, BivariateSpline - %s" % ( testfunc.__name__, testfunc.__name__ ), fontsize=11 ) def subplot( z, jplot, label ): ax = pl.subplot( 1, nplot, jplot ) im = pl.imshow( np.clip( z, *imclip ), # plot to same scale cmap=pl.cm.RdYlBu, interpolation="nearest" ) # nearest: squares, else imshow interpolates too # todo: centre the pixels ny, nx = z.shape pl.scatter( X*nx, Y*ny, edgecolor="y", s=1 ) # for random XY pl.xlabel(label) return [ax, im] subplot( trierr, 1, "griddata, Delaunay triangulation + Natural neighbor: max %.2g" % np.nanmax(np.abs(trierr)) ) ax, im = subplot( splineerr, 2, "SmoothBivariateSpline kx %d ky %d smooth %.3g: max %.2g" % ( kx, ky, smooth, np.nanmax(np.abs(splineerr)) )) pl.subplots_adjust( .02, .01, .92, .98, .05, .05 ) # l b r t cax = pl.axes([.95, .05, .02, .9]) # l b w h pl.colorbar( im, cax=cax ) # -1.5 .. 9 ?? if plot >= 2: pl.savefig( "tmp.png" ) pl.show() Notes on 2d interpolation, BivariateSpline vs. griddata. scipy.interpolate.*BivariateSpline and matplotlib.mlab.griddata both take 1d arrays as arguments: Znew = griddata( X,Y,Z, Xnew,Ynew ) # 1d X Y Z Xnew Ynew -> interpolated 2d Znew on meshgrid(Xnew,Ynew) assert X.ndim == Y.ndim == Z.ndim == 1 and len(X) == len(Y) == len(Z) The inputs X,Y,Z describe a surface or cloud of points in 3-space: X,Y (or latitude,longitude or ...) points in a plane, and Z a surface or terrain above that. X,Y may fill most of the rectangle [Xmin .. Xmax] x [Ymin .. Ymax], or may be just a squiggly S or Y inside it. The Z surface may be smooth, or smooth + a bit of noise, or not smooth at all, rough volcanic mountains. Xnew and Ynew are usually also 1d, describing a rectangular grid of |Xnew| x |Ynew| points where you want to interpolate or estimate Z. Znew = griddata(...) returns a 2d array over this grid, np.meshgrid(Xnew,Ynew): Znew[Xnew0,Ynew0], Znew[Xnew1,Ynew0], Znew[Xnew2,Ynew0] ... Znew[Xnew0,Ynew1] ... Znew[Xnew0,Ynew2] ... ... Xnew,Ynew points far from any of the input X,Y s spell trouble. griddata checks this: A masked array is returned if any grid points are outside convex hull defined by input data (no extrapolation is done). ("Convex hull" is the area inside an imaginary rubber band stretched around all the X,Y points.) griddata works by first constructing a Delaunay triangulation of the input X,Y, then doing Natural neighbor interpolation. This is robust and quite fast. BivariateSpline, though, can extrapolate, generating wild swings without warning. Furthermore, all the *Spline routines in Fitpack are very sensitive to smoothing parameter S. Dierckx's book (books.google isbn 019853440X p. 89) says: if S is too small, the spline approximation is too wiggly and picks up too much noise (overfit); if S is too large the spline will be too smooth and signal will be lost (underfit). Interpolation of scattered data is hard, smoothing not easy, both together really hard. What should an interpolator do with big holes in XY, or with very noisy Z ? ("If you want to sell it, you're going to have to describe it.") Yet more notes, fine print: 1d vs 2d: Some interpolators take X,Y,Z either 1d or 2d. Others take 1d only, so flatten before interpolating: Xmesh, Ymesh = np.meshgrid( np.linspace(0,1,Nx), np.linspace(0,1,Ny) ) Z = f( Xmesh, Ymesh ) # Nx x Ny Znew = griddata( Xmesh.flatten(), Ymesh.flatten(), Z.flatten(), Xnew, Ynew ) On masked arrays: matplotlib handles them just fine, plotting only unmasked / non-NaN points. But I wouldn't bet that that a bozo numpy/scipy functions would work at all. Check for interpolation outside the convex hull of X,Y like this: Znew = griddata(...) nmask = np.ma.count_masked(Znew) if nmask > 0: print "info: griddata: %d of %d points are masked, not interpolated" % ( nmask, Znew.size) # Znew = Znew.data # array with NaNs On polar coordinates: X,Y and Xnew,Ynew should be in the same space, both Cartesion, or both in [rmin .. rmax] x [tmin .. tmax]. To plot (r, theta, z) points in 3d: from mpl_toolkits.mplot3d import Axes3D Znew = griddata( R,T,Z, Rnew,Tnew ) ax = Axes3D(fig) ax.plot_surface( Rnew * np.cos(Tnew), Rnew * np.sin(Tnew), Znew ) See also (haven't tried this): ax = subplot(1,1,1, projection="polar", aspect=1.) ax.pcolormesh(theta, r, Z) Two tips for the wary programmer: check for outliers, or funny scaling: def minavmax( X ): m = np.nanmin(X) M = np.nanmax(X) av = np.mean( X[ - np.isnan(X) ]) # masked ? histo = np.histogram( X, bins=5, range=(m,M) ) [0] return "min %.2g av %.2g max %.2g histo %s" % (m, av, M, histo) for nm, x in zip( "X Y Z Xnew Ynew Znew".split(), (X,Y,Z, Xnew,Ynew,Znew) ): print nm, minavmax(x) check interpolation with simple data: interpolate( X,Y,Z, X,Y ) -- interpolate at the same points interpolate( X,Y, np.ones(len(X)), Xnew,Ynew ) -- constant 1 ?
Problem with 2D interpolation in SciPy, non-rectangular grid
I've been trying to use scipy.interpolate.bisplrep() and scipy.interpolate.interp2d() to find interpolants for data on my (218x135) 2D spherical-polar grid. To these I pass 2D arrays, X and Y, of the Cartesian positions of my grid nodes. I keep getting errors like the following (for linear interp. with interp2d): "Warning: No more knots can be added because the additional knot would coincide with an old one. Probably cause: s too small or too large a weight to an inaccurate data point. (fp>s) kx,ky=1,1 nx,ny=4,5 m=29430 fp=1390609718.902140 s=0.000000" I get a similar result for bivariate splines with the default value of the smoothing parameter s etc. My data are smooth. I've attached my code below in case I'm doing something obviously wrong. Any ideas? Thanks! Kyle class Field(object): Nr = 0 Ntheta = 0 grid = np.array([]) def __init__(self, Nr, Ntheta, f): self.Nr = Nr self.Ntheta = Ntheta self.grid = np.empty([Nr, Ntheta]) for i in range(Nr): for j in range(Ntheta): self.grid[i,j] = f[i*Ntheta + j] def calculate_lines(filename): ri,ti,r,t,Br,Bt,Bphi,Bmag = np.loadtxt(filename, skiprows=3,\ usecols=(1,2,3,4,5,6,7,9), unpack=True) Nr = int(max(ri)) + 1 Ntheta = int(max(ti)) + 1 ### Initialise coordinate grids ### X = np.empty([Nr, Ntheta]) Y = np.empty([Nr, Ntheta]) for i in range(Nr): for j in range(Ntheta): indx = i*Ntheta + j X[i,j] = r[indx]*sin(t[indx]) Y[i,j] = r[indx]*cos(t[indx]) ### Initialise field objects ### Bradial = Field(Nr=Nr, Ntheta=Ntheta, f=Br) ### Interpolate the fields ### intp_Br = interpolate.interp2d(X, Y, Bradial.grid, kind='linear') #rbf_0 = interpolate.Rbf(X,Y, Bradial.grid, epsilon=2) return
[ "Added 27Aug: Kyle followed this up on a\nscipy-user thread.\n30Aug: @Kyle, it looks as though there's a mixup between Cartesion X,Y and polar Xnew,Ynew.\nSee \"polar\" in the too-long notes below.\n\n# griddata vs SmoothBivariateSpline\n# http://stackoverflow.com/questions/3526514/\n# problem-with-2d-interpolati...
[ 19 ]
[]
[]
[ "interpolation", "python", "scipy" ]
stackoverflow_0003526514_interpolation_python_scipy.txt
Q: Trying to parse an XML file with Python - what am I doing wrong? I'm working with XML and Python for the first time. The ultimate goal is to send a request to a REST service, receive a response in XML, and parse the values and send emails depending on what was returned. However, the REST service is not yet in place, so for now I'm experimenting with an XML file saved on my C drive. I have a simple bit of code, and I'm confused about why it isn't working. This is my xml file ("XMLTest.xml"): <Response> <exitCode>1</exitCode> <fileName>C:/Something/</fileName> <errors> <error>Error generating report</error> </errors> </Response> This is my code so far: from xml.dom import minidom something = open("C:/XMLTest.xml") something = minidom.parse(something) nodeList = [] for node in something.getElementsByTagName("Response"): nodeList.extend(t.nodeValue for t in node.childNodes) print nodeList But the results that print out are... [u'\n\t', None, u'\n\t', None, u'\n\t', None, u'\n'] What am I doing wrong? I'm trying to get the node values. Is there a better way to do this? Is there a built-in method in Python to convert an xml file to an object or dictionary? I'd like to get all the values, preferably with the names attached. A: Does this help? doc = '''<Response> <exitCode>1</exitCode> <fileName>C:/Something/</fileName> <errors> <error>Error generating report</error> </errors> </Response>''' from xml.dom import minidom something = minidom.parseString( doc ) nodeList = [ ] for node in something.getElementsByTagName( "Response" ): response = { } response[ "exit code" ] = node.getElementsByTagName( "exitCode" )[ 0 ].childNodes[ 0 ].nodeValue response[ "file name" ] = node.getElementsByTagName( "fileName" )[ 0 ].childNodes[ 0 ].nodeValue errors = node.getElementsByTagName( "errors" )[ 0 ].getElementsByTagName( "error" ) response[ "errors" ] = [ error.childNodes[ 0 ].nodeValue for error in errors ] nodeList.append( response ) import pprint pprint.pprint( nodeList ) yields [{'errors': [u'Error generating report'], 'exit code': u'1', 'file name': u'C:/Something/'}] A: If you are just starting out with xml and python, and have no compelling reason to use DOM, I strongly suggest you have a look at the ElementTree api (implemented in the standard library in xml.etree.ElementTree) To give you a taste: import xml.etree.cElementTree as etree tree = etree.parse('C:/XMLTest.xml') response = tree.getroot() exitcode = response.find('exitCode').text filename = response.find('fileName').text errors = [i.text for i in response.find('errors')] (if you need more power - xpath, validation, xslt etc... - you can even switch to lxml, which implements the same API, but with a lot of extras) A: You're not thinking about the XML from the DOM standpoint. Namely, 'C:/Something' isn't the nodevalue of the element whose tagname is 'fileName'; it's the nodevalue of the text node that is the first child of the element whose tagname is 'fileName'. What I recommend you do is play around with it a little more in python itself: start python. from xml.dom import minidom x = minidom.parseString('<Response><filename>C:/</filename>>') x.getElementsByTagName('Response') ... x.getElementsByTagName('Response')[0].childNodes[0] ... and so forth. You'll get a quick appreciation for how the document is being parsed. A: I recommend my library xml2obj. It is way cleaner than DOM. The "library" has only 84 lines of code you can embed anywhere. In [185]: resp = xml2obj(something) In [186]: resp.exitCode Out[186]: u'1' In [187]: resp.fileName Out[187]: u'C:/Something/' In [188]: len(resp.errors) Out[188]: 1 In [189]: for node in resp.errors: .....: print node.error .....: .....: Error generating report
Trying to parse an XML file with Python - what am I doing wrong?
I'm working with XML and Python for the first time. The ultimate goal is to send a request to a REST service, receive a response in XML, and parse the values and send emails depending on what was returned. However, the REST service is not yet in place, so for now I'm experimenting with an XML file saved on my C drive. I have a simple bit of code, and I'm confused about why it isn't working. This is my xml file ("XMLTest.xml"): <Response> <exitCode>1</exitCode> <fileName>C:/Something/</fileName> <errors> <error>Error generating report</error> </errors> </Response> This is my code so far: from xml.dom import minidom something = open("C:/XMLTest.xml") something = minidom.parse(something) nodeList = [] for node in something.getElementsByTagName("Response"): nodeList.extend(t.nodeValue for t in node.childNodes) print nodeList But the results that print out are... [u'\n\t', None, u'\n\t', None, u'\n\t', None, u'\n'] What am I doing wrong? I'm trying to get the node values. Is there a better way to do this? Is there a built-in method in Python to convert an xml file to an object or dictionary? I'd like to get all the values, preferably with the names attached.
[ "Does this help?\ndoc = '''<Response>\n <exitCode>1</exitCode>\n <fileName>C:/Something/</fileName>\n <errors>\n <error>Error generating report</error>\n </errors>\n</Response>'''\n\nfrom xml.dom import minidom\n\nsomething = minidom.parseString( doc )\n\nnodeList = [ ]\nfor node in something.get...
[ 3, 3, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003576190_python_xml.txt
Q: Blob object for python (ctypes), C++ Hallo! I want a blob object which I can pass around in python and from time to time give it to a C++ function to write to. ctypes seems the way to go but I have problem with the python standard functions. For example: >>> import ctypes >>> T=ctypes.c_byte * 1000 >>> blob = T() >>> ctypes.pointer(blob) <__main__.LP_c_byte_Array_1000 object at 0x7f6558795200> # Do stuff with blob data through the pointer in C++ >>> f = open('test.bin', 'wb') >>> f.write(blob) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument 1 must be string or buffer, not _ctypes.ArrayType I would really like to avoid copying the data if not necessary. Thanks A: You'll probably have better luck with using string buffers and accessing the content through the raw attribute value pstr = ctypes.create_string_buffer( 1000 ) f.write( pstr.raw )
Blob object for python (ctypes), C++
Hallo! I want a blob object which I can pass around in python and from time to time give it to a C++ function to write to. ctypes seems the way to go but I have problem with the python standard functions. For example: >>> import ctypes >>> T=ctypes.c_byte * 1000 >>> blob = T() >>> ctypes.pointer(blob) <__main__.LP_c_byte_Array_1000 object at 0x7f6558795200> # Do stuff with blob data through the pointer in C++ >>> f = open('test.bin', 'wb') >>> f.write(blob) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument 1 must be string or buffer, not _ctypes.ArrayType I would really like to avoid copying the data if not necessary. Thanks
[ "You'll probably have better luck with using string buffers and accessing the content through the raw attribute value\npstr = ctypes.create_string_buffer( 1000 )\nf.write( pstr.raw )\n\n" ]
[ 0 ]
[]
[]
[ "blob", "ctypes", "python" ]
stackoverflow_0003575564_blob_ctypes_python.txt
Q: make python os.chdir follow vim autochdir? I use the autochdir option in VIM and I also utilize VIM's built-in Python interface. Is it possible to have the current directory for the built-in Python interpreter follow VIM's autochdir. For example, when I am editing a Python file, VIM's autochdir option puts me in the same directory as the edited file as far as VIM is concerned, but I still have to manually :py os.chdir(directory) from the VIM command line in order to get the Python interpreter to recognize the same directory that VIM has. Is this possible? I'm using VIM 7.2 on Windows. A: You could try putting in vimrc autocmd Filetype python py os.chdir(directory) which means that whenever a python file is read or written, it executes this command.
make python os.chdir follow vim autochdir?
I use the autochdir option in VIM and I also utilize VIM's built-in Python interface. Is it possible to have the current directory for the built-in Python interpreter follow VIM's autochdir. For example, when I am editing a Python file, VIM's autochdir option puts me in the same directory as the edited file as far as VIM is concerned, but I still have to manually :py os.chdir(directory) from the VIM command line in order to get the Python interpreter to recognize the same directory that VIM has. Is this possible? I'm using VIM 7.2 on Windows.
[ "You could try putting in vimrc\nautocmd Filetype python py os.chdir(directory)\n\nwhich means that whenever a python file is read or written, it executes this command.\n" ]
[ 2 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0003566228_python_vim.txt
Q: Custom sort of directory contents I have a number of directories containing the files similar to the below example: test setup adder hello _CONFIG TEST2 The file(s) in these directories with the prefix _ represent configuration files of significance. The aim was to have these files appear first when I listed the directory i.e. I would like to be provided with: _CONFIG TEST2 adder hello setup test However, I am using for element in sorted(os.listdir(path)): print(element) and this provides a list where files starting in uppercase are listed above the _ prefixed files: TEST2 _CONFIG adder hello setup test Is there anyway around this without filtering each file by its first character and printing seperately as this would seem to be overkill. Thank you Tom A: sorted( ..., key = lambda s: ( not s.startswith( "_" ), s ) ) A: for element in sorted(os.listdir(path), key=lambda x:x.replace('_', ' ')): print(element)
Custom sort of directory contents
I have a number of directories containing the files similar to the below example: test setup adder hello _CONFIG TEST2 The file(s) in these directories with the prefix _ represent configuration files of significance. The aim was to have these files appear first when I listed the directory i.e. I would like to be provided with: _CONFIG TEST2 adder hello setup test However, I am using for element in sorted(os.listdir(path)): print(element) and this provides a list where files starting in uppercase are listed above the _ prefixed files: TEST2 _CONFIG adder hello setup test Is there anyway around this without filtering each file by its first character and printing seperately as this would seem to be overkill. Thank you Tom
[ "sorted( ..., key = lambda s: ( not s.startswith( \"_\" ), s ) )\n\n", "for element in sorted(os.listdir(path), key=lambda x:x.replace('_', ' ')):\n print(element)\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003576678_python_sorting.txt
Q: How can I get Eclipse / PyDev to ignore alternatives to cls? I have inherited some code that uses klass instead of PyDev's preferred cls: def func(klass): # do something that doesn't reference klass return True PyDev issues a warning that there is an unused parameter klass, which it wouldn't do if we used the parameter cls. Is there an easy way to let PyDev know that klass is the same thing as cls? A: The only unused name Pydev doesn't warn about is _. cls is the name used for the first argument in classmethods, but that doesnt seem to be the case here. A: If you're using PyDev's built-in code analysis, go to Preferences > Pydev > Editor > Code Analysis, and switch to the 'Unused' tab. At the bottom is a text field containing a list of variable names to ignore if unused. Add klass to that list and you should be all set.
How can I get Eclipse / PyDev to ignore alternatives to cls?
I have inherited some code that uses klass instead of PyDev's preferred cls: def func(klass): # do something that doesn't reference klass return True PyDev issues a warning that there is an unused parameter klass, which it wouldn't do if we used the parameter cls. Is there an easy way to let PyDev know that klass is the same thing as cls?
[ "The only unused name Pydev doesn't warn about is _.\ncls is the name used for the first argument in classmethods, but that doesnt seem to be the case here.\n", "If you're using PyDev's built-in code analysis, go to Preferences > Pydev > Editor > Code Analysis, and switch to the 'Unused' tab. At the bottom is a ...
[ 0, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003575828_eclipse_pydev_python.txt
Q: copy objects between different Virtual-Machines efficiently I have a feeling that I am going to ask a "stupid" question, yet I must ask ... I have 2 virtual machines. I would like to copy an instance of an object from one to another, Is it possible to copy the bits that represents this object in the VM's heap, send it to the other VM, like that the other VM just need to allocate the bits in it's memory and add a reference in it's stack to this memory slot...? Currently, in order to do such a thing we serialize the object and unserialize it, which is much less efficient(computational wise) than just copy the instance as is...the parsing is a computational waste... JS serialization Example: each VM is an instance of V8 (JavaScript), one way of doing it is to convert the object to JSON(JSON.stringify), send it some how to the other VM which get the string and convert it back to object ( e.g. var myObject = eval('(' + myJSONtext + ')');) .. (JavaScript is just an example here, this is some sort of serialization) A: Lets ignore for a second the naive assumption that you can generalize this question over multiple VMs easily. Any attempt to build a mechanism like this would be heavily dependent on the implementation details of the VM you were building the mechanism for. Here are several reasons why this isn't done: In-core representation is not generally portable across architectures. If I were sending an "object" from a VM on a SPARC machine to a VM on an x86 machine without knowledge of its structure, the object would appear corrupt on the other side. The object will not neccesarily exist at the same memory location on both machines, so internal pointers within the object will need to be patched up after it reaches the second VM. This too requires internal knowledge of the object's structure. The object probably contains references to other objects, thus copying an object means copying a tree of objects, and generally not an acyclic tree either. You end up building code that looks an awful lot like a serialization library in order to do this reliably. Objects often hold on to native resources (like file handles and sockets) that can't be reliably transmitted across machines. In many VMs, there is a distinction made between data (the object you're trying to copy) and metadata (for example, the class of the object you're trying to copy). In these kinds of VMs, even if you could copy the object bit-for-bit unscathed, it might depend on a bunch of metadata that doesn't exist at the remote end. Copying metadata bit-for-bit is also tricky, as many VMs use implementation techniques (such as a global pool of interned strings or memory mapped object code) that make the data inherently non-portable. You also might end up with much more metadata than you want (e.g. in .net the smallest unit of metadata that you can package up and send somewhere is typically an assembly). In-core representation is generally not portable among different versions of the same VM and don't contain internal version information that could be used to patch up the data. In-core representation contains lots of things (e.g. inline caches, garbage collection information) that don't need to be copied. Copying this stuff would be wasteful, and the information might not even be sensible on the other side. Basically, to do this reliably, you end up building the world's most awkward and unreliable serialization library, and the performance gains of the simple memory copy are lost in patching up the many things that get broken when you do the copy naively. Thus, these mechanisms tend not to exist. There is one huge exception to this rule: image based virtual machines (such as many smalltalk and self VMs) are built around the idea that the virtual machine state exists in an "image" that can be copied, moved between machines, etc. This generally comes at a substantial performance cost. A: Why not use cpickle. It will serialize data very reliably and very quickly then you can send it over a socket, named pipe, mmap, you name it, except on the other end you can expect to reliably reassemble it as long as it didn't get corrupted in transfer and the versions of the pickle module aren't hugely different. Of course the truly enterprisey way is to use a platform agnostic standard such as XML which will let you expand platform interoperability beyond python. I know this sidesteps the question, but I think someone who's contributed to the python interpreter codebase would have to clarify that for you. A: I am certain there is no way to do this kind of direct memory transfer in the VMware APIs; I don't know about other hypervisors, but I still kind of doubt it. VMware has ways of shipping the memory of an entire machine to another host server (mostly by using a paging file), but nothing that can extract only a piece of memory from a running program and give it to another--there's just too much involved there. So your existing tactic of object serialization is definitely a good and common solution for this need, and fortunately the programming languages you're working with have good options (Python, Java). But I'm wondering if you really need to have the entire object stashed and re-created, or is it only some of the data included. If the data is not excessive, you could use some kind of remote method invocation to send a message from the source VM to the receiver telling it to create an object with this data. In this case, you would be serializing only the data necessary, and letting the target machine re-build the object in its own memory.
copy objects between different Virtual-Machines efficiently
I have a feeling that I am going to ask a "stupid" question, yet I must ask ... I have 2 virtual machines. I would like to copy an instance of an object from one to another, Is it possible to copy the bits that represents this object in the VM's heap, send it to the other VM, like that the other VM just need to allocate the bits in it's memory and add a reference in it's stack to this memory slot...? Currently, in order to do such a thing we serialize the object and unserialize it, which is much less efficient(computational wise) than just copy the instance as is...the parsing is a computational waste... JS serialization Example: each VM is an instance of V8 (JavaScript), one way of doing it is to convert the object to JSON(JSON.stringify), send it some how to the other VM which get the string and convert it back to object ( e.g. var myObject = eval('(' + myJSONtext + ')');) .. (JavaScript is just an example here, this is some sort of serialization)
[ "Lets ignore for a second the naive assumption that you can generalize this question over multiple VMs easily. Any attempt to build a mechanism like this would be heavily dependent on the implementation details of the VM you were building the mechanism for.\nHere are several reasons why this isn't done:\n\nIn-core ...
[ 7, 2, 0 ]
[]
[]
[ "c#", "java", "javascript", "python", "vm_implementation" ]
stackoverflow_0003575218_c#_java_javascript_python_vm_implementation.txt
Q: _really_ disable GtkTreeView searching How do I really disable gtk treeview interactive search? The docs say to set_enable_search(False), but if I do this, CTRL+F still causes an annoying search pop-up to appear. Connecting to start-interactive-search and returning True doesn't work either. A: The pygtk docs don't state this, but the C docs do: gtk_tree_view_set_search_column (GtkTreeView *tree_view, gint column) column : the column of the model to search in, or -1 to disable searching Passing -1 for the column really disables searching.
_really_ disable GtkTreeView searching
How do I really disable gtk treeview interactive search? The docs say to set_enable_search(False), but if I do this, CTRL+F still causes an annoying search pop-up to appear. Connecting to start-interactive-search and returning True doesn't work either.
[ "The pygtk docs don't state this, but the C docs do:\ngtk_tree_view_set_search_column (GtkTreeView *tree_view, gint column)\n\ncolumn :\n the column of the model to search in, or -1 to disable searching \n\nPassing -1 for the column really disables searching.\n" ]
[ 9 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0003577224_gtk_gtktreeview_pygtk_python.txt
Q: How can I change windows codepage in python? >>> a = os.popen('chcp 65001') >>> a.read() 'Active code page: 65001\n' >>> a.close() >>> a = os.popen('chcp') >>> a.read() 'Active code page: 437\n' >>> a.close() After I set the codepage to 65001, the next time i call chcp it should say the active codepage is 65001, not 437. I tried this in windows command prompt and it worked. Why doesn't it work through python code? A: The reason is that every time you call os.popen you are spawning a new process. Try opening up two cmd.exe sessions and running chcp 65001 in one and chcp in the other -- that's what you are doing here in your Python code. One thing to note: all of the [popen*()][1] calls are depreciated as of Python 2.6. The new module to use is the subprocess module.
How can I change windows codepage in python?
>>> a = os.popen('chcp 65001') >>> a.read() 'Active code page: 65001\n' >>> a.close() >>> a = os.popen('chcp') >>> a.read() 'Active code page: 437\n' >>> a.close() After I set the codepage to 65001, the next time i call chcp it should say the active codepage is 65001, not 437. I tried this in windows command prompt and it worked. Why doesn't it work through python code?
[ "The reason is that every time you call os.popen you are spawning a new process. Try opening up two cmd.exe sessions and running chcp 65001 in one and chcp in the other -- that's what you are doing here in your Python code.\nOne thing to note: all of the [popen*()][1] calls are depreciated as of Python 2.6. The ...
[ 3 ]
[]
[]
[ "codepages", "python" ]
stackoverflow_0003577249_codepages_python.txt
Q: Do Django Fixtures load in incorrect order when testing? I am testing my application and I am running into an issue and I'm not sure why. I'm loading fixtures for my tests and the fixtures have foreign keys that rely on each other. They must be loaded in a certain order or it won't work. The fixtures I'm loading are: ["test_company_data", "test_rate_index", 'test_rate_description'] Company data is the first one. test_rate_index has a foreign key to company, and test_rate_description has a foreign key to a model declared in test_rate_index. (as an aside, different test need different fixtures which is why I'm not just shoving everything in one) If I use django's standard procedure for loading tests, the tests do not load in the proper order. class TestPackages(test.TestCase): fixtures = ["test_company_data", "test_rate_index", "test_rate_description",] I get the message DoesNotExist: RateDescription matching query does not exist. But if I reverse the order of my fixtures (which makes no sense) it works: fixtures = ["test_rate_description", "test_company_data", "test_rate_index",] Django's documentation states that the fixtures load in the order they are declared, but this doesn't seem to be the case. As a workaround, instead of using django's call_command('loaddata', *fixtures, **{ 'verbosity': 0, 'commit': False, 'database': 'default' }) I'm using a different function in the setUp method that loads the fixtures one at a time. def load_fixtures(fixtures): for fixture in fixtures: call_command('loaddata', fixture, **{ 'verbosity': 0, 'commit': False, 'database': 'default' }) Is there something I'm doing incorrectly or not understanding that is causing my fixtures not to be loaded in the proper order when trying to use the standard method? A: Django's documentation states that the fixtures load in the order they are declared, but this doesn't seem to be the case. This is certainly strange. Fixtures are getting loaded in the proper order when I tested one of my projects (Django 1.2.1, Python 2.6.2, Postgresql 8.3.11). Here is what I'd do to troubleshoot. DoesNotExist: RateDescription matching query does not exist. Are you getting this error when loading a fixture or when executing a test? Can you find the fixture/code that is raising this? Increase verbosity if need be. Can you try firing a loaddata command from the command line? Call it three times, passing the name of one fixture for each call in the proper expected sequence. And see if the fixtures get loaded. I know you'd probably have done this already but can you make sure that the first and second fixtures do not contain any RateDescription data?
Do Django Fixtures load in incorrect order when testing?
I am testing my application and I am running into an issue and I'm not sure why. I'm loading fixtures for my tests and the fixtures have foreign keys that rely on each other. They must be loaded in a certain order or it won't work. The fixtures I'm loading are: ["test_company_data", "test_rate_index", 'test_rate_description'] Company data is the first one. test_rate_index has a foreign key to company, and test_rate_description has a foreign key to a model declared in test_rate_index. (as an aside, different test need different fixtures which is why I'm not just shoving everything in one) If I use django's standard procedure for loading tests, the tests do not load in the proper order. class TestPackages(test.TestCase): fixtures = ["test_company_data", "test_rate_index", "test_rate_description",] I get the message DoesNotExist: RateDescription matching query does not exist. But if I reverse the order of my fixtures (which makes no sense) it works: fixtures = ["test_rate_description", "test_company_data", "test_rate_index",] Django's documentation states that the fixtures load in the order they are declared, but this doesn't seem to be the case. As a workaround, instead of using django's call_command('loaddata', *fixtures, **{ 'verbosity': 0, 'commit': False, 'database': 'default' }) I'm using a different function in the setUp method that loads the fixtures one at a time. def load_fixtures(fixtures): for fixture in fixtures: call_command('loaddata', fixture, **{ 'verbosity': 0, 'commit': False, 'database': 'default' }) Is there something I'm doing incorrectly or not understanding that is causing my fixtures not to be loaded in the proper order when trying to use the standard method?
[ "\nDjango's documentation states that the fixtures load in the order they are declared, but this doesn't seem to be the case.\n\nThis is certainly strange. Fixtures are getting loaded in the proper order when I tested one of my projects (Django 1.2.1, Python 2.6.2, Postgresql 8.3.11).\nHere is what I'd do to troubl...
[ 1 ]
[]
[]
[ "django", "django_fixtures", "python" ]
stackoverflow_0003575867_django_django_fixtures_python.txt
Q: Set comprehensions don't work on Pydev (Python) {x for x in range(10)} works perfectly on IDLE, but when I try this in eclipse (with Pydev plugin) I get a syntax error: Undefined variable: x Is it because Pydev doesn't support set comprehensions or something? What can I do to make this work? (This was just one example that doesn't work. All set comprehensions don't work for me). (I'm using Python 3) A: This is a bug in PyDev; in this case ignore the editor's warning and execute the code: it will work. I get this a lot, PyDev isn't perfect but it's good enough! A: Make sure that Pydev is configured to use Python 3. A: You can find out which version of Python you are using with import sys sys.stdout.write( sys.version )
Set comprehensions don't work on Pydev (Python)
{x for x in range(10)} works perfectly on IDLE, but when I try this in eclipse (with Pydev plugin) I get a syntax error: Undefined variable: x Is it because Pydev doesn't support set comprehensions or something? What can I do to make this work? (This was just one example that doesn't work. All set comprehensions don't work for me). (I'm using Python 3)
[ "This is a bug in PyDev; in this case ignore the editor's warning and execute the code: it will work.\nI get this a lot, PyDev isn't perfect but it's good enough!\n", "Make sure that Pydev is configured to use Python 3.\n", "You can find out which version of Python you are using with\nimport sys\nsys.stdout.wri...
[ 3, 2, 0 ]
[]
[]
[ "eclipse_plugin", "list_comprehension", "pydev", "python", "set" ]
stackoverflow_0003576927_eclipse_plugin_list_comprehension_pydev_python_set.txt
Q: Sending multiple POST data items with the same name, using AppEngine I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values. form_fields = { "data": "foo", "data": "bar" } form_data = urllib.urlencode(form_fields) result = urlfetch.fetch(url="http://www.foo.com/", payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) However, in this example, the server seems to receieve only one item named data, with the value bar. How could I solve this problem? A: Modify your form_fields dictionary so that fields with the same name are turned into lists, and use the doseq argument to urllib.urlencode: form_fields = { "data": ["foo","bar"] } form_data = urllib.urlencode(form_fields, doseq=True) At this point, form_data is 'data=foo&data=bar', which is what I think you need. A: A normal python dict can't handle this sort of thing; use something like a webob.MultiDict: >>> z = webob.MultiDict([('foo', 'bar'), ('foo', 'baz')]) >>> urllib.urlencode(z) 'foo=bar&foo=baz'
Sending multiple POST data items with the same name, using AppEngine
I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values. form_fields = { "data": "foo", "data": "bar" } form_data = urllib.urlencode(form_fields) result = urlfetch.fetch(url="http://www.foo.com/", payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) However, in this example, the server seems to receieve only one item named data, with the value bar. How could I solve this problem?
[ "Modify your form_fields dictionary so that fields with the same name are turned into lists, and use the doseq argument to urllib.urlencode:\nform_fields = {\n \"data\": [\"foo\",\"bar\"]\n}\n\nform_data = urllib.urlencode(form_fields, doseq=True)\n\nAt this point, form_data is 'data=foo&data=bar', which is what ...
[ 14, 1 ]
[]
[]
[ "google_app_engine", "python", "urlfetch" ]
stackoverflow_0003577064_google_app_engine_python_urlfetch.txt
Q: in gql, how do i sort by a field in another class linked by referenceproperty? for example, 2 classes in a 1-to-many relationship: class owner(db.model): name = db.StringProperty() class cat(db.model): name = db.StringProperty() owner = db.ReferenceProperty(owner) so how do i produce a list of cats ordered by owner.name (then optionally by cat.name)? i tried "SELECT * FROM cat ORDER BY owner.name" but got Parse Error: Expected no additional symbols at symbol .name Thanks A: You can't; this would require a join, which the datastore doesn't support. If you need to sort like this, denormalize your data and include the owner name in the cat model.
in gql, how do i sort by a field in another class linked by referenceproperty?
for example, 2 classes in a 1-to-many relationship: class owner(db.model): name = db.StringProperty() class cat(db.model): name = db.StringProperty() owner = db.ReferenceProperty(owner) so how do i produce a list of cats ordered by owner.name (then optionally by cat.name)? i tried "SELECT * FROM cat ORDER BY owner.name" but got Parse Error: Expected no additional symbols at symbol .name Thanks
[ "You can't; this would require a join, which the datastore doesn't support. If you need to sort like this, denormalize your data and include the owner name in the cat model.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003573122_google_app_engine_gql_python.txt
Q: SSH Tunnel for Python MySQLdb connection I tried creating a SSH tunnel using ssh -L 3306:localhost:22 <hostip> Then running my python script to connect via localhost conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test') However, I receive the following error (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)") How can I make sure I'm hitting the correct host and not just some problem with the bind? A: Try changing "localhost" to "127.0.0.1", it should work as you expect. This behavior is detailed in the manual: UNIX sockets and named pipes don't work over a network, so if you specify a host other than localhost, TCP will be used, and you can specify an odd port if you need to (the default port is 3306): db=_mysql.connect(host="outhouse", port=3307, passwd="moonpie", db="thangs") If you really had to, you could connect to the local host with TCP by specifying the full host name, or 127.0.0.1. A: Does mysqld run on port 22 on the remote? Call me ignorant but I think what you're trying to do is ssh -n -N -f -L 3306:localhost:3306 remotehost Then making MySQL connections on local machine will transparently get tunneled over to the target host. A: You can't specify localhost as the hostname, as this suggests that MySQLdb should try to use a UNIX socket. Use 127.0.0.1 for the host instead. If you want to make sure the connection works, you can use the standard mysql client.
SSH Tunnel for Python MySQLdb connection
I tried creating a SSH tunnel using ssh -L 3306:localhost:22 <hostip> Then running my python script to connect via localhost conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test') However, I receive the following error (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)") How can I make sure I'm hitting the correct host and not just some problem with the bind?
[ "Try changing \"localhost\" to \"127.0.0.1\", it should work as you expect. This behavior is detailed in the manual:\n\nUNIX sockets and named pipes don't\n work over a network, so if you specify\n a host other than localhost, TCP will\n be used, and you can specify an odd\n port if you need to (the default por...
[ 18, 13, 3 ]
[]
[]
[ "mysql", "python", "ssh" ]
stackoverflow_0003577555_mysql_python_ssh.txt
Q: Python: How do I convert an int to its string representation with a set number of digits? Pretty much what it says up there. Basically, how do I get the string produced by print "%05d" % 100 A: Maybe I'm misinterpreting the question, but this should work: my_string = "%05d" % 100 A: Use str.zfill(width) A: This should work too: `100`.zfill(5) A: print('{0:0=5d}'.format(100)) # 00100 use the 0th positional argument to format / fill character is '0' / / desired width of formatted string / / / {0:0=5d} For more, see the docs. A: i = 100 str(i).zfill(5) A: If you're using Python 3, the str.format method is preferred. It was introduced in Python 2.6. (Alas, my work system is at 2.4 (and I'm not permitted to upgrade), so I can't construct and test an example.)
Python: How do I convert an int to its string representation with a set number of digits?
Pretty much what it says up there. Basically, how do I get the string produced by print "%05d" % 100
[ "Maybe I'm misinterpreting the question, but this should work:\nmy_string = \"%05d\" % 100\n\n", "Use str.zfill(width)\n", "This should work too:\n`100`.zfill(5)\n\n", "print('{0:0=5d}'.format(100))\n# 00100\n\n\n use the 0th positional argument to format\n / fill character is '0'\n / / desired width ...
[ 11, 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003577582_python_string.txt
Q: Substitute for u'string' I saved my script in UTF-8 encoding. I changed my codepage on windows to 65001. I'm on python 2.6 Script #1 # -*- coding: utf-8 -*- print u'Español' x = raw_input() Script #2 # -*- coding: utf-8 -*- a = 'Español' a.encode('utf8') print a x = raw_input() Script #1, prints the word fine with no errors, Script #2 does error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 4: ordinal not in range(128) I want to be able to print this variable without errors dynamically as in script #2. the encode('utf8') was mentioned to me as the equivalent of doing u'string' Obviously, it's not because it throws errors. How can I do it folks? A: Change your code to the following: # -*- coding: utf-8 -*- a = 'Español' a = a.decode('utf8') print a x = raw_input() Decode specifies how the string should be read, and returns the value. Making the changes above should fix your problem. The problem is that python stores a string as a list of bytes, regardless of the encoding of the file. What matters is how those bytes are read, and that is what we are doing when we use decode() and u''. A: For script #2: a = 'Español' # In Python2 this is a string of bytes a = a.decode('utf-8') # This converts it to a unicode string print(a)
Substitute for u'string'
I saved my script in UTF-8 encoding. I changed my codepage on windows to 65001. I'm on python 2.6 Script #1 # -*- coding: utf-8 -*- print u'Español' x = raw_input() Script #2 # -*- coding: utf-8 -*- a = 'Español' a.encode('utf8') print a x = raw_input() Script #1, prints the word fine with no errors, Script #2 does error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 4: ordinal not in range(128) I want to be able to print this variable without errors dynamically as in script #2. the encode('utf8') was mentioned to me as the equivalent of doing u'string' Obviously, it's not because it throws errors. How can I do it folks?
[ "Change your code to the following:\n# -*- coding: utf-8 -*-\na = 'Español'\na = a.decode('utf8')\nprint a\nx = raw_input()\n\nDecode specifies how the string should be read, and returns the value. Making the changes above should fix your problem.\nThe problem is that python stores a string as a list of bytes, rega...
[ 8, 5 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0003577561_python_utf_8.txt
Q: In Python, how to add distinct items to a list of dicts from another dict? In Python, the original dict list is as follows: orig = [{'team': 'team1', 'other': 'blah', 'abbrev': 't1'}, {'team': 'team2', 'other': 'blah', 'abbrev': 't2'}, {'team': 'team3', 'other': 'blah', 'abbrev': 't3'}, {'team': 'team1', 'other': 'blah', 'abbrev': 't1'}, {'team': 'team3', 'other': 'blah', 'abbrev': 't3'}] Need to get a new dict list of just team and abbrev but of distinct teams into a list like this: new = [{'team': 'team1', 'abbrev': 't1'}, {'team': 'team2', 'abbrev': 't2'}, {'team': 'team3', 'abbrev': 't3'}] A: dict keys are unique, which you can exploit: teamdict = dict([(data['team'], data) for data in t]) new = [{'team': team, 'abbrev': data['abbrev']} for (team, data) in teamdict.items()] Can't help to suggest that a dict might be your data structure of choice to begin with. Oh, I don't know how dict() reacts to the fact that there are several identical keys in the list. You may have to construct the dictionary less pythonesque in that case: teamdict={} for data in t: teamdict[data['team']] = data implicitly overriding double entries
In Python, how to add distinct items to a list of dicts from another dict?
In Python, the original dict list is as follows: orig = [{'team': 'team1', 'other': 'blah', 'abbrev': 't1'}, {'team': 'team2', 'other': 'blah', 'abbrev': 't2'}, {'team': 'team3', 'other': 'blah', 'abbrev': 't3'}, {'team': 'team1', 'other': 'blah', 'abbrev': 't1'}, {'team': 'team3', 'other': 'blah', 'abbrev': 't3'}] Need to get a new dict list of just team and abbrev but of distinct teams into a list like this: new = [{'team': 'team1', 'abbrev': 't1'}, {'team': 'team2', 'abbrev': 't2'}, {'team': 'team3', 'abbrev': 't3'}]
[ "dict keys are unique, which you can exploit:\nteamdict = dict([(data['team'], data) for data in t])\nnew = [{'team': team, 'abbrev': data['abbrev']} for (team, data) in teamdict.items()]\n\nCan't help to suggest that a dict might be your data structure of choice to begin with.\nOh, I don't know how dict() reacts t...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003577833_python.txt
Q: cPickle.UnpicklingError: invalid load key My program work fine on windows, with cpickle, and I am using binary mode, like 'wb', or 'rb'. When I ran my program on Linux, it still works fine. But when I tried to unpickle the files obtained from the Linux platform on my windows platform, I got this wired message says: cPickle.UnpicklingError: invalid load key' '. Can anyone please tell me why? It seems that I could not unpickle anyfile from the Linux platform. BTW, the two programs that I run are identical. Thanks a million. A: Looking at the code (http://svn.python.org/view/python/trunk/Modules/cPickle.c?revision=81029&view=markup), it looks like it was a parsing error (load key is a pickle format key). It sounds like the file has been altered. How were the files transferred from Linux to Windows? If it was FTP, did you transfer in binary mode? (You are using HIGHEST_PROTOCOL right?)
cPickle.UnpicklingError: invalid load key
My program work fine on windows, with cpickle, and I am using binary mode, like 'wb', or 'rb'. When I ran my program on Linux, it still works fine. But when I tried to unpickle the files obtained from the Linux platform on my windows platform, I got this wired message says: cPickle.UnpicklingError: invalid load key' '. Can anyone please tell me why? It seems that I could not unpickle anyfile from the Linux platform. BTW, the two programs that I run are identical. Thanks a million.
[ "Looking at the code (http://svn.python.org/view/python/trunk/Modules/cPickle.c?revision=81029&view=markup), it looks like it was a parsing error (load key is a pickle format key). It sounds like the file has been altered.\nHow were the files transferred from Linux to Windows? If it was FTP, did you transfer in b...
[ 4 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0003577382_pickle_python.txt
Q: How to print japanese utf-8 on console in windows? #coding=<utf8> import os os.popen('chcp 65001') a = 'こんにちは世界' print a.decode('utf8') x = raw_input() PYTHON 2.6 on Windows 7 It will run in IDLE with no errors. However when run from the console, it errors and flashes very quickly and I can't read the error message. How can it be done in windows console? By the way, doing this with other languages like spanish or portuguese will work fine. It's languages like japanese, russian, greek, hebrew that have this error behavior in the windows console. *EDIT as requested I changed to this code: #coding=<utf8> import os, sys os.popen('chcp 65001') print(sys.stdout.encoding) x = raw_input('press enter to continue') a = 'こんにちは世界' print a.decode('utf8') x = raw_input() It will print: cp437 and then of course, continue on to flash and fail on the decoding bit... It looks like the popen('chcp 65001') doesn't work in changing the codepage. I still don't think this is the root of the problem, however it would be helpful to know an efficient way of changing this codepage. A: Update Never mind. The OP is using Windows. Interestingly changing the encoding declaration to #encoding=<utf8> did not work in Ubuntu. Original Answer This worked for me (Ubuntu Jaunty, Python 2.6.2). The only change I made was to the first line declaring the encoding. # encoding: utf-8 import os os.popen('chcp 65001') a = 'こんにちは世界' print a.decode('utf8') x = raw_input()
How to print japanese utf-8 on console in windows?
#coding=<utf8> import os os.popen('chcp 65001') a = 'こんにちは世界' print a.decode('utf8') x = raw_input() PYTHON 2.6 on Windows 7 It will run in IDLE with no errors. However when run from the console, it errors and flashes very quickly and I can't read the error message. How can it be done in windows console? By the way, doing this with other languages like spanish or portuguese will work fine. It's languages like japanese, russian, greek, hebrew that have this error behavior in the windows console. *EDIT as requested I changed to this code: #coding=<utf8> import os, sys os.popen('chcp 65001') print(sys.stdout.encoding) x = raw_input('press enter to continue') a = 'こんにちは世界' print a.decode('utf8') x = raw_input() It will print: cp437 and then of course, continue on to flash and fail on the decoding bit... It looks like the popen('chcp 65001') doesn't work in changing the codepage. I still don't think this is the root of the problem, however it would be helpful to know an efficient way of changing this codepage.
[ "Update\nNever mind. The OP is using Windows. \nInterestingly changing the encoding declaration to #encoding=<utf8> did not work in Ubuntu.\nOriginal Answer\nThis worked for me (Ubuntu Jaunty, Python 2.6.2). The only change I made was to the first line declaring the encoding.\n# encoding: utf-8 \nimport os\nos.pop...
[ 0 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0003578104_python_utf_8.txt
Q: Selenium, with Python, how to simplify scripts so that I can run them from other python scripts? I'm having some trouble figuring out how to take out what is not necessary in a selenium strip and package it in such a way that I can call it from another script.. I am having trouble understanding what is going on with this, as I don't get where the unit testint parts are coming from... ideally if I could just separate this into a function that I could call that would be idea, thanks for any advice. (AND, yes i do need selenium, I kindly ask that you please don't suggest alternatives as I am going to be using selenium for a lot of things so I need to figure this out) This is just a basic demo script: from selenium import selenium import unittest class TestGoogle(unittest.TestCase): def setUp(self): self.selenium = selenium("localhost", \ 4444, "*firefox", "http://www.bing.com") self.selenium.start() def test_google(self): sel = self.selenium sel.open("http://www.google.com/webhp") sel.type("q", "hello world") sel.click("btnG") sel.wait_for_page_to_load(5000) self.assertEqual("hello world - Google Search", sel.get_title()) def tearDown(self): self.selenium.stop() if __name__ == "__main__": unittest.main() A: What I would recommend is to make functions in your other script that have as an argument a reference to the test case. That way, your functions could fail the test case if something does not go right. Like so (to search google for a string and check the title): def search_s(utest, in_str): s = utest.selenium s.type('q', in_str) s.click('btnG') s.wait_for_page_to_load('30000') utest.assertEqual("%s - Google Search" % (in_str,), s.get_title()) Then, in your test case, call it like this: def test_google(self): s.open('/') search_s(self, "hello world") You can then make libraries of these types of methods, allowing you to mix-and-match pieces of your tests.
Selenium, with Python, how to simplify scripts so that I can run them from other python scripts?
I'm having some trouble figuring out how to take out what is not necessary in a selenium strip and package it in such a way that I can call it from another script.. I am having trouble understanding what is going on with this, as I don't get where the unit testint parts are coming from... ideally if I could just separate this into a function that I could call that would be idea, thanks for any advice. (AND, yes i do need selenium, I kindly ask that you please don't suggest alternatives as I am going to be using selenium for a lot of things so I need to figure this out) This is just a basic demo script: from selenium import selenium import unittest class TestGoogle(unittest.TestCase): def setUp(self): self.selenium = selenium("localhost", \ 4444, "*firefox", "http://www.bing.com") self.selenium.start() def test_google(self): sel = self.selenium sel.open("http://www.google.com/webhp") sel.type("q", "hello world") sel.click("btnG") sel.wait_for_page_to_load(5000) self.assertEqual("hello world - Google Search", sel.get_title()) def tearDown(self): self.selenium.stop() if __name__ == "__main__": unittest.main()
[ "What I would recommend is to make functions in your other script that have as an argument a reference to the test case. That way, your functions could fail the test case if something does not go right. Like so (to search google for a string and check the title):\ndef search_s(utest, in_str):\n s = utest.selenium\...
[ 1 ]
[]
[]
[ "python", "selenium", "unit_testing" ]
stackoverflow_0003577986_python_selenium_unit_testing.txt
Q: mplot3d broken ubuntu 10.04 I'm trying to use mplot3d. I installed matibplot using the Ubuntu (lucid) repositories and it seems broken out-of-the-box. Any help would be appreciated. This is the code I'm running: from __future__ import division from mpl_toolkits.mplot3d import Axes3D from random import * from scipy import * import matplotlib.pyplot as plt locA = mat([0,0,0]) locB = mat([2,0,0]) locC = mat([1,sqrt(3),0]) locD = mat([1,sqrt(3)/2,sqrt(3)]) startLoc = locA points = startLoc n = 10000 x = linspace(1,n,n) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in x: j = randint(1,4) if j < 2: startLoc = (startLoc+locA)/2 points = concatenate((points,startLoc)) elif j < 3: startLoc = (startLoc+locB)/2 points = concatenate((points,startLoc)) elif j < 4: startLoc = (startLoc+locC)/2 points = concatenate((points,startLoc)) else: startLoc = (startLoc+locD)/2 points = concatenate((points,startLoc)) ax.scatter(points[:,0],points[:,1],points[:,2]) plt.show() And this is the error that I get: Traceback (most recent call last): File "triangle_random_3D.py", line 17, in <module> ax = fig.add_subplot(111, projection='3d') File "/usr/lib/pymodules/python2.6/matplotlib/figure.py", line 677, in add_subplot projection_class = get_projection_class(projection) File "/usr/lib/pymodules/python2.6/matplotlib/projections/__init__.py", line 61, in get_projection_class raise ValueError("Unknown projection '%s'" % projection) ValueError: Unknown projection '3d' Thanks. A: First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib. Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib.__version__') I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib. If you're running version 0.99, try doing this: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) Second, the code you posted doesn't work even when mplot3D is set up properly. Try a simpler example. E.g.: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) plt.show() Edit: Actually your posted example code does work with matplotlib 0.99 if you replace ax = fig.add_subplot... with ax = Axes3D(fig). However it doesn't seem work with matplotlib 1.0, either way... Not sure what the problem is...
mplot3d broken ubuntu 10.04
I'm trying to use mplot3d. I installed matibplot using the Ubuntu (lucid) repositories and it seems broken out-of-the-box. Any help would be appreciated. This is the code I'm running: from __future__ import division from mpl_toolkits.mplot3d import Axes3D from random import * from scipy import * import matplotlib.pyplot as plt locA = mat([0,0,0]) locB = mat([2,0,0]) locC = mat([1,sqrt(3),0]) locD = mat([1,sqrt(3)/2,sqrt(3)]) startLoc = locA points = startLoc n = 10000 x = linspace(1,n,n) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in x: j = randint(1,4) if j < 2: startLoc = (startLoc+locA)/2 points = concatenate((points,startLoc)) elif j < 3: startLoc = (startLoc+locB)/2 points = concatenate((points,startLoc)) elif j < 4: startLoc = (startLoc+locC)/2 points = concatenate((points,startLoc)) else: startLoc = (startLoc+locD)/2 points = concatenate((points,startLoc)) ax.scatter(points[:,0],points[:,1],points[:,2]) plt.show() And this is the error that I get: Traceback (most recent call last): File "triangle_random_3D.py", line 17, in <module> ax = fig.add_subplot(111, projection='3d') File "/usr/lib/pymodules/python2.6/matplotlib/figure.py", line 677, in add_subplot projection_class = get_projection_class(projection) File "/usr/lib/pymodules/python2.6/matplotlib/projections/__init__.py", line 61, in get_projection_class raise ValueError("Unknown projection '%s'" % projection) ValueError: Unknown projection '3d' Thanks.
[ "First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib. \nWhich version are you using? (Try running: python -c 'import matplotlib; print matplotlib.__version__')\nI'm guessing you're running version 0.99, in which case you'll need to eithe...
[ 1 ]
[]
[]
[ "matplotlib", "python", "ubuntu_10.04" ]
stackoverflow_0003576875_matplotlib_python_ubuntu_10.04.txt
Q: Does this web app require a task queue? Background I have a web app that will create an image from user input. The image creation could take up to a couple seconds. Problem If I let the server thread, that is handling the request/response also generate the image, that is going to tie up a thread for a couple seconds, and possibly bog down my server, affect performance, kill puppies, etc. Question Should I use a task queue, such as Celery, so that the server can hand off the image creation, and go back to handling requests/responses? I have no problem letting the user who is creating the image wait, but I dont want it to effect other peoples access to the site. A: I'm going to say No - for now. A couple of second is not that long. You'll anyway have to implement some sort of polling (or comet processing) to feed the image back to the user. It will make your system more complex. Design the system so adding on a task queue later on is feasible and easy. So, keep it simple at first and get it working, but Keep in mind that you might add a task queue later. Implement that task queue when/if you need to scale. A: I have an image-generating site as well (Names4Frames) and did things like this via AJAX (and PHP). I haven't had any noticeable slow-downs (or dead puppies), but the site in question doesn't generate huge amounts of traffic either. I am not an expert on threads, and to be honest, I'm not 100% sure what your exact concern is and what technologies you're using... Basically have one page request the image from another page (Perhaps even located on a different server), and when it's done the second page passes back to the first any relevant information about the image for processing/display purposes. If we're only talking about a few seconds, I can't see that being a real problem, unless you're dealing with MASSIVE amounts of visitors constantly using this image creation service. A: rule of thumb: use a queue if tasks could pile up. In your case, the task could take up to 2 seconds, assuming 8hours a day, you could do up to 8*60*60/2 = 14400 images a day without concurrency. If you get over 7200 requests a day, you have a 50% chance of any one of them overlapping. There are more sophisticated analysis to show the expected level of overlapping you're likely to get; but it seems safe to say that you could do over a thousand images a day before getting overloaded. Now the question seems easier: Do you think you'll get more than a thousand or two image creations a day anytime soon? If so, then set a queue; if not, leave it for later. In any case, keep good logs; make sure that you could tell when there's any processing overlap. Remember that once you get two tasks processing concurrently, they'll take longer, increasing probabilities that a third one could arrive before finishing the other two, and a fourth... when you arrive to an invisible threshold, performance will plummet drastically. Don't lose sleep on this, just don't let it happen before you notice.
Does this web app require a task queue?
Background I have a web app that will create an image from user input. The image creation could take up to a couple seconds. Problem If I let the server thread, that is handling the request/response also generate the image, that is going to tie up a thread for a couple seconds, and possibly bog down my server, affect performance, kill puppies, etc. Question Should I use a task queue, such as Celery, so that the server can hand off the image creation, and go back to handling requests/responses? I have no problem letting the user who is creating the image wait, but I dont want it to effect other peoples access to the site.
[ "I'm going to say No - for now.\n\nA couple of second is not that long.\nYou'll anyway have to implement some sort of polling (or comet processing) to feed the image back to the user.\nIt will make your system more complex.\nDesign the system so adding on a task queue later on is feasible and easy.\n\nSo, keep it s...
[ 6, 0, 0 ]
[]
[]
[ "architecture", "celery", "python" ]
stackoverflow_0003578218_architecture_celery_python.txt
Q: Django: Update Field Value Based on Other Fields I am not sure this is even possible without modifying the Admin interface. I have a model called "Quote" that can contain multiple "Product" models. I connect the two using an intermediate model "QuoteIncludes". Here are the three models as they currently stand: class Product(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=200) default_cost = models.DecimalField(max_digits=15, decimal_places=2) default_price = models.DecimalField(max_digits=15, decimal_places=2) shipping_per_unit = models.DecimalField(max_digits=9, decimal_places=2) weight_in_lbs = models.DecimalField(max_digits=5, decimal_places=2) def __unicode__(self): return self.name class Quote(models.Model): ## Human name for easy reference name = models.CharField(max_length=100) items = models.ManyToManyField(Product, through='QuoteIncludes') def __unicode__(self): return self.name class QuoteIncludes(models.Model): ## Attach foreign keys between a Quote and Product product = models.ForeignKey(Product) quote = models.ForeignKey(Quote) ## Additional fields when adding product to a Quote quantity = models.PositiveIntegerField() per_unit_cost = models.DecimalField(max_digits=15, decimal_places=2) per_unit_price = models.DecimalField(max_digits=15, decimal_places=2) def _get_extended_price(self): """Gets extended price by multiplying quantity and unit price.""" if self.quantity and self.per_unit_price: return self.quantity * self.per_unit_price else: return 0.00 extended_price = _get_extended_price What I would like to be able to do is create a Quote in the Admin interface such that when I've filled in both the quantity and the per_unit_price of a line item, it fills in the "extended_price" as a product of the two when I tab over. I think it requires adding some AJAX in there. A: Info on how to include js in your model admin: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions For example: class Media: js = ( 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js', '/media/js/calculate.js', ) And your script could look something like this: function currencyFormat(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2'); } return x1 + x2; } jQuery(document).ready(function($){ $('input[id$=quantity], input[id$=per_unit_cost]').live('keyup', function() { var $tr = $(this).parents('tr'); var quantity = parseInt($tr.find('input[id$=quantity]').val()); var count = parseInt($tr.find('input[id$=per_unit_cost]').val()); if(quantity && count) { $tr.find('input[id$=per_unit_price]').html(currencyFormat(quantity * count)); } }); }); Something like that. Just added the currency format function in case you wanted to use it. A: You won't easily get that field in to the change list there because it belongs to another model from the one being editied. You wil be able to include the through models as an inline below this model, though, and then you could simply write some JS that takes your two input fields and generates the output value you want and plonks it into the appropriate field on the through model that's included in the inline. Or, write a custom view that doesn't lean on the admin ;o)
Django: Update Field Value Based on Other Fields
I am not sure this is even possible without modifying the Admin interface. I have a model called "Quote" that can contain multiple "Product" models. I connect the two using an intermediate model "QuoteIncludes". Here are the three models as they currently stand: class Product(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=200) default_cost = models.DecimalField(max_digits=15, decimal_places=2) default_price = models.DecimalField(max_digits=15, decimal_places=2) shipping_per_unit = models.DecimalField(max_digits=9, decimal_places=2) weight_in_lbs = models.DecimalField(max_digits=5, decimal_places=2) def __unicode__(self): return self.name class Quote(models.Model): ## Human name for easy reference name = models.CharField(max_length=100) items = models.ManyToManyField(Product, through='QuoteIncludes') def __unicode__(self): return self.name class QuoteIncludes(models.Model): ## Attach foreign keys between a Quote and Product product = models.ForeignKey(Product) quote = models.ForeignKey(Quote) ## Additional fields when adding product to a Quote quantity = models.PositiveIntegerField() per_unit_cost = models.DecimalField(max_digits=15, decimal_places=2) per_unit_price = models.DecimalField(max_digits=15, decimal_places=2) def _get_extended_price(self): """Gets extended price by multiplying quantity and unit price.""" if self.quantity and self.per_unit_price: return self.quantity * self.per_unit_price else: return 0.00 extended_price = _get_extended_price What I would like to be able to do is create a Quote in the Admin interface such that when I've filled in both the quantity and the per_unit_price of a line item, it fills in the "extended_price" as a product of the two when I tab over. I think it requires adding some AJAX in there.
[ "Info on how to include js in your model admin:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions\nFor example:\nclass Media:\n js = (\n 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',\n '/media/js/calculate.js',\n )\n\nAnd your script could l...
[ 3, 0 ]
[]
[]
[ "admin", "django", "django_admin", "methods", "python" ]
stackoverflow_0003570898_admin_django_django_admin_methods_python.txt
Q: I can`t decide what to select: ASP.NET MVC 2 (C#) or Django (Python)? I`m learning programming languages. And I decide that I need to lear a new web framework. I have 2 candidates: Django or ASP.NET MVC 2. Can you say me the difference between them and what is so interesting? A: Try both, then decide. A: Well, I'm using both and found both to be state of the art, easy to learn, fast and easy to install. Maybe don't look at it from a technical standpoint but from the context. ASP.NET needs a Windows Server, ASP.NET and an IIS installed. You have the license for that? Django on the other hand is open source runs on cheap but fast linux machines and provides you with the Python Language and it's vast easy to install moduls. If you don't know Python or C# maybe Django is the better way to go. Djangos Documentation is great and has a great tutorial, which is yet to be found on the ASP.NET MVC side. Well, the conclusion is: Try both :) And if you're gonna use ASP.NET MVC, watch the Nerddinner Sessions (PDC) by Scott Hanselman and Phil Haack. A: I would create a small app to try each for a day or two and then choose. I can't speak for Django, but here are some Asp.Net MVC benefits Tight integration with other Microsoft technologies Uses jquery out of the box Choice of several server-side languages Very flexible (choice of unit test framework, view engine, model architecture etc) and a potential negative Might take extra work getting it running on anything other than Windows A: What reasons lead you to choose those two frameworks? What reasons lead you to choose those two languages? If you don't like the answers, then keep looking. Otherwise... Do you want to be on a non-Microsoft web stack? Go Django. Do you want to interface with lots of other Microsoft web stack technologies? Go MVC. Do you want complied language speed? Go C#. Do you want interpreted language portability? Go Python.
I can`t decide what to select: ASP.NET MVC 2 (C#) or Django (Python)?
I`m learning programming languages. And I decide that I need to lear a new web framework. I have 2 candidates: Django or ASP.NET MVC 2. Can you say me the difference between them and what is so interesting?
[ "Try both, then decide.\n", "Well, I'm using both and found both to be state of the art, easy to learn, fast and easy to install. \nMaybe don't look at it from a technical standpoint but from the context. ASP.NET needs a Windows Server, ASP.NET and an IIS installed. You have the license for that? Django on the ot...
[ 4, 2, 1, 1 ]
[]
[]
[ "asp.net_mvc_2", "c#", "django", "python" ]
stackoverflow_0003578822_asp.net_mvc_2_c#_django_python.txt
Q: Invalid syntax problem with Python (running pygame) I've been using The New Boston tutorial (http://www.youtube.com/watch?v=x9M3R6igH2E) on how to program with pygame and I keep getting an "invalid syntax" error on the print self.diff command. Only the self is highlighted. Here is the code (i've bolded the problem): class vector(object): def __init__(self, list1, list2): self.diff=(list2[0]-list1[0], list2[1]-list1[1]) print **self**.diff a =(20.0, 25.0) b =(40.0, 55.0) thing=vector(a,b) A: Python 3? If so, arguments to print must be enclosed in parentheses: print(self.diff). If your learning materials and tutorials are based on the Python 2.x branch, you won't be too lucky with Python 3. Otherwise it's a great choice because it cleans up with many of the issues of the older Python versions.
Invalid syntax problem with Python (running pygame)
I've been using The New Boston tutorial (http://www.youtube.com/watch?v=x9M3R6igH2E) on how to program with pygame and I keep getting an "invalid syntax" error on the print self.diff command. Only the self is highlighted. Here is the code (i've bolded the problem): class vector(object): def __init__(self, list1, list2): self.diff=(list2[0]-list1[0], list2[1]-list1[1]) print **self**.diff a =(20.0, 25.0) b =(40.0, 55.0) thing=vector(a,b)
[ "Python 3? If so, arguments to print must be enclosed in parentheses: print(self.diff).\nIf your learning materials and tutorials are based on the Python 2.x branch, you won't be too lucky with Python 3. Otherwise it's a great choice because it cleans up with many of the issues of the older Python versions.\n" ]
[ 2 ]
[]
[]
[ "python", "syntax", "vector" ]
stackoverflow_0003579144_python_syntax_vector.txt
Q: What is the best solution to bind objects in wx.DC? So, for example I draw some objects on wx.PaintDC, such as lines and rectangles. Now I want next: on mouse click I wont know which object was clicked. Of course, I can see what object is the closest, but what about more exact answer? Maybe even not standart wx.DC, but such things as FloatCanvas or something like this. So, what's the best solution? A: You can use a PseudoDC and its FindObjects method In my drawing program, Whyteboard I employ a whole bunch of maths, polymorphic classes and such to allow users to "hit test" drawn items with the Select drawing tool. You can also do this with FloatCanvas, it provides HitTest(x, y) (off the top of my head) methods that should do what you want. But, I'm not sure how hard it'll be for you to convert your application to use it. A: Does calling event.GetEventObject() in your event handler give you the object you need?
What is the best solution to bind objects in wx.DC?
So, for example I draw some objects on wx.PaintDC, such as lines and rectangles. Now I want next: on mouse click I wont know which object was clicked. Of course, I can see what object is the closest, but what about more exact answer? Maybe even not standart wx.DC, but such things as FloatCanvas or something like this. So, what's the best solution?
[ "You can use a PseudoDC and its FindObjects method\nIn my drawing program, Whyteboard I employ a whole bunch of maths, polymorphic classes and such to allow users to \"hit test\" drawn items with the Select drawing tool.\nYou can also do this with FloatCanvas, it provides HitTest(x, y) (off the top of my head) meth...
[ 1, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003576071_python_user_interface_wxpython.txt
Q: SQLAlchemy override types.DateTime on raw sql expressions is it possible to override the default type.DateTime behaviour when using sqlalchemy with raw sql expressions? for example when using myconnection.execute(text("select * from mytable where mydate > :mydate), {'mydate': mypythondatetimeobject)} , i would like to have type.DateTime to automatically strip the TimeZone from the DateTime object. UPDATE: i found out, that it works by using bindparam and a Typedecorator on the query like this: class MyType(types.TypeDecorator): impl = types.DateTime def process_bind_param(self, value, dialect): if value is not None: return value.replace(tzinfo=None) session.execute( text(myquery, bindparams=[bindparam('mydateparam', type_=MyType())]), {'mydateparam':mydate} ) but i really dont want to use "bindparams" on every query. isnt it possible to simply replace or override the default types.DateTime behaviour somehow? A: If you used SQL expressions based on Table metadata, then you'd just set your MyType on the appropriate columns. The plain text approach loses some convenience. You could stick your MyType into the sqlalchemy.types.type_map keyed to the datetime class, though this is currently not public API. If it were me I'd do: def mytext(stmt, params): bindparams = [] for k, v in params: if isinstance(v, datetime): type_ = MyType() else: type_ = None bindparams.append(bindparam(k, v, type_=type)) return text(stmt, bindparams=bindparams) then just use mytext("select * from table where date=:date", {'date':datetime.today()})
SQLAlchemy override types.DateTime on raw sql expressions
is it possible to override the default type.DateTime behaviour when using sqlalchemy with raw sql expressions? for example when using myconnection.execute(text("select * from mytable where mydate > :mydate), {'mydate': mypythondatetimeobject)} , i would like to have type.DateTime to automatically strip the TimeZone from the DateTime object. UPDATE: i found out, that it works by using bindparam and a Typedecorator on the query like this: class MyType(types.TypeDecorator): impl = types.DateTime def process_bind_param(self, value, dialect): if value is not None: return value.replace(tzinfo=None) session.execute( text(myquery, bindparams=[bindparam('mydateparam', type_=MyType())]), {'mydateparam':mydate} ) but i really dont want to use "bindparams" on every query. isnt it possible to simply replace or override the default types.DateTime behaviour somehow?
[ "If you used SQL expressions based on Table metadata, then you'd just set your MyType on the appropriate columns. The plain text approach loses some convenience. You could stick your MyType into the sqlalchemy.types.type_map keyed to the datetime class, though this is currently not public API.\nIf it were me I'...
[ 1 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0003567131_postgresql_python_sqlalchemy.txt
Q: Using PIL on web hosting machine I want to be able to use the PIL library on a web hosting machine. The machine has Python 2.4.3 installed, but not the PIL library. I tried downloading the PIL source and putting the PIL folder into my directory. It kind of works, except when I need to do some actual image processing, which brings up an ImportError, saying that "The _imaging C module is not installed". Googling this, it seems like I would need to throw an _imaging.so file into the PIL folder, but I couldn't find a precompiled one online. At this point, I'm not sure if I'm even on the right track. What should I do from here? Any help is appreciated. Thanks. A: You need to compile that module. Running the setup.py install command should do it for you, provided the host has a working compiler and the required libraries. You can use virtualenv to have it installed somewhere where you have rights to put files (by default it would try to install it system-wide). If it doesn't have a working compiler and right libraries and header files, then you need to either compile it on another computer with the same architecture and copy it, or find the packages for whatever operating system your host is running and extract the right files from them. By the way, just asking them to install PIL could work too! A: I know this isn't a programmatic answer but ... you should switch webhosts. There is no good reason to be using Python 2.4 and dealing with old stuff when so many problems have been fixed already. I recommend WebFaction but any host running a modern OS/Python installation is fine (Ubuntu is really the easiest at this point).
Using PIL on web hosting machine
I want to be able to use the PIL library on a web hosting machine. The machine has Python 2.4.3 installed, but not the PIL library. I tried downloading the PIL source and putting the PIL folder into my directory. It kind of works, except when I need to do some actual image processing, which brings up an ImportError, saying that "The _imaging C module is not installed". Googling this, it seems like I would need to throw an _imaging.so file into the PIL folder, but I couldn't find a precompiled one online. At this point, I'm not sure if I'm even on the right track. What should I do from here? Any help is appreciated. Thanks.
[ "You need to compile that module. Running the setup.py install command should do it for you, provided the host has a working compiler and the required libraries. You can use virtualenv to have it installed somewhere where you have rights to put files (by default it would try to install it system-wide).\nIf it doesn...
[ 1, 0 ]
[]
[]
[ "python", "python_imaging_library", "web_hosting" ]
stackoverflow_0003560246_python_python_imaging_library_web_hosting.txt
Q: Could someone help me here? Python object maintaining between separate functions I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem. import copy class Obj(object): def __init__(self, name): self.name = name def one(o): print("1: o.name:", o.name) # "foo" obackup = copy.deepcopy(o) o.name = "bar" print("2: o.name:", o.name) # "bar" print("3: obackup.name:", obackup.name) # "foo" o = obackup print("4: o.name:", o.name) # "foo" def two(o): print("5: o.name:", o.name) # "bar"! def main(): o = Obj("foo") one(o) two(o) main() My guess is that o is being overwritten somehow as a local variable to the function one(). But I have no idea how to fix that. A: Forget that the copy module exists, it almost never is needed and often produces surprising results. As soon as you say o = obackup in one() you have created a new binding for the formal argument which then goes out of scope after print('4... A: o is a local variable to the one() so this problem cannot be fixed elegantly. But you could use some reference/pointer which you pass to the one() and two(). Simulating Pointers in Python
Could someone help me here? Python object maintaining between separate functions
I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem. import copy class Obj(object): def __init__(self, name): self.name = name def one(o): print("1: o.name:", o.name) # "foo" obackup = copy.deepcopy(o) o.name = "bar" print("2: o.name:", o.name) # "bar" print("3: obackup.name:", obackup.name) # "foo" o = obackup print("4: o.name:", o.name) # "foo" def two(o): print("5: o.name:", o.name) # "bar"! def main(): o = Obj("foo") one(o) two(o) main() My guess is that o is being overwritten somehow as a local variable to the function one(). But I have no idea how to fix that.
[ "Forget that the copy module exists, it almost never is needed and often produces surprising results.\nAs soon as you say o = obackup in one() you have created a new binding for the formal argument which then goes out of scope after print('4...\n", "o is a local variable to the one() so this problem cannot be fix...
[ 2, 0 ]
[]
[]
[ "oop", "python", "scope" ]
stackoverflow_0003579447_oop_python_scope.txt
Q: How to parse broken XML in Python? A sever I can't influence sends very broken XML. Specifically, a Unicode WHITE STAR would get encoded as UTF-8 (E2 98 86) and then translated using a Latin-1 to HTML entity table. What I get is &acirc; 98 86 (9 bytes) in a file that's declared as utf-8 with no DTD. I couldn't configure W3C tidy in a way that doesn't garble this irreversibly. I only found how to make lxml skip it silently. SAX uses Expat, which cannot recover after encountering this. I'd like to avoid BeautifulSoup for speed reasons. What else is there? A: BeautifulSoup is your best bet in this case. I suggest profiling before ruling out BeautifulSoup altogether. A: Maybe something like: import htmlentitydefs as ents from lxml import etree # or maybe 'html' , if the input is still more broken def repl_ent(m): return ents.entitydefs[m.group()[1:-1]] goodxml = re.sub( '&\w+;', repl_ent, badxml ) etree.fromstring( goodxml )
How to parse broken XML in Python?
A sever I can't influence sends very broken XML. Specifically, a Unicode WHITE STAR would get encoded as UTF-8 (E2 98 86) and then translated using a Latin-1 to HTML entity table. What I get is &acirc; 98 86 (9 bytes) in a file that's declared as utf-8 with no DTD. I couldn't configure W3C tidy in a way that doesn't garble this irreversibly. I only found how to make lxml skip it silently. SAX uses Expat, which cannot recover after encountering this. I'd like to avoid BeautifulSoup for speed reasons. What else is there?
[ "BeautifulSoup is your best bet in this case. I suggest profiling before ruling out BeautifulSoup altogether. \n", "Maybe something like:\nimport htmlentitydefs as ents\nfrom lxml import etree # or maybe 'html' , if the input is still more broken\ndef repl_ent(m): \n return ents.entitydefs[m.group()[1:-1]]\n...
[ 2, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003577652_python_xml.txt
Q: python: complex string algorithm i have a list listcdtitles = [""" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphonic Poem. (NW German Phil./ Kulka) """, """ Puccini, Verdi, Gounod, Bizet: Arias & Duets from Butterfly, Tosca, Boheme, Turandot, I Vespri, Faust, Carmen. (Fiamma Izzo d'Amico & Peter Dvorsky w.Berlin Radio Symph./Paternostro) """, """ Tchaikovsky, 'The Tempest' Fantasy. Liszt, Symphonic Poem #1. (London Symph./Butt) """, """ Duffy, John: 'Heritage: Civilization and the Jews'- Fanfare & Chorale, Symphonic Dances + Orchestral Suite. Bernstein, 'On the Town' Dance Episodes. (Royal Phil./R.Williams) """, """ Lilien, Ignace {1897-1963}: Songs, 1920-1935. (Anja van Wijk, mezzo & Frans van Ruth, piano) """, """ Hindemith, Trauermusik. Purcell, 'Fairy Queen' Suite. Rossini, String Sonata #6. Petrov, 'Creation of the World' Ballet Suite. Bartok, Romanian Folkdances Sz 56. Tartini, Flute Concerto in G {w.A.Maiorov} (Leningrad Orch.for Ancient & Modern Music/ Serov) """, """ Bizet, Verdi, Massenet, Puccini: Arias from Carmen, Rigoletto, Werther, Manon Lescaut, Tosca, Turandot + Songs by Lara, Di Capua et al. (Peter Dvorsky, tenor w.Bratislava Orch./Lenard {Also performing 'Carmen' Overt.& 'Thais' Meditation}. Rec.Live, 10/87) """, """ Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour) """, """ Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting) """, """ Gluck, Mozart, Beethoven, Weber, Verdi, Wagner, Ponchielli, Mascagni, Puccini: Arias from Alceste, Don Giovanni, Fidelio, Oberon, Ballo, Tristan, Walkure, Siegfried, Gotterdammerung, Gioconda, Cavalleria, Tosca. (Helene Wildbrunn. Rec.1919-24) """, """ Stanley, Wesley, Stubley, Boyce, Handel, Heron, Russell, Hook: '18th Century Organ Music on Period Instruments' (Same instruments and artist as above) """, """ Reimann, 'Unrevealed' for Baritone & String Quartet to Texts by Lord Byron {R.Salter w.Kreuzberger Quartet}; Variations for Piano (David Levine) """, """ Bruckner, Symphony #9. (Berlin Philharmonic/ Jochum. Rec. 'live', 11/28/77) """, """ Bruckner, Symphony #5. (Haas Edition. BBC Symph./ Horenstein. Rec.9/71) """, ..............................] i have about 14,000 elements in this list i would like to bunch up those strings together which have similar words. any ideas on how to do this? i dont think there is a right/wrong way thank you so much for any advice A: I'm a newbie to python language but I've written a sample code that calculates similarity scores between entries in that list. The code is as follows. import re import array listcdtitles = [""" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphonic Poem. (NW German Phil./ Kulka) """, """ Puccini, Verdi, Gounod, Bizet: Arias & Duets from Butterfly, Tosca, Boheme, Turandot, I Vespri, Faust, Carmen. (Fiamma Izzo d'Amico & Peter Dvorsky w.Berlin Radio Symph./Paternostro) """, """ Tchaikovsky, 'The Tempest' Fantasy. Liszt, Symphonic Poem #1. (London Symph./Butt) """, """ Duffy, John: 'Heritage: Civilization and the Jews'- Fanfare & Chorale, Symphonic Dances + Orchestral Suite. Bernstein, 'On the Town' Dance Episodes. (Royal Phil./R.Williams) """, """ Lilien, Ignace {1897-1963}: Songs, 1920-1935. (Anja van Wijk, mezzo & Frans van Ruth, piano) """, """ Hindemith, Trauermusik. Purcell, 'Fairy Queen' Suite. Rossini, String Sonata #6. Petrov, 'Creation of the World' Ballet Suite. Bartok, Romanian Folkdances Sz 56. Tartini, Flute Concerto in G {w.A.Maiorov} (Leningrad Orch.for Ancient & Modern Music/ Serov) """, """ Bizet, Verdi, Massenet, Puccini: Arias from Carmen, Rigoletto, Werther, Manon Lescaut, Tosca, Turandot + Songs by Lara, Di Capua et al. (Peter Dvorsky, tenor w.Bratislava Orch./Lenard {Also performing 'Carmen' Overt.& 'Thais' Meditation}. Rec.Live, 10/87) """, """ Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour) """, """ Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting) """, """ Gluck, Mozart, Beethoven, Weber, Verdi, Wagner, Ponchielli, Mascagni, Puccini: Arias from Alceste, Don Giovanni, Fidelio, Oberon, Ballo, Tristan, Walkure, Siegfried, Gotterdammerung, Gioconda, Cavalleria, Tosca. (Helene Wildbrunn. Rec.1919-24) """, """ Stanley, Wesley, Stubley, Boyce, Handel, Heron, Russell, Hook: '18th Century Organ Music on Period Instruments' (Same instruments and artist as above) """, """ Reimann, 'Unrevealed' for Baritone & String Quartet to Texts by Lord Byron {R.Salter w.Kreuzberger Quartet}; Variations for Piano (David Levine) """, """ Bruckner, Symphony #9. (Berlin Philharmonic/ Jochum. Rec. 'live', 11/28/77) """, """ Bruckner, Symphony #5. (Haas Edition. BBC Symph./ Horenstein. Rec.9/71) """] entryDictionary = {} i=0 for entry in listcdtitles: #remove unnecessary characters from the string entry=re.sub(r'[^\w ]', '', entry.lower(), flags=re.IGNORECASE) #split the entry into words and store it in the entryDictionary[i]=entry.split(" ") i=i+1 # print the dictionary print("Entries") print(entryDictionary) # define a score matrix, compare the words in each entry and if # a word is same in both entries, that is one point scoreMatrix = [] for k in range(i): scoreMatrix.append([]) for j in range (i): if j>k: scoreMatrix[k].append(0) else: scoreMatrix[k].append("-") k=0 j=0 for k in range(i-1): entry1 = entryDictionary[k] for j in range(k+1,i): entry2 = entryDictionary[j] for kk in range(len(entry1)): for jj in range(len(entry2)): if entry1[kk] != "" and entry1[kk] == entry2[jj]: scoreMatrix[k][j] = scoreMatrix[k][j] + 1 print "Score Matrix (Higher numbers denote heigher similarity between two entries" print repr("").rjust(10), for k in range(i-1): print repr("Entry " + str(k)).rjust(10), print repr("Entry " + str(i-1)).rjust(10) for k in range(i): scoreMatrix.append([]) print repr("Entry " + str(k)).rjust(10), for j in range (i-1): print repr(scoreMatrix[k][j]).rjust(10), print repr(scoreMatrix[k][i-1]).rjust(10) The result is as follows: Score Matrix (Higher numbers denote higher similarity between two entries '' 'Entry 0' 'Entry 1' 'Entry 2' 'Entry 3' 'Entry 4' 'Entry 5' 'Entry 6' 'Entry 7' 'Entry 8' 'Entry 9' 'Entry 10' 'Entry 11' 'Entry 12' 'Entry 13' 'Entry 0' '-' 2 3 2 0 1 1 0 1 1 0 0 0 0 'Entry 1' '-' '-' 0 0 0 0 11 0 2 5 0 0 0 0 'Entry 2' '-' '-' '-' 3 0 1 0 1 0 0 0 0 0 0 'Entry 3' '-' '-' '-' '-' 0 4 0 2 0 0 2 0 0 0 'Entry 4' '-' '-' '-' '-' '-' 0 1 0 0 0 0 1 0 0 'Entry 5' '-' '-' '-' '-' '-' '-' 0 3 1 0 1 1 0 0 'Entry 6' '-' '-' '-' '-' '-' '-' '-' 0 2 5 0 1 0 0 'Entry 7' '-' '-' '-' '-' '-' '-' '-' '-' 0 0 0 0 0 0 'Entry 8' '-' '-' '-' '-' '-' '-' '-' '-' '-' 2 0 0 0 0 'Entry 9' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' 0 0 0 0 'Entry 10' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' 0 0 0 'Entry 11' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' 0 0 'Entry 12' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' 2 'Entry 13' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' '-' A: First of all, parse all that and associate each token to a frequency. Tokens with high frequency will have to be blacklisted. Then you'll have to compare strings, iterating over them, and associating the tuple to a distance score. According to this score, you'll concatenate them - or not. That would be a simple method to do that.
python: complex string algorithm
i have a list listcdtitles = [""" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphonic Poem. (NW German Phil./ Kulka) """, """ Puccini, Verdi, Gounod, Bizet: Arias & Duets from Butterfly, Tosca, Boheme, Turandot, I Vespri, Faust, Carmen. (Fiamma Izzo d'Amico & Peter Dvorsky w.Berlin Radio Symph./Paternostro) """, """ Tchaikovsky, 'The Tempest' Fantasy. Liszt, Symphonic Poem #1. (London Symph./Butt) """, """ Duffy, John: 'Heritage: Civilization and the Jews'- Fanfare & Chorale, Symphonic Dances + Orchestral Suite. Bernstein, 'On the Town' Dance Episodes. (Royal Phil./R.Williams) """, """ Lilien, Ignace {1897-1963}: Songs, 1920-1935. (Anja van Wijk, mezzo & Frans van Ruth, piano) """, """ Hindemith, Trauermusik. Purcell, 'Fairy Queen' Suite. Rossini, String Sonata #6. Petrov, 'Creation of the World' Ballet Suite. Bartok, Romanian Folkdances Sz 56. Tartini, Flute Concerto in G {w.A.Maiorov} (Leningrad Orch.for Ancient & Modern Music/ Serov) """, """ Bizet, Verdi, Massenet, Puccini: Arias from Carmen, Rigoletto, Werther, Manon Lescaut, Tosca, Turandot + Songs by Lara, Di Capua et al. (Peter Dvorsky, tenor w.Bratislava Orch./Lenard {Also performing 'Carmen' Overt.& 'Thais' Meditation}. Rec.Live, 10/87) """, """ Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour) """, """ Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting) """, """ Gluck, Mozart, Beethoven, Weber, Verdi, Wagner, Ponchielli, Mascagni, Puccini: Arias from Alceste, Don Giovanni, Fidelio, Oberon, Ballo, Tristan, Walkure, Siegfried, Gotterdammerung, Gioconda, Cavalleria, Tosca. (Helene Wildbrunn. Rec.1919-24) """, """ Stanley, Wesley, Stubley, Boyce, Handel, Heron, Russell, Hook: '18th Century Organ Music on Period Instruments' (Same instruments and artist as above) """, """ Reimann, 'Unrevealed' for Baritone & String Quartet to Texts by Lord Byron {R.Salter w.Kreuzberger Quartet}; Variations for Piano (David Levine) """, """ Bruckner, Symphony #9. (Berlin Philharmonic/ Jochum. Rec. 'live', 11/28/77) """, """ Bruckner, Symphony #5. (Haas Edition. BBC Symph./ Horenstein. Rec.9/71) """, ..............................] i have about 14,000 elements in this list i would like to bunch up those strings together which have similar words. any ideas on how to do this? i dont think there is a right/wrong way thank you so much for any advice
[ "I'm a newbie to python language but I've written a sample code that calculates similarity scores between entries in that list.\nThe code is as follows. \nimport re\nimport array\n\nlistcdtitles = [\"\"\" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphon...
[ 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003570959_python_string.txt
Q: SQL to handle table updates in a "dynamically typed" fashion I'm playing around with Python 3's sqlite3 module, and acquainting myself with SQL in the process. I've written a toy program to hash a salted password and store it, the associated username, and the salt into a database. I thought it would be intuitive to create a function of the signature: def store(table, data, database=':memory:') Callable as, for example, store('logins', {'username': 'bob', 'salt': 'foo', 'salted_hash' : 'bar'}), and be able to individually add into logins, into new a row, the value bob for username, foo for salt, et caetera. Unfortunately I'm swamped with what SQL to code. I'm trying to do this in a "dynamically typed" fashion, in that I won't be punished for storing the wrong types, or be able to add new columns at will, for example. I want the function to, sanitizing all input: Check if the table exists, and create it if it doesn't, with the passed keys from the dictionary as the columns; If the table already exists, check if a table has the specified columns (the keys to the passed dictionary), and add them if it doesn't (is this even possible with SQL?); Add the individual values from my dictionary to the appropriate columns in the dictionary. I can use INSERT for the latter, but it seems very rigid. What happens if the columns don't exist, for example? How could we then add them? I don't mind whether the code is tailored to Python 3's sqlite3, or just the SQL as an outline; as long as I can work it and use it to some extent (and learn from it) I'm very grateful. (On a different note, I'm wondering what other approaches I could use instead of a SQL'd relational database; I've used Amazon's SimpleDB before and have considered using that for this purpose as it was very "dynamically typed", but I want to know what SQL code I'd have to use for this purpose.) A: SQLite3 is dynamically typed, so no problem there. CREATE TABLE IF NOT EXISTS <name> ... See here. You can see if the columns you need already exist in the table by using sqlite_master documented in this FAQ. You'll need to parse the sql column, but since it's exactly what your program provided to create the table, you should know the syntax. If the column does not exist, you can ALTER TABLE <nam>? ADD COLUMN ... See here.
SQL to handle table updates in a "dynamically typed" fashion
I'm playing around with Python 3's sqlite3 module, and acquainting myself with SQL in the process. I've written a toy program to hash a salted password and store it, the associated username, and the salt into a database. I thought it would be intuitive to create a function of the signature: def store(table, data, database=':memory:') Callable as, for example, store('logins', {'username': 'bob', 'salt': 'foo', 'salted_hash' : 'bar'}), and be able to individually add into logins, into new a row, the value bob for username, foo for salt, et caetera. Unfortunately I'm swamped with what SQL to code. I'm trying to do this in a "dynamically typed" fashion, in that I won't be punished for storing the wrong types, or be able to add new columns at will, for example. I want the function to, sanitizing all input: Check if the table exists, and create it if it doesn't, with the passed keys from the dictionary as the columns; If the table already exists, check if a table has the specified columns (the keys to the passed dictionary), and add them if it doesn't (is this even possible with SQL?); Add the individual values from my dictionary to the appropriate columns in the dictionary. I can use INSERT for the latter, but it seems very rigid. What happens if the columns don't exist, for example? How could we then add them? I don't mind whether the code is tailored to Python 3's sqlite3, or just the SQL as an outline; as long as I can work it and use it to some extent (and learn from it) I'm very grateful. (On a different note, I'm wondering what other approaches I could use instead of a SQL'd relational database; I've used Amazon's SimpleDB before and have considered using that for this purpose as it was very "dynamically typed", but I want to know what SQL code I'd have to use for this purpose.)
[ "\nSQLite3 is dynamically typed, so no problem there.\nCREATE TABLE IF NOT EXISTS <name> ... See here.\nYou can see if the columns you need already exist in the table by using sqlite_master documented in this FAQ. You'll need to parse the sql column, but since it's exactly what your program provided to create the t...
[ 1 ]
[]
[]
[ "python", "python_3.x", "sql", "sqlite" ]
stackoverflow_0003577324_python_python_3.x_sql_sqlite.txt
Q: Display GAE list by most recent entry n00b problem- I am trying to have a list show the most recent entry first. This works without the reverse(), but retrieves nothing with it in. I have heard I should try and use order_by(), but I can't seem to get that to work either. Thanks for the help! class MainHandler(webapp.RequestHandler): def get(self): que = db.Query(models.URL) url_list = que.fetch(limit=100) new_list = url_list.reverse() path = self.request.path if doRender(self,path): return doRender(self,'base/index.html', { 'new_list' : new_list }) A: In django, you use order_by(), but for GAE it is order(). So the answer was not in using reverse but: class MainHandler(webapp.RequestHandler): def get(self): que = db.Query(models.URL).order('-created') url_list = que.fetch(limit=100) path = self.request.path if doRender(self,path): return doRender(self,'base/index.html', { 'url_list' : url_list }) A: Keys aren't automatically in incrementing order; if you want to sort by the date an entity was added, you need to add a DateTimeProperty with auto_now_add set to True, and sort on that. A: reverse() modifies the list in place. It doesn't return the sorted list, so just do: url_list.reverse() path = self.request.path if doRender(self,path): return doRender(self,'base/index.html', { 'new_list' : url_list })
Display GAE list by most recent entry
n00b problem- I am trying to have a list show the most recent entry first. This works without the reverse(), but retrieves nothing with it in. I have heard I should try and use order_by(), but I can't seem to get that to work either. Thanks for the help! class MainHandler(webapp.RequestHandler): def get(self): que = db.Query(models.URL) url_list = que.fetch(limit=100) new_list = url_list.reverse() path = self.request.path if doRender(self,path): return doRender(self,'base/index.html', { 'new_list' : new_list })
[ "In django, you use order_by(), but for GAE it is order().\nSo the answer was not in using reverse but:\nclass MainHandler(webapp.RequestHandler):\ndef get(self):\n\n que = db.Query(models.URL).order('-created')\n url_list = que.fetch(limit=100)\n\n path = self.request.path \n if doRender(self,pa...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003577910_google_app_engine_python.txt
Q: How do I restore default settings of an application in Gtk (set all the widgets to the state as if the application was restarted)? I would like to implement a button "New" that would work the same as File>New in most applications - that is: resets all the labels, treeviews, etc. to the original state. Thank you, Tomas A: The widgets don't remember their original state; you have to set them all back one by one. Give labels their original text, clear the tree views by setting their model to None. Perhaps it is better to destroy your window and rebuild it from your Glade file if you have one?
How do I restore default settings of an application in Gtk (set all the widgets to the state as if the application was restarted)?
I would like to implement a button "New" that would work the same as File>New in most applications - that is: resets all the labels, treeviews, etc. to the original state. Thank you, Tomas
[ "The widgets don't remember their original state; you have to set them all back one by one. Give labels their original text, clear the tree views by setting their model to None.\nPerhaps it is better to destroy your window and rebuild it from your Glade file if you have one?\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003577335_gtk_pygtk_python.txt
Q: Web gateway interfaces in Python 3 I've finally concluded that I can no longer afford to just hope the ongoing Py3k/WSGI disasterissues will be resolved anytime soon, so I need to get ready to move on. Unfortunately, my available options don't seem a whole lot better: While I find a few different Python modules for FastCGI scattered around the web, none of them seem to be getting much (if any) attention and/or maintenance, particularly with regard to Python 3.x, and it's difficult to distinguish which, if any, are really viable. Falling all the way back to the built-in CGI module is hardly better than building something myself from scratch (worse, there's an important bug or two in there that may not get attention until Python 3.3). There is no higher sin than handling HTTP directly in a production webapp. And anyway, that's still reinventing the wheel. Surely somebody out there is deploying webapps on 3.x in production. What gateway interface are you using, with which module/libraries, and why? A: CherryPy 3.2 release candidates support Python 3.X. Because it only supports WSGI at the web server interface layer and not through the whole stack, then you are isolated from issues as to whether WSGI will change. CherryPy has its own internal WSGI server, but also can run under Apache/mod_wsgi with Python 3.1+. See: http://www.cherrypy.org/wiki/WhatsNewIn32 http://code.google.com/p/modwsgi/wiki/SupportForPython3X A: bottle supports Python 3, but it suffers from the broken stdlib. However, multipart reimplements cgi.FieldStorage and can be used with bottle to build a Python 3 WSGI web app. I just published a demo. For the moment it is just a test, but as far as I can tell it works well.
Web gateway interfaces in Python 3
I've finally concluded that I can no longer afford to just hope the ongoing Py3k/WSGI disasterissues will be resolved anytime soon, so I need to get ready to move on. Unfortunately, my available options don't seem a whole lot better: While I find a few different Python modules for FastCGI scattered around the web, none of them seem to be getting much (if any) attention and/or maintenance, particularly with regard to Python 3.x, and it's difficult to distinguish which, if any, are really viable. Falling all the way back to the built-in CGI module is hardly better than building something myself from scratch (worse, there's an important bug or two in there that may not get attention until Python 3.3). There is no higher sin than handling HTTP directly in a production webapp. And anyway, that's still reinventing the wheel. Surely somebody out there is deploying webapps on 3.x in production. What gateway interface are you using, with which module/libraries, and why?
[ "CherryPy 3.2 release candidates support Python 3.X. Because it only supports WSGI at the web server interface layer and not through the whole stack, then you are isolated from issues as to whether WSGI will change. CherryPy has its own internal WSGI server, but also can run under Apache/mod_wsgi with Python 3.1+. ...
[ 2, 1 ]
[]
[]
[ "fastcgi", "python", "python_3.x", "wsgi" ]
stackoverflow_0003476481_fastcgi_python_python_3.x_wsgi.txt
Q: Behavior of Python exec() differs depending on the where it is called from I have a Python script 'runme.py' that I am trying to execute from 'callerX.py' below. I am using exec(open(filename).read()) to accomplish this task. The script being executed contains a simple class that attempts to call the 'time()' function both from the global namespace & inside a function. In all of the examples below, we are executing the following file using exec(): # runme.py # this code is being exec()'d by the stand-alone examples 1-3 below: from time import * class MyClass(): def main(self): print("Local tracepoint 1") t = time() print("Local tracepoint 2") mc = MyClass() print("Tracepoint 1") gt = time() print("Tracepoint 2") mc.main() print("Tracepoint 3") caller1.py: (this works properly, the 'time' function can be used within MyClass.main()) print("Run from main scope:") exec(open("runme.py").read()) caller2.py: (this does not work, fails with the Exception "NameError: global name 'time' is not defined" inside MyClass.main()) def Run(): exec(open("runme.py").read()) print("Run from function:") Run() caller3.py: (this works properly, both exec()s run without Exceptions) def Run(): exec(open("runme.py").read()) print("Run from main scope:") exec(open("runme.py").read()) print("Run from function:") Run() Note that in the examples above, the calls to the time() function in the global namespace of 'runme.py' always work, and the calls to the time() function from MyClass.main() only sometimes work, depending on whether or not the file runme.py was exec()'d from within a function. If we call exec() from outside a function (caller1.py), it works. If we call exec() from inside a function (caller2.py), it fails with an Exception. If we call exec() from outside a function and subsequently from inside a function (caller3.py), both calls to exec() run without an Exception. This behavior seems inconsistent. Any ideas? I know this is a contrived example, however, it was distilled from a much more complicated program that has requirements that have brought us to this juncture. A: This has probably to do with how 'from x import *' works. If you call this from 'top-level', it gets imported into globals() for the whole module. However, if you call this inside a function, it gets imported only into locals() - in the function. The exec() gets evaluated inside a function in caller2; therefore the import * doesn't get into globals() and the 'inner' main function doesn't see it. BTW: it is intersting that if you try code like this: def run(): from time import * def test(): print time() test() run() You will get an exception: SyntaxError: import * is not allowed in function 'run' because it is contains a nested function with free variables But that is precisely what you are doing with the exec, but it somehow surprisingly sneaks through. However - considering the other answer here - why don't you use something other instead? Look at the 'imp' module documentation - in particular functions find_module and load_module.
Behavior of Python exec() differs depending on the where it is called from
I have a Python script 'runme.py' that I am trying to execute from 'callerX.py' below. I am using exec(open(filename).read()) to accomplish this task. The script being executed contains a simple class that attempts to call the 'time()' function both from the global namespace & inside a function. In all of the examples below, we are executing the following file using exec(): # runme.py # this code is being exec()'d by the stand-alone examples 1-3 below: from time import * class MyClass(): def main(self): print("Local tracepoint 1") t = time() print("Local tracepoint 2") mc = MyClass() print("Tracepoint 1") gt = time() print("Tracepoint 2") mc.main() print("Tracepoint 3") caller1.py: (this works properly, the 'time' function can be used within MyClass.main()) print("Run from main scope:") exec(open("runme.py").read()) caller2.py: (this does not work, fails with the Exception "NameError: global name 'time' is not defined" inside MyClass.main()) def Run(): exec(open("runme.py").read()) print("Run from function:") Run() caller3.py: (this works properly, both exec()s run without Exceptions) def Run(): exec(open("runme.py").read()) print("Run from main scope:") exec(open("runme.py").read()) print("Run from function:") Run() Note that in the examples above, the calls to the time() function in the global namespace of 'runme.py' always work, and the calls to the time() function from MyClass.main() only sometimes work, depending on whether or not the file runme.py was exec()'d from within a function. If we call exec() from outside a function (caller1.py), it works. If we call exec() from inside a function (caller2.py), it fails with an Exception. If we call exec() from outside a function and subsequently from inside a function (caller3.py), both calls to exec() run without an Exception. This behavior seems inconsistent. Any ideas? I know this is a contrived example, however, it was distilled from a much more complicated program that has requirements that have brought us to this juncture.
[ "This has probably to do with how 'from x import *' works. If you call this from 'top-level', it gets imported into globals() for the whole module.\nHowever, if you call this inside a function, it gets imported only into locals() - in the function. The exec() gets evaluated inside a function in caller2; therefore t...
[ 0 ]
[ "Here's an idea: don't use exec. Basically every time I've seen someone use exec or eval it's because they don't know that a better way to accomplish the same thing already exists; it's a crutch that hinders writing dynamic code, not a way to write code that's somehow more dynamic.\n" ]
[ -1 ]
[ "exec", "python", "scope" ]
stackoverflow_0003578573_exec_python_scope.txt
Q: mod_wsgi not working with pinax of django I tried hard to configure mod_wsgi for an pinax project. I followed the exact instructions from the site (pinaxproject.org), unfortunately, I always got the following error: [Thu Aug 26 17:32:46 2010] [error] [client 173.48.119.55] (13)Permission denied: mod_wsgi (pid=26749): Unable to connect to WSGI daemon process 'www.mysiste.com-production' on '/etc/httpd/logs/wsgi.26745.0.1.sock' after multiple attempts. here is the code: LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost xx.xxx.xxx.xx:80> ServerName mysite.com ServerAlias www.mysite.com ServerAdmin mymailg@yahoo.com WSGIDaemonProcess www.mysite.com-production python-path=/usr/pinax/pinax-env/lib/python2.6/site-packages WSGIProcessGroup www.mysite.com-production WSGIScriptAlias / /usr/pinax/newsino/deploy/pinax.wsgi <Directory /usr/pinax/newsino/deploy> Order deny,allow Allow from all </Directory> Alias /robots.txt /srv/www/newsino/public_html/robots.txt Alias /favicon.ico /srv/www/newsino/public_html/favicon.ico Alias /images /srv/www/newsino/public_html/images Alias /static /srv/www/newsino/public_html/static ErrorLog /srv/www/newsino/logs/error.log CustomLog /srv/www/newsino/logs/access.log combined </VirtualHost> A: Read: http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets Setup WSGISocketPrefix directive as indicated.
mod_wsgi not working with pinax of django
I tried hard to configure mod_wsgi for an pinax project. I followed the exact instructions from the site (pinaxproject.org), unfortunately, I always got the following error: [Thu Aug 26 17:32:46 2010] [error] [client 173.48.119.55] (13)Permission denied: mod_wsgi (pid=26749): Unable to connect to WSGI daemon process 'www.mysiste.com-production' on '/etc/httpd/logs/wsgi.26745.0.1.sock' after multiple attempts. here is the code: LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost xx.xxx.xxx.xx:80> ServerName mysite.com ServerAlias www.mysite.com ServerAdmin mymailg@yahoo.com WSGIDaemonProcess www.mysite.com-production python-path=/usr/pinax/pinax-env/lib/python2.6/site-packages WSGIProcessGroup www.mysite.com-production WSGIScriptAlias / /usr/pinax/newsino/deploy/pinax.wsgi <Directory /usr/pinax/newsino/deploy> Order deny,allow Allow from all </Directory> Alias /robots.txt /srv/www/newsino/public_html/robots.txt Alias /favicon.ico /srv/www/newsino/public_html/favicon.ico Alias /images /srv/www/newsino/public_html/images Alias /static /srv/www/newsino/public_html/static ErrorLog /srv/www/newsino/logs/error.log CustomLog /srv/www/newsino/logs/access.log combined </VirtualHost>
[ "Read:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets\nSetup WSGISocketPrefix directive as indicated.\n" ]
[ 0 ]
[]
[]
[ "django", "mod_wsgi", "pinax", "python", "web_deployment_project" ]
stackoverflow_0003579850_django_mod_wsgi_pinax_python_web_deployment_project.txt
Q: Issues w/ Widget.hide() Problem: Widget 'A' is a toplevel window that is displayed after a button click in MainWindow 'B'. How do I assign a handler to handle the signal sent back after the 'X' along the window border of Widget 'A' is clicked (see below for current implementation)? def on_mainWindow_B_button_clicked(self, widget): self.widget_a.show() def on_widget_a_destroy(self, widget): #this is the handler I have right now yet after it's called and widget.a closes and 'on_mainWindow_B_button_clicked' is called for the second time none of widget.a's children appear in the new window widget.hide() A: The handler for the delete_event signal must return True in order to stop the Window being permanently destroyed on closing. self.widget_a.connect('delete_event', self.on_widget_a_delete) def on_widget_a_delete(self, widget, event): widget.hide() # do something return True If you only want to have the window hide, there's a builtin shortcut you can use: self.widget_a.connect('delete_event', self.widget_a.hide_on_delete)
Issues w/ Widget.hide()
Problem: Widget 'A' is a toplevel window that is displayed after a button click in MainWindow 'B'. How do I assign a handler to handle the signal sent back after the 'X' along the window border of Widget 'A' is clicked (see below for current implementation)? def on_mainWindow_B_button_clicked(self, widget): self.widget_a.show() def on_widget_a_destroy(self, widget): #this is the handler I have right now yet after it's called and widget.a closes and 'on_mainWindow_B_button_clicked' is called for the second time none of widget.a's children appear in the new window widget.hide()
[ "The handler for the delete_event signal must return True in order to stop the Window being permanently destroyed on closing.\n self.widget_a.connect('delete_event', self.on_widget_a_delete)\n\ndef on_widget_a_delete(self, widget, event):\n widget.hide()\n # do something\n return True\n\nIf you only wan...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003580469_gtk_pygtk_python.txt
Q: Do Python regexes support something like Perl's \G? I have a Perl regular expression (shown here, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do? A: Try these: import re re.sub() re.findall() re.finditer() for example: # Finds all words of length 3 or 4 s = "the quick brown fox jumped over the lazy dogs." print re.findall(r'\b\w{3,4}\b', s) # prints ['the','fox','over','the','lazy','dogs'] A: Python does not have the /g modifier for their regexen, and so do not have the \G regex token. A pity, really. A: You can use re.match to match anchored patterns. re.match will only match at the beginning (position 0) of the text, or where you specify. def match_sequence(pattern,text,pos=0): pat = re.compile(pattern) match = pat.match(text,pos) while match: yield match if match.end() == pos: break # infinite loop otherwise pos = match.end() match = pat.match(text,pos) This will only match pattern from the given position, and any matches that follow 0 characters after. >>> for match in match_sequence(r'[^\W\d]+|\d+',"he11o world!"): ... print match.group() ... he 11 o A: I know I'm little late, but here's an alternative to the \G approach: import re def replace(match): if match.group(0)[0] == '/': return match.group(0) else: return '<' + match.group(0) + '>' source = '''http://a.com http://b.com //http://etc.''' pattern = re.compile(r'(?m)^//.*$|http://\S+') result = re.sub(pattern, replace, source) print(result) output (via Ideone): <http://a.com> <http://b.com> //http://etc. The idea is to use a regex that matches both kinds of string: a URL or a commented line. Then you use a callback (delegate, closure, embedded code, etc.) to find out which one you matched and return the appropriate replacement string. As a matter of fact, this is my preferred approach even in flavors that do support \G. Even in Java, where I have to write a bunch of boilerplate code to implement the callback. (I'm not a Python guy, so forgive me if the code is terribly un-pythonic.) A: Don't try to put everything into one expression as it become very hard to read, translate (as you see for yourself) and maintain. import re lines = [re.sub(r'http://[^\s]+', r'<\g<0>>', line) for line in text_block.splitlines() if not line.startedwith('//')] print '\n'.join(lines) Python is not usually best when you literally translate from Perl, it has it's own programming patterns.
Do Python regexes support something like Perl's \G?
I have a Perl regular expression (shown here, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?
[ "Try these:\nimport re\nre.sub()\nre.findall()\nre.finditer()\n\nfor example:\n# Finds all words of length 3 or 4\ns = \"the quick brown fox jumped over the lazy dogs.\"\nprint re.findall(r'\\b\\w{3,4}\\b', s)\n\n# prints ['the','fox','over','the','lazy','dogs']\n\n", "Python does not have the /g modifier for the...
[ 4, 4, 2, 2, 0 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0000529830_perl_python_regex.txt
Q: PyGTK: Parent window wait until child window is showed I'm learning PyGTK and I have a parent window and a child window. Inside of a parent window's method, i create the child window and then I refresh a treeview... something like that: def add_user(self, widget, data = None): save_user.SaveUser(self.window) self.load_tree_view() But, when it's running, the child window appears and the load_tree_view() method is executed. I want that parent window wait until the child window is opened/showed. After that, load_tree_view runs ... How can I do that? Thank you. A: gtk.Dialog solves my problem but i don't know if is right use that ... When should I use a dialog? #! /usr/bin/python import pygtk import gtk class Window: def __init__(self): self.window = gtk.Window() self.window.connect('delete-event', self.close_window) self.window.show() self.dialog = gtk.Dialog() self.dialog.connect('delete-event', self.close_dialog) self.dialog.run() print 'after dialog...' gtk.main() def close_window(self, widget, data = None): gtk.main_quit() def close_dialog(self, widget, data = None): self.dialog.hide() if __name__ == '__main__': Window() "print 'after dialog...'" code only appears after when the dialog is closed. That is what I want. Thank you.
PyGTK: Parent window wait until child window is showed
I'm learning PyGTK and I have a parent window and a child window. Inside of a parent window's method, i create the child window and then I refresh a treeview... something like that: def add_user(self, widget, data = None): save_user.SaveUser(self.window) self.load_tree_view() But, when it's running, the child window appears and the load_tree_view() method is executed. I want that parent window wait until the child window is opened/showed. After that, load_tree_view runs ... How can I do that? Thank you.
[ "gtk.Dialog solves my problem but i don't know if is right use that ... When should I use a dialog?\n#! /usr/bin/python\n\nimport pygtk\nimport gtk\n\nclass Window:\n def __init__(self):\n self.window = gtk.Window()\n self.window.connect('delete-event', self.close_window)\n self.window.show(...
[ 0 ]
[]
[]
[ "methods", "oop", "pygtk", "python", "windows" ]
stackoverflow_0003579641_methods_oop_pygtk_python_windows.txt
Q: Sorting list of dictionaries according to specific order I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc), but not in the same order as the original list. I now need to re-sort this list of dictionaries so that the documents are in the order that their IDs were in the first list. What's the best way of doing this? A: Don't. Move your "list of dictionaries (one for each doc), but not in the same order as the original list" into a dictionary. This new dictionary-of-dictionaries has the matching key. Then go through your first list in it's order and find items in the dictionary-of-dictionaries that match. some_list= query_data_store_1() some_other_list= query_data_store_2( some_list ) dict_of_dict = dict( (d['key'], d) for d in some_other_list ) for item in some_list: other_item = dict_of_dict[ item['key'] ] # Now you have item from the first list matching item from the second list. # And it's in order by the first list. A: You could build a separate dictionary mapping ids to positions and use that to order the documents: ids = ... positions = {} for pos, id in enumerate(ids): positions[id] = pos docs = ... docs.sort(key=lambda doc: positions[doc['id']]) A: The best (and general) solution seems to be given here: reordering list of dicts arbitrarily in python
Sorting list of dictionaries according to specific order
I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc), but not in the same order as the original list. I now need to re-sort this list of dictionaries so that the documents are in the order that their IDs were in the first list. What's the best way of doing this?
[ "Don't.\nMove your \"list of dictionaries (one for each doc), but not in the same order as the original list\" into a dictionary.\nThis new dictionary-of-dictionaries has the matching key.\nThen go through your first list in it's order and find items in the dictionary-of-dictionaries that match.\nsome_list= query_d...
[ 4, 1, 0 ]
[]
[]
[ "dictionary", "mapping", "python", "sorting" ]
stackoverflow_0003559960_dictionary_mapping_python_sorting.txt
Q: Python permanent assignment variables I have just started python and came across something kind of strange. The following code assigns a co-ordinate of x=1 and y=2 to the variable test. The test2 variable assigns itself the same value as test and then the [x] value for test2 is changed to the old [x] value minus 1. This works fine, however, when the last part is executed, not only does it minus 1 from the [x] value in test2, it does the same to the [x] value in the test variable too. test = [1,2]; test2 = test; test2[1] = test2[1] - 1; I found doing the following worked fine but I still don't understand why the first method changes the test value as well as the test2 value. test = [1,2]; test2 = test; test2 = [test2[0] -1 ,test2[1]]; Could someone please explain why this happens. Thank You TheLorax A: In Python, like in Java, assignment per se never makes a copy -- rahter, assignment adds another reference to the same object as the right-hand side of the =. (Argument passing works the same way). Strange that you've never heard of the concept, when Python is quite popular and Java even much more so (and many other languages tend to work similarly, possibly with more complications or distinguos). When you want a copy, you ask for a copy (as part of the expression that is on the right-hand side, or gets used to get the argument you're passing)! In Python, depending on your exact purposes, there are several ways -- the copy module of the standard library being a popular ones (with functions copy, for "shallow" copies, and deepcopy -- for "deep" copies, of course, i.e., ones where, not just the container, but every contained item, also gets deep copied recursively). Often, though, what you want is "a new list" -- whether the original sequence is a list, a copy, or something else that's iterable, you may not care: you want a new list instance, whose items are the same as those of "something else". The perfect way to express this is to use list(somethingelse) -- call the list type, which always makes a new instance of list, and give it as an argument the iterable whose items you want in the new list. Similarly, dict(somemapping) makes a new dict, and set(someiterable) makes a new set -- calling a type to make a new instance of that type is a very general and useful concept! A: It's because when you do test2 = test you are not copying the contents of the list, but simply assigning test2 a reference to the original list. Thus, any changes to the test2 will also affect test. The right way to do this is using deepcopy() from the copy module (or copy() if you can get away with a shallow copy. import copy test2 = copy.deepcopy(test) # deep copy test2 = copy.copy(test)) # shallow copy test2 = test[:] # shallow copy using slices See this page for a more in-depth explanation as well as other methods to copy a list. A: [1,2] is an array and when you assign it to test you assign a reference to that array to test. So when you do test2=test, you are assigning the reference to yet another variable. Make changes to any variable and the array will get changed. Your second example works, because you create a new array altogether. You might as well have done it like this: test = [1,2] test2 = [test[0]-1, test[1]] A: Python does not do assignment. It does name binding. There is a difference, and it is explained wonderfully and in detail here. In your first example: Your first line binds the name "test" to a list object created by the "[1,2]" expression. Your second line binds the name "test2" to the same object that is bounded to "test". Your third line mutates the object bound to "test2", which is the same as the object bound to by "test". In your second example: Your first line binds the name "test" to a list object created by the "[1,2]" expression. Your second line binds the name "test2" to the same object that is bounded to "test". Your third line binds the name "test2" to a new object, created by the expression "[test2[0]-1, test21]". If you really want two independent lists with the same values bound to different variables, you need to: >>> test = [1, 2] >>> test2 = list(test) >>> test2[0] = 3 >>> print(test) [1, 2] >>> print(test2) [3, 2] Note that this is a shallow-copy list, so changing the state of the object of an element in test2 will, of course, effect test if the the same object is found in that list. p.s. Python. Semi-colons. Ugly. Unnecessary. Do not use.
Python permanent assignment variables
I have just started python and came across something kind of strange. The following code assigns a co-ordinate of x=1 and y=2 to the variable test. The test2 variable assigns itself the same value as test and then the [x] value for test2 is changed to the old [x] value minus 1. This works fine, however, when the last part is executed, not only does it minus 1 from the [x] value in test2, it does the same to the [x] value in the test variable too. test = [1,2]; test2 = test; test2[1] = test2[1] - 1; I found doing the following worked fine but I still don't understand why the first method changes the test value as well as the test2 value. test = [1,2]; test2 = test; test2 = [test2[0] -1 ,test2[1]]; Could someone please explain why this happens. Thank You TheLorax
[ "In Python, like in Java, assignment per se never makes a copy -- rahter, assignment adds another reference to the same object as the right-hand side of the =. (Argument passing works the same way). Strange that you've never heard of the concept, when Python is quite popular and Java even much more so (and many o...
[ 4, 3, 0, 0 ]
[]
[]
[ "list", "python", "reference" ]
stackoverflow_0003580913_list_python_reference.txt
Q: tcp port 80 redirector in python for windows 7 I want to redirect the port 80 traffic to port 3128 for windows 7 , i want to write it in python. I am relatively new to this....could you guys help ..by giving me some pointers regarding from where to start. Thanks. A: http://code.activestate.com/recipes/483730/ or http://code.activestate.com/recipes/114642/ might be good places to start
tcp port 80 redirector in python for windows 7
I want to redirect the port 80 traffic to port 3128 for windows 7 , i want to write it in python. I am relatively new to this....could you guys help ..by giving me some pointers regarding from where to start. Thanks.
[ "http://code.activestate.com/recipes/483730/ or http://code.activestate.com/recipes/114642/ might be good places to start\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003581154_python.txt
Q: about the return expression level: beginner the following code will print 'False' def function(x): if len(x) == 5: return True else: return x[0] == x[-1] print function('annb') why does the line "else: return x[0] == x[-1]" print False? i do understand what's happening but i'm having difficulties to put this into plain english...how can this behaviour be described? is this a commonly / often used "technique"? I first came across this particular syntax when trying to solve a palindrome exercise recursivley. It seems that the only way to make recursion work is to use this shorthand approach: def isPalindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPalindrome(s[1:-1]) print isPalindrome('anna') thanks Baba A: Sorry, I'm not entirely sure what you mean, but here think of it this way: return (x[0] == x[-1]) If you only consider what is within the parenthesis, you realize that, that 'statement' equates to a boolean, right? That's why you can also do: if x[0] == x[-1] So basically, what is being returned here is a boolean that says whether or not x[0] is equal to [-1]. One could be more explicit and expand this statement to something like this: if x[0] == x[-1]: # if this is true return True # then return true else: return False But as you can see, both the condition and what you would like to return are the same value, so one just does it shorthand like you saw: return x[0] == x[-1] Sorry if I misunderstood your question. EDIT: If you referred to the negative index (x[-1]), in Python, negative indices basically 'wrap around', so where as x[0] would be the first element from 'left-to-right' so to speak, x[-1] loops around such that it is the first element from 'right-to-left'. A: I think the thing you're confused about is the behavior of x[-1]. Negative array indices are relative to the end of the array, so in your example, x[-1] == 'b'. Which is obviously not equal to x[0] == 'a', so the function returns False. A: On the whole the function of your function is: if length of x equals 5 , return True else if last character of string equals first one return True, else return False This kind of condition else condition...else return False is best expressed with or statement which return False only if all conditions are False and returns value of first not-False element. Other choice is any function which does basically same with any sequence. Here test of those alternatives for all branches of original if statement: def function(x): if len(x) == 5: return True else: return x[0] == x[-1] def funcor(x): return (len(x)==5) or (x[0] == x[-1]) def funcany(x): return any((len(x)==5, x[0] == x[-1])) def funcverbal(sequence): ## sequence[0] is the first element of zero based indexed sequence ## endswith is string specific function so sequence must be string ## if it's length is not 5 return len(sequence)==5 or sequence.endswith(sequence[0]) ## function is normal data type in Python, so we can pass it in as variable def test(func): print('Testing %s function' % func) for value in ('12345','annb','ansa','23424242',('1','2','1'), 123, '131'): try: print ("%r -> %r" % (value,func(value))) except: print ("Failed to call function with " + repr(value)) print(10 * '-'+'Finished testing '+str(func) + 10 * '-') for thisfunction in (function, funcor, funcany, funcverbal): test(thisfunction) (function is hightlighted as reserved word in blue but it is mistake in highlight routine in this website) In case of the isPalindrome function, the length condition is not arbitrary, but it is necessary to recognize the primitive cases to stop the recursion, in case of 'anna' the palindrome function does: see if the length of 'anna' is less than 2 (1 or 0), no they are not compare 'a' with 'a' , continue as they are same drop out the compared first and last letter and call isPalindrome with 'nn' see if the length of 'nn' is less than 2 (1 or 0), no they are not compare 'n' with 'n', continue as they are same drop out the compared first and last letter and call isPalindrome with '' see if the length of '' is less than 2 (1 or 0), yes. Return True as we found palindrome. Here is alternative shorte function of palindrome testing based on the fact that palindrome reversed is same as palindrome. def isPalindrome(s): return s==s[::-1]
about the return expression
level: beginner the following code will print 'False' def function(x): if len(x) == 5: return True else: return x[0] == x[-1] print function('annb') why does the line "else: return x[0] == x[-1]" print False? i do understand what's happening but i'm having difficulties to put this into plain english...how can this behaviour be described? is this a commonly / often used "technique"? I first came across this particular syntax when trying to solve a palindrome exercise recursivley. It seems that the only way to make recursion work is to use this shorthand approach: def isPalindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPalindrome(s[1:-1]) print isPalindrome('anna') thanks Baba
[ "Sorry, I'm not entirely sure what you mean, but here think of it this way:\nreturn (x[0] == x[-1])\n\nIf you only consider what is within the parenthesis, you realize that, that 'statement' equates to a boolean, right? That's why you can also do:\nif x[0] == x[-1]\n\nSo basically, what is being returned here is a ...
[ 6, 1, 0 ]
[]
[]
[ "python", "return", "semantics" ]
stackoverflow_0003580228_python_return_semantics.txt
Q: Django 1.2 Equivalent of QuerySet.query.as_sql() In Django 1.1 I was able to produce the SQL used by a QuerySet with this notation: QuerySet.query.as_sql() In Django 1.2, this raises as AttributeError. Anyone know the Django 1.2 equivalent of that method? Thanks A: In Django 1.1, QuerySet.query returned a BaseQuery object, now it returns a Query objects. The query object has a __str__ method defined that returns the SQL. A: as answered in In django 1.2.1 how can I get something like the old .as_sql? it's just: print QuerySet.query
Django 1.2 Equivalent of QuerySet.query.as_sql()
In Django 1.1 I was able to produce the SQL used by a QuerySet with this notation: QuerySet.query.as_sql() In Django 1.2, this raises as AttributeError. Anyone know the Django 1.2 equivalent of that method? Thanks
[ "In Django 1.1, QuerySet.query returned a BaseQuery object, now it returns a Query objects. The query object has a __str__ method defined that returns the SQL.\n", "as answered in In django 1.2.1 how can I get something like the old .as_sql?\nit's just:\nprint QuerySet.query\n\n" ]
[ 12, 4 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0002900057_django_django_queryset_python.txt
Q: py2exe error on MSVCR80.dll from distutils.core import setup import py2exe,sys,os sys.argv.append('py2exe') try: setup( options = {'py2exe': {'bundle_files': 1}}, console=['my_console_script.py'], zipfile = None, ) except Exception, e: print e outputs: > running py2exe > *** searching for required modules *** > *** parsing results *** > *** finding dlls needed *** Traceback (most recent call last): File > "C:\scripts\download_ghost_recon\setup.py", > line 26, in <module> > zipfile = None, File "C:\Python26\lib\distutils\core.py", > line 162, in setup > raise SystemExit, error SystemExit: error: MSVCR80.dll: No > such file or directory I'm on python 2.6 in Windows 7 So how can I make this MSVCR80.dll error go away, and compile my script? On other scripts, I can run the same setup.py and not receive this error. This makes me think that in this script, py2exe needs this MSVCR80.dll I also tried this code, which I found here: http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls but it also didn't work. from distutils.core import setup import py2exe,sys,os origIsSystemDLL = py2exe.build_exe.isSystemDLL def isSystemDLL(pathname): if os.path.basename(pathname).lower() in ("msvcp71.dll", "dwmapi.dll"): return 0 return origIsSystemDLL(pathname) py2exe.build_exe.isSystemDLL = isSystemDLL sys.argv.append('py2exe') try: setup( options = {'py2exe': {'bundle_files': 1}}, console=['my_console_script.py'], zipfile = None, ) except Exception, e: print e *EDIT I've also run a search on my computer for this file, it is found in these locations: C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.762_none_10b2f55f9bffb8f8 C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4053_none_d08d7da0442a985d C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_d08a205e442db5b5 A: Append to your call to setup: { 'py2exe': { ..., 'dll_excludes': [ 'msvcr80.dll', 'msvcp80.dll', 'msvcr80d.dll', 'msvcp80d.dll', 'powrprof.dll', 'mswsock.dll' ] }, ... If you want to include the visual C runtime DLLs in your application, have a look at Microsoft's distributable runtime downloads. Probably you're using a library or module that is imported in this application, but not the others you speak of. It may be a good idea to check if you can recompile them using Visual Studio 2008, because that's what is used to create the standard Python 2.6 Windows builds.
py2exe error on MSVCR80.dll
from distutils.core import setup import py2exe,sys,os sys.argv.append('py2exe') try: setup( options = {'py2exe': {'bundle_files': 1}}, console=['my_console_script.py'], zipfile = None, ) except Exception, e: print e outputs: > running py2exe > *** searching for required modules *** > *** parsing results *** > *** finding dlls needed *** Traceback (most recent call last): File > "C:\scripts\download_ghost_recon\setup.py", > line 26, in <module> > zipfile = None, File "C:\Python26\lib\distutils\core.py", > line 162, in setup > raise SystemExit, error SystemExit: error: MSVCR80.dll: No > such file or directory I'm on python 2.6 in Windows 7 So how can I make this MSVCR80.dll error go away, and compile my script? On other scripts, I can run the same setup.py and not receive this error. This makes me think that in this script, py2exe needs this MSVCR80.dll I also tried this code, which I found here: http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls but it also didn't work. from distutils.core import setup import py2exe,sys,os origIsSystemDLL = py2exe.build_exe.isSystemDLL def isSystemDLL(pathname): if os.path.basename(pathname).lower() in ("msvcp71.dll", "dwmapi.dll"): return 0 return origIsSystemDLL(pathname) py2exe.build_exe.isSystemDLL = isSystemDLL sys.argv.append('py2exe') try: setup( options = {'py2exe': {'bundle_files': 1}}, console=['my_console_script.py'], zipfile = None, ) except Exception, e: print e *EDIT I've also run a search on my computer for this file, it is found in these locations: C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.762_none_10b2f55f9bffb8f8 C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4053_none_d08d7da0442a985d C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_d08a205e442db5b5
[ "Append to your call to setup:\n{ 'py2exe': { ...,\n 'dll_excludes': [ 'msvcr80.dll', 'msvcp80.dll',\n 'msvcr80d.dll', 'msvcp80d.dll',\n 'powrprof.dll', 'mswsock.dll' ] }, ...\n\nIf you want to include the visual C runtime DLLs in your appli...
[ 2 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0003581814_py2exe_python.txt
Q: Get angles in the range -180 to +180 Before I start thanking everybody. Through my application s/w I will read syncro values which will be in angles. When I run Python script, the values are collected in particular variables. Suppose the range is -180 to 180. And I got angle as -180. According to the requirement it should be +/-1 deg window;ie; between 179 and -179. How I will check whether its falling in that range ? angle = -180 tolerance = 1 (in degree) if(180-1) <= -180 <= (-180+1): # statements angle1 = -179 tolerance = 1 if(-170-1)<= -179 <= (-179+1): # statements angle2 = 179 tolerance = 1 if(179-1) <= 179 <= (179+1): # statements will this work for all angle combinations ? what you think ? A: if -180 < x < 180: #do something This includes -179 and 179 in the range, but not -180 and 180. A: If I understand you correctly, you have some angles that you want to make sure that they are close to a target angle, given a specific tolerance defining the closeness. I think this is what you need: def restrict_angle(angle): "make sure any angle falls in the [0..360) range" return angle % 360 def is_angle_almost(angle, target_angle, tolerance): tolerance= abs(tolerance) # same meaning, easier logic angle= restrict_angle(angle) upper_limit= restrict_angle(target_angle + tolerance) lower_limit= restrict_angle(target_angle - tolerance) if upper_limit < lower_limit: # when target_angle close to -180 upper_limit+= 360 return (lower_limit <= angle <= upper_limit or lower_limit <= angle + 360 <= upper_limit) if __name__ == "__main__": for test in ( ( (90, 92, 3), True), ( (90, 92, -3), True), ( (90, 92, -1), False), ( (180, 181, 1), True), ( (180, 182, 1), False), ( (179, -180, 1), True), ( (-175, 180, 6), True), ( (-175, 180, 4), False), ( (4, 0, 5), True), ): if is_angle_almost(*test[0]) != test[1]: print ("fails for " + str(test[0])) break else: print "all tests successful" The function you will use is is_angle_almost.
Get angles in the range -180 to +180
Before I start thanking everybody. Through my application s/w I will read syncro values which will be in angles. When I run Python script, the values are collected in particular variables. Suppose the range is -180 to 180. And I got angle as -180. According to the requirement it should be +/-1 deg window;ie; between 179 and -179. How I will check whether its falling in that range ? angle = -180 tolerance = 1 (in degree) if(180-1) <= -180 <= (-180+1): # statements angle1 = -179 tolerance = 1 if(-170-1)<= -179 <= (-179+1): # statements angle2 = 179 tolerance = 1 if(179-1) <= 179 <= (179+1): # statements will this work for all angle combinations ? what you think ?
[ "if -180 < x < 180:\n #do something\n\nThis includes -179 and 179 in the range, but not -180 and 180. \n", "If I understand you correctly, you have some angles that you want to make sure that they are close to a target angle, given a specific tolerance defining the closeness. I think this is what you need:\nde...
[ 1, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003351254_math_python.txt
Q: Python client for MSSQL, with encrypted connections? I am looking for a Python client for MSSQL, but one that supports encrypted connections to a remote MSSQL server. Can someone recommend a technique for using Python to read from MSSQL, over an encrypted connection? A: Encryption is usually a feature of the MSSQL client library and/or the OS, not Python. So first work out what encrpytion mechanism you want to use, then see how you can use it from Python. MSSQL can be configured to support and even require encrypted connections from clients: http://msdn.microsoft.com/en-us/library/ms191192.aspx That means that any Python library that uses the native MSSQL client drivers would support encryption, which probably means something like adodbapi or pymssql on Windows. You could also look into implementing something at the OS level to encrypt all network traffic, or even the network level (using a VPN). It might be easier, depending on your requirements, But it's probably a question for http://serverfault.com.
Python client for MSSQL, with encrypted connections?
I am looking for a Python client for MSSQL, but one that supports encrypted connections to a remote MSSQL server. Can someone recommend a technique for using Python to read from MSSQL, over an encrypted connection?
[ "Encryption is usually a feature of the MSSQL client library and/or the OS, not Python. So first work out what encrpytion mechanism you want to use, then see how you can use it from Python.\nMSSQL can be configured to support and even require encrypted connections from clients: \nhttp://msdn.microsoft.com/en-us/lib...
[ 0 ]
[]
[]
[ "encryption", "python", "sql", "sql_server", "tunnel" ]
stackoverflow_0003580591_encryption_python_sql_sql_server_tunnel.txt