Re: Help
On 02/29/2016 01:53 PM, tomwilliamson...@gmail.com wrote: Thanks. If a word appears more than once how would I bring back both locations? for i, str in enumerate(l): . . . . -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with dateutil
On 02/13/2016 09:45 PM, Gary Herron wrote: On 02/13/2016 12:27 PM, Tom P wrote: On 02/13/2016 07:13 PM, Gary Herron wrote: On 02/13/2016 09:58 AM, Tom P wrote: I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? Yes, there is a way to specify your own format. Search the datetime documentation for datetime.strptime(date_string, format) Gary Herron Thanks. I started out with datetime.strptime but AFAICS that means I have to go through try/except for every conceivable format. Are you saying that I can't use dateutil.parser? Well now... If by "every conceivable format" you are including formats that the author of dateutil.parser did not conceive of, then of course you cannot use dateutil.parser. But you have the code for dateutil.parser -- perhaps you could modify it to accept whatever odd formats you care about. Gary Herron I had a look at the code for dateutil.parser. Have you looked at it? Meanwhile I'm living with try: dt = datetime.datetime.strptime(datetimestr, '%Y:%m:%d %H:%M:%S') except ValueError: dt = dateutil.parser.parse(datetimestr) unixtime = time.mktime(dt.timetuple()) -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with dateutil
On 02/13/2016 10:01 PM, Mark Lawrence wrote: On 13/02/2016 17:58, Tom P wrote: I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? From http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c parserinfo This parameter allows one to change how the string is parsed, by using a different parserinfo class instance. Using it you may, for example, intenationalize the parser strings, or make it ignore additional words. HTH. Thanks, let me look at that. -- https://mail.python.org/mailman/listinfo/python-list
problem with dateutil
I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with dateutil
On 02/13/2016 07:13 PM, Gary Herron wrote: On 02/13/2016 09:58 AM, Tom P wrote: I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? Yes, there is a way to specify your own format. Search the datetime documentation for datetime.strptime(date_string, format) Gary Herron Thanks. I started out with datetime.strptime but AFAICS that means I have to go through try/except for every conceivable format. Are you saying that I can't use dateutil.parser? -- https://mail.python.org/mailman/listinfo/python-list
Re: Nearest neighbours of points
On 10/24/2015 10:05 PM, Poul Riis wrote: I have N points in 3D, organized in a list. I want to to point out the numbers of the two that have the smallest distance. With scipy.spatial.distance.pdist I can make a list of all the distances, and I can point out the number of the minimum value of that list (see simple example below - the line with pts.append... should be indented three times). But I guess there is a standard (numpy?) routine which points out the numbers of the corresponding two points but I cannot find it. Can someone help? Poul Riis import numpy as np import scipy from scipy.spatial.distance import pdist pts=[] for i in range(-1,2): for j in range(-1,2): for k in range(-1,2): pts.append((i+np.random.random()/10,j+np.random.random()/10,k+np.random.random()/10)) for i in range(0,len(pts)): print(pts[i]) distances=scipy.spatial.distance.pdist(pts) n=np.argmin(distances) for i in range(0,len(distances)): print(i,distances[i]) print('The minimum distance is: ',min(distances),' which has number ',n) I won't claim to have the definitive answer but - is this a clustering problem? Did you look at any machine learning packages? -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with netCDF4 OpenDAP
On 08/13/2015 05:55 PM, Jason Swails wrote: On Thu, Aug 13, 2015 at 6:32 AM, Tom P werot...@freent.dd mailto:werot...@freent.dd wrote: I'm having a problem trying to access OpenDAP files using netCDF4. The netCDF4 is installed from the Anaconda package. According to their changelog, openDAP is supposed to be supported. netCDF4.__version__ Out[7]: '1.1.8' Here's some code: url = 'http://www1.ncdc.noaa.gov/pub/data/cmb/ersst/v3b/netcdf/ersst.201507.nc' nc = netCDF4.Dataset(url) I get the error - netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Dataset.__init__ (netCDF4/_netCDF4.c:9551)() RuntimeError: NetCDF: file not found However if I download the same file, it works - url = '/home/tom/Downloads/ersst.201507.nc http://ersst.201507.nc' nc = netCDF4.Dataset(url) print nc . . . . Is it something I'm doing wrong? Yes. URLs are not files and cannot be opened like normal files. netCDF4 *requires* a local file as far as I can tell. All the best, Jason -- Jason M. Swails BioMaPS, Rutgers University Postdoctoral Researcher Thanks for the reply but that is not what the documentation says. http://unidata.github.io/netcdf4-python/#section8 Remote OPeNDAP-hosted datasets can be accessed for reading over http if a URL is provided to the netCDF4.Dataset constructor instead of a filename. However, this requires that the netCDF library be built with OPenDAP support, via the --enable-dap configure option (added in version 4.0.1). and for the Anaconda package - http://docs.continuum.io/anaconda/changelog 2013-05-08: 1.5.0: Highlights: updates to all important packages: python, numpy, scipy, ipython, matplotlib, pandas, cython added netCDF4 (with OpenDAP support) on Linux and MacOSX -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with netCDF4 OpenDAP
On 08/14/2015 03:15 PM, Jason Swails wrote: On Aug 14, 2015, at 3:18 AM, Tom P werot...@freent.dd wrote: Thanks for the reply but that is not what the documentation says. http://unidata.github.io/netcdf4-python/#section8 Remote OPeNDAP-hosted datasets can be accessed for reading over http if a URL is provided to the netCDF4.Dataset constructor instead of a filename. However, this requires that the netCDF library be built with OPenDAP support, via the --enable-dap configure option (added in version 4.0.1).” Huh, so it does. Your error message says file not found, though, which suggested to me that it's trying to interpret the NetCDF file as a local file instead of a URL. Indeed, when I run that example, the traceback is more complete (the traceback you printed had omitted some information): netCDF4.Dataset('http://www1.ncdc.noaa.gov/pub/data/cmb/ersst/v3b/netcdf/ersst.201507.nc') syntax error, unexpected WORD_WORD, expecting SCAN_ATTR or SCAN_DATASET or SCAN_ERROR context: !DOCTYPE^ HTML PUBLIC -//IETF//DTD HTML 2.0//ENhtmlheadtitle404 Not Found/title/headbodyh1Not Found/h1pThe requested URL /pub/data/cmb/ersst/v3b/netcdf/ersst.201507.nc.dds was not found on this server./p/body/html Traceback (most recent call last): File stdin, line 1, in module File netCDF4/_netCDF4.pyx, line 1547, in netCDF4._netCDF4.Dataset.__init__ (netCDF4/_netCDF4.c:9551) RuntimeError: NetCDF: file not found So it’s clear that netCDF4 is at least *trying* to go online to look for the file, but it simply can’t find it. Since the docs say it’s linking to libcurl, I tried using curl to download the file (curl -# http://www1.ncdc.noaa.gov/pub/data/cmb/ersst/v3b/netcdf/ersst.201507.nc test.nc) and it worked fine. What’s more, it *seems* like the file (/pub/.../ersst.201507.nc.dds) was decorated with the ‘.dds’ suffix for some reason (not sure if the server redirected the request there or not). But this looks like a netCDF4 issue. Perhaps you can go to their project page on Github and file an issue there -- they will be more likely to have your answer than people here. HTH, Jason Hi, yes the file does appear to be there, I can download it and I can open and read the URL using urllib. Since there are a whole bunch of files in the directory, I really need MFDataset, but according to the documentation that doesn't work with URLs. Maybe the solution really is to D/L them all into a temporary folder and use MFDataset. and for the Anaconda package - http://docs.continuum.io/anaconda/changelog 2013-05-08: 1.5.0: Highlights: updates to all important packages: python, numpy, scipy, ipython, matplotlib, pandas, cython added netCDF4 (with OpenDAP support) on Linux and MacOSX -- https://mail.python.org/mailman/listinfo/python-list -- Jason M. Swails BioMaPS, Rutgers University Postdoctoral Researcher -- https://mail.python.org/mailman/listinfo/python-list
problem with netCDF4 OpenDAP
I'm having a problem trying to access OpenDAP files using netCDF4. The netCDF4 is installed from the Anaconda package. According to their changelog, openDAP is supposed to be supported. netCDF4.__version__ Out[7]: '1.1.8' Here's some code: url = 'http://www1.ncdc.noaa.gov/pub/data/cmb/ersst/v3b/netcdf/ersst.201507.nc' nc = netCDF4.Dataset(url) I get the error - netCDF4/_netCDF4.pyx in netCDF4._netCDF4.Dataset.__init__ (netCDF4/_netCDF4.c:9551)() RuntimeError: NetCDF: file not found However if I download the same file, it works - url = '/home/tom/Downloads/ersst.201507.nc' nc = netCDF4.Dataset(url) print nc . . . . Is it something I'm doing wrong? -- https://mail.python.org/mailman/listinfo/python-list
Re: want to learn python
On 04/21/2015 12:57 PM, pm05...@gmail.com wrote: Hello everyone, I am willing to learn Python from scratch.Please he me to learn.Although I hv knowledge of c and object oriented programming. Apart from the various tutorials you might want to look at the on-line courses offered by Coursera and EDX. https://www.coursera.org/course/pythonlearn https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-0 Check out the websites for more advanced courses. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python code in presentations
On 30.09.2014 13:50, Jean-Michel Pichavant wrote: Hello list, I'm currently writing a presentation to help my co-workers ramp up on new features of our tool (written in python (2.7)). I have some difficulties presenting code in an efficient way (with some basic syntax highlights). I need to be catchy about the code I'm presenting otherwise the presentation will fail and I would be better saying to my co-workers RTFM, cause there is a manual. So I really need to make them realize the code I'm presenting will benefit them (they're not software engineers, python is just a tool, their expertise and focus is aimed at something else, don't blame them :) ) Right now the method I'm using is write the code in notepad++, use a plugin (NppExport) to copy paste code into powerpoint. After using it a little bit, I'm really not satisfied with this method, it's expensive and all this copy paste stuff is driving me crazy. Not to mention that the syntax highlight from notepads renders like crap in powerpoint. I wonder if some people in this list who have successfully presented python code have some tips about doing the proper way. Ned's presentations for pycons are to me one example of successful code presentation: - the layout is simple - the code and code output are clearly identified - a line of code can be highlighted while presenting http://nedbatchelder.com/text/iter.html I have access to powerpoint, or any tool under linux (I don't have access to Mac's stuff). Right now I'm so not satisfied by my current method that I'm about to make the presentation showing the code from the file directly, alt-tabing between the slides and the code. At least it's cheap. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. I can't answer your question, but thanks for the great presentation on iterables! -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert numpy array to single number
On 28.04.2014 15:04, mboyd02...@gmail.com wrote: I have a numpy array consisting of 1s and zeros for representing binary numbers: e.g. binary array([ 1., 0., 1., 0.]) I wish the array to be in the form 1010, so it can be manipulated. I do not want to use built in binary converters as I am trying to build my own. Do you mean that each element in the array represents a power of two? So array([ 1., 0., 1., 0.]) represents 2^3 + 2 = 6 decimal? -- https://mail.python.org/mailman/listinfo/python-list
numpy masked array puzzle
I have two numpy arrays, xx and yy - (Pdb) xx array([0.7820524520874, masked, masked, 0.3700476837158, 0.7252384185791, 0.6002384185791, 0.6908474121094, 0.7878760223389, 0.6512288818359, 0.1110143051147, masked, 0.716205039978, 0.5460381469727, 0.4358950958252, 0.63868808746337891, 0.02700700354576, masked, masked], dtype=object) (Pdb) yy array([-0.015120843222826226, -0.0080196081193390761, 0.02241851002495138, -0.021720756657755306, -0.0095334465407607427, -0.0063953867288363917, -0.013363615476044387, 0.0080645889792231359, -0.0056745213729654086, -0.0071783823973457523, -0.0019400978318164389, -0.0038670581150256019, 0.0048961156278229494, -0.01315129469368378, -0.007727079344820257, -0.0042560259937610449, 0.0063857167196111056, 0.0024528141737232877], dtype=object) (Pdb) -- which gives a strange error - stats.mstats.linregress(x, y) *** AttributeError: 'int' object has no attribute 'view' (Pdb) What is stranger I can't get the mask - (Pdb) np.ma.getmaskarray(xx) array([False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False], dtype=bool) (Pdb) -- https://mail.python.org/mailman/listinfo/python-list
Python PDB conditional breakpoint
I can't get conditional breakpoints to work. I have a variable ID and I want to set a breakpoint which runs until ID==11005. Here's what happens - - import sys ... (Pdb) b 53, ID==11005 Breakpoint 1 at /home/tom/Desktop/BEST Tmax/MYSTUFF/sqlanalyze3.py:53 (Pdb) b Num Type Disp Enb Where 1 breakpoint keep yes at /home/tom/Desktop/BEST Tmax/MYSTUFF/sqlanalyze3.py:53 stop only if ID==11005 (Pdb) l 50 for ID in distinct_IDs: 51 cursr.execute(select Date, Temperature from data where StationID = ? and Date 1963, ID) 52 datarecords = cursr.fetchall() # [(date, temp),..] 53 B- ll = len(datarecords) 54 if ll 150: # and len(results) 100 : (Pdb) c ... std_error too large -132.433 61.967 10912 std_error too large -133.36274 62.2165 10925 std_error too large -137.37 62.82 10946 std_error too large -138.217 64.45 10990 std_error too large -138.32 65.35 11005 std_error too large -138.32 65.35 11005 std_error too large -138.32 65.35 11005 std_error too large -138.32 65.35 11005 std_error too large -134.86625 67.415 11036 std_error too large -135.0 68.22908 11053 ... - in other words it doesn't stop even though the value ID == 11005 shows up. Am I specifying the condition incorrectly? This is Python 2.7.4, Linux 64 bit. -- https://mail.python.org/mailman/listinfo/python-list
[solved]Re: Python PDB conditional breakpoint
On 06.11.2013 16:14, Tom P wrote: ok I figured it. ID is a tuple, not a simple variable. The correct test is ID[0]==11005 I can't get conditional breakpoints to work. I have a variable ID and I want to set a breakpoint which runs until ID==11005. Here's what happens - -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I trust downloading Python?
On 10.09.2013 11:45, Oscar Benjamin wrote: On 10 September 2013 01:06, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Mon, 09 Sep 2013 12:19:11 +, Fattburger wrote: But really, we've learned *nothing* from the viruses of the 1990s. Remember when we used to talk about how crazy it was to download code from untrusted sites on the Internet and execute it? We're still doing it, a hundred times a day. Every time you go on the Internet, you download other people's code and execute it. Javascript, Flash, HTML5, PDF are all either executable, or they include executable components. Now they're *supposed* to be sandboxed, but we've gone from don't execute untrusted code to let's hope my browser doesn't have any bugs that the untrusted code might exploit. You could have also mentioned pip/PyPI in that. 'pip install X' downloads and runs arbitrary code from a largely unmonitored and uncontrolled code repository. The maintainers of PyPI can only try to ensure that the original author of X would remain in control of what happens and could remove a package X if it were discovered to be malware. However they don't have anything like the resources to monitor all the code coming in so it's essentially a system based on trust in the authors where the only requirement to be an author is that you have an email address. Occasionally I see the suggestion to do 'sudo pip install X' which literally gives root permissions to arbitrary code coming straight from the net. Oscar Interesting observation -- https://mail.python.org/mailman/listinfo/python-list
Google App Engine dev_appserver and pdb?
Is there a way to use pdb to debug Google apps written in Python? When I start the development system to run the app test like this - './google_appengine/dev_appserver.py' './test' - I'd like to send the program into debug. I couldn't see anything in the documentation how to do this. If I do this - python -mpdb './google_appengine/dev_appserver.py' './test' - then dev_appserver.py goes into debug but doesn't know anything about test. -- http://mail.python.org/mailman/listinfo/python-list
HTTPServer again
Hi, a few weeks back I posed a question about passing static data to a request server, and thanks to some useful suggestions, got it working. I see yesterday there is a suggestion to use a framework like Tornado rather than base classes. However I can't figure achieve the same effect using Tornado (BTW this is all python 2.7). The key point is how to access the server class from within do_GET, and from the server class instance, to access its get and set methods. Here are some code fragments that work with HTTPServer: class MyHandler(BaseHTTPRequestHandler): def do_GET(self): ss = self.server tracks = ss.tracks . . . class MyWebServer(object): def get_params(self): return self.global_params def set_params(self, params): self.global_params = params def get_tracks(self): return self.tracks def __init__(self): self.global_params = self.tracks = setup_() myServer = HTTPServer myServer.tracks = self.get_tracks() myServer.params = self.get_params() self.server = myServer(('', 7878), MyHandler) print 'started httpserver on port 7878...' . . . . def main(): aServer = MyWebServer() aServer.runIt() if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: HTTPserver: how to access variables of a higher class?
On 04/05/2013 02:27 PM, Dylan Evans wrote: On 05/04/2013 9:09 PM, Tom P werot...@freent.dd wrote: First, here's a sample test program: code import sys from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyRequestHandler(BaseHTTPRequestHandler, object): def do_GET(self): top_self = super(MyRequestHandler, self) # try to access MyWebServer instance self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(thanks for trying, but I'd like to get at self.foo and self.bar) return class MyWebServer(object): def __init__(self): self.foo = foo # these are what I want to access from inside do_GET self.bar = bar self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) sa = self.httpd.socket.getsockname() print Serving HTTP on, sa[0], port, sa[1], ... def runIt(self): self.httpd.serve_forever() server = MyWebServer() server.runIt() /code I want to access the foo and bar variables from do_GET, but I can't figure out how. I suppose this is something to do with new-style vs. old-style classes, but I lost for a solution. Consider inheriting HTTPServer in MyWebServer which is passed to the request handler. -- http://mail.python.org/mailman/listinfo/python-list I keep getting the same problem - if inherit from any of these classes in BaseHTTPServer and try to use super(class, self) to initiate the higher class, I get the error TypeError: must be type, not classobj - in other words, these are old-style classes. That means that in this call - self.httpd = MyHTTPServer(('127.0.0.1', 8000), MyRequestHandler) there doesn't seem to be a way to define a class MyHTTPServer(HTTPServer) -- http://mail.python.org/mailman/listinfo/python-list
Re: The SOLUTION HTTPserver: how to access variables of a higher class
On 04/05/2013 01:02 PM, Tom P wrote: ok, after much experimenting it looks like the solution is as follows: class MyWebServer(object): def __init__(self): # self.foo = foo delete these from self # self.bar = bar myServer = HTTPServer myServer.foo = foo #define foo,bar here myServer.bar = bar self.httpd = myServer(('127.0.0.1', 8000), MyRequestHandler) Then, in the request handler: class MyRequestHandler(BaseHTTPRequestHandler): def do_GET(self): ss=self.server print ss.foo -- http://mail.python.org/mailman/listinfo/python-list
HTTPserver: how to access variables of a higher class?
First, here's a sample test program: code import sys from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyRequestHandler(BaseHTTPRequestHandler, object): def do_GET(self): top_self = super(MyRequestHandler, self) # try to access MyWebServer instance self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(thanks for trying, but I'd like to get at self.foo and self.bar) return class MyWebServer(object): def __init__(self): self.foo = foo # these are what I want to access from inside do_GET self.bar = bar self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) sa = self.httpd.socket.getsockname() print Serving HTTP on, sa[0], port, sa[1], ... def runIt(self): self.httpd.serve_forever() server = MyWebServer() server.runIt() /code I want to access the foo and bar variables from do_GET, but I can't figure out how. I suppose this is something to do with new-style vs. old-style classes, but I lost for a solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTTPserver: how to access variables of a higher class?
On 04/05/2013 02:27 PM, Dylan Evans wrote: On 05/04/2013 9:09 PM, Tom P werot...@freent.dd wrote: First, here's a sample test program: code import sys from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyRequestHandler(BaseHTTPRequestHandler, object): def do_GET(self): top_self = super(MyRequestHandler, self) # try to access MyWebServer instance self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(thanks for trying, but I'd like to get at self.foo and self.bar) return class MyWebServer(object): def __init__(self): self.foo = foo # these are what I want to access from inside do_GET self.bar = bar self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) sa = self.httpd.socket.getsockname() print Serving HTTP on, sa[0], port, sa[1], ... def runIt(self): self.httpd.serve_forever() server = MyWebServer() server.runIt() /code I want to access the foo and bar variables from do_GET, but I can't figure out how. I suppose this is something to do with new-style vs. old-style classes, but I lost for a solution. Consider inheriting HTTPServer in MyWebServer which is passed to the request handler. That was the next thing I was going to try, thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: HTTPserver: how to access variables of a higher class?
On 04/05/2013 01:54 PM, Dave Angel wrote: On 04/05/2013 07:02 AM, Tom P wrote: First, here's a sample test program: code import sys from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyRequestHandler(BaseHTTPRequestHandler, object): def do_GET(self): top_self = super(MyRequestHandler, self) # try to access MyWebServer instance self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(thanks for trying, but I'd like to get at self.foo and self.bar) return class MyWebServer(object): def __init__(self): self.foo = foo # these are what I want to access from inside do_GET self.bar = bar self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) sa = self.httpd.socket.getsockname() print Serving HTTP on, sa[0], port, sa[1], ... def runIt(self): self.httpd.serve_forever() server = MyWebServer() server.runIt() /code I want to access the foo and bar variables from do_GET, but I can't figure out how. I suppose this is something to do with new-style vs. old-style classes, but I lost for a solution. It'd have been good to tell us that this was on Python 2.7 Yes, sorry for the omission. Is MyWebServer class intended to have exactly one instance? Yes, but I was trying to keep it general. If so, you could save the instance as a class attribute, and trivially access it from outside the class. If it might have more than one instance, then we'd need to know more about the class BaseHTTPServer.HTTPServer, From a quick glance at the docs, it looks like you get an attribute called server. So inside the do_GET() method, you should be able to access self.server.foo and self.server.bar ok, let me test that. Do I assume correctly from what you write that the super() is not needed? In reality there is just one instance of MyWebServer, but I was looking for a general solution. See http://docs.python.org/2/library/basehttpserver.html -- http://mail.python.org/mailman/listinfo/python-list
Re: HTTPserver: how to access variables of a higher class?
On 04/05/2013 01:54 PM, Dave Angel wrote: On 04/05/2013 07:02 AM, Tom P wrote: First, here's a sample test program: code import sys from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyRequestHandler(BaseHTTPRequestHandler, object): def do_GET(self): top_self = super(MyRequestHandler, self) # try to access MyWebServer instance self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(thanks for trying, but I'd like to get at self.foo and self.bar) return class MyWebServer(object): def __init__(self): self.foo = foo # these are what I want to access from inside do_GET self.bar = bar self.httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) sa = self.httpd.socket.getsockname() print Serving HTTP on, sa[0], port, sa[1], ... def runIt(self): self.httpd.serve_forever() server = MyWebServer() server.runIt() /code I want to access the foo and bar variables from do_GET, but I can't figure out how. I suppose this is something to do with new-style vs. old-style classes, but I lost for a solution. It'd have been good to tell us that this was on Python 2.7 Is MyWebServer class intended to have exactly one instance? If so, you could save the instance as a class attribute, and trivially access it from outside the class. If it might have more than one instance, then we'd need to know more about the class BaseHTTPServer.HTTPServer, From a quick glance at the docs, it looks like you get an attribute called server. So inside the do_GET() method, you should be able to access self.server.foo and self.server.bar See http://docs.python.org/2/library/basehttpserver.html That doesn't work. Maybe you mean something that I'm missing? Setting a breakpoint in do_GET: Pdb) b 7 Breakpoint 1 at /home/tom/Desktop/tidy/Python/webserver/simpleWebserver.py:7 (Pdb) c Serving HTTP on 127.0.0.1 port 8000 ... /home/tom/Desktop/tidy/Python/webserver/simpleWebserver.py(7)do_GET() - self.send_response(200) (Pdb) self __main__.MyRequestHandler instance at 0x7ff20dde3bd8 (Pdb) self.server BaseHTTPServer.HTTPServer instance at 0x7ff20dde3830 (Pdb) dir(self.server) ['RequestHandlerClass', '_BaseServer__is_shut_down', '_BaseServer__shutdown_request', '__doc__', '__init__', '__module__', '_handle_request_noblock', 'address_family', 'allow_reuse_address', 'close_request', 'fileno', 'finish_request', 'get_request', 'handle_error', 'handle_request', 'handle_timeout', 'process_request', 'request_queue_size', 'serve_forever', 'server_activate', 'server_address', 'server_bind', 'server_close', 'server_name', 'server_port', 'shutdown', 'shutdown_request', 'socket', 'socket_type', 'timeout', 'verify_request'] (Pdb) self.server.foo *** AttributeError: HTTPServer instance has no attribute 'foo' -- http://mail.python.org/mailman/listinfo/python-list
Re: The usage of -m option of python
On 03/18/2013 10:17 PM, Peng Yu wrote: Hi, I don't quite understand how -m option is used. And it is difficult to search for -m in google. Could anybody provide me with an example on how to use this option? Thanks! -m module-name Searches sys.path for the named module and runs the corresponding .py file as a script. The most practical use I know is to run the debug program.. python -mpdb yourprogramm.py arguments.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquely identifying each every html template
On 01/21/2013 01:39 PM, Oscar Benjamin wrote: On 21 January 2013 12:06, Ferrous Cranus nikos.gr...@gmail.com wrote: Τη Δευτέρα, 21 Ιανουαρίου 2013 11:31:24 π.μ. UTC+2, ο χρήστης Chris Angelico έγραψε: Seriously, you're asking for something that's beyond the power of humans or computers. You want to identify that something's the same file, without tracking the change or having any identifiable tag. That's a fundamentally impossible task. No, it is difficult but not impossible. It just cannot be done by tagging the file by: 1. filename 2. filepath 3. hash (math algorithm producing a string based on the file's contents) We need another way to identify the file WITHOUT using the above attributes. This is a very old problem (still unsolved I believe): http://en.wikipedia.org/wiki/Ship_of_Theseus Oscar That wiki article gives a hint to a poosible solution -use a timestamp to determine which key is valid when. -- http://mail.python.org/mailman/listinfo/python-list
looking for a neat solution to a nested loop problem
consider a nested loop algorithm - for i in range(100): for j in range(100): do_something(i,j) Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some other values i = N and j = M, and I want to iterate through all 10,000 values in sequence - is there a neat python-like way to this? I realize I can do things like use a variable for k in range(1): and then derive values for i and j from k, but I'm wondering if there's something less clunky. -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
On 08/06/2012 06:18 PM, Nobody wrote: On Mon, 06 Aug 2012 17:52:31 +0200, Tom P wrote: consider a nested loop algorithm - for i in range(100): for j in range(100): do_something(i,j) Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some other values i = N and j = M, and I want to iterate through all 10,000 values in sequence - is there a neat python-like way to this? for i in range(N,N+100): for j in range(M,M+100): do_something(i,j) Or did you mean something else? no, I meant something else .. j runs through range(M, 100) and then range(0,M), and i runs through range(N,100) and then range(0,N) .. apologies if I didn't make that clear enough. Alternatively: import itertools for i, j in itertools.product(range(N,N+100),range(M,M+100)): do_something(i,j) This can be preferable to deeply-nested loops. Also: in 2.x, use xrange() in preference to range(). -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
On 08/06/2012 06:03 PM, John Gordon wrote: In a8a7hvf8c...@mid.individual.net Tom P werot...@freent.dd writes: consider a nested loop algorithm - for i in range(100): for j in range(100): do_something(i,j) Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some other values i = N and j = M, and I want to iterate through all 10,000 values in sequence - is there a neat python-like way to this? I realize I can do things like use a variable for k in range(1): and then derive values for i and j from k, but I'm wondering if there's something less clunky. You could define your own generator function that yields values in whatever order you want: def my_generator(): yield 9 yield 100 for i in range(200, 250): yield i yield 5 Thanks, I'll look at that but I think it just moves the clunkiness from one place in the code to another. -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a neat solution to a nested loop problem
On 08/06/2012 08:29 PM, Grant Edwards wrote: On 2012-08-06, Grant Edwards invalid@invalid.invalid wrote: On 2012-08-06, Tom P werot...@freent.dd wrote: On 08/06/2012 06:18 PM, Nobody wrote: On Mon, 06 Aug 2012 17:52:31 +0200, Tom P wrote: consider a nested loop algorithm - for i in range(100): for j in range(100): do_something(i,j) Now, suppose I don't want to use i = 0 and j = 0 as initial values, but some other values i = N and j = M, and I want to iterate through all 10,000 values in sequence - is there a neat python-like way to this? for i in range(N,N+100): for j in range(M,M+100): do_something(i,j) Or did you mean something else? no, I meant something else .. j runs through range(M, 100) and then range(0,M), and i runs through range(N,100) and then range(0,N) In 2.x: for i in range(M,100)+range(0,M): for j in range(N,100)+range(0,N): do_something(i,j) Dunno if that still works in 3.x. I doubt it, since I think in 3.x range returns an iterator, not? Indeed it doesn't work in 3.x, but this does: from itertools import chain for i in chain(range(M,100),range(0,M)): for j in chain(range(N,100),range(0,N)): do_something(i,j) ah, that looks good - I guess it works in 2.x as well? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question on python programming
On 07/21/2012 02:30 AM, Ian Kelly wrote: On Fri, Jul 20, 2012 at 5:38 PM, Chris Williams purplewel...@googlemail.com wrote: Hello I hope this is the right newsgroup for this post. I am just starting to learn python programming and it seems very straightforward so far. It seems, however, geared toward doing the sort of programming for terminal output. Is it possible to write the sort of applications you can create in something like c-sharp or visual c++, or should I be looking at some other programming language? I am using ubuntu 12.04. There are plenty of options for GUI programming in Python. Among the most popular are Tkinter, wxPython, PyGTK, and PyQT, all of which are cross-platform and free. Also, since you specifically mention the .NET languages, IronPython runs on .NET and so is able to make full use of the .NET APIs including Windows Forms and WPF. A more comprehensive list can be found at: http://wiki.python.org/moin/GuiProgramming Another platform independent approach is to write the program as a web server something like this- def application(environ, start_response): start_response(200 OK, [(Content-type, text/plain)]) return [Hello World!] if __name__ == '__main__': from wsgiref.simple_server import make_server server = make_server('localhost', 8080, application) server.serve_forever() Run this and then use your browser to connect to localhost:8080 You can then use html features such as forms for input/output. -- http://mail.python.org/mailman/listinfo/python-list