code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # wedge.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # For old times sake -- the PostScript cookbook wedge example in python... def inch(x): return 72*x def rad(angle): return angle*math.pi/180.0 def wedge(c): c.beginPath() c.moveToPoint(0,0) c.translateCTM(1,0) c.rotateCTM(rad(16)) c.translateCTM(0, math.sin(rad(15))) c.addArc(0,0, math.sin(rad(15)), rad(-90), rad(90), 0) c.closePath() pageRect = CGRectMake (0, 0, 612, 792) # landscape c = CGPDFContextCreateWithFilename ("wedge.pdf", pageRect) c.beginPage(pageRect) c.saveGState() c.translateCTM(inch(4.25), inch(4.25)) c.scaleCTM(inch(1.75), inch(1.75)) c.setLineWidth(.02) for i in range(1,13): c.setGrayFillColor(i/12.0,1.0) c.saveGState() wedge(c) c.fillPath() c.restoreGState() c.saveGState() c.setGrayStrokeColor(0,1) wedge(c) c.strokePath() c.restoreGState() c.rotateCTM(rad(30)) c.restoreGState() c.endPage() c.finish()
Python
#!/usr/bin/python # watermark.py -- add a "watermark" to each page of a pdf document # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os, math, getopt, string def usage (): print ''' usage: python watermark.py [OPTION]... INPUT-PDF OUTPUT-PDF Add a "watermark" to a PDF document. -t, --text=STRING -f, --font-name=FONTNAME -F, --font-size=SIZE -c, --color=R,G,B ''' def main (): text = 'CONFIDENTIAL' color = (1, 0, 0) font_name = 'Gill Sans Bold' font_size = 36 page_rect = CGRectMake (0, 0, 612, 792) try: opts,args = getopt.getopt (sys.argv[1:], 't:f:F:c:', ['text=', 'font-name=', 'font-size=', 'color=']) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 2: usage () sys.exit (1) for o,a in opts: if o in ('-t', '--text'): text = a elif o in ('-f', '--font-name'): font_name = a elif o in ('-F', '--font-size'): font_size = float (a) elif o in ('-c', '--color'): color = map (float, string.split (a, ',')) c = CGPDFContextCreateWithFilename (args[1], page_rect) pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (args[0])) for p in range (1, pdf.getNumberOfPages () + 1): r = pdf.getMediaBox (p) c.beginPage (r) c.saveGState () c.drawPDFDocument (r, pdf, p) c.restoreGState () c.saveGState () c.setRGBFillColor (color[0], color[1], color[2], 1) c.setTextDrawingMode (kCGTextFill) c.setTextMatrix (CGAffineTransformIdentity) c.selectFont (font_name, font_size, kCGEncodingMacRoman) c.translateCTM (r.size.width - font_size, r.size.height - font_size) c.rotateCTM (-90.0 / 180 * math.pi) c.showTextAtPoint (0, 0, text, len (text)) c.restoreGState () c.endPage () c.finish () if __name__ == '__main__': main ()
Python
#!/usr/bin/python # bitmap.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import math # Create an RGB bitmap context, transparent black background, 256x256 cs = CGColorSpaceCreateDeviceRGB () c = CGBitmapContextCreateWithColor (256, 256, cs, (0,0,0,0)) # Draw a yellow square with a red outline in the center c.saveGState () c.setRGBStrokeColor (1,0,0,1) # red c.setRGBFillColor (1,1,0,1) # yellow c.setLineWidth (3) c.setLineJoin (kCGLineJoinBevel) c.addRect (CGRectMake (32.5, 32.5, 191, 191)) c.drawPath (kCGPathFillStroke); c.restoreGState () # Draw some text at an angle c.saveGState () c.translateCTM (128, 128) c.rotateCTM ((-30.0 / 360) * (2 * math.pi)) c.translateCTM (-128, -128) c.setRGBStrokeColor (0,0,0,1) c.setRGBFillColor (1,1,1,1) c.selectFont ("Helvetica", 36, kCGEncodingMacRoman) c.setTextPosition (40, 118) c.setTextDrawingMode (kCGTextFillStroke) c.setShadow (CGSizeMake (0,-10), 2) c.showText ("hello, world", 12) c.restoreGState () # Write the bitmap to disk in PNG format c.writeToFile ("out.png", kCGImageFormatPNG)
Python
#!/usr/bin/python # contactsheet.py -- create contact sheet from a list of jpg files # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys, os, getopt, string, pwd, math, time from CoreGraphics import * baseCTM = 0 totSize = 0 # Generic Graphic classes # - sourceRect defines drawing coordinate system for graphic # - xform transform between this graphic and it's drawing coordinate transform # - boundingRect: computed axis-aligned bbox result of sending sourceRect through transform class Graphic: def __init__(self, sourceRect): self.sourceRect = sourceRect self.xform = CGAffineTransformIdentity def centerPoint(self): return CGPointMake(self.sourceRect.getMidX(),self.sourceRect.getMidY()).applyAffineTransform(self.xform) # drawing transform is pre multipled with new transforms (opposite of CTM) def concat(self, xform): self.xform = self.xform.concat(xform) def scaleAboutCenter(self,sx,sy): currentCenter = self.centerPoint() self.translate(-currentCenter.x, -currentCenter.y) self.xform = self.xform.concat(CGAffineTransformMakeScale(sx,sy)) self.translate(currentCenter.x, currentCenter.y) def rotateAboutCenter(self, angle): currentCenter = self.centerPoint() self.translate(-currentCenter.x, -currentCenter.y) self.xform = self.xform.concat(CGAffineTransformMakeRotation(angle*math.pi/180.0)) self.translate(currentCenter.x, currentCenter.y) def translate(self, tx, ty): self.xform = self.xform.concat(CGAffineTransformMakeTranslation(tx,ty)) def boundingRect(self): # compute bounding rect lowerLeft = CGPointMake(self.sourceRect.origin.x, self.sourceRect.origin.y) lowerLeft = lowerLeft.applyAffineTransform(self.xform) upperRight = CGPointMake(self.sourceRect.origin.x + self.sourceRect.size.width, self.sourceRect.origin.y + self.sourceRect.size.height) upperRight = upperRight.applyAffineTransform(self.xform) return CGRectMake(lowerLeft.x, lowerLeft.y, upperRight.x - lowerLeft.x, upperRight.y - lowerLeft.y).standardize() def render(self, c): c.saveGState() c.concatCTM(self.xform) self.draw(c) c.restoreGState() def centerInRect(self, rect): cx = rect.getMidX() cy = rect.getMidY() currentCenter = self.centerPoint() self.translate(cx - currentCenter.x, cy - currentCenter.y) def fitInRect(self, rect, preserveAspectRatio): self.centerInRect(rect) bbox = self.boundingRect() if(preserveAspectRatio): scale = rect.size.width/bbox.size.width; if (scale * bbox.size.height > rect.size.height): scale = rect.size.height/bbox.size.height self.scaleAboutCenter(scale,scale) else: self.scaleAboutCenter(rect.size.width/bbox.size.width, rect.size.height/bbox.size.height) class Rectangle(Graphic): def draw(self,c): c.addRect(self.sourceRect) ## return to "base space" for consistent linewidth c.saveGState() c.concatCTM(baseCTM.concat(c.getCTM().invert())) c.setLineWidth(1) c.strokePath() c.restoreGState() class Image(Graphic): def __init__(self,imageRef): self.i = imageRef Graphic.__init__(self, CGRectMake(0,0,imageRef.getWidth(), imageRef.getHeight())) def draw(self,c): c.drawImage(self.sourceRect, self.i) class TextString(Graphic): def __init__(self, rect, string, font, size, sizeToFit): # self.html = '<html><p style="font-size:%spx; font-family:%s;"> %s/p></html>\n' % (size, font, string) self.html = '<html><p <FONT="font-size:%spx; font-family:%s;"> %s/p></html>\n' % (size, font, string) self.rtf = '{\\rtf1\\mac\\ansicpg10000\\cocoartf102{\\fonttbl\\f0\\fnil\\fcharset77 %s;}\\f0\\fs%s %s}\n' % (font, size, string) if (sizeToFit) : rect = CGContextMeasureRTFTextInRect(CGDataProviderCreateWithString (self.rtf), rect) Graphic.__init__(self, rect) def draw(self,c): # tr = c.drawHTMLTextInRect (CGDataProviderCreateWithString (self.html), self.sourceRect) tr = c.drawRTFTextInRect (CGDataProviderCreateWithString (self.rtf), self.sourceRect) # helper to create an image from a filename def ImageFromFile(filename): # special case JPG files and render directly with CG -- this keeps created PDFs smaller if (os.path.splitext(filename)[1].upper() == '.JPG') : return Image(CGImageCreateWithJPEGDataProvider(CGDataProviderCreateWithFilename (filename), [0,1,0,1,0,1], 1, kCGRenderingIntentDefault)) return Image(CGImageImport (CGDataProviderCreateWithFilename (filename))) # # Contact Sheet specific classes # # # ContactSheetCell object # class ContactSheetCell(Graphic): def __init__(self, jpgFile): global totSize str = os.path.basename(jpgFile) str += "\\\n" + time.strftime('%x', time.localtime(os.path.getmtime(jpgFile))) str += "\\\n" + ('%dK' % (os.path.getsize(jpgFile)/1024)) totSize += os.path.getsize(jpgFile) self.label = TextString(CGRectMake(0,0,100,30), str , "LucidaGrande", 12, 0) self.image = ImageFromFile(jpgFile) self.image.fitInRect(CGRectMake(0,30,100,70), 1) self.border = Rectangle(CGRectMake(0,0,100,100)) Graphic.__init__(self, CGRectMake(0,0,100,100)) def draw(self,c): self.label.render(c) self.image.render(c) self.border.render(c) class ContactSheetPage(Graphic): def __init__(self, imageFiles, rect, cellSize): # create the array of cells self.cells = [ ContactSheetCell(i) for i in imageFiles] # position each cell row,col = 0,0 for cell in self.cells: x = rect.origin.x + col*cellSize if ( x + cellSize > rect.origin.x + rect.size.width) : col = 0 x = rect.origin.x row += 1 cell.fitInRect(CGRectMake(x, rect.origin.y + rect.size.height - (row + 1)*cellSize, cellSize, cellSize), 1) col += 1 Graphic.__init__(self, rect) def draw(self,c): for cell in self.cells: cell.render(c) def LayoutContactSheets(imageFiles, pageRect): rect = pageRect.inset(36,36) # use .5 inch margins nCols = int(math.ceil(math.sqrt(len(imageFiles)*rect.size.width/rect.size.height))) step = rect.size.width/nCols while (step < 72): # constrain tiles to be at least 1 inch nCols -= 1 step = rect.size.width/nCols nRows = int(math.floor(rect.size.height/step)) cellsPerPage = nRows*nCols base = 0 pages = [] while(base < len(imageFiles)): slice = imageFiles[base:base+cellsPerPage] pages.append(ContactSheetPage(slice, rect, step)) base += cellsPerPage return pages def usage (): print ''' usage: python contactsheet.py [OPTION]... JPG-FILES... Create a pdf contact sheet of JPGs. -o, --output=FILENAME ''' def main (): global baseCTM try: opts,args = getopt.getopt (sys.argv[1:], 'o:', ['output=']) except getopt.GetoptError: usage () sys.exit (1) output_file = "" page_rect = CGRectMake (0, 0, 612, 792) for o,a in opts: if o in ('-o', '--output'): output_file = a # need at least an output file if output_file == "": print "error: missing output filename" usage () sys.exit (1) c = CGPDFContextCreateWithFilename (output_file, page_rect) print "%d image files" % len(args) pages = LayoutContactSheets(args, page_rect) for page in pages: c.beginPage (page_rect) baseCTM = c.getCTM() page.render(c) c.endPage () # serialized the constructed PDF document to its file c.finish () print "Wrote output: \'%s\', %d pages, %dK bytes" % (output_file, len(pages), os.path.getsize(output_file)/1024) if __name__ == '__main__': main ()
Python
#!/usr/bin/python # watermark.py -- add a "watermark" to each page of a pdf document # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os, math, getopt, string def usage (): print ''' usage: python watermark.py [OPTION]... INPUT-PDF OUTPUT-PDF Add a "watermark" to a PDF document. -t, --text=STRING -f, --font-name=FONTNAME -F, --font-size=SIZE -c, --color=R,G,B ''' def main (): text = 'CONFIDENTIAL' color = (1, 0, 0) font_name = 'Gill Sans Bold' font_size = 36 page_rect = CGRectMake (0, 0, 612, 792) try: opts,args = getopt.getopt (sys.argv[1:], 't:f:F:c:', ['text=', 'font-name=', 'font-size=', 'color=']) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 2: usage () sys.exit (1) for o,a in opts: if o in ('-t', '--text'): text = a elif o in ('-f', '--font-name'): font_name = a elif o in ('-F', '--font-size'): font_size = float (a) elif o in ('-c', '--color'): color = map (float, string.split (a, ',')) c = CGPDFContextCreateWithFilename (args[1], page_rect) pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (args[0])) for p in range (1, pdf.getNumberOfPages () + 1): r = pdf.getMediaBox (p) c.beginPage (r) c.saveGState () c.drawPDFDocument (r, pdf, p) c.restoreGState () c.saveGState () c.setRGBFillColor (color[0], color[1], color[2], 1) c.setTextDrawingMode (kCGTextFill) c.setTextMatrix (CGAffineTransformIdentity) c.selectFont (font_name, font_size, kCGEncodingMacRoman) c.translateCTM (r.size.width - font_size, r.size.height - font_size) c.rotateCTM (-90.0 / 180 * math.pi) c.showTextAtPoint (0, 0, text, len (text)) c.restoreGState () c.endPage () c.finish () if __name__ == '__main__': main ()
Python
#!/usr/bin/python # filter-pdf.py -- apply a ColorSync Filter to each page of a pdf document # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys, os, math, getopt, string def usage (): print ''' usage: python filter-pdf.py FILTER INPUT-PDF OUTPUT-PDF Apply a ColorSync Filter to a PDF document. ''' def main (): page_rect = CGRectMake (0, 0, 612, 792) try: opts,args = getopt.getopt (sys.argv[1:], '', []) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 3: usage () sys.exit (1) filter = CGContextFilterCreateDictionary (args[0]) if not filter: print 'Unable to create context filter' sys.exit (1) pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (args[1])) if not pdf: print 'Unable to open input file' sys.exit (1) c = CGPDFContextCreateWithFilename (args[2], page_rect, filter) if not c: print 'Unable to create output context' sys.exit (1) for p in range (1, pdf.getNumberOfPages () + 1): r = pdf.getMediaBox (p) c.beginPage (r) c.drawPDFDocument (r, pdf, p) c.endPage () c.finish () if __name__ == '__main__': main ()
Python
#!/usr/bin/python # Usage: picttopdf pict-data-file # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os import string from CoreGraphics import * # we need two arguments, the zeroth argument is the name of the executable # and the first is the data file to convert if len(sys.argv) != 2: sys.stderr.write("Usage: picttopdf pict_data_file\n") sys.stderr.write("produces pict_data_file.pdf\n") sys.stderr.write("if the file suffix is .pict or .pic then it is replaced with .pdf\n") sys.exit() inFile = sys.argv[1]; if os.path.isfile(inFile): qdPict = QDPictCreateWithFilename(inFile) else: sys.stderr.write('ERROR: "'+inFile+'"' + " is not a file\n") sys.exit() if not qdPict: sys.stderr.write('ERROR: "'+inFile+'"' + " is not a PICT file!\n") sys.exit() pictRect = qdPict.getBounds(); if pictRect.size.width <= 0 or pictRect.size.height <= 0 : sys.stderr.write("Width or height of PICT bounds is zero! Can't use this picture!\n") sys.exit() result = os.path.splitext(inFile) extension = string.upper(result[1]) if (extension == ".PICT") or (extension == ".PIC"): outFile = result[0] +".pdf" else: outFile = inFile +".pdf" ctx = CGPDFContextCreateWithFilename(outFile, pictRect); if ctx: ctx.beginPage(pictRect); success = qdPict.drawToCGContext(ctx, pictRect) ctx.endPage(); ctx.finish() else: sys.stderr.write("Couldn't create PDF context for output file " + '"' + outFile + '"\n')
Python
#!/usr/bin/python # cmyk-bitmap.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * pi = 3.1415927 # Create a CYMK bitmap context with an opaque white background cs = CGColorSpaceCreateWithName (kCGColorSpaceUserCMYK) c = CGBitmapContextCreateWithColor (256, 256, cs, (0,0,0,0,1)) # Draw a yellow square with a red outline in the center c.saveGState () c.setRGBStrokeColor (1,0,0,1) # red c.setRGBFillColor (1,1,0,1) # yellow c.setLineWidth (3) c.setLineJoin (kCGLineJoinBevel) c.addRect (CGRectMake (32.5, 32.5, 191, 191)) c.drawPath (kCGPathFillStroke); c.restoreGState () # Draw some text at an angle c.saveGState () c.translateCTM (128, 128) c.rotateCTM ((-30.0 / 360) * (2 * pi)) c.translateCTM (-128, -128) c.setRGBStrokeColor (0,0,0,1) c.setRGBFillColor (1,1,1,1) c.selectFont ("Helvetica", 36, kCGEncodingMacRoman) c.setTextPosition (40, 118) c.setTextDrawingMode (kCGTextFillStroke) c.showText ("hello, world", 12) c.restoreGState () # Write the bitmap to disk as a TIFF c.writeToFile ("out.tiff", kCGImageFormatTIFF)
Python
#!/usr/bin/env python # doc2pdf.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * from fnmatch import fnmatch import os, sys, getopt def usage(): print ''' usage: python doc2pdf.py [OPTION] DOCUMENT[S] Convert any of several document types to PDF: Text: .txt .? .?? RTF: .rtf HTML: .htm .html .php Word: .doc .xml .wordml Options: -f, --font-size=SIZE ''' def drawDocument(input_file, font_size): '''Convert input file into PDF, using font_size''' text = CGDataProviderCreateWithFilename(input_file) if not text: return "Error: document '%s' not found"%(input_file) (root, ext) = os.path.splitext(input_file) output_file = root + ".pdf" pageRect = CGRectMake(0, 0, 612, 792) c = CGPDFContextCreateWithFilename(output_file, pageRect) c.beginPage(pageRect) if fnmatch(ext,".txt") or fnmatch(ext,".?") or fnmatch(ext,".??"): tr = c.drawPlainTextInRect(text, pageRect, font_size) elif fnmatch(ext,".rtf"): tr = c.drawRTFTextInRect(text, pageRect, font_size) elif fnmatch(ext,".htm*") or fnmatch(ext,".php"): tr = c.drawHTMLTextInRect(text, pageRect, font_size) elif fnmatch(ext,".doc"): tr = c.drawDocFormatTextInRect(text, pageRect, font_size) elif fnmatch(ext,"*ml"): tr = c.drawWordMLFormatTextInRect(text, pageRect, font_size) else: return "Error: unknown type '%s' for '%s'"%(ext, input_file) c.endPage() c.finish() return output_file def main(): '''Parse font_size option, then convert each argument''' try: opts,args = getopt.getopt(sys.argv[1:], 'f:', ['font-size=']) except getopt.GetoptError: usage() sys.exit(1) font_size = 12.0 for(o,a) in opts: if o in('-f', '--font-size'): font_size = float(a) if len(args) < 1: usage() exit() for arg in args: print arg, "->", drawDocument(arg, font_size) # Run as main if __name__ == '__main__': main()
Python
#!/usr/bin/python # image.py # Copyright (c) 2004, Apple Computer, Inc., all rights reserved. # IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in # consideration of your agreement to the following terms, and your use, installation, # modification or redistribution of this Apple software constitutes acceptance of these # terms. If you do not agree with these terms, please do not use, install, modify or # redistribute this Apple software. # In consideration of your agreement to abide by the following terms, and subject to these # terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in # this original Apple software (the "Apple Software"), to use, reproduce, modify and # redistribute the Apple Software, with or without modifications, in source and/or binary # forms; provided that if you redistribute the Apple Software in its entirety and without # modifications, you must retain this notice and the following text and disclaimers in all # such redistributions of the Apple Software. Neither the name, trademarks, service marks # or logos of Apple Computer, Inc. may be used to endorse or promote products derived from # the Apple Software without specific prior written permission from Apple. Except as expressly # stated in this notice, no other rights or licenses, express or implied, are granted by Apple # herein, including but not limited to any patent rights that may be infringed by your # derivative works or by other works in which the Apple Software may be incorporated. # The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, # EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS # USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. # IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, # REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND # WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR # OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from CoreGraphics import * import sys if len (sys.argv) >= 2: inputFile = sys.argv[1]; else: inputFile = "out.png" outputFile = "out.pdf" i = CGImageImport (CGDataProviderCreateWithFilename (inputFile)) print "Image \'%s\' size is (%d,%d)" % (inputFile, i.getWidth(), i.getHeight()) # create an output document to draw the image into pageRect = CGRectMake (0, 0, 612, 792) c = CGPDFContextCreateWithFilename (outputFile, pageRect) c.beginPage (pageRect) c.drawImage (pageRect.inset (72, 72), i) c.endPage () c.finish () print "Output PDF file created at \'%s\' " % outputFile
Python
from __future__ import division import numpy as np import sys import analysedata as adata #Find last signal signal recorded during Qin Bin scan. #Set 'dirname' to directory containing files to be analysed. #Set 'indices_select' to choose files by index (indices_select=[] selects all files) #'channel_id' can be used to select particular channels # #'cut_off_freq' determines the cut off point in the high pass filter #Set 'method' to 'fixed' or 'noise' to determine the signal threshold in two ways. In the 'fixed' case # a fixed voltage threshold is used (threshold_volts in signal_loss_time) while in the 'noise' case # the signal is assumed to be some multiple of the rms of the noise calculated at the end of the data #dirname ="../data/SortByDate/2014/3/24/dmag/" #dirname ="../data/SortByDate/2014/3/25/D0_1012_D1_140_F7/" #dirname = "../data/SortByDate/2014/3/27/Corr_700A/" dirname = "../data/SortByDate/2014/3/31/QinBin/F7/" # indices_select = [] #select particular indices from each channel, empty list means process all files #channel_id = ["CH1","CH2","CH3"] #string to identify each channel channel_id = ["F1","F5","F7"] #identifier for channels to be analysed #select channel files ch_files_sel = adata.select_filenames(dirname, indices_select, channel_id) print "ch_files_sel ",ch_files_sel #set parameters for high pass filter cut_off_freq = 0.5e6 #0.5 MHz nstd = 10 #set threshold above noise to determine final loss point method = 'noise' #choose "fixed" or "noise" #calculate loss time loss_time_all = [] for chf in ch_files_sel: loss_time_ch =[] if chf != []: for chf1 in chf: #read scope data tdat_chf, data_chf = adata.read_scope(dirname, chf1) loss_time = adata.signal_loss_time(tdat_chf, data_chf, method) loss_time_ch.append(loss_time) loss_time_all.append(loss_time_ch) print "loss time all ",loss_time_all, "len ",len(loss_time_all) #-------------------------Rest specific to file format used at particular time----------------- #31/3/14 - map each index to probe position F5_pos = [890, 870, 850, 830, 800, 750, 700, 650, 600, 550, 500, 450, 425, 400, 380, 360, 340] F1_pos = [870, 850, 800, 750, 700, 650, 600, 550, 500, 450, 425, 400, 380, 360, 340] F7_pos = [870, 850, 800, 750, 700, 650, 600, 550, 500, 450, 425, 400, 380, 360, 340, 320, 300] loss_time_flatten = loss_time_all[0] if "F1" in dirname: fout = 'QinBin_F1.txt' fpos = list(F1_pos) elif "F5" in dirname: fout = 'QinBin_F5.txt' fpos = list(F5_pos) elif "F7" in dirname: fout = 'QinBin_F7.txt' fpos = list(F7_pos) ff = open(fout,"w") print >>ff, "probe position (mm) loss time (us)" for pos, losst in zip(fpos, loss_time_flatten): print >>ff, pos, 1e6*losst ff.close()
Python
#!/usr/bin/python import matplotlib import glob from pylab import * import numpy as np from analysedata import * from scipy import interpolate #Written by S. Sheehy on 27/3/2014 #Updates: #21/10/2014: Updated to use individual ranges for each probe calculation (S. Sheehy) # matplotlib.rcParams['legend.fontsize']=8 def calcsingleDispersion(pvals, rvals): '''Use to calculate a single value of the dispersion for a set of r vs p data''' #central momentum pcentral=mean(pvals) dp=max(pvals)-min(pvals) dpp=dp/pcentral #print "delta p: ", dp print "delta p/p: ", dpp dr=max(rvals)-min(rvals) print "dr: ", dr return p*(dr/dp) def idealDispersionvsr(rvals, kval): '''returns an array which contains the ideal dispersion values vs radius with a given fixed k value''' disp=np.array(rvals)/(kval+1.0) return disp def calcDispersion(pvals, rvals): '''Use to calculate the dispersion over a range of radii''' disp=[] dpp_array=[] for i in range(len(rvals)-1): dr=rvals[i+1]-rvals[i] dp=pvals[i+1]-pvals[i] dpp=dp/pvals[i] disp.append(pvals[i]*dr/dp) #changed from dr/dpp dpp_array.append(dpp) #dispersion = dr/(dp/p) return disp, dpp_array def calckfromdisp(Dval, rval): #gamma_val=(Eval+938.0)/938.0 #print gamma_val #kval=(1-Dval)*pow(gamma_val,2)-1 kval=(rval/Dval)-1 #print kval return kval def calcKvalue_poly(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' #fvals=interpolate.splev(tvals, findyfromx_spline(f_rf, t_rf), der=0) #E_vals=interpolate.splev(tvals, findyfromx_spline(E_rf, t_rf),der=0) fvals=map(findFfromt(t_rf, f_rf), tvals) E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array def calcKvalue(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' #fvals=interpolate.splev(tvals, findyfromx_spline(f_rf, t_rf), der=0) E_vals=interpolate.splev(tvals, findyfromx_spline(E_rf, t_rf),der=0) fvals=map(findFfromt(t_rf, f_rf), tvals) #E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array if __name__ == "__main__": '''This analysis code needs updating/checking!!!''' colors = ['b', 'g', 'r'] #Directory for plots resdir="Results/" #Filenames for plots pfile1 ="r_vs_t.pdf" pfile2="rfpattern.pdf" #pfile2="k_vs_t.pdf" pfile3="p_vs_r.pdf" pfile4="Dispersion_vs_E.pdf" pfile5="Dispersion_vs_r.pdf" pfile7="kvalue_vs_E.pdf" #fig=figure(num=1, figsize=(6.5, 10.5), dpi=150, facecolor='w', edgecolor='k') #Data directory #dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/COD_data_140325/" #dir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-27/" dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/Qin_Bin_31_3_31/" rfdir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-25/rf_pattern/" #Filenames for sets of data #set1=glob.glob(dir+"QinBin_F?.txt") #print set1 set1=["QinBin_F1.txt", "QinBin_F5.txt", "QinBin_F7.txt"] #set1 =["D0_0amps_F1.txt" ,"D0_0amps_F5.txt" ,"D0_0amps_F7.txt"] #468A #set1=["D0_550Aamps_F1.txt" ,"D0_550Aamps_F5.txt" ,"D0_550Aamps_F7.txt"] #550A 27/3/2014 #set1 =["D0_140amps_F1.txt", "D0_140amps_F5.txt", "D0_140amps_F7.txt"] #468A #set1=["D0_400Aamps_F1.txt", "D0_400Aamps_F5.txt", "D0_400Aamps_F7.txt"] #400A 27/3/14 #set1=["D0_700amps_F1.txt", "D0_700amps_F5.txt", "D0_700amps_F7.txt"] #27/3/2014 #get the radial position at each time from each probe data1=readset(dir, set1) #gets the data #time_range=np.arange(500,15000,1) #rad_range=np.arange(300,420,1) time_range=[] rad_range=[] radial_values=[] time_values=[] probenames=["F1","F5","F7"] proberadius=4300.0 #mm kvalue=7.6 fig=figure(num=1, figsize=(8.5, 6.5), dpi=150, facecolor='w', edgecolor='k') #Get radius as a function of t for the three probes (ie. CO movement) for i in range(len(data1)): fittedrfunc=findRfromt(data1[i][0], data1[i][1]) j=data1[i][0].argsort() time_range=np.arange(min(data1[i][1]), max(data1[i][1]), 10) print "time range: ", min(data1[i][1]), max(data1[i][1]) #Rfit_values=interpolate.splev(time_range, findyfromx_spline(data1[i][0][j], data1[i][1][j]), der=0) Rfit_values=map(fittedrfunc, time_range) radial_values.append(Rfit_values) time_values.append(time_range) plot(data1[i][1], data1[i][0], 'x', color=colors[i], label=probenames[i]) #plot R vs t for each of the 3 probes for i in range(len(probenames)): plot(time_values[i], radial_values[i], color=colors[i], label=probenames[i]+"fit") xlabel(r'Time [$\mu$sec]', size=12) ylabel(r'Radius [mm]',size=12) legend(loc=0) savefig(resdir+pfile1) close() #also calculate the average value of CO movement # avg_radial_values=[] # max_radial_offset=[] # min_radial_offset=[] # for r in np.transpose(np.array(radial_values)): # avg_radial_values.append(np.mean(r)) # max_radial_offset.append(np.max(r)-np.mean(r)) # min_radial_offset.append(np.mean(r)-np.min(r)) #Convert the time to an energy then a momentum (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 rfdat_E=np.array(rfdat[1])*1E-6 rfdat_F=np.array(rfdat[2]) #frequency in hertz mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) toffset= -93.3 #make a list of momentum values corresponding to a given set of time points fittedpfunc=findPfromt(rfdat_t,rfdat_p) #using RF data #get a range of momenta over the given time range for each probe P_values=[] E_values=[] for i in range(len(probenames)): #P_values.append(interpolate.splev(time_values[i]+toffset, findyfromx_spline(rfdat_p, rfdat_t), der=0)) P_values.append(map(fittedpfunc, time_values[i]+toffset)) E_values.append(map(lambda x: mom_to_ke(mass, x), P_values[i])) #plot time vs momentum fig=figure(num=3, figsize=(8, 10), dpi=150, facecolor='w', edgecolor='k') subplot(2,1,1) plot(rfdat_t, rfdat_p, 'k--') for i in range(len(probenames)): plot(time_values[i], P_values[i], '-', color=colors[i], label=probenames[i]) xlabel(r'time [$\mu$sec]', size=12) ylabel(r'Momentum [MeV/c]',size=12) # #plot time vs energy subplot(2,1,2) plot(rfdat_t, rfdat_E, 'k--') for i in range(len(probenames)): plot(time_values[i], E_values[i], '-', color=colors[i], label=probenames[i]) xlabel(r'time [$\mu$sec]', size=12) ylabel(r'Energy[MeV]',size=12) savefig(resdir+pfile2) close() #CALCULATE THE DISPERSION #first adjust radial values to be in [m] and with correct offset from r=0 radii_metres=[] dispresult=[] dpp=[] for probe in range(len(probenames)): radii_metres.append((np.array(radial_values[probe])+proberadius)/1E3) dispresult.append(calcDispersion(P_values[probe], radii_metres[probe])[0]) dpp.append(calcDispersion(P_values[probe], radii_metres[probe])[1]) #sys.exit() #plot deltap/p with momentum # pfile4a="dpp_vs_p.pdf" # fig=figure(num=7, figsize=(6.5, 10.5), dpi=150, facecolor='w', edgecolor='k') # for i in range(len(probenames)): # plot(P_values[1:], dpp[i], color=colors[i], label=probenames[i]) # xlabel(r'Momentum [MeV/c]', size=12) # ylabel(r'dp/p',size=12) # legend() # savefig(pfile4a) #plot dispersion with radial probe position fig=figure(num=4, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') for i in range(len(probenames)): plot(radii_metres[i][1:], dispresult[i], color=colors[i], label=probenames[i]) #plot(rad_range_m, idealDispersionvsr(rad_range_m, kvalue)) xlabel(r'Radius [m]', size=12) ylabel(r'Dispersion [m]',size=12) ylim([0.3,0.8]) legend() savefig(resdir+pfile5) close() fig=figure(num=5, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') for i in range(len(probenames)): plot(E_values[i][1:], dispresult[i], color=colors[i], label=probenames[i]) #plot(rad_range_m, idealDispersionvsr(rad_range_m, kvalue)) xlabel(r'Energy [MeV]', size=12) ylabel(r'Dispersion [m]',size=12) ylim([0.3,0.8]) legend() savefig(resdir+pfile4) close() #plot radial position with momentum fig=figure(num=6, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') #plot( P_values,np.array(avg_radial_values),'k:', label="avg") for i in range(len(probenames)): plot(P_values[i], radii_metres[i], color=colors[i], label=probenames[i]) xlabel(r'Momentum [MeV/c]', size=12) ylabel(r'Radius [m]',size=12) legend() savefig(resdir+pfile3) close() #plot effective k value calculated from dispersion fig=figure(num=7, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') k_values=[] for i in range(len(probenames)): k_values.append(map(lambda x, y: calckfromdisp(x,y), dispresult[i], radii_metres[i][1:])) #plot(time_values[i][1:], k_values[i], '--', color=colors[i], label=probenames[i]+'dmethod') xlabel(r'time [us]', size=12) ylabel(r'k value',size=12) ylim([5.5,9]) #legend() #savefig(resdir+pfile7) #CALCULATE THE K-VALUE BASED ON FREQUENCY FROM EACH TIME POINT #THIS ALSO USES THE LOOKUP TABLE TO FIND E AND USE ESTIMATED GAMMA FACTOR FOR A MORE EXACT RESULT kresult=[] #fig=figure(num=3, figsize=(6, 15), dpi=150, facecolor='w', edgecolor='k') for probe in range(len(probenames)): fittedtfunc=findtfromR(data1[probe][1], data1[probe][0]) #from experimental data j=data1[probe][0].argsort() #data sorted by index of sorted radial values #print data1[probe][0][j] #print data1[probe][1][j] #tfit_values=interpolate.splev(radial_values[probe], findyfromx_spline(data1[probe][1][j], data1[probe][0][j]), der=0) #use cubic spline to fit time values for finer radial points #tfit_values=map(lambda x: x+toffset, tfit_values) #shift t values by timing offset tfit_values=map(fittedtfunc+toffset, radial_values[probe]) #find t values corresponding to finer points in r kresult.append(calcKvalue_poly(rfdat_t, rfdat_F, rfdat_E, tfit_values, radii_metres[probe])) #calculate the k value in this range #print kresult[probe] plot(time_values[probe][1:],kresult[probe], '-', color=colors[probe],label=probenames[probe]) xlabel(r'time [us]', size=12) ylabel(r'effective k value',size=12) legend() #xlabel(r'time [$\mu$sec]', size=12) savefig(resdir+pfile7) sys.exit()
Python
#!/usr/bin/python import matplotlib import glob from pylab import * import numpy as np from analysedata import * #from dispersion_analysis140327 import * matplotlib.rcParams['legend.fontsize']=8 def calcKvalue(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' fvals=map(findFfromt(t_rf, f_rf), tvals) E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV #print E_vals gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array colors = ['b', 'g', 'r'] #Filenames for plots pfile1 = "r_vs_t.pdf" pfile2="k_vs_t.pdf" #Data directory #dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/COD_data_140325/" #dir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-27/" dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/Qin_Bin_31_3_31/" rfdir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-25/rf_pattern/" #Filenames for sets of data #set1=glob.glob(dir+"QinBin_F?.txt") #print set1 set1=["QinBin_F1.txt", "QinBin_F5.txt", "QinBin_F7.txt"] #set1 =["D0_0amps_F1.txt" ,"D0_0amps_F5.txt" ,"D0_0amps_F7.txt"] #468A #set1=["D0_550Aamps_F1.txt" ,"D0_550Aamps_F5.txt" ,"D0_550Aamps_F7.txt"] #550A 27/3/2014 #set1 =["D0_140amps_F1.txt", "D0_140amps_F5.txt", "D0_140amps_F7.txt"] #468A #set1=["D0_400Aamps_F1.txt", "D0_400Aamps_F5.txt", "D0_400Aamps_F7.txt"] #400A 27/3/14 #set1=["D0_700amps_F1.txt", "D0_700amps_F5.txt", "D0_700amps_F7.txt"] #27/3/2014 use_radius_range=True use_time_range=False #For a given time range, get the radial position at each time from each probe data1=readset(dir, set1) #gets the data time_range=np.arange(500,1500,1) #rad_range=np.arange(300,420,1) radial_values=[] time_values=[] probenames=["F1","F5","F7"] proberadius=4300.0 #mm kvalue=7.6 fig=figure(num=1, figsize=(10.5, 6.5), dpi=150, facecolor='w', edgecolor='k') #Lookup table of time, frequency and estimated energy (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 #time in musec rfdat_E=np.array(rfdat[1])*1E-6 #Energy in MeV rfdat_F=np.array(rfdat[2]) #frequency in hertz #Can also map the momentum values from the Energy values. mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) #CALCULATE THE K-VALUE BASED ON FREQUENCY FROM EACH TIME POINT #THIS ALSO USES THE LOOKUP TABLE TO FIND E AND USE ESTIMATED GAMMA FACTOR FOR A MORE EXACT RESULT kresult=[] toffset= -93.3 # musec timing offset from 31/3/14 data fig=figure(num=3, figsize=(6, 10), dpi=150, facecolor='w', edgecolor='k') smoothed_data=False for probe in range(len(probenames)): if smoothed_data==True: rad_range_1=np.arange(min(data1[probe][0]),max(data1[probe][0]), 1) else: rad_range_1=sort(np.array(data1[probe][0])) fittedtfunc=findtfromR(data1[probe][1], data1[probe][0]) tfit_values=map(fittedtfunc+toffset, rad_range_1) rad_range_m=(rad_range_1+proberadius)/1E3 subplot(2,1,1) plot(tfit_values, rad_range_m, '-', color=colors[probe]) plot(data1[probe][1]+toffset, (np.array(data1[probe][0])+proberadius)/1E3, 'x',color=colors[probe]) ylabel(r'radius [m]') subplot(2,1,2) kresult.append(calcKvalue(rfdat_t, rfdat_F, rfdat_E, tfit_values, rad_range_m)) plot(tfit_values[:-1],kresult[probe], '.-', color=colors[probe],label=probenames[probe]) legend() xlabel(r'time [$\mu$sec]', size=12) ylabel(r'measured k',size=12) ylim([6,9]) savefig(pfile2) sys.exit()
Python
title = 'Read scope trace' import sys sys.path[:0] = ['../../..'] import os import numpy import scipy import scipy.optimize #import Tkinter import Pmw import time #import shutil import string import pylab as plt import math #from Tkinter import * # # # class Bpm: def __init__(self): global dirname, filenum, file_c1, file_c2, file_c3, file_c4 dirname = '/Users/machida/Documents/FFAGOthers/KURRI/KURRI2014data/' filenum = '2014-03-26/TUNE_Meas/' curr = '-15.0A_D1000A' file_c1 = dirname + filenum + 'F_773.3A_Foil_86mm_ST6_' + curr + '_S11_1st_ch3.csv' file_c2 = dirname + filenum + 'F_773.3A_Foil_86mm_ST6_' + curr + '_S7up_ch1.csv' file_c3 = dirname + filenum + 'F_773.3A_Foil_86mm_ST6_' + curr + '_S7dw_ch2.csv' # filenum = '2014-03-24/ST5V_D950/' # curr = '-2.93' # file_c1 = dirname + filenum + 'D950_ST5_' + curr + '_ch1.csv' # file_c2 = dirname + filenum + 'D950_ST5_' + curr + '_ch2.csv' # file_c3 = dirname + filenum + 'D950_ST5_' + curr + '_ch3.csv' # filenum = '2014-03-24/dmag/' # curr = '1200' # file_c1 = dirname + filenum + 'D' + curr + '_ch1.csv' # file_c2 = dirname + filenum + 'D' + curr + '_ch2.csv' # file_c3 = dirname + filenum + 'D' + curr + '_ch3.csv' self.ch23out() # vertical bpm self.bpm = Vbpm() # read data self.bpmsig = self.bpm.possig() # bpmsig = self.bpm.difsig() # bpmsig = self.bpm.difsig_wired() print 'data length =', len(self.bpmsig) gx = [] gy = [] for i in range(len(self.bpmsig)): gx.append(self.bpmsig[i][0]) gy.append(self.bpmsig[i][1]) plt.xlabel('time (us)') plt.ylabel('bunch signal and peak (arb.)') plt.xlim(2., 40.) plt.ylim(-0.22,0.22) plt.plot(gx, gy, 'r-') plt.show() # Ch2 out def ch2out(self): self.ch2 = Ch2() c2 = self.ch2.scope_ch self.gx2 = [] self.gy2 = [] for i in range(len(c2)): self.gx2.append(c2[i][0]) self.gy2.append(c2[i][1]) plt.xlabel('time (us)') plt.ylabel('bunch signal and peak (arb.)') plt.xlim(0., 40.) plt.plot(self.gx2, self.gy2, 'r-') plt.show() # Ch3 out def ch3out(self): self.ch3 = Ch3() c3 = self.ch3.scope_ch self.gx3 = [] self.gy3 = [] cfac = 1.8 for i in range(len(c3)): self.gx3.append(c3[i][0]) self.gy3.append(cfac*c3[i][1]) plt.xlabel('time (us)') plt.ylabel('bunch signal and peak (arb.)') plt.xlim(0., 40.) plt.plot(self.gx3, self.gy3, 'b-') plt.show() # CH2+Ch3 out def ch23out(self): self.ch2out() self.ch3out() plt.xlabel('time (us)') plt.ylabel('bunch signal and peak (arb.)') plt.xlim(0., 40.) plt.plot(self.gx2, self.gy2, 'r-') plt.plot(self.gx3, self.gy3, 'b-') plt.show() # # NAFF tune # class Tune: def __init__(self): self.bpmraw = Bpm() self.naff() def naff(self): def avcal(dpt): n = 0 av = 0 for i in range(0,len(dpt)): if dpt[i] < 1.E9: n += 1 av += dpt[i] if n > 0: av = av/n else: av = 1.E9 for i in range(0,len(dpt)): if dpt[i] < 1.E9: dpt[i] = dpt[i] - av return av def resal(q): twopi = 2*math.pi cs = 0 sn = 0 for i in range(0,len(dpt)): if dpt[i] < 1.E9: # no filter #cs += dpt[i]*math.cos(twopi*q*i) #sn += dpt[i]*math.sin(twopi*q*i) # Hanning filter # cs += dpt[i]*math.cos(twopi*q*ind[i]) * 2*(math.sin(twopi*ind[i]/(2*len(dpt))))**2 # sn += dpt[i]*math.sin(twopi*q*ind[i]) * 2*(math.sin(twopi*ind[i]/(2*len(dpt))))**2 cs += dpt[i]*math.cos(twopi*q*ind[i]) * 2*(math.sin(twopi*ind[i]/(2*self.nw)))**2 sn += dpt[i]*math.sin(twopi*q*ind[i]) * 2*(math.sin(twopi*ind[i]/(2*self.nw)))**2 #esm = 1./math.sqrt(math.sqrt(cs*cs + sn*sn)) if cs*cs+sn*sn !=0.: esm = 1./((cs*cs + sn*sn)) else: esm = 1. return esm ind = [] dpt = [] self.nw = 30 for i in range(self.nw): ind.append(i) dpt.append(self.bpmraw.bpmsig[i][1]) av = avcal(dpt) self.htune = scipy.optimize.fminbound(resal, 0.001, 1.0, xtol = 1.e-05, disp=3) if self.htune > 0.5: self.htune = 1. - self.htune print 'tune = ', self.htune # # vertical BPM # class Vbpm: def __init__(self): self.s12 = Ch1() self.s7up = Ch2() self.s7dw = Ch3() self.idelay = 0 self.cfac = 1.8 def difsig(self): self.pkup = self.s7up.peak() self.pkdw = self.s7dw.peak() len_up = len(self.pkup) len_dw = len(self.pkdw) print len_up, len_dw if len_up < len_dw: len_s7 = len_up else: len_s7 = len_dw self.dif = [] for i in range(len_s7): self.dif.append( ( self.pkup[i][0], self.pkup[i][1]-self.cfac*self.pkdw[i][1] ) ) return self.dif def sumsig(self): self.pkup = self.s7up.peak() self.pkdw = self.s7dw.peak() len_up = len(self.pkup) len_dw = len(self.pkdw) if len_up < len_dw: len_s7 = len_up else: len_s7 = len_dw self.sum = [] for i in range(len_s7): self.sum.append( ( self.pkup[i][0], self.pkup[i][1]+self.cfac*self.pkdw[i][1] ) ) return self.sum def possig(self): self.difsig() self.sumsig() self.pkup = self.s7up.peak() self.pkdw = self.s7dw.peak() len_up = len(self.pkup) len_dw = len(self.pkdw) if len_up < len_dw: len_s7 = len_up - self.idelay else: len_s7 = len_dw - self.idelay self.pos = [] for i in range(len_s7): if self.sum[i][1] != 0.: self.pos.append( ( self.pkup[i][0], self.dif[i][1]/self.sum[i][1] ) ) else: self.pos.append( ( self.pkup[i][0], 1000000. ) ) f_data_w = open('pksig', 'w') for i in range(len(self.pos)): f_data_w.write('%13.6e %13.6e\n' % (float(self.pos[i][0]), float(self.pos[i][1]))) f_data_w.close() return self.pos def difsig_wired(self): len_up = len(self.s7up.scope_ch) len_dw = len(self.s7dw.scope_ch) if len_up < len_dw: len_s7 = len_up else: len_s7 = len_dw self.dif_wired = [] for i in range(len_s7): self.dif_wired.append( ( self.s7up.scope_ch[i][0], self.s7up.scope_ch[i][1] ) ) return self.dif_wired def peak(self): nw = 0 fst = 0 pmin = 1.E9 pmax = -1.E9 self.peakvalue = [] for i in range(len(self.dif)): if (self.dif[i][0] > 2.86 + 0.64*nw) & (self.dif[i][0] < 2.86 + 0.64*(nw+1) - 0.1): if fst == 0: basel = self.dif[i][1] fst = 1 if pmin > self.dif[i][1]: pmin = self.dif[i][1] pmin0 = self.dif[i][0] if pmax < self.dif[i][1]: pmax = self.dif[i][1] pmax0 = self.dif[i][0] if (self.dif[i][0] > 2.86 + 0.64*nw) & (self.dif[i][0] > 2.86 + 0.64*(nw+1) - 0.1): baser = self.dif[i][1] pmin = pmin - (basel+baser)/2 pmax = pmax - (basel+baser)/2 if abs(pmin) > abs(pmax): self.peakvalue.append( (pmin0, pmin) ) else: self.peakvalue.append( (pmax0, pmax) ) nw += 1 fst = 0 pmin = 1.E9 pmax = -1.E9 return self.peakvalue # # read trace ch1 data # class Ch1: def __init__(self): print 'reading ', file_c1, '.' f_ch1_data = open(file_c1, 'r') n = 0 self.scope_ch = [] for line in f_ch1_data: timeandamp = line.split(',') n += 1 if ((n > 18) & (n <=100000)): self.scope_ch.append( ( 1.E6*float(timeandamp[0]), float(timeandamp[1]) ) ) f_ch1_data.close() # check f_data_w = open('check_ch1', 'w') for i in range(1,len(self.scope_ch)): f_data_w.write('%13.6e %13.6e\n' % (self.scope_ch[i][0], self.scope_ch[i][1])) f_data_w.close() def average(self): amp_av = 0. for i in range(0,len(self.scope_ch)): amp_av += self.scope_ch[i][1] amp_av = amp_av/len(self.scope_ch) print 'average of ch1 ', amp_av return amp_av # # read trace ch2 data # class Ch2: def __init__(self): print 'reading ', file_c2, '.' f_ch2_data = open(file_c2, 'r') n = 0 self.scope_ch = [] for line in f_ch2_data: timeandamp = line.split(',') n += 1 if ((n > 18) & (n <=100000)): self.scope_ch.append( ( 1.E6*float(timeandamp[0]), float(timeandamp[1]) ) ) f_ch2_data.close() # check f_data_w = open('check_ch2', 'w') for i in range(1,len(self.scope_ch)): f_data_w.write('%13.6e %13.6e\n' % (self.scope_ch[i][0], self.scope_ch[i][1])) f_data_w.close() def average(self): amp_av = 0. for i in range(0,len(self.scope_ch)): amp_av += self.scope_ch[i][1] amp_av = amp_av/len(self.scope_ch) print 'average of ch2 ', amp_av return amp_av def peak(self): nw = 0 fst = 0 pmin = 1.E9 pmax = -1.E9 self.peakvalue = [] for i in range(len(self.scope_ch)): if (self.scope_ch[i][0] > 2.86 + 0.64*nw) & (self.scope_ch[i][0] < 2.86 + 0.64*(nw+1) - 0.1): if fst == 0: basel = self.scope_ch[i][1] fst = 1 if pmin > self.scope_ch[i][1]: pmin = self.scope_ch[i][1] pmin0 = self.scope_ch[i][0] if pmax < self.scope_ch[i][1]: pmax = self.scope_ch[i][1] pmax0 = self.scope_ch[i][0] if (self.scope_ch[i][0] > 2.86 + 0.64*nw) & (self.scope_ch[i][0] > 2.86 + 0.64*(nw+1) - 0.1): baser = self.scope_ch[i][1] pmin = pmin - (basel+baser)/2 pmax = pmax - (basel+baser)/2 if abs(pmin) > abs(pmax): self.peakvalue.append( (pmin0, pmin) ) else: self.peakvalue.append( (pmax0, pmax) ) nw += 1 fst = 0 pmin = 1.E9 pmax = -1.E9 f_data_w = open('pksig_ch2', 'w') for i in range(len(self.peakvalue)): f_data_w.write('%13.6e %13.6e\n' % (float(self.peakvalue[i][0]), float(self.peakvalue[i][1]))) f_data_w.close() return self.peakvalue # # read trace ch3 data # class Ch3: def __init__(self): print 'reading ', file_c3, '.' f_ch3_data = open(file_c3, 'r') n = 0 self.scope_ch = [] for line in f_ch3_data: timeandamp = line.split(',') n += 1 if ((n > 18) & (n <=100000)): self.scope_ch.append( ( 1.E6*float(timeandamp[0]), float(timeandamp[1]) ) ) f_ch3_data.close() # check f_data_w = open('check_ch3', 'w') for i in range(1,len(self.scope_ch)): f_data_w.write('%13.6e %13.6e\n' % (self.scope_ch[i][0], self.scope_ch[i][1])) f_data_w.close() def average(self): amp_av = 0. for i in range(0,len(self.scope_ch)): amp_av += self.scope_ch[i][1] amp_av = amp_av/len(self.scope_ch) print 'average of ch3 ', amp_av return amp_av def peak(self): nw = 0 fst = 0 pmin = 1.E9 pmax = -1.E9 self.peakvalue = [] for i in range(len(self.scope_ch)): if (self.scope_ch[i][0] > 2.86 + 0.64*nw) & (self.scope_ch[i][0] < 2.86 + 0.64*(nw+1) - 0.1): if fst == 0: basel = self.scope_ch[i][1] fst = 1 if pmin > self.scope_ch[i][1]: pmin = self.scope_ch[i][1] pmin0 = self.scope_ch[i][0] if pmax < self.scope_ch[i][1]: pmax = self.scope_ch[i][1] pmax0 = self.scope_ch[i][0] if (self.scope_ch[i][0] > 2.86 + 0.64*nw) & (self.scope_ch[i][0] > 2.86 + 0.64*(nw+1) - 0.1): baser = self.scope_ch[i][1] pmin = pmin - (basel+baser)/2 pmax = pmax - (basel+baser)/2 if abs(pmin) > abs(pmax): self.peakvalue.append( (pmin0, pmin) ) else: self.peakvalue.append( (pmax0, pmax) ) nw += 1 fst = 0 pmin = 1.E9 pmax = -1.E9 f_data_w = open('pksig_ch3', 'w') for i in range(len(self.peakvalue)): f_data_w.write('%13.6e %13.6e\n' % (float(self.peakvalue[i][0]), float(self.peakvalue[i][1]))) f_data_w.close() return self.peakvalue # # Zero crossing points # BPM signla in Ch2. # class Scope: def __init__(self): self.ch = Ch2() def rawdata(self): return self.ch.scope_ch # # Top level # if __name__ == '__main__': dialog = None widget = Tune()
Python
#!/usr/bin/python import matplotlib matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['legend.fontsize']=12 from pylab import * from scipy import interpolate import numpy as np import os #DAVID'S READSCOPE FUNCTION def read_scope(dirname, filename, tfactor=1): """Read scope data. The script deals with two specific scope formats - that used in November 2013, and in March 2014. The two are distinguished by looking for the string DP04104 that appears in the later case""" filepath = dirname + filename print 'reading ', filepath f_data = open(filepath, 'r') n = 0 tdat = [] ydat = [] for line in f_data: timeandamp = line.split(',') #identify scope if n == 0: if timeandamp[1][:7] == 'DPO4104': nskip = 17 xi = 0 yi = 1 else: nskip = 6 xi = 3 yi = 4 if n > nskip: if line !='\r\n': tdat.append(tfactor*float(timeandamp[xi])) ydat.append(float(timeandamp[yi])) else: break n += 1 f_data.close() return tdat, ydat #DAVIDS HIGHPASS FILTER FUNCTION added 26/3/14 def highpass(signal,dt,RC): """ Return RC high-pass output samples, given input samples, time constant RC and time interval dt""" alpha = RC/(RC + dt) y = [signal[0]] for i in range(1,len(signal)): y.append(alpha*y[i-1] + alpha*(signal[i] - signal[i-1])) return y #DAVIDS PEAK FINDING ALGORITHM ADDED 15/5/2014 def find_peaks(xdat, ydat, interval, find_hminus): pmxi = [] pmx = [] pmy = [] pmi = [] for i in range(int(len(xdat)/interval) + 10): my = 0. my_min = 100 winsize = int(0.5*interval) if i == 0 : istart = 0 xwindow = xdat[:2*winsize] ywindow = ydat[:2*winsize] elif i == 1: istart = 2*winsize xwindow = xdat[2*winsize:4*winsize] ywindow = ydat[2*winsize:4*winsize] else: icen = mi + interval #test if in range if icen + winsize > len(xdat): print "reach end of data ",icen+winsize, len(xdat) break xwindow = xdat[icen-winsize: icen+winsize] ywindow = ydat[icen-winsize: icen+winsize] istart = icen - winsize for xd,yd in zip(xwindow, ywindow): #look for positive H- peak if i == 0 and find_hminus: if yd > my: mx = xd my = yd mi = ywindow.index(yd) + istart else: #look for negative proton peak if yd < my: mx = xd my = yd mi = ywindow.index(yd) + istart if i >= 10 and i <= 5: #if xwindow[0] > 88 and xwindow[0] < 100: #plt.plot(xdat[i*interval:(i+1)*interval],ydat[i*interval:(i+1)*interval]) plt.plot(xwindow,ywindow) plt.axvline(x=mx) plt.show() pmxi.append(i) pmx.append(mx) pmy.append(my) pmi.append(mi) #if i > 0: # xgap = pmx[-1] - pmx[-2] # print "xgap ",xgap, xgap/0.008 # # lastpeaki = mi return pmxi, pmx, pmy, pmi def get_files(directory, file_type): """ return files of type file_type in directory""" if not os.path.exists(directory): print "directory ",directory, "not found" sys.exit() listf = os.listdir(directory) listf.sort() files = [] for file1 in listf: if file1[0] != '.': if file_type in file1: files.append(file1) return files def select_filenames(directory, indices_select, channel_id): """Select channel files according to indices""" ch_files_list = [] for cid in channel_id: f = get_files(directory, cid) if f !=[]: if indices_select: fsel = [f[i] for i in indices_select] else: fsel = list(f) ch_files_list.append(fsel) else: ch_files_list.append([]) return ch_files_list def signal_loss_time(tdat,data, method, cut_off_freq = 0.5e6, threshold_volts = 0.05, sigtonoise = 10): """Find time of last signal. The low frequency component is first removed using a high pass filter (below cut_off_freq). method can be "fixed" in which case the latest time with voltage at threshold_volts is found or "noise" in which case the latest time with voltage sigtonoise times the rms of the noise calculated in the last 100 points (where the script assumes no signal)""" #parameters for filter dt = tdat[1] - tdat[0] RC = 1/(2*np.pi*cut_off_freq) #apply high pass filter filter_chf = highpass(data,dt,RC) if method == 'fixed': threshold = threshold_volts elif method == 'noise': noise_level = np.std(filter_chf[-100:]) threshold = sigtonoise*noise_level j = 0 for y in reversed(filter_chf): if abs(y) > threshold: loss_time = tdat[len(tdat) - j - 1] index_loss_time = len(tdat) - j - 1 break j = j + 1 return loss_time, index_loss_time #SUZIE'S ANALYSIS FUNCTIONS def readset(dirname, setname): '''Read in a set of data where a 'set' is from a number of different probes''' dat=[] for i in range(len(setname)): print "Reading data from: ", setname[i] ffile = dirname+setname[i] dat.append(np.loadtxt(ffile, skiprows=1, usecols=(0,1), unpack=True)) return dat def plotset(dirname, setname): '''Plot a set of data where a 'set' is from a number of different probes''' dataset = readset(dirname, setname) for i in range(len(dat)): dat=dataset[i] plot(dat[0], dat[1], '.-',label=setname[i]) def findRfromt(rvals, tvals, order=5): '''do a polynomial fit to find R as a function of t from set of datapoints''' rfit = np.polyfit(tvals,rvals,order) #r=t/a-b/a #make a polynomial that gives the r value for any t value rpoly = np.poly1d(rfit) return rpoly def findyfromx_spline(yvals, xvals): '''do a cubic spline fit to find y as a function of x from set of datapoints''' yfit = interpolate.splrep(xvals, yvals, s=0) return yfit def findtfromR(tvals, rvals): '''do a polynomial fit to find t as a function of R from set of datapoints''' tfit = np.polyfit(rvals,tvals,5) #r=t/a-b/a #make a polynomial that gives the t value for any r value tpoly = np.poly1d(tfit) return tpoly def findFfromt(tvals, fvals): '''do a polynomial fit to find f as a function of t from set of datapoints''' ffit = np.polyfit(tvals,fvals,5) #make a polynomial that gives the f value for any r value fpoly = np.poly1d(ffit) return fpoly def findPfromt(pvals, tvals, order=5): '''do a polynomial fit to find momentum as a function of t from set of datapoints''' pfit = np.polyfit(pvals,tvals,order) usepoly = np.poly1d(pfit) return usepoly def findEfromt(tvals, Evals): '''do a polynomial fit to find energy as a function of t from set of datapoints''' Efit = np.polyfit(tvals,Evals,5) usepoly = np.poly1d(Efit) return usepoly def findPfromR(rvals, pvals): pfit = np.polyfit(pvals,rvals,5) usepoly = np.poly1d(pfit) return usepoly def ke_to_mom(pmass, kenergy): '''Convert kinetic energy to momentum''' te= pmass+kenergy mom=math.sqrt(pow(te,2) - pow(pmass,2)) return mom def mom_to_ke(pmass, mom): '''Convert momentum to kinetic energy''' te=math.sqrt(pow(mom,2)+pow(pmass,2)) kenergy=te-pmass #print "mom: ",mom, "te: ",te, "ke: ", kenergy return kenergy def readcsv_old(fname, nsamples=100000): """csv files from the oscilloscope that was used in Nov 13""" time=[] volts=[] dat = csv2rec(fname, skiprows=6) print 'read data from ', fname for it in range(nsamples): time.append(float(dat[it][3])) volts.append(float(dat[it][4])) print len(time) return time, volts def readcsv(fname, nsamples=100000): time=[] volts=[] dat=csv2rec(fname, skiprows=17) for it in range(nsamples): time.append(float(dat[it][0])) volts.append(float(dat[it][1])) print len(time) return time, volts def getpeaks(rawdata,revfreq, startindex=0,endindex=10000): """This breaks up data into chunks defined by int(1/revfreq), between given start & end points finds the maximum value within that window & returns arrays of peak values & positions.""" si=startindex step=int(1/revfreq) print step pmax=[] ppos=[] index=si+step while index<endindex+1: peak=abs(rawdata[si:index]).max() pmax.append(peak) print peak ppos.append(si+ np.where(abs(rawdata[si:index])==peak)[0][0]) si=si+step index=index+step return pmax, ppos def perform_fft(data, plotswitch=0, plotname="fft_spectrum.png"): """Performs a basic FFT and returns the dominant frequency in the data and the freq. vs power spectrum data""" t=np.arange(len(data)) Y = np.fft.fft(data) n=len(Y) power = abs(Y[1:(n/2)])**2 nyquist=1./2 freq=np.array(range(n/2))/(n/2.0)*nyquist if plotswitch==1: plot(freq[:len(power)], power, '-') yscale('log') #xlim(0, 0.04) #ylim(1, 100000) savefig(plotname) clf() maxindex=np.where(power==power.max())[0][0] print "Max. frequency in spectrum: ", freq[maxindex+1] return freq[maxindex+1], freq[:len(power)], power ### This is the Gaussian data smoothing function I got from: ### http://www.swharden.com/blog/2008-11-17-linear-data-smoothing-in-python/ def smoothListGaussian(list,degree=5): window=degree*2-1 weight=np.array([1.0]*window) weightGauss=[] for i in range(window): i=i-degree+1 frac=i/float(window) gauss=1/(np.exp((4*(frac))**2)) weightGauss.append(gauss) weight=np.array(weightGauss)*weight smoothed=[0.0]*(len(list)-window) for i in range(len(smoothed)): smoothed[i]=sum(np.array(list[i:i+window])*weight)/sum(weight) return smoothed def smoothListTriangle(list,strippedXs=False,degree=5): weight=[] window=degree*2-1 smoothed=[0.0]*(len(list)-window) for x in range(1,2*degree):weight.append(degree-abs(degree-x)) w=np.array(weight) for i in range(len(smoothed)): smoothed[i]=sum(np.array(list[i:i+window])*w)/float(sum(w)) return smoothed def peakfinder(data, thresh=2.5): """Method: take derivative of data, Find sign of gradient (increasing/decreasing) Find where the gradient of the sign changes -> take downward crossing only (gives maxima) Find the array indices where that is 'True' and add one""" c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max threshold = thresh*mean(data) #threshold=thresh print 'total peaks found: ', len(c) print 'threshold: ', threshold # Next remove maxima from the list if they fall below the threshold of 2.5*mean & print how many 'peaks' c_keep = np.delete(c, ravel(where(data[c]<threshold))) print 'peaks found above threshold: ',len(c_keep) return c_keep def extremumfinder(data, thresh=2.5): """Method: take derivative of data, Find sign of gradient (increasing/decreasing) Find where the gradient of the sign changes -> take downward crossing only (gives maxima) Find the array indices where that is 'True' and add one""" c = (diff(sign(diff(data)))).nonzero()[0] + 1 # local max print 'total extrema found: ', len(c) threshold = thresh*mean(data) print 'threshold: ', threshold # Next remove maxima from the list if they fall below the threshold of 2.5*mean & print how many 'peaks' c_keep = np.delete(c, ravel(where(abs(data[c])<threshold))) print 'peaks found: ',len(c_keep) return c_keep def makeplot(ffile, pfile): """JUST MAKES A PLOT EITHER WITH TWO COLUMNS OF DATA, OR A THIRD REPRESENTING YERR VALUES 0 = timebase 1 = volt""" xax=[] yax=[] errs=[] for line in file(ffile): line = line.split() xax.append(float(line[0])) yax.append(float(line[1])) if len(line)>2: errs.append(float(line[2])) fig=figure(num=1, figsize=(6.5, 6.5), dpi=150, facecolor='w', edgecolor='k') if len(errs)==len(yax): errorbar(np.array(xax), np.array(yax), yerr=np.array(errs), fmt='bo-') else: plot(xax, yax, 'k.-') #ylim(0,0.5) #xlabel(r'x [mm]', size=12) #ylabel(r'z [mm]',size=12) savefig(pfile) clf() def powerlaw_fit(xdata, ydata, yerr): # Power-law fitting is best done by first converting # to a linear equation and then fitting to a straight line. # y = a * x^b # log(y) = log(a) + b*log(x) from scipy import log10 from scipy import optimize powerlaw = lambda x, amp, index: amp*np.power(x,index) logx = log10(xdata) logy = log10(ydata) logyerr = yerr / ydata # define our (line) fitting function fitfunc = lambda p, x: p[0] + p[1] * x errfunc = lambda p, x, y, err: (y - fitfunc(p, x)) / err pinit = [1.0, -1.0] out = optimize.leastsq(errfunc, pinit, args=(logx, logy, logyerr), full_output=1) pfinal = out[0] covar = out[1] #y = amp * x^exponent exponent = pfinal[1] #index in original amp = 10.0**pfinal[0] exponentErr = np.sqrt( covar[0][0] ) ampErr = np.sqrt( covar[1][1] ) * amp chisq = np.sum((((ydata - powerlaw(xdata, amp, exponent))/yerr)**2),axis=0) return exponent, amp, chisq def rf_convert(rfdir): #Convert the time to an energy then a momentum (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 rfdat_E=np.array(rfdat[1])*1E-6 rfdat_F=np.array(rfdat[2]) #frequency in hertz mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) #toffset=0 #make a list of momentum values corresponding to a given set of time points fittedpfunc=findPfromt(rfdat_t,rfdat_p, order=2) #using RF data return fittedpfunc def powerlaw_fit_outlier(pdat, rdat, rerr): """Successively remove initial data points until chi-squared of power law fit is below some threshold Return resulting fit parameters and the modified error array""" for iteration in range(5): if iteration > 0: rerr[iteration - 1] = 1000 #eliminate point near injection exponent, amp, chisq = powerlaw_fit(pdat, rdat, rerr) if iteration > 0: #test for convergence if abs(chisq - chisq_prev) <= 5.0: break #store results from this iteration exponent_prev = exponent amp_prev = amp chisq_prev = chisq return exponent_prev, amp_prev, chisq_prev, rerr def polynomial_fit_outlier(pdat, rdat, order=1, threshold = 1e-5): """Successively remove initial data points until chi-squared of power law fit is below some threshold Return resulting fit parameters and the modified error array""" for iteration in range(5): out = np.polyfit(pdat[iteration:], rdat[iteration:], order, full=True) poly_coef = out[0] poly = np.poly1d(poly_coef) chisq = sum([(poly(p)-r)**2 for p,r in zip(pdat[iteration:], rdat[iteration:])]) if iteration >= 0: if chisq <= threshold: break return poly_coef, chisq_fit, iteration-1 def fit_qinbin_data(data1, fit_type='powerlaw', plot_fit = False): #Convert R(t) qinbin data to R(p) and fit. rfdir="/home/pvq65952/accelerators/KURRI_ADS/march14_exp/rf_pattern/" colors = ['k', 'r', 'b'] probenames=["F1","F5","F7"] #print "data1 time ",[d[1] for d in data1] toffset= -93.3 proberadius=4300.0 #mm fittedpfunc = rf_convert(rfdir) pdata_probe = [] rdata_probe = [] momentum_initial = [] exponent_fit_all = [] amp_fit_all = [] if fit_type == 'powerlaw': powerlaw1 = lambda x, amp, index: amp*np.power(x,index) else: print "polynomial fit part needs fixing!" sys.exit() radii_fit = [] momenta_fit = [] p_fit_ini = [] p_fit_last = [] for i_probe in range(len(data1)): j=data1[i_probe][0].argsort() #sort by probe position pdata = fittedpfunc(data1[i_probe][1][j]+toffset) #momentum data rdata = 1e-3*(data1[i_probe][0][j] + proberadius) #position data w.r.t centre #p_ini_fit = fittedpfunc(data1[0][1][0]+toffset) #store data in list rdata_probe.append(rdata) pdata_probe.append(pdata) #fit data if fit_type == 'powerlaw': #pnorm = [p/pdata[0] for p in pdata] #p/p0 #pnorm = np.array([p/p_ini_fit for p in pdata]) radii_err = [1e-3]*len(rdata) momentum_initial.append(pdata[0]) exponent_fit, amp_fit, chisq_fit, rerr = powerlaw_fit_outlier(pdata, rdata, radii_err) exponent_fit_all.append(exponent_fit) amp_fit_all.append(amp_fit) index_fit_first = next((i for i,v in enumerate(rerr) if v != 1000),0) kfit = (1/exponent_fit) - 1 leg_text = probenames[i_probe]+", k="+str(kfit)[:5] else: poly_coef, chisq, index_fit_first = polynomial_fit_outlier(pdata, rdata, threshold=1e-4) fittedrvsp = np.poly1d(poly_coef) #extract fit parameters a1 = fittedrvsp[1] a2 = fittedrvsp[2] drdpfn = np.poly1d([2*a2, a1]) drdp_probe = drdpfn(pdata) p_fit_ini.append(pdata[index_fit_first]) p_fit_last.append(pdata[-1]) if plot_fit: if fit_type == 'powerlaw': plot(pdata, powerlaw1(pdata, amp_fit, exponent_fit), color=colors[i_probe],linestyle='--', label=leg_text) else: plot(pdata, fittedrvsp(pdata), '-', color=colors[i_probe], label=probenames[i_probe]) plot(pdata, rdata, color=colors[i_probe], marker='o', linestyle='None')#, label=probenames[i_probe]) if plot_fit: xlabel('p (MeV/c)') ylabel('r (m)') legend(loc="lower right", prop={'size':12}) plt.show() #common momentum range min_p_com = max(p_fit_ini) max_p_com = min(p_fit_last) return pdata_probe, rdata_probe, exponent_fit_all, amp_fit_all, [min_p_com, max_p_com]
Python
from scipy.signal import butter, lfilter def butter_highpass(cutoff, fs, order=5): '''butterworth highpass filter''' nyq = 0.5 * fs b, a = butter(order, cutoff/nyq, btype='highpass') return b, a def butter_bandpass_filter(data, cutoff, fs, order=5): '''butterworth bandpass filter''' b, a = butter_highpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y if __name__ == "__main__": import numpy as np import matplotlib.pyplot as plt from scipy.signal import freqz # Sample rate and desired cutoff frequencies (in Hz). fs = 5000.0 cutoff = 500.0 # Plot the frequency response for a few different orders. plt.figure(1) plt.clf() for order in [3, 6, 9]: b, a = butter_highpass(cutoff, fs, order=order) w, h = freqz(b, a, worN=2000) plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order) plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)], '--', label='sqrt(0.5)') plt.xlabel('Frequency (Hz)') plt.ylabel('Gain') plt.grid(True) plt.legend(loc='best') # Filter a noisy signal. T = 0.05 nsamples = T * fs t = np.linspace(0, T, nsamples, endpoint=False) a = 0.02 f0 = 600.0 x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t)) x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1) x += a * np.cos(2 * np.pi * f0 * t + .11) x += 0.03 * np.cos(2 * np.pi * 2000 * t) plt.figure(2) plt.clf() plt.plot(t, x, label='Noisy signal') y = butter_bandpass_filter(x, cutoff, fs, order=6) plt.plot(t, y, label='Filtered signal (%g Hz)' % f0) plt.xlabel('time (seconds)') plt.hlines([-a, a], 0, T, linestyles='--') plt.grid(True) plt.axis('tight') plt.legend(loc='upper left') plt.show() def savitzky_golay(y, window_size, order, deriv=0, rate=1): '''Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688 ''' import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError, msg: raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with # values taken from the signal itself firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] ) lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1]) y = np.concatenate((firstvals, y, lastvals)) return np.convolve( m[::-1], y, mode='valid')
Python
#!/usr/bin/python import matplotlib matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['legend.fontsize']=12 from pylab import * from scipy import interpolate import numpy as np import os #DAVID'S READSCOPE FUNCTION def read_scope(dirname, filename, tfactor=1): """Read scope data. The script deals with two specific scope formats - that used in November 2013, and in March 2014. The two are distinguished by looking for the string DP04104 that appears in the later case""" filepath = dirname + filename print 'reading ', filepath f_data = open(filepath, 'r') n = 0 tdat = [] ydat = [] for line in f_data: timeandamp = line.split(',') #identify scope if n == 0: if timeandamp[1][:7] == 'DPO4104': nskip = 17 xi = 0 yi = 1 else: nskip = 6 xi = 3 yi = 4 if n > nskip: if line !='\r\n': tdat.append(tfactor*float(timeandamp[xi])) ydat.append(float(timeandamp[yi])) else: break n += 1 f_data.close() return tdat, ydat #DAVIDS HIGHPASS FILTER FUNCTION added 26/3/14 def highpass(signal,dt,RC): """ Return RC high-pass output samples, given input samples, time constant RC and time interval dt""" alpha = RC/(RC + dt) y = [signal[0]] for i in range(1,len(signal)): y.append(alpha*y[i-1] + alpha*(signal[i] - signal[i-1])) return y #DAVIDS PEAK FINDING ALGORITHM ADDED 15/5/2014 def find_peaks(xdat, ydat, interval, find_hminus): pmxi = [] pmx = [] pmy = [] pmi = [] for i in range(int(len(xdat)/interval) + 10): my = 0. my_min = 100 winsize = int(0.5*interval) if i == 0 : istart = 0 xwindow = xdat[:2*winsize] ywindow = ydat[:2*winsize] elif i == 1: istart = 2*winsize xwindow = xdat[2*winsize:4*winsize] ywindow = ydat[2*winsize:4*winsize] else: icen = mi + interval #test if in range if icen + winsize > len(xdat): print "reach end of data ",icen+winsize, len(xdat) break xwindow = xdat[icen-winsize: icen+winsize] ywindow = ydat[icen-winsize: icen+winsize] istart = icen - winsize for xd,yd in zip(xwindow, ywindow): #look for positive H- peak if i == 0 and find_hminus: if yd > my: mx = xd my = yd mi = ywindow.index(yd) + istart else: #look for negative proton peak if yd < my: mx = xd my = yd mi = ywindow.index(yd) + istart if i >= 10 and i <= 5: #if xwindow[0] > 88 and xwindow[0] < 100: #plt.plot(xdat[i*interval:(i+1)*interval],ydat[i*interval:(i+1)*interval]) plt.plot(xwindow,ywindow) plt.axvline(x=mx) plt.show() pmxi.append(i) pmx.append(mx) pmy.append(my) pmi.append(mi) #if i > 0: # xgap = pmx[-1] - pmx[-2] # print "xgap ",xgap, xgap/0.008 # # lastpeaki = mi return pmxi, pmx, pmy, pmi def get_files(directory, file_type): """ return files of type file_type in directory""" if not os.path.exists(directory): print "directory ",directory, "not found" sys.exit() listf = os.listdir(directory) listf.sort() files = [] for file1 in listf: if file1[0] != '.': if file_type in file1: files.append(file1) return files def select_filenames(directory, indices_select, channel_id): """Select channel files according to indices""" ch_files_list = [] for cid in channel_id: f = get_files(directory, cid) if f !=[]: if indices_select: fsel = [f[i] for i in indices_select] else: fsel = list(f) ch_files_list.append(fsel) else: ch_files_list.append([]) return ch_files_list def signal_loss_time(tdat,data, method, cut_off_freq = 0.5e6, threshold_volts = 0.05, sigtonoise = 10): """Find time of last signal. The low frequency component is first removed using a high pass filter (below cut_off_freq). method can be "fixed" in which case the latest time with voltage at threshold_volts is found or "noise" in which case the latest time with voltage sigtonoise times the rms of the noise calculated in the last 100 points (where the script assumes no signal)""" #parameters for filter dt = tdat[1] - tdat[0] RC = 1/(2*np.pi*cut_off_freq) #apply high pass filter filter_chf = highpass(data,dt,RC) if method == 'fixed': threshold = threshold_volts elif method == 'noise': noise_level = np.std(filter_chf[-100:]) threshold = sigtonoise*noise_level j = 0 for y in reversed(filter_chf): if abs(y) > threshold: loss_time = tdat[len(tdat) - j - 1] index_loss_time = len(tdat) - j - 1 break j = j + 1 return loss_time, index_loss_time #SUZIE'S ANALYSIS FUNCTIONS def readset(dirname, setname): '''Read in a set of data where a 'set' is from a number of different probes''' dat=[] for i in range(len(setname)): print "Reading data from: ", setname[i] ffile = dirname+setname[i] dat.append(np.loadtxt(ffile, skiprows=1, usecols=(0,1), unpack=True)) return dat def plotset(dirname, setname): '''Plot a set of data where a 'set' is from a number of different probes''' dataset = readset(dirname, setname) for i in range(len(dat)): dat=dataset[i] plot(dat[0], dat[1], '.-',label=setname[i]) def findRfromt(rvals, tvals, order=5): '''do a polynomial fit to find R as a function of t from set of datapoints''' rfit = np.polyfit(tvals,rvals,order) #r=t/a-b/a #make a polynomial that gives the r value for any t value rpoly = np.poly1d(rfit) return rpoly def findyfromx_spline(yvals, xvals): '''do a cubic spline fit to find y as a function of x from set of datapoints''' yfit = interpolate.splrep(xvals, yvals, s=0) return yfit def findtfromR(tvals, rvals): '''do a polynomial fit to find t as a function of R from set of datapoints''' tfit = np.polyfit(rvals,tvals,5) #r=t/a-b/a #make a polynomial that gives the t value for any r value tpoly = np.poly1d(tfit) return tpoly def findFfromt(tvals, fvals): '''do a polynomial fit to find f as a function of t from set of datapoints''' ffit = np.polyfit(tvals,fvals,5) #make a polynomial that gives the f value for any r value fpoly = np.poly1d(ffit) return fpoly def findPfromt(pvals, tvals, order=5): '''do a polynomial fit to find momentum as a function of t from set of datapoints''' pfit = np.polyfit(pvals,tvals,order) usepoly = np.poly1d(pfit) return usepoly def findEfromt(tvals, Evals): '''do a polynomial fit to find energy as a function of t from set of datapoints''' Efit = np.polyfit(tvals,Evals,5) usepoly = np.poly1d(Efit) return usepoly def findPfromR(rvals, pvals): pfit = np.polyfit(pvals,rvals,5) usepoly = np.poly1d(pfit) return usepoly def ke_to_mom(pmass, kenergy): '''Convert kinetic energy to momentum''' te= pmass+kenergy mom=math.sqrt(pow(te,2) - pow(pmass,2)) return mom def mom_to_ke(pmass, mom): '''Convert momentum to kinetic energy''' te=math.sqrt(pow(mom,2)+pow(pmass,2)) kenergy=te-pmass #print "mom: ",mom, "te: ",te, "ke: ", kenergy return kenergy def readcsv_old(fname, nsamples=100000): """csv files from the oscilloscope that was used in Nov 13""" time=[] volts=[] dat = csv2rec(fname, skiprows=6) print 'read data from ', fname for it in range(nsamples): time.append(float(dat[it][3])) volts.append(float(dat[it][4])) print len(time) return time, volts def readcsv(fname, nsamples=100000): time=[] volts=[] dat=csv2rec(fname, skiprows=17) for it in range(nsamples): time.append(float(dat[it][0])) volts.append(float(dat[it][1])) print len(time) return time, volts def getpeaks(rawdata,revfreq, startindex=0,endindex=10000): """This breaks up data into chunks defined by int(1/revfreq), between given start & end points finds the maximum value within that window & returns arrays of peak values & positions.""" si=startindex step=int(1/revfreq) print step pmax=[] ppos=[] index=si+step while index<endindex+1: peak=abs(rawdata[si:index]).max() pmax.append(peak) print peak ppos.append(si+ np.where(abs(rawdata[si:index])==peak)[0][0]) si=si+step index=index+step return pmax, ppos def perform_fft(data, plotswitch=0, plotname="fft_spectrum.png"): """Performs a basic FFT and returns the dominant frequency in the data and the freq. vs power spectrum data""" t=np.arange(len(data)) Y = np.fft.fft(data) n=len(Y) power = abs(Y[1:(n/2)])**2 nyquist=1./2 freq=np.array(range(n/2))/(n/2.0)*nyquist if plotswitch==1: plot(freq[:len(power)], power, '-') yscale('log') #xlim(0, 0.04) #ylim(1, 100000) savefig(plotname) clf() maxindex=np.where(power==power.max())[0][0] print "Max. frequency in spectrum: ", freq[maxindex+1] return freq[maxindex+1], freq[:len(power)], power ### This is the Gaussian data smoothing function I got from: ### http://www.swharden.com/blog/2008-11-17-linear-data-smoothing-in-python/ def smoothListGaussian(list,degree=5): window=degree*2-1 weight=np.array([1.0]*window) weightGauss=[] for i in range(window): i=i-degree+1 frac=i/float(window) gauss=1/(np.exp((4*(frac))**2)) weightGauss.append(gauss) weight=np.array(weightGauss)*weight smoothed=[0.0]*(len(list)-window) for i in range(len(smoothed)): smoothed[i]=sum(np.array(list[i:i+window])*weight)/sum(weight) return smoothed def smoothListTriangle(list,strippedXs=False,degree=5): weight=[] window=degree*2-1 smoothed=[0.0]*(len(list)-window) for x in range(1,2*degree):weight.append(degree-abs(degree-x)) w=np.array(weight) for i in range(len(smoothed)): smoothed[i]=sum(np.array(list[i:i+window])*w)/float(sum(w)) return smoothed def peakfinder(data, thresh=2.5): """Method: take derivative of data, Find sign of gradient (increasing/decreasing) Find where the gradient of the sign changes -> take downward crossing only (gives maxima) Find the array indices where that is 'True' and add one""" c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max threshold = thresh*mean(data) #threshold=thresh print 'total peaks found: ', len(c) print 'threshold: ', threshold # Next remove maxima from the list if they fall below the threshold of 2.5*mean & print how many 'peaks' c_keep = np.delete(c, ravel(where(data[c]<threshold))) print 'peaks found above threshold: ',len(c_keep) return c_keep def extremumfinder(data, thresh=2.5): """Method: take derivative of data, Find sign of gradient (increasing/decreasing) Find where the gradient of the sign changes -> take downward crossing only (gives maxima) Find the array indices where that is 'True' and add one""" c = (diff(sign(diff(data)))).nonzero()[0] + 1 # local max print 'total extrema found: ', len(c) threshold = thresh*mean(data) print 'threshold: ', threshold # Next remove maxima from the list if they fall below the threshold of 2.5*mean & print how many 'peaks' c_keep = np.delete(c, ravel(where(abs(data[c])<threshold))) print 'peaks found: ',len(c_keep) return c_keep def makeplot(ffile, pfile): """JUST MAKES A PLOT EITHER WITH TWO COLUMNS OF DATA, OR A THIRD REPRESENTING YERR VALUES 0 = timebase 1 = volt""" xax=[] yax=[] errs=[] for line in file(ffile): line = line.split() xax.append(float(line[0])) yax.append(float(line[1])) if len(line)>2: errs.append(float(line[2])) fig=figure(num=1, figsize=(6.5, 6.5), dpi=150, facecolor='w', edgecolor='k') if len(errs)==len(yax): errorbar(np.array(xax), np.array(yax), yerr=np.array(errs), fmt='bo-') else: plot(xax, yax, 'k.-') #ylim(0,0.5) #xlabel(r'x [mm]', size=12) #ylabel(r'z [mm]',size=12) savefig(pfile) clf() def powerlaw_fit(xdata, ydata, yerr): # Power-law fitting is best done by first converting # to a linear equation and then fitting to a straight line. # y = a * x^b # log(y) = log(a) + b*log(x) from scipy import log10 from scipy import optimize powerlaw = lambda x, amp, index: amp*np.power(x,index) logx = log10(xdata) logy = log10(ydata) logyerr = yerr / ydata # define our (line) fitting function fitfunc = lambda p, x: p[0] + p[1] * x errfunc = lambda p, x, y, err: (y - fitfunc(p, x)) / err pinit = [1.0, -1.0] out = optimize.leastsq(errfunc, pinit, args=(logx, logy, logyerr), full_output=1) pfinal = out[0] covar = out[1] #y = amp * x^exponent exponent = pfinal[1] #index in original amp = 10.0**pfinal[0] exponentErr = np.sqrt( covar[0][0] ) ampErr = np.sqrt( covar[1][1] ) * amp chisq = np.sum((((ydata - powerlaw(xdata, amp, exponent))/yerr)**2),axis=0) return exponent, amp, chisq def rf_convert(rfdir): #Convert the time to an energy then a momentum (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 rfdat_E=np.array(rfdat[1])*1E-6 rfdat_F=np.array(rfdat[2]) #frequency in hertz mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) #toffset=0 #make a list of momentum values corresponding to a given set of time points fittedpfunc=findPfromt(rfdat_t,rfdat_p, order=2) #using RF data return fittedpfunc def powerlaw_fit_outlier(pdat, rdat, rerr): """Successively remove initial data points until chi-squared of power law fit is below some threshold Return resulting fit parameters and the modified error array""" for iteration in range(5): if iteration > 0: rerr[iteration - 1] = 1000 #eliminate point near injection exponent, amp, chisq = powerlaw_fit(pdat, rdat, rerr) if iteration > 0: #test for convergence if abs(chisq - chisq_prev) <= 5.0: break #store results from this iteration exponent_prev = exponent amp_prev = amp chisq_prev = chisq return exponent_prev, amp_prev, chisq_prev, rerr def polynomial_fit_outlier(pdat, rdat, order=1, threshold = 1e-5): """Successively remove initial data points until chi-squared of power law fit is below some threshold Return resulting fit parameters and the modified error array""" for iteration in range(5): out = np.polyfit(pdat[iteration:], rdat[iteration:], order, full=True) poly_coef = out[0] poly = np.poly1d(poly_coef) chisq = sum([(poly(p)-r)**2 for p,r in zip(pdat[iteration:], rdat[iteration:])]) if iteration >= 0: if chisq <= threshold: break return poly_coef, chisq_fit, iteration-1 def fit_qinbin_data(data1, fit_type='powerlaw', plot_fit = False): #Convert R(t) qinbin data to R(p) and fit. rfdir="/home/pvq65952/accelerators/KURRI_ADS/march14_exp/rf_pattern/" colors = ['k', 'r', 'b'] probenames=["F1","F5","F7"] #print "data1 time ",[d[1] for d in data1] toffset= -93.3 proberadius=4300.0 #mm fittedpfunc = rf_convert(rfdir) pdata_probe = [] rdata_probe = [] momentum_initial = [] exponent_fit_all = [] amp_fit_all = [] if fit_type == 'powerlaw': powerlaw1 = lambda x, amp, index: amp*np.power(x,index) else: print "polynomial fit part needs fixing!" sys.exit() radii_fit = [] momenta_fit = [] p_fit_ini = [] p_fit_last = [] for i_probe in range(len(data1)): j=data1[i_probe][0].argsort() #sort by probe position pdata = fittedpfunc(data1[i_probe][1][j]+toffset) #momentum data rdata = 1e-3*(data1[i_probe][0][j] + proberadius) #position data w.r.t centre #p_ini_fit = fittedpfunc(data1[0][1][0]+toffset) #store data in list rdata_probe.append(rdata) pdata_probe.append(pdata) #fit data if fit_type == 'powerlaw': #pnorm = [p/pdata[0] for p in pdata] #p/p0 #pnorm = np.array([p/p_ini_fit for p in pdata]) radii_err = [1e-3]*len(rdata) momentum_initial.append(pdata[0]) exponent_fit, amp_fit, chisq_fit, rerr = powerlaw_fit_outlier(pdata, rdata, radii_err) exponent_fit_all.append(exponent_fit) amp_fit_all.append(amp_fit) index_fit_first = next((i for i,v in enumerate(rerr) if v != 1000),0) kfit = (1/exponent_fit) - 1 leg_text = probenames[i_probe]+", k="+str(kfit)[:5] else: poly_coef, chisq, index_fit_first = polynomial_fit_outlier(pdata, rdata, threshold=1e-4) fittedrvsp = np.poly1d(poly_coef) #extract fit parameters a1 = fittedrvsp[1] a2 = fittedrvsp[2] drdpfn = np.poly1d([2*a2, a1]) drdp_probe = drdpfn(pdata) p_fit_ini.append(pdata[index_fit_first]) p_fit_last.append(pdata[-1]) if plot_fit: if fit_type == 'powerlaw': plot(pdata, powerlaw1(pdata, amp_fit, exponent_fit), color=colors[i_probe],linestyle='--', label=leg_text) else: plot(pdata, fittedrvsp(pdata), '-', color=colors[i_probe], label=probenames[i_probe]) plot(pdata, rdata, color=colors[i_probe], marker='o', linestyle='None')#, label=probenames[i_probe]) if plot_fit: xlabel('p (MeV/c)') ylabel('r (m)') legend(loc="lower right", prop={'size':12}) plt.show() #common momentum range min_p_com = max(p_fit_ini) max_p_com = min(p_fit_last) return pdata_probe, rdata_probe, exponent_fit_all, amp_fit_all, [min_p_com, max_p_com]
Python
#!/usr/bin/python import matplotlib import glob from pylab import * import numpy as np from analysedata import * from scipy import interpolate #Written by S. Sheehy on 27/3/2014 #Updates: #21/10/2014: Updated to use individual ranges for each probe calculation (S. Sheehy) # matplotlib.rcParams['legend.fontsize']=8 def calcsingleDispersion(pvals, rvals): '''Use to calculate a single value of the dispersion for a set of r vs p data''' #central momentum pcentral=mean(pvals) dp=max(pvals)-min(pvals) dpp=dp/pcentral #print "delta p: ", dp print "delta p/p: ", dpp dr=max(rvals)-min(rvals) print "dr: ", dr return p*(dr/dp) def idealDispersionvsr(rvals, kval): '''returns an array which contains the ideal dispersion values vs radius with a given fixed k value''' disp=np.array(rvals)/(kval+1.0) return disp def calcDispersion(pvals, rvals): '''Use to calculate the dispersion over a range of radii''' disp=[] dpp_array=[] for i in range(len(rvals)-1): dr=rvals[i+1]-rvals[i] dp=pvals[i+1]-pvals[i] dpp=dp/pvals[i] disp.append(pvals[i]*dr/dp) #changed from dr/dpp dpp_array.append(dpp) #dispersion = dr/(dp/p) return disp, dpp_array def calckfromdisp(Dval, rval): #gamma_val=(Eval+938.0)/938.0 #print gamma_val #kval=(1-Dval)*pow(gamma_val,2)-1 kval=(rval/Dval)-1 #print kval return kval def calcKvalue_poly(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' #fvals=interpolate.splev(tvals, findyfromx_spline(f_rf, t_rf), der=0) #E_vals=interpolate.splev(tvals, findyfromx_spline(E_rf, t_rf),der=0) fvals=map(findFfromt(t_rf, f_rf), tvals) E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array def calcKvalue(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' #fvals=interpolate.splev(tvals, findyfromx_spline(f_rf, t_rf), der=0) E_vals=interpolate.splev(tvals, findyfromx_spline(E_rf, t_rf),der=0) fvals=map(findFfromt(t_rf, f_rf), tvals) #E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array if __name__ == "__main__": '''This analysis code needs updating/checking!!!''' colors = ['b', 'g', 'r'] #Directory for plots resdir="Results/" #Filenames for plots pfile1 ="r_vs_t.pdf" pfile2="rfpattern.pdf" #pfile2="k_vs_t.pdf" pfile3="p_vs_r.pdf" pfile4="Dispersion_vs_E.pdf" pfile5="Dispersion_vs_r.pdf" pfile7="kvalue_vs_E.pdf" #fig=figure(num=1, figsize=(6.5, 10.5), dpi=150, facecolor='w', edgecolor='k') #Data directory #dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/COD_data_140325/" #dir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-27/" dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/Qin_Bin_31_3_31/" rfdir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-25/rf_pattern/" #Filenames for sets of data #set1=glob.glob(dir+"QinBin_F?.txt") #print set1 set1=["QinBin_F1.txt", "QinBin_F5.txt", "QinBin_F7.txt"] #set1 =["D0_0amps_F1.txt" ,"D0_0amps_F5.txt" ,"D0_0amps_F7.txt"] #468A #set1=["D0_550Aamps_F1.txt" ,"D0_550Aamps_F5.txt" ,"D0_550Aamps_F7.txt"] #550A 27/3/2014 #set1 =["D0_140amps_F1.txt", "D0_140amps_F5.txt", "D0_140amps_F7.txt"] #468A #set1=["D0_400Aamps_F1.txt", "D0_400Aamps_F5.txt", "D0_400Aamps_F7.txt"] #400A 27/3/14 #set1=["D0_700amps_F1.txt", "D0_700amps_F5.txt", "D0_700amps_F7.txt"] #27/3/2014 #get the radial position at each time from each probe data1=readset(dir, set1) #gets the data #time_range=np.arange(500,15000,1) #rad_range=np.arange(300,420,1) time_range=[] rad_range=[] radial_values=[] time_values=[] probenames=["F1","F5","F7"] proberadius=4300.0 #mm kvalue=7.6 fig=figure(num=1, figsize=(8.5, 6.5), dpi=150, facecolor='w', edgecolor='k') #Get radius as a function of t for the three probes (ie. CO movement) for i in range(len(data1)): fittedrfunc=findRfromt(data1[i][0], data1[i][1]) j=data1[i][0].argsort() time_range=np.arange(min(data1[i][1]), max(data1[i][1]), 10) print "time range: ", min(data1[i][1]), max(data1[i][1]) #Rfit_values=interpolate.splev(time_range, findyfromx_spline(data1[i][0][j], data1[i][1][j]), der=0) Rfit_values=map(fittedrfunc, time_range) radial_values.append(Rfit_values) time_values.append(time_range) plot(data1[i][1], data1[i][0], 'x', color=colors[i], label=probenames[i]) #plot R vs t for each of the 3 probes for i in range(len(probenames)): plot(time_values[i], radial_values[i], color=colors[i], label=probenames[i]+"fit") xlabel(r'Time [$\mu$sec]', size=12) ylabel(r'Radius [mm]',size=12) legend(loc=0) savefig(resdir+pfile1) close() #also calculate the average value of CO movement # avg_radial_values=[] # max_radial_offset=[] # min_radial_offset=[] # for r in np.transpose(np.array(radial_values)): # avg_radial_values.append(np.mean(r)) # max_radial_offset.append(np.max(r)-np.mean(r)) # min_radial_offset.append(np.mean(r)-np.min(r)) #Convert the time to an energy then a momentum (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 rfdat_E=np.array(rfdat[1])*1E-6 rfdat_F=np.array(rfdat[2]) #frequency in hertz mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) toffset= -93.3 #make a list of momentum values corresponding to a given set of time points fittedpfunc=findPfromt(rfdat_t,rfdat_p) #using RF data #get a range of momenta over the given time range for each probe P_values=[] E_values=[] for i in range(len(probenames)): #P_values.append(interpolate.splev(time_values[i]+toffset, findyfromx_spline(rfdat_p, rfdat_t), der=0)) P_values.append(map(fittedpfunc, time_values[i]+toffset)) E_values.append(map(lambda x: mom_to_ke(mass, x), P_values[i])) #plot time vs momentum fig=figure(num=3, figsize=(8, 10), dpi=150, facecolor='w', edgecolor='k') subplot(2,1,1) plot(rfdat_t, rfdat_p, 'k--') for i in range(len(probenames)): plot(time_values[i], P_values[i], '-', color=colors[i], label=probenames[i]) xlabel(r'time [$\mu$sec]', size=12) ylabel(r'Momentum [MeV/c]',size=12) # #plot time vs energy subplot(2,1,2) plot(rfdat_t, rfdat_E, 'k--') for i in range(len(probenames)): plot(time_values[i], E_values[i], '-', color=colors[i], label=probenames[i]) xlabel(r'time [$\mu$sec]', size=12) ylabel(r'Energy[MeV]',size=12) savefig(resdir+pfile2) close() #CALCULATE THE DISPERSION #first adjust radial values to be in [m] and with correct offset from r=0 radii_metres=[] dispresult=[] dpp=[] for probe in range(len(probenames)): radii_metres.append((np.array(radial_values[probe])+proberadius)/1E3) dispresult.append(calcDispersion(P_values[probe], radii_metres[probe])[0]) dpp.append(calcDispersion(P_values[probe], radii_metres[probe])[1]) #sys.exit() #plot deltap/p with momentum # pfile4a="dpp_vs_p.pdf" # fig=figure(num=7, figsize=(6.5, 10.5), dpi=150, facecolor='w', edgecolor='k') # for i in range(len(probenames)): # plot(P_values[1:], dpp[i], color=colors[i], label=probenames[i]) # xlabel(r'Momentum [MeV/c]', size=12) # ylabel(r'dp/p',size=12) # legend() # savefig(pfile4a) #plot dispersion with radial probe position fig=figure(num=4, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') for i in range(len(probenames)): plot(radii_metres[i][1:], dispresult[i], color=colors[i], label=probenames[i]) #plot(rad_range_m, idealDispersionvsr(rad_range_m, kvalue)) xlabel(r'Radius [m]', size=12) ylabel(r'Dispersion [m]',size=12) ylim([0.3,0.8]) legend() savefig(resdir+pfile5) close() fig=figure(num=5, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') for i in range(len(probenames)): plot(E_values[i][1:], dispresult[i], color=colors[i], label=probenames[i]) #plot(rad_range_m, idealDispersionvsr(rad_range_m, kvalue)) xlabel(r'Energy [MeV]', size=12) ylabel(r'Dispersion [m]',size=12) ylim([0.3,0.8]) legend() savefig(resdir+pfile4) close() #plot radial position with momentum fig=figure(num=6, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') #plot( P_values,np.array(avg_radial_values),'k:', label="avg") for i in range(len(probenames)): plot(P_values[i], radii_metres[i], color=colors[i], label=probenames[i]) xlabel(r'Momentum [MeV/c]', size=12) ylabel(r'Radius [m]',size=12) legend() savefig(resdir+pfile3) close() #plot effective k value calculated from dispersion fig=figure(num=7, figsize=(8, 5), dpi=150, facecolor='w', edgecolor='k') k_values=[] for i in range(len(probenames)): k_values.append(map(lambda x, y: calckfromdisp(x,y), dispresult[i], radii_metres[i][1:])) #plot(time_values[i][1:], k_values[i], '--', color=colors[i], label=probenames[i]+'dmethod') xlabel(r'time [us]', size=12) ylabel(r'k value',size=12) ylim([5.5,9]) #legend() #savefig(resdir+pfile7) #CALCULATE THE K-VALUE BASED ON FREQUENCY FROM EACH TIME POINT #THIS ALSO USES THE LOOKUP TABLE TO FIND E AND USE ESTIMATED GAMMA FACTOR FOR A MORE EXACT RESULT kresult=[] #fig=figure(num=3, figsize=(6, 15), dpi=150, facecolor='w', edgecolor='k') for probe in range(len(probenames)): fittedtfunc=findtfromR(data1[probe][1], data1[probe][0]) #from experimental data j=data1[probe][0].argsort() #data sorted by index of sorted radial values #print data1[probe][0][j] #print data1[probe][1][j] #tfit_values=interpolate.splev(radial_values[probe], findyfromx_spline(data1[probe][1][j], data1[probe][0][j]), der=0) #use cubic spline to fit time values for finer radial points #tfit_values=map(lambda x: x+toffset, tfit_values) #shift t values by timing offset tfit_values=map(fittedtfunc+toffset, radial_values[probe]) #find t values corresponding to finer points in r kresult.append(calcKvalue_poly(rfdat_t, rfdat_F, rfdat_E, tfit_values, radii_metres[probe])) #calculate the k value in this range #print kresult[probe] plot(time_values[probe][1:],kresult[probe], '-', color=colors[probe],label=probenames[probe]) xlabel(r'time [us]', size=12) ylabel(r'effective k value',size=12) legend() #xlabel(r'time [$\mu$sec]', size=12) savefig(resdir+pfile7) sys.exit()
Python
#!/usr/bin/python import matplotlib import glob from pylab import * import numpy as np from analysedata import * #from dispersion_analysis140327 import * matplotlib.rcParams['legend.fontsize']=8 def calcKvalue(t_rf, f_rf, E_rf, tvals, rvals): '''use rvalues and tvals to get k value from rf file''' fvals=map(findFfromt(t_rf, f_rf), tvals) E_vals=map(findEfromt(t_rf, E_rf*1E6)/1E6, tvals) #approximate value of gamma at 60MeV #print E_vals gamma_vals=map(lambda x: (x+938.0)/938.0, E_vals) #print gamma_vals kval_array=[] for i in range(len(rvals)-1): drr=(rvals[i+1]-rvals[i])/rvals[i] dff=(fvals[i+1]-fvals[i])/fvals[i] kval_array.append(gamma_vals[i]*gamma_vals[i]*dff/drr-(1.0-gamma_vals[i]*gamma_vals[i])) #print dff/drr return kval_array colors = ['b', 'g', 'r'] #Filenames for plots pfile1 = "r_vs_t.pdf" pfile2="k_vs_t.pdf" #Data directory #dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/COD_data_140325/" #dir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-27/" dir="/Users/Suzie/Physics/KURRIFFAG/MARCH14/Davidcode/Qin_Bin_31_3_31/" rfdir="/Users/Suzie/Physics/KURRIFFAG/DATA/2014/2014-03-25/rf_pattern/" #Filenames for sets of data #set1=glob.glob(dir+"QinBin_F?.txt") #print set1 set1=["QinBin_F1.txt", "QinBin_F5.txt", "QinBin_F7.txt"] #set1 =["D0_0amps_F1.txt" ,"D0_0amps_F5.txt" ,"D0_0amps_F7.txt"] #468A #set1=["D0_550Aamps_F1.txt" ,"D0_550Aamps_F5.txt" ,"D0_550Aamps_F7.txt"] #550A 27/3/2014 #set1 =["D0_140amps_F1.txt", "D0_140amps_F5.txt", "D0_140amps_F7.txt"] #468A #set1=["D0_400Aamps_F1.txt", "D0_400Aamps_F5.txt", "D0_400Aamps_F7.txt"] #400A 27/3/14 #set1=["D0_700amps_F1.txt", "D0_700amps_F5.txt", "D0_700amps_F7.txt"] #27/3/2014 use_radius_range=True use_time_range=False #For a given time range, get the radial position at each time from each probe data1=readset(dir, set1) #gets the data time_range=np.arange(500,1500,1) #rad_range=np.arange(300,420,1) radial_values=[] time_values=[] probenames=["F1","F5","F7"] proberadius=4300.0 #mm kvalue=7.6 fig=figure(num=1, figsize=(10.5, 6.5), dpi=150, facecolor='w', edgecolor='k') #Lookup table of time, frequency and estimated energy (based on RF settings file) rffile="SimulatedVariableK.dat" rfdat = np.loadtxt(rfdir+rffile, skiprows=2, usecols=(0,1,2), unpack=True) rfdat_t=np.array(rfdat[0])*1E6 #time in musec rfdat_E=np.array(rfdat[1])*1E-6 #Energy in MeV rfdat_F=np.array(rfdat[2]) #frequency in hertz #Can also map the momentum values from the Energy values. mass=938.272 rfdat_p=map(lambda x: ke_to_mom(mass, x), rfdat_E) #CALCULATE THE K-VALUE BASED ON FREQUENCY FROM EACH TIME POINT #THIS ALSO USES THE LOOKUP TABLE TO FIND E AND USE ESTIMATED GAMMA FACTOR FOR A MORE EXACT RESULT kresult=[] toffset= -93.3 # musec timing offset from 31/3/14 data fig=figure(num=3, figsize=(6, 10), dpi=150, facecolor='w', edgecolor='k') smoothed_data=False for probe in range(len(probenames)): if smoothed_data==True: rad_range_1=np.arange(min(data1[probe][0]),max(data1[probe][0]), 1) else: rad_range_1=sort(np.array(data1[probe][0])) fittedtfunc=findtfromR(data1[probe][1], data1[probe][0]) tfit_values=map(fittedtfunc+toffset, rad_range_1) rad_range_m=(rad_range_1+proberadius)/1E3 subplot(2,1,1) plot(tfit_values, rad_range_m, '-', color=colors[probe]) plot(data1[probe][1]+toffset, (np.array(data1[probe][0])+proberadius)/1E3, 'x',color=colors[probe]) ylabel(r'radius [m]') subplot(2,1,2) kresult.append(calcKvalue(rfdat_t, rfdat_F, rfdat_E, tfit_values, rad_range_m)) plot(tfit_values[:-1],kresult[probe], '.-', color=colors[probe],label=probenames[probe]) legend() xlabel(r'time [$\mu$sec]', size=12) ylabel(r'measured k',size=12) ylim([6,9]) savefig(pfile2) sys.exit()
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
#!/usr/bin/python2 # coding: utf-8 import psycopg2 def update_grp(grp_db): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS groups;") cur.execute("CREATE TABLE groups (id SERIAL, group_no smallint, subgroup_no smallint, spec_id integer NOT NULL, PRIMARY KEY (id), FOREIGN KEY (spec_id) REFERENCES specs (id));") for i in range(len(grp_db)): for j in range(len(grp_db[i])): tmp_spec = grp_db[i][j][1][1] cur.execute("INSERT INTO groups (group_no, subgroup_no, spec_id) VALUES (%s, 1, %s);", (grp_db[i][j][1], tmp_spec)) if grp_db[i][j][0] == '2': cur.execute("INSERT INTO groups (group_no, subgroup_no, spec_id) VALUES (%s, 2, %s);", (grp_db[i][j][1], tmp_spec)) conn.commit() cur.close() conn.close() #print(tmp) def update_schedule(schd_db, dates, grp_db): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS dates CASCADE;") cur.execute("CREATE TABLE dates (id SERIAL, day_date char(12), PRIMARY KEY (id));") for i in range(len(dates)): cur.execute("INSERT INTO dates (day_date) VALUES (%s);", (dates[i], )) cur.execute("DROP TABLE IF EXISTS schedule;") cur.execute("""CREATE TABLE schedule (id SERIAL, day integer NOT NULL, group_id integer, sched text, PRIMARY KEY (id), FOREIGN KEY (day) REFERENCES dates (id), FOREIGN KEY (group_id) REFERENCES groups (id));""") s = 0 for i in range(len(schd_db)): for j in range(len(schd_db[i][0])): s += 1 for k in range(6): cur.execute("""INSERT INTO schedule (day, group_id, sched) VALUES (%s, %s, %s);""", (k+1, s, schd_db[i][k][j])) conn.commit() cur.close() conn.close() def get_schedule(grp, sub_grp, day=0): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() if day != 0: cur.execute("""SELECT day_date, sched FROM schedule, groups, dates WHERE groups.id = schedule.group_id and dates.id = schedule.day and groups.group_no = %s and groups.subgroup_no = %s and schedule.day = %s;""", (grp, sub_grp, day)) else: cur.execute("""SELECT day_date, sched FROM schedule, groups, dates WHERE groups.id = schedule.group_id and dates.id = schedule.day and groups.group_no = %s and groups.subgroup_no = %s """, (grp, sub_grp)) res = '\n' for rec in cur: res += rec[0] + '\n' + rec[1] + '\n' conn.commit() cur.close() conn.close() return res
Python
#!/usr/bin/python2 # -*- coding: utf-8 -*- import sys,os,xmpp,time,select,string,re import db_oper class Bot: def __init__(self,jabber): self.jabber = jabber # self.remotejid = remotejid def register_handlers(self): self.jabber.RegisterHandler('message',self.xmpp_message) self.jabber.RegisterHandler('presence', self.authRoster, typ='subscribe') def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() #if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() != None: body = event.getBody() sys.stdout.write(body.encode('utf-8') + '\n') if re.match("(!пары [1-9]{2} [1-2])", body[:10].encode('utf-8')): #if body.lower()[:5] == u'!пары': days = {'пн': 1, 'вт': 2, 'ср': 3, 'чт': 4, 'пт': 5, 'сб': 6} grp = int(body[6:8]) sub_grp = int(body[9:10]) day = body[11:13].encode('utf-8') num = 0 if day: num = days[day] msg = xmpp.protocol.Message(to=fromjid,body=db_oper.get_schedule(grp, sub_grp, num),typ='chat') self.jabber.send(msg) else: msg = xmpp.protocol.Message(to=fromjid,body='Мне Вам нечего показать, возможно Вы допустили ошибку при вводе запроса.',typ='chat') self.jabber.send(msg) def authRoster(self, conn, msg): r = self.jabber.getRoster() x = msg.getFrom() r.Authorize(x) r.Subscribe(x) def stdio_message(self, message): m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') self.jabber.send(m) pass def xmpp_connect(self): con=self.jabber.connect() if not con: sys.stderr.write('could not connect!\n') return False sys.stderr.write('connected with %s\n'%con) auth=self.jabber.auth(jid.getNode(),jidparams['password'],resource=jid.getResource(), sasl=1) if not auth: sys.stderr.write('could not authenticate!\n') return False sys.stderr.write('authenticated using %s\n'%auth) self.jabber.sendInitPresence() self.register_handlers() return con if __name__ == '__main__': #tojid="sirius_gs@jabber.ru" jidparams = {'jid': "schedulebot@jabber.ru", 'password': "Oy2e3L8"} #jidparams = {'jid': "megabot@zloiia.ath.cx/suka", 'password': "qwerty123"} jid=xmpp.protocol.JID(jidparams['jid']) cl=xmpp.Client(jid.getDomain(),debug=[]) bot=Bot(cl) if not bot.xmpp_connect(): sys.stderr.write("Could not connect to server, or password mismatch!\n") sys.exit(1) #cl.SendInitPresence(requestRoster=0) # you may need to uncomment this for old server socketlist = {cl.Connection._sock:'xmpp',sys.stdin:'stdio'} online = 1 while online: cl.Process(1) cl.disconnect()
Python
#!/usr/bin/python2 # coding: utf-8 import psycopg2 def update_grp(grp_db): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS groups;") cur.execute("CREATE TABLE groups (id SERIAL, group_no smallint, subgroup_no smallint, spec_id integer NOT NULL, PRIMARY KEY (id), FOREIGN KEY (spec_id) REFERENCES specs (id));") for i in range(len(grp_db)): for j in range(len(grp_db[i])): tmp_spec = grp_db[i][j][1][1] cur.execute("INSERT INTO groups (group_no, subgroup_no, spec_id) VALUES (%s, 1, %s);", (grp_db[i][j][1], tmp_spec)) if grp_db[i][j][0] == '2': cur.execute("INSERT INTO groups (group_no, subgroup_no, spec_id) VALUES (%s, 2, %s);", (grp_db[i][j][1], tmp_spec)) conn.commit() cur.close() conn.close() #print(tmp) def update_schedule(schd_db, dates, grp_db): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS dates CASCADE;") cur.execute("CREATE TABLE dates (id SERIAL, day_date char(12), PRIMARY KEY (id));") for i in range(len(dates)): cur.execute("INSERT INTO dates (day_date) VALUES (%s);", (dates[i], )) cur.execute("DROP TABLE IF EXISTS schedule;") cur.execute("""CREATE TABLE schedule (id SERIAL, day integer NOT NULL, group_id integer, sched text, PRIMARY KEY (id), FOREIGN KEY (day) REFERENCES dates (id), FOREIGN KEY (group_id) REFERENCES groups (id));""") s = 0 for i in range(len(schd_db)): for j in range(len(schd_db[i][0])): s += 1 for k in range(6): cur.execute("""INSERT INTO schedule (day, group_id, sched) VALUES (%s, %s, %s);""", (k+1, s, schd_db[i][k][j])) conn.commit() cur.close() conn.close() def get_schedule(grp, sub_grp, day=0): conn = psycopg2.connect(database="ff_schedule", user="postgres", password="postgres") cur = conn.cursor() if day != 0: cur.execute("""SELECT day_date, sched FROM schedule, groups, dates WHERE groups.id = schedule.group_id and dates.id = schedule.day and groups.group_no = %s and groups.subgroup_no = %s and schedule.day = %s;""", (grp, sub_grp, day)) else: cur.execute("""SELECT day_date, sched FROM schedule, groups, dates WHERE groups.id = schedule.group_id and dates.id = schedule.day and groups.group_no = %s and groups.subgroup_no = %s """, (grp, sub_grp)) res = '\n' for rec in cur: res += rec[0] + '\n' + rec[1] + '\n' conn.commit() cur.close() conn.close() return res
Python
#!/usr/bin/python2 # -*- coding: cp1251 -*- import re import urllib import db_oper def parse_schedule(): schedule_db = [] #расписание - schedule[курс][день][№ группы на курсе] dates = [] #даты дней недели group_db = [] #группы - group_db[курс][группа] - (кол-во подгрупп, номер группы) n = i = 0 for num in ['one', 'two', 'three', 'four', 'five']: j = 0 schedule_db.append([]) page = urllib.urlopen('http://physics.pomorsu.ru/schedule/schedule_print_'+num+'.php').read().decode('cp1251') group_db.append(re.findall("\<td[^\r\n\t]*colspan=\'([1-2])\'\>[ А-Яа-я]+\№([0-9]{2})\<\/td\>".decode('utf8'), page)) schedule_tmp = re.findall("\<td\>(.*?)\<\/td\>".decode('utf8'), page) if num == 'one': dates = re.findall("\<td[^\r\n\t]+\>[А-Яа-я]{4,12}, ([.0-9]{8,10})\<\/td\>".decode('utf-8'), page) #я понятия не имею, как я это написал, но оно работает for d in range(6): schedule_db[n].append([]) for h in range(6): for g in range(len(group_db[n])): for sg in range(int(group_db[n][g][0])): if h==0: schedule_db[n][d].append('') if schedule_tmp[j] == '&nbsp;': schedule_tmp[j] = '_' schedule_db[n][d][i] += schedule_tmp[j] + '\n' j += 1 i += 1 i = 0 n += 1 db_oper.update_schedule(schedule_db, dates, group_db) #print(db_oper.get_schedule(43, 1, 2)) parse_schedule()
Python
#!/usr/bin/python2 # -*- coding: cp1251 -*- import re import urllib import db_oper def parse_schedule(): schedule_db = [] #расписание - schedule[курс][день][№ группы на курсе] dates = [] #даты дней недели group_db = [] #группы - group_db[курс][группа] - (кол-во подгрупп, номер группы) n = i = 0 for num in ['one', 'two', 'three', 'four', 'five']: j = 0 schedule_db.append([]) page = urllib.urlopen('http://physics.pomorsu.ru/schedule/schedule_print_'+num+'.php').read().decode('cp1251') group_db.append(re.findall("\<td[^\r\n\t]*colspan=\'([1-2])\'\>[ А-Яа-я]+\№([0-9]{2})\<\/td\>".decode('utf8'), page)) schedule_tmp = re.findall("\<td\>(.*?)\<\/td\>".decode('utf8'), page) if num == 'one': dates = re.findall("\<td[^\r\n\t]+\>[А-Яа-я]{4,12}, ([.0-9]{8,10})\<\/td\>".decode('utf-8'), page) #я понятия не имею, как я это написал, но оно работает for d in range(6): schedule_db[n].append([]) for h in range(6): for g in range(len(group_db[n])): for sg in range(int(group_db[n][g][0])): if h==0: schedule_db[n][d].append('') if schedule_tmp[j] == '&nbsp;': schedule_tmp[j] = '_' schedule_db[n][d][i] += schedule_tmp[j] + '\n' j += 1 i += 1 i = 0 n += 1 db_oper.update_schedule(schedule_db, dates, group_db) #print(db_oper.get_schedule(43, 1, 2)) parse_schedule()
Python
#!/usr/bin/python2 # -*- coding: utf-8 -*- import sys,os,xmpp,time,select,string,re import db_oper class Bot: def __init__(self,jabber): self.jabber = jabber # self.remotejid = remotejid def register_handlers(self): self.jabber.RegisterHandler('message',self.xmpp_message) self.jabber.RegisterHandler('presence', self.authRoster, typ='subscribe') def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() #if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() != None: body = event.getBody() sys.stdout.write(body.encode('utf-8') + '\n') if re.match("(!пары [1-9]{2} [1-2])", body[:10].encode('utf-8')): #if body.lower()[:5] == u'!пары': days = {'пн': 1, 'вт': 2, 'ср': 3, 'чт': 4, 'пт': 5, 'сб': 6} grp = int(body[6:8]) sub_grp = int(body[9:10]) day = body[11:13].encode('utf-8') num = 0 if day: num = days[day] msg = xmpp.protocol.Message(to=fromjid,body=db_oper.get_schedule(grp, sub_grp, num),typ='chat') self.jabber.send(msg) else: msg = xmpp.protocol.Message(to=fromjid,body='Мне Вам нечего показать, возможно Вы допустили ошибку при вводе запроса.',typ='chat') self.jabber.send(msg) def authRoster(self, conn, msg): r = self.jabber.getRoster() x = msg.getFrom() r.Authorize(x) r.Subscribe(x) def stdio_message(self, message): m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') self.jabber.send(m) pass def xmpp_connect(self): con=self.jabber.connect() if not con: sys.stderr.write('could not connect!\n') return False sys.stderr.write('connected with %s\n'%con) auth=self.jabber.auth(jid.getNode(),jidparams['password'],resource=jid.getResource(), sasl=1) if not auth: sys.stderr.write('could not authenticate!\n') return False sys.stderr.write('authenticated using %s\n'%auth) self.jabber.sendInitPresence() self.register_handlers() return con if __name__ == '__main__': #tojid="sirius_gs@jabber.ru" jidparams = {'jid': "schedulebot@jabber.ru", 'password': "Oy2e3L8"} #jidparams = {'jid': "megabot@zloiia.ath.cx/suka", 'password': "qwerty123"} jid=xmpp.protocol.JID(jidparams['jid']) cl=xmpp.Client(jid.getDomain(),debug=[]) bot=Bot(cl) if not bot.xmpp_connect(): sys.stderr.write("Could not connect to server, or password mismatch!\n") sys.exit(1) #cl.SendInitPresence(requestRoster=0) # you may need to uncomment this for old server socketlist = {cl.Connection._sock:'xmpp',sys.stdin:'stdio'} online = 1 while online: cl.Process(1) cl.disconnect()
Python
# This is Python example on how to use Mongoose embeddable web server, # http://code.google.com/p/mongoose # # Before using the mongoose module, make sure that Mongoose shared library is # built and present in the current (or system library) directory import mongoose import sys # Handle /show and /form URIs. def EventHandler(event, conn, info): if event == mongoose.HTTP_ERROR: conn.printf('%s', 'HTTP/1.0 200 OK\r\n') conn.printf('%s', 'Content-Type: text/plain\r\n\r\n') conn.printf('HTTP error: %d\n', info.status_code) return True elif event == mongoose.NEW_REQUEST and info.uri == '/show': conn.printf('%s', 'HTTP/1.0 200 OK\r\n') conn.printf('%s', 'Content-Type: text/plain\r\n\r\n') conn.printf('%s %s\n', info.request_method, info.uri) if info.request_method == 'POST': content_len = conn.get_header('Content-Length') post_data = conn.read(int(content_len)) my_var = conn.get_var(post_data, 'my_var') else: my_var = conn.get_var(info.query_string, 'my_var') conn.printf('my_var: %s\n', my_var or '<not set>') conn.printf('HEADERS: \n') for header in info.http_headers[:info.num_headers]: conn.printf(' %s: %s\n', header.name, header.value) return True elif event == mongoose.NEW_REQUEST and info.uri == '/form': conn.write('HTTP/1.0 200 OK\r\n' 'Content-Type: text/html\r\n\r\n' 'Use GET: <a href="/show?my_var=hello">link</a>' '<form action="/show" method="POST">' 'Use POST: type text and submit: ' '<input type="text" name="my_var"/>' '<input type="submit"/>' '</form>') return True elif event == mongoose.NEW_REQUEST and info.uri == '/secret': conn.send_file('/etc/passwd') return True else: return False # Create mongoose object, and register '/foo' URI handler # List of options may be specified in the contructor server = mongoose.Mongoose(EventHandler, document_root='/tmp', listening_ports='8080') print ('Mongoose started on port %s, press enter to quit' % server.get_option('listening_ports')) sys.stdin.read(1) # Deleting server object stops all serving threads print 'Stopping server.' del server
Python
# Copyright (c) 2004-2009 Sergey Lyubka # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $ """ This module provides python binding for the Mongoose web server. There are two classes defined: Connection: - wraps all functions that accept struct mg_connection pointer as first argument. Mongoose: wraps all functions that accept struct mg_context pointer as first argument. Creating Mongoose object automatically starts server, deleting object automatically stops it. There is no need to call mg_start() or mg_stop(). """ import ctypes import os NEW_REQUEST = 0 HTTP_ERROR = 1 EVENT_LOG = 2 INIT_SSL = 3 class mg_header(ctypes.Structure): """A wrapper for struct mg_header.""" _fields_ = [ ('name', ctypes.c_char_p), ('value', ctypes.c_char_p), ] class mg_request_info(ctypes.Structure): """A wrapper for struct mg_request_info.""" _fields_ = [ ('user_data', ctypes.c_char_p), ('request_method', ctypes.c_char_p), ('uri', ctypes.c_char_p), ('http_version', ctypes.c_char_p), ('query_string', ctypes.c_char_p), ('remote_user', ctypes.c_char_p), ('log_message', ctypes.c_char_p), ('remote_ip', ctypes.c_long), ('remote_port', ctypes.c_int), ('status_code', ctypes.c_int), ('is_ssl', ctypes.c_int), ('num_headers', ctypes.c_int), ('http_headers', mg_header * 64), ] mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(mg_request_info)) class Connection(object): """A wrapper class for all functions that take struct mg_connection * as the first argument.""" def __init__(self, mongoose, connection): self.m = mongoose self.conn = ctypes.c_void_p(connection) def get_header(self, name): val = self.m.dll.mg_get_header(self.conn, name) return ctypes.c_char_p(val).value def get_var(self, data, name): size = data and len(data) or 0 buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_get_var(data, size, name, buf, size) return n >= 0 and buf or None def printf(self, fmt, *args): val = self.m.dll.mg_printf(self.conn, fmt, *args) return ctypes.c_int(val).value def write(self, data): val = self.m.dll.mg_write(self.conn, data, len(data)) return ctypes.c_int(val).value def read(self, size): buf = ctypes.create_string_buffer(size) n = self.m.dll.mg_read(self.conn, buf, size) return n <= 0 and None or buf[:n] def send_file(self, path): self.m.dll.mg_send_file(self.conn, path) class Mongoose(object): """A wrapper class for Mongoose shared library.""" def __init__(self, callback, **kwargs): dll_extension = os.name == 'nt' and 'dll' or 'so' self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension) self.dll.mg_start.restype = ctypes.c_void_p self.dll.mg_modify_passwords_file.restype = ctypes.c_int self.dll.mg_read.restype = ctypes.c_int self.dll.mg_write.restype = ctypes.c_int self.dll.mg_printf.restype = ctypes.c_int self.dll.mg_get_header.restype = ctypes.c_char_p self.dll.mg_get_var.restype = ctypes.c_int self.dll.mg_get_cookie.restype = ctypes.c_int self.dll.mg_get_option.restype = ctypes.c_char_p if callback: # Create a closure that will be called by the shared library. def func(event, connection, request_info): # Wrap connection pointer into the connection # object and call Python callback conn = Connection(self, connection) return callback(event, conn, request_info.contents) and 1 or 0 # Convert the closure into C callable object self.callback = mg_callback_t(func) self.callback.restype = ctypes.c_char_p else: self.callback = ctypes.c_void_p(0) args = [y for x in kwargs.items() for y in x] + [None] options = (ctypes.c_char_p * len(args))(*args) ret = self.dll.mg_start(self.callback, 0, options) self.ctx = ctypes.c_void_p(ret) def __del__(self): """Destructor, stop Mongoose instance.""" self.dll.mg_stop(self.ctx) def get_option(self, name): return self.dll.mg_get_option(self.ctx, name)
Python
from composite import CompositeGoal from onek_onek import OneKingAttackOneKingEvaluator, OneKingFleeOneKingEvaluator class Goal_Think(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) self.evaluators = [OneKingAttackOneKingEvaluator(1.0), OneKingFleeOneKingEvaluator(1.0)] def activate(self): self.arbitrate() self.status = self.ACTIVE def process(self): self.activateIfInactive() status = self.processSubgoals() if status == self.COMPLETED or status == self.FAILED: self.status = self.INACTIVE return status def terminate(self): pass def arbitrate(self): most_desirable = None best_score = 0 for e in self.evaluators: d = e.calculateDesirability() if d > best_score: most_desirable = e best_score = d if most_desirable: most_desirable.setGoal(self.owner) return best_score
Python
from goal import Goal class CompositeGoal(Goal): def __init__(self, owner): Goal.__init__(self, owner) self.subgoals = [] def removeAllSubgoals(self): for s in self.subgoals: s.terminate() self.subgoals = [] def processSubgoals(self): # remove all completed and failed goals from the front of the # subgoal list while (self.subgoals and (self.subgoals[0].isComplete or self.subgoals[0].hasFailed)): subgoal = self.subgoals.pop() subgoal.terminate() if (self.subgoals): subgoal = self.subgoals.pop() status = subgoal.process() if status == COMPLETED and len(self.subgoals) > 1: return ACTIVE return status else: return COMPLETED def addSubgoal(self, goal): self.subgoals.append(goal)
Python
import unittest import checkers import games from globalconst import * # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) class TestBlackManSingleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[6] = BLACK | MAN squares[12] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[6, BLACK | MAN, FREE], [12, WHITE | MAN, FREE], [18, FREE, BLACK | MAN]]) class TestBlackManDoubleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[6] = BLACK | MAN squares[12] = WHITE | MAN squares[23] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[6, BLACK | MAN, FREE], [12, WHITE | MAN, FREE], [18, FREE, FREE], [23, WHITE | MAN, FREE], [28, FREE, BLACK | MAN]]) class TestBlackManCrownKingOnJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) squares[12] = BLACK | MAN squares[18] = WHITE | MAN squares[30] = WHITE | MAN squares[41] = WHITE | MAN # set another man on 40 to test that crowning # move ends the turn squares[40] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[12, BLACK | MAN, FREE], [18, WHITE | MAN, FREE], [24, FREE, FREE], [30, WHITE | MAN, FREE], [36, FREE, FREE], [41, WHITE | MAN, FREE], [46, FREE, BLACK | KING]]) class TestBlackManCrownKingOnMove(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[39] = BLACK | MAN squares[18] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[39, BLACK | MAN, FREE], [45, FREE, BLACK | KING]]) class TestBlackKingOptionalJumpDiamond(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[13] = BLACK | KING squares[19] = WHITE | MAN squares[30] = WHITE | MAN squares[29] = WHITE | MAN squares[18] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[13, BLACK | KING, FREE], [18, WHITE | MAN, FREE], [23, FREE, FREE], [29, WHITE | MAN, FREE], [35, FREE, FREE], [30, WHITE | MAN, FREE], [25, FREE, FREE], [19, WHITE | MAN, FREE], [13, FREE, BLACK | KING]]) self.assertEqual(moves[1].affected_squares, [[13, BLACK | KING, FREE], [19, WHITE | MAN, FREE], [25, FREE, FREE], [30, WHITE | MAN, FREE], [35, FREE, FREE], [29, WHITE | MAN, FREE], [23, FREE, FREE], [18, WHITE | MAN, FREE], [13, FREE, BLACK | KING]]) class TestWhiteManSingleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, WHITE | MAN]]) class TestWhiteManDoubleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN squares[25] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, FREE], [25, BLACK | MAN, FREE], [19, FREE, WHITE | MAN]]) class TestWhiteManCrownKingOnMove(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[15] = WHITE | MAN squares[36] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[15, WHITE | MAN, FREE], [9, FREE, WHITE | KING]]) class TestWhiteManCrownKingOnJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN squares[25] = BLACK | MAN squares[13] = BLACK | KING # set another man on 10 to test that crowning # move ends the turn squares[12] = BLACK | KING def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, FREE], [25, BLACK | MAN, FREE], [19, FREE, FREE], [13, BLACK | KING, FREE], [7, FREE, WHITE | KING]]) class TestWhiteKingOptionalJumpDiamond(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[13] = WHITE | KING squares[19] = BLACK | MAN squares[30] = BLACK | MAN squares[29] = BLACK | MAN squares[18] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[13, WHITE | KING, FREE], [18, BLACK | MAN, FREE], [23, FREE, FREE], [29, BLACK | MAN, FREE], [35, FREE, FREE], [30, BLACK | MAN, FREE], [25, FREE, FREE], [19, BLACK | MAN, FREE], [13, FREE, WHITE | KING]]) self.assertEqual(moves[1].affected_squares, [[13, WHITE | KING, FREE], [19, BLACK | MAN, FREE], [25, FREE, FREE], [30, BLACK | MAN, FREE], [35, FREE, FREE], [29, BLACK | MAN, FREE], [23, FREE, FREE], [18, BLACK | MAN, FREE], [13, FREE, WHITE | KING]]) class TestUtilityFunc(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE self.squares = self.board.squares def testInitialUtility(self): code = sum(self.board.value[s] for s in self.squares) nwm = code % 16 nwk = (code >> 4) % 16 nbm = (code >> 8) % 16 nbk = (code >> 12) % 16 nm = nbm + nwm nk = nbk + nwk self.assertEqual(self.board._eval_cramp(self.squares), 0) self.assertEqual(self.board._eval_backrankguard(self.squares), 0) self.assertEqual(self.board._eval_doublecorner(self.squares), 0) self.assertEqual(self.board._eval_center(self.squares), 0) self.assertEqual(self.board._eval_edge(self.squares), 0) self.assertEqual(self.board._eval_tempo(self.squares, nm, nbk, nbm, nwk, nwm), 0) self.assertEqual(self.board._eval_playeropposition(self.squares, nwm, nwk, nbk, nbm, nm, nk), 0) self.assertEqual(self.board.utility(WHITE), -2) class TestSuccessorFuncForBlack(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state def testInitialBlackMoves(self): # Tests whether initial game moves are correct from # Black's perspective moves = [m for m, _ in self.game.successors(self.board)] self.assertEqual(moves[0].affected_squares, [[17, BLACK | MAN, FREE], [23, FREE, BLACK | MAN]]) self.assertEqual(moves[1].affected_squares, [[18, BLACK | MAN, FREE], [23, FREE, BLACK | MAN]]) self.assertEqual(moves[2].affected_squares, [[18, BLACK | MAN, FREE], [24, FREE, BLACK | MAN]]) self.assertEqual(moves[3].affected_squares, [[19, BLACK | MAN, FREE], [24, FREE, BLACK | MAN]]) self.assertEqual(moves[4].affected_squares, [[19, BLACK | MAN, FREE], [25, FREE, BLACK | MAN]]) self.assertEqual(moves[5].affected_squares, [[20, BLACK | MAN, FREE], [25, FREE, BLACK | MAN]]) self.assertEqual(moves[6].affected_squares, [[20, BLACK | MAN, FREE], [26, FREE, BLACK | MAN]]) class TestSuccessorFuncForWhite(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state # I'm cheating here ... white never moves first in # a real game, but I want to see that the moves # would work anyway. self.board.to_move = WHITE def testInitialWhiteMoves(self): # Tests whether initial game moves are correct from # White's perspective moves = [m for m, _ in self.game.successors(self.board)] self.assertEqual(moves[0].affected_squares, [[34, WHITE | MAN, FREE], [29, FREE, WHITE | MAN]]) self.assertEqual(moves[1].affected_squares, [[34, WHITE | MAN, FREE], [28, FREE, WHITE | MAN]]) self.assertEqual(moves[2].affected_squares, [[35, WHITE | MAN, FREE], [30, FREE, WHITE | MAN]]) self.assertEqual(moves[3].affected_squares, [[35, WHITE | MAN, FREE], [29, FREE, WHITE | MAN]]) self.assertEqual(moves[4].affected_squares, [[36, WHITE | MAN, FREE], [31, FREE, WHITE | MAN]]) self.assertEqual(moves[5].affected_squares, [[36, WHITE | MAN, FREE], [30, FREE, WHITE | MAN]]) self.assertEqual(moves[6].affected_squares, [[37, WHITE | MAN, FREE], [31, FREE, WHITE | MAN]]) if __name__ == '__main__': unittest.main()
Python
import utils class Observer(object): def update(self, change): utils.abstract()
Python
import re import sys class LinkRules(object): """Rules for recognizing external links.""" # For the link targets: proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc' extern = r'(?P<extern_addr>(?P<extern_proto>%s):.*)' % proto interwiki = r''' (?P<inter_wiki> [A-Z][a-zA-Z]+ ) : (?P<inter_page> .* ) ''' def __init__(self): self.addr_re = re.compile('|'.join([ self.extern, self.interwiki, ]), re.X | re.U) # for addresses class Rules(object): """Hold all the rules for generating regular expressions.""" # For the inline elements: proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc' link = r'''(?P<link> \[\[ (?P<link_target>.+?) \s* ([|] \s* (?P<link_text>.+?) \s*)? ]] )''' image = r'''(?P<image> {{ (?P<image_target>.+?) \s* ([|] \s* (?P<image_text>.+?) \s*)? }} )''' macro = r'''(?P<macro> << (?P<macro_name> \w+) (\( (?P<macro_args> .*?) \))? \s* ([|] \s* (?P<macro_text> .+?) \s* )? >> )''' code = r'(?P<code> {{{ (?P<code_text>.*?) }}} )' emph = r'(?P<emph> (?<!:)// )' # there must be no : in front of the // # avoids italic rendering in urls with # unknown protocols strong = r'(?P<strong> \*\* )' linebreak = r'(?P<break> \\\\ )' escape = r'(?P<escape> ~ (?P<escaped_char>\S) )' char = r'(?P<char> . )' # For the block elements: separator = r'(?P<separator> ^ \s* ---- \s* $ )' # horizontal line line = r'(?P<line> ^ \s* $ )' # empty line that separates paragraphs head = r'''(?P<head> ^ \s* (?P<head_head>=+) \s* (?P<head_text> .*? ) \s* (?P<head_tail>=*) \s* $ )''' text = r'(?P<text> .+ )' list = r'''(?P<list> ^ [ \t]* ([*][^*\#]|[\#][^\#*]).* $ ( \n[ \t]* [*\#]+.* $ )* )''' # Matches the whole list, separate items are parsed later. The # list *must* start with a single bullet. item = r'''(?P<item> ^ \s* (?P<item_head> [\#*]+) \s* (?P<item_text> .*?) $ )''' # Matches single list items pre = r'''(?P<pre> ^{{{ \s* $ (\n)? (?P<pre_text> ([\#]!(?P<pre_kind>\w*?)(\s+.*)?$)? (.|\n)+? ) (\n)? ^}}} \s*$ )''' pre_escape = r' ^(?P<indent>\s*) ~ (?P<rest> \}\}\} \s*) $' table = r'''(?P<table> ^ \s* [|].*? \s* [|]? \s* $ )''' # For splitting table cells: cell = r''' \| \s* ( (?P<head> [=][^|]+ ) | (?P<cell> ( %s | [^|])+ ) ) \s* ''' % '|'.join([link, macro, image, code]) def __init__(self, bloglike_lines=False, url_protocols=None, wiki_words=False): c = re.compile # For pre escaping, in creole 1.0 done with ~: self.pre_escape_re = c(self.pre_escape, re.M | re.X) # for link descriptions self.link_re = c('|'.join([self.image, self.linebreak, self.char]), re.X | re.U) # for list items self.item_re = c(self.item, re.X | re.U | re.M) # for table cells self.cell_re = c(self.cell, re.X | re.U) # For block elements: if bloglike_lines: self.text = r'(?P<text> .+ ) (?P<break> (?<!\\)$\n(?!\s*$) )?' self.block_re = c('|'.join([self.line, self.head, self.separator, self.pre, self.list, self.table, self.text]), re.X | re.U | re.M) # For inline elements: if url_protocols is not None: self.proto = '|'.join(re.escape(p) for p in url_protocols) self.url = r'''(?P<url> (^ | (?<=\s | [.,:;!?()/=])) (?P<escaped_url>~)? (?P<url_target> (?P<url_proto> %s ):\S+? ) ($ | (?=\s | [,.:;!?()] (\s | $))))''' % self.proto inline_elements = [self.link, self.url, self.macro, self.code, self.image, self.strong, self.emph, self.linebreak, self.escape, self.char] if wiki_words: import unicodedata up_case = u''.join(unichr(i) for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i))=='Lu') self.wiki = ur'''(?P<wiki>[%s]\w+[%s]\w+)''' % (up_case, up_case) inline_elements.insert(3, self.wiki) self.inline_re = c('|'.join(inline_elements), re.X | re.U)
Python
from Tkinter import * class AutoScrollbar(Scrollbar): def __init__(self, master=None, cnf={}, **kw): self.container = kw.pop('container', None) self.row = kw.pop('row', 0) self.column = kw.pop('column', 0) self.sticky = kw.pop('sticky', '') Scrollbar.__init__(self, master, cnf, **kw) # a scrollbar that hides itself if it's not needed. only # works if you use the grid geometry manager. def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: # grid_remove is currently missing from Tkinter! self.tk.call('grid', 'remove', self) else: if not self.container: self.grid() else: self.grid(in_=self.container, row=self.row, column=self.column, sticky=self.sticky) Scrollbar.set(self, lo, hi) def pack(self, **kw): raise TclError, 'cannot use pack with this widget' def place(self, **kw): raise TclError, 'cannot use place with this widget'
Python
import games import copy import multiprocessing import time import random from controller import Controller from transpositiontable import TranspositionTable from globalconst import * class AlphaBetaController(Controller): def __init__(self, **props): self._model = props['model'] self._view = props['view'] self._end_turn_event = props['end_turn_event'] self._highlights = [] self._search_time = props['searchtime'] # in seconds self._before_turn_event = None self._parent_conn, self._child_conn = multiprocessing.Pipe() self._term_event = multiprocessing.Event() self.process = multiprocessing.Process() self._start_time = None self._call_id = 0 self._trans_table = TranspositionTable(50000) def set_before_turn_event(self, evt): self._before_turn_event = evt def add_highlights(self): for h in self._highlights: self._view.highlight_square(h, OUTLINE_COLOR) def remove_highlights(self): for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) def start_turn(self): if self._model.terminal_test(): self._before_turn_event() self._model.curr_state.attach(self._view) return self._view.update_statusbar('Thinking ...') self.process = multiprocessing.Process(target=calc_move, args=(self._model, self._trans_table, self._search_time, self._term_event, self._child_conn)) self._start_time = time.time() self.process.daemon = True self.process.start() self._view.canvas.after(100, self.get_move) def get_move(self): #if self._term_event.is_set() and self._model.curr_state.ok_to_move: # self._end_turn_event() # return self._highlights = [] moved = self._parent_conn.poll() while (not moved and (time.time() - self._start_time) < self._search_time * 2): self._call_id = self._view.canvas.after(500, self.get_move) return self._view.canvas.after_cancel(self._call_id) move = self._parent_conn.recv() #if self._model.curr_state.ok_to_move: self._before_turn_event() # highlight remaining board squares used in move step = 2 if len(move.affected_squares) > 2 else 1 for m in move.affected_squares[0::step]: idx = m[0] self._view.highlight_square(idx, OUTLINE_COLOR) self._highlights.append(idx) self._model.curr_state.attach(self._view) self._model.make_move(move, None, True, True, self._view.get_annotation()) # a new move obliterates any more redo's along a branch of the game tree self._model.curr_state.delete_redo_list() self._end_turn_event() def set_search_time(self, time): self._search_time = time # in seconds def stop_process(self): self._term_event.set() self._view.canvas.after_cancel(self._call_id) def end_turn(self): self._view.update_statusbar() self._model.curr_state.detach(self._view) def longest_of(moves): length = -1 selected = None for move in moves: l = len(move.affected_squares) if l > length: length = l selected = move return selected def calc_move(model, table, search_time, term_event, child_conn): move = None term_event.clear() captures = model.captures_available() if captures: time.sleep(0.7) move = longest_of(captures) else: depth = 0 start_time = time.time() curr_time = start_time checkpoint = start_time model_copy = copy.deepcopy(model) while 1: depth += 1 table.set_hash_move(depth, -1) move = games.alphabeta_search(model_copy.curr_state, model_copy, depth) checkpoint = curr_time curr_time = time.time() rem_time = search_time - (curr_time - checkpoint) if term_event.is_set(): # a signal means terminate term_event.clear() move = None break if (curr_time - start_time > search_time or ((curr_time - checkpoint) * 2) > rem_time or depth > MAXDEPTH): break child_conn.send(move) #model.curr_state.ok_to_move = True
Python
from goal import Goal from composite import CompositeGoal class Goal_OneKingAttack(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) def activate(self): self.status = self.ACTIVE self.removeAllSubgoals() # because goals are *pushed* onto the front of the subgoal list they must # be added in reverse order. self.addSubgoal(Goal_MoveTowardEnemy(self.owner)) self.addSubgoal(Goal_PinEnemy(self.owner)) def process(self): self.activateIfInactive() return self.processSubgoals() def terminate(self): self.status = self.INACTIVE class Goal_MoveTowardEnemy(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # if status is inactive, activate self.activateIfInactive() # only moves (not captures) are a valid goal if self.owner.captures: self.status = self.FAILED return # identify player king and enemy king plr_color = self.owner.to_move enemy_color = self.owner.enemy player = self.owner.get_pieces(plr_color)[0] p_idx, _ = player p_row, p_col = self.owner.row_col_for_index(p_idx) enemy = self.owner.get_pieces(enemy_color)[0] e_idx, _ = enemy e_row, e_col = self.owner.row_col_for_index(e_idx) # if distance between player and enemy is already down # to 2 rows or cols, then goal is complete. if abs(p_row - e_row) == 2 or abs(p_col - e_col) == 2: self.status = self.COMPLETED # select the available move that decreases the distance # between the player and the enemy. If no such move exists, # the goal has failed. good_move = None for m in self.owner.moves: # try a move and gather the new row & col for the player self.owner.make_move(m, False, False) plr_update = self.owner.get_pieces(plr_color)[0] pu_idx, _ = plr_update pu_row, pu_col = self.owner.row_col_for_index(pu_idx) self.owner.undo_move(m, False, False) new_diff = abs(pu_row - e_row) + abs(pu_col - e_col) old_diff = abs(p_row - e_row) + abs(p_col - e_col) if new_diff < old_diff: good_move = m break if good_move: self.owner.make_move(good_move, True, True) else: self.status = self.FAILED def terminate(self): self.status = self.INACTIVE class Goal_PinEnemy(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # for now, I'm not even sure I need this goal, but I'm saving it # as a placeholder. self.status = self.COMPLETED def terminate(self): self.status = self.INACTIVE
Python
import math, os, sys from ConfigParser import RawConfigParser DEFAULT_SIZE = 400 BOARD_SIZE = 8 CHECKER_SIZE = 30 MAX_VALID_SQ = 32 MOVE = 0 JUMP = 1 OCCUPIED = 0 BLACK = 1 WHITE = 2 MAN = 4 KING = 8 FREE = 16 COLORS = BLACK | WHITE TYPES = OCCUPIED | BLACK | WHITE | MAN | KING | FREE HUMAN = 0 COMPUTER = 1 MIN = 0 MAX = 1 IMAGE_DIR = 'images' + os.sep RAVEN_ICON = IMAGE_DIR + '_raven.ico' BULLET_IMAGE = IMAGE_DIR + 'bullet_green.gif' CROWN_IMAGE = IMAGE_DIR + 'crown.gif' BOLD_IMAGE = IMAGE_DIR + 'text_bold.gif' ITALIC_IMAGE = IMAGE_DIR + 'text_italic.gif' BULLETS_IMAGE = IMAGE_DIR + 'text_list_bullets.gif' NUMBERS_IMAGE = IMAGE_DIR + 'text_list_numbers.gif' ADDLINK_IMAGE = IMAGE_DIR + 'link.gif' REMLINK_IMAGE = IMAGE_DIR + 'link_break.gif' UNDO_IMAGE = IMAGE_DIR + 'resultset_previous.gif' UNDOALL_IMAGE = IMAGE_DIR + 'resultset_first.gif' REDO_IMAGE = IMAGE_DIR + 'resultset_next.gif' REDOALL_IMAGE = IMAGE_DIR + 'resultset_last.gif' LIGHT_SQUARES = 'tan' DARK_SQUARES = 'dark green' OUTLINE_COLOR = 'white' LIGHT_CHECKERS = 'white' DARK_CHECKERS = 'red' WHITE_CHAR = 'w' WHITE_KING = 'W' BLACK_CHAR = 'b' BLACK_KING = 'B' FREE_CHAR = '.' OCCUPIED_CHAR = '-' INFINITY = 9999999 MAXDEPTH = 10 VERSION = '0.4' TITLE = 'Raven ' + VERSION PROGRAM_TITLE = 'Raven Checkers' CUR_DIR = sys.path[0] TRAINING_DIR = 'training' # search values for transposition table hashfALPHA, hashfBETA, hashfEXACT = range(3) # constants for evaluation function TURN = 2 # color to move gets + turn BRV = 3 # multiplier for back rank KCV = 5 # multiplier for kings in center MCV = 1 # multiplier for men in center MEV = 1 # multiplier for men on edge KEV = 5 # multiplier for kings on edge CRAMP = 5 # multiplier for cramp OPENING = 2 # multipliers for tempo MIDGAME = -1 ENDGAME = 2 INTACTDOUBLECORNER = 3 BLACK_IDX = [5,6] WHITE_IDX = [-5,-6] KING_IDX = [-6,-5,5,6] FIRST = 0 MID = 1 LAST = -1 # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) # other squares reachable from a particular square with a white man WHITEMAP = {45: set([39,40,34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 46: set([40,41,34,35,36,28,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 47: set([41,42,35,36,37,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 48: set([42,36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 39: set([34,28,29,23,24,17,18,19,12,13,14,6,7,8,9]), 40: set([34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 41: set([35,36,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 42: set([36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 34: set([28,29,23,24,17,18,19,12,13,14,6,7,8,9]), 35: set([29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 36: set([30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 37: set([31,25,26,19,20,13,14,15,7,8,9]), 28: set([23,17,18,12,13,6,7,8]), 29: set([23,24,17,18,19,12,13,14,6,7,8,9]), 30: set([24,25,18,19,20,12,13,14,15,6,7,8,9]), 31: set([25,26,19,20,13,14,15,7,8,9]), 23: set([17,18,12,13,6,7,8]), 24: set([18,19,12,13,14,6,7,8,9]), 25: set([19,20,13,14,15,7,8,9]), 26: set([20,14,15,8,9]), 17: set([12,6,7]), 18: set([12,13,6,7,8]), 19: set([13,14,7,8,9]), 20: set([14,15,8,9]), 12: set([6,7]), 13: set([7,8]), 14: set([8,9]), 15: set([9]), 6: set(), 7: set(), 8: set(), 9: set()} # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) # other squares reachable from a particular square with a black man BLACKMAP = {6: set([12,17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 7: set([12,13,17,18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 8: set([13,14,18,19,20,23,24,25,26,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 9: set([14,15,19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 12: set([17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 13: set([18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 14: set([19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 15: set([20,25,26,30,31,35,36,37,40,41,42,45,46,47,48]), 17: set([23,28,29,34,35,39,40,41,45,46,47]), 18: set([23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 19: set([24,25,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 20: set([25,26,30,31,35,36,37,40,41,42,45,46,47,48]), 23: set([28,29,34,35,39,40,41,45,46,47]), 24: set([29,30,34,35,36,39,40,41,42,45,46,47,48]), 25: set([30,31,35,36,37,40,41,42,45,46,47,48]), 26: set([31,36,37,41,42,46,47,48]), 28: set([34,39,40,45,46]), 29: set([34,35,39,40,41,45,46,47]), 30: set([35,36,40,41,42,45,46,47,48]), 31: set([36,37,41,42,46,47,48]), 34: set([39,40,45,46]), 35: set([40,41,45,46,47]), 36: set([41,42,46,47,48]), 37: set([42,47,48]), 39: set([45]), 40: set([45,46]), 41: set([46,47]), 42: set([47,48]), 45: set(), 46: set(), 47: set(), 48: set()} # translate from simple input notation to real checkerboard notation IMAP = {'a1': 5, 'c1': 6, 'e1': 7, 'g1': 8, 'b2': 10, 'd2': 11, 'f2': 12, 'h2': 13, 'a3': 14, 'c3': 15, 'e3': 16, 'g3': 17, 'b4': 19, 'd4': 20, 'f4': 21, 'h4': 22, 'a5': 23, 'c5': 24, 'e5': 25, 'g5': 26, 'b6': 28, 'd6': 29, 'f6': 30, 'h6': 31, 'a7': 32, 'c7': 33, 'e7': 34, 'g7': 35, 'b8': 37, 'd8': 38, 'f8': 39, 'h8': 40} CBMAP = {5:4, 6:3, 7:2, 8:1, 10:8, 11:7, 12:6, 13:5, 14:12, 15:11, 16:10, 17:9, 19:16, 20:15, 21:14, 22:13, 23:20, 24:19, 25:18, 26:17, 28:24, 29:23, 30:22, 31:21, 32:28, 33:27, 34:26, 35:25, 37:32, 38:31, 39:30, 40:29} def create_position_map(): """ Maps compressed grid indices xi + yi * 8 to internal board indices """ pos = {} pos[1] = 45; pos[3] = 46; pos[5] = 47; pos[7] = 48 pos[8] = 39; pos[10] = 40; pos[12] = 41; pos[14] = 42 pos[17] = 34; pos[19] = 35; pos[21] = 36; pos[23] = 37 pos[24] = 28; pos[26] = 29; pos[28] = 30; pos[30] = 31 pos[33] = 23; pos[35] = 24; pos[37] = 25; pos[39] = 26 pos[40] = 17; pos[42] = 18; pos[44] = 19; pos[46] = 20 pos[49] = 12; pos[51] = 13; pos[53] = 14; pos[55] = 15 pos[56] = 6; pos[58] = 7; pos[60] = 8; pos[62] = 9 return pos def create_key_map(): """ Maps internal board indices to checkerboard label numbers """ key = {} key[6] = 4; key[7] = 3; key[8] = 2; key[9] = 1 key[12] = 8; key[13] = 7; key[14] = 6; key[15] = 5 key[17] = 12; key[18] = 11; key[19] = 10; key[20] = 9 key[23] = 16; key[24] = 15; key[25] = 14; key[26] = 13 key[28] = 20; key[29] = 19; key[30] = 18; key[31] = 17 key[34] = 24; key[35] = 23; key[36] = 22; key[37] = 21 key[39] = 28; key[40] = 27; key[41] = 26; key[42] = 25 key[45] = 32; key[46] = 31; key[47] = 30; key[48] = 29 return key def create_grid_map(): """ Maps internal board indices to grid (row, col) coordinates """ grd = {} grd[6] = (7,0); grd[7] = (7,2); grd[8] = (7,4); grd[9] = (7,6) grd[12] = (6,1); grd[13] = (6,3); grd[14] = (6,5); grd[15] = (6,7) grd[17] = (5,0); grd[18] = (5,2); grd[19] = (5,4); grd[20] = (5,6) grd[23] = (4,1); grd[24] = (4,3); grd[25] = (4,5); grd[26] = (4,7) grd[28] = (3,0); grd[29] = (3,2); grd[30] = (3,4); grd[31] = (3,6) grd[34] = (2,1); grd[35] = (2,3); grd[36] = (2,5); grd[37] = (2,7) grd[39] = (1,0); grd[40] = (1,2); grd[41] = (1,4); grd[42] = (1,6) grd[45] = (0,1); grd[46] = (0,3); grd[47] = (0,5); grd[48] = (0,7) return grd def flip_dict(m): d = {} keys = [k for k, _ in m.iteritems()] vals = [v for _, v in m.iteritems()] for k, v in zip(vals, keys): d[k] = v return d def reverse_dict(m): d = {} keys = [k for k, _ in m.iteritems()] vals = [v for _, v in m.iteritems()] for k, v in zip(keys, reversed(vals)): d[k] = v return d def similarity(pattern, pieces): global grid p1 = [grid[i] for i in pattern] p2 = [grid[j] for j in pieces] return sum(min(math.hypot(x1-x2, y1-y2) for x1, y1 in p1) for x2, y2 in p2) def get_preferences_from_file(): config = RawConfigParser() if not os.access('raven.ini',os.F_OK): # no .ini file yet, so make one config.add_section('AnnotationWindow') config.set('AnnotationWindow', 'font', 'Arial') config.set('AnnotationWindow', 'size', '12') # Writing our configuration file to 'raven.ini' with open('raven.ini', 'wb') as configfile: config.write(configfile) config.read('raven.ini') font = config.get('AnnotationWindow', 'font') size = config.get('AnnotationWindow', 'size') return font, size def write_preferences_to_file(font, size): config = RawConfigParser() config.add_section('AnnotationWindow') config.set('AnnotationWindow', 'font', font) config.set('AnnotationWindow', 'size', size) # Writing our configuration file to 'raven.ini' with open('raven.ini', 'wb') as configfile: config.write(configfile) def parse_index(idx): line, _, char = idx.partition('.') return int(line), int(char) def to_string(line, char): return "%d.%d" % (line, char) grid = create_grid_map() keymap = create_key_map() squaremap = flip_dict(keymap)
Python
import os from Tkinter import * from Tkconstants import END, N, S, E, W from command import * from observer import * from globalconst import * from autoscrollbar import AutoScrollbar from textserialize import Serializer from hyperlinkmgr import HyperlinkManager from tkFileDialog import askopenfilename from tkFont import Font from tooltip import ToolTip class BoardView(Observer): def __init__(self, root, **props): self._statusbar = props['statusbar'] self.root = root self._model = props['model'] self._model.curr_state.attach(self) self._gameMgr = props['parent'] self._board_side = props.get('side') or DEFAULT_SIZE self.light_squares = props.get('lightsquares') or LIGHT_SQUARES self.dark_squares = props.get('darksquares') or DARK_SQUARES self.light_color = props.get('lightcheckers') or LIGHT_CHECKERS self.dark_color = props.get('darkcheckers') or DARK_CHECKERS self._square_size = self._board_side / 8 self._piece_offset = self._square_size / 5 self._crownpic = PhotoImage(file=CROWN_IMAGE) self._boardpos = create_position_map() self._gridpos = create_grid_map() self.canvas = Canvas(root, width=self._board_side, height=self._board_side, borderwidth=0, highlightthickness=0) right_panel = Frame(root, borderwidth=1, relief='sunken') self.toolbar = Frame(root) font, size = get_preferences_from_file() self.scrollbar = AutoScrollbar(root, container=right_panel, row=1, column=1, sticky='ns') self.txt = Text(root, width=40, height=1, borderwidth=0, font=(font,size), wrap='word', yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.txt.yview) self.canvas.pack(side='left', fill='both', expand=False) self.toolbar.grid(in_=right_panel, row=0, column=0, sticky='ew') right_panel.pack(side='right', fill='both', expand=True) self.txt.grid(in_=right_panel, row=1, column=0, sticky='nsew') right_panel.grid_rowconfigure(1, weight=1) right_panel.grid_columnconfigure(0, weight=1) self.init_images() self.init_toolbar_buttons() self.init_font_sizes(font, size) self.init_tags() self._register_event_handlers() self.btnset = set([self.bold, self.italic, self.addLink, self.remLink]) self.btnmap = {'bold': self.bold, 'italic': self.italic, 'bullet': self.bullets, 'number': self.numbers, 'hyper': self.addLink} self.hypermgr = HyperlinkManager(self.txt, self._gameMgr.load_game) self.serializer = Serializer(self.txt, self.hypermgr) self.curr_annotation = '' self._setup_board(root) starting_squares = [i for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] & (BLACK | WHITE)] self._draw_checkers(Command(add=starting_squares)) self.flip_view = False # black on bottom self._label_board() self.update_statusbar() def _toggle_state(self, tags, btn): # toggle the text state based on the first character in the # selected range. if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') elif self.txt.tag_ranges('insert'): current_tags = self.txt.tag_names('insert') else: return for tag in tags: already_tagged = any((x for x in current_tags if x.startswith(tag))) for t in current_tags: if t != 'sel': self.txt.tag_remove(t, 'sel.first', 'sel.last') if not already_tagged: self.txt.tag_add(tag, 'sel.first', 'sel.last') btn.configure(relief='sunken') other_btns = self.btnset.difference([btn]) for b in other_btns: b.configure(relief='raised') else: btn.configure(relief='raised') def _on_bold(self): self.bold_tooltip.hide() self._toggle_state(['bold'], self.bold) def _on_italic(self): self.italic_tooltip.hide() self._toggle_state(['italic'], self.italic) def _on_bullets(self): self._process_button_click('bullet', self.bullets_tooltip, self._add_bullets_if_needed, self._remove_bullets_if_needed) def _on_numbers(self): self._process_button_click('number', self.numbers_tooltip, self._add_numbers_if_needed, self._remove_numbers_if_needed) def _process_button_click(self, tag, tooltip, add_func, remove_func): tooltip.hide() if self.txt.tag_ranges('sel'): startline, _ = parse_index(self.txt.index('sel.first')) endline, _ = parse_index(self.txt.index('sel.last')) else: startline, _ = parse_index(self.txt.index(INSERT)) endline = startline current_tags = self.txt.tag_names('%d.0' % startline) if tag not in current_tags: add_func(startline, endline) else: remove_func(startline, endline) def _add_bullets_if_needed(self, startline, endline): self._remove_numbers_if_needed(startline, endline) for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'bullet' not in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.insert(start, '\t') self.txt.image_create(start, image=self.bullet_image) self.txt.insert(start, '\t') self.txt.tag_add('bullet', start, end) self.bullets.configure(relief='sunken') self.numbers.configure(relief='raised') def _remove_bullets_if_needed(self, startline, endline): for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'bullet' in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.tag_remove('bullet', start, end) start = '%d.0' % line end = '%d.3' % line self.txt.delete(start, end) self.bullets.configure(relief='raised') def _add_numbers_if_needed(self, startline, endline): self._remove_bullets_if_needed(startline, endline) num = 1 for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'number' not in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.insert(start, '\t') numstr = '%d.' % num self.txt.insert(start, numstr) self.txt.insert(start, '\t') self.txt.tag_add('number', start, end) num += 1 self.numbers.configure(relief='sunken') self.bullets.configure(relief='raised') def _remove_numbers_if_needed(self, startline, endline): cnt = IntVar() for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'number' in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.tag_remove('number', start, end) # Regex to match a tab, followed by any number of digits, # followed by a period, all at the start of a line. # The cnt variable stores the number of characters matched. pos = self.txt.search('^\t\d+\.\t', start, end, None, None, None, True, None, cnt) if pos: end = '%d.%d' % (line, cnt.get()) self.txt.delete(start, end) self.numbers.configure(relief='raised') def _on_undo(self): self.undo_tooltip.hide() self._gameMgr.parent.undo_single_move() def _on_undo_all(self): self.undoall_tooltip.hide() self._gameMgr.parent.undo_all_moves() def _on_redo(self): self.redo_tooltip.hide() self._gameMgr.parent.redo_single_move() def _on_redo_all(self): self.redoall_tooltip.hide() self._gameMgr.parent.redo_all_moves() def _on_add_link(self): filename = askopenfilename(initialdir='training') if filename: filename = os.path.relpath(filename, CUR_DIR) self._toggle_state(self.hypermgr.add(filename), self.addLink) def _on_remove_link(self): if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') if 'hyper' in current_tags: self._toggle_state(['hyper'], self.addLink) def _register_event_handlers(self): self.txt.event_add('<<KeyRel>>', '<KeyRelease-Home>', '<KeyRelease-End>', '<KeyRelease-Left>', '<KeyRelease-Right>', '<KeyRelease-Up>', '<KeyRelease-Down>', '<KeyRelease-Delete>', '<KeyRelease-BackSpace>') Widget.bind(self.txt, '<<Selection>>', self._sel_changed) Widget.bind(self.txt, '<ButtonRelease-1>', self._sel_changed) Widget.bind(self.txt, '<<KeyRel>>', self._key_release) def _key_release(self, event): line, char = parse_index(self.txt.index(INSERT)) self.update_button_state(to_string(line, char)) def _sel_changed(self, event): self.update_button_state(self.txt.index(INSERT)) def is_dirty(self): return self.curr_annotation != self.get_annotation() def reset_toolbar_buttons(self): for btn in self.btnset: btn.configure(relief='raised') def update_button_state(self, index): if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') else: current_tags = self.txt.tag_names(index) for btn in self.btnmap.itervalues(): btn.configure(relief='raised') for tag in current_tags: if tag in self.btnmap.keys(): self.btnmap[tag].configure(relief='sunken') def init_font_sizes(self, font, size): self.txt.config(font=[font, size]) self._b_font = Font(self.root, (font, size, 'bold')) self._i_font = Font(self.root, (font, size, 'italic')) def init_tags(self): self.txt.tag_config('bold', font=self._b_font, wrap='word') self.txt.tag_config('italic', font=self._i_font, wrap='word') self.txt.tag_config('number', tabs='.5c center 1c left', lmargin1='0', lmargin2='1c') self.txt.tag_config('bullet', tabs='.5c center 1c left', lmargin1='0', lmargin2='1c') def init_images(self): self.bold_image = PhotoImage(file=BOLD_IMAGE) self.italic_image = PhotoImage(file=ITALIC_IMAGE) self.addlink_image = PhotoImage(file=ADDLINK_IMAGE) self.remlink_image = PhotoImage(file=REMLINK_IMAGE) self.bullets_image = PhotoImage(file=BULLETS_IMAGE) self.bullet_image = PhotoImage(file=BULLET_IMAGE) self.numbers_image = PhotoImage(file=NUMBERS_IMAGE) self.undo_image = PhotoImage(file=UNDO_IMAGE) self.undoall_image= PhotoImage(file=UNDOALL_IMAGE) self.redo_image = PhotoImage(file=REDO_IMAGE) self.redoall_image = PhotoImage(file=REDOALL_IMAGE) def init_toolbar_buttons(self): self.bold = Button(name='bold', image=self.bold_image, borderwidth=1, command=self._on_bold) self.bold.grid(in_=self.toolbar, row=0, column=0, sticky=W) self.italic = Button(name='italic', image=self.italic_image, borderwidth=1, command=self._on_italic) self.italic.grid(in_=self.toolbar, row=0, column=1, sticky=W) self.bullets = Button(name='bullets', image=self.bullets_image, borderwidth=1, command=self._on_bullets) self.bullets.grid(in_=self.toolbar, row=0, column=2, sticky=W) self.numbers = Button(name='numbers', image=self.numbers_image, borderwidth=1, command=self._on_numbers) self.numbers.grid(in_=self.toolbar, row=0, column=3, sticky=W) self.addLink = Button(name='addlink', image=self.addlink_image, borderwidth=1, command=self._on_add_link) self.addLink.grid(in_=self.toolbar, row=0, column=4, sticky=W) self.remLink = Button(name='remlink', image=self.remlink_image, borderwidth=1, command=self._on_remove_link) self.remLink.grid(in_=self.toolbar, row=0, column=5, sticky=W) self.frame = Frame(width=0) self.frame.grid(in_=self.toolbar, padx=5, row=0, column=6, sticky=W) self.undoall = Button(name='undoall', image=self.undoall_image, borderwidth=1, command=self._on_undo_all) self.undoall.grid(in_=self.toolbar, row=0, column=7, sticky=W) self.undo = Button(name='undo', image=self.undo_image, borderwidth=1, command=self._on_undo) self.undo.grid(in_=self.toolbar, row=0, column=8, sticky=W) self.redo = Button(name='redo', image=self.redo_image, borderwidth=1, command=self._on_redo) self.redo.grid(in_=self.toolbar, row=0, column=9, sticky=W) self.redoall = Button(name='redoall', image=self.redoall_image, borderwidth=1, command=self._on_redo_all) self.redoall.grid(in_=self.toolbar, row=0, column=10, sticky=W) self.bold_tooltip = ToolTip(self.bold, 'Bold') self.italic_tooltip = ToolTip(self.italic, 'Italic') self.bullets_tooltip = ToolTip(self.bullets, 'Bullet list') self.numbers_tooltip = ToolTip(self.numbers, 'Numbered list') self.addlink_tooltip = ToolTip(self.addLink, 'Add hyperlink') self.remlink_tooltip = ToolTip(self.remLink, 'Remove hyperlink') self.undoall_tooltip = ToolTip(self.undoall, 'First move') self.undo_tooltip = ToolTip(self.undo, 'Back one move') self.redo_tooltip = ToolTip(self.redo, 'Forward one move') self.redoall_tooltip = ToolTip(self.redoall, 'Last move') def reset_view(self, model): self._model = model self.txt.delete('1.0', END) sq = self._model.curr_state.valid_squares self.canvas.delete(self.dark_color) self.canvas.delete(self.light_color) starting_squares = [i for i in sq if (self._model.curr_state.squares[i] & (BLACK | WHITE))] self._draw_checkers(Command(add=starting_squares)) for i in sq: self.highlight_square(i, DARK_SQUARES) def calc_board_loc(self, x, y): vx, vy = self.calc_valid_xy(x, y) xi = int(vx / self._square_size) yi = int(vy / self._square_size) return xi, yi def calc_board_pos(self, xi, yi): return self._boardpos.get(xi + yi * 8, 0) def calc_grid_pos(self, pos): return self._gridpos[pos] def highlight_square(self, idx, color): row, col = self._gridpos[idx] hpos = col + row * 8 self.canvas.itemconfigure('o'+str(hpos), outline=color) def calc_valid_xy(self, x, y): return (min(max(0, self.canvas.canvasx(x)), self._board_side-1), min(max(0, self.canvas.canvasy(y)), self._board_side-1)) def notify(self, move): add_lst = [] rem_lst = [] for idx, _, newval in move.affected_squares: if newval & FREE: rem_lst.append(idx) else: add_lst.append(idx) cmd = Command(add=add_lst, remove=rem_lst) self._draw_checkers(cmd) self.txt.delete('1.0', END) self.serializer.restore(move.annotation) self.curr_annotation = move.annotation if self.txt.get('1.0','end').strip() == '': start = keymap[move.affected_squares[FIRST][0]] dest = keymap[move.affected_squares[LAST][0]] movestr = '%d-%d' % (start, dest) self.txt.insert('1.0', movestr) def get_annotation(self): return self.serializer.dump() def erase_checker(self, index): self.canvas.delete('c'+str(index)) def flip_board(self, flip): self._delete_labels() self.canvas.delete(self.dark_color) self.canvas.delete(self.light_color) if self.flip_view != flip: self.flip_view = flip self._gridpos = reverse_dict(self._gridpos) self._boardpos = reverse_dict(self._boardpos) self._label_board() starting_squares = [i for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] & (BLACK | WHITE)] all_checkers = Command(add=starting_squares) self._draw_checkers(all_checkers) def update_statusbar(self, output=None): if output: self._statusbar['text'] = output self.root.update() return if self._model.terminal_test(): text = "Game over. " if self._model.curr_state.to_move == WHITE: text += "Black won." else: text += "White won." self._statusbar['text'] = text return if self._model.curr_state.to_move == WHITE: self._statusbar['text'] = "White to move" else: self._statusbar['text'] = "Black to move" def get_positions(self, type): return map(str, sorted((keymap[i] for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] == type))) # private functions def _setup_board(self, root): for r in range(0, 8, 2): row = r * self._square_size for c in range(0, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row, col+self._square_size-1, row+self._square_size-1, fill=LIGHT_SQUARES, outline=LIGHT_SQUARES) for c in range(1, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row+self._square_size, col+self._square_size-1, row+self._square_size*2-1, fill=LIGHT_SQUARES, outline=LIGHT_SQUARES) for r in range(0, 8, 2): row = r * self._square_size for c in range(1, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row, col+self._square_size-1, row+self._square_size-1, fill=DARK_SQUARES, outline=DARK_SQUARES, tags='o'+str(r*8+c)) for c in range(0, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row+self._square_size, col+self._square_size-1, row+self._square_size*2-1, fill=DARK_SQUARES, outline=DARK_SQUARES, tags='o'+str(((r+1)*8)+c)) def _label_board(self): for key, pair in self._gridpos.iteritems(): row, col = pair xpos, ypos = col * self._square_size, row * self._square_size self.canvas.create_text(xpos+self._square_size-7, ypos+self._square_size-7, text=str(keymap[key]), fill=LIGHT_SQUARES, tag='label') def _delete_labels(self): self.canvas.delete('label') def _draw_checkers(self, change): if change == None: return for i in change.remove: self.canvas.delete('c'+str(i)) for i in change.add: checker = self._model.curr_state.squares[i] color = self.dark_color if checker & COLORS == BLACK else self.light_color row, col = self._gridpos[i] x = col * self._square_size + self._piece_offset y = row * self._square_size + self._piece_offset tag = 'c'+str(i) self.canvas.create_oval(x+2, y+2, x+2+CHECKER_SIZE, y+2+CHECKER_SIZE, outline='black', fill='black', tags=(color, tag)) self.canvas.create_oval(x, y, x+CHECKER_SIZE, y+CHECKER_SIZE, outline='black', fill=color, tags=(color, tag)) if checker & KING: self.canvas.create_image(x+15, y+15, image=self._crownpic, anchor=CENTER, tags=(color, tag))
Python
import sys import games from globalconst import * class Player(object): def __init__(self, color): self.col = color def _get_color(self): return self.col color = property(_get_color, doc="Player color") class AlphabetaPlayer(Player): def __init__(self, color, depth=4): Player.__init__(self, color) self.searchDepth = depth def select_move(self, game, state): sys.stdout.write('\nThinking ... ') movelist = games.alphabeta_search(state, game, False, self.searchDepth) positions = [] step = 2 if game.captures_available(state) else 1 for i in range(0, len(movelist), step): idx, old, new = movelist[i] positions.append(str(CBMAP[idx])) move = '-'.join(positions) print 'I move %s' % move return movelist class HumanPlayer(Player): def __init__(self, color): Player.__init__(self, color) def select_move(self, game, state): while 1: moves = game.legal_moves(state) positions = [] idx = 0 while 1: reqstr = 'Move to? ' if positions else 'Move from? ' # do any positions match the input pos = self._valid_pos(raw_input(reqstr), moves, idx) if pos: positions.append(pos) # reduce moves to number matching the positions entered moves = self._filter_moves(pos, moves, idx) if game.captures_available(state): idx += 2 else: idx += 1 if len(moves) <= 1: break if len(moves) == 1: return moves[0] else: print "Illegal move!" def _valid_pos(self, pos, moves, idx): t_pos = IMAP.get(pos.lower(), 0) if t_pos == 0: return None # move is illegal for m in moves: if idx < len(m) and m[idx][0] == t_pos: return t_pos return None def _filter_moves(self, pos, moves, idx): del_list = [] for i, m in enumerate(moves): if pos != m[idx][0]: del_list.append(i) for i in reversed(del_list): del moves[i] return moves
Python
from UserDict import UserDict class TranspositionTable (UserDict): def __init__ (self, maxSize): UserDict.__init__(self) assert maxSize > 0 self.maxSize = maxSize self.krono = [] self.maxdepth = 0 self.killer1 = [-1]*20 self.killer2 = [-1]*20 self.hashmove = [-1]*20 def __setitem__ (self, key, item): if not key in self: if len(self) >= self.maxSize: try: del self[self.krono[0]] except KeyError: pass # Overwritten del self.krono[0] self.data[key] = item self.krono.append(key) def probe (self, hash, depth, alpha, beta): if not hash in self: return move, score, hashf, ply = self[hash] if ply < depth: return if hashf == hashfEXACT: return move, score, hashf if hashf == hashfALPHA and score <= alpha: return move, alpha, hashf if hashf == hashfBETA and score >= beta: return move, beta, hashf def record (self, hash, move, score, hashf, ply): self[hash] = (move, score, hashf, ply) def add_killer (self, ply, move): if self.killer1[ply] == -1: self.killer1[ply] = move elif move != self.killer1[ply]: self.killer2[ply] = move def is_killer (self, ply, move): if self.killer1[ply] == move: return 10 elif self.killer2[ply] == move: return 8 if ply >= 2: if self.killer1[ply-2] == move: return 6 elif self.killer2[ply-2] == move: return 4 return 0 def set_hash_move (self, ply, move): self.hashmove[ply] = move def is_hash_move (self, ply, move): return self.hashmove[ply] == move
Python
import re import sys from rules import Rules from document import DocNode class Parser(object): """ Parse the raw text and create a document object that can be converted into output using Emitter. A separate instance should be created for parsing a new document. The first parameter is the raw text to be parsed. An optional second argument is the Rules object to use. You can customize the parsing rules to enable optional features or extend the parser. """ def __init__(self, raw, rules=None): self.rules = rules or Rules() self.raw = raw self.root = DocNode('document', None) self.cur = self.root # The most recent document node self.text = None # The node to add inline characters to def _upto(self, node, kinds): """ Look up the tree to the first occurence of one of the listed kinds of nodes or root. Start at the node node. """ while node.parent is not None and not node.kind in kinds: node = node.parent return node # The _*_repl methods called for matches in regexps. Sometimes the # same method needs several names, because of group names in regexps. def _url_repl(self, groups): """Handle raw urls in text.""" if not groups.get('escaped_url'): # this url is NOT escaped target = groups.get('url_target', '') node = DocNode('link', self.cur) node.content = target DocNode('text', node, node.content) self.text = None else: # this url is escaped, we render it as text if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('url_target') def _link_repl(self, groups): """Handle all kinds of links.""" target = groups.get('link_target', '') text = (groups.get('link_text', '') or '').strip() parent = self.cur self.cur = DocNode('link', self.cur) self.cur.content = target self.text = None self.parse_re(text, self.rules.link_re) self.cur = parent self.text = None def _wiki_repl(self, groups): """Handle WikiWord links, if enabled.""" text = groups.get('wiki', '') node = DocNode('link', self.cur) node.content = text DocNode('text', node, node.content) self.text = None def _macro_repl(self, groups): """Handles macros using the placeholder syntax.""" name = groups.get('macro_name', '') text = (groups.get('macro_text', '') or '').strip() node = DocNode('macro', self.cur, name) node.args = groups.get('macro_args', '') or '' DocNode('text', node, text or name) self.text = None def _image_repl(self, groups): """Handles images and attachemnts included in the page.""" target = groups.get('image_target', '').strip() text = (groups.get('image_text', '') or '').strip() node = DocNode("image", self.cur, target) DocNode('text', node, text or node.content) self.text = None def _separator_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) DocNode('separator', self.cur) def _item_repl(self, groups): bullet = groups.get('item_head', u'') text = groups.get('item_text', u'') if bullet[-1] == '#': kind = 'number_list' else: kind = 'bullet_list' level = len(bullet) lst = self.cur # Find a list of the same kind and level up the tree while (lst and not (lst.kind in ('number_list', 'bullet_list') and lst.level == level) and not lst.kind in ('document', 'section', 'blockquote')): lst = lst.parent if lst and lst.kind == kind: self.cur = lst else: # Create a new level of list self.cur = self._upto(self.cur, ('list_item', 'document', 'section', 'blockquote')) self.cur = DocNode(kind, self.cur) self.cur.level = level self.cur = DocNode('list_item', self.cur) self.parse_inline(text) self.text = None def _list_repl(self, groups): text = groups.get('list', u'') self.parse_re(text, self.rules.item_re) def _head_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) node = DocNode('header', self.cur, groups.get('head_text', '').strip()) node.level = len(groups.get('head_head', ' ')) def _text_repl(self, groups): text = groups.get('text', '') if self.cur.kind in ('table', 'table_row', 'bullet_list', 'number_list'): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) if self.cur.kind in ('document', 'section', 'blockquote'): self.cur = DocNode('paragraph', self.cur) else: text = u' ' + text self.parse_inline(text) if groups.get('break') and self.cur.kind in ('paragraph', 'emphasis', 'strong', 'code'): DocNode('break', self.cur, '') self.text = None _break_repl = _text_repl def _table_repl(self, groups): row = groups.get('table', '|').strip() self.cur = self._upto(self.cur, ( 'table', 'document', 'section', 'blockquote')) if self.cur.kind != 'table': self.cur = DocNode('table', self.cur) tb = self.cur tr = DocNode('table_row', tb) text = '' for m in self.rules.cell_re.finditer(row): cell = m.group('cell') if cell: self.cur = DocNode('table_cell', tr) self.text = None self.parse_inline(cell) else: cell = m.group('head') self.cur = DocNode('table_head', tr) self.text = DocNode('text', self.cur, u'') self.text.content = cell.strip('=') self.cur = tb self.text = None def _pre_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) kind = groups.get('pre_kind', None) text = groups.get('pre_text', u'') def remove_tilde(m): return m.group('indent') + m.group('rest') text = self.rules.pre_escape_re.sub(remove_tilde, text) node = DocNode('preformatted', self.cur, text) node.sect = kind or '' self.text = None def _line_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) def _code_repl(self, groups): DocNode('code', self.cur, groups.get('code_text', u'').strip()) self.text = None def _emph_repl(self, groups): if self.cur.kind != 'emphasis': self.cur = DocNode('emphasis', self.cur) else: self.cur = self._upto(self.cur, ('emphasis', )).parent self.text = None def _strong_repl(self, groups): if self.cur.kind != 'strong': self.cur = DocNode('strong', self.cur) else: self.cur = self._upto(self.cur, ('strong', )).parent self.text = None def _break_repl(self, groups): DocNode('break', self.cur, None) self.text = None def _escape_repl(self, groups): if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('escaped_char', u'') def _char_repl(self, groups): if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('char', u'') def parse_inline(self, raw): """Recognize inline elements inside blocks.""" self.parse_re(raw, self.rules.inline_re) def parse_re(self, raw, rules_re): """Parse a fragment according to the compiled rules.""" for match in rules_re.finditer(raw): groups = dict((k, v) for (k, v) in match.groupdict().iteritems() if v is not None) name = match.lastgroup function = getattr(self, '_%s_repl' % name) function(groups) def parse(self): """Parse the text given as self.raw and return DOM tree.""" self.parse_re(self.raw, self.rules.block_re) return self.root
Python
from Tkinter import * from ttk import Combobox, Label from tkFont import families from tkSimpleDialog import Dialog class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8,15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
Python
from Tkinter import PhotoImage from Tkconstants import * from globalconst import BULLET_IMAGE from creoleparser import Parser from rules import LinkRules class TextTagEmitter(object): """ Generate tagged output compatible with the Tkinter Text widget """ def __init__(self, root, txtWidget, hyperMgr, bulletImage, link_rules=None): self.root = root self.link_rules = link_rules or LinkRules() self.txtWidget = txtWidget self.hyperMgr = hyperMgr self.line = 1 self.index = 0 self.number = 1 self.bullet = False self.bullet_image = bulletImage self.begin_italic = '' self.begin_bold = '' self.begin_list_item = '' self.list_item = '' self.begin_link = '' # visit/leave methods for emitting nodes of the document: def visit_document(self, node): pass def leave_document(self, node): # leave_paragraph always leaves two extra carriage returns at the # end of the text. This deletes them. txtindex = '%d.%d' % (self.line-1, self.index) self.txtWidget.delete(txtindex, END) def visit_text(self, node): if self.begin_list_item: self.list_item = node.content elif self.begin_link: pass else: txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, node.content) def leave_text(self, node): if not self.begin_list_item: self.index += len(node.content) def visit_separator(self, node): raise NotImplementedError def leave_separator(self, node): raise NotImplementedError def visit_paragraph(self, node): pass def leave_paragraph(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n\n') self.line += 2 self.index = 0 self.number = 1 def visit_bullet_list(self, node): self.bullet = True def leave_bullet_list(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') self.line += 1 self.index = 0 self.bullet = False def visit_number_list(self, node): self.number = 1 def leave_number_list(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') self.line += 1 self.index = 0 def visit_list_item(self, node): self.begin_list_item = '%d.%d' % (self.line, self.index) def leave_list_item(self, node): if self.bullet: self.txtWidget.insert(self.begin_list_item, '\t') next = '%d.%d' % (self.line, self.index+1) self.txtWidget.image_create(next, image=self.bullet_image) next = '%d.%d' % (self.line, self.index+2) content = '\t%s\t\n' % self.list_item self.txtWidget.insert(next, content) end_list_item = '%d.%d' % (self.line, self.index + len(content)+2) self.txtWidget.tag_add('bullet', self.begin_list_item, end_list_item) elif self.number: content = '\t%d.\t%s\n' % (self.number, self.list_item) end_list_item = '%d.%d' % (self.line, self.index + len(content)) self.txtWidget.insert(self.begin_list_item, content) self.txtWidget.tag_add('number', self.begin_list_item, end_list_item) self.number += 1 self.begin_list_item = '' self.list_item = '' self.line += 1 self.index = 0 def visit_emphasis(self, node): self.begin_italic = '%d.%d' % (self.line, self.index) def leave_emphasis(self, node): end_italic = '%d.%d' % (self.line, self.index) self.txtWidget.tag_add('italic', self.begin_italic, end_italic) def visit_strong(self, node): self.begin_bold = '%d.%d' % (self.line, self.index) def leave_strong(self, node): end_bold = '%d.%d' % (self.line, self.index) self.txtWidget.tag_add('bold', self.begin_bold, end_bold) def visit_link(self, node): self.begin_link = '%d.%d' % (self.line, self.index) def leave_link(self, node): end_link = '%d.%d' % (self.line, self.index) # TODO: Revisit unicode encode/decode issues later. # 1. Decode early. 2. Unicode everywhere 3. Encode late # However, decoding filename and link_text here works for now. fname = str(node.content).replace('%20', ' ') link_text = str(node.children[0].content).replace('%20', ' ') self.txtWidget.insert(self.begin_link, link_text, self.hyperMgr.add(fname)) self.begin_link = '' def visit_break(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') def leave_break(self, node): self.line += 1 self.index = 0 def visit_default(self, node): """Fallback function for visiting unknown nodes.""" raise TypeError def leave_default(self, node): """Fallback function for leaving unknown nodes.""" raise TypeError def emit_children(self, node): """Emit all the children of a node.""" for child in node.children: self.emit_node(child) def emit_node(self, node): """Visit/depart a single node and its children.""" visit = getattr(self, 'visit_%s' % node.kind, self.visit_default) visit(node) self.emit_children(node) leave = getattr(self, 'leave_%s' % node.kind, self.leave_default) leave(node) def emit(self): """Emit the document represented by self.root DOM tree.""" return self.emit_node(self.root) class Serializer(object): def __init__(self, txtWidget, hyperMgr): self.txt = txtWidget self.hyperMgr = hyperMgr self.bullet_image = PhotoImage(file=BULLET_IMAGE) self._reset() def _reset(self): self.number = 0 self.bullet = False self.filename = '' self.link_start = False self.first_tab = True self.list_end = False def dump(self, index1='1.0', index2=END): # outputs contents from Text widget in Creole format. creole = '' self._reset() for key, value, index in self.txt.dump(index1, index2): if key == 'tagon': if value == 'bold': creole += '**' elif value == 'italic': creole += '//' elif value == 'bullet': creole += '*' self.bullet = True self.list_end = False elif value.startswith('hyper-'): self.filename = self.hyperMgr.filenames[value] self.link_start = True elif value == 'number': creole += '#' self.number += 1 elif key == 'tagoff': if value == 'bold': creole += '**' elif value == 'italic': creole += '//' elif value.startswith('hyper-'): creole += ']]' elif value == 'number': numstr = '#\t%d.\t' % self.number if numstr in creole: creole = creole.replace(numstr, '# ', 1) self.list_end = True elif value == 'bullet': creole = creole.replace('\n*\t\t', '\n* ', 1) self.bullet = False self.list_end = True elif key == 'text': if self.link_start: # TODO: Revisit unicode encode/decode issues later. # 1. Decode early. 2. Unicode everywhere 3. Encode late # However, encoding filename and link_text here works for # now. fname = self.filename.replace(' ', '%20').encode('utf-8') link_text = value.replace(' ', '%20') value = '[[%s|%s' % (fname, link_text) self.link_start = False numstr = '%d.\t' % self.number if self.list_end and value != '\n' and numstr not in value: creole += '\n' self.number = 0 self.list_end = False creole += value return creole.rstrip() def restore(self, creole): self.hyperMgr.reset() document = Parser(unicode(creole, 'utf-8', 'ignore')).parse() return TextTagEmitter(document, self.txt, self.hyperMgr, self.bullet_image).emit()
Python
import os from Tkinter import * from Tkconstants import W, E import Tkinter as tk from tkMessageBox import askyesnocancel from multiprocessing import freeze_support from globalconst import * from aboutbox import AboutBox from setupboard import SetupBoard from gamemanager import GameManager from centeredwindow import CenteredWindow from prefdlg import PreferencesDialog class MainFrame(object, CenteredWindow): def __init__(self, master): self.root = master self.root.withdraw() self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=5) self.manager = GameManager(root=self.root, parent=self) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify() def _on_close(self): if self.manager.view.is_dirty(): msg = 'Do you want to save your changes before exiting?' result = askyesnocancel(TITLE, msg) if result == True: self.manager.save_game() elif result == None: return self.root.destroy() def set_title_bar_filename(self, filename=None): if not filename: self.root.title(TITLE) else: self.root.title(TITLE + ' - ' + os.path.basename(filename)) def undo_all_moves(self, *args): self.stop_processes() self.manager.model.undo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_all_moves(self, *args): self.stop_processes() self.manager.model.redo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def undo_single_move(self, *args): self.stop_processes() self.manager.model.undo_move(None, None, True, True, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_single_move(self, *args): self.stop_processes() annotation = self.manager.view.get_annotation() self.manager.model.redo_move(None, None, annotation) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def create_game_menu(self): game = Menu(self.menubar, tearoff=0) game.add_command(label='New game', underline=0, command=self.manager.new_game) game.add_command(label='Open game ...', underline=0, command=self.manager.open_game) game.add_separator() game.add_command(label='Save game', underline=0, command=self.manager.save_game) game.add_command(label='Save game As ...', underline=10, command=self.manager.save_game_as) game.add_separator() game.add_command(label='Set up Board ...', underline=7, command=self.show_setup_board_dialog) game.add_command(label='Flip board', underline=0, command=self.flip_board) game.add_separator() game.add_command(label='Exit', underline=0, command=self._on_close) self.menubar.add_cascade(label='Game', menu=game) def create_options_menu(self): options = Menu(self.menubar, tearoff=0) think = Menu(options, tearoff=0) think.add_radiobutton(label="1 second", underline=None, command=self.set_think_time, variable=self.thinkTime, value=1) think.add_radiobutton(label="2 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=2) think.add_radiobutton(label="5 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=5) think.add_radiobutton(label="10 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=10) think.add_radiobutton(label="30 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=30) think.add_radiobutton(label="1 minute", underline=None, command=self.set_think_time, variable=self.thinkTime, value=60) options.add_cascade(label='CPU think time', underline=0, menu=think) options.add_separator() options.add_command(label='Preferences ...', underline=0, command=self.show_preferences_dialog) self.menubar.add_cascade(label='Options', menu=options) def create_help_menu(self): helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label='About Raven ...', underline=0, command=self.show_about_box) self.menubar.add_cascade(label='Help', menu=helpmenu) def stop_processes(self): # stop any controller processes from making moves self.manager.model.curr_state.ok_to_move = False self.manager._controller1.stop_process() self.manager._controller2.stop_process() def show_about_box(self): AboutBox(self.root, 'About Raven') def show_setup_board_dialog(self): self.stop_processes() dlg = SetupBoard(self.root, 'Set up board', self.manager) self.manager.set_controllers() self.root.focus_set() self.manager.turn_finished() def show_preferences_dialog(self): font, size = get_preferences_from_file() dlg = PreferencesDialog(self.root, 'Preferences', font, size) if dlg.result: self.manager.view.init_font_sizes(dlg.font, dlg.size) self.manager.view.init_tags() write_preferences_to_file(dlg.font, dlg.size) def set_think_time(self): self.manager._controller1.set_search_time(self.thinkTime.get()) self.manager._controller2.set_search_time(self.thinkTime.get()) def flip_board(self): if self.manager.model.to_move == BLACK: self.manager._controller1.remove_highlights() else: self.manager._controller2.remove_highlights() self.manager.view.flip_board(not self.manager.view.flip_view) if self.manager.model.to_move == BLACK: self.manager._controller1.add_highlights() else: self.manager._controller2.add_highlights() def start(): root = Tk() mainframe = MainFrame(root) mainframe.root.update() mainframe.root.mainloop() if __name__=='__main__': freeze_support() start()
Python
from globalconst import BLACK, WHITE, MAN, KING from goalevaluator import GoalEvaluator from onekingattack import Goal_OneKingAttack class OneKingAttackOneKingEvaluator(GoalEvaluator): def __init__(self, bias): GoalEvaluator.__init__(self, bias) def calculateDesirability(self, board): plr_color = board.to_move enemy_color = board.enemy # if we don't have one man on each side or the player # doesn't have the opposition, then goal is undesirable. if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or not board.has_opposition(plr_color)): return 0.0 player = board.get_pieces(plr_color)[0] p_idx, p_val = player p_row, p_col = board.row_col_for_index(p_idx) enemy = board.get_pieces(enemy_color)[0] e_idx, e_val = enemy e_row, e_col = board.row_col_for_index(e_idx) # must be two kings against each other and the distance # between them at least three rows away if ((p_val & KING) and (e_val & KING) and (abs(p_row - e_row) > 2 or abs(p_col - e_col) > 2)): return 1.0 return 0.0 def setGoal(self, board): player = board.to_move board.removeAllSubgoals() if player == WHITE: goalset = board.addWhiteSubgoal else: goalset = board.addBlackSubgoal goalset(Goal_OneKingAttack(board)) class OneKingFleeOneKingEvaluator(GoalEvaluator): def __init__(self, bias): GoalEvaluator.__init__(self, bias) def calculateDesirability(self, board): plr_color = board.to_move enemy_color = board.enemy # if we don't have one man on each side or the player # has the opposition (meaning we should attack instead), # then goal is not applicable. if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or board.has_opposition(plr_color)): return 0.0 player = board.get_pieces(plr_color)[0] p_idx, p_val = player enemy = board.get_pieces(enemy_color)[0] e_idx, e_val = enemy # must be two kings against each other; otherwise it's # not applicable. if not ((p_val & KING) and (e_val & KING)): return 0.0 return 1.0 def setGoal(self, board): player = board.to_move board.removeAllSubgoals() if player == WHITE: goalset = board.addWhiteSubgoal else: goalset = board.addBlackSubgoal goalset(Goal_OneKingFlee(board))
Python
from Tkinter import * class CenteredWindow: def __init__(self, root): self.root = root self.root.after_idle(self.center_on_screen) self.root.update() def center_on_screen(self): self.root.update_idletasks() sw = self.root.winfo_screenwidth() sh = self.root.winfo_screenheight() w = self.root.winfo_reqwidth() h = self.root.winfo_reqheight() new_geometry = "+%d+%d" % ((sw-w)/2, (sh-h)/2) self.root.geometry(newGeometry=new_geometry)
Python
import sys from goal import Goal from composite import CompositeGoal class Goal_OneKingFlee(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) def activate(self): self.status = self.ACTIVE self.removeAllSubgoals() # because goals are *pushed* onto the front of the subgoal list they must # be added in reverse order. self.addSubgoal(Goal_MoveTowardNearestDoubleCorner(self.owner)) self.addSubgoal(Goal_SeeSaw(self.owner)) def process(self): self.activateIfInactive() return self.processSubgoals() def terminate(self): self.status = self.INACTIVE class Goal_MoveTowardBestDoubleCorner(Goal): def __init__(self, owner): Goal.__init__(self, owner) self.dc = [8, 13, 27, 32] def activate(self): self.status = self.ACTIVE def process(self): # if status is inactive, activate self.activateIfInactive() # only moves (not captures) are a valid goal if self.owner.captures: self.status = self.FAILED return # identify player king and enemy king plr_color = self.owner.to_move enemy_color = self.owner.enemy player = self.owner.get_pieces(plr_color)[0] p_idx, _ = player p_row, p_col = self.owner.row_col_for_index(p_idx) enemy = self.owner.get_pieces(enemy_color)[0] e_idx, _ = enemy e_row, e_col = self.owner.row_col_for_index(e_idx) # pick DC that isn't blocked by enemy lowest_dist = sys.maxint dc = 0 for i in self.dc: dc_row, dc_col = self.owner.row_col_for_index(i) pdist = abs(dc_row - p_row) + abs(dc_col - p_col) edist = abs(dc_row - e_row) + abs(dc_col - e_col) if pdist < lowest_dist and edist > pdist: lowest_dist = pdist dc = i # if lowest distance is 0, then goal is complete. if lowest_dist == 0: self.status = self.COMPLETED return # select the available move that decreases the distance # between the original player position and the chosen double corner. # If no such move exists, the goal has failed. dc_row, dc_col = self.owner.row_col_for_index(dc) good_move = None for m in self.owner.moves: # try a move and gather the new row & col for the player self.owner.make_move(m, False, False) plr_update = self.owner.get_pieces(plr_color)[0] pu_idx, _ = plr_update pu_row, pu_col = self.owner.row_col_for_index(pu_idx) self.owner.undo_move(m, False, False) new_diff = abs(pu_row - dc_row) + abs(pu_col - dc_col) if new_diff < lowest_dist: good_move = m break if good_move: self.owner.make_move(good_move, True, True) else: self.status = self.FAILED def terminate(self): self.status = self.INACTIVE class Goal_SeeSaw(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # for now, I'm not even sure I need this goal, but I'm saving it # as a placeholder. self.status = self.COMPLETED def terminate(self): self.status = self.INACTIVE
Python
"""Provide some widely useful utilities. Safe for "from utils import *".""" from __future__ import generators import operator, math, random, copy, sys, os.path, bisect #______________________________________________________________________________ # Simple Data Structures: booleans, infinity, Dict, Struct infinity = 1.0e400 def Dict(**entries): """Create a dict out of the argument=value arguments. Ex: Dict(a=1, b=2, c=3) ==> {'a':1, 'b':2, 'c':3}""" return entries class DefaultDict(dict): """Dictionary with a default value for unknown keys. Ex: d = DefaultDict(0); d['x'] += 1; d['x'] ==> 1 d = DefaultDict([]); d['x'] += [1]; d['y'] += [2]; d['x'] ==> [1]""" def __init__(self, default): self.default = default def __getitem__(self, key): if key in self: return self.get(key) return self.setdefault(key, copy.deepcopy(self.default)) class Struct: """Create an instance with argument=value slots. This is for making a lightweight object whose class doesn't matter. Ex: s = Struct(a=1, b=2); s.a ==> 1; s.a = 3; s ==> Struct(a=3, b=2)""" def __init__(self, **entries): self.__dict__.update(entries) def __cmp__(self, other): if isinstance(other, Struct): return cmp(self.__dict__, other.__dict__) else: return cmp(self.__dict__, other) def __repr__(self): args = ['%s=%s' % (k, repr(v)) for (k, v) in vars(self).items()] return 'Struct(%s)' % ', '.join(args) def update(x, **entries): """Update a dict, or an object with slots, according to entries. Ex: update({'a': 1}, a=10, b=20) ==> {'a': 10, 'b': 20} update(Struct(a=1), a=10, b=20) ==> Struct(a=10, b=20)""" if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x #______________________________________________________________________________ # Functions on Sequences (mostly inspired by Common Lisp) # NOTE: Sequence functions (count_if, find_if, every, some) take function # argument first (like reduce, filter, and map). def sort(seq, compare=cmp): """Sort seq (mutating it) and return it. compare is the 2nd arg to .sort. Ex: sort([3, 1, 2]) ==> [1, 2, 3]; reverse(sort([3, 1, 2])) ==> [3, 2, 1] sort([-3, 1, 2], comparer(abs)) ==> [1, 2, -3]""" if isinstance(seq, str): seq = ''.join(sort(list(seq), compare)) elif compare == cmp: seq.sort() else: seq.sort(compare) return seq def comparer(key=None, cmp=cmp): """Build a compare function suitable for sort. The most common use is to specify key, meaning compare the values of key(x), key(y).""" if key == None: return cmp else: return lambda x,y: cmp(key(x), key(y)) def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. Ex: removeall(3, [1, 2, 3, 3, 2, 1, 3]) ==> [1, 2, 2, 1] removeall(4, [1, 2, 3]) ==> [1, 2, 3]""" if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item] def reverse(seq): """Return the reverse of a string or list or tuple. Mutates the seq. Ex: reverse([1, 2, 3]) ==> [3, 2, 1]; reverse('abc') ==> 'cba'""" if isinstance(seq, str): return ''.join(reverse(list(seq))) elif isinstance(seq, tuple): return tuple(reverse(list(seq))) else: seq.reverse(); return seq def unique(seq): """Remove duplicate elements from seq. Assumes hashable elements. Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary""" return list(set(seq)) def count_if(predicate, seq): """Count the number of elements of seq for which the predicate is true. count_if(callable, [42, None, max, min]) ==> 2""" f = lambda count, x: count + (not not predicate(x)) return reduce(f, seq, 0) def find_if(predicate, seq): """If there is an element of seq that satisfies predicate, return it. Ex: find_if(callable, [3, min, max]) ==> min find_if(callable, [1, 2, 3]) ==> None""" for x in seq: if predicate(x): return x return None def every(predicate, seq): """True if every element of seq satisfies predicate. Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3]) ==> 0""" for x in seq: if not predicate(x): return False return True def some(predicate, seq): """If some element x of seq satisfies predicate(x), return predicate(x). Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0""" for x in seq: px = predicate(x) if px: return px return False # Added by Brandon def flatten(x): if type(x) != type([]): return [x] if x == []: return x return flatten(x[0]) + flatten(x[1:]) #______________________________________________________________________________ # Functions on sequences of numbers # NOTE: these take the sequence argument first, like min and max, # and like standard math notation: \sigma (i = 1..n) fn(i) # A lot of programing is finding the best value that satisfies some condition; # so there are three versions of argmin/argmax, depending on what you want to # do with ties: return the first one, return them all, or pick at random. def sum(seq, fn=None): """Sum the elements seq[i], or fn(seq[i]) if fn is given. Ex: sum([1, 2, 3]) ==> 6; sum(range(8), lambda x: 2**x) ==> 255""" if fn: seq = map(fn, seq) return reduce(operator.add, seq, 0) def product(seq, fn=None): """Multiply the elements seq[i], or fn(seq[i]) if fn is given. product([1, 2, 3]) ==> 6; product([1, 2, 3], lambda x: x*x) ==> 1*4*9""" if fn: seq = map(fn, seq) return reduce(operator.mul, seq, 1) def argmin(gen, fn): """Return an element with lowest fn(x) score; tie goes to first one. Gen must be a generator. Ex: argmin(['one', 'to', 'three'], len) ==> 'to'""" best = gen.next(); best_score = fn(best) for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score return best def argmin_list(gen, fn): """Return a list of elements of gen with the lowest fn(x) scores. Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']""" best_score, best = fn(gen.next()), [] for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = [x], x_score elif x_score == best_score: best.append(x) return best #def argmin_list(seq, fn): # """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. # Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']""" # best_score, best = fn(seq[0]), [] # for x in seq: # x_score = fn(x) # if x_score < best_score: # best, best_score = [x], x_score # elif x_score == best_score: # best.append(x) # return best def argmin_random_tie(gen, fn): """Return an element with lowest fn(x) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" try: best = gen.next(); best_score = fn(best); n = 0 except StopIteration: return [] for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score; n = 1 elif x_score == best_score: n += 1 if random.randrange(n) == 0: best = x return best #def argmin_random_tie(seq, fn): # """Return an element with lowest fn(seq[i]) score; break ties at random. # Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" # best_score = fn(seq[0]); n = 0 # for x in seq: # x_score = fn(x) # if x_score < best_score: # best, best_score = x, x_score; n = 1 # elif x_score == best_score: # n += 1 # if random.randrange(n) == 0: # best = x # return best def argmax(gen, fn): """Return an element with highest fn(x) score; tie goes to first one. Ex: argmax(['one', 'to', 'three'], len) ==> 'three'""" return argmin(gen, lambda x: -fn(x)) def argmax_list(seq, fn): """Return a list of elements of gen with the highest fn(x) scores. Ex: argmax_list(['one', 'three', 'seven'], len) ==> ['three', 'seven']""" return argmin_list(seq, lambda x: -fn(x)) def argmax_random_tie(seq, fn): "Return an element with highest fn(x) score; break ties at random." return argmin_random_tie(seq, lambda x: -fn(x)) #______________________________________________________________________________ # Statistical and mathematical functions def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first. Ex: vals = [100, 110, 160, 200, 160, 110, 200, 200, 220] histogram(vals) ==> [(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)] histogram(vals, 1) ==> [(200, 3), (160, 2), (110, 2), (100, 1), (220, 1)] histogram(vals, 1, lambda v: round(v, -2)) ==> [(200.0, 6), (100.0, 3)]""" if bin_function: values = map(bin_function, values) bins = {} for val in values: bins[val] = bins.get(val, 0) + 1 if mode: return sort(bins.items(), lambda x,y: cmp(y[1],x[1])) else: return sort(bins.items()) def log2(x): """Base 2 logarithm. Ex: log2(1024) ==> 10.0; log2(1.0) ==> 0.0; log2(0) raises OverflowError""" return math.log10(x) / math.log10(2) def mode(values): """Return the most common value in the list of values. Ex: mode([1, 2, 3, 2]) ==> 2""" return histogram(values, mode=1)[0][0] def median(values): """Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. Ex: median([10, 100, 11]) ==> 11; median([1, 2, 3, 4]) ==> 2.5""" n = len(values) values = sort(values[:]) if n % 2 == 1: return values[n/2] else: middle2 = values[(n/2)-1:(n/2)+1] try: return mean(middle2) except TypeError: return random.choice(middle2) def mean(values): """Return the arithmetic average of the values.""" return sum(values) / float(len(values)) def stddev(values, meanval=None): """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt(sum([(x - meanval)**2 for x in values])) def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. Ex: dotproduct([1, 2, 3], [1000, 100, 10]) ==> 1230""" return sum([x * y for x, y in zip(X, Y)]) def vector_add(a, b): """Component-wise addition of two vectors. Ex: vector_add((0, 1), (8, 9)) ==> (8, 10)""" return tuple(map(operator.add, a, b)) def probability(p): "Return true with probability p." return p > random.uniform(0.0, 1.0) def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """ try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip() def distance((ax, ay), (bx, by)): "The distance between two (x, y) points." return math.hypot((ax - bx), (ay - by)) def distance2((ax, ay), (bx, by)): "The square of the distance between two (x, y) points." return (ax - bx)**2 + (ay - by)**2 def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). Ex: normalize([1,2,1]) ==> [0.25, 0.5, 0.25]""" k = total / sum(numbers) return [k * n for n in numbers] #______________________________________________________________________________ # Misc Functions def printf(format, *args): """Format args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.""" sys.stdout.write(str(format) % args) return if_(args, args[-1], format) def print_(*args): """Print the args and return the last one.""" for arg in args: print arg, print return if_(args, args[-1], None) def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary. Ex: def fib(n): return (n<=1 and 1) or (fib(n-1) + fib(n-2)); fib(9) ==> 55 # Now we make it faster: fib = memoize(fib); fib(9) ==> 55""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn def method(name, *args): """Return a function that invokes the named method with the optional args. Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE'] map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]""" return lambda x: getattr(x, name)(*args) def method2(name, *static_args): """Return a function that invokes the named method with the optional args. Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE'] map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]""" return lambda x, *dyn_args: getattr(x, name)(*(dyn_args + static_args)) def abstract(): """Indicate abstract methods that should be implemented in a subclass. Ex: def m(): abstract() # Similar to Java's 'abstract void m()'""" raise NotImplementedError(caller() + ' must be implemented in subclass') def caller(n=1): """Return the name of the calling function n levels up in the frame stack. Ex: caller(0) ==> 'caller'; def f(): return caller(); f() ==> 'f'""" import inspect return inspect.getouterframes(inspect.currentframe())[n][3] def indexed(seq): """Like [(i, seq[i]) for i in range(len(seq))], but with yield. Ex: for i, c in indexed('abc'): print i, c""" i = 0 for x in seq: yield i, x i += 1 def if_(test, result, alternative): """Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. Ex: if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) ==> 'ok' """ if test: if callable(result): return result() return result else: if callable(alternative): return alternative() return alternative def name(object): "Try to find some reasonable name for the object." return (getattr(object, 'name', 0) or getattr(object, '__name__', 0) or getattr(getattr(object, '__class__', 0), '__name__', 0) or str(object)) def isnumber(x): "Is x a number? We say it is if it has a __int__ method." return hasattr(x, '__int__') def issequence(x): "Is x a sequence? We say it is if it has a __getitem__ method." return hasattr(x, '__getitem__') def print_table(table, header=None, sep=' ', numfmt='%g'): """Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in differnt columns, don't use print_table.) sep is the separator between columns.""" justs = [if_(isnumber(x), 'rjust', 'ljust') for x in table[0]] if header: table = [header] + table table = [[if_(isnumber(x), lambda: numfmt % x, x) for x in row] for row in table] maxlen = lambda seq: max(map(len, seq)) sizes = map(maxlen, zip(*[map(str, row) for row in table])) for row in table: for (j, size, x) in zip(justs, sizes, row): print getattr(str(x), j)(size), sep, print def AIMAFile(components, mode='r'): "Open a file based at the AIMA root directory." dir = os.path.dirname(__file__) return open(apply(os.path.join, [dir] + components), mode) def DataFile(name, mode='r'): "Return a file in the AIMA /data directory." return AIMAFile(['data', name], mode) #______________________________________________________________________________ # Queues: Stack, FIFOQueue, PriorityQueue class Queue: """Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.""" def __init__(self): abstract() def extend(self, items): for item in items: self.append(item) def Stack(): """Return an empty list, suitable as a Last-In-First-Out Queue. Ex: q = Stack(); q.append(1); q.append(2); q.pop(), q.pop() ==> (2, 1)""" return [] class FIFOQueue(Queue): """A First-In-First-Out Queue. Ex: q = FIFOQueue();q.append(1);q.append(2); q.pop(), q.pop() ==> (1, 2)""" def __init__(self): self.A = []; self.start = 0 def append(self, item): self.A.append(item) def __len__(self): return len(self.A) - self.start def extend(self, items): self.A.extend(items) def pop(self): e = self.A[self.start] self.start += 1 if self.start > 5 and self.start > len(self.A)/2: self.A = self.A[self.start:] self.start = 0 return e class PriorityQueue(Queue): """A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x).""" def __init__(self, order=min, f=lambda x: x): update(self, A=[], order=order, f=f) def append(self, item): bisect.insort(self.A, (self.f(item), item)) def __len__(self): return len(self.A) def pop(self): if self.order == min: return self.A.pop(0)[1] else: return self.A.pop()[1] #______________________________________________________________________________ ## NOTE: Once we upgrade to Python 2.3, the following class can be replaced by ## from sets import set class set: """This implements the set class from PEP 218, except it does not overload the infix operators. Ex: s = set([1,2,3]); 1 in s ==> True; 4 in s ==> False s.add(4); 4 in s ==> True; len(s) ==> 4 s.discard(999); s.remove(4); 4 in s ==> False s2 = set([3,4,5]); s.union(s2) ==> set([1,2,3,4,5]) s.intersection(s2) ==> set([3]) set([1,2,3]) == set([3,2,1]); repr(s) == '{1, 2, 3}' for e in s: pass""" def __init__(self, elements): self.dict = {} for e in elements: self.dict[e] = 1 def __contains__(self, element): return element in self.dict def add(self, element): self.dict[element] = 1 def remove(self, element): del self.dict[element] def discard(self, element): if element in self.dict: del self.dict[element] def clear(self): self.dict.clear() def union(self, other): return set(self).union_update(other) def intersection(self, other): return set(self).intersection_update(other) def union_update(self, other): for e in other: self.add(e) def intersection_update(self, other): for e in self.dict.keys(): if e not in other: self.remove(e) def __iter__(self): for e in self.dict: yield e def __len__(self): return len(self.dict) def __cmp__(self, other): return (self is other or (isinstance(other, set) and self.dict == other.dict)) def __repr__(self): return "{%s}" % ", ".join([str(e) for e in self.dict.keys()]) #______________________________________________________________________________ # Additional tests _docex = """ def is_even(x): return x % 2 == 0 sort([1, 2, -3]) ==> [-3, 1, 2] sort(range(10), comparer(key=is_even)) ==> [1, 3, 5, 7, 9, 0, 2, 4, 6, 8] sort(range(10), lambda x,y: y-x) ==> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] removeall(4, []) ==> [] removeall('s', 'This is a test. Was a test.') ==> 'Thi i a tet. Wa a tet.' removeall('s', 'Something') ==> 'Something' removeall('s', '') ==> '' reverse([]) ==> [] reverse('') ==> '' count_if(is_even, [1, 2, 3, 4]) ==> 2 count_if(is_even, []) ==> 0 sum([]) ==> 0 product([]) ==> 1 argmax([1], lambda x: x*x) ==> 1 argmin([1], lambda x: x*x) ==> 1 argmax([]) raises TypeError argmin([]) raises TypeError # Test of memoize with slots in structures countries = [Struct(name='united states'), Struct(name='canada')] # Pretend that 'gnp' was some big hairy operation: def gnp(country): return len(country.name) * 1e10 gnp = memoize(gnp, '_gnp') map(gnp, countries) ==> [13e10, 6e10] countries # note the _gnp slot. # This time we avoid re-doing the calculation map(gnp, countries) ==> [13e10, 6e10] # Test Queues: nums = [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0] def qtest(q): return [q.extend(nums), [q.pop() for i in range(len(q))]][1] qtest(Stack()) ==> reverse(nums) qtest(FIFOQueue()) ==> nums qtest(PriorityQueue(min)) ==> [-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99] qtest(PriorityQueue(max)) ==> [99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99] qtest(PriorityQueue(min, abs)) ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, -99, 99] qtest(PriorityQueue(max, abs)) ==> [99, -99, 8, 7, 6, 5, 4, 3, 2, 1, 0] """
Python
import games import time from move import Move from globalconst import BLACK, WHITE, KING, MAN, OCCUPIED, BLACK_CHAR, WHITE_CHAR from globalconst import BLACK_KING, WHITE_KING, FREE, OCCUPIED_CHAR, FREE_CHAR from globalconst import COLORS, TYPES, TURN, CRAMP, BRV, KEV, KCV, MEV, MCV from globalconst import INTACTDOUBLECORNER, ENDGAME, OPENING, MIDGAME from globalconst import create_grid_map, KING_IDX, BLACK_IDX, WHITE_IDX import copy class Checkerboard(object): # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) valid_squares = [6,7,8,9,12,13,14,15,17,18,19,20,23,24,25,26, 28,29,30,31,34,35,36,37,39,40,41,42,45,46, 47,48] # values of pieces (KING, MAN, BLACK, WHITE, FREE) value = [0,0,0,0,0,1,256,0,0,16,4096,0,0,0,0,0,0] edge = [6,7,8,9,15,17,26,28,37,39,45,46,47,48] center = [18,19,24,25,29,30,35,36] # values used to calculate tempo -- one for each square on board (0, 48) row = [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,2,2,2,2,0,0,3,3,3,3,0, 4,4,4,4,0,0,5,5,5,5,0,6,6,6,6,0,0,7,7,7,7] safeedge = [9,15,39,45] rank = {0:0, 1:-1, 2:1, 3:0, 4:1, 5:1, 6:2, 7:1, 8:1, 9:0, 10:7, 11:4, 12:2, 13:2, 14:9, 15:8} def __init__(self): self.squares = [OCCUPIED for i in range(56)] s = self.squares for i in range(0, 4): s[6+i] = s[12+i] = s[17+i] = BLACK | MAN s[34+i] = s[39+i] = s[45+i] = WHITE | MAN s[23+i] = s[28+i] = FREE self.to_move = BLACK self.charlookup = {BLACK | MAN: BLACK_CHAR, WHITE | MAN: WHITE_CHAR, BLACK | KING: BLACK_KING, WHITE | KING: WHITE_KING, OCCUPIED: OCCUPIED_CHAR, FREE: FREE_CHAR} self.observers = [] self.white_pieces = [] self.black_pieces = [] self.undo_list = [] self.redo_list = [] self.white_total = 12 self.black_total = 12 self.gridmap = create_grid_map() self.ok_to_move = True def __repr__(self): bc = self.count(BLACK) wc = self.count(WHITE) sq = self.squares lookup = self.lookup s = "[%s=%2d %s=%2d (%+d)]\n" % (BLACK_CHAR, bc, WHITE_CHAR, wc, bc - wc) s += "8 %s %s %s %s\n" % (lookup(sq[45]), lookup(sq[46]), lookup(sq[47]), lookup(sq[48])) s += "7 %s %s %s %s\n" % (lookup(sq[39]), lookup(sq[40]), lookup(sq[41]), lookup(sq[42])) s += "6 %s %s %s %s\n" % (lookup(sq[34]), lookup(sq[35]), lookup(sq[36]), lookup(sq[37])) s += "5 %s %s %s %s\n" % (lookup(sq[28]), lookup(sq[29]), lookup(sq[30]), lookup(sq[31])) s += "4 %s %s %s %s\n" % (lookup(sq[23]), lookup(sq[24]), lookup(sq[25]), lookup(sq[26])) s += "3 %s %s %s %s\n" % (lookup(sq[17]), lookup(sq[18]), lookup(sq[19]), lookup(sq[20])) s += "2 %s %s %s %s\n" % (lookup(sq[12]), lookup(sq[13]), lookup(sq[14]), lookup(sq[15])) s += "1 %s %s %s %s\n" % (lookup(sq[6]), lookup(sq[7]), lookup(sq[8]), lookup(sq[9])) s += " a b c d e f g h" return s def _get_enemy(self): if self.to_move == BLACK: return WHITE return BLACK enemy = property(_get_enemy, doc="The color for the player that doesn't have the current turn") def attach(self, observer): if observer not in self.observers: self.observers.append(observer) def detach(self, observer): if observer in self.observers: self.observers.remove(observer) def clear(self): s = self.squares for i in range(0, 4): s[6+i] = s[12+i] = s[17+i] = FREE s[23+i] = s[28+i] = FREE s[34+i] = s[39+i] = s[45+i] = FREE def lookup(self, square): return self.charlookup[square & TYPES] def count(self, color): return self.white_total if color == WHITE else self.black_total def get_pieces(self, color): return self.black_pieces if color == BLACK else self.white_pieces def has_opposition(self, color): sq = self.squares cols = range(6,10) if self.to_move == BLACK else range(12,16) pieces_in_system = 0 for i in cols: for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 return pieces_in_system % 2 == 1 def row_col_for_index(self, idx): return self.gridmap[idx] def update_piece_count(self): self.white_pieces = [] for i, piece in enumerate(self.squares): if piece & COLORS == WHITE: self.white_pieces.append((i, piece)) self.black_pieces = [] for i, piece in enumerate(self.squares): if piece & COLORS == BLACK: self.black_pieces.append((i, piece)) self.white_total = len(self.white_pieces) self.black_total = len(self.black_pieces) def delete_redo_list(self): del self.redo_list[:] def make_move(self, move, notify=True, undo=True, annotation=''): sq = self.squares for idx, _, newval in move.affected_squares: sq[idx] = newval self.to_move ^= COLORS if notify: self.update_piece_count() for o in self.observers: o.notify(move) if undo: move.annotation = annotation self.undo_list.append(move) return self def undo_move(self, move=None, notify=True, redo=True, annotation=''): if move is None: if not self.undo_list: return if redo: move = self.undo_list.pop() rev_move = Move([[idx, dest, src] for idx, src, dest in move.affected_squares]) rev_move.annotation = move.annotation self.make_move(rev_move, notify, False) if redo: move.annotation = annotation self.redo_list.append(move) def undo_all_moves(self, annotation=''): while self.undo_list: move = self.undo_list.pop() rev_move = Move([[idx, dest, src] for idx, src, dest in move.affected_squares]) rev_move.annotation = move.annotation self.make_move(rev_move, True, False) move.annotation = annotation self.redo_list.append(move) annotation = rev_move.annotation def redo_move(self, move=None, annotation=''): if move is None: if not self.redo_list: return move = self.redo_list.pop() self.make_move(move, True, True, annotation) def redo_all_moves(self, annotation=''): while self.redo_list: move = self.redo_list.pop() next_annotation = move.annotation self.make_move(move, True, True, annotation) annotation = next_annotation def reset_undo(self): self.undo_list = [] self.redo_list = [] def utility(self, player): """ Player evaluation function """ sq = self.squares code = sum(self.value[s] for s in sq) nwm = code % 16 nwk = (code >> 4) % 16 nbm = (code >> 8) % 16 nbk = (code >> 12) % 16 v1 = 100 * nbm + 130 * nbk v2 = 100 * nwm + 130 * nwk eval = v1 - v2 # material values # favor exchanges if in material plus eval += (250 * (v1 - v2))/(v1 + v2) nm = nbm + nwm nk = nbk + nwk # fine evaluation below if player == BLACK: eval += TURN mult = -1 else: eval -= TURN mult = 1 return mult * \ (eval + self._eval_cramp(sq) + self._eval_backrankguard(sq) + self._eval_doublecorner(sq) + self._eval_center(sq) + self._eval_edge(sq) + self._eval_tempo(sq, nm, nbk, nbm, nwk, nwm) + self._eval_playeropposition(sq, nwm, nwk, nbk, nbm, nm, nk)) def _extend_capture(self, valid_moves, captures, add_sq_func, visited): player = self.to_move enemy = self.enemy squares = self.squares final_captures = [] while captures: c = captures.pop() new_captures = [] for j in valid_moves: capture = c.affected_squares[:] last_pos = capture[-1][0] mid = last_pos+j dest = last_pos+j*2 if ((last_pos, mid, dest) not in visited and (dest, mid, last_pos) not in visited and squares[mid] & enemy and squares[dest] & FREE): sq2, sq3 = add_sq_func(player, squares, mid, dest, last_pos) capture[-1][2] = FREE capture.extend([sq2, sq3]) visited.add((last_pos, mid, dest)) new_captures.append(Move(capture)) if new_captures: captures.extend(new_captures) else: final_captures.append(Move(capture)) return final_captures def _capture_man(self, player, squares, mid, dest, last_pos): sq2 = [mid, squares[mid], FREE] if ((player == BLACK and last_pos>=34) or (player == WHITE and last_pos<=20)): sq3 = [dest, FREE, player | KING] else: sq3 = [dest, FREE, player | MAN] return sq2, sq3 def _capture_king(self, player, squares, mid, dest, last_pos): sq2 = [mid, squares[mid], FREE] sq3 = [dest, squares[dest], player | KING] return sq2, sq3 def _get_captures(self): player = self.to_move enemy = self.enemy squares = self.squares valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX all_captures = [] for i in self.valid_squares: if squares[i] & player and squares[i] & MAN: for j in valid_indices: mid = i+j dest = i+j*2 if squares[mid] & enemy and squares[dest] & FREE: sq1 = [i, player | MAN, FREE] sq2 = [mid, squares[mid], FREE] if ((player == BLACK and i>=34) or (player == WHITE and i<=20)): sq3 = [dest, FREE, player | KING] else: sq3 = [dest, FREE, player | MAN] capture = [Move([sq1, sq2, sq3])] visited = set() visited.add((i, mid, dest)) temp = squares[i] squares[i] = FREE captures = self._extend_capture(valid_indices, capture, self._capture_man, visited) squares[i] = temp all_captures.extend(captures) if squares[i] & player and squares[i] & KING: for j in KING_IDX: mid = i+j dest = i+j*2 if squares[mid] & enemy and squares[dest] & FREE: sq1 = [i, player | KING, FREE] sq2 = [mid, squares[mid], FREE] sq3 = [dest, squares[dest], player | KING] capture = [Move([sq1, sq2, sq3])] visited = set() visited.add((i, mid, dest)) temp = squares[i] squares[i] = FREE captures = self._extend_capture(KING_IDX, capture, self._capture_king, visited) squares[i] = temp all_captures.extend(captures) return all_captures captures = property(_get_captures, doc="Forced captures for the current player") def _get_moves(self): player = self.to_move squares = self.squares valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX moves = [] for i in self.valid_squares: for j in valid_indices: dest = i+j if (squares[i] & player and squares[i] & MAN and squares[dest] & FREE): sq1 = [i, player | MAN, FREE] if ((player == BLACK and i>=39) or (player == WHITE and i<=15)): sq2 = [dest, FREE, player | KING] else: sq2 = [dest, FREE, player | MAN] moves.append(Move([sq1, sq2])) for j in KING_IDX: dest = i+j if (squares[i] & player and squares[i] & KING and squares[dest] & FREE): sq1 = [i, player | KING, FREE] sq2 = [dest, FREE, player | KING] moves.append(Move([sq1, sq2])) return moves moves = property(_get_moves, doc="Available moves for the current player") def _eval_cramp(self, sq): eval = 0 if sq[28] == BLACK | MAN and sq[34] == WHITE | MAN: eval += CRAMP if sq[26] == WHITE | MAN and sq[20] == BLACK | MAN: eval -= CRAMP return eval def _eval_backrankguard(self, sq): eval = 0 code = 0 if sq[6] & MAN: code += 1 if sq[7] & MAN: code += 2 if sq[8] & MAN: code += 4 if sq[9] & MAN: code += 8 backrank = self.rank[code] code = 0 if sq[45] & MAN: code += 8 if sq[46] & MAN: code += 4 if sq[47] & MAN: code += 2 if sq[48] & MAN: code += 1 backrank = backrank - self.rank[code] eval *= BRV * backrank return eval def _eval_doublecorner(self, sq): eval = 0 if sq[9] == BLACK | MAN: if sq[14] == BLACK | MAN or sq[15] == BLACK | MAN: eval += INTACTDOUBLECORNER if sq[45] == WHITE | MAN: if sq[39] == WHITE | MAN or sq[40] == WHITE | MAN: eval -= INTACTDOUBLECORNER return eval def _eval_center(self, sq): eval = 0 nbmc = nbkc = nwmc = nwkc = 0 for c in self.center: if sq[c] != FREE: if sq[c] == BLACK | MAN: nbmc += 1 if sq[c] == BLACK | KING: nbkc += 1 if sq[c] == WHITE | MAN: nwmc += 1 if sq[c] == WHITE | KING: nwkc += 1 eval += (nbmc-nwmc) * MCV eval += (nbkc-nwkc) * KCV return eval def _eval_edge(self, sq): eval = 0 nbme = nbke = nwme = nwke = 0 for e in self.edge: if sq[e] != FREE: if sq[e] == BLACK | MAN: nbme += 1 if sq[e] == BLACK | KING: nbke += 1 if sq[e] == WHITE | MAN: nwme += 1 if sq[e] == WHITE | KING: nwke += 1 eval -= (nbme-nwme) * MEV eval -= (nbke-nwke) * KEV return eval def _eval_tempo(self, sq, nm, nbk, nbm, nwk, nwm): eval = tempo = 0 for i in range(6, 49): if sq[i] == BLACK | MAN: tempo += self.row[i] if sq[i] == WHITE | MAN: tempo -= 7 - self.row[i] if nm >= 16: eval += OPENING * tempo if nm <= 15 and nm >= 12: eval += MIDGAME * tempo if nm < 9: eval += ENDGAME * tempo for s in self.safeedge: if nbk + nbm > nwk + nwm and nwk < 3: if sq[s] == WHITE | KING: eval -= 15 if nwk + nwm > nbk + nbm and nbk < 3: if sq[s] == BLACK | KING: eval += 15 return eval def _eval_playeropposition(self, sq, nwm, nwk, nbk, nbm, nm, nk): eval = 0 pieces_in_system = 0 tn = nm + nk if nwm + nwk - nbk - nbm == 0: if self.to_move == BLACK: for i in range(6, 10): for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 if pieces_in_system % 2: if tn <= 12: eval += 1 if tn <= 10: eval += 1 if tn <= 8: eval += 2 if tn <= 6: eval += 2 else: if tn <= 12: eval -= 1 if tn <= 10: eval -= 1 if tn <= 8: eval -= 2 if tn <= 6: eval -= 2 else: for i in range(12, 16): for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 if pieces_in_system % 2 == 0: if tn <= 12: eval += 1 if tn <= 10: eval += 1 if tn <= 8: eval += 2 if tn <= 6: eval += 2 else: if tn <= 12: eval -= 1 if tn <= 10: eval -= 1 if tn <= 8: eval -= 2 if tn <= 6: eval -= 2 return eval class Checkers(games.Game): def __init__(self): self.curr_state = Checkerboard() def captures_available(self, curr_state=None): state = curr_state or self.curr_state return state.captures def legal_moves(self, curr_state=None): state = curr_state or self.curr_state return state.captures or state.moves def make_move(self, move, curr_state=None, notify=True, undo=True, annotation=''): state = curr_state or self.curr_state return state.make_move(move, notify, undo, annotation) def undo_move(self, move=None, curr_state=None, notify=True, redo=True, annotation=''): state = curr_state or self.curr_state return state.undo_move(move, notify, redo, annotation) def undo_all_moves(self, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.undo_all_moves(annotation) def redo_move(self, move=None, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.redo_move(move, annotation) def redo_all_moves(self, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.redo_all_moves(annotation) def utility(self, player, curr_state=None): state = curr_state or self.curr_state return state.utility(player) def terminal_test(self, curr_state=None): state = curr_state or self.curr_state return not self.legal_moves(state) def successors(self, curr_state=None): state = curr_state or self.curr_state moves = self.legal_moves(state) if not moves: yield [], state else: undone = False try: try: for move in moves: undone = False self.make_move(move, state, False) yield move, state self.undo_move(move, state, False) undone = True except GeneratorExit: raise finally: if moves and not undone: self.undo_move(move, state, False) def perft(self, depth, curr_state=None): if depth == 0: return 1 state = curr_state or self.curr_state nodes = 0 for move in self.legal_moves(state): state.make_move(move, False, False) nodes += self.perft(depth-1, state) state.undo_move(move, False, False) return nodes def play(): game = Checkers() for depth in range(1, 11): start = time.time() print "Perft for depth %d: %d. Time: %5.3f sec" % (depth, game.perft(depth), time.time() - start) if __name__ == '__main__': play()
Python
from Tkinter import * from Tkconstants import W, E, N, S from tkFileDialog import askopenfilename, asksaveasfilename from tkMessageBox import askyesnocancel, showerror from globalconst import * from checkers import Checkers from boardview import BoardView from playercontroller import PlayerController from alphabetacontroller import AlphaBetaController from gamepersist import SavedGame from textserialize import Serializer class GameManager(object): def __init__(self, **props): self.model = Checkers() self._root = props['root'] self.parent = props['parent'] statusbar = Label(self._root, relief=SUNKEN, font=('Helvetica',7), anchor=NW) statusbar.pack(side='bottom', fill='x') self.view = BoardView(self._root, model=self.model, parent=self, statusbar=statusbar) self.player_color = BLACK self.num_players = 1 self.set_controllers() self._controller1.start_turn() self.filename = None def set_controllers(self): think_time = self.parent.thinkTime.get() if self.num_players == 0: self._controller1 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) self._controller2 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) elif self.num_players == 1: # assumption here is that Black is the player self._controller1 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller2 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) # swap controllers if White is selected as the player if self.player_color == WHITE: self._controller1, self._controller2 = self._controller2, self._controller1 elif self.num_players == 2: self._controller1 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller2 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller1.set_before_turn_event(self._controller2.remove_highlights) self._controller2.set_before_turn_event(self._controller1.remove_highlights) def _stop_updates(self): # stop alphabeta threads from making any moves self.model.curr_state.ok_to_move = False self._controller1.stop_process() self._controller2.stop_process() def _save_curr_game_if_needed(self): if self.view.is_dirty(): msg = 'Do you want to save your changes' if self.filename: msg += ' to %s?' % self.filename else: msg += '?' result = askyesnocancel(TITLE, msg) if result == True: self.save_game() return result else: return False def new_game(self): self._stop_updates() self._save_curr_game_if_needed() self.filename = None self._root.title('Raven ' + VERSION) self.model = Checkers() self.player_color = BLACK self.view.reset_view(self.model) self.think_time = self.parent.thinkTime.get() self.set_controllers() self.view.update_statusbar() self.view.reset_toolbar_buttons() self.view.curr_annotation = '' self._controller1.start_turn() def load_game(self, filename): self._stop_updates() try: saved_game = SavedGame() saved_game.read(filename) self.model.curr_state.clear() self.model.curr_state.to_move = saved_game.to_move self.num_players = saved_game.num_players squares = self.model.curr_state.squares for i in saved_game.black_men: squares[squaremap[i]] = BLACK | MAN for i in saved_game.black_kings: squares[squaremap[i]] = BLACK | KING for i in saved_game.white_men: squares[squaremap[i]] = WHITE | MAN for i in saved_game.white_kings: squares[squaremap[i]] = WHITE | KING self.model.curr_state.reset_undo() self.model.curr_state.redo_list = saved_game.moves self.model.curr_state.update_piece_count() self.view.reset_view(self.model) self.view.serializer.restore(saved_game.description) self.view.curr_annotation = self.view.get_annotation() self.view.flip_board(saved_game.flip_board) self.view.update_statusbar() self.parent.set_title_bar_filename(filename) self.filename = filename except IOError as (err): showerror(PROGRAM_TITLE, 'Invalid file. ' + str(err)) def open_game(self): self._stop_updates() self._save_curr_game_if_needed() f = askopenfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR) if not f: return self.load_game(f) def save_game_as(self): self._stop_updates() filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR, defaultextension='.rcf') if filename == '': return self._write_file(filename) def save_game(self): self._stop_updates() filename = self.filename if not self.filename: filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR, defaultextension='.rcf') if filename == '': return self._write_file(filename) def _write_file(self, filename): try: saved_game = SavedGame() # undo moves back to the beginning of play undo_steps = 0 while self.model.curr_state.undo_list: undo_steps += 1 self.model.curr_state.undo_move(None, True, True, self.view.get_annotation()) # save the state of the board saved_game.to_move = self.model.curr_state.to_move saved_game.num_players = self.num_players saved_game.black_men = [] saved_game.black_kings = [] saved_game.white_men = [] saved_game.white_kings = [] for i, sq in enumerate(self.model.curr_state.squares): if sq == BLACK | MAN: saved_game.black_men.append(keymap[i]) elif sq == BLACK | KING: saved_game.black_kings.append(keymap[i]) elif sq == WHITE | MAN: saved_game.white_men.append(keymap[i]) elif sq == WHITE | KING: saved_game.white_kings.append(keymap[i]) saved_game.description = self.view.serializer.dump() saved_game.moves = self.model.curr_state.redo_list saved_game.flip_board = self.view.flip_view saved_game.write(filename) # redo moves forward to the previous state for i in range(undo_steps): annotation = self.view.get_annotation() self.model.curr_state.redo_move(None, annotation) # record current filename in title bar self.parent.set_title_bar_filename(filename) self.filename = filename except IOError: showerror(PROGRAM_TITLE, 'Could not save file.') def turn_finished(self): if self.model.curr_state.to_move == BLACK: self._controller2.end_turn() # end White's turn self._root.update() self.view.update_statusbar() self._controller1.start_turn() # begin Black's turn else: self._controller1.end_turn() # end Black's turn self._root.update() self.view.update_statusbar() self._controller2.start_turn() # begin White's turn
Python
class Move(object): def __init__(self, squares, annotation=''): self.affected_squares = squares self.annotation = annotation def __repr__(self): return str(self.affected_squares)
Python
"""Games, or Adversarial Search. (Chapters 6) """ from utils import infinity, argmax, argmax_random_tie, num_or_str, Dict, update from utils import if_, Struct import random import time #______________________________________________________________________________ # Minimax Search def minimax_decision(state, game): """Given a state in a game, calculate the best move by searching forward all the way to the terminal states. [Fig. 6.4]""" player = game.to_move(state) def max_value(state): if game.terminal_test(state): return game.utility(state, player) v = -infinity for (_, s) in game.successors(state): v = max(v, min_value(s)) return v def min_value(state): if game.terminal_test(state): return game.utility(state, player) v = infinity for (_, s) in game.successors(state): v = min(v, max_value(s)) return v # Body of minimax_decision starts here: action, state = argmax(game.successors(state), lambda ((a, s)): min_value(s)) return action #______________________________________________________________________________ def alphabeta_full_search(state, game): """Search game to determine best action; use alpha-beta pruning. As in [Fig. 6.7], this version searches all the way to the leaves.""" player = game.to_move(state) def max_value(state, alpha, beta): if game.terminal_test(state): return game.utility(state, player) v = -infinity for (a, s) in game.successors(state): v = max(v, min_value(s, alpha, beta)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, alpha, beta): if game.terminal_test(state): return game.utility(state, player) v = infinity for (a, s) in game.successors(state): v = min(v, max_value(s, alpha, beta)) if v <= alpha: return v beta = min(beta, v) return v # Body of alphabeta_search starts here: action, state = argmax(game.successors(state), lambda ((a, s)): min_value(s, -infinity, infinity)) return action def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" player = game.to_move(state) def max_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = -infinity succ = game.successors(state) for (a, s) in succ: v = max(v, min_value(s, alpha, beta, depth+1)) if v >= beta: succ.close() return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = infinity succ = game.successors(state) for (a, s) in succ: v = min(v, max_value(s, alpha, beta, depth+1)) if v <= alpha: succ.close() return v beta = min(beta, v) return v # Body of alphabeta_search starts here: # The default test cuts off at depth d or at a terminal state cutoff_test = (cutoff_test or (lambda state,depth: depth>d or game.terminal_test(state))) eval_fn = eval_fn or (lambda state: game.utility(player, state)) action, state = argmax_random_tie(game.successors(state), lambda ((a, s)): min_value(s, -infinity, infinity, 0)) return action #______________________________________________________________________________ # Players for Games def query_player(game, state): "Make a move by querying standard input." game.display(state) return num_or_str(raw_input('Your move? ')) def random_player(game, state): "A player that chooses a legal move at random." return random.choice(game.legal_moves()) def alphabeta_player(game, state): return alphabeta_search(state, game) def play_game(game, *players): "Play an n-person, move-alternating game." print game.curr_state while True: for player in players: if game.curr_state.to_move == player.color: move = player.select_move(game) print game.make_move(move) if game.terminal_test(): return game.utility(player.color) #______________________________________________________________________________ # Some Sample Games class Game: """A game is similar to a problem, but it has a utility for each state and a terminal test instead of a path cost and a goal test. To create a game, subclass this class and implement legal_moves, make_move, utility, and terminal_test. You may override display and successors or you can inherit their default methods. You will also need to set the .initial attribute to the initial state; this can be done in the constructor.""" def legal_moves(self, state): "Return a list of the allowable moves at this point." abstract def make_move(self, move, state): "Return the state that results from making a move from a state." abstract def utility(self, state, player): "Return the value of this final state to player." abstract def terminal_test(self, state): "Return True if this is a final state for the game." return not self.legal_moves(state) def to_move(self, state): "Return the player whose move it is in this state." return state.to_move def display(self, state): "Print or otherwise display the state." print state def successors(self, state): "Return a list of legal (move, state) pairs." return [(move, self.make_move(move, state)) for move in self.legal_moves(state)] def __repr__(self): return '<%s>' % self.__class__.__name__ class Fig62Game(Game): """The game represented in [Fig. 6.2]. Serves as a simple test case. >>> g = Fig62Game() >>> minimax_decision('A', g) 'a1' >>> alphabeta_full_search('A', g) 'a1' >>> alphabeta_search('A', g) 'a1' """ succs = {'A': [('a1', 'B'), ('a2', 'C'), ('a3', 'D')], 'B': [('b1', 'B1'), ('b2', 'B2'), ('b3', 'B3')], 'C': [('c1', 'C1'), ('c2', 'C2'), ('c3', 'C3')], 'D': [('d1', 'D1'), ('d2', 'D2'), ('d3', 'D3')]} utils = Dict(B1=3, B2=12, B3=8, C1=2, C2=4, C3=6, D1=14, D2=5, D3=2) initial = 'A' def successors(self, state): return self.succs.get(state, []) def utility(self, state, player): if player == 'MAX': return self.utils[state] else: return -self.utils[state] def terminal_test(self, state): return state not in ('A', 'B', 'C', 'D') def to_move(self, state): return if_(state in 'BCD', 'MIN', 'MAX') class TicTacToe(Game): """Play TicTacToe on an h x v board, with Max (first player) playing 'X'. A state has the player to move, a cached utility, a list of moves in the form of a list of (x, y) positions, and a board, in the form of a dict of {(x, y): Player} entries, where Player is 'X' or 'O'.""" def __init__(self, h=3, v=3, k=3): update(self, h=h, v=v, k=k) moves = [(x, y) for x in range(1, h+1) for y in range(1, v+1)] self.initial = Struct(to_move='X', utility=0, board={}, moves=moves) def legal_moves(self, state): "Legal moves are any square not yet taken." return state.moves def make_move(self, move, state): if move not in state.moves: return state # Illegal move has no effect board = state.board.copy(); board[move] = state.to_move moves = list(state.moves); moves.remove(move) return Struct(to_move=if_(state.to_move == 'X', 'O', 'X'), utility=self.compute_utility(board, move, state.to_move), board=board, moves=moves) def utility(self, state): "Return the value to X; 1 for win, -1 for loss, 0 otherwise." return state.utility def terminal_test(self, state): "A state is terminal if it is won or there are no empty squares." return state.utility != 0 or len(state.moves) == 0 def display(self, state): board = state.board for x in range(1, self.h+1): for y in range(1, self.v+1): print board.get((x, y), '.'), print def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1))): return if_(player == 'X', +1, -1) else: return 0 def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= self.k class ConnectFour(TicTacToe): """A TicTacToe-like game in which you can only make a move on the bottom row, or in a square directly above an occupied square. Traditionally played on a 7x6 board and requiring 4 in a row.""" def __init__(self, h=7, v=6, k=4): TicTacToe.__init__(self, h, v, k) def legal_moves(self, state): "Legal moves are any square not yet taken." return [(x, y) for (x, y) in state.moves if y == 0 or (x, y-1) in state.board]
Python
from Tkinter import * from tkSimpleDialog import Dialog from globalconst import * class AboutBox(Dialog): def body(self, master): self.canvas = Canvas(self, width=300, height=275) self.canvas.pack(side=TOP, fill=BOTH, expand=0) self.canvas.create_text(152,47,text='Raven', fill='black', font=('Helvetica', 36)) self.canvas.create_text(150,45,text='Raven', fill='white', font=('Helvetica', 36)) self.canvas.create_text(150,85,text='Version '+ VERSION, fill='black', font=('Helvetica', 12)) self.canvas.create_text(150,115,text='An open source checkers program', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,130,text='by Brandon Corfman', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,160,text='Evaluation function translated from', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,175,text="Martin Fierz's Simple Checkers", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,205,text="Alpha-beta search code written by", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,220,text="Peter Norvig for the AIMA project;", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,235,text="adopted for checkers usage", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,250,text="by Brandon Corfman", fill='black', font=('Helvetica', 10)) return self.canvas def cancel(self, event=None): self.destroy() def buttonbox(self): self.button = Button(self, text='OK', padx='5m', command=self.cancel) self.blank = Canvas(self, width=10, height=20) self.blank.pack(side=BOTTOM, fill=BOTH, expand=0) self.button.pack(side=BOTTOM) self.button.focus_set() self.bind("<Escape>", self.cancel)
Python
import copy, textwrap from globalconst import * from move import Move from checkers import Checkers class SavedGame(object): def __init__(self): self._model = Checkers() self.to_move = None self.moves = [] self.description = '' self.black_men = [] self.white_men = [] self.black_kings = [] self.white_kings = [] self.flip_board = False self.num_players = 1 self._move_check = False self._bm_check = False self._bk_check = False self._wm_check = False self._wk_check = False def _write_positions(self, f, prefix, positions): f.write(prefix + ' ') for p in sorted(positions): f.write('%d ' % p) f.write('\n') def _write_moves(self, f): f.write('<moves>\n') for move in reversed(self.moves): start = keymap[move.affected_squares[FIRST][0]] dest = keymap[move.affected_squares[LAST][0]] movestr = '%d-%d' % (start, dest) annotation = move.annotation if annotation.startswith(movestr): annotation = annotation.replace(movestr, '', 1).rstrip() f.write('%s;%s\n' % (movestr, annotation)) def write(self, filename): with open(filename, 'w') as f: f.write('<description>\n') for line in self.description.splitlines(): # numbered lists or hyperlinks are not word wrapped. if line.startswith('# ') or '[[' in line: f.write(line + '\n') continue else: f.write(textwrap.fill(line, 80) + '\n') f.write('<setup>\n') if self.to_move == WHITE: f.write('white_first\n') elif self.to_move == BLACK: f.write('black_first\n') else: raise ValueError, "Unknown value for to_move variable" if self.num_players >=0 and self.num_players <=2: f.write('%d_player_game\n' % self.num_players) else: raise ValueError, "Unknown value for num_players variable" if self.flip_board: f.write('flip_board 1\n') else: f.write('flip_board 0\n') self._write_positions(f, 'black_men', self.black_men) self._write_positions(f, 'black_kings', self.black_kings) self._write_positions(f, 'white_men', self.white_men) self._write_positions(f, 'white_kings', self.white_kings) self._write_moves(f) def read(self, filename): with open(filename, 'r') as f: lines = f.readlines() linelen = len(lines) i = 0 while True: if i >= linelen: break line = lines[i].strip() if line.startswith('<description>'): self.description = '' i += 1 while i < linelen and not lines[i].startswith('<setup>'): self.description += lines[i] i += 1 elif line.startswith('<setup>'): i = self._parse_setup(lines, i, linelen) elif line.startswith('<moves>'): i = self._parse_moves(lines, i, linelen) else: raise IOError, 'Unrecognized section in file, line %d' % (i+1) def _parse_items(self, line): men = line.split()[1:] return map(int, men) def _add_men_to_board(self, locations, val): squares = self._model.curr_state.squares try: for loc in locations: idx = squaremap[loc] squares[idx] = val except ValueError: raise IOError, 'Checker location not valid, line %d' % (i+1) def _parse_setup(self, lines, idx, linelen): curr_state = self._model.curr_state curr_state.clear() idx += 1 while idx < linelen and '<moves>' not in lines[idx]: line = lines[idx].strip().lower() if line == 'white_first': self.to_move = curr_state.to_move = WHITE self._move_check = True elif line == 'black_first': self.to_move = curr_state.to_move = BLACK self._move_check = True elif line.endswith('player_game'): numstr, _ = line.split('_', 1) self.num_players = int(numstr) elif line.startswith('flip_board'): _, setting = line.split() val = int(setting) self.flip_board = True if val else False elif line.startswith('black_men'): self.black_men = self._parse_items(line) self._add_men_to_board(self.black_men, BLACK | MAN) self._bm_check = True elif line.startswith('white_men'): self.white_men = self._parse_items(line) self._add_men_to_board(self.white_men, WHITE | MAN) self._wm_check = True elif line.startswith('black_kings'): self.black_kings = self._parse_items(line) self._add_men_to_board(self.black_kings, BLACK | KING) self._bk_check = True elif line.startswith('white_kings'): self.white_kings = self._parse_items(line) self._add_men_to_board(self.white_kings, WHITE | KING) self._wk_check = True idx += 1 if (not self._move_check and not self._bm_check and not self._wm_check and not self._bk_check and not self._wk_check): raise IOError, 'Error in <setup> section: not all required items found' return idx def _is_move(self, delta): return delta in KING_IDX def _is_jump(self, delta): return delta not in KING_IDX def _try_move(self, idx, start, dest, state_copy, annotation): legal_moves = self._model.legal_moves(state_copy) # match move from file with available moves on checkerboard found = False startsq, destsq = squaremap[start], squaremap[dest] for move in legal_moves: if (startsq == move.affected_squares[FIRST][0] and destsq == move.affected_squares[LAST][0]): self._model.make_move(move, state_copy, False, False) move.annotation = annotation self.moves.append(move) found = True break if not found: raise IOError, 'Illegal move found in file, line %d' % (idx+1) def _try_jump(self, idx, start, dest, state_copy, annotation): if not self._model.captures_available(state_copy): return False legal_moves = self._model.legal_moves(state_copy) # match jump from file with available jumps on checkerboard startsq, destsq = squaremap[start], squaremap[dest] small, large = min(startsq, destsq), max(startsq, destsq) found = False for move in legal_moves: # a valid jump may either have a single jump in it, or # multiple jumps. In the multiple jump case, startsq is the # source of the first jump, and destsq is the endpoint of the # last jump. if (startsq == move.affected_squares[FIRST][0] and destsq == move.affected_squares[LAST][0]): self._model.make_move(move, state_copy, False, False) move.annotation = annotation self.moves.append(move) found = True break return found def _parse_moves(self, lines, idx, linelen): """ Each move in the file lists the beginning and ending square, along with an optional annotation string (in Creole format) that describes it. Since the move listing in the file contains less information than we need inside our Checkerboard model, I make sure that each move works on a copy of the model before I commit to using it inside the code. """ state_copy = copy.deepcopy(self._model.curr_state) idx += 1 while idx < linelen: line = lines[idx].strip() if line == "": idx += 1 continue # ignore blank lines try: movestr, annotation = line.split(';', 1) except ValueError: raise IOError, 'Unrecognized section in file, line %d' % (idx+1) # move is always part of the annotation; I just don't want to # have to repeat it explicitly in the file. annotation = movestr + annotation # analyze affected squares to perform a move or jump. try: start, dest = [int(x) for x in movestr.split('-')] except ValueError: raise IOError, 'Bad move format in file, line %d' % idx delta = squaremap[start] - squaremap[dest] if self._is_move(delta): self._try_move(idx, start, dest, state_copy, annotation) else: jumped = self._try_jump(idx, start, dest, state_copy, annotation) if not jumped: raise IOError, 'Bad move format in file, line %d' % idx idx += 1 self.moves.reverse() return idx
Python
from Tkinter import Widget from controller import Controller from globalconst import * class PlayerController(Controller): def __init__(self, **props): self._model = props['model'] self._view = props['view'] self._before_turn_event = None self._end_turn_event = props['end_turn_event'] self._highlights = [] self._move_in_progress = False def _register_event_handlers(self): Widget.bind(self._view.canvas, '<Button-1>', self.mouse_click) def _unregister_event_handlers(self): Widget.unbind(self._view.canvas, '<Button-1>') def stop_process(self): pass def set_search_time(self, time): pass def get_player_type(self): return HUMAN def set_before_turn_event(self, evt): self._before_turn_event = evt def add_highlights(self): for h in self._highlights: self._view.highlight_square(h, OUTLINE_COLOR) def remove_highlights(self): for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) def start_turn(self): self._register_event_handlers() self._model.curr_state.attach(self._view) def end_turn(self): self._unregister_event_handlers() self._model.curr_state.detach(self._view) def mouse_click(self, event): xi, yi = self._view.calc_board_loc(event.x, event.y) pos = self._view.calc_board_pos(xi, yi) sq = self._model.curr_state.squares[pos] if not self._move_in_progress: player = self._model.curr_state.to_move self.moves = self._model.legal_moves() if (sq & player) and self.moves: self._before_turn_event() # highlight the start square the user clicked on self._view.highlight_square(pos, OUTLINE_COLOR) self._highlights = [pos] # reduce moves to number matching the positions entered self.moves = self._filter_moves(pos, self.moves, 0) self.idx = 2 if self._model.captures_available() else 1 # if only one move available, take it. if len(self.moves) == 1: self._make_move() self._view.canvas.after(100, self._end_turn_event) return self._move_in_progress = True else: if sq & FREE: self.moves = self._filter_moves(pos, self.moves, self.idx) if len(self.moves) == 0: # illegal move # remove previous square highlights for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) self._move_in_progress = False return else: self._view.highlight_square(pos, OUTLINE_COLOR) self._highlights.append(pos) if len(self.moves) == 1: self._make_move() self._view.canvas.after(100, self._end_turn_event) return self.idx += 2 if self._model.captures_available() else 1 def _filter_moves(self, pos, moves, idx): del_list = [] for i, m in enumerate(moves): if pos != m.affected_squares[idx][0]: del_list.append(i) for i in reversed(del_list): del moves[i] return moves def _make_move(self): move = self.moves[0].affected_squares step = 2 if len(move) > 2 else 1 # highlight remaining board squares used in move for m in move[step::step]: idx = m[0] self._view.highlight_square(idx, OUTLINE_COLOR) self._highlights.append(idx) self._model.make_move(self.moves[0], None, True, True, self._view.get_annotation()) # a new move obliterates any more redo's along a branch of the game tree self._model.curr_state.delete_redo_list() self._move_in_progress = False
Python
from abc import ABCMeta, abstractmethod class GoalEvaluator(object): __metaclass__ = ABCMeta def __init__(self, bias): self.bias = bias @abstractmethod def calculateDesirability(self, board): pass @abstractmethod def setGoal(self, board): pass
Python
from Tkinter import * from time import time, localtime, strftime class ToolTip( Toplevel ): """ Provides a ToolTip widget for Tkinter. To apply a ToolTip to any Tkinter widget, simply pass the widget to the ToolTip constructor """ def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ): """ Initialize the ToolTip Arguments: wdgt: The widget this ToolTip is assigned to msg: A static string message assigned to the ToolTip msgFunc: A function that retrieves a string to use as the ToolTip text delay: The delay in seconds before the ToolTip appears(may be float) follow: If True, the ToolTip follows motion, otherwise hides """ self.wdgt = wdgt self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel self.withdraw() # Hide initially self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip if msg == None: self.msgVar.set( 'No message provided' ) else: self.msgVar.set( msg ) self.msgFunc = msgFunc self.delay = delay self.follow = follow self.visible = 0 self.lastMotion = 0 Message( self, textvariable=self.msgVar, bg='#FFFFDD', aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has self.wdgt.bind( '<Leave>', self.hide, '+' ) self.wdgt.bind( '<Motion>', self.move, '+' ) def spawn( self, event=None ): """ Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton """ self.visible = 1 self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds def show( self ): """ Displays the ToolTip if the time delay has been long enough """ if self.visible == 1 and time() - self.lastMotion > self.delay: self.visible = 2 if self.visible == 2: self.deiconify() def move( self, event ): """ Processes motion within the widget. Arguments: event: The event that called this function """ self.lastMotion = time() if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear self.withdraw() self.visible = 1 self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer try: self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails except: pass self.after( int( self.delay * 1000 ), self.show ) def hide( self, event=None ): """ Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function """ self.visible = 0 self.withdraw() def xrange2d( n,m ): """ Returns a generator of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A generator of values in a 2d range """ return ( (i,j) for i in xrange(n) for j in xrange(m) ) def range2d( n,m ): """ Returns a list of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A list of values in a 2d range """ return [(i,j) for i in range(n) for j in range(m) ] def print_time(): """ Prints the current time in the following format: HH:MM:SS.00 """ t = time() timeString = 'time=' timeString += strftime( '%H:%M:', localtime(t) ) timeString += '%.2f' % ( t%60, ) return timeString def main(): root = Tk() btnList = [] for (i,j) in range2d( 6, 4 ): text = 'delay=%i\n' % i delay = i if j >= 2: follow=True text += '+follow\n' else: follow = False text += '-follow\n' if j % 2 == 0: msg = None msgFunc = print_time text += 'Message Function' else: msg = 'Button at %s' % str( (i,j) ) msgFunc = None text += 'Static Message' btnList.append( Button( root, text=text ) ) ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay) btnList[-1].grid( row=i, column=j, sticky=N+S+E+W ) root.mainloop() if __name__ == '__main__': main()
Python
class Command(object): def __init__(self, **props): self.add = props.get('add') or [] self.remove = props.get('remove') or []
Python
from globalconst import BLACK, WHITE, KING import checkers class Operator(object): pass class OneKingAttackOneKing(Operator): def precondition(self, board): plr_color = board.to_move opp_color = board.enemy return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and any((x & KING for x in board.get_pieces(opp_color))) and any((x & KING for x in board.get_pieces(plr_color))) and board.has_opposition(plr_color)) def postcondition(self, board): board.make_move() class PinEnemyKingInCornerWithPlayerKing(Operator): def __init__(self): self.pidx = 0 self.eidx = 0 self.goal = 8 def precondition(self, state): self.pidx, plr = self.plr_lst[0] # only 1 piece per side self.eidx, enemy = self.enemy_lst[0] delta = abs(self.pidx - self.eidx) return ((self.player_total == 1) and (self.enemy_total == 1) and (plr & KING > 0) and (enemy & KING > 0) and not (8 <= delta <= 10) and state.have_opposition(plr)) def postcondition(self, state): new_state = None old_delta = abs(self.eidx - self.pidx) goal_delta = abs(self.goal - old_delta) for move in state.moves: for m in move: newidx, _, _ = m[1] new_delta = abs(self.eidx - newidx) if abs(goal - new_delta) < goal_delta: new_state = state.make_move(move) break return new_state # (white) # 37 38 39 40 # 32 33 34 35 # 28 29 30 31 # 23 24 25 26 # 19 20 21 22 # 14 15 16 17 # 10 11 12 13 # 5 6 7 8 # (black) class SingleKingFleeToDoubleCorner(Operator): def __init__(self): self.pidx = 0 self.eidx = 0 self.dest = [8, 13, 27, 32] self.goal_delta = 0 def precondition(self, state): # fail fast if self.player_total == 1 and self.enemy_total == 1: return False self.pidx, _ = self.plr_lst[0] self.eidx, _ = self.enemy_lst[0] for sq in self.dest: if abs(self.pidx - sq) < abs(self.eidx - sq): self.goal = sq return True return False def postcondition(self, state): self.goal_delta = abs(self.goal - self.pidx) for move in state.moves: for m in move: newidx, _, _ = m[1] new_delta = abs(self.goal - newidx) if new_delta < self.goal_delta: new_state = state.make_move(move) break return new_state class FormShortDyke(Operator): def precondition(self): pass
Python
class Controller(object): def stop_process(self): pass
Python
from abc import ABCMeta, abstractmethod class Goal: __metaclass__ = ABCMeta INACTIVE = 0 ACTIVE = 1 COMPLETED = 2 FAILED = 3 def __init__(self, owner): self.owner = owner self.status = self.INACTIVE @abstractmethod def activate(self): pass @abstractmethod def process(self): pass @abstractmethod def terminate(self): pass def handleMessage(self, msg): return False def addSubgoal(self, goal): raise NotImplementedError('Cannot add goals to atomic goals') def reactivateIfFailed(self): if self.status == self.FAILED: self.status = self.INACTIVE def activateIfInactive(self): if self.status == self.INACTIVE: self.status = self.ACTIVE
Python
from Tkinter import * from ttk import Checkbutton from tkSimpleDialog import Dialog from globalconst import * class SetupBoard(Dialog): def __init__(self, parent, title, gameManager): self._master = parent self._manager = gameManager self._load_entry_box_vars() self.result = False Dialog.__init__(self, parent, title) def body(self, master): self._npLFrame = LabelFrame(master, text='No. of players:') self._npFrameEx1 = Frame(self._npLFrame, width=30) self._npFrameEx1.pack(side=LEFT, pady=5, expand=1) self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)', value=0, variable=self._num_players, command=self._disable_player_color) self._npButton1.pack(side=LEFT, pady=5, expand=1) self._npButton2 = Radiobutton(self._npLFrame, text='One', value=1, variable=self._num_players, command=self._enable_player_color) self._npButton2.pack(side=LEFT, pady=5, expand=1) self._npButton3 = Radiobutton(self._npLFrame, text='Two', value=2, variable=self._num_players, command=self._disable_player_color) self._npButton3.pack(side=LEFT, pady=5, expand=1) self._npFrameEx2 = Frame(self._npLFrame, width=30) self._npFrameEx2.pack(side=LEFT, pady=5, expand=1) self._npLFrame.pack(fill=X) self._playerFrame = LabelFrame(master, text='Player color:') self._playerFrameEx1 = Frame(self._playerFrame, width=50) self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbColor1 = Radiobutton(self._playerFrame, text='Black', value=BLACK, variable=self._player_color) self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbColor2 = Radiobutton(self._playerFrame, text='White', value=WHITE, variable=self._player_color) self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1) self._playerFrameEx2 = Frame(self._playerFrame, width=50) self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1) self._playerFrame.pack(fill=X) self._rbFrame = LabelFrame(master, text='Next to move:') self._rbFrameEx1 = Frame(self._rbFrame, width=50) self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbTurn1 = Radiobutton(self._rbFrame, text='Black', value=BLACK, variable=self._player_turn) self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbTurn2 = Radiobutton(self._rbFrame, text='White', value=WHITE, variable=self._player_turn) self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbFrameEx2 = Frame(self._rbFrame, width=50) self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1) self._rbFrame.pack(fill=X) self._bcFrame = LabelFrame(master, text='Board configuration') self._wmFrame = Frame(self._bcFrame, borderwidth=0) self._wmLabel = Label(self._wmFrame, text='White men:') self._wmLabel.pack(side=LEFT, padx=7, pady=10) self._wmEntry = Entry(self._wmFrame, width=40, textvariable=self._white_men) self._wmEntry.pack(side=LEFT, padx=10) self._wmFrame.pack() self._wkFrame = Frame(self._bcFrame, borderwidth=0) self._wkLabel = Label(self._wkFrame, text='White kings:') self._wkLabel.pack(side=LEFT, padx=5, pady=10) self._wkEntry = Entry(self._wkFrame, width=40, textvariable=self._white_kings) self._wkEntry.pack(side=LEFT, padx=10) self._wkFrame.pack() self._bmFrame = Frame(self._bcFrame, borderwidth=0) self._bmLabel = Label(self._bmFrame, text='Black men:') self._bmLabel.pack(side=LEFT, padx=7, pady=10) self._bmEntry = Entry(self._bmFrame, width=40, textvariable=self._black_men) self._bmEntry.pack(side=LEFT, padx=10) self._bmFrame.pack() self._bkFrame = Frame(self._bcFrame, borderwidth=0) self._bkLabel = Label(self._bkFrame, text='Black kings:') self._bkLabel.pack(side=LEFT, padx=5, pady=10) self._bkEntry = Entry(self._bkFrame, width=40, textvariable=self._black_kings) self._bkEntry.pack(side=LEFT, padx=10) self._bkFrame.pack() self._bcFrame.pack(fill=X) self._bsState = IntVar() self._bsFrame = Frame(master, borderwidth=0) self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState, text='Start new game with the current setup?') self._bsCheck.pack() self._bsFrame.pack(fill=X) if self._num_players.get() == 1: self._enable_player_color() else: self._disable_player_color() def validate(self): self.wm_list = self._parse_int_list(self._white_men.get()) self.wk_list = self._parse_int_list(self._white_kings.get()) self.bm_list = self._parse_int_list(self._black_men.get()) self.bk_list = self._parse_int_list(self._black_kings.get()) if (self.wm_list == None or self.wk_list == None or self.bm_list == None or self.bk_list == None): return 0 # Error occurred during parsing if not self._all_unique(self.wm_list, self.wk_list, self.bm_list, self.bk_list): return 0 # A repeated index occurred return 1 def apply(self): mgr = self._manager model = mgr.model view = mgr.view state = model.curr_state mgr.player_color = self._player_color.get() mgr.num_players = self._num_players.get() mgr.model.curr_state.to_move = self._player_turn.get() # only reset the BoardView if men or kings have new positions if (sorted(self.wm_list) != sorted(self._orig_white_men) or sorted(self.wk_list) != sorted(self._orig_white_kings) or sorted(self.bm_list) != sorted(self._orig_black_men) or sorted(self.bk_list) != sorted(self._orig_black_kings) or self._bsState.get() == 1): state.clear() sq = state.squares for item in self.wm_list: idx = squaremap[item] sq[idx] = WHITE | MAN for item in self.wk_list: idx = squaremap[item] sq[idx] = WHITE | KING for item in self.bm_list: idx = squaremap[item] sq[idx] = BLACK | MAN for item in self.bk_list: idx = squaremap[item] sq[idx] = BLACK | KING state.to_move = self._player_turn.get() state.reset_undo() view.reset_view(mgr.model) if self._bsState.get() == 1: mgr.filename = None mgr.parent.set_title_bar_filename() state.ok_to_move = True self.result = True self.destroy() def cancel(self, event=None): self.destroy() def _load_entry_box_vars(self): self._white_men = StringVar() self._white_kings = StringVar() self._black_men = StringVar() self._black_kings = StringVar() self._player_color = IntVar() self._player_turn = IntVar() self._num_players = IntVar() self._player_color.set(self._manager.player_color) self._num_players.set(self._manager.num_players) model = self._manager.model self._player_turn.set(model.curr_state.to_move) view = self._manager.view self._white_men.set(', '.join(view.get_positions(WHITE | MAN))) self._white_kings.set(', '.join(view.get_positions(WHITE | KING))) self._black_men.set(', '.join(view.get_positions(BLACK | MAN))) self._black_kings.set(', '.join(view.get_positions(BLACK | KING))) self._orig_white_men = map(int, view.get_positions(WHITE | MAN)) self._orig_white_kings = map(int, view.get_positions(WHITE | KING)) self._orig_black_men = map(int, view.get_positions(BLACK | MAN)) self._orig_black_kings = map(int, view.get_positions(BLACK | KING)) def _disable_player_color(self): self._rbColor1.configure(state=DISABLED) self._rbColor2.configure(state=DISABLED) def _enable_player_color(self): self._rbColor1.configure(state=NORMAL) self._rbColor2.configure(state=NORMAL) def _all_unique(self, *lists): s = set() total_list = [] for i in lists: total_list.extend(i) s = s.union(i) return sorted(total_list) == sorted(s) def _parse_int_list(self, parsestr): try: lst = parsestr.split(',') except AttributeError: return None if lst == ['']: return [] try: lst = [int(i) for i in lst] except ValueError: return None if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)): return None return lst
Python
from Tkinter import * class HyperlinkManager(object): def __init__(self, textWidget, linkFunc): self.txt = textWidget self.linkfunc = linkFunc self.txt.tag_config('hyper', foreground='blue', underline=1) self.txt.tag_bind('hyper', '<Enter>', self._enter) self.txt.tag_bind('hyper', '<Leave>', self._leave) self.txt.tag_bind('hyper', '<Button-1>', self._click) self.reset() def reset(self): self.filenames = {} def add(self, filename): # Add a link with associated filename. The link function returns tags # to use in the associated text widget. tag = 'hyper-%d' % len(self.filenames) self.filenames[tag] = filename return 'hyper', tag def _enter(self, event): self.txt.config(cursor='hand2') def _leave(self, event): self.txt.config(cursor='') def _click(self, event): for tag in self.txt.tag_names(CURRENT): if tag.startswith('hyper-'): self.linkfunc(self.filenames[tag]) return
Python
class DocNode(object): """ A node in the document. """ def __init__(self, kind='', parent=None, content=None): self.children = [] self.parent = parent self.kind = kind self.content = content if self.parent is not None: self.parent.children.append(self)
Python
import urllib2, re, Image, shutil, stat, os, random from urllib import FancyURLopener border = 5 bigw = 1920 bigh = 1200 class AgentOpener(FancyURLopener): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' agent_opener = AgentOpener() def getImages(file): data = file.read() return re.findall('src="([^"]*?/([^"/]*?_m.jpg))"', data) def downloadImages(images): for image_url, image_name in images: print " -", image_name, local_file_path = "images/"+image_name if os.path.exists(local_file_path) and os.stat(local_file_path)[stat.ST_SIZE] > 1024: print "exist!" continue local_image = open(local_file_path, "wb", 10240) remote_image = agent_opener.open(image_url) shutil.copyfileobj(remote_image, local_image) print "OK!" def h_sorter(a, b): return cmp(a["h"]+a["y"], b["h"]+b["y"]) def findpos(w): global imagedb imagedb.sort(h_sorter) index = 0 for image in imagedb: if image["w"] <= w: break else: index += 1 if index > len(image): return None return imagedb.pop(index) def createBigimage(images): global imagedb random.shuffle(images) bigim = Image.new("RGB", (bigw, bigh)) nextx = border imagedb = [] for image_url, image_name in images: im = Image.open("images/"+image_name) w,h = im.size if (nextx+border > bigw): #if its reached the image border parent_image = findpos(w) if not parent_image: continue #not found smaller image x = parent_image["x"] y = parent_image["y"]+parent_image["h"]+border neww = parent_image["w"] h = int(float(neww)/w*h) w = neww im = im.resize((w, h), Image.ANTIALIAS) else: #not reached the image border yet x = nextx y = border w = int(float(w)*0.7) h = int(float(h)*0.7) im = im.resize((w, h), Image.ANTIALIAS) nextx += w+border bigim.paste(im, (x, y)) imagedb.append({"x": x, "y": y, "w": w, "h": h}) return bigim def setWallpaper( bmp ): import win32api, win32con, win32gui k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0") win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp, 1+2) print " * Opening mainpage..." images = getImages(urllib2.urlopen("http://ffffound.com")) randompage = str(500+random.randint(0,100)*25) randompage = str(25) print " * Opening random page...", randompage images.extend( getImages(urllib2.urlopen("http://ffffound.com/?offset="+randompage)) ) print " * Downloading images..." downloadImages(images) print " * Creating Bigimage..." createBigimage(images).save("C:\\windows\\ffffound.bmp") setWallpaper("C:\\windows\\ffffound.bmp") print " * All done!"
Python
#!/usr/bin/env python import os import sys import string import re import StringIO import copy AVOF_name = [ "name", "long_name", "mime_type", "extensions", "priv_data_size", "audio_codec", "video_codec", "write_header", "write_packet", "write_trailer", "flags", "set_parameters", "interleave_packet", "codec_tag", "subtitle_codec", "next", ] AVOF_vaule = [ "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "CODEC_ID_NONE,\n", "CODEC_ID_NONE,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "CODEC_ID_NONE,\n", "0,\n", ] AVIF_name = [ "name", "long_name", "priv_data_size", "read_probe", "read_header", "read_packet", "read_close", "read_seek", "read_timestamp", "flags", "extensions", "value", "read_play", "read_pause", "codec_tag", "next", ] AVIF_vaule =[ "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", ] AVCodecName =[ "name", "type", "id", "priv_data_size", "init", "encode", "close", "decode", "capabilities", "next", "flush", "supported_framerates", "pix_fmts", "long_name", "supported_samplerates", "sample_fmts", "channel_layouts", ] AVCodecVaule = [ "0,", "CODEC_TYPE_UNKNOWN,", "CODEC_ID_NONE,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", ] "AVOutputFormat","AVInputFormat","AVCodec" iovname = {"AVOutputFormat":AVOF_name, "AVInputFormat":AVIF_name, "AVCodec":AVCodecName } iovvalue = {"AVOutputFormat":AVOF_vaule, "AVInputFormat":AVIF_vaule, "AVCodec":AVCodecVaule } class FFmpegException(Exception): pass class FFmpegVC: def __init__(self, fpold, modpath, filename): self.fpold = fpold self.modpath = modpath self.fpnew = None self.txt = "" self.filename = filename self.codectagBock="" self.conditionFlag = 0 self.conditionBlock ="" self.avname = "" self.avtype = "" self.newblocks= [] # all blocks in one page self.newblock = "" # one block content self.newblockHeader = "" # if there is content about other like codec_tag self.newblcokName = "" # like "AVOutputFormat mymux = { \n" self.logfile = r"c:\ffmpeg.py.log.txt" self.log = open(self.logfile, "a") self.valueIdx = 0 self.valueDefault = [] # the whole content between the top level '{' and '}', which define a mux/demux/en/decode self.IOCVariableName = [] # one of AVOF_name ,AVIF_name ,AVCodecName list self.matchIdx = 0 self.lineHeader = " " self.dummy = " "#just dummy self.comment = "/* boirs@gmaildotcom .python */" re_dbblock = re.compile(r"(\b(AVInputFormat|AVOutputFormat|AVCodec)\b\s*([^=]*?)=\s*?{\s*(.*?)\s*?})\s*?;", re.DOTALL) av_type_lst = ["AVOutputFormat","AVInputFormat","AVCodec"] def run(self): self.txt = self.fpold.read() matchdb = self.re_dbblock.finditer(self.txt) if matchdb: self.fpnew = open(os.path.join(self.modpath, self.filename), "w") for db in matchdb: newdb = self.buildNewDB(db) self.newblocks.append(newdb) self.dbsub() self.fpnew.close() self.fpold.close() self.log.close() regex_remove_comment = re.compile(r"/\*.*?\*/|//.*?$", re.MULTILINE|re.DOTALL) def buildNewDB(self, olddb): wholedb = olddb.group(1) # the whole block self.avtype = olddb.group(2) # O or I? self.avname = olddb.group(3) # like my_mux self.newblcokName = self.avtype + " " +self.avname + "= {\n" dbdata = olddb.group(4) dbdata = self.regex_remove_comment.sub("", dbdata) strFile = StringIO.StringIO(dbdata) self.valueDefault = copy.copy(iovvalue[self.avtype]) self.IOCVariableName = iovname[self.avtype] #print self.IOCVariableName.index("name") self.valueIdx = 0 for line in strFile: afterCheckEmpty = line.strip() if not afterCheckEmpty: continue if afterCheckEmpty[0] != '#':#debug bool0 = afterCheckEmpty.count("[") == afterCheckEmpty.count("]") bool1 = afterCheckEmpty.count("(") == afterCheckEmpty.count(")") bool2 = afterCheckEmpty.count("{") == afterCheckEmpty.count("}") bool3 = afterCheckEmpty.count('"')%2 == 0 bool4 = afterCheckEmpty.rfind(',') == len(afterCheckEmpty) - 1 boolall = [bool0, bool1, bool2, bool3, bool4] if not all(boolall): self.log.write(self.filename) self.log.write(self.avname) self.log.write(dbdata) print self.filename + " has an error" indexxxx = 0 for item in boolall: if not item: print indexxxx else: indexxxx += 1 raise FFmpegException, " error " #process line by line avalue = "" if str(afterCheckEmpty[0:3]) == '#if': self.conditionFlag = 1 if self.conditionFlag == 1: if str(afterCheckEmpty[0:3]) == '#if': #if self.conditionBlock = "" self.conditionBlock += afterCheckEmpty + "\n" elif str(afterCheckEmpty[0:3]) == '#el': # #elif |#else self.conditionBlock += afterCheckEmpty + "\n" elif str(afterCheckEmpty[0:4]) == '#end': ##end self.conditionBlock += afterCheckEmpty + "\n" self.conditionFlag = 0 self.valueDefault[self.valueIdx] = self.conditionBlock self.valueIdx += 1 else: avalue = self.processLine(afterCheckEmpty) self.conditionBlock += avalue else: avalue = self.processLine(afterCheckEmpty) self.valueDefault[self.valueIdx] = avalue self.valueIdx += 1 tempValueDefault = "" vr = range(self.valueIdx) for item in vr: tempValueDefault += self.valueDefault[item] the_whole_new_block = self.newblockHeader + self.newblcokName + tempValueDefault + "};\n" #print the_whole_new_block return the_whole_new_block def processLine(self, aline): if aline[0] == '.': return self.processDotLine(aline) else: return self.processNormalLIne(aline) #dotRe = re.compile(r"\.(.+?)\s*=\(.+?\)({.+?})\s*,") dotRe = re.compile(r"\.(.+?)\s*=\s*(.*?)\s*,") dotCodecTagRe = re.compile(r".codec_tag\s*=\s*\(.*?\)\s*({.*})\s*,") def processDotLine(self, aline): dot_mo = self.dotRe.match(aline) nameOfdot = dot_mo.group(1) valueOfDot = dot_mo.group(2) self.valueIdx = self.IOCVariableName.index(nameOfdot) if nameOfdot == "codec_tag": dot_moct = self.dotCodecTagRe.match(aline) valueOfDot = dot_moct.group(1) valueOfDot = self.processCodecTag(valueOfDot) return valueOfDot+ ",\n" def processNormalLIne(self, aline): normalValue = aline.strip(',') findcodectag = 0 try: findcodectag = self.valueIdx == self.IOCVariableName.index("codec_tag") except: print "codec_tag execept" if findcodectag == 1: normalValue = self.processCodecTag(normalValue) return normalValue + ",\n" def processCodecTag(self, valueofDot): ctname = "ct_"+self.avname self.newblockHeader = "static const struct AVCodecTag * const ct_{0} [] = {1};".format(ctname, valueofDot) + "\n" return ctname def dbsub(self): newtxt = self.re_dbblock.sub(self.repfuction, self.txt) #print newtxt self.fpnew.write(newtxt) def repfuction(self, mo): substr = self.newblocks[self.matchIdx] self.matchIdx += 1 return substr def test(): fpold = open(r"J:\svkwork\ffmpeg2\libavformat\asf-enc.c") fpnew = open(r"J:\svkwork\ffmpeg2\libavformat\new\asf-enc.c", "w") fs = FFmpegVC(fpold, fpnew, "asf-enc.c").run() print "finished" def main(): ori_fm = r"J:\svkwork\ffmpeg\ffmpeg_ori\libavformat" mod_fm = r"J:\svkwork\ffmpeg\ffmpeg_mod\libavformat" ori_codec = r"J:\svkwork\ffmpeg\ffmpeg_ori\libavcodec" mod_codec = r"J:\svkwork\ffmpeg\ffmpeg_mod\libavcodec" filecoll = os.listdir(ori_fm) for fl in filecoll: fullfilename = os.path.join(ori_fm, fl) if os.path.isfile(fullfilename) and os.path.splitext(fl)[1] == ".c" : fpold = open(fullfilename) fs = FFmpegVC(fpold, mod_fm, fl).run() filecoll = os.listdir(ori_codec) for fl in filecoll: fullfilename = os.path.join(ori_codec, fl) if os.path.isfile(fullfilename) and os.path.splitext(fl)[1] == ".c" : fpold = open(fullfilename) try: fs = FFmpegVC(fpold, mod_fm, fl).run() except: print "errro" print "finish" if __name__ == "__main__": main()
Python
#!/usr/bin/env python import os import sys import string import re import StringIO import copy AVOF_name = [ "name", "long_name", "mime_type", "extensions", "priv_data_size", "audio_codec", "video_codec", "write_header", "write_packet", "write_trailer", "flags", "set_parameters", "interleave_packet", "codec_tag", "subtitle_codec", "next", ] AVOF_vaule = [ "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "CODEC_ID_NONE,\n", "CODEC_ID_NONE,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "CODEC_ID_NONE,\n", "0,\n", ] AVIF_name = [ "name", "long_name", "priv_data_size", "read_probe", "read_header", "read_packet", "read_close", "read_seek", "read_timestamp", "flags", "extensions", "value", "read_play", "read_pause", "codec_tag", "next", ] AVIF_vaule =[ "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", "0,\n", ] AVCodecName =[ "name", "type", "id", "priv_data_size", "init", "encode", "close", "decode", "capabilities", "next", "flush", "supported_framerates", "pix_fmts", "long_name", "supported_samplerates", "sample_fmts", "channel_layouts", ] AVCodecVaule = [ "0,", "CODEC_TYPE_UNKNOWN,", "CODEC_ID_NONE,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", "0,", ] "AVOutputFormat","AVInputFormat","AVCodec" iovname = {"AVOutputFormat":AVOF_name, "AVInputFormat":AVIF_name, "AVCodec":AVCodecName } iovvalue = {"AVOutputFormat":AVOF_vaule, "AVInputFormat":AVIF_vaule, "AVCodec":AVCodecVaule } class FFmpegException(Exception): pass class FFmpegVC: def __init__(self, fpold, modpath, filename): self.fpold = fpold self.modpath = modpath self.fpnew = None self.txt = "" self.filename = filename self.codectagBock="" self.conditionFlag = 0 self.conditionBlock ="" self.avname = "" self.avtype = "" self.newblocks= [] # all blocks in one page self.newblock = "" # one block content self.newblockHeader = "" # if there is content about other like codec_tag self.newblcokName = "" # like "AVOutputFormat mymux = { \n" self.logfile = r"c:\ffmpeg.py.log.txt" self.log = open(self.logfile, "a") self.valueIdx = 0 self.valueDefault = [] # the whole content between the top level '{' and '}', which define a mux/demux/en/decode self.IOCVariableName = [] # one of AVOF_name ,AVIF_name ,AVCodecName list self.matchIdx = 0 self.lineHeader = " " self.dummy = " "#just dummy self.comment = "/* boirs@gmaildotcom .python */" re_dbblock = re.compile(r"(\b(AVInputFormat|AVOutputFormat|AVCodec)\b\s*([^=]*?)=\s*?{\s*(.*?)\s*?})\s*?;", re.DOTALL) av_type_lst = ["AVOutputFormat","AVInputFormat","AVCodec"] def run(self): self.txt = self.fpold.read() matchdb = self.re_dbblock.finditer(self.txt) if matchdb: self.fpnew = open(os.path.join(self.modpath, self.filename), "w") for db in matchdb: newdb = self.buildNewDB(db) self.newblocks.append(newdb) self.dbsub() self.fpnew.close() self.fpold.close() self.log.close() regex_remove_comment = re.compile(r"/\*.*?\*/|//.*?$", re.MULTILINE|re.DOTALL) def buildNewDB(self, olddb): wholedb = olddb.group(1) # the whole block self.avtype = olddb.group(2) # O or I? self.avname = olddb.group(3) # like my_mux self.newblcokName = self.avtype + " " +self.avname + "= {\n" dbdata = olddb.group(4) dbdata = self.regex_remove_comment.sub("", dbdata) strFile = StringIO.StringIO(dbdata) self.valueDefault = copy.copy(iovvalue[self.avtype]) self.IOCVariableName = iovname[self.avtype] #print self.IOCVariableName.index("name") self.valueIdx = 0 for line in strFile: afterCheckEmpty = line.strip() if not afterCheckEmpty: continue if afterCheckEmpty[0] != '#':#debug bool0 = afterCheckEmpty.count("[") == afterCheckEmpty.count("]") bool1 = afterCheckEmpty.count("(") == afterCheckEmpty.count(")") bool2 = afterCheckEmpty.count("{") == afterCheckEmpty.count("}") bool3 = afterCheckEmpty.count('"')%2 == 0 bool4 = afterCheckEmpty.rfind(',') == len(afterCheckEmpty) - 1 boolall = [bool0, bool1, bool2, bool3, bool4] if not all(boolall): self.log.write(self.filename) self.log.write(self.avname) self.log.write(dbdata) print self.filename + " has an error" indexxxx = 0 for item in boolall: if not item: print indexxxx else: indexxxx += 1 raise FFmpegException, " error " #process line by line avalue = "" if str(afterCheckEmpty[0:3]) == '#if': self.conditionFlag = 1 if self.conditionFlag == 1: if str(afterCheckEmpty[0:3]) == '#if': #if self.conditionBlock = "" self.conditionBlock += afterCheckEmpty + "\n" elif str(afterCheckEmpty[0:3]) == '#el': # #elif |#else self.conditionBlock += afterCheckEmpty + "\n" elif str(afterCheckEmpty[0:4]) == '#end': ##end self.conditionBlock += afterCheckEmpty + "\n" self.conditionFlag = 0 self.valueDefault[self.valueIdx] = self.conditionBlock self.valueIdx += 1 else: avalue = self.processLine(afterCheckEmpty) self.conditionBlock += avalue else: avalue = self.processLine(afterCheckEmpty) self.valueDefault[self.valueIdx] = avalue self.valueIdx += 1 tempValueDefault = "" vr = range(self.valueIdx) for item in vr: tempValueDefault += self.valueDefault[item] the_whole_new_block = self.newblockHeader + self.newblcokName + tempValueDefault + "};\n" #print the_whole_new_block return the_whole_new_block def processLine(self, aline): if aline[0] == '.': return self.processDotLine(aline) else: return self.processNormalLIne(aline) #dotRe = re.compile(r"\.(.+?)\s*=\(.+?\)({.+?})\s*,") dotRe = re.compile(r"\.(.+?)\s*=\s*(.*?)\s*,") dotCodecTagRe = re.compile(r".codec_tag\s*=\s*\(.*?\)\s*({.*})\s*,") def processDotLine(self, aline): dot_mo = self.dotRe.match(aline) nameOfdot = dot_mo.group(1) valueOfDot = dot_mo.group(2) self.valueIdx = self.IOCVariableName.index(nameOfdot) if nameOfdot == "codec_tag": dot_moct = self.dotCodecTagRe.match(aline) valueOfDot = dot_moct.group(1) valueOfDot = self.processCodecTag(valueOfDot) return valueOfDot+ ",\n" def processNormalLIne(self, aline): normalValue = aline.strip(',') findcodectag = 0 try: findcodectag = self.valueIdx == self.IOCVariableName.index("codec_tag") except: print "codec_tag execept" if findcodectag == 1: normalValue = self.processCodecTag(normalValue) return normalValue + ",\n" def processCodecTag(self, valueofDot): ctname = "ct_"+self.avname self.newblockHeader = "static const struct AVCodecTag * const ct_{0} [] = {1};".format(ctname, valueofDot) + "\n" return ctname def dbsub(self): newtxt = self.re_dbblock.sub(self.repfuction, self.txt) #print newtxt self.fpnew.write(newtxt) def repfuction(self, mo): substr = self.newblocks[self.matchIdx] self.matchIdx += 1 return substr def test(): fpold = open(r"J:\svkwork\ffmpeg2\libavformat\asf-enc.c") fpnew = open(r"J:\svkwork\ffmpeg2\libavformat\new\asf-enc.c", "w") fs = FFmpegVC(fpold, fpnew, "asf-enc.c").run() print "finished" def main(): ori_fm = r"J:\svkwork\ffmpeg\ffmpeg_ori\libavformat" mod_fm = r"J:\svkwork\ffmpeg\ffmpeg_mod\libavformat" ori_codec = r"J:\svkwork\ffmpeg\ffmpeg_ori\libavcodec" mod_codec = r"J:\svkwork\ffmpeg\ffmpeg_mod\libavcodec" filecoll = os.listdir(ori_fm) for fl in filecoll: fullfilename = os.path.join(ori_fm, fl) if os.path.isfile(fullfilename) and os.path.splitext(fl)[1] == ".c" : fpold = open(fullfilename) fs = FFmpegVC(fpold, mod_fm, fl).run() filecoll = os.listdir(ori_codec) for fl in filecoll: fullfilename = os.path.join(ori_codec, fl) if os.path.isfile(fullfilename) and os.path.splitext(fl)[1] == ".c" : fpold = open(fullfilename) try: fs = FFmpegVC(fpold, mod_fm, fl).run() except: print "errro" print "finish" if __name__ == "__main__": main()
Python
import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import memcache import dbmodels import os import json import datetime import calgen import math import logging import time import pickle from utilities import * import views from google.appengine.ext.webapp import template from dbmodels import Partner, Project, Site, Volunteer, Settings, Calendar from StringIO import StringIO class Show(webapp2.RequestHandler): def get(self): t1 = time.time() v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = "assignments.html"# views.assignments logging.info(v.pageinfo.html) v.pageinfo.title = "Calendar" v.params = TemplateValues() calendar = Calendar.get_by_key_name("main") v.calendar = sorted(pickle.loads(calendar.data)) v.caption = "Calendar was generated {} at {}.".format({True: "manually", False: "automatically"}[calendar.manual], calendar.timestamp) logging.info(v.caption) new_assignments = dbmodels.NewAssignment.all() for i, week in enumerate(v.calendar): for assignment in new_assignments: if assignment.assignment.start_date.date() <= week[0] <= assignment.assignment.end_date.date() - datetime.timedelta(days=7): v.calendar[i][1].append(assignment.assignment) v.calendar[i][1].sort(key=lambda a: (a.project_name, a.start_date,a.end_date)) path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Form(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.assignmentForm v.pageinfo.title = "Assignment Form" v.weeks = range(2,52) origin = self.request.get('origin') if origin == "calendar": v.project = Project.get(self.request.get('project')) v.calsites = Site.all() v.calsites.filter("project =", v.project.key()) v.site = Site.get(self.request.get('site')) v.start_date = self.request.get('start_date') v.sites = dbmodels.Site.all() v.projects = dbmodels.Project.all() v.volunteers = Volunteer.all() else: vkey = self.request.get('vkey') akey = self.request.get('akey') if akey == '': pass else: v.assignment = dbmodels.Assignment.get(akey) v.vkey = vkey v.volunteer = dbmodels.Volunteer.get(vkey) v.sites = dbmodels.Site.all() v.projects = dbmodels.Project.all() path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): akey = self.request.get('akey') vkey = self.request.get('vkey') # print self.request partnerkey = self.request.get('partnerkey') if akey == '': assignment = dbmodels.Assignment() assignment.reg_date = datetime.datetime.now() assignment.volunteer = dbmodels.Volunteer.get(self.request.get('vkey')) else: assignment = dbmodels.Assignment.get(akey) sd = [ int(x) for x in self.request.get('start_date').split("-")] ed = [ int(x) for x in self.request.get('end_date').split("-")] assignment.partner = dbmodels.Partner.get(partnerkey) assignment.project = dbmodels.Project.get(self.request.get('project')) assignment.project_name = assignment.project.name assignment.partner_name = assignment.partner.name assignment.volunteer_name = assignment.volunteer.name # assignment.site = dbmodels.Site.get(self.request.get('site')) assignment.start_date = datetime.datetime(*sd) assignment.end_date = datetime.datetime(*ed) logging.info("--------"+self.request.get('weeks')) assignment.num_weeks = int(self.request.get('weeks')) logging.info("++++++++"+str(assignment.num_weeks)) assignment.comment = self.request.get('comment') # assignment.discount = float(self.request.get('discount')) assignment.put() if akey == '': new_assignment = dbmodels.NewAssignment() new_assignment.assignment = assignment # new_assignment.assignment_id = assignment.key() new_assignment.put() months = (assignment.end_date - assignment.start_date).days/30 year = assignment.start_date.year month = assignment.start_date.month #Delete memcache for each calendar month this assignment should #Appear in while months >= 0: cache_name = "calendar:{}:{}".format(year, month) logging.info("deleting cache: {}".format(cache_name)) memcache.delete(cache_name) month += 1 if month == 13: month = 0 year += 1 months -= 1 memcache.delete("assignment:volunteer:%s" % vkey) logging.info( str(assignment.start_date)+" "+ str(assignment.end_date)) self.redirect('/volunteerForm?key=' + vkey) class Delete(webapp2.RequestHandler): def get(self): akey = self.request.get('akey') vkey = self.request.get('vkey') assignment = dbmodels.Assignment.get(akey) new_assignment = db.GqlQuery("SELECT __key__ FROM NewAssignment WHERE assignment = :1", assignment.key()) db.delete(new_assignment) db.delete(assignment) self.response.out.write(akey+"<br>") self.response.out.write(vkey+"<br>") self.redirect('/volunteerForm?key=' + vkey) class ajaxAssignment(webapp2.RequestHandler): def get(self): start_date = self.request.get('start_date') end_date = self.request.get('end_date') project = dbmodels.Project.get(self.request.get('project')) site = dbmodels.Site.get(self.request.get('site')) respData = [] assignments = dbmodels.Assignment.get_all() assignments.filter("site = ", site) # assignments.filter("start_date >=", # datetime.datetime(*[int(x) for x in self.request.get('start_date').split("-")])) # assignments.filter("end_date <=", # datetime.datetime(*[int(x) for x in self.request.get('end_date').split("-")])) # assignments.filter("project =", project) # assignments.filter("site =", site) if assignments.count(1000) > 0: for a in assignments: respData.append({ "vname" : "%s, %s" % (a.volunteer.lname, a.volunteer.fname), "start_date" : a.start_date_str, "end_date" : a.end_date_str, "duration" : str(a.duration) }) else: respData.append("No Assignments") respData.append(site.capacity) self.response.headers['Content-Type'] = "application/json" self.response.out.write(json.dumps(respData)) class ajaxComment(webapp2.RequestHandler): def get(self): assignmentid = self.request.get('assignmentid') comment = self.request.get('comment') assignment = dbmodels.Assignment.get(assignmentid) assignment.comment = comment assignment.put() self.response.headers['Content-Type'] = "application/json" self.response.out.write(json.dumps({"message":""}))
Python
import webapp2 from google.appengine.ext import db import dbmodels import os from utilities import * import views import logging from google.appengine.ext.webapp import template import logging class Show(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.settings v.pageinfo.title = "Settings" v.saved = self.request.get('saved') == '1' v.calendar = dbmodels.Calendar.get_by_key_name("main") v.settings = db.get(db.Key.from_path('Settings', 'main')) path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) logging.info(template.render( "views/"+views.settings, {})) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): request = self.request settings = dbmodels.Settings.get(db.Key.from_path("Settings", "main")) logging.info(settings) logging.info(type(request.get('companyName'))) if not settings: settings = dbmodels.Settings(key_name="main") settings.companyName = request.get(u'companyName') settings.companyAddress = request.get('companyAddress') settings.companyPhone1 = request.get('companyPhone1') settings.companyPhone2 = request.get('companyPhone2') settings.bankName = request.get('bankName') settings.bankAddress = request.get('bankAddress') settings.bankAcctName = request.get('bankAcctName') settings.bankAcctNum = request.get('bankAcctNum') settings.routingNumber = request.get('routing_number') settings.swiftCode = request.get('swift_code') logging.info(settings.bankAcctNum) settings.email = request.get('email') settings.sdin = request.get('sdin') settings.sales_tax = float(request.get('sales_tax')) settings.num_months = int(request.get('num_months')) settings.put() self.redirect('/settings?saved=1')
Python
countries= [ "United States", "United Kingdom", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, The Democratic Republic of The", "Cook Islands", "Costa Rica", "Cote D'ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-bissau", "Guyana", "Haiti", "Heard Island and Mcdonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", "Saint Vincent and The Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and The South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Timor-leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", "Virgin Islands, British", "Virgin Islands, U.S.", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"]
Python
from google.appengine.ext import db import calendar import datetime from dbmodels import Assignment, Site import logging class Month(): names = [ "January","February","March","April","May","June", "July","August","September","October","November","December"] def __init__(self, year, month, request): self.month = month self.name = self.names[month-1] self.year = year self.calendar = calendar.Calendar(0) self.weeks = [] self.request = request def addWeek(self, week): self.weeks.append(week) def populate(self): # country = self.request.get("country") # partner = self.request.get("partner") # project = self.request.get("project") # site = self.request.get("site") oneweek = datetime.timedelta(days=7) weeks = [x[0] for x in self.calendar.monthdatescalendar(self.year, self.month) if x[0].month == self.month] a_query = Assignment.get_all()#_all() a_query.filter("end_date >", weeks[0]) for week in weeks: a_query.filter("end_date >", week).order("end_date") # a_query = db.GqlQuery("SELECT * FROM Assignment WHERE start_date < :1 ORDER BY start_date, end_date DESC", week + oneweek) assignments = [a for a in a_query] assignments = filter(lambda a: week >= a.start_date.date(), assignments) # if country: # assignments = filter(lambda a: a.site.country == country, assignments) # if partner: # assignments = filter(lambda a: unicode(a.partner.key()) == unicode(partner), assignments) # if project: # assignments = filter(lambda a: unicode(a.project.key()) == unicode(project), assignments) # if site: # assignments = filter(lambda a: unicode(a.site.key()) == unicode(site), assignments) if len(assignments) > 0: # assignments = sorted(assignments, key=lambda a: a.site.country) assignments = sorted(assignments, key=lambda a: a.project.name) new_week = Week(week) new_week.setAssignments(assignments) self.addWeek(new_week) class Week(): def __init__(self, week): self.week = week self.strweek = week.strftime("%Y-%m-%d") self.oneweek = datetime.timedelta(days=7) self.__assignments = [] def setAssignments(self, assignments): oneweek = datetime.timedelta(days=7) self.__assignments = assignments for a in self.__assignments: a.weeks_remaining = ((a.end_date.date() - self.week).days + 1)/7 a.first_week = (self.week + oneweek) >= a.start_date_date >= self.week a.last_week = (self.week + oneweek) >= a.end_date_date >= self.week @property def assignments(self): return self.__assignments
Python
#from google.appengine.ext import webapp import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import db import dbmodels import os import datetime from utilities import * import views import json import logging from google.appengine.ext.webapp import template from dateutil.relativedelta import relativedelta import logging import urllib from google.appengine.api import urlfetch from google.appengine.api import app_identity class Show(webapp2.RequestHandler): def get(self): logging.info("invoices.Show.get") v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.invoices v.pageinfo.title = "Invoices" v.invoices = dbmodels.Invoice.all() v.invoices.order("partner").order("date") v.invoices = v.invoices.fetch(1000) v.saved = self.request.get('saved') == 'true' path = os.path.join(os.path.dirname(__file__), views.main) logging.info(path) for i in v.invoices: logging.info(i.key()) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path,{"v":v})) class Form(webapp2.RequestHandler): def get(self): """ This just loads the page. The content is retrieved with an ajax request from in invoice.js """ logging.info("invoices.Form.get") v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.invoiceForm ikey = self.request.get('ikey') if ikey: v.invoice = dbmodels.Invoice.get(ikey) v.partner = v.invoice.partner v.pageinfo.title = "Invoice for %s %s" % (v.invoice.partner.name, v.invoice.date.date()) logging.info( ikey) else: logging.info("no ikey") key = self.request.get('key') v.partner = dbmodels.Partner.get(key) v.pageinfo.title = "Invoice for %s" % v.partner.name path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class JSON(webapp2.RequestHandler): def get(self): options = {"start_date": self.request.get('start_date'), "end_date" : self.request.get('end_date'), "partnerkey" : self.request.get('partnerkey'), "invoiced" : self.request.get('invoiced'), "alldates" : self.request.get('alldates')} start_date = self.request.get('start_date') end_date = self.request.get('end_date') partnerkey = self.request.get('partnerkey') invoiced = self.request.get('invoiced') alldates = self.request.get('alldates') p = dbmodels.Partner.get(partnerkey) invoicekey = self.request.get('invoicekey') on_invoice = [] if invoicekey: i = dbmodels.Invoice.get(invoicekey) on_invoice = [str(k) for k in i.akeys] assignments = dbmodels.Assignment.all() if invoiced != "checked": assignments.filter("invoiced =", False) assignments.order("start_date").order("end_date")#.order("volunteer.lname") assignments.filter("partner =", p.key()) if alldates != "checked": logging.info(start_date) start_date = strtodt(start_date) logging.info(start_date) end_date = strtodt(end_date) + relativedelta(day=1, months=1) logging.info((start_date, end_date)) assignments.filter("start_date >=", start_date) # assignments.filter("start_date <", end_date) assignments = [a.jsonAssignment for a in assignments] assignments.sort(lambda a,b: cmp(a['volunteer'].lower(),b['volunteer'].lower())) logging.info(assignments) for i, assignment in enumerate(assignments): if i > 0: if assignment['volunteer'] == assignments[i-1]['volunteer']: assignments[i]['price'] = assignment['additionalWeekPrice'] * assignment['minimum_duration'] assignments[i]['is_additional'] = True else: assignments[i]['is_additional'] = False logging.info(i) logging.info(assignment) logging.info("--------") jsonResponse = {"assignments":assignments, "on_invoice": on_invoice } self.response.out.write(json.dumps(jsonResponse)) class Save(webapp2.RequestHandler): def post(self): akeys = map(lambda x: x[5:],filter( lambda x: x[0:5] == "akey:",self.request.params))#self.request.get("akeys").split(":") assignments = dbmodels.Assignment.get(akeys) invoicekey = self.request.get('invoicekey') if invoicekey: invoice = dbmodels.Invoice.get(invoicekey) logging.info("editting invoice") else: invoice = dbmodels.Invoice() logging.info("creating new invoice") invoice.partner = dbmodels.Partner.get(self.request.get('partnerkey')) invoice.date = datetime.datetime.now() keys = [] for a in assignments: a.invoiced = True a.invoiceDate = datetime.datetime.now() keys.append(a.key()) a.put() invoice.akeys = keys invoice.comment = self.request.get("comment") invoice.discount = float(self.request.get("discount")) invoice.fees = float(self.request.get("fees")) invoice.put() logging.info(invoice) self.redirect("/partnerForm?key=%s&saved=true" % str(invoice.partner.key())) class Delete(webapp2.RequestHandler): def get(self): logging.info("invoices.Delete.get") ikey = self.request.get('ikey') invoice = dbmodels.Invoice.get(ikey) pkey = invoice.partner.key() invoice.delete() self.redirect("/partnerForm?key="+str(pkey)) class Generate(webapp2.RequestHandler): def get(self): docname = self.request.get('docname') scope = "https://script.google.com/macros/s/AKfycbxAIMNcXOcTnlz3MS-AAeqJ_iGpPVDogFd9l80u8qEC/dev" authorization_token, _ = app_identity.get_access_token(scope) result = urlfetch.fetch( url="https://script.google.com/macros/s/AKfycbwKLckJael18kaWSQFazXExzsSTSwrlRglbOAKWuuMQ4-nae_ra/exec", payload=urllib.urlencode({"docname":docname}), method=urlfetch.POST, follow_redirects=False, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if result.status_code == 200: logging.info(result.content) self.response.out.write(result.content) else: self.response.out.write(result.status_code)
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #import atom import sys #sys.path.insert(0, "reportlab.zip") from google.appengine.ext import webapp import webapp2 import dbmodels #import volunteers, partners, projects, sites, assignments, api, pdftest, settings, invoices import reportlab import os, sys from google.appengine.ext.webapp import template, util from utilities import * from dbmodels import * from csv import writer import StringIO import zipfile import reportlab import datetime import logging import random from google.appengine.api import users class MainHandler(webapp2.RequestHandler): def get(self): user = users.get_current_user() if user: self.redirect("/calendar") else: self.redirect(users.create_login_url("/")) class Dump(webapp2.RequestHandler): def get(self): tables = [Partner.all(), Volunteer.all(), Project.all(), Site.all(), Assignment.all(), Invoice.all()] out = StringIO.StringIO() z = zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) date = datetime.datetime.now() for table in tables: model = str(table._model_class).replace("<","").replace(">","").replace("class", "").replace(" ", "").replace("'","") fn = "%s.%s.xml" % (model, date.strftime("%Y-%m-%d")) dio = StringIO.StringIO() dio.write("<?xml version='1.0' encoding='ISO-8859-1'?><%ss date='%s'>" % (model, date.strftime("%Y-%m-%d"))) for row in table: dio.write(row.to_xml()) dio.write("</%ss>" % model) z.writestr(fn, dio.getvalue()) z.close() out.seek(0) self.response.headers.add_header("Content-type", "application/zip") self.response.headers.add_header("Content-disposition", 'attachment; filename=ffabackup.zip') self.response.out.write( out.read()) class API(webapp2.RequestHandler): def get(self, id): self.response.out.write(id) def name(): letters = "abcdefghijklmnopqrstuvwxyz" name = "".join([ random.choice(letters) for i in range(0, random.randint(5,10))]) return name class GenData(webapp2.RequestHandler): def get(self): partners = [] while True: paname = name() p = dbmodels.Partner(name=paname, abbr=paname[:2], comment=paname+" "+paname, address="here\nthere\neverywhere") p.put() partners.append(p) if random.random() <.05: break logging.info(partners) projects = [] while True: prname = name() price = 1000+(1000*random.random()) pr = dbmodels.Project(name=prname, abbr=prname[:2], price=price, additionalWeekPrice=price*.1, minimum_duration=2, comment="No Comment") pr.put() projects.append(pr) if random.random() < .05: break volunteers = [] while True: vol = dbmodels.Volunteer() vol.fname = name() vol.lname = name() vol.country = random.choice(("US", "CA", "FR", "DE", "NE", "EN")) vol.DOB = datetime.datetime(random.randint(1970, 1985), random.randint(1,12), random.randint(1,27)) vol.email = vol.fname+vol.lname+"@"+name()+".com" vol.partner = random.choice(partners) vol.address = "Here\nThere\nEverywhere" vol.emergency = "!!!" vol.comment = "---" vol.status = "OK" vol.put() volunteers.append(vol) if random.random() < .02: break for v in volunteers: while True: a = dbmodels.Assignment() a.volunteer = v a.project = random.choice(projects) a.project_name = a.project.name a.volunteer_name = a.volunteer.name a.partner = v.partner a.partner_name = v.partner.name now = datetime.datetime.now() delta = datetime.timedelta(days=now.weekday()) basedate = now-delta a.start_date = basedate + datetime.timedelta(weeks=random.randint(0, 10)) a.end_date = a.start_date + datetime.timedelta(weeks=random.randint(2,20)) a.num_weeks = (a.end_date - a.start_date).days / 7 a.put() n = dbmodels.NewAssignment() n.assignment = a n.put() if random.random > 0.05: break routes= [ ('/', MainHandler), webapp2.Route('/calendar', handler="assignments.Show"), webapp2.Route('/volunteers', handler="volunteers.Show", name="volunteers"), webapp2.Route('/volunteersNew', handler="volunteers.ShowNew", name="volunteersNew"), webapp2.Route('/volunteerForm', handler="volunteers.Form", name="volunteerForm"), webapp2.Route('/volunteerEdit', handler="volunteers.Edit", name="volunteerEdit"), webapp2.Route('/volunteerDelete', handler="volunteers.Delete", name="volunteerDelete"), webapp2.Route('/volunteerCreateCache', handler="volunteers.CreateCache", name="volunteerCreateCache") , webapp2.Route('/volunteerRetrieveCache', handler="volunteers.RetrieveCache", name="volunteerRetrieveCache"), webapp2.Route('/partners', handler="partners.Show"), webapp2.Route('/partnerForm', handler="partners.Form"), webapp2.Route('/partnerEdit', handler="partners.Edit"), webapp2.Route('/partnerDelete', handler="partners.Delete"), webapp2.Route('/invoiceGen', handler="invoices.Generate"), webapp2.Route('/invoices', handler="invoices.Show"), webapp2.Route('/invoiceForm', handler="invoices.Form"), webapp2.Route('/invoiceView', handler="invoices.View"), webapp2.Route('/invoiceJSON', handler="invoices.JSON"), webapp2.Route('/invoiceSave', handler="invoices.Save"), webapp2.Route('/invoiceDelete', handler="invoices.Delete"), webapp2.Route('/projects', handler="projects.Show"), webapp2.Route('/projectForm', handler="projects.Form"), webapp2.Route('/projectEdit', handler="projects.Edit"), webapp2.Route('/projectDelete', handler="projects.Delete"), webapp2.Route('/siteForm', handler="sites.Form"), webapp2.Route('/siteEdit', handler="sites.Edit"), webapp2.Route('/siteDelete', handler="sites.Delete"), webapp2.Route('/assignments', handler="assignments.Show"), webapp2.Route('/assignmentForm', handler="assignments.Form"), webapp2.Route('/assignmentEdit', handler="assignments.Edit"), webapp2.Route('/assignmentDelete', handler="assignments.Delete"), webapp2.Route('/ajaxAssignment', handler="assignments.ajaxAssignment"), webapp2.Route('/ajaxComment', handler="assignments.ajaxComment"), webapp2.Route('/dump', Dump), ('/api/(.+)', API),#"api.Api"), webapp2.Route('/pdf', handler="pdftest.PDF"), webapp2.Route('/settings', handler="settings.Show"), webapp2.Route('/settingsEdit', handler="settings.Edit"), webapp2.Route('/tasks/calgen', handler="tasks.calgen.Run"), webapp2.Route('/gendata', handler=GenData) ] app = webapp2.WSGIApplication( routes, config = { "ADD_PARTNER" : False }, debug=True) # util.run_wsgi_app(app) #if __name__=="__main__": # main()
Python
#from google.appengine.ext import webapp import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import memcache import dbmodels import os import datetime import logging from utilities import * import views from google.appengine.ext.webapp import template class Show(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.projects v.pageinfo.title = "Projects" v.projects = dbmodels.Project.all()#_all() path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Form(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.projectForm v.pageinfo.title = "Project Form" key = self.request.get('key') if key == '': pass else: v.project = dbmodels.Project.get(key) v.project.sites.order('country') v.project.sites.order('name') path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): memcache.delete("project:all") key = self.request.get('key') if key == '': project = dbmodels.Project() else: project = dbmodels.Project.get(key) project.name = self.request.get('name') project.abbr = self.request.get('abbr') project.price = float(self.request.get('price')) project.additionalWeekPrice = float(self.request.get('additionalWeekPrice')) project.minimum_duration = int(self.request.get('minimum_duration')) project.comment = self.request.get('comment') db.put(project) memcache.delete("project:all") self.redirect('/projects') class Delete(webapp2.RequestHandler): def get(self): key = self.request.get('key') project = dbmodels.Project.get(key) sites = project.sites db.delete(sites) db.delete(project) memcache.delete("project:all") self.redirect('/projects')
Python
import datetime from google.appengine.ext import db from google.appengine.datastore import entity_pb from google.appengine.api import users from google.appengine.api import memcache import logging import webapp2 class Calendar(db.Model): data = db.BlobProperty() timestamp = db.DateTimeProperty() manual = db.BooleanProperty() class Cache(db.Model): data = db.BlobProperty() timestamp = db.DateTimeProperty() manual = db.BooleanProperty() class Partner(db.Model): name = db.StringProperty() abbr = db.StringProperty() comment = db.TextProperty() address = db.TextProperty() feed_uri = db.StringProperty() @property def activeVolunteers(self): cacheKey = "partner:volunteer:active:%s" % self.key() activeVolunteers = memcache.get(cacheKey) if activeVolunteers is None: logging.info("creating cache: " + cacheKey) activeVolunteers = [v for v in self.volunteers if v.active_assignments > 0] memcache.add(cacheKey, activeVolunteers) else: logging.info("using cache: " + cacheKey) return activeVolunteers @property def allVolunteers(self): cacheKey = "partner:volunteer:all:%s" % self.key() allVolunteers = memcache.get(cacheKey) if allVolunteers is None: logging.info("creating cache: " + cacheKey) allVolunteers = [a for a in self.volunteers.order("lname")] memcache.add(cacheKey, allVolunteers) else: logging.info("using cache: " + cacheKey) return allVolunteers @classmethod def get_all(cls, added): cacheKey = "partner:all" logging.info("Added = " + str(added)) allPartners = memcache.get(cacheKey) if allPartners is None or added: logging.info("creating cache: " + cacheKey) allPartners = cls.all() memcache.add(cacheKey, allPartners) return allPartners class Volunteer(db.Model): fname = db.StringProperty() lname = db.StringProperty() country = db.StringProperty() DOB = db.DateTimeProperty() email = db.EmailProperty() partner = db.ReferenceProperty(reference_class=Partner, collection_name="volunteers") address = db.TextProperty() emergency = db.TextProperty() invoiced = db.BooleanProperty(default=False) comment = db.TextProperty() # not in calender status = db.TextProperty() # This is on calender and includes info about paperwork @classmethod def get_all(cls): cacheKey = "volunteer:all" allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all().order('lname') allInstances = [a for a in allInstances] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances @classmethod def get_active(cls): cacheKey = "volunteer:active" allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all() allInstances = [a for a in allInstances if a.active_assignments > 0] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances @classmethod def get_for_partner(cls, partnerkey): cacheKey = "volunteers_for_partner:%s" % partnerkey allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all() allInstances.filter("partner =", partnerkey) allInstances = [a for a in allInstances] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances @property def name(self): return "%s, %s" % (self.lname, self.fname) @property def active_assignments(self): return self.assignments.filter("end_date >=", datetime.datetime.now()).count() @property def json(self): pass class NewVolunteer(db.Model): volunteer = db.ReferenceProperty(reference_class=Volunteer) class Project(db.Model): name = db.StringProperty() abbr = db.StringProperty() price = db.FloatProperty() additionalWeekPrice = db.FloatProperty() minimum_duration = db.IntegerProperty() sales_tax = db.FloatProperty(default=.075) comment = db.TextProperty() @classmethod def get_all(cls): cacheKey = "project:all" allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = [a for a in cls.all()] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances class Site(db.Model): name = db.StringProperty() abbr = db.StringProperty() project = db.ReferenceProperty(reference_class=Project, collection_name="sites") country = db.StringProperty() capacity = db.IntegerProperty() comment = db.TextProperty() @classmethod def get_all(cls): cacheKey = "site:all" allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = [a for a in cls.all()] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances class Assignment(db.Model): volunteer = db.ReferenceProperty(reference_class=Volunteer, collection_name="assignments") partner = db.ReferenceProperty(reference_class=Partner, collection_name="assignments") project = db.ReferenceProperty(reference_class=Project, collection_name='assignments') project_name = db.StringProperty(default=None) partner_name = db.StringProperty(default=None) volunteer_name = db.StringProperty(default=None) site = db.ReferenceProperty(reference_class=Site) start_date = db.DateTimeProperty() end_date = db.DateTimeProperty() num_weeks = db.IntegerProperty() #do something with this booking_date = db.DateTimeProperty() invoiceDate = db.DateTimeProperty() discount = db.FloatProperty() invoiced = db.BooleanProperty(default=False) comment = db.TextProperty() expired = db.BooleanProperty(default=False) @classmethod def get_all(cls): cacheKey = "assignment:all" allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all() memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances @classmethod def get_all_for_volunteer(cls, vkey): cacheKey = "assignment:volunteer:%s" % vkey allInstances = memcache.get(cacheKey) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all().filter("volunteer =", vkey).order("start_date") memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances @property def projectName(self): return self.project.name @property def jsonAssignment(self): duration = self.duration.days / 7.0 return { "volunteer" : "%s, %s" % (self.volunteer.lname, self.volunteer.fname), "project" : self.project.name, "minimum_duration" : self.project.minimum_duration, # "site" : self.site.name, "start_date" : self.start_date_str, "end_date" : self.end_date_str, "num_weeks" : (self.end_date - self.start_date).days / 7.0, "duration" : duration, "additionalWeeks" : duration - 2, "price" : float(self.project.price), "additionalWeekPrice" : self.project.additionalWeekPrice, # "discount" : float(self.discount), "invoiced" : self.invoiced, "key" : unicode(self.key())} @property def duration(self): return self.end_date - self.start_date @property def additional_weeks(self): logging.info(str(self.num_weeks)) return self.num_weeks - 2 @property def additional_weeks_price(self): return self.project.additionalWeekPrice * self.additional_weeks @property def item_price(self): return self.project.price @property def total_price(self): return self.additional_weeks_price + self.item_price @property def start_date_str(self): return self.start_date.strftime("%Y-%m-%d")# "%d-%d-%d" % (self.start_date.year, self.start_date.month, self.start_date.day) @property def end_date_str(self): try: # return (self.end_date - datetime.timedelta(days=6)).strftime("%Y-%m-%d")#"%d-%d-%d" % (self.end_date.year, self.end_date.month, self.end_date.day - 1) return (self.start_date + datetime.timedelta(weeks=self.num_weeks-1)).strftime("%Y-%m-%d")#"%d-%d-%d" % (self.end_date.year, self.end_date.month, self.end_date.day - 1) except TypeError: return "" @property def start_date_date(self): return self.start_date.date() @property def end_date_date(self): return self.end_date.date() class NewAssignment(db.Model): assignment = db.ReferenceProperty(reference_class=Assignment) assignment_id = db.StringProperty() #used to match for deleting class Invoice(db.Model): partner = db.ReferenceProperty(reference_class=Partner, collection_name="invoices") date = db.DateTimeProperty() akeys = db.ListProperty(db.Key) comment = db.TextProperty() discount = db.FloatProperty() fees = db.FloatProperty() @classmethod def get_all(cls): allInstances = memcache.get("invoice:all") if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all() memcache.add("invoice:all", allInstances) else: logging.info("using cache: " + cacheKey) return allInstances class Settings(db.Model): companyName = db.StringProperty() companyAddress = db.PostalAddressProperty() companyPhone1 = db.PhoneNumberProperty() companyPhone2 = db.PhoneNumberProperty() logo = db.BlobProperty() bankName = db.StringProperty() bankAddress = db.PostalAddressProperty() bankAcctName = db.StringProperty() bankAcctNum = db.StringProperty() routingNumber = db.StringProperty() swiftCode = db.StringProperty() email = db.EmailProperty() sdin = db.StringProperty() sales_tax = db.FloatProperty(default=0.0) num_months = db.IntegerProperty(default=6) @classmethod def get_all(cls): cacheKey = "settings:all" allInstances = memcache.get(cacheKey) logging.info("******") logging.info(allInstances) if allInstances is None: logging.info("creating cache: " + cacheKey) allInstances = cls.all()[0] memcache.add(cacheKey, allInstances) else: logging.info("using cache: " + cacheKey) return allInstances
Python
#from google.appengine.ext import webapp import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import db import dbmodels import os import datetime from utilities import * import views from google.appengine.ext.webapp import template class Show(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = "sites.html" v.pageinfo.title = "Sites" v.sites = dbmodels.Site.get_all() path = os.path.join(os.path.dirname(__file__), 'sites.html') self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Form(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.siteForm skey = self.request.get('skey') pkey = self.request.get('pkey') if skey == '': v.pkey = pkey v.project = dbmodels.Project.get(pkey) v.pageinfo.title = "Site: %s" % (v.project.name) else: v.site = dbmodels.Site.get(skey) v.project = dbmodels.Project.get(pkey) v.pkey = pkey v.pageinfo.title = "Site: %s %s" % (v.project.name, v.site.name) path = os.path.join(os.path.dirname(__file__), views.main) # self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): skey = self.request.get('skey') pkey = self.request.get('pkey') if skey == '': site = dbmodels.Site() else: site = dbmodels.Site.get(skey) site.name = self.request.get('name') site.abbr = self.request.get('abbr') site.country = self.request.get('country') site.project = dbmodels.Project.get(pkey) site.capacity = int(self.request.get('capacity')) site.comment = self.request.get('comment') site.put() self.redirect('/projectForm?key=' + pkey) class Delete(webapp2.RequestHandler): def get(self): skey = self.request.get('skey') pkey = self.request.get('pkey') site = dbmodels.Site.get(skey) db.delete(site) self.redirect('/projectForm?key=' + pkey)
Python
from google.appengine.ext import db import calendar import datetime from dbmodels import Assignment, Site import logging import webapp2 class Run(webapp2.RequestHandler): def get(self): num_months = 3 now = datetime.datetime.now() assignment_query = Assignment.get_all() assignment_query.order("end_date") logging.info("it worked")
Python
import reportlab from reportlab.lib.pagesizes import A4, letter from reportlab.lib.units import mm, inch from reportlab.rl_config import defaultPageSize from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from reportlab.pdfgen import canvas from reportlab.lib.enums import TA_LEFT, TA_RIGHT import datetime #from google.appengine.ext import webapp import webapp2 from google.appengine.ext import db import dbmodels WIDTH, HEIGHT = defaultPageSize MARGIN_LEFT = 50 MARGIN_TOP = 75 MARGIN_RIGHT = WIDTH - MARGIN_LEFT NORMAL = "Helvetica" BOLD = "Helvetica-Bold" OBLIQUE = "Helvetica-Oblique" styles=getSampleStyleSheet() def firstPage(canvas, doc): canvas.saveState() canvas.restoreState() def laterPages(canvas, doc): canvas.saveState() canvas.setFont("Times-Roman", 9) canvas.drawString(inch, 0.75 * inch, "Page %d / %s" % (doc.page, "Friends for Asia")) canvas.restoreState() class PDF(webapp2.RequestHandler): def get(self): invoice = dbmodels.Invoice.get(self.request.get("ikey")) assignments = dbmodels.Assignment.get([str(key) for key in invoice.akeys]) # assignments = sorted(assignments, key=lambda assignment: assignment.start_date) settings = dbmodels.Settings.get(db.Key.from_path("Settings", "main")) timestamp = datetime.datetime.now() self.response.headers.add_header("Content-type", "application/pdf") self.response.headers.add_header("Content-disposition", 'attachment; filename=%s-%s.pdf' % (str(invoice.partner.name), timestamp.strftime("%Y-%m-%d"))) doc = SimpleDocTemplate(self.response.out, leftMargin=inch*.5) doc.timestamp = timestamp Story = [] style = styles["Normal"] style.spaceAfter = inch * 0.5 # style.leftIndent = -inch #* 0.5 address = Paragraph(""" <font size='24' face='Helvetica-Bold'>%s</font><br/> %s <br/> %s <br/> <font face='Helvetica-Bold'>SDIN#: %s</font>""" % (settings.companyName, settings.companyAddress.replace("\n","<br/>"), settings.email, settings.sdin), style) Story.append(address) partnerAddress = Paragraph(""" <font face='Helvetica-Bold'>%s</font><br/> %s """ % (invoice.partner.name, invoice.partner.address.replace("\n","<br/>")), style) Story.append(partnerAddress) Story.append(Paragraph("<font face='Helvetica-Bold'>Invoice Date:</font> %s <br/><font face='Helvetica-Bold'>Invoice Number:</font> %s" % (timestamp.strftime("%Y-%m-%d"), invoice.key().id()), style)) tableData = [] tableData.append(["Volunteer", "Project", "Start Date", "# Weeks", "",#"", "Item Total"]) subTotal = 0 for i, a in enumerate(assignments): a = a.jsonAssignment prev = assignments[i-1].jsonAssignment addWeeks = a["additionalWeeks"] * a["additionalWeekPrice"] if i > 0 and a['volunteer'] == assignments[i-1].jsonAssignment['volunteer']: itemSub = a['additionalWeekPrice'] * a['minimum_duration'] + addWeeks a['volunteer'] = '"' else: itemSub = a["price"] + addWeeks #- a["discount"] assignmentData = [a["volunteer"], a["project"], a["start_date"], int(a["num_weeks"]), # "", "", "$%.2f" % itemSub] tableData.append(assignmentData) subTotal += itemSub subTotal = subTotal + invoice.fees - invoice.discount salesTax = subTotal * settings.sales_tax total = subTotal + salesTax tableData.append(["","","","","Discount:", "-$%.2f" % invoice.discount]) tableData.append(["","","","","Other Fees:", "$%.2f" % invoice.fees]) tableData.append(["","","","","Sub-Total:", "$%.2f" % subTotal]) tableData.append(["","","","","Sales Tax:", "$%.2f" % salesTax]) tableData.append(["","","","","Total:", "$%.2f" % total]) tableStyle = TableStyle( [('ALIGN', (-1,0),(-1,-1), 'RIGHT'), ('LINEBELOW',(0,0),(-1,0), 2, colors.black), ('LINEBELOW',(0,-6),(-1,-6), 2, colors.black), # ('ALIGN', (5,-1),(5,-1), 'RIGHT'), ('FACE', (4,-5),(4,-1), 'Helvetica-Bold'), ('FACE', (0,0),(-1,0), 'Helvetica-Bold'), ('SIZE', (0,0),(-1,-1), 8)]) colWidths = [2*inch, 2*inch, None, None,None, None] table = Table(tableData, colWidths=colWidths, style=tableStyle) table.hAlign = "LEFT" Story.append(table) if invoice.comment != "": comment = Paragraph("<b>Comments:</b><br/>%s"%invoice.comment, style) Story.append(comment) bankInfo = Paragraph(""" <b>Bank Info</b><br/> %s<br/> %s<br/> <br/> <b>Acct. Name:</b> %s<br/> <b>Acct. #:</b> %s<br/> <b>Routing #:</b> %s<br/> <b>Swift Code:</b> %s<br/> """ % (settings.bankName, settings.bankAddress.replace("\n", "<br/>"), settings.bankAcctName, settings.bankAcctNum, settings.routingNumber, settings.swiftCode), style) Story.append(bankInfo) doc.build(Story, onFirstPage=firstPage, onLaterPages=laterPages)
Python
import datetime from google.appengine.api import users class TemplateValues(object): def __init__(self): self.user = users.get_current_user() self.logout_url = users.create_logout_url("/") self.login_url = users.create_login_url("/") def expdate(): delta = datetime.timedelta(days=7) expdate = datetime.datetime.now()+delta return expdate.ctime() def session(): user = users.get_current_user() logout_url = users.create_logout_url("/") login_url = users.create_login_url("/") return { "user" : user, "login_url" : login_url, "logout_url" : logout_url} def strtodt(date_str): d = date_str.split("-") return datetime.datetime(*[int(x) for x in d])
Python
from google.appengine.ext import db import calendar import datetime from dbmodels import Assignment, Calendar, NewAssignment import logging import webapp2 import pickle def assignmentDict(model): pass class Run(webapp2.RequestHandler): def get(self): manual = self.request.get("manual") == "1" num_months = 6 now = datetime.datetime.now().date() this_week = now - datetime.timedelta(days=now.weekday()) dmonth = this_week.month + num_months if dmonth > 11: dmonth = 1 dyear = this_week.year + 1 else: dyear = this_week.year logging.info("{} {}".format(dyear,dmonth)) end_date = datetime.date(year=dyear, month=dmonth, day=1) logging.info(end_date) assignments = Assignment.gql("WHERE end_date > :1 ORDER BY end_date", now ) assignments = [ a for a in assignments if a.start_date.date() < end_date ] assignments = sorted(assignments, key=lambda a: a.project_name) one_week = datetime.timedelta(days=7) weeks = [] while this_week < end_date: this_weeks_assignments = [] for a in assignments: if a.start_date.date() <= this_week <= a.end_date.date() - datetime.timedelta(days=6): # a.weeks_remaining = ((a.end_date.date() - this_week).days + 1)/7 # logging.info(a.weeks_remaining) this_weeks_assignments.append(a) weeks.append((this_week, this_weeks_assignments)) this_week += one_week logging.info(weeks) calendar = Calendar.get_or_insert("main", title="Main Calendar Data") calendar.data = pickle.dumps(weeks) calendar.timestamp = datetime.datetime.now() calendar.manual = manual calendar.put() #delete all the NewAssignments that are now in the calendar db.delete(NewAssignment.all(keys_only=True)) if manual: self.redirect("/settings?status=calgen")
Python
#
Python
#from google.appengine.ext import webapp import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import memcache import dbmodels import os import datetime from utilities import * import views from google.appengine.ext.webapp import template import logging import pickle import json class CreateCache(webapp2.RequestHandler): def get(self): query = dbmodels.Volunteer.all() query.order('lname').order('fname') volunteers = query.fetch(1000) db.delete(NewVolunteer.all(keys_only=True)) for v in volunteers: v.partner_name = v.partner.name v.all_assignments = [ a.project_name for a in v.assignments ] cache = dbmodels.Cache.get_or_insert('volunteers', title="Volunteer Cache") cache.data = pickle.dumps(volunteers) cache.timestamp = datetime.datetime.now() cache.manual = False cache.put() class RetrieveCache(webapp2.RequestHandler): def get(self): cache = dbmodels.Cache.get_by_key_name('volunteers') data = [ [ v.lname, v.fname, v.country, v.email, v.partner.name, str(v.key()) ] for v in pickle.loads(cache.data) ] new_volunteers = [v.volunteer for v in dbmodels.NewVolunteer.all()] [ data.append([v.lname, v.fname, v.country, v.email, v.partner.name, str(v.key())]) for v in new_volunteers] self.response.out.write(json.dumps(data)) class ShowNew(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = "volunteersNew.html"#views.volunteers v.pageinfo.title = "Volunteers" path = os.path.join(os.path.dirname(__file__), views.main) self.response.out.write( template.render(path, { "v" : v })) class Show(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.volunteers v.pageinfo.title = "Volunteers" v.key = self.request.get('key') view = self.request.get('view') if v.key: v.partner = dbmodels.Partner.get(v.key) if view == 'all': v.volunteers = v.partner.allVolunteers else: v.volunteers = v.partner.activeVolunteers v.pageinfo.title = "Volunteers - %s" % v.partner.name else: v.pageinfo.title = "All Volunteers" if view != 'active': v.volunteers = dbmodels.Volunteer.get_all() else: v.volunteers = dbmodels.Volunteer.get_active() path = os.path.join(os.path.dirname(__file__), views.main) self.response.out.write( template.render(path, { "v" : v })) class Form(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.volunteerForm v.pageinfo.title = "Volunteer Form" key = self.request.get('key') try: v.partnerkey = db.Key(self.request.get('pkey')) except db.BadKeyError: pass if key == '': pass else: v.volunteer = dbmodels.Volunteer.get(key) v.assignments = dbmodels.Assignment.get_all_for_volunteer(v.volunteer.key()) v.assignments.filter("volunteer =", v.volunteer.key()).order("start_date") v.total_price = 0.0 for a in v.assignments: v.total_price += a.total_price v.partners = dbmodels.Partner.get_all(False) path = os.path.join(os.path.dirname(__file__), views.main) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): key = self.request.get('key') if key == '': volunteer = dbmodels.Volunteer() new_volunteer = True else: volunteer = dbmodels.Volunteer.get(key) volunteer.fname = self.request.get('fname') volunteer.lname = self.request.get('lname') volunteer.country = self.request.get('country') volunteer.DOB = datetime.datetime(int(self.request.get('year')), int(self.request.get('month')), int(self.request.get('day'))) volunteer.partner = dbmodels.Partner.get(self.request.get('partner')) volunteer.email = self.request.get('email') or None volunteer.address = self.request.get('address') volunteer.emergency = self.request.get('emergency') volunteer.comment = self.request.get('comment') volunteer.put() if new_volunteer: nv = dbmodels.NewVolunteer() nv.volunteer = volunteer nv.put() memcache.delete("volunteer:all") memcache.delete("volunteer:all:%s" % volunteer.partner.key()) memcache.delete("partner:volunteer:active:%s" % volunteer.partner.key()) memcache.delete("partner:volunteer:all:%s" % volunteer.partner.key()) memcache.delete("volunteer:delete") memcache.delete("volunteer:active") logging.info("cleared the cache") if key == "": self.redirect('/assignmentForm?vkey='+unicode(volunteer.key())) else: self.redirect('/volunteers') class Delete(webapp2.RequestHandler): def get(self): key = self.request.get('key') volunteer = dbmodels.Volunteer.get(key) memcache.delete("volunteer:all") memcache.delete("volunteer:all:%s" % volunteer.partner.key()) memcache.delete("partner:volunteer:active:%s" % volunteer.partner.key()) memcache.delete("partner:volunteer:all:%s" % volunteer.partner.key()) memcache.delete("volunteer:delete") memcache.delete("volunteer:active") logging.info("cleared the cache") db.delete(volunteer.assignments) db.delete(volunteer) self.redirect('/volunteers')
Python
#from google.appengine.ext import webapp import webapp2 from google.appengine.ext.webapp import util from google.appengine.ext import ndb from google.appengine.api import memcache import dbmodels import os import datetime from utilities import * import views import json import logging from google.appengine.ext.webapp import template import logging class Show(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.partners logging.info(views.partners) v.pageinfo.title = "Partners" v.partners = dbmodels.Partner.all()#get_all(added) v.partners.order("name") path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Form(webapp2.RequestHandler): def get(self): v = TemplateValues() v.pageinfo = TemplateValues() v.pageinfo.html = views.partnerForm v.pageinfo.title = "Partner Form" key = self.request.get('key') if key == '': pass else: v.partner = dbmodels.Partner.get(key) v.partner.invoices.order("date") path = os.path.join(os.path.dirname(__file__), views.main) self.response.headers.add_header("Expires", expdate()) self.response.out.write(template.render(path, { "v" : v })) class Edit(webapp2.RequestHandler): def post(self): key = self.request.get('key') if key == '': partner = dbmodels.Partner() else: partner = dbmodels.Partner.get(key) partner.name = self.request.get('name') partner.abbr = self.request.get('abbr') partner.address = self.request.get('address') partner.comment = self.request.get('comment') partner.put() self.redirect('/partners') class Delete(webapp2.RequestHandler): def get(self): key = self.request.get('key') partner = dbmodels.Partner.get(key) db.delete(partner) self.redirect('/partners')
Python
import os views = "views" main = os.path.join(views, "main.html") assignments = os.path.join(views,"assignments.html") assignmentForm = os.path.join("assignmentForm.html") partners = "partners.html" partnerForm = "partnerForm.html" projects = "projects.html" projectForm = "projectForm.html" sites = "sites.html" siteForm = "siteForm.html" volunteers = "volunteers.html" volunteerForm = "volunteerForm.html" invoice = "invoice.html" invoices = "invoices.html" invoiceForm = "invoiceForm.html" settings = "settings.html"
Python
from google.appengine.ext import webapp import webapp2 import dbmodels class Api(webapp2.RequestHandler): def get(self, arg): self.response.write(arg)
Python
""" Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" import datetime import struct import time import sys import os relativedelta = None parser = None rrule = None __all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz"] try: from dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal = None, None ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO def tzname(self, dt): return "UTC" def __eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO def tzname(self, dt): return self._name def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, `self._name`, self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't use mktime here. It is unstable when deciding if # the hour near to a change is DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above yields the following result: # #>>> import tz, datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a more stable implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other, tzlocal): return False return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) return True def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt"] def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def __repr__(self): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, `value`)) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo): return False return (self.offset == other.offset and self.delta == other.delta and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt) def __ne__(self, other): return not self.__eq__(other) def __getstate__(self): state = {} for name in self.__slots__: state[name] = getattr(self, name, None) return state def __setstate__(self, state): for name in self.__slots__: if name in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://elsie.nci.nih.gov/pub/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, basestring): self._filename = fileobj fileobj = open(fileobj) elif hasattr(fileobj, "name"): self._filename = fileobj.name else: self._filename = `fileobj` # From tzfile(5): # # The time zone information files used by tzset(3) # begin with the magic characters "TZif" to identify # them as time zone information files, followed by # sixteen bytes reserved for future use, followed by # six four-byte values of type long, written in a # ``standard'' byte order (the high-order byte # of the value is written first). if fileobj.read(4) != "TZif": raise ValueError, "magic not found" fileobj.read(16) ( # The number of UTC/local indicators stored in the file. ttisgmtcnt, # The number of standard/wall indicators stored in the file. ttisstdcnt, # The number of leap seconds for which data is # stored in the file. leapcnt, # The number of "transition times" for which data # is stored in the file. timecnt, # The number of "local time types" for which data # is stored in the file (must not be zero). typecnt, # The number of characters of "time zone # abbreviation strings" stored in the file. charcnt, ) = struct.unpack(">6l", fileobj.read(24)) # The above header is followed by tzh_timecnt four-byte # values of type long, sorted in ascending order. # These values are written in ``standard'' byte order. # Each is used as a transition time (as returned by # time(2)) at which the rules for computing local time # change. if timecnt: self._trans_list = struct.unpack(">%dl" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] # Next come tzh_timecnt one-byte values of type unsigned # char; each one tells which of the different types of # ``local time'' types described in the file is associated # with the same-indexed transition time. These values # serve as indices into an array of ttinfo structures that # appears next in the file. if timecnt: self._trans_idx = struct.unpack(">%dB" % timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] # Each ttinfo structure is written as a four-byte value # for tt_gmtoff of type long, in a standard byte # order, followed by a one-byte value for tt_isdst # and a one-byte value for tt_abbrind. In each # structure, tt_gmtoff gives the number of # seconds to be added to UTC, tt_isdst tells whether # tm_isdst should be set by localtime(3), and # tt_abbrind serves as an index into the array of # time zone abbreviation characters that follow the # ttinfo structure(s) in the file. ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) abbr = fileobj.read(charcnt) # Then there are tzh_leapcnt pairs of four-byte # values, written in standard byte order; the # first value of each pair gives the time (as # returned by time(2)) at which a leap second # occurs; the second gives the total number of # leap seconds to be applied after the given time. # The pairs of values are sorted in ascending order # by time. # Not used, for now if leapcnt: leap = struct.unpack(">%dl" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as standard # time or wall clock time, and are used when # a time zone file is used in handling POSIX-style # time zone environment variables. if ttisstdcnt: isstd = struct.unpack(">%db" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as UTC or # local time, and are used when a time zone file # is used in handling POSIX-style time zone envi- # ronment variables. if ttisgmtcnt: isgmt = struct.unpack(">%db" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been read ** # Build ttinfo list self._ttinfo_list = [] for i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round to full-minutes if that's not the case. Python's # datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects. trans_idx = [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard, dst, and before ttinfos. before will be # used when a given time is before any transitions, # and will be set to the first non-dst ttinfo, or to # the first dst, if all of them are dst. self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before = None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for i in range(timecnt-1,-1,-1): tti = self._trans_idx[i] if not self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before = self._ttinfo_list[0] # Now fix transition times to become relative to wall time. # # I'm not sure about this. In my tests, the tz source file # is setup to wall time, and in the binary file isstd and # isgmt are off, so it should be in wall time. OTOH, it's # always in gmt time. Let me know if you have comments # about this. laststdoffset = 0 self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst: # This is std time. self._trans_list[i] += tti.offset laststdoffset = tti.offset else: # This is dst time. Convert to std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute * 60 + dt.second) idx = 0 for trans in self._trans_list: if timestamp < trans: break idx += 1 else: return self._ttinfo_std if idx == 0: return self._ttinfo_before if laststd: while idx > 0: tti = self._trans_idx[idx-1] if not tti.isdst: return tti idx -= 1 else: return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO # The documentation says that utcoffset()-dst() must # be constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores historical changes in the # dst offset, so I belive that this wouldn't be the right # way to implement this. def tzname(self, dt): if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile): return False return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, `self._filename`) def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError, "Unpickable %s class" % self.__class__.__name__ return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if not relativedelta: from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def _isdst(self, dt): if not self._start_delta: return False year = datetime.datetime(dt.year,1,1) start = year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None) if start < end: return dt >= start and dt < end else: return dt >= start or dt < end def __eq__(self, other): if not isinstance(other, tzrange): return False return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(...)" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self, s): global parser if not parser: from dateutil import parser self._s = s res = parser._parsetz(s) if res is None: raise ValueError, "unknown string format" # Here we break the compatibility with the TZ variable handling. # GMT-3 actually *means* the timezone -3. if res.stdabbr in ("GMT", "UTC"): res.stdoffset *= -1 # We must initialize it first, since _delta() needs # _std_offset and _dst_offset set. Use False in start/end # to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs = {} if x.month is not None: kwargs["month"] = x.month if x.weekday is not None: kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs["day"] = 1 else: kwargs["day"] = 31 elif x.day: kwargs["day"] = x.day elif x.yday is not None: kwargs["yearday"] = x.yday elif x.jyday is not None: kwargs["nlyearday"] = x.jyday if not kwargs: # Default is to start on first sunday of april, and end # on last sunday of october. if not isend: kwargs["month"] = 4 kwargs["day"] = 1 kwargs["weekday"] = relativedelta.SU(+1) else: kwargs["month"] = 10 kwargs["day"] = 31 kwargs["weekday"] = relativedelta.SU(-1) if x.time is not None: kwargs["seconds"] = x.time else: # Default is 2AM. kwargs["seconds"] = 7200 if isend: # Convert to standard time, to follow the documented way # of working with the extra hour. See the documentation # of the tzinfo class. delta = self._dst_offset-self._std_offset kwargs["seconds"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, `self._s`) class _tzicalvtzcomp: def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid = tzid self._comps = comps self._cachedate = [] self._cachecomp = [] def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None lastcompdt = None for comp in self._comps: if not comp.isdst: # Handle the extra hour in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp = comp if not lastcomp: # RFC says nothing about what to do when a given # time is before the first onset date. We'll look for the # first standard component, or the first component, if # none is found. for comp in self._comps: if not comp.isdst: lastcomp = comp break else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return "<tzicalvtz %s>" % `self._tzid` __reduce__ = object.__reduce__ class tzical: def __init__(self, fileobj): global rrule if not rrule: from dateutil import rrule if isinstance(fileobj, basestring): self._s = fileobj fileobj = open(fileobj) elif hasattr(fileobj, "name"): self._s = fileobj.name else: self._s = `fileobj` self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return self._vtz.keys() def get(self, tzid=None): if tzid is None: keys = self._vtz.keys() if len(keys) == 0: raise ValueError, "no timezones defined" elif len(keys) > 1: raise ValueError, "more than one timezone available" tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not s: raise ValueError, "empty offset" if s[0] in ('+', '-'): signal = (-1,+1)[s[0]=='+'] s = s[1:] else: signal = +1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError, "invalid offset: "+s def _parse_rfc(self, s): lines = s.splitlines() if not lines: raise ValueError, "empty string" # Unfold i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 tzid = None comps = [] invtz = False comptype = None for line in lines: if not line: continue name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError, "empty property name" name = parms[0].upper() parms = parms[1:] if invtz: if name == "BEGIN": if value in ("STANDARD", "DAYLIGHT"): # Process component pass else: raise ValueError, "unknown component: "+value comptype = value founddtstart = False tzoffsetfrom = None tzoffsetto = None rrulelines = [] tzname = None elif name == "END": if value == "VTIMEZONE": if comptype: raise ValueError, \ "component not closed: "+comptype if not tzid: raise ValueError, \ "mandatory TZID not found" if not comps: raise ValueError, \ "at least one component is needed" # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value == comptype: if not founddtstart: raise ValueError, \ "mandatory DTSTART not found" if tzoffsetfrom is None: raise ValueError, \ "mandatory TZOFFSETFROM not found" if tzoffsetto is None: raise ValueError, \ "mandatory TZOFFSETFROM not found" # Process component rr = None if rrulelines: rr = rrule.rrulestr("\n".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == "DAYLIGHT"), tzname, rr) comps.append(comp) comptype = None else: raise ValueError, \ "invalid component end: "+value elif comptype: if name == "DTSTART": rrulelines.append(line) founddtstart = True elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): rrulelines.append(line) elif name == "TZOFFSETFROM": if parms: raise ValueError, \ "unsupported %s parm: %s "%(name, parms[0]) tzoffsetfrom = self._parse_offset(value) elif name == "TZOFFSETTO": if parms: raise ValueError, \ "unsupported TZOFFSETTO parm: "+parms[0] tzoffsetto = self._parse_offset(value) elif name == "TZNAME": if parms: raise ValueError, \ "unsupported TZNAME parm: "+parms[0] tzname = value elif name == "COMMENT": pass else: raise ValueError, "unsupported property: "+name else: if name == "TZID": if parms: raise ValueError, \ "unsupported TZID parm: "+parms[0] tzid = value elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): pass else: raise ValueError, "unsupported property: "+name elif name == "BEGIN" and value == "VTIMEZONE": tzid = None comps = [] invtz = True def __repr__(self): return "%s(%s)" % (self.__class__.__name__, `self._s`) if sys.platform != "win32": TZFILES = ["/etc/localtime", "localtime"] TZPATHS = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"] else: TZFILES = [] TZPATHS = [] def gettz(name=None): tz = None if not name: try: name = os.environ["TZ"] except KeyError: pass if name is None or name == ":": for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = tzlocal() else: if name.startswith(":"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None else: for path in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ','_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = None if tzwin: try: tz = tzwin(name) except OSError: pass if not tz: from dateutil.zoneinfo import gettz tz = gettz(name) if not tz: for c in name: # name must have at least one offset to be a tzstr if c in "0123456789": try: tz = tzstr(name) except ValueError: pass break else: if name in ("GMT", "UTC"): tz = tzutc() elif name in time.tzname: tz = tzlocal() return tz # vim:ts=4:sw=4:et
Python
""" Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" import itertools import datetime import calendar import thread import sys __all__ = ["rrule", "rruleset", "rrulestr", "YEARLY", "MONTHLY", "WEEKLY", "DAILY", "HOURLY", "MINUTELY", "SECONDLY", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] # Every mask is 7 days longer to handle cross-year weekly periods. M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30+ [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) M365MASK = list(M366MASK) M29, M30, M31 = range(1,30), range(1,31), range(1,32) MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) MDAY365MASK = list(MDAY366MASK) M29, M30, M31 = range(-29,0), range(-30,0), range(-31,0) NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) NMDAY365MASK = list(NMDAY366MASK) M366RANGE = (0,31,60,91,121,152,182,213,244,274,305,335,366) M365RANGE = (0,31,59,90,120,151,181,212,243,273,304,334,365) WDAYMASK = [0,1,2,3,4,5,6]*55 del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] MDAY365MASK = tuple(MDAY365MASK) M365MASK = tuple(M365MASK) (YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY) = range(7) # Imported on demand. easter = None parser = None class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): if n == 0: raise ValueError, "Can't create weekday with n == 0" self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class rrulebase: def __init__(self, cache=False): if cache: self._cache = [] self._cache_lock = thread.allocate_lock() self._cache_gen = self._iter() self._cache_complete = False else: self._cache = None self._cache_complete = False self._len = None def __iter__(self): if self._cache_complete: return iter(self._cache) elif self._cache is None: return self._iter() else: return self._iter_cached() def _iter_cached(self): i = 0 gen = self._cache_gen cache = self._cache acquire = self._cache_lock.acquire release = self._cache_lock.release while gen: if i == len(cache): acquire() if self._cache_complete: break try: for j in range(10): cache.append(gen.next()) except StopIteration: self._cache_gen = gen = None self._cache_complete = True break release() yield cache[i] i += 1 while i < self._len: yield cache[i] i += 1 def __getitem__(self, item): if self._cache_complete: return self._cache[item] elif isinstance(item, slice): if item.step and item.step < 0: return list(iter(self))[item] else: return list(itertools.islice(self, item.start or 0, item.stop or sys.maxint, item.step or 1)) elif item >= 0: gen = iter(self) try: for i in range(item+1): res = gen.next() except StopIteration: raise IndexError return res else: return list(iter(self))[item] def __contains__(self, item): if self._cache_complete: return item in self._cache else: for i in self: if i == item: return True elif i > item: return False return False # __len__() introduces a large performance penality. def count(self): if self._len is None: for x in self: pass return self._len def before(self, dt, inc=False): if self._cache_complete: gen = self._cache else: gen = self last = None if inc: for i in gen: if i > dt: break last = i else: for i in gen: if i >= dt: break last = i return last def after(self, dt, inc=False): if self._cache_complete: gen = self._cache else: gen = self if inc: for i in gen: if i >= dt: return i else: for i in gen: if i > dt: return i return None def between(self, after, before, inc=False): if self._cache_complete: gen = self._cache else: gen = self started = False l = [] if inc: for i in gen: if i > before: break elif not started: if i >= after: started = True l.append(i) else: l.append(i) else: for i in gen: if i >= before: break elif not started: if i > after: started = True l.append(i) else: l.append(i) return l class rrule(rrulebase): def __init__(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False): rrulebase.__init__(self, cache) global easter if not dtstart: dtstart = datetime.datetime.now().replace(microsecond=0) elif not isinstance(dtstart, datetime.datetime): dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) else: dtstart = dtstart.replace(microsecond=0) self._dtstart = dtstart self._tzinfo = dtstart.tzinfo self._freq = freq self._interval = interval self._count = count if until and not isinstance(until, datetime.datetime): until = datetime.datetime.fromordinal(until.toordinal()) self._until = until if wkst is None: self._wkst = calendar.firstweekday() elif type(wkst) is int: self._wkst = wkst else: self._wkst = wkst.weekday if bysetpos is None: self._bysetpos = None elif type(bysetpos) is int: if bysetpos == 0 or not (-366 <= bysetpos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") self._bysetpos = (bysetpos,) else: self._bysetpos = tuple(bysetpos) for pos in self._bysetpos: if pos == 0 or not (-366 <= pos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") if not (byweekno or byyearday or bymonthday or byweekday is not None or byeaster is not None): if freq == YEARLY: if not bymonth: bymonth = dtstart.month bymonthday = dtstart.day elif freq == MONTHLY: bymonthday = dtstart.day elif freq == WEEKLY: byweekday = dtstart.weekday() # bymonth if not bymonth: self._bymonth = None elif type(bymonth) is int: self._bymonth = (bymonth,) else: self._bymonth = tuple(bymonth) # byyearday if not byyearday: self._byyearday = None elif type(byyearday) is int: self._byyearday = (byyearday,) else: self._byyearday = tuple(byyearday) # byeaster if byeaster is not None: if not easter: from dateutil import easter if type(byeaster) is int: self._byeaster = (byeaster,) else: self._byeaster = tuple(byeaster) else: self._byeaster = None # bymonthay if not bymonthday: self._bymonthday = () self._bynmonthday = () elif type(bymonthday) is int: if bymonthday < 0: self._bynmonthday = (bymonthday,) self._bymonthday = () else: self._bymonthday = (bymonthday,) self._bynmonthday = () else: self._bymonthday = tuple([x for x in bymonthday if x > 0]) self._bynmonthday = tuple([x for x in bymonthday if x < 0]) # byweekno if byweekno is None: self._byweekno = None elif type(byweekno) is int: self._byweekno = (byweekno,) else: self._byweekno = tuple(byweekno) # byweekday / bynweekday if byweekday is None: self._byweekday = None self._bynweekday = None elif type(byweekday) is int: self._byweekday = (byweekday,) self._bynweekday = None elif hasattr(byweekday, "n"): if not byweekday.n or freq > MONTHLY: self._byweekday = (byweekday.weekday,) self._bynweekday = None else: self._bynweekday = ((byweekday.weekday, byweekday.n),) self._byweekday = None else: self._byweekday = [] self._bynweekday = [] for wday in byweekday: if type(wday) is int: self._byweekday.append(wday) elif not wday.n or freq > MONTHLY: self._byweekday.append(wday.weekday) else: self._bynweekday.append((wday.weekday, wday.n)) self._byweekday = tuple(self._byweekday) self._bynweekday = tuple(self._bynweekday) if not self._byweekday: self._byweekday = None elif not self._bynweekday: self._bynweekday = None # byhour if byhour is None: if freq < HOURLY: self._byhour = (dtstart.hour,) else: self._byhour = None elif type(byhour) is int: self._byhour = (byhour,) else: self._byhour = tuple(byhour) # byminute if byminute is None: if freq < MINUTELY: self._byminute = (dtstart.minute,) else: self._byminute = None elif type(byminute) is int: self._byminute = (byminute,) else: self._byminute = tuple(byminute) # bysecond if bysecond is None: if freq < SECONDLY: self._bysecond = (dtstart.second,) else: self._bysecond = None elif type(bysecond) is int: self._bysecond = (bysecond,) else: self._bysecond = tuple(bysecond) if self._freq >= HOURLY: self._timeset = None else: self._timeset = [] for hour in self._byhour: for minute in self._byminute: for second in self._bysecond: self._timeset.append( datetime.time(hour, minute, second, tzinfo=self._tzinfo)) self._timeset.sort() self._timeset = tuple(self._timeset) def _iter(self): year, month, day, hour, minute, second, weekday, yearday, _ = \ self._dtstart.timetuple() # Some local variables to speed things up a bit freq = self._freq interval = self._interval wkst = self._wkst until = self._until bymonth = self._bymonth byweekno = self._byweekno byyearday = self._byyearday byweekday = self._byweekday byeaster = self._byeaster bymonthday = self._bymonthday bynmonthday = self._bynmonthday bysetpos = self._bysetpos byhour = self._byhour byminute = self._byminute bysecond = self._bysecond ii = _iterinfo(self) ii.rebuild(year, month) getdayset = {YEARLY:ii.ydayset, MONTHLY:ii.mdayset, WEEKLY:ii.wdayset, DAILY:ii.ddayset, HOURLY:ii.ddayset, MINUTELY:ii.ddayset, SECONDLY:ii.ddayset}[freq] if freq < HOURLY: timeset = self._timeset else: gettimeset = {HOURLY:ii.htimeset, MINUTELY:ii.mtimeset, SECONDLY:ii.stimeset}[freq] if ((freq >= HOURLY and self._byhour and hour not in self._byhour) or (freq >= MINUTELY and self._byminute and minute not in self._byminute) or (freq >= SECONDLY and self._bysecond and second not in self._bysecond)): timeset = () else: timeset = gettimeset(hour, minute, second) total = 0 count = self._count while True: # Get dayset with the right frequency dayset, start, end = getdayset(year, month, day) # Do the "hard" work ;-) filtered = False for i in dayset[start:end]: if ((bymonth and ii.mmask[i] not in bymonth) or (byweekno and not ii.wnomask[i]) or (byweekday and ii.wdaymask[i] not in byweekday) or (ii.nwdaymask and not ii.nwdaymask[i]) or (byeaster and not ii.eastermask[i]) or ((bymonthday or bynmonthday) and ii.mdaymask[i] not in bymonthday and ii.nmdaymask[i] not in bynmonthday) or (byyearday and ((i < ii.yearlen and i+1 not in byyearday and -ii.yearlen+i not in byyearday) or (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and -ii.nextyearlen+i-ii.yearlen not in byyearday)))): dayset[i] = None filtered = True # Output results if bysetpos and timeset: poslist = [] for pos in bysetpos: if pos < 0: daypos, timepos = divmod(pos, len(timeset)) else: daypos, timepos = divmod(pos-1, len(timeset)) try: i = [x for x in dayset[start:end] if x is not None][daypos] time = timeset[timepos] except IndexError: pass else: date = datetime.date.fromordinal(ii.yearordinal+i) res = datetime.datetime.combine(date, time) if res not in poslist: poslist.append(res) poslist.sort() for res in poslist: if until and res > until: self._len = total return elif res >= self._dtstart: total += 1 yield res if count: count -= 1 if not count: self._len = total return else: for i in dayset[start:end]: if i is not None: date = datetime.date.fromordinal(ii.yearordinal+i) for time in timeset: res = datetime.datetime.combine(date, time) if until and res > until: self._len = total return elif res >= self._dtstart: total += 1 yield res if count: count -= 1 if not count: self._len = total return # Handle frequency and interval fixday = False if freq == YEARLY: year += interval if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == MONTHLY: month += interval if month > 12: div, mod = divmod(month, 12) month = mod year += div if month == 0: month = 12 year -= 1 if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == WEEKLY: if wkst > weekday: day += -(weekday+1+(6-wkst))+self._interval*7 else: day += -(weekday-wkst)+self._interval*7 weekday = wkst fixday = True elif freq == DAILY: day += interval fixday = True elif freq == HOURLY: if filtered: # Jump to one iteration before next day hour += ((23-hour)//interval)*interval while True: hour += interval div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True if not byhour or hour in byhour: break timeset = gettimeset(hour, minute, second) elif freq == MINUTELY: if filtered: # Jump to one iteration before next day minute += ((1439-(hour*60+minute))//interval)*interval while True: minute += interval div, mod = divmod(minute, 60) if div: minute = mod hour += div div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True filtered = False if ((not byhour or hour in byhour) and (not byminute or minute in byminute)): break timeset = gettimeset(hour, minute, second) elif freq == SECONDLY: if filtered: # Jump to one iteration before next day second += (((86399-(hour*3600+minute*60+second)) //interval)*interval) while True: second += self._interval div, mod = divmod(second, 60) if div: second = mod minute += div div, mod = divmod(minute, 60) if div: minute = mod hour += div div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True if ((not byhour or hour in byhour) and (not byminute or minute in byminute) and (not bysecond or second in bysecond)): break timeset = gettimeset(hour, minute, second) if fixday and day > 28: daysinmonth = calendar.monthrange(year, month)[1] if day > daysinmonth: while day > daysinmonth: day -= daysinmonth month += 1 if month == 13: month = 1 year += 1 if year > datetime.MAXYEAR: self._len = total return daysinmonth = calendar.monthrange(year, month)[1] ii.rebuild(year, month) class _iterinfo(object): __slots__ = ["rrule", "lastyear", "lastmonth", "yearlen", "nextyearlen", "yearordinal", "yearweekday", "mmask", "mrange", "mdaymask", "nmdaymask", "wdaymask", "wnomask", "nwdaymask", "eastermask"] def __init__(self, rrule): for attr in self.__slots__: setattr(self, attr, None) self.rrule = rrule def rebuild(self, year, month): # Every mask is 7 days longer to handle cross-year weekly periods. rr = self.rrule if year != self.lastyear: self.yearlen = 365+calendar.isleap(year) self.nextyearlen = 365+calendar.isleap(year+1) firstyday = datetime.date(year, 1, 1) self.yearordinal = firstyday.toordinal() self.yearweekday = firstyday.weekday() wday = datetime.date(year, 1, 1).weekday() if self.yearlen == 365: self.mmask = M365MASK self.mdaymask = MDAY365MASK self.nmdaymask = NMDAY365MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M365RANGE else: self.mmask = M366MASK self.mdaymask = MDAY366MASK self.nmdaymask = NMDAY366MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M366RANGE if not rr._byweekno: self.wnomask = None else: self.wnomask = [0]*(self.yearlen+7) #no1wkst = firstwkst = self.wdaymask.index(rr._wkst) no1wkst = firstwkst = (7-self.yearweekday+rr._wkst)%7 if no1wkst >= 4: no1wkst = 0 # Number of days in the year, plus the days we got # from last year. wyearlen = self.yearlen+(self.yearweekday-rr._wkst)%7 else: # Number of days in the year, minus the days we # left in last year. wyearlen = self.yearlen-no1wkst div, mod = divmod(wyearlen, 7) numweeks = div+mod//4 for n in rr._byweekno: if n < 0: n += numweeks+1 if not (0 < n <= numweeks): continue if n > 1: i = no1wkst+(n-1)*7 if no1wkst != firstwkst: i -= 7-firstwkst else: i = no1wkst for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if 1 in rr._byweekno: # Check week number 1 of next year as well # TODO: Check -numweeks for next year. i = no1wkst+numweeks*7 if no1wkst != firstwkst: i -= 7-firstwkst if i < self.yearlen: # If week starts in next year, we # don't care about it. for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if no1wkst: # Check last week number of last year as # well. If no1wkst is 0, either the year # started on week start, or week number 1 # got days from last year, so there are no # days from last year's last week number in # this year. if -1 not in rr._byweekno: lyearweekday = datetime.date(year-1,1,1).weekday() lno1wkst = (7-lyearweekday+rr._wkst)%7 lyearlen = 365+calendar.isleap(year-1) if lno1wkst >= 4: lno1wkst = 0 lnumweeks = 52+(lyearlen+ (lyearweekday-rr._wkst)%7)%7//4 else: lnumweeks = 52+(self.yearlen-no1wkst)%7//4 else: lnumweeks = -1 if lnumweeks in rr._byweekno: for i in range(no1wkst): self.wnomask[i] = 1 if (rr._bynweekday and (month != self.lastmonth or year != self.lastyear)): ranges = [] if rr._freq == YEARLY: if rr._bymonth: for month in rr._bymonth: ranges.append(self.mrange[month-1:month+1]) else: ranges = [(0, self.yearlen)] elif rr._freq == MONTHLY: ranges = [self.mrange[month-1:month+1]] if ranges: # Weekly frequency won't get here, so we may not # care about cross-year weekly periods. self.nwdaymask = [0]*self.yearlen for first, last in ranges: last -= 1 for wday, n in rr._bynweekday: if n < 0: i = last+(n+1)*7 i -= (self.wdaymask[i]-wday)%7 else: i = first+(n-1)*7 i += (7-self.wdaymask[i]+wday)%7 if first <= i <= last: self.nwdaymask[i] = 1 if rr._byeaster: self.eastermask = [0]*(self.yearlen+7) eyday = easter.easter(year).toordinal()-self.yearordinal for offset in rr._byeaster: self.eastermask[eyday+offset] = 1 self.lastyear = year self.lastmonth = month def ydayset(self, year, month, day): return range(self.yearlen), 0, self.yearlen def mdayset(self, year, month, day): set = [None]*self.yearlen start, end = self.mrange[month-1:month+1] for i in range(start, end): set[i] = i return set, start, end def wdayset(self, year, month, day): # We need to handle cross-year weeks here. set = [None]*(self.yearlen+7) i = datetime.date(year, month, day).toordinal()-self.yearordinal start = i for j in range(7): set[i] = i i += 1 #if (not (0 <= i < self.yearlen) or # self.wdaymask[i] == self.rrule._wkst): # This will cross the year boundary, if necessary. if self.wdaymask[i] == self.rrule._wkst: break return set, start, i def ddayset(self, year, month, day): set = [None]*self.yearlen i = datetime.date(year, month, day).toordinal()-self.yearordinal set[i] = i return set, i, i+1 def htimeset(self, hour, minute, second): set = [] rr = self.rrule for minute in rr._byminute: for second in rr._bysecond: set.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) set.sort() return set def mtimeset(self, hour, minute, second): set = [] rr = self.rrule for second in rr._bysecond: set.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) set.sort() return set def stimeset(self, hour, minute, second): return (datetime.time(hour, minute, second, tzinfo=self.rrule._tzinfo),) class rruleset(rrulebase): class _genitem: def __init__(self, genlist, gen): try: self.dt = gen() genlist.append(self) except StopIteration: pass self.genlist = genlist self.gen = gen def next(self): try: self.dt = self.gen() except StopIteration: self.genlist.remove(self) def __cmp__(self, other): return cmp(self.dt, other.dt) def __init__(self, cache=False): rrulebase.__init__(self, cache) self._rrule = [] self._rdate = [] self._exrule = [] self._exdate = [] def rrule(self, rrule): self._rrule.append(rrule) def rdate(self, rdate): self._rdate.append(rdate) def exrule(self, exrule): self._exrule.append(exrule) def exdate(self, exdate): self._exdate.append(exdate) def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate).next) for gen in [iter(x).next for x in self._rrule]: self._genitem(rlist, gen) rlist.sort() exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate).next) for gen in [iter(x).next for x in self._exrule]: self._genitem(exlist, gen) exlist.sort() lastdt = None total = 0 while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: exlist[0].next() exlist.sort() if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt ritem.next() rlist.sort() self._len = total class _rrulestr: _freq_map = {"YEARLY": YEARLY, "MONTHLY": MONTHLY, "WEEKLY": WEEKLY, "DAILY": DAILY, "HOURLY": HOURLY, "MINUTELY": MINUTELY, "SECONDLY": SECONDLY} _weekday_map = {"MO":0,"TU":1,"WE":2,"TH":3,"FR":4,"SA":5,"SU":6} def _handle_int(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = int(value) def _handle_int_list(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = [int(x) for x in value.split(',')] _handle_INTERVAL = _handle_int _handle_COUNT = _handle_int _handle_BYSETPOS = _handle_int_list _handle_BYMONTH = _handle_int_list _handle_BYMONTHDAY = _handle_int_list _handle_BYYEARDAY = _handle_int_list _handle_BYEASTER = _handle_int_list _handle_BYWEEKNO = _handle_int_list _handle_BYHOUR = _handle_int_list _handle_BYMINUTE = _handle_int_list _handle_BYSECOND = _handle_int_list def _handle_FREQ(self, rrkwargs, name, value, **kwargs): rrkwargs["freq"] = self._freq_map[value] def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): global parser if not parser: from dateutil import parser try: rrkwargs["until"] = parser.parse(value, ignoretz=kwargs.get("ignoretz"), tzinfos=kwargs.get("tzinfos")) except ValueError: raise ValueError, "invalid until date" def _handle_WKST(self, rrkwargs, name, value, **kwargs): rrkwargs["wkst"] = self._weekday_map[value] def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwarsg): l = [] for wday in value.split(','): for i in range(len(wday)): if wday[i] not in '+-0123456789': break n = wday[:i] or None w = wday[i:] if n: n = int(n) l.append(weekdays[self._weekday_map[w]](n)) rrkwargs["byweekday"] = l _handle_BYDAY = _handle_BYWEEKDAY def _parse_rfc_rrule(self, line, dtstart=None, cache=False, ignoretz=False, tzinfos=None): if line.find(':') != -1: name, value = line.split(':') if name != "RRULE": raise ValueError, "unknown parameter name" else: value = line rrkwargs = {} for pair in value.split(';'): name, value = pair.split('=') name = name.upper() value = value.upper() try: getattr(self, "_handle_"+name)(rrkwargs, name, value, ignoretz=ignoretz, tzinfos=tzinfos) except AttributeError: raise ValueError, "unknown parameter '%s'" % name except (KeyError, ValueError): raise ValueError, "invalid '%s': %s" % (name, value) return rrule(dtstart=dtstart, cache=cache, **rrkwargs) def _parse_rfc(self, s, dtstart=None, cache=False, unfold=False, forceset=False, compatible=False, ignoretz=False, tzinfos=None): global parser if compatible: forceset = True unfold = True s = s.upper() if not s.strip(): raise ValueError, "empty string" if unfold: lines = s.splitlines() i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 else: lines = s.split() if (not forceset and len(lines) == 1 and (s.find(':') == -1 or s.startswith('RRULE:'))): return self._parse_rfc_rrule(lines[0], cache=cache, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos) else: rrulevals = [] rdatevals = [] exrulevals = [] exdatevals = [] for line in lines: if not line: continue if line.find(':') == -1: name = "RRULE" value = line else: name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError, "empty property name" name = parms[0] parms = parms[1:] if name == "RRULE": for parm in parms: raise ValueError, "unsupported RRULE parm: "+parm rrulevals.append(value) elif name == "RDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError, "unsupported RDATE parm: "+parm rdatevals.append(value) elif name == "EXRULE": for parm in parms: raise ValueError, "unsupported EXRULE parm: "+parm exrulevals.append(value) elif name == "EXDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError, "unsupported RDATE parm: "+parm exdatevals.append(value) elif name == "DTSTART": for parm in parms: raise ValueError, "unsupported DTSTART parm: "+parm if not parser: from dateutil import parser dtstart = parser.parse(value, ignoretz=ignoretz, tzinfos=tzinfos) else: raise ValueError, "unsupported property: "+name if (forceset or len(rrulevals) > 1 or rdatevals or exrulevals or exdatevals): if not parser and (rdatevals or exdatevals): from dateutil import parser set = rruleset(cache=cache) for value in rrulevals: set.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in rdatevals: for datestr in value.split(','): set.rdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exrulevals: set.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exdatevals: for datestr in value.split(','): set.exdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) if compatible and dtstart: set.rdate(dtstart) return set else: return self._parse_rfc_rrule(rrulevals[0], dtstart=dtstart, cache=cache, ignoretz=ignoretz, tzinfos=tzinfos) def __call__(self, s, **kwargs): return self._parse_rfc(s, **kwargs) rrulestr = _rrulestr() # vim:ts=4:sw=4:et
Python
""" Copyright (c) 2003-2005 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ from dateutil.tz import tzfile from tarfile import TarFile import os __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" __all__ = ["setcachesize", "gettz", "rebuild"] CACHE = [] CACHESIZE = 10 class tzfile(tzfile): def __reduce__(self): return (gettz, (self._filename,)) def getzoneinfofile(): filenames = os.listdir(os.path.join(os.path.dirname(__file__))) filenames.sort() filenames.reverse() for entry in filenames: if entry.startswith("zoneinfo") and ".tar." in entry: return os.path.join(os.path.dirname(__file__), entry) return None ZONEINFOFILE = getzoneinfofile() del getzoneinfofile def setcachesize(size): global CACHESIZE, CACHE CACHESIZE = size del CACHE[size:] def gettz(name): tzinfo = None if ZONEINFOFILE: for cachedname, tzinfo in CACHE: if cachedname == name: break else: tf = TarFile.open(ZONEINFOFILE) try: zonefile = tf.extractfile(name) except KeyError: tzinfo = None else: tzinfo = tzfile(zonefile) tf.close() CACHE.insert(0, (name, tzinfo)) del CACHE[CACHESIZE:] return tzinfo def rebuild(filename, tag=None, format="gz"): import tempfile, shutil tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os.path.dirname(__file__) if tag: tag = "-"+tag targetname = "zoneinfo%s.tar.%s" % (tag, format) try: tf = TarFile.open(filename) for name in tf.getnames(): if not (name.endswith(".sh") or name.endswith(".tab") or name == "leapseconds"): tf.extract(name, tmpdir) filepath = os.path.join(tmpdir, name) os.system("zic -d %s %s" % (zonedir, filepath)) tf.close() target = os.path.join(moduledir, targetname) for entry in os.listdir(moduledir): if entry.startswith("zoneinfo") and ".tar." in entry: os.unlink(os.path.join(moduledir, entry)) tf = TarFile.open(target, "w:%s" % format) for entry in os.listdir(zonedir): entrypath = os.path.join(zonedir, entry) tf.add(entrypath, entry) tf.close() finally: shutil.rmtree(tmpdir)
Python
""" Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" import datetime import calendar __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class relativedelta: """ The relativedelta type is based on the specification of the excelent work done by M.-A. Lemburg in his mx.DateTime extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There's two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes: relativedelta(datetime1, datetime2) And the other way is to use the following keyword arguments: year, month, day, hour, minute, second, microsecond: Absolute information. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative. weekday: One of the weekday instances (MO, TU, etc). These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. Here is the behavior of operations with relativedelta: 1) Calculate the absolute year, using the 'year' argument, or the original datetime year, if the argument is not present. 2) Add the relative 'years' argument to the absolute year. 3) Do steps 1 and 2 for month/months. 4) Calculate the absolute day, using the 'day' argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations. 5) Add the relative 'days' argument to the absolute day. Notice that the 'weeks' argument is multiplied by 7 and added to 'days'. 6) Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds, microsecond/microseconds. 7) If the 'weekday' argument is present, calculate the weekday, with the given (wday, nth) tuple. wday is the index of the weekday (0-6, 0=Mon), and nth is the number of weeks to add forward or backward, depending on its signal. Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won't change the day. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: if not isinstance(dt1, datetime.date) or \ not isinstance(dt2, datetime.date): raise TypeError, "relativedelta only diffs datetime/date" if type(dt1) is not type(dt2): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 months = (dt1.year*12+dt1.month)-(dt2.year*12+dt2.month) self._set_months(months) dtm = self.__radd__(dt2) if dt1 < dt2: while dt1 > dtm: months += 1 self._set_months(months) dtm = self.__radd__(dt2) else: while dt1 < dtm: months -= 1 self._set_months(months) dtm = self.__radd__(dt2) delta = dt1 - dtm self.seconds = delta.seconds+delta.days*86400 self.microseconds = delta.microseconds else: self.years = years self.months = months self.days = days+weeks*7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if type(weekday) is int: self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31,59,90,120,151,181,212,243,273,304,334,366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError, "invalid year day (%d)" % yday self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = self.microseconds//abs(self.microseconds) div, mod = divmod(self.microseconds*s, 1000000) self.microseconds = mod*s self.seconds += div*s if abs(self.seconds) > 59: s = self.seconds//abs(self.seconds) div, mod = divmod(self.seconds*s, 60) self.seconds = mod*s self.minutes += div*s if abs(self.minutes) > 59: s = self.minutes//abs(self.minutes) div, mod = divmod(self.minutes*s, 60) self.minutes = mod*s self.hours += div*s if abs(self.hours) > 23: s = self.hours//abs(self.hours) div, mod = divmod(self.hours*s, 24) self.hours = mod*s self.days += div*s if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years += div*s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years = div*s else: self.years = 0 def __radd__(self, other): if not isinstance(other, datetime.date): raise TypeError, "unsupported type for add operation" elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth)-1)*7 if nth > 0: jumpdays += (7-ret.weekday()+weekday)%7 else: jumpdays += (ret.weekday()-weekday)%7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __rsub__(self, other): return self.__neg__().__radd__(other) def __add__(self, other): if not isinstance(other, relativedelta): raise TypeError, "unsupported type for add operation" return relativedelta(years=other.years+self.years, months=other.months+self.months, days=other.days+self.days, hours=other.hours+self.hours, minutes=other.minutes+self.minutes, seconds=other.seconds+self.seconds, microseconds=other.microseconds+self.microseconds, leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=other.second or self.microsecond) def __sub__(self, other): if not isinstance(other, relativedelta): raise TypeError, "unsupported type for sub operation" return relativedelta(years=other.years-self.years, months=other.months-self.months, days=other.days-self.days, hours=other.hours-self.hours, minutes=other.minutes-self.minutes, seconds=other.seconds-self.seconds, microseconds=other.microseconds-self.microseconds, leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=other.second or self.microsecond) def __neg__(self): return relativedelta(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __nonzero__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) def __mul__(self, other): f = float(other) return relativedelta(years=self.years*f, months=self.months*f, days=self.days*f, hours=self.hours*f, minutes=self.minutes*f, seconds=self.seconds*f, microseconds=self.microseconds*f, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __eq__(self, other): if not isinstance(other, relativedelta): return False if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): return self.__mul__(1/float(other)) def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("%s=%+d" % (attr, value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, `value`)) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) # vim:ts=4:sw=4:et
Python
# This code was originally contributed by Jeffrey Harris. import datetime import struct import _winreg __author__ = "Jeffrey Harris & Gustavo Niemeyer <gustavo@niemeyer.net>" __all__ = ["tzwin", "tzwinlocal"] ONEWEEK = datetime.timedelta(7) TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" def _settzkeyname(): global TZKEYNAME handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) try: _winreg.OpenKey(handle, TZKEYNAMENT).Close() TZKEYNAME = TZKEYNAMENT except WindowsError: TZKEYNAME = TZKEYNAME9X handle.Close() _settzkeyname() class tzwinbase(datetime.tzinfo): """tzinfo class based on win32's timezones available in the registry.""" def utcoffset(self, dt): if self._isdst(dt): return datetime.timedelta(minutes=self._dstoffset) else: return datetime.timedelta(minutes=self._stdoffset) def dst(self, dt): if self._isdst(dt): minutes = self._dstoffset - self._stdoffset return datetime.timedelta(minutes=minutes) else: return datetime.timedelta(0) def tzname(self, dt): if self._isdst(dt): return self._dstname else: return self._stdname def list(): """Return a list of all time zones known to the system.""" handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) tzkey = _winreg.OpenKey(handle, TZKEYNAME) result = [_winreg.EnumKey(tzkey, i) for i in range(_winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result list = staticmethod(list) def display(self): return self._display def _isdst(self, dt): dston = picknthweekday(dt.year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(dt.year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) if dston < dstoff: return dston <= dt.replace(tzinfo=None) < dstoff else: return not dstoff <= dt.replace(tzinfo=None) < dston class tzwin(tzwinbase): def __init__(self, name): self._name = name handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) tzkey = _winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name)) keydict = valuestodict(tzkey) tzkey.Close() handle.Close() self._stdname = keydict["Std"].encode("iso-8859-1") self._dstname = keydict["Dlt"].encode("iso-8859-1") self._display = keydict["Display"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=3l16h", keydict["TZI"]) self._stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1 (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[4:9] (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[12:17] def __repr__(self): return "tzwin(%s)" % repr(self._name) def __reduce__(self): return (self.__class__, (self._name,)) class tzwinlocal(tzwinbase): def __init__(self): handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) tzlocalkey = _winreg.OpenKey(handle, TZLOCALKEYNAME) keydict = valuestodict(tzlocalkey) tzlocalkey.Close() self._stdname = keydict["StandardName"].encode("iso-8859-1") self._dstname = keydict["DaylightName"].encode("iso-8859-1") try: tzkey = _winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname)) _keydict = valuestodict(tzkey) self._display = _keydict["Display"] tzkey.Close() except OSError: self._display = None handle.Close() self._stdoffset = -keydict["Bias"]-keydict["StandardBias"] self._dstoffset = self._stdoffset-keydict["DaylightBias"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=8h", keydict["StandardStart"]) (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[1:6] tup = struct.unpack("=8h", keydict["DaylightStart"]) (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[1:6] def __reduce__(self): return (self.__class__, ()) def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek 5 means last instance""" first = datetime.datetime(year, month, 1, hour, minute) weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1)) for n in xrange(whichweek): dt = weekdayone+(whichweek-n)*ONEWEEK if dt.month == month: return dt def valuestodict(key): """Convert a registry key's values to a dictionary.""" dict = {} size = _winreg.QueryInfoKey(key)[1] for i in range(size): data = _winreg.EnumValue(key, i) dict[data[0]] = data[1] return dict
Python
""" Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" __version__ = "1.5"
Python
""" Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard python 2.3+ datetime module. """ __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>" __license__ = "PSF License" import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different easter calculation methods: 1 - Original calculation in Julian calendar, valid in dates after 326 AD 2 - Original method, with date converted to Gregorian calendar, valid in years 1583 to 4099 3 - Revised method, in Gregorian calendar, valid in years 1583 to 4099 as well These methods are represented by the constants: EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 The default method is method 3. More about the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html """ if not (1 <= method <= 3): raise ValueError, "invalid method" # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 if method < 3: # Old method i = (19*g+15)%30 j = (y+y//4+i)%7 if method == 2: # Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e+y//100-16-(y//100-16)//4 else: # New method c = y//100 h = (c-c//4-(8*c+13)//25+19*g+15)%30 i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11)) j = (y+y//4+i+2-c+c//4)%7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i-j+e d = 1+(p+27+(p+6)//40)%31 m = 3+(p+26)//30 return datetime.date(int(y),int(m),int(d))
Python
#!/usr/bin/env pypy import os, sys, logging, re import argparse import fnmatch configurations = {'lite', 'pro'} package_dirs = { 'lite': ('src/cx/hell/android/pdfview',), 'pro': ('src/cx/hell/android/pdfviewpro',) } file_replaces = { 'lite': ( 'cx.hell.android.pdfview.', '"cx.hell.android.pdfview"', 'package cx.hell.android.pdfview;', 'android:icon="@drawable/pdfviewer"', ), 'pro': ( 'cx.hell.android.pdfviewpro.', '"cx.hell.android.pdfviewpro"', 'package cx.hell.android.pdfviewpro;', 'android:icon="@drawable/apvpro_icon"', ), } def make_comment(file_type, line): """Add comment to line and return modified line, but try not to add comments to already commented out lines.""" if file_type in ('java', 'c'): return '// ' + line if not line.startswith('//') else line elif file_type in ('html', 'xml'): return '<!-- ' + line.strip() + ' -->\n' if not line.strip().startswith('<!--') else line else: raise Exception("unknown file type: %s" % file_type) def remove_comment(file_type, line): """Remove comment from line, but only if line is commented, otherwise return unchanged line.""" if file_type in ('java', 'c'): if line.startswith('// '): return line[3:] else: return line elif file_type in ('html', 'xml'): if line.strip().startswith('<!-- ') and line.strip().endswith(' -->'): return line.strip()[5:-4] + '\n' else: return line else: raise Exception("unknown file type: %s" % file_type) def handle_comments(conf, file_type, lines, filename): new_lines = [] re_cmd_starts = re.compile(r'(?:(//|<!--))\s+#ifdef\s+(?P<def>[a-zA-Z]+)') re_cmd_ends = re.compile(r'(?:(//|<!--))\s+#endif') required_defs = [] for i, line in enumerate(lines): m = re_cmd_starts.search(line) if m: required_def = m.group('def') logging.debug("line %s:%d %s matches as start of %s" % (filename, i+1, line.strip(), required_def)) required_defs.append(required_def) new_lines.append(line) continue m = re_cmd_ends.search(line) if m: logging.debug("line %s:%d %s matches as endif" % (filename, i+1, line.strip())) required_defs.pop() new_lines.append(line) continue if len(required_defs) == 0: new_lines.append(line) elif len(required_defs) == 1 and required_defs[0] == conf: new_line = remove_comment(file_type, line) new_lines.append(new_line) else: new_line = make_comment(file_type, line) new_lines.append(new_line) assert len(new_lines) == len(lines) return new_lines def find_files(dirname, name): matches = [] for root, dirnames, filenames in os.walk(dirname): for filename in fnmatch.filter(filenames, name): matches.append(os.path.join(root, filename)) return matches def fix_package_dirs(conf): for i, dirname in enumerate(package_dirs[conf]): logging.debug("trying to restore %s" % dirname) if os.path.exists(dirname): if os.path.isdir(dirname): logging.debug(" already exists") continue else: logging.error(" %s already exists, but is not dir" % dirname) continue # find other name found_dirname = None for other_conf, other_dirnames in package_dirs.items(): other_dirname = other_dirnames[i] if other_conf == conf: continue # skip this conf when looking for other conf if os.path.isdir(other_dirname): if found_dirname is None: found_dirname = other_dirname else: # source dir already found :/ raise Exception("too many possible dirs for this package: %s, %s" % (found_dirname, other_dirname)) if found_dirname is None: raise Exception("didn't find %s" % dirname) # now rename found_dirname to dirname os.rename(found_dirname, dirname) logging.debug("renamed %s to %s" % (found_dirname, dirname)) def handle_comments_in_files(conf, file_type, filenames): for filename in filenames: lines = open(filename).readlines() new_lines = handle_comments(conf, file_type, lines, filename) if lines != new_lines: logging.debug("file %s comments changed" % filename) f = open(filename, 'w') f.write(''.join(new_lines)) f.close() del f def replace_in_files(conf, filenames): #logging.debug("about replace to %s in %s" % (conf, ', '.join(filenames))) other_confs = [other_conf for other_conf in file_replaces.keys() if other_conf != conf] #logging.debug("there are %d other confs to replace from: %s" % (len(other_confs), ', '.join(other_confs))) for filename in filenames: new_lines = [] lines = open(filename).readlines() for line in lines: new_line = line for i, target_string in enumerate(file_replaces[conf]): for other_conf in other_confs: source_string = file_replaces[other_conf][i] new_line = new_line.replace(source_string, target_string) new_lines.append(new_line) if new_lines != lines: logging.debug("file %s changed, writing..." % filename) f = open(filename, 'w') f.write(''.join(new_lines)) f.close() del f else: logging.debug("file %s didn't change, no need to rewrite" % filename) def fix_java_files(conf): filenames = find_files('src', name='*.java') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'java', filenames) def fix_xml_files(conf): filenames = find_files('.', name='*.xml') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'xml', filenames) def fix_html_files(conf): filenames = find_files('res', name='*.html') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'html', filenames) def fix_c_files(conf): filenames = find_files('jni/pdfview2', name='*.c') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'c', filenames) filenames = find_files('jni/pdfview2', name='*.h') replace_in_files(conf, filenames) handle_comments_in_files(conf, 'c', filenames) def fix_resources(conf): pass def main(): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') parser = argparse.ArgumentParser(description='Switch project configurations') parser.add_argument('--configuration', dest='configuration', default='lite') args = parser.parse_args() if not os.path.exists('AndroidManifest.xml'): raise Exception('android manifest not found, please run this script from main project directory') conf = args.configuration if conf not in configurations: raise Exception("invalid configuration: %s" % conf) fix_package_dirs(conf) fix_java_files(conf) fix_xml_files(conf) fix_html_files(conf) fix_c_files(conf) fix_resources(conf) if __name__ == '__main__': main()
Python
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
Python
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
Python
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
Python
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
Python
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
Python
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
Python
#!/usr/bin/env python import codecs import re import jinja2 import markdown def process_slides(): with codecs.open('../../presentation-output.html', 'w', encoding='utf8') as outfile: md = codecs.open('slides.md', encoding='utf8').read() md_slides = md.split('\n---\n') print 'Compiled %s slides.' % len(md_slides) slides = [] # Process each slide separately. for md_slide in md_slides: slide = {} sections = md_slide.split('\n\n') # Extract metadata at the beginning of the slide (look for key: value) # pairs. metadata_section = sections[0] metadata = parse_metadata(metadata_section) slide.update(metadata) remainder_index = metadata and 1 or 0 # Get the content from the rest of the slide. content_section = '\n\n'.join(sections[remainder_index:]) html = markdown.markdown(content_section) slide['content'] = postprocess_html(html, metadata) slides.append(slide) template = jinja2.Template(open('base.html').read()) outfile.write(template.render(locals())) def parse_metadata(section): """Given the first part of a slide, returns metadata associated with it.""" metadata = {} metadata_lines = section.split('\n') for line in metadata_lines: colon_index = line.find(':') if colon_index != -1: key = line[:colon_index].strip() val = line[colon_index + 1:].strip() metadata[key] = val return metadata def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html if __name__ == '__main__': process_slides()
Python