<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians

mapw= 100
maph=100
scrw=1000
scrh=640
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(mwidth)
print(mheight)
click = 0

go=0
screenside=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            walls['0'+str(x)+'0'+str(y)]=1
        else:
            walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            Sprite(rsquare_asset,(x*10, y*10))
        else:
            Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":5,"y":5,"dir":90}
change=1
first=1

def right(event):
    global change
    global first
    change=1
    first=1
    if Position['dir']<360:
        Position['dir']=Position['dir']+1
    else:
        Position['dir']=0

def left(event):
    global first
    global change
    change=1
    first=1
    if Position['dir']>0:
        Position['dir']=Position['dir']-1
    else:
        Position['dir']=359

def up(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)*90
    if sqdir==0:
        Position['x']=int(Position['x'])+1
    if sqdir==90:
        Position['y']=int(Position['y'])+1
    if sqdir==180:
        Position['x']=int(Position['x'])-1
    if sqdir==270:
        Position['y']=int(Position['y'])-1

def down(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)
    if sqdir==0:
        Position['x']=Position['x']-1
    if sqdir==1:
        Position['y']=Position['y']-1
    if sqdir==2:
        Position['x']=Position['x']+1
    if sqdir==3:
        Position['y']=Position['y']+1
def space(event):
    global go
    if go==0:
        go=1
    else:
        go=0
wall=True
raydir=0
def ray():
    global wall
    global raydir
    global first
    global walls
    global go
    global position
    global change
    global screenside
    if change==1 and go==1:
        clear=RectangleAsset(1000,640, noline, white)
        if first==1:
            print('clear')
            Sprite(clear,(110,0))
            raydir=int(Position['dir'])
            first=0
        print('ray has started')
        wall=False
        distance=0
        intilex=int(Position['x'])-int(Position['x'])//1
        intiley=int(Position['y'])-int(Position['y'])//1
        rayx=(int(Position['x'])*10)//10
        rayy=(int(Position['y'])*10)//10
        while wall==False:
            print('while works')
            print('0'+str(round(rayx))+'0'+str(round(rayy)))
            print(walls['0'+str(round(rayx))+'0'+str(round(rayy))])
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                print('wall is detected')
                wallcolor='b'+str(distance)
                print(wallcolor)
                wallbox=RectangleAsset(((10/float(distance))),10*(200/float(distance)), thinline, b5)
                Sprite(wallbox,(screenside+110,0))
                print('sprite is displayed')
                raydir=raydir+1/distance
                screenside=screenside+10/distance
                wall=True
                if screenside>=100:
                    change=0
                    screenside=0
                    print(change)
            else:
                print('else')
                distance=distance+abs(cos(radians(raydir)))+abs(sin(radians(raydir)))
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'd', right)
myapp.listenKeyEvent('keydown', 'a', left)
myapp.listenKeyEvent('keydown', 'w', up)
myapp.listenKeyEvent('keydown', 's', down)
myapp.listenKeyEvent('keydown', 'space', space)

myapp = App()
myapp.run(ray)<commit_msg>Updated from Brython Server: 12/14/2016 4:35:44 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians

mapw= 100
maph=100
scrw=1000
scrh=640
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(mwidth)
print(mheight)
click = 0

go=0
screenside=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            walls['0'+str(x)+'0'+str(y)]=1
        else:
            walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            Sprite(rsquare_asset,(x*10, y*10))
        else:
            Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":5,"y":5,"dir":90}
change=1
first=1

def right(event):
    global change
    global first
    change=1
    first=1
    if Position['dir']<360:
        Position['dir']=Position['dir']+1
    else:
        Position['dir']=0

def left(event):
    global first
    global change
    change=1
    first=1
    if Position['dir']>0:
        Position['dir']=Position['dir']-1
    else:
        Position['dir']=359

def up(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)*90
    if sqdir==0:
        Position['x']=int(Position['x'])+1
    if sqdir==90:
        Position['y']=int(Position['y'])+1
    if sqdir==180:
        Position['x']=int(Position['x'])-1
    if sqdir==270:
        Position['y']=int(Position['y'])-1

def down(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)
    if sqdir==0:
        Position['x']=Position['x']-1
    if sqdir==1:
        Position['y']=Position['y']-1
    if sqdir==2:
        Position['x']=Position['x']+1
    if sqdir==3:
        Position['y']=Position['y']+1
def space(event):
    global go
    if go==0:
        go=1
    else:
        go=0
wall=True
raydir=0
def ray():
    global wall
    global raydir
    global first
    global walls
    global go
    global position
    global change
    global screenside
    if change==1 and go==1:
        clear=RectangleAsset(1000,640, noline, white)
        if first==1:
            print('clear')
            Sprite(clear,(110,0))
            raydir=int(Position['dir'])
            first=0
        print('ray has started')
        wall=False
        distance=0
        intilex=int(Position['x'])-int(Position['x'])//1
        intiley=int(Position['y'])-int(Position['y'])//1
        rayx=(int(Position['x'])*10)//10
        rayy=(int(Position['y'])*10)//10
        while wall==False:
            print('while works')
            print('0'+str(round(rayx))+'0'+str(round(rayy)))
            print(walls['0'+str(round(rayx))+'0'+str(round(rayy))])
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                print('wall is detected')
                wallcolor='b'+str(distance)
                print(wallcolor)
                wallbox=RectangleAsset(((10/float(distance))),10*(200/float(distance)), thinline, b5)
                Sprite(wallbox,(screenside+110,0))
                print('sprite is displayed')
                raydir=raydir+.1/distance
                screenside=screenside+10/distance
                wall=True
                if screenside>=100:
                    change=0
                    screenside=0
                    print(change)
            else:
                print('else')
                distance=distance+abs(cos(radians(raydir)))+abs(sin(radians(raydir)))
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'd', right)
myapp.listenKeyEvent('keydown', 'a', left)
myapp.listenKeyEvent('keydown', 'w', up)
myapp.listenKeyEvent('keydown', 's', down)
myapp.listenKeyEvent('keydown', 'space', space)

myapp = App()
myapp.run(ray)<|endoftext|>


<commit_before>from aws import Action, BaseARN

service_name = 'Amazon Elasticsearch Service'
prefix = 'es'

class ARN(BaseARN):
    def __init__(self, resource="*", region='', account=''):
        sup = super(ARN, self)
        sup.__init__(service=prefix, resource=resource, region=region,
                     account=account)

class ESAction(Action):
    def __init__(self, action=None):
        self.prefix = prefix
        self.action = action

AddTags = ESAction('AddTags')
CreateElasticsearchDomain = ESAction('CreateElasticsearchDomain')
DeleteElasticsearchDomain = ESAction('DeleteElasticsearchDomain')
DescribeElasticsearchDomain = ESAction('DescribeElasticsearchDomain')
DescribeElasticsearchDomains = ESAction('DescribeElasticsearchDomains')
DescribeElasticsearchDomainConfig = \
    ESAction('DescribeElasticsearchDomainConfig')
ListDomainNames = ESAction('ListDomainNames')
ListTags = ESAction('ListTags')
RemoveTags = ESAction('RemoveTags')
UpdateElasticsearchDomainConfig = ESAction('UpdateElasticsearchDomainConfig')
<commit_msg>Adding ES HTTP methods<commit_after>from aws import Action, BaseARN

service_name = 'Amazon Elasticsearch Service'
prefix = 'es'

class ARN(BaseARN):
    def __init__(self, resource="*", region='', account=''):
        sup = super(ARN, self)
        sup.__init__(service=prefix, resource=resource, region=region,
                     account=account)

class ESAction(Action):
    def __init__(self, action=None):
        self.prefix = prefix
        self.action = action

AddTags = ESAction('AddTags')
CreateElasticsearchDomain = ESAction('CreateElasticsearchDomain')
DeleteElasticsearchDomain = ESAction('DeleteElasticsearchDomain')
DescribeElasticsearchDomain = ESAction('DescribeElasticsearchDomain')
DescribeElasticsearchDomains = ESAction('DescribeElasticsearchDomains')
DescribeElasticsearchDomainConfig = \
    ESAction('DescribeElasticsearchDomainConfig')
ESHttpDelete = ESAction('ESHttpDelete')
ESHttpGet = ESAction('ESHttpGet')
ESHttpHead = ESAction('ESHttpHead')
ESHttpPost = ESAction('ESHttpPost')
ESHttpPut = ESAction('ESHttpPut')
ListDomainNames = ESAction('ListDomainNames')
ListTags = ESAction('ListTags')
RemoveTags = ESAction('RemoveTags')
UpdateElasticsearchDomainConfig = ESAction('UpdateElasticsearchDomainConfig')
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Test package for `twodolib` module."""
<commit_msg>* fixed import<commit_after># -*- coding: utf-8 -*-
"""Test package for `twodolib` module."""
from . import test_twodolib  # noqa
<|endoftext|>


<commit_before>#!/usr/bin/python2.7
import pickle
from setDbName import setDbName
from deleteBook import deleteBook
ISBNuse={}
#Dizionario che contiene le informazioni sullo stato dell'ISBN
isbnPos={}
#Dizionario contenente l'ISBN in relazione alla posizione del volume
titleIsbn={}
#Dizionario contenente il titolo in relazione all'ISBN
isbnTitle={}
#Dizionario contenente l'autore in relazione all'ISBN
isbnAuthor={}
#Dizionario contenente il proprietario in relazione all'ISBN
ISBNown={}
nomeFile="db_libri"
try:
    o=open('bibliodb.pickle','r')
except IOError:
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
else:
    o.close
finally:
    with open('bibliodb.pickle','r') as o:
                    ISBNuse, isbnPos, titleIsbn, isbnTitle,isbnAuthor,nomeFile=pickle.load(o)
                    o.close
def add():
    titolo=raw_input("Titolo: ").lower()
    autore=raw_input("Autore: ").lower()
    isbn=raw_input("ISBN o ID volume: ")
    pos=raw_input("La posizione: ")
    isbnPos[isbn]=pos
    titleIsbn[titolo]= isbn
    isbnTitle[isbn]= titolo
    isbnAuthor[isbn]=autore
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
    pass
def find(titolo):
    print"Titolo: \t"
def titToISBN(tit):
    Isbn=titleIsbn[tit]
    return Isbn
    pass
def ISBNTotit(tISBN):
    titP=isbnTitle[tISBN]
    return titP
    pass
def ISBNToAut(aISBN):
    autP=isbnAuthor[aISBN]
    return autP
def prestaISBN(pISBN,state):
    ISBNuse[pISBN]=state
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
    print"Libro:\t\t"+ISBNTotit(pISBN)+"\n+Posizione:\t"+isbnPos[pISBN]+"\nStato:\t\t"
    if state==0:
        print"Prestato"
    elif state==1:
        print"Reso"
def manageISBN():
    #da implementare
    print "Da implementare..."
    todoP=raw_input("Si preferisce usare l'ISBN o il titolo? ").lower()
    if todoP.lower()=='isbn':
        isbn=raw_input("ISBN: ")
    else:
        titolo=raw_input("Titolo: ").lower()
        isbn=titToISBN(titolo)
    prestaISBN(isbn,0)
def main():
    while 1:
        print "Scrivi:\n* 's' per cambiare stato ad un volume;\n* 'a' per aggiungerne uno;\n* 'x' per generare un file TSV;\n* 'l' per ottenere una lista dei libri registrati;\n* 'i' per aprire il menu di impostazioni;"
        todoM=raw_input("* 'q' per uscire\n: ").lower()
        if todoM=='s':
            manageISBN()
        elif todoM.lower()=='l':
            lista()
        elif todoM.lower()=='x':
            tsvExport(nomeFile)
        elif todoM.lower()=='q':
            break
        elif todoM.lower()=='a':
            add()
        elif todoM.lower()=='i':
            iInput=raw_input("Scrivi 'e' per eliminare un libro, 'f' per cambiare il nome del file TSV").lower()
            if iInput=='e':
                deleteBook()
            elif iInput=='f':
                setDbName()
            else:
                print "ERRORE"
        else:
            print"ERRORE"
def lista():
    for isbn, num in isbnPos.items():
        print isbn+":\t"+ISBNTotit(isbn).title()+", "+ISBNToAut(isbn).title()+"\t"+num.upper()
#while True:
#    add()
def tsvExport(fileName):
    nome=(fileName.title())+".tsv"
    export=open(nome,'w')
    export.write("ISBN o Codice\tTitolo\tAutore\tPosizione\n")
    for isbn, num in isbnPos.items():
        export.write (isbn+"\t"+ISBNTotit(isbn).title()+"\t"+ISBNToAut(isbn).title()+"\t"+num.upper()+"\n")
    export.close()
main()
<commit_msg>Fixed a Pickle Import bug<commit_after>#!/usr/bin/python2.7
import pickle
from setDbName import setDbName
from deleteBook import deleteBook
ISBNuse={}
#Dizionario che contiene le informazioni sullo stato dell'ISBN
isbnPos={}
#Dizionario contenente l'ISBN in relazione alla posizione del volume
titleIsbn={}
#Dizionario contenente il titolo in relazione all'ISBN
isbnTitle={}
#Dizionario contenente l'autore in relazione all'ISBN
isbnAuthor={}
#Dizionario contenente il proprietario in relazione all'ISBN
ISBNown={}
nomeFile="db_libri"
try:
    o=open('bibliodb.pickle','r')
except IOError:
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
else:
    o.close
finally:
    with open('bibliodb.pickle','r') as o:
                    ISBNuse, isbnPos, titleIsbn, isbnTitle,isbnAuthor,nomeFile,ISBNown=pickle.load(o)
                    o.close
def add():
    titolo=raw_input("Titolo: ").lower()
    autore=raw_input("Autore: ").lower()
    isbn=raw_input("ISBN o ID volume: ")
    pos=raw_input("La posizione: ")
    isbnPos[isbn]=pos
    titleIsbn[titolo]= isbn
    isbnTitle[isbn]= titolo
    isbnAuthor[isbn]=autore
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
    pass
def find(titolo):
    print"Titolo: \t"
def titToISBN(tit):
    Isbn=titleIsbn[tit]
    return Isbn
    pass
def ISBNTotit(tISBN):
    titP=isbnTitle[tISBN]
    return titP
    pass
def ISBNToAut(aISBN):
    autP=isbnAuthor[aISBN]
    return autP
def prestaISBN(pISBN,state):
    ISBNuse[pISBN]=state
    o=open('bibliodb.pickle','w')
    pickle.dump((ISBNuse,isbnPos,titleIsbn,isbnTitle,isbnAuthor,nomeFile,ISBNown),o)
    o.close()
    print"Libro:\t\t"+ISBNTotit(pISBN)+"\n+Posizione:\t"+isbnPos[pISBN]+"\nStato:\t\t"
    if state==0:
        print"Prestato"
    elif state==1:
        print"Reso"
def manageISBN():
    #da implementare
    print "Da implementare..."
    todoP=raw_input("Si preferisce usare l'ISBN o il titolo? ").lower()
    if todoP.lower()=='isbn':
        isbn=raw_input("ISBN: ")
    else:
        titolo=raw_input("Titolo: ").lower()
        isbn=titToISBN(titolo)
    prestaISBN(isbn,0)
def main():
    while 1:
        print "Scrivi:\n* 's' per cambiare stato ad un volume;\n* 'a' per aggiungerne uno;\n* 'x' per generare un file TSV;\n* 'l' per ottenere una lista dei libri registrati;\n* 'i' per aprire il menu di impostazioni;"
        todoM=raw_input("* 'q' per uscire\n: ").lower()
        if todoM=='s':
            manageISBN()
        elif todoM.lower()=='l':
            lista()
        elif todoM.lower()=='x':
            tsvExport(nomeFile)
        elif todoM.lower()=='q':
            break
        elif todoM.lower()=='a':
            add()
        elif todoM.lower()=='i':
            iInput=raw_input("Scrivi 'e' per eliminare un libro, 'f' per cambiare il nome del file TSV").lower()
            if iInput=='e':
                deleteBook()
            elif iInput=='f':
                setDbName()
            else:
                print "ERRORE"
        else:
            print"ERRORE"
def lista():
    for isbn, num in isbnPos.items():
        print isbn+":\t"+ISBNTotit(isbn).title()+", "+ISBNToAut(isbn).title()+"\t"+num.upper()
#while True:
#    add()
def tsvExport(fileName):
    nome=(fileName.title())+".tsv"
    export=open(nome,'w')
    export.write("ISBN o Codice\tTitolo\tAutore\tPosizione\n")
    for isbn, num in isbnPos.items():
        export.write (isbn+"\t"+ISBNTotit(isbn).title()+"\t"+ISBNToAut(isbn).title()+"\t"+num.upper()+"\n")
    export.close()
main()
<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians, atan2

mapw= 100
maph=100
scrw=1000
scrh=640
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(mwidth)
print(mheight)
click = 0

go=0
screenside=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            walls['0'+str(x)+'0'+str(y)]=1
        else:
            walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            Sprite(rsquare_asset,(x*10, y*10))
        else:
            Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":5,"y":5,"dir":90}
change=1
first=1

def right(event):
    global change
    global first
    change=1
    first=1
    if Position['dir']<360:
        Position['dir']=Position['dir']+1
    else:
        Position['dir']=0

def left(event):
    global first
    global change
    change=1
    first=1
    if Position['dir']>0:
        Position['dir']=Position['dir']-1
    else:
        Position['dir']=359

def up(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)*90
    if sqdir==0:
        Position['x']=int(Position['x'])+1
    if sqdir==90:
        Position['y']=int(Position['y'])+1
    if sqdir==180:
        Position['x']=int(Position['x'])-1
    if sqdir==270:
        Position['y']=int(Position['y'])-1

def down(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)
    if sqdir==0:
        Position['x']=Position['x']-1
    if sqdir==1:
        Position['y']=Position['y']-1
    if sqdir==2:
        Position['x']=Position['x']+1
    if sqdir==3:
        Position['y']=Position['y']+1
def space(event):
    global go
    if go==0:
        go=1
    else:
        go=0
wall=True
raydir=0
inpov=0
def ray():
    global wall
    global inpov
    global raydir
    global first
    global scrh
    global walls
    global go
    global position
    global change
    global screenside
    if change==1 and go==1:
        clear=RectangleAsset(1000,640, noline, white)
        if first==1:
            print('clear')
            Sprite(clear,(110,0))
            raydir=int(Position['dir'])-45
            inpov=0
            first=0
        print('ray has started')
        wall=False
        distance=0
        intilex=int(Position['x'])-int(Position['x'])//1
        intiley=int(Position['y'])-int(Position['y'])//1
        rayx=(int(Position['x'])*10)//10
        rayy=(int(Position['y'])*10)//10
        while wall==False:
            print('while works')
            print('0'+str(round(rayx))+'0'+str(round(rayy)))
            print(walls['0'+str(round(rayx))+'0'+str(round(rayy))])
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                print('wall is detected')
                inpov=abs(raydir-int(Position['dir']))
                xdif=(int(Position['x'])-rayx)
                print(xdif)
                ydif=(int(Position['y'])-rayy)**2
                print(ydif)
                distance1=(abs(xdif)**2+abs(ydif))**(1/2)
                print(inpov)
                distance=distance1*sin(radians(90-(inpov)))
                print(distance)
                wallbox=RectangleAsset(((10/float(distance))),10*(200/(float(distance))), thinline, b5)
                Sprite(wallbox,(screenside+110,(scrh/2)-(10*(200/(float(distance))))/2))
                print('sprite is displayed')
                raydir=raydir+1/distance
                screenside=screenside+10/distance
                wall=True
                if inpov>=46:
                    change=0
                    screenside=0
                    print(change)
            else:
                print('else')
                distance=distance+1
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'd', right)
myapp.listenKeyEvent('keydown', 'a', left)
myapp.listenKeyEvent('keydown', 'w', up)
myapp.listenKeyEvent('keydown', 's', down)
myapp.listenKeyEvent('keydown', 'space', space)

myapp = App()
myapp.run(ray)<commit_msg>Updated from Brython Server: 1/3/2017 1:47:04 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians, atan2

mapw= 100
maph=100
scrw=1000
scrh=640
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(mwidth)
print(mheight)
click = 0

go=0
screenside=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            walls['0'+str(x)+'0'+str(y)]=1
        else:
            walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in mwidth:
    for y in mheight:
        if x==0 or y==0 or x==mapw//10 or y==maph//10:
            Sprite(rsquare_asset,(x*10, y*10))
        else:
            Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":5,"y":5,"dir":90}
change=1
first=1

def right(event):
    global change
    global first
    change=1
    first=1
    if Position['dir']<360:
        Position['dir']=Position['dir']+1
    else:
        Position['dir']=0

def left(event):
    global first
    global change
    change=1
    first=1
    if Position['dir']>0:
        Position['dir']=Position['dir']-1
    else:
        Position['dir']=359

def up(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)*90
    if sqdir==0:
        Position['x']=int(Position['x'])+1
    if sqdir==90:
        Position['y']=int(Position['y'])+1
    if sqdir==180:
        Position['x']=int(Position['x'])-1
    if sqdir==270:
        Position['y']=int(Position['y'])-1

def down(event):
    global change
    global first
    change=1
    first=1
    sqdir=(int(Position['dir'])//90)
    if sqdir==0:
        Position['x']=Position['x']-1
    if sqdir==1:
        Position['y']=Position['y']-1
    if sqdir==2:
        Position['x']=Position['x']+1
    if sqdir==3:
        Position['y']=Position['y']+1
def space(event):
    global go
    if go==0:
        go=1
    else:
        go=0
wall=True
raydir=0
inpov=0
def ray():
    global wall
    global inpov
    global raydir
    global first
    global scrh
    global walls
    global go
    global position
    global change
    global screenside
    if change==1 and go==1:
        clear=RectangleAsset(1000,640, noline, white)
        if first==1:
            print('clear')
            Sprite(clear,(110,0))
            raydir=int(Position['dir'])-45
            inpov=0
            first=0
            oldrayx=0
            oldrayy=0
        print('ray has started')
        wall=False
        distance=0
        intilex=int(Position['x'])-int(Position['x'])//1
        intiley=int(Position['y'])-int(Position['y'])//1
        rayx=(int(Position['x'])*10)//10
        rayy=(int(Position['y'])*10)//10
        while wall==False:
            print('while works')
            print('0'+str(round(rayx))+'0'+str(round(rayy)))
            print(walls['0'+str(round(rayx))+'0'+str(round(rayy))])
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                print('wall is detected')
                inpov=abs(raydir-int(Position['dir']))
                xdif=(int(Position['x'])-rayx)
                print(xdif)
                ydif=(int(Position['y'])-rayy)**2
                print(ydif)
                distance1=(abs(xdif)**2+abs(ydif))**(1/2)
                print(inpov)
                if round(rayx)!=oldrayx and round(rayy)!=oldrayy:
                    distance=distance1*sin(radians(90-(inpov)))
                print(distance)
                wallbox=RectangleAsset(((10/float(distance))),10*(200/(float(distance))), thinline, b5)
                Sprite(wallbox,(screenside+110,(scrh/2)-(10*(200/(float(distance))))/2))
                print('sprite is displayed')
                raydir=raydir+1/distance
                screenside=screenside+10/distance
                wall=True
                oldrayx=round(rayx)
                oldrayy=round(rayy)
                if inpov>=46:
                    change=0
                    screenside=0
                    print(change)
            else:
                print('else')
                distance=distance+1
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'd', right)
myapp.listenKeyEvent('keydown', 'a', left)
myapp.listenKeyEvent('keydown', 'w', up)
myapp.listenKeyEvent('keydown', 's', down)
myapp.listenKeyEvent('keydown', 'space', space)

myapp = App()
myapp.run(ray)<|endoftext|>


<commit_before>import Image
import AlignLib
from skimage import data
import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple

Rectangle = namedtuple('Rectangle', 'xmin, ymin, xmax, ymax')

p1 = Image.Image(data.camera())
p2 = Image.Image(data.coins())
p3 = Image.Image(data.chelsea()[:, :, 0])
p4 = Image.Image(data.astronaut()[:, :, 0])
print np.shape(p1.Img), np.shape(p2.Img), np.shape(p3.Img), np.shape(p4.Img)

offsets = AlignLib.Align((p1,p2,p3,p4))
print offsets

def MoveAlignedImages(image, offsets):
	image.Img = np.roll(np.roll(image.Img,
			offsets[0], axis = 1),
			offsets[1], axis = 0)
#	mask =
	mask = np.all(np.isnan(image.Img), axis = 0)
	mask0 = np.all(np.isnan(image.Img), axis = 1)
	image.Img = image.Img[:, ~mask]
	image.Img = image.Img[~mask0, :]
	return image

#	Img1a = np.copy(Img1)
#	Img2a = np.copy(Img2)

#	if self.horizontal >= 0:
#		Img2a = Img2a[:, self.horizontal:]
#		Img1a = Img1a[:, self.horizontal:]
#	#			self.Img2 = self.Img2[:, self.horizontal:]
#		self.Img1 = self.Img1[:, self.horizontal:]
#	else:
#		Img2a = Img2a[:, :self.horizontal]
#		Img1a = Img1a[:, :self.horizontal]
#	#			self.Img2 = self.Img2[:, :self.horizontal]
#	#			self.Img1 = self.Img1[:, :self.horizontal]

#	if self.vertical >= 0:
#		Img2a = Img2a[self.vertical:, :]
#		Img1a = Img1a[self.vertical:, :]
#		self.Img2 = self.Img2[self.vertical:, :]
#		self.Img1 = self.Img1[self.vertical:, :]
#	else:
#		Img2a = Img2a[:self.vertical, :]
#		Img1a = Img1a[:self.vertical, :]
#		self.Img2 = self.Img2[:self.vertical, :]
#		self.Img1 = self.Img1[:self.vertical, :]
#	#		print np.where(np.isnan(Img1a))
#	self.ax2 = plt.axes([0.05, 0.05, 0.90, 0.90])
#	#		plt.imshow(Img2a)
#	self.ShowImages(self.Img1, self.Img2, self.ax2)
#	#		plt.close()

#p2a = MoveAlignedImages(p2, offsets[:, 1])
#print p1.size, p2.size
r1 = Rectangle(offsets[0, 0], offsets[1,0], p1.size[1]+offsets[0,0], p1.size[0]+offsets[1,0])
r2 = Rectangle(offsets[0, 1], offsets[1,1], p2.size[1]+offsets[0,1], p2.size[0]+offsets[1,1])

def FindRectangleIntersectionWillsWay(r1, r2):
	if (r1.xmax<r2.xmin or r2.xmax<r1.xmin or r1.ymax<r2.ymin or r2.ymax<r1.ymin):
		raise ValueError("No intersection! Fix it!")

	h_edge = sorted((r1.xmin, r1.xmax, r2.xmin, r2.xmax))
	v_edge = sorted((r1.ymin, r1.ymax, r2.ymin, r2.ymax))
	return Rectangle(h_edge[1], v_edge[1], h_edge[2], v_edge[2])

print "Will's rectangle stuff"
#r1=Rectangle(0,0,10,10)
#r2=Rectangle(2,2,17,17)
print FindRectangleIntersectionWillsWay(r1, r2)

#print h_edge, v_edge
#r_overlap = Rectangle(v_edge[1], h_edge[1], v_edge[2], h_edge[2])

#p1b = p1.Img[r_overlap.xmin-offsets[0,0]:r_overlap.xmax-offsets[0,0],
#	r_overlap.ymin-offsets[1,0]:r_overlap.ymax-offsets[1,0]]

#print r_overlap.xmin-offsets[0,1], r_overlap.xmax-offsets[0,1], r_overlap.ymin-offsets[1,1], r_overlap.ymax-offsets[1,1]
#p2b = p2.Img[r_overlap.xmin-offsets[0,1]:r_overlap.xmax-offsets[0,1],
#	r_overlap.ymin-offsets[1,1]:r_overlap.ymax-offsets[1,1]]

print 'offsets', offsets
#print 'sizes', np.roll(np.transpose((p1.size, p2.size, p3.size, p4.size)), 1, axis = 0)

maxcorners = np.roll(np.transpose((p1.size, p2.size, p3.size, p4.size)), 1, axis = 0)
overlapcorners = (np.max(offsets, axis = 1), np.min(maxcorners+offsets, axis = 1))

print 'overlapcorners', overlapcorners

p1_aligned = p1.Img[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]
p2_aligned = np.roll(np.roll(p2.Img,
			offsets[0][1], axis = 1),
			offsets[1][1], axis = 0)
p2_aligned = p2_aligned[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]

p3_aligned = np.roll(np.roll(p3.Img,
			offsets[0][2], axis = 1),
			offsets[1][2], axis = 0)
p3_aligned = p3_aligned[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]

p4_aligned = np.roll(np.roll(p4.Img,
			offsets[0][3], axis = 1),
			offsets[1][3], axis = 0)
p4_aligned = p4_aligned[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]
#p3_aligned = p3.Img[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]
#p4_aligned = p4.Img[overlapcorners[0][1]:overlapcorners[1][1], overlapcorners[0][0]:overlapcorners[1][0]]

#p1.Img = np.roll(np.roll(p1.Img, offsets[0][0], axis = 1), offsets[1][0], axis = 0)
#p2.Img = np.roll(np.roll(p2.Img, offsets[0][1], axis = 1), offsets[1][1], axis = 0)

#mask = ~np.isnan(p1.Img)&~np.isnan(p2.Img)&~np.isnan(p3.Img)&~np.isnan(p4.Img)

fig = plt.figure()
ax = plt.axes([0,0,1,1])
ax.imshow(p2_aligned, interpolation = 'none', cmap = 'Reds')
ax.imshow(p3_aligned, interpolation = 'none', cmap = 'gray', alpha = 0.2)
#ax.imshow(p4_aligned, interpolation = 'none', cmap = 'hot', alpha = 0.2)
ax.imshow(p1_aligned, alpha = 0.2, cmap = 'Blues', interpolation = 'none')
#ax.imshow(mask, cmap = 'gray', alpha = 0.8)
ax.axis('off')

plt.show()
<commit_msg>Update test file<commit_after>import Image
import AlignLib
from skimage import data
import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple
import AlignCrop

Rectangle = namedtuple('Rectangle', 'xmin, ymin, xmax, ymax')

p1 = Image.Image(data.camera())
p2 = Image.Image(data.coins())
p3 = Image.Image(data.chelsea()[:, :, 0])
p4 = Image.Image(data.astronaut()[:, :, 0])
#print np.shape(p1.Img), np.shape(p2.Img), np.shape(p3.Img), np.shape(p4.Img)

offsets = AlignLib.Align((p1,p2,p3,p4))
#print offsets

################Will's thing
r1 = Rectangle(offsets[0, 0], offsets[1,0], p1.size[1]+offsets[0,0], p1.size[0]+offsets[1,0])
r2 = Rectangle(offsets[0, 1], offsets[1,1], p2.size[1]+offsets[0,1], p2.size[0]+offsets[1,1])

def FindRectangleIntersectionWillsWay(r1, r2):
	if (r1.xmax<r2.xmin or r2.xmax<r1.xmin or r1.ymax<r2.ymin or r2.ymax<r1.ymin):
		raise ValueError("No intersection! Fix it!")

	h_edge = sorted((r1.xmin, r1.xmax, r2.xmin, r2.xmax))
	v_edge = sorted((r1.ymin, r1.ymax, r2.ymin, r2.ymax))
	return Rectangle(h_edge[1], v_edge[1], h_edge[2], v_edge[2])

#print "Will's rectangle stuff"
#r1=Rectangle(0,0,10,10)
#r2=Rectangle(2,2,17,17)
#print FindRectangleIntersectionWillsWay(r1, r2)
################End of Will's thing

#maxcorners = np.roll(np.transpose((p1.size, p2.size, p3.size, p4.size)), 1, axis = 0)
#overlapcorners = (np.max(offsets, axis = 1), np.min(maxcorners+offsets, axis = 1))
#p2_alignedtest = p2.Img[overlapcorners[0][1] - offsets[1][1]:overlapcorners[1][1]-offsets[1][1], overlapcorners[0][0] - offsets[0][1]:overlapcorners[1][0] - offsets[0][1]]
print (offsets)
AlignCrop.AlignCrop((p1, p2, p3, p4), offsets)

fig = plt.figure()
ax = plt.axes([0,0,1,1])
ax.imshow(p3.Img, interpolation = 'none', cmap = 'gray')
ax.imshow(p1.Img, interpolation = 'none', cmap = 'Reds', alpha = 0.2)
#ax.imshow(p4_aligned, interpolation = 'none', cmap = 'hot', alpha = 0.2)
#ax.imshow(p1_aligned, alpha = 0.2, cmap = 'Blues', interpolation = 'none')
#ax.imshow(mask, cmap = 'gray', alpha = 0.8)
ax.axis('off')

plt.show()
<|endoftext|>


<commit_before># Noninteractive UI
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

import sys, time
from UIBase import UIBase

class Basic(UIBase):
    def getpass(s, accountname, config, errmsg = None):
        raise NotImplementedError, "Prompting for a password is not supported in noninteractive mode."

    def _display(s, msg):
        print msg
        sys.stdout.flush()

    def warn(s, msg, minor = 0):
        warntxt = 'WARNING'
        if minor:
            warntxt = 'warning'
        sys.stderr.write(warntxt + ": " + str(msg) + "\n")

    def sleep(s, sleepsecs):
        if s.verbose >= 0:
            s._msg("Sleeping for %d:%02d" % (sleepsecs / 60, sleepsecs % 60))
        UIBase.sleep(s, sleepsecs)

    def sleeping(s, sleepsecs, remainingsecs):
        if sleepsecs > 0:
            time.sleep(sleepsecs)
        return 0

class Quiet(Basic):
    def __init__(s, config, verbose = -1):
        Basic.__init__(s, config, verbose)
<commit_msg>Fixed locked() for noninteractive UIs<commit_after># Noninteractive UI
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

import sys, time
from UIBase import UIBase

class Basic(UIBase):
    def getpass(s, accountname, config, errmsg = None):
        raise NotImplementedError, "Prompting for a password is not supported in noninteractive mode."

    def _display(s, msg):
        print msg
        sys.stdout.flush()

    def warn(s, msg, minor = 0):
        warntxt = 'WARNING'
        if minor:
            warntxt = 'warning'
        sys.stderr.write(warntxt + ": " + str(msg) + "\n")

    def sleep(s, sleepsecs):
        if s.verbose >= 0:
            s._msg("Sleeping for %d:%02d" % (sleepsecs / 60, sleepsecs % 60))
        UIBase.sleep(s, sleepsecs)

    def sleeping(s, sleepsecs, remainingsecs):
        if sleepsecs > 0:
            time.sleep(sleepsecs)
        return 0

    def locked(s):
        s.warn("Another OfflineIMAP is running with the same metadatadir; exiting.")

class Quiet(Basic):
    def __init__(s, config, verbose = -1):
        Basic.__init__(s, config, verbose)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import pprint
from .exceptions import NoSessionError, ModelNotFoundError, APIError

__all__ = ['Advertiser', 'Bidder', 'Browser', 'Campaign', 'Category', 'ConnectionType',
           'ConversionPixel', 'Country', 'Creative', 'Datacenter', 'DeviceType',
           'Domain', 'Fallback', 'Isp', 'Languages', 'Network', 'OperatingSystem',
           'Placement', 'Profile', 'Publisher', 'Reason', 'Segment', 'Seller',
           'Site', 'Size', 'User']

class AtomxModel(object):
    def __init__(self, session=None, **attributes):
        super(AtomxModel, self).__setattr__('session', session)
        super(AtomxModel, self).__setattr__('_attributes', attributes)
        super(AtomxModel, self).__setattr__('_dirty', set())  # list of changed attributes

    def __getattr__(self, item):
        from .utils import get_attribute_model_name
        model_name = get_attribute_model_name(item)
        attr = self._attributes.get(item)
        # if requested attribute item is a valid model name and and int or
        # a list of integers, just delete the attribute so it gets
        # fetched from the api
        if model_name and (isinstance(attr, int) or
                           isinstance(attr, list) and len(attr) > 0 and
                           isinstance(attr[0], int)):
            del self._attributes[item]

        # if item not in model and session exists,
        # try to load model attribute from server if possible
        if not item.startswith('_') and item not in self._attributes and self.session:
            try:
                v = self.session.get(self.__class__.__name__ + '/' +
                                     str(self.id) + '/' + str(item))
                self._attributes[item] = v
            except APIError as e:
                raise AttributeError(e)
        return self._attributes.get(item)

    def __setattr__(self, key, value):
        if self._attributes.get(key) != value:
            self._attributes[key] = value
            self._dirty.add(key)

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__, pprint.pformat(self.json))

    @property
    def _dirty_json(self):
        return {k: self._attributes[k] for k in self._dirty}

    @property
    def json(self):
        return self._attributes

    def save(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        res = session.post(self.__class__.__name__, json=self.json)
        self.__init__(session=session, **res)
        return self

    def update(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        res = session.put(self.__class__.__name__, self.id, json=self._dirty_json)
        self.__init__(session=session, **res)
        return self

    def delete(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        return session.delete(self.__class__.__name__, self.id, json=self._dirty_json)

    def reload(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        if not hasattr(self, 'id'):
            raise ModelNotFoundError("Can't reload without 'id' parameter. "
                                     "Forgot to save() first?")
        res = session.get(self.__class__.__name__ + '/' + str(self.id))
        self.__init__(session=session, **res.json)
        return self

for m in __all__:
    locals()[m] = type(m, (AtomxModel,), {})
<commit_msg>rename save -> create (and save==update)<commit_after># -*- coding: utf-8 -*-

import pprint
from .exceptions import NoSessionError, ModelNotFoundError, APIError

__all__ = ['Advertiser', 'Bidder', 'Browser', 'Campaign', 'Category', 'ConnectionType',
           'ConversionPixel', 'Country', 'Creative', 'Datacenter', 'DeviceType',
           'Domain', 'Fallback', 'Isp', 'Languages', 'Network', 'OperatingSystem',
           'Placement', 'Profile', 'Publisher', 'Reason', 'Segment', 'Seller',
           'Site', 'Size', 'User']

class AtomxModel(object):
    def __init__(self, session=None, **attributes):
        super(AtomxModel, self).__setattr__('session', session)
        super(AtomxModel, self).__setattr__('_attributes', attributes)
        super(AtomxModel, self).__setattr__('_dirty', set())  # list of changed attributes

    def __getattr__(self, item):
        from .utils import get_attribute_model_name
        model_name = get_attribute_model_name(item)
        attr = self._attributes.get(item)
        # if requested attribute item is a valid model name and and int or
        # a list of integers, just delete the attribute so it gets
        # fetched from the api
        if model_name and (isinstance(attr, int) or
                           isinstance(attr, list) and len(attr) > 0 and
                           isinstance(attr[0], int)):
            del self._attributes[item]

        # if item not in model and session exists,
        # try to load model attribute from server if possible
        if not item.startswith('_') and item not in self._attributes and self.session:
            try:
                v = self.session.get(self.__class__.__name__ + '/' +
                                     str(self.id) + '/' + str(item))
                self._attributes[item] = v
            except APIError as e:
                raise AttributeError(e)
        return self._attributes.get(item)

    def __setattr__(self, key, value):
        if self._attributes.get(key) != value:
            self._attributes[key] = value
            self._dirty.add(key)

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__, pprint.pformat(self.json))

    @property
    def _dirty_json(self):
        return {k: self._attributes[k] for k in self._dirty}

    @property
    def json(self):
        return self._attributes

    def create(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        res = session.post(self.__class__.__name__, json=self.json)
        self.__init__(session=session, **res)
        return self

    def update(self, session=None):
        return self.save(session)

    def save(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        res = session.put(self.__class__.__name__, self.id, json=self._dirty_json)
        self.__init__(session=session, **res)
        return self

    def delete(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        return session.delete(self.__class__.__name__, self.id, json=self._dirty_json)

    def reload(self, session=None):
        session = session or self.session
        if not session:
            raise NoSessionError
        if not hasattr(self, 'id'):
            raise ModelNotFoundError("Can't reload without 'id' parameter. "
                                     "Forgot to save() first?")
        res = session.get(self.__class__.__name__ + '/' + str(self.id))
        self.__init__(session=session, **res.json)
        return self

for m in __all__:
    locals()[m] = type(m, (AtomxModel,), {})
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2010-2013 Raphaël Barrois

from test_full import *
from test_lexer import *
from test_parser import *
from test_tokens import *
<commit_msg>Fix tests for Python3.<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2010-2013 Raphaël Barrois

from .test_full import *
from .test_lexer import *
from .test_parser import *
from .test_tokens import *
<|endoftext|>


<commit_before>from PIL import Image, ExifTags

from django.conf import settings
from django.contrib.postgres.fields import ArrayField, HStoreField
from django.db import connection, models
from django.db.models.query import QuerySet
from django.utils.translation import ugettext_lazy as _

from markitup.fields import MarkupField
from model_utils import Choices
from model_utils.models import StatusModel, TimeStampedModel

def sanitize_exif_value(key, value):
    if isinstance(value, str):
        return value.replace('\x00', '').strip()
    return str(value)

class GalleryQuerySet(QuerySet):
    def published(self):
        return self.filter(status='published')

class Gallery(StatusModel, TimeStampedModel):
    STATUS = Choices(
        ('draft', _("draft")),
        ('published', _("published")),
    )
    author = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, verbose_name=_("author"), on_delete=models.CASCADE)
    title = models.CharField(_("title"), max_length=255)
    slug = models.SlugField(_("slug"), max_length=255, unique=True)
    description = MarkupField(_("description"))
    shot_date = models.DateField(_("shot date"), null=True, blank=True)
    cover_photo = models.ImageField(_("cover photo"), upload_to='photos/%Y/%m/%d', null=True, blank=True)

    objects = GalleryQuerySet.as_manager()

    class Meta:
        verbose_name_plural = _("Galleries")
        ordering = ['-shot_date']

    def __str__(self):
        """
        The string representation of a gallery is its title.
        """
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('pgallery:gallery_details', [], {'slug': self.slug})

    def get_teaser_photos(self):
        return self.photos.all()[:4]

class PhotoManager(models.Manager):
    def tagged(self, tag):
        return self.filter(tags__contains=[tag]).order_by('-gallery__shot_date')

    def for_exif(self, exif_key, exif_value):
        return self.filter(exif__contains={exif_key: exif_value}).order_by('-gallery__shot_date')

    def popular_tags(self, count=10):
        query = """
        select
            t.tag,
            count(t.tag) as tag_count
        from
            (select unnest(tags) as tag from %s) t
        group by tag
        order by tag_count desc
        limit %%s
        """ % Photo._meta.db_table
        cursor = connection.cursor()
        cursor.execute(query, (count,))
        tags = [{'tag': row[0], 'count': row[1]} for row in cursor.fetchall()]
        return tags

class Photo(TimeStampedModel):
    gallery = models.ForeignKey(Gallery, null=True, related_name='photos', verbose_name=_("gallery"), on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, verbose_name=_("author"), on_delete=models.CASCADE)
    title = models.CharField(_("title"), max_length=255)
    image = models.ImageField(_("image"), upload_to='photos/%Y/%m/%d')
    tags = ArrayField(models.CharField(max_length=64), blank=True, default=list)
    exif = HStoreField(editable=False, default={}, db_index=True)

    objects = PhotoManager()

    class Meta:
        verbose_name_plural = _("Photos")
        ordering = ['created']

    def __str__(self):
        """
        The string representation of a photo is its title.
        """
        return self.title

    def save(self, *args, **kwargs):
        """
        Updates EXIF data before saving.
        """
        # you really should be doing this in a background task
        try:
            img = Image.open(self.image.file)
            raw_exif = img._getexif()
            if raw_exif:
                self.exif = {ExifTags.TAGS[k]: sanitize_exif_value(k, v) for k, v in raw_exif.items() if k in ExifTags.TAGS}
        except Exception:
            pass
        super(Photo, self).save(*args, **kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ('pgallery:photo_details', [], {'pk': self.pk})

    def get_next_photo(self):
        """
        Returns next photo from the same gallery (in chronological order).

        Wraps around from last photo in the gallery to the first one.
        """
        try:
            next_photo = Photo.objects.filter(
                gallery=self.gallery,
                created__gt=self.created,
            )[0]
        except IndexError:
            next_photo = Photo.objects.filter(gallery=self.gallery)[0]
        return next_photo

    def get_previous_photo(self):
        """
        Returns previous photo from the same gallery (in chronological order).

        Wraps around from first photo in the gallery to the last one.
        """
        try:
            previous_photo = Photo.objects.filter(
                gallery=self.gallery,
                created__lt=self.created,
            ).latest('created')
        except Photo.DoesNotExist:
            previous_photo = Photo.objects.filter(gallery=self.gallery).latest('created')
        return previous_photo
<commit_msg>Use reverse() instead of @models.permalink.<commit_after>from PIL import Image, ExifTags

from django.conf import settings
from django.contrib.postgres.fields import ArrayField, HStoreField
from django.db import connection, models
from django.db.models.query import QuerySet
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _

from markitup.fields import MarkupField
from model_utils import Choices
from model_utils.models import StatusModel, TimeStampedModel

def sanitize_exif_value(key, value):
    if isinstance(value, str):
        return value.replace('\x00', '').strip()
    return str(value)

class GalleryQuerySet(QuerySet):
    def published(self):
        return self.filter(status='published')

class Gallery(StatusModel, TimeStampedModel):
    STATUS = Choices(
        ('draft', _("draft")),
        ('published', _("published")),
    )
    author = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, verbose_name=_("author"), on_delete=models.CASCADE)
    title = models.CharField(_("title"), max_length=255)
    slug = models.SlugField(_("slug"), max_length=255, unique=True)
    description = MarkupField(_("description"))
    shot_date = models.DateField(_("shot date"), null=True, blank=True)
    cover_photo = models.ImageField(_("cover photo"), upload_to='photos/%Y/%m/%d', null=True, blank=True)

    objects = GalleryQuerySet.as_manager()

    class Meta:
        verbose_name_plural = _("Galleries")
        ordering = ['-shot_date']

    def __str__(self):
        """
        The string representation of a gallery is its title.
        """
        return self.title

    def get_absolute_url(self):
        return reverse('pgallery:gallery_details', kwargs={'slug': self.slug})

    def get_teaser_photos(self):
        return self.photos.all()[:4]

class PhotoManager(models.Manager):
    def tagged(self, tag):
        return self.filter(tags__contains=[tag]).order_by('-gallery__shot_date')

    def for_exif(self, exif_key, exif_value):
        return self.filter(exif__contains={exif_key: exif_value}).order_by('-gallery__shot_date')

    def popular_tags(self, count=10):
        query = """
        select
            t.tag,
            count(t.tag) as tag_count
        from
            (select unnest(tags) as tag from %s) t
        group by tag
        order by tag_count desc
        limit %%s
        """ % Photo._meta.db_table
        cursor = connection.cursor()
        cursor.execute(query, (count,))
        tags = [{'tag': row[0], 'count': row[1]} for row in cursor.fetchall()]
        return tags

class Photo(TimeStampedModel):
    gallery = models.ForeignKey(Gallery, null=True, related_name='photos', verbose_name=_("gallery"), on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, verbose_name=_("author"), on_delete=models.CASCADE)
    title = models.CharField(_("title"), max_length=255)
    image = models.ImageField(_("image"), upload_to='photos/%Y/%m/%d')
    tags = ArrayField(models.CharField(max_length=64), blank=True, default=list)
    exif = HStoreField(editable=False, default={}, db_index=True)

    objects = PhotoManager()

    class Meta:
        verbose_name_plural = _("Photos")
        ordering = ['created']

    def __str__(self):
        """
        The string representation of a photo is its title.
        """
        return self.title

    def save(self, *args, **kwargs):
        """
        Updates EXIF data before saving.
        """
        # you really should be doing this in a background task
        try:
            img = Image.open(self.image.file)
            raw_exif = img._getexif()
            if raw_exif:
                self.exif = {ExifTags.TAGS[k]: sanitize_exif_value(k, v) for k, v in raw_exif.items() if k in ExifTags.TAGS}
        except Exception:
            pass
        super(Photo, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('pgallery:photo_details', kwargs={'pk': self.pk})

    def get_next_photo(self):
        """
        Returns next photo from the same gallery (in chronological order).

        Wraps around from last photo in the gallery to the first one.
        """
        try:
            next_photo = Photo.objects.filter(
                gallery=self.gallery,
                created__gt=self.created,
            )[0]
        except IndexError:
            next_photo = Photo.objects.filter(gallery=self.gallery)[0]
        return next_photo

    def get_previous_photo(self):
        """
        Returns previous photo from the same gallery (in chronological order).

        Wraps around from first photo in the gallery to the last one.
        """
        try:
            previous_photo = Photo.objects.filter(
                gallery=self.gallery,
                created__lt=self.created,
            ).latest('created')
        except Photo.DoesNotExist:
            previous_photo = Photo.objects.filter(gallery=self.gallery).latest('created')
        return previous_photo
<|endoftext|>


<commit_before>from collections import namedtuple

ServerInfo = namedtuple('ServerInfo', ['password', 'players', 'max_players', 'hostname', 'gamemode', 'language'])
<commit_msg>Define models for rule and client responses<commit_after>from __future__ import absolute_import, unicode_literals
from collections import namedtuple

ServerInfo = namedtuple('ServerInfo', ['password', 'players', 'max_players', 'hostname', 'gamemode', 'language'])
Rule = namedtuple('Rule', ['name', 'value'])
Client = namedtuple('Client', ['name', 'score'])
ClientDetail = namedtuple('ClientDetail', ['id', 'name', 'score', 'ping'])
<|endoftext|>


<commit_before>import mistune
import re
import copy
import urlparse
import posixpath

#TODO disable embedded HTML ?

__version__ = '0.0.0'
__author__ = 'John Pickerill <me@curiouscrab.com>'
__all__ = [
    'BlockGrammar', 'BlockLexer',
    'InlineGrammar', 'InlineLexer',
    'Renderer', 'Markdown',
    'markdown', 'escape',
]

class Markdown(mistune.Markdown):
    def __init__(self, renderer=None, inline=None, block=None, **kwargs):
        super(Markdown, self).__init__(renderer=renderer, inline=inline, block=block, **kwargs)

class InlineGrammar(mistune.InlineGrammar):
    x = "l2"

class InlineLexer(mistune.InlineLexer):
    default_rules = copy.copy(mistune.InlineLexer.default_rules)
    def __init__(self, renderer, rules=None, **kwargs):
        if rules is None:
            # use the inline grammar
            rules = mistune.InlineGrammar()
        super(InlineLexer, self).__init__(renderer, rules, **kwargs)

class BlockGrammar(mistune.BlockGrammar):
    x = "2"

class BlockLexer(mistune.BlockLexer):
    def __init__(self,  rules=None, **kwargs):
        if rules is None:
            # use the inline grammar
            rules = mistune.BlockGrammar()
        super(BlockLexer, self).__init__(rules, **kwargs)

def markdown(text, escape=True, **kwargs):
    """Render markdown formatted text to html.

    :param text: markdown formatted text content.
    :param escape: if set to False, all html tags will not be escaped.
    :param use_xhtml: output with xhtml tags.
    :param hard_wrap: if set to True, it will use the GFM line breaks feature.
    :param parse_block_html: parse text only in block level html.
    :param parse_inline_html: parse text only in inline level html.
    """
    return Markdown(escape=escape, **kwargs)(text)

<commit_msg>dependancies<commit_after>import mistune
import re
import copy
import urlparse
import posixpath

#TODO disable embedded HTML ?

__version__ = '0.0.0'
__author__ = 'John Pickerill <me@curiouscrab.com>'
__all__ = [
    'BlockGrammar', 'BlockLexer',
    'InlineGrammar', 'InlineLexer',
    'Renderer', 'Markdown',
    'markdown', 'escape',
]

class Markdown(mistune.Markdown):
    def __init__(self, renderer=None, inline=None, block=None, **kwargs):
        super(Markdown, self).__init__(renderer=renderer, inline=inline, block=block, **kwargs)

class Renderer(mistune.Renderer):
    hn = "hd"
    hi = 0

    def __init__(self, hn="hdx" , **kwargs):
        self.hn = hn
        super(Renderer,self).__init__(**kwargs)

class InlineGrammar(mistune.InlineGrammar):
    x = "l2"

class InlineLexer(mistune.InlineLexer):
    default_rules = copy.copy(mistune.InlineLexer.default_rules)
    def __init__(self, renderer, rules=None, **kwargs):
        if rules is None:
            # use the inline grammar
            rules = mistune.InlineGrammar()
        super(InlineLexer, self).__init__(renderer, rules, **kwargs)

class BlockGrammar(mistune.BlockGrammar):
    x = "2"

class BlockLexer(mistune.BlockLexer):
    def __init__(self,  rules=None, **kwargs):
        if rules is None:
            # use the inline grammar
            rules = mistune.BlockGrammar()
        super(BlockLexer, self).__init__(rules, **kwargs)

def markdown(text, escape=True, **kwargs):
    """Render markdown formatted text to html.

    :param text: markdown formatted text content.
    :param escape: if set to False, all html tags will not be escaped.
    :param use_xhtml: output with xhtml tags.
    :param hard_wrap: if set to True, it will use the GFM line breaks feature.
    :param parse_block_html: parse text only in block level html.
    :param parse_inline_html: parse text only in inline level html.
    """
    return Markdown(escape=escape, **kwargs)(text)

<|endoftext|>


<commit_before>"""Git utility functions."""

import os

def update_repository_name(repository):
    """Update given repository name so it won't contain any prefix(es)."""
    lastSlash = repository.rfind("/")

    # make sure we use just the repo name
    if lastSlash >= 0 and lastSlash < len(repository) - 1:
        return repository[1 + lastSlash:]
    else:
        return repository

def is_repository_cloned(repository):
    """Check if the directory with cloned repository exist."""
    return os.path.isdir("repositories/" + update_repository_name(repository))

def clone_repository(repository, full_history):
    """Clone the selected repository."""
    print("Cloning the repository {repository}".format(repository=repository))
    prefix = "https://github.com"
    if full_history:
        cmd = "pushd repositories; git clone {prefix}/{repo}.git; popd".\
              format(prefix=prefix, repo=repository)
    else:
        cmd = "pushd repositories; git clone --single-branch --depth 1 {prefix}/{repo}.git; popd".\
              format(prefix=prefix, repo=repository)
    os.system(cmd)

def fetch_repository(repository):
    """Fetch the selected repository."""
    repository = update_repository_name(repository)
    print("Fetching changes from the repository {repository}".format(repository=repository))
    command = "pushd repositories/{repository}; git fetch; popd".format(repository=repository)
    os.system(command)

def clone_or_fetch_repository(repository, full_history=False):
    """Clone or fetch the selected repository."""
    if is_repository_cloned(repository):
        fetch_repository(repository)
    else:
        clone_repository(repository, full_history)
<commit_msg>Two new GIT-related function: short log and checkout<commit_after>"""Git utility functions."""

import os

def update_repository_name(repository):
    """Update given repository name so it won't contain any prefix(es)."""
    lastSlash = repository.rfind("/")

    # make sure we use just the repo name
    if lastSlash >= 0 and lastSlash < len(repository) - 1:
        return repository[1 + lastSlash:]
    else:
        return repository

def is_repository_cloned(repository):
    """Check if the directory with cloned repository exist."""
    return os.path.isdir("repositories/" + update_repository_name(repository))

def clone_repository(repository, full_history):
    """Clone the selected repository."""
    print("Cloning the repository {repository}".format(repository=repository))
    prefix = "https://github.com"
    if full_history:
        cmd = "pushd repositories; git clone {prefix}/{repo}.git; popd".\
              format(prefix=prefix, repo=repository)
    else:
        cmd = "pushd repositories; git clone --single-branch --depth 1 {prefix}/{repo}.git; popd".\
              format(prefix=prefix, repo=repository)
    os.system(cmd)

def fetch_repository(repository):
    """Fetch the selected repository."""
    repository = update_repository_name(repository)
    print("Fetching changes from the repository {repository}".format(repository=repository))
    command = "pushd repositories/{repository}; git fetch; popd".format(repository=repository)
    os.system(command)

def clone_or_fetch_repository(repository, full_history=False):
    """Clone or fetch the selected repository."""
    if is_repository_cloned(repository):
        fetch_repository(repository)
    else:
        clone_repository(repository, full_history)

def get_log(repository):
    """Retrieve the log for the given repository."""
    repository = update_repository_name(repository)
    command = ("pushd repositories/{repo} >> /dev/null; " +
               "git log --pretty=oneline > ../logs.txt; " +
               "popd >> /dev/null").format(repo=repository)
    os.system(command)

def checkout(repository, commit):
    """Perform the GIT checkout in the selected repository."""
    repository = update_repository_name(repository)
    command = ("pushd repositories/{repo} >> /dev/null; " +
               "git checkout {commit}; " +
               "popd >> /dev/null").format(repo=repository, commit=commit)
    os.system(command)
<|endoftext|>


<commit_before>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians

mapw= 100
maph=100
scrw=640
scrh=480
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(width)
print(height)
click = 0

go=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in width:
    for y in height:
        Sprite(nosquare_asset,(x*10, y*10))

for x in mwidth:
    for y in mheight:
        Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":"50","y":"50","dir":"0"}
change=1

def right(event):
    global change
    change=1
    if Position['dir']<360:
        Position['dir']=Position[x]+1
    else:
        Position['dir']=0

def left(event):
    global change
    change=1
    if Position['dir']>0:
        Position['dir']=Position[x]-1
    else:
        Position['dir']=359

def up(event):
    global change
    change=1
    Position['x']=Position['x']+sin(int(Position['x']))
    Position['y']=Position['y']+cos(int(Position['x']))

def down(event):
    global change
    change=1
    Position['x']=Position['x']-sin(int(Position['x']))
    Position['y']=Position['y']-cos(int(Position['x']))

def space(event):
    if go!=1:
        go=1
    else:
        go=0

def ray():
    global go
    global position
    global change
    if change==1 and go==1:
        raydir=Position['dir']
        wall=0
        screenside=0
        distance=0
        intilex=Position['x']-int(Position['x'])//1
        intiley=Position['y']-int(Position['y'])//1
        rayx=(Position['x']*10)//10
        rayy=(Position['y']*10)//10
        while wall==0:
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                Sprite(RectangleAsset((screenside,0),1000/distance,100/distance, thinline, 'b'+str(distance)))
                raydir=raydir+10/distance
                screenside=screenside+10/distance
                if screenside==100:
                    wall=1
            else:
                distance=distance+1
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'right', right)
myapp.listenKeyEvent('keydown', 'left', left)
myapp.listenKeyEvent('keydown', 'up', up)
myapp.listenKeyEvent('keydown', 'down', down)
myapp.listenKeyEvent('space', 'space', space)

myapp = App()
myapp.run(ray)<commit_msg>Updated from Brython Server: 11/15/2016 3:54:41 PM<commit_after>from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos,tan, radians

mapw= 100
maph=100
scrw=640
scrh=480
SCREEN_WIDTH = scrw
SCREEN_HEIGHT = scrh

black = Color(0x000000, 1.0)
red = Color(0xff0000, 1.0)
white = Color(0xffffff, 1.0)
b1 = Color(0x0000ff, 1.0)
b2 = Color(0x0000e5, 1.0)
b3 = Color(0x0000cc, 1.0)
b4 = Color(0x0000b2, 1.0)
b5 = Color(0x000099, 1.0)
b6 = Color(0x00007f, 1.0)
b7 = Color(0x000066, 1.0)
b8 = Color(0x00004c, 1.0)
b9 = Color(0x000033, 1.0)
b10 = Color(0x000019, 1.0)
b11 = Color(0x000000, 1.0)

width=list(range(0,int((scrw/10))+1))
height = list(range(0,int((scrh/10))+1))

mwidth=list(range(0,int((mapw/10))+1))
mheight = list(range(0,int((maph/10))+1))
print(width)
print(height)
click = 0

go=0

walls={"0101":"0"}
for x in mwidth:
    for y in mheight:
        walls['0'+str(x)+'0'+str(y)]=0

thinline = LineStyle(1, black)
noline= LineStyle(0,black)
rsquare_asset =RectangleAsset(10,10, thinline, red)
wsquare_asset = RectangleAsset(10, 10, thinline, white)
nosquare_asset = RectangleAsset(10, 10, noline, white)

for x in width:
    for y in height:
        Sprite(nosquare_asset,(x*10, y*10))

for x in mwidth:
    for y in mheight:
        Sprite(wsquare_asset,(x*10, y*10))

def mouseclick(event):
    global click
    click = 1
    pixelpositionx = ((event.x)//10)*10
    pixelpositiony = ((event.y)//10)*10
    if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
        Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
    else:
        Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
        walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

def mouseup(event):
    global click
    click = 0

def drag(event):
    global click
    if click==1:
        pixelpositionx = ((event.x)//10)*10
        pixelpositiony = ((event.y)//10)*10
        if walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]==0:
            Sprite(rsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=1
        else:
            Sprite(wsquare_asset, (pixelpositionx, pixelpositiony))
            walls['0'+str(round(pixelpositionx/10))+'0'+str(round(pixelpositiony/10))]=0

Position={"x":"50","y":"50","dir":"0"}
change=1

def right(event):
    global change
    change=1
    if Position['dir']<360:
        Position['dir']=Position[x]+1
    else:
        Position['dir']=0

def left(event):
    global change
    change=1
    if Position['dir']>0:
        Position['dir']=Position[x]-1
    else:
        Position['dir']=359

def up(event):
    global change
    change=1
    Position['x']=Position['x']+sin(int(Position['x']))
    Position['y']=Position['y']+cos(int(Position['x']))

def down(event):
    global change
    change=1
    Position['x']=Position['x']-sin(int(Position['x']))
    Position['y']=Position['y']-cos(int(Position['x']))

def space(event):
    if go!=1:
        go=1
    else:
        go=0

def ray():
    global go
    print(go)
    global position
    global change
    if change==1 and go==1:
        print(go)
        raydir=Position['dir']
        wall=0
        screenside=0
        distance=0
        intilex=Position['x']-int(Position['x'])//1
        intiley=Position['y']-int(Position['y'])//1
        rayx=(Position['x']*10)//10
        rayy=(Position['y']*10)//10
        while wall==0:
            if walls['0'+str(round(rayx))+'0'+str(round(rayy))]==1:
                Sprite(RectangleAsset((screenside,0),1000/distance,100/distance, thinline, 'b'+str(distance)))
                raydir=raydir+10/distance
                screenside=screenside+10/distance
                wall=1
                if screenside==100:
                    change=0
            else:
                distance=distance+1
                rayx=rayx+cos(radians(raydir))
                rayy=rayy+sin(radians(raydir))

myapp = App(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.listenMouseEvent('mouseup', mouseup)
myapp.listenMouseEvent('mousedown', mouseclick)
myapp.listenMouseEvent('mousemove', drag)
myapp.listenKeyEvent('keydown', 'right', right)
myapp.listenKeyEvent('keydown', 'left', left)
myapp.listenKeyEvent('keydown', 'up', up)
myapp.listenKeyEvent('keydown', 'down', down)
myapp.listenKeyEvent('space', 'space', space)

myapp = App()
myapp.run(ray)<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

import os
import json
import ast
import numpy as np

from zarr import defaults as _defaults

def read_array_metadata(path):

    # check path exists
    if not os.path.exists(path):
        raise ValueError('path not found: %s' % path)

    # check metadata file
    meta_path = os.path.join(path, _defaults.metapath)
    if not os.path.exists(meta_path):
        raise ValueError('array metadata not found: %s' % path)

    # read from file
    with open(meta_path) as f:
        meta = json.load(f)

    # decode some values
    meta['shape'] = tuple(meta['shape'])
    meta['chunks'] = tuple(meta['chunks'])
    meta['cname'] = meta['cname'].encode('ascii')
    meta['dtype'] = decode_dtype(meta['dtype'])

    return meta

def write_array_metadata(path, shape, chunks, dtype, cname, clevel, shuffle,
                         fill_value):

    # construct metadata dictionary
    meta = dict(
        shape=shape,
        chunks=chunks,
        dtype=encode_dtype(dtype),
        cname=str(cname, 'ascii'),
        clevel=clevel,
        shuffle=shuffle,
        fill_value=fill_value,
    )

    # write to file
    meta_path = os.path.join(path, _defaults.metapath)
    with open(meta_path, 'w') as f:
        json.dump(meta, f, indent=4, sort_keys=True)

def encode_dtype(d):
    if d.fields is None:
        return d.str
    else:
        return d.descr

def _decode_dtype_descr(d):
    # need to convert list items to tuples
    if isinstance(d, list):
        d = [(f, _decode_dtype_descr(v)) for f, v in d]
    return d

def decode_dtype(d):
    return np.dtype(_decode_dtype_descr(d))
<commit_msg>comments<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

import os
import json
import ast
import numpy as np

from zarr import defaults as _defaults

def read_array_metadata(path):

    # check path exists
    if not os.path.exists(path):
        raise ValueError('path not found: %s' % path)

    # check metadata file
    meta_path = os.path.join(path, _defaults.metapath)
    if not os.path.exists(meta_path):
        raise ValueError('array metadata not found: %s' % path)

    # read from file
    with open(meta_path) as f:
        meta = json.load(f)

    # decode some values
    meta['shape'] = tuple(meta['shape'])
    meta['chunks'] = tuple(meta['chunks'])
    meta['cname'] = meta['cname'].encode('ascii')
    meta['dtype'] = decode_dtype(meta['dtype'])

    return meta

def write_array_metadata(path, shape, chunks, dtype, cname, clevel, shuffle,
                         fill_value):

    # construct metadata dictionary
    meta = dict(
        shape=shape,
        chunks=chunks,
        dtype=encode_dtype(dtype),
        cname=str(cname, 'ascii'),
        clevel=clevel,
        shuffle=shuffle,
        fill_value=fill_value,
    )

    # write to file
    meta_path = os.path.join(path, _defaults.metapath)
    with open(meta_path, 'w') as f:
        json.dump(meta, f, indent=4, sort_keys=True)

def encode_dtype(d):
    if d.fields is None:
        return d.str
    else:
        return d.descr

def _decode_dtype_descr(d):
    # need to convert list items to tuples
    if isinstance(d, list):
        # recurse to handle nested structures
        d = [(f, _decode_dtype_descr(v)) for f, v in d]
    return d

def decode_dtype(d):
    return np.dtype(_decode_dtype_descr(d))
<|endoftext|>


<commit_before>import numpy as np
import pytest
from ogusa import demographics

def test_get_pop_objs():
    """
    Test of the that omega_SS and the last period of omega_path_S are
    close to each other.
    """
    E = 20
    S = 80
    T = int(round(4.0 * S))
    start_year = 2018

    (omega, g_n_ss, omega_SS, surv_rate, rho, g_n_vector, imm_rates,
        omega_S_preTP) = demographics.get_pop_objs(E, S, T, 1, 100,
                                                   start_year, False)

    assert (np.allclose(omega_SS, omega[-1, :]))

def test_pop_smooth():
    """
    Test that population growth rates evolve smoothly.
    """
    E = 20
    S = 80
    T = int(round(4.0 * S))
    start_year = 2018

    (omega, g_n_ss, omega_SS, surv_rate, rho, g_n_vector, imm_rates,
        omega_S_preTP) = demographics.get_pop_objs(E, S, T, 1, 100,
                                                   start_year, False)

    assert (np.any(np.absolute(omega[:-1, :] - omega[1:, :]) < 0.0001))
    assert (np.any(np.absolute(g_n_vector[:-1] - g_n_vector[1:]) < 0.0001))
<commit_msg>test imm rates<commit_after>import numpy as np
import pytest
from ogusa import demographics

def test_get_pop_objs():
    """
    Test of the that omega_SS and the last period of omega_path_S are
    close to each other.
    """
    E = 20
    S = 80
    T = int(round(4.0 * S))
    start_year = 2018

    (omega, g_n_ss, omega_SS, surv_rate, rho, g_n_vector, imm_rates,
        omega_S_preTP) = demographics.get_pop_objs(E, S, T, 1, 100,
                                                   start_year, False)

    assert (np.allclose(omega_SS, omega[-1, :]))

def test_pop_smooth():
    """
    Test that population growth rates evolve smoothly.
    """
    E = 20
    S = 80
    T = int(round(4.0 * S))
    start_year = 2018

    (omega, g_n_ss, omega_SS, surv_rate, rho, g_n_vector, imm_rates,
        omega_S_preTP) = demographics.get_pop_objs(E, S, T, 1, 100,
                                                   start_year, False)

    assert (np.any(np.absolute(omega[:-1, :] - omega[1:, :]) < 0.0001))
    assert (np.any(np.absolute(g_n_vector[:-1] - g_n_vector[1:]) < 0.0001))

def test_imm_smooth():
    """
    Test that population growth rates evolve smoothly.
    """
    E = 20
    S = 80
    T = int(round(4.0 * S))
    start_year = 2018

    (omega, g_n_ss, omega_SS, surv_rate, rho, g_n_vector, imm_rates,
        omega_S_preTP) = demographics.get_pop_objs(E, S, T, 1, 100,
                                                   start_year, False)

    assert (np.any(np.absolute(imm_rates[:-1, :] - imm_rates[1:, :]) <
                   0.0001))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
<commit_msg>remove unnecessary __init__.py<commit_after><|endoftext|>


<commit_before>import pyparsing, re, doctest

sqlStyleComment = pyparsing.Literal("--") + pyparsing.ZeroOrMore(pyparsing.CharsNotIn("\n"))
keywords = {'order by': pyparsing.Keyword('order', caseless=True) +
                        pyparsing.Keyword('by', caseless=True),
            'select': pyparsing.Keyword('select', caseless=True),
            'from': pyparsing.Keyword('from', caseless=True),
            'having': pyparsing.Keyword('having', caseless=True),
            'update': pyparsing.Keyword('update', caseless=True),
            'set': pyparsing.Keyword('set', caseless=True),
            'delete': pyparsing.Keyword('delete', caseless=True),
            'insert into': pyparsing.Keyword('insert', caseless=True) +
                           pyparsing.Keyword('into', caseless=True),
            'values': pyparsing.Keyword('values', caseless=True),
            'group by': pyparsing.Keyword('group', caseless=True) +
                        pyparsing.Keyword('by', caseless=True),
            'where': pyparsing.Keyword('where', caseless=True)}
for (name, parser) in keywords.items():
    parser.ignore(pyparsing.sglQuotedString)
    parser.ignore(pyparsing.dblQuotedString)
    parser.ignore(pyparsing.cStyleComment)
    parser.ignore(sqlStyleComment)
    parser.name = name

fromClauseFinder = re.compile(r".*(from|update)(.*)(where|set)",
                    re.IGNORECASE | re.DOTALL | re.MULTILINE)
def tableNamesFromFromClause(statement):
    result = fromClauseFinder.search(statement)
    if not result:
        return []
    result = [r.upper() for r in result if r.upper() not in ('JOIN','ON')]
    return result

def orderedParseResults(parsers, statement):
    results = []
    for parser in parsers:
        results.extend(parser.scanString(statement))
    results.sort(cmp=lambda x,y:cmp(x[1],y[1]))
    return results

at_beginning = re.compile(r'^\s*\S+$')
def whichSegment(statement):
    '''
    >>> whichSegment("SELECT col FROM t")
    'from'
    >>> whichSegment("SELECT * FROM t")
    'from'
    >>> whichSegment("DESC ")
    'DESC'
    >>> whichSegment("DES")
    'beginning'
    >>> whichSegment("")
    'beginning'
    >>> whichSegment("select  ")
    'select'

    '''
    if (not statement) or at_beginning.search(statement):
        return 'beginning'
    results = orderedParseResults(keywords.values(), statement)
    if results:
        return ' '.join(results[-1][0])
    else:
        return statement.split(None,1)[0]

reserved = '''
      access
     add
     all
     alter
     and
     any
     as
     asc
     audit
     between
     by
     char
     check
     cluster
     column
     comment
     compress
     connect
     create
     current
     date
     decimal
     default
     delete
     desc
     distinct
     drop
     else
     exclusive
     exists
     file
     float
     for
     from
     grant
     group
     having
     identified
     immediate
     in
     increment
     index
     initial
     insert
     integer
     intersect
     into
     is
     level
     like
     lock
     long
     maxextents
     minus
     mlslabel
     mode
     modify
     noaudit
     nocompress
     not
     nowait
     null
     number
     of
     offline
     on
     online
     option
     or
     order
     pctfree
     prior
     privileges
     public
     raw
     rename
     resource
     revoke
     row
     rowid
     rownum
     rows
     select
     session
     set
     share
     size
     smallint
     start
     successful
     synonym
     sysdate
     table
     then
     to
     trigger
     uid
     union
     unique
     update
     user
     validate
     values
     varchar
     varchar2
     view
     whenever
     where
     with '''.split()

if __name__ == '__main__':
    doctest.testmod()
<commit_msg>Remove sqlparser.<commit_after><|endoftext|>


<commit_before>import unittest, glob, os, cgi
import pyless
from pyless.antlr3 import tree
from pyless.lesscssParser import tokenNames

##

def _fbtgen(fname):
	def test(self):
		self._do_file_test(fname)
	return test

class FileBasedParserTest(unittest.TestCase):

	counter = None # Override this !
	name = None  # Override this !

	def _do_file_test(self, fname):
		lexer, parser, result = pyless.parse(fname)
		if lexer.getNumberOfSyntaxErrors() > 0:
			self.fail("Lexer errors:\n" + '\n'.join(lexer.errormsgcache))
		if parser.getNumberOfSyntaxErrors() > 0:
			self.fail("Parser errors:\n" + '\n'.join(parser.errormsgcache))

		r = result.tree.toStringTree()
		self.assertIsNotNone(r, "Parsing silently failed!")

		###

		fout = open(fname+'.dot', "w")
		fout.write('digraph {0} {{\nratio = fill;packMode=graph;\n'.format(os.path.basename(fname)[:-4].replace('-','_')))
		fout.write('node [style="filled",fontname=Arial];\n')
		def twalker(t):
			tname = tokenNames[t.getType()]
			if tname == str(t):
				fout.write('"{0}" [shape=ellipse,label="{1}",fillcolor=paleturquoise];\n'.format(
					id(t),
					cgi.escape("{0}".format(t), True),
					)
				)
			else:
				fout.write('"{0}" [shape=record,label="{{{2}|{1}}}",fillcolor=palegreen];\n'.format(
					id(t),
					cgi.escape("{0}".format(t).replace('"','\\"'), True),
					cgi.escape(tname, True)
					)
				)

			if t.parent is not None:
				fout.write('"{0}" -> "{1}";\n'.format(id(t.parent), id(t)))

			for ch in t.children:
				twalker(ch)

		twalker(result.tree)

		fout.write("}\n")

	@classmethod
	def AddTestDirGlob(cls, dglob):

		for f in glob.glob(dglob):
			cls.counter += 1
			test_name = 'test_{name}_{counter:02d}_{fnamebase}'.format(name=cls.name,counter=cls.counter, fnamebase=os.path.basename(f)[:-4].replace('-','_'))
			test = _fbtgen(f)
			test.func_doc = os.path.basename(f)
			setattr(cls, test_name, test)
<commit_msg>Replace newlines and { } in labels<commit_after>import unittest, glob, os, cgi
import pyless
from pyless.antlr3 import tree
from pyless.lesscssParser import tokenNames

##

def _fbtgen(fname):
	def test(self):
		self._do_file_test(fname)
	return test

class FileBasedParserTest(unittest.TestCase):

	counter = None # Override this !
	name = None  # Override this !

	def _do_file_test(self, fname):
		lexer, parser, result = pyless.parse(fname)
		if lexer.getNumberOfSyntaxErrors() > 0:
			self.fail("Lexer errors:\n" + '\n'.join(lexer.errormsgcache))
		if parser.getNumberOfSyntaxErrors() > 0:
			self.fail("Parser errors:\n" + '\n'.join(parser.errormsgcache))

		r = result.tree.toStringTree()
		self.assertIsNotNone(r, "Parsing silently failed!")

		###

		fout = open(fname+'.dot', "w")
		fout.write('digraph {0} {{\nratio = fill;packMode=graph;\n'.format(os.path.basename(fname)[:-4].replace('-','_')))
		fout.write('node [style="filled",fontname=Arial];\n')
		def twalker(t):
			tname = tokenNames[t.getType()]
			if tname == str(t):
				fout.write('"{0}" [shape=ellipse,label="{1}",fillcolor=paleturquoise];\n'.format(
					id(t),
					cgi.escape("{0}".format(t), True).replace("\n", "\\n").replace("{", "\{").replace("}", "\}"),
					)
				)
			else:
				fout.write('"{0}" [shape=record,label="{{{2}|{1}}}",fillcolor=palegreen];\n'.format(
					id(t),
					cgi.escape("{0}".format(t), True).replace("\n", "\\n").replace("\n", "\\n").replace("{", "\{").replace("}", "\}"),
					cgi.escape(tname, True).replace("\n", "\\n").replace("\n", "\\n").replace("{", "\{").replace("}", "\}")
					)
				)

			if t.parent is not None:
				fout.write('"{0}" -> "{1}";\n'.format(id(t.parent), id(t)))

			for ch in t.children:
				twalker(ch)

		twalker(result.tree)

		fout.write("}\n")

	@classmethod
	def AddTestDirGlob(cls, dglob):

		for f in glob.glob(dglob):
			cls.counter += 1
			test_name = 'test_{name}_{counter:02d}_{fnamebase}'.format(name=cls.name,counter=cls.counter, fnamebase=os.path.basename(f)[:-4].replace('-','_'))
			test = _fbtgen(f)
			test.func_doc = os.path.basename(f)
			setattr(cls, test_name, test)
<|endoftext|>