<commit_before>"""
spaceshooter.py
Author: Liam S
Credit: Mr. Dennison's Spacewar source code Vinzent for Photoshop Help

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Stars(Sprite):

    asset = ImageAsset("images/starfield.jpg")
    width = 512
    height = 512

    def __init__(self, position):
        super().__init__(Stars.asset, position)

class Moon(Sprite):

    asset = ImageAsset("images/Le_Voyage_dans_la_lune_Transparent.png")
    def __init__(self, position):
        super().__init__(Moon.asset, position)
        self.counter = 0
        self.vx = 0
        self.vy = 0
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        if self.counter >= 0 and self.counter <= 1200:
            self.vx = 1
            self.vy = 0
        if self.counter >= 1200 and self.counter <= 1800:
            self.vx = 0
            self.vy = 1
        if self.counter >= 1800 and self.counter <= 3000:
            self.vx = -1
            self.vy = 0
        if self.counter >= 3000 and self.counter <= 3600:
            self.vx = 0
            self.vy = -1
        if self.counter == 3601:
            self.counter = 0
        self.counter += 1

        self.x += self.vx
        self.y += self.vy
class SpaceShip(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,230,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vAddedx = 0
        self.vAddedy = 0
        self.vAddedr = 0
        self.sideThrust = 0
        self.vertThrust = 0
        self.RotThrust = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.thrustLeft)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.thrustRightoff)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.thrustLeftoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.thrustRight)

        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustUp)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.thrustDownoff)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustUpoff)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.thrustDown)

        SpaceGame.listenKeyEvent("keydown", "i", self.thrustCounterClock)
        SpaceGame.listenKeyEvent("keyup", "p", self.thrustClockoff)
        SpaceGame.listenKeyEvent("keyup", "i", self.thrustCounterClockoff)
        SpaceGame.listenKeyEvent("keydown", "p", self.thrustClock)

        self.fxcenter = self.fycenter = 0.5
    def step(self):
        if self.sideThrust == 1:
            self.vAddedx += 0.05
        if self.sideThrust == -1:
            self.vAddedx -= 0.05
        if self.sideThrust == 0:
            self.vAddedx += 0
        if self.vertThrust == 1:
            self.vAddedy += 0.05
        if self.vertThrust == -1:
            self.vAddedy -= 0.05
        if self.vertThrust == 0:
            self.vAddedy += 0
        if self.RotThrust == 1:
            self.vAddedr = -0.03
        if self.RotThrust == -1:
            self.vAddedr = 0.03
        if self.RotThrust == 0:
            self.vAddedr = 0
        self.x += self.vAddedx
        self.y += self.vAddedy
        self.rotation += self.vAddedr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOff(self, event):
        self.thrust = 0

    def thrustLeft(self, event):
        self.sideThrust = -1
        self.thrust = 1

    def thrustRight(self, event):
        self.sideThrust = 1
        self.thrust = 1

    def thrustRightoff(self, event):
        self.sideThrust = 0
        self.thrust = 0

    def thrustLeftoff(self, event):
        self.sideThrust = 0
        self.thrust = 0

    def thrustUp(self, event):
        self.vertThrust = -1
        self.thrust = 1

    def thrustDown(self, event):
        self.vertThrust = 1
        self.thrust = 1

    def thrustDownoff(self, event):
        self.vertThrust = 0
        self.thrust = 0

    def thrustUpoff(self, event):
        self.vertThrust = 0
        self.thrust = 0

    def thrustCounterClock(self, event):
        self.RotThrust = -1
        self.thrust = 1

    def thrustClock(self, event):
        self.RotThrust = 1
        self.thrust = 1

    def thrustClockoff(self, event):
        self.RotThrust = 0
        self.thrust = 0

    def thrustCounterClockoff(self, event):
        self.RotThrust = 0
        self.thrust = 0

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Stars.width + 1):
            for y in range(self.height//Stars.height + 1):
                Stars((x*Stars.width, y*Stars.height))
        Moon((200,200))
        SpaceShip((400,400))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        for ship in self.getSpritesbyClass(Moon):
            ship.step()

app = SpaceGame(1900,935)
app.run()

<commit_msg>Updated from Brython Server: 11/9/2016 1:11:24 PM<commit_after>"""
spaceshooter.py
Author: Liam S
Credit: Mr. Dennison's Spacewar source code Vinzent for Photoshop Help

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import SoundAsset, Sound, TextAsset, Color
import math
from time import time

class Stars(Sprite):

    asset = ImageAsset("images/starfield.jpg")
    width = 512
    height = 512

    def __init__(self, position):
        super().__init__(Stars.asset, position)

class Moon(Sprite):

    asset = ImageAsset("images/Le_Voyage_dans_la_lune_Transparent.png")
    def __init__(self, position):
        super().__init__(Moon.asset, position)
        self.counter = 0
        self.vx = 0
        self.vy = 0
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        if self.counter >= 0 and self.counter <= 1200:
            self.vx = 1
            self.vy = 0
        if self.counter >= 1200 and self.counter <= 1800:
            self.vx = 0
            self.vy = 1
        if self.counter >= 1800 and self.counter <= 3000:
            self.vx = -1
            self.vy = 0
        if self.counter >= 3000 and self.counter <= 3600:
            self.vx = 0
            self.vy = -1
        if self.counter == 3601:
            self.counter = 0
        self.counter += 1

        self.x += self.vx
        self.y += self.vy
class SpaceShip(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,230,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vAddedx = 0
        self.vAddedy = 0
        self.vAddedr = 0
        self.sideThrust = 0
        self.vertThrust = 0
        self.RotThrust = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.thrustLeft)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.thrustRightoff)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.thrustLeftoff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.thrustRight)

        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustUp)
        SpaceGame.listenKeyEvent("keyup", "down arrow", self.thrustDownoff)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustUpoff)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.thrustDown)

        SpaceGame.listenKeyEvent("keydown", "i", self.thrustCounterClock)
        SpaceGame.listenKeyEvent("keyup", "p", self.thrustClockoff)
        SpaceGame.listenKeyEvent("keyup", "i", self.thrustCounterClockoff)
        SpaceGame.listenKeyEvent("keydown", "p", self.thrustClock)

        self.fxcenter = self.fycenter = 0.5
    def step(self):
        if self.sideThrust == 1:
            self.vAddedx += 0.05
        if self.sideThrust == -1:
            self.vAddedx -= 0.05
        if self.sideThrust == 0:
            self.vAddedx += 0
        if self.vertThrust == 1:
            self.vAddedy += 0.05
        if self.vertThrust == -1:
            self.vAddedy -= 0.05
        if self.vertThrust == 0:
            self.vAddedy += 0
        if self.RotThrust == 1:
            self.vAddedr = -0.03
        if self.RotThrust == -1:
            self.vAddedr = 0.03
        if self.RotThrust == 0:
            self.vAddedr = 0
        self.x += self.vAddedx
        self.y += self.vAddedy
        self.rotation += self.vAddedr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOff(self, event):
        self.thrust = 0

    def thrustLeft(self, event):
        self.sideThrust = -1
        self.thrust = 1

    def thrustRight(self, event):
        self.sideThrust = 1
        self.thrust = 1

    def thrustRightoff(self, event):
        self.sideThrust = 0
        self.thrust = 0

    def thrustLeftoff(self, event):
        self.sideThrust = 0
        self.thrust = 0

    def thrustUp(self, event):
        self.vertThrust = -1
        self.thrust = 1

    def thrustDown(self, event):
        self.vertThrust = 1
        self.thrust = 1

    def thrustDownoff(self, event):
        self.vertThrust = 0
        self.thrust = 0

    def thrustUpoff(self, event):
        self.vertThrust = 0
        self.thrust = 0

    def thrustCounterClock(self, event):
        self.RotThrust = -1
        self.thrust = 1

    def thrustClock(self, event):
        self.RotThrust = 1
        self.thrust = 1

    def thrustClockoff(self, event):
        self.RotThrust = 0
        self.thrust = 0

    def thrustCounterClockoff(self, event):
        self.RotThrust = 0
        self.thrust = 0
class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image = self.image + 1
        if self.image == 50:
            self.destroy()

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        for x in range(self.width//Stars.width + 1):
            for y in range(self.height//Stars.height + 1):
                Stars((x*Stars.width, y*Stars.height))
        Moon((200,200))
        SpaceShip((400,400))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        for ship in self.getSpritesbyClass(Moon):
            ship.step()

app = SpaceGame(1900,935)
app.run()

<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

class SpaceShip(Sprite):

#    Animated space ship

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
    Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = .0
        self.thrust = 0
        self.thrustframe = 1

        SpaceGame.listenKeyEvent("keydown", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<525 and x>475):
            if (y<375 and y>325):
                print("sdfdgbtb")
                SpaceGame.explode(x, y)
                print("dsfgsdfg")

class SpaceGame(App):

    #Tutorial4 space game example.

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(self, xx, yy):
        print("h")
        return()
        print("abdjhcjhbvehjqbfjgv")
        expl =  ImageAsset("images/explosion.png")
        ex = Sprite(expl, (xx, yy))
        print("jfgvsrtgwerge")

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<commit_msg>Updated from Brython Server: 3/29/2016 9:07:35 PM<commit_after>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

class SpaceShip(Sprite):

#    Animated space ship

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
    Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = .0
        self.thrust = 0
        self.thrustframe = 1

        SpaceGame.listenKeyEvent("keydown", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<525 and x>475):
            if (y<375 and y>325):
                print("1")
                SpaceGame.explode(x, y)
                print("2")

class SpaceGame(App):

    #Tutorial4 space game example.

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(self, xx, yy):
        print("3")
        return()
        print("4")
        expl =  ImageAsset("images/explosion.png")
        ex = Sprite(expl, (xx, yy))
        print("5")

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code,

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.x =self.x+1
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode()

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def explode(self):
        self.visible=False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((400,360))
        SpaceShip((100,100))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<commit_msg>Updated from Brython Server: 3/10/2016 2:30:38 PM<commit_after>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code,

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.x =self.x+1
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode()

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def explode(self):
        self.visible=False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((400,360))
        SpaceShip((100,100))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<|endoftext|>


<commit_before>import os
import sys
import atexit
import json
from .connection import Connection, Pager
from .exceptions import ResponseError
from functools import wraps

## System Startup tasks

if "--no-cache" not in sys.argv:
  # Always run on start import
  cache_file = "cache_file.json"
  cache = {}

  if os.path.isfile(cache_file):
    with open(cache_file, "r") as f:
      try:
        cache = json.load(f)
      except ValueError:
        pass

  # Always run on exit
  def save_cache():
    with open(cache_file, 'w') as f:
      json.dump(cache, f)

  atexit.register(save_cache)

  def memoise(wrapped):

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
      key = args[0]
      if key not in cache:
        cache[key] = wrapped(*args, **kwargs)
      return cache[key]

    return wrapper

else:
  # Disable memoisation, force all calls to happen regardless
  def memoise(wrapped):

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)

    return wrapper

token = os.environ.get("GITHUB_TOKEN")
debug = os.environ.get("DEBUG")

if token is None:
  print("Warning: No GITHUB_TOKEN found - Unauthenticated "
        "requests are rate limited to 60 requests per hour.")
else:
  if debug:
    print("GITHUB_TOKEN found of length %d" % len(token))

conn = Connection(token)

# Walk a json endpoint where pagination is link driven
@memoise
def get_paged_json(uri):
  json = []
  try:
    pager = Pager(conn, uri, params={}, max_pages=0)
    for response in pager:
      progress_advance()
      json += response.json()
  except ResponseError:
    pass

  return json

# Walk a json endpoint where pagination is integer driven
@memoise
def get_page_int_json(uri):
   json = []
   page = 1
   while True:
      progress_advance()
      response = get_data("%s?page=%d" % (uri, page))
      if len(response) == 0:
         break
      else:
         page = page + 1
         json += response
   return json

# Get the users defined by GitHub as contributors
def get_api_contributors(repo_name):
  progress("Collecting API contributors")
  users = []
  response = get_page_int_json("/repos/%s/contributors" % repo_name)
  for entry in response:
    user = get_user_data(entry)
    if user is not None:
      users.append(user)
  progress_complete()

  return users

# Get all Pull Requests and Issues (PRI) users
def get_pri_contributors(repo_name, limit):
  progress("Collecting all repo contributors")

  pri_count = get_pri_count(repo_name)
  if limit == 0:
    minimum = 1
  else:
    minimum = max(1, pri_count - limit)

  users = []
  for index in range(minimum, pri_count + 1):
    user = get_user("/repos/%s/pulls/%d" % (repo_name, index))
    if user is not None:
      users.append(user)

    user = get_user("/repos/%s/issues/%d" % (repo_name, index))
    if user is not None:
      users.append(user)

    for entry in get_paged_json("/repos/%s/pulls/%d/comments" %
                                (repo_name, index)):
        user = get_user_data(entry)
        if user is not None:
          users.append(user)

    for entry in get_paged_json("/repos/%s/issues/%d/comments" %
                                (repo_name, index)):
        user = get_user_data(entry)
        if user is not None:
          users.append(user)

  progress_complete()

  return users

def unique_users(a, b, c, d):
  f = a + b + c + d
  array = [x for x in f if x is not None]
  return list({v['user_name']: v for v in array}.values())

@memoise
def get_data(uri):
  try:
    resp = conn.send("GET", uri)
    return resp.json()
  except ResponseError as e:
    return None

# Get the number of Pull Requests and Issues
def get_pri_count(repo_name):
  prs = get_data("/repos/%s/pulls?state=all" % repo_name)
  issues = get_data("/repos/%s/issues?state=all" % repo_name)

  if not prs:
    pr_count = 0
  else:
    pr_count = prs[0]["number"]

  if not issues:
    issue_count = 0
  else:
    issue_count = issues[0]["number"]

  return max(pr_count, issue_count)

def get_user_data(entry):
  if "user" in entry.keys():
    if entry['user'] is None:
      return None
    return {"user_name": entry["user"]["login"],
            "avatar": "%s&s=128" % entry["user"]["avatar_url"],
            "name": get_user_name(entry["user"]["login"])}
  else:
    return {"user_name": entry["login"],
            "avatar": "%s&s=128" % entry["avatar_url"],
            "name": get_user_name(entry["login"])}

@memoise
def get_user(uri):
  progress_advance()
  entry = get_data(uri)
  if entry is not None:
    return get_user_data(entry)

@memoise
def repo_exists(repo_name):
  try:
    conn.send("GET", "/repos/%s" % repo_name)
    return True
  except ResponseError:
    return False

def progress(message):
  sys.stdout.write("%s..." % message)
  sys.stdout.flush()

def progress_advance():
  sys.stdout.write(".")
  sys.stdout.flush()

def progress_complete():
  sys.stdout.write("\n")

def display_results(repo_name, api_contributors, all_contributors):
    print("")

    print("GitHub Contributors:")
    display_users(api_contributors)
    print("")

    print("All Contributors:")
    display_users(all_contributors)
    print("")

    print("Repo: %s" % repo_name)
    print("GitHub Contributors: %s" % len(api_contributors))
    print("All Contributors: %s" % len(all_contributors))

def display_users(user_list, array=False):
  if array:
    print("\n".join(user_list))
  else:
    for user in sorted(user_list,  key=lambda k: k['user_name'].lower()):
      if user["name"] != user["user_name"]:
        print("%s (%s)" % (user["user_name"], user['name']))
      else:
        print(user["user_name"])

def get_user_name(login):
  user = get_data("/users/%s" % login)
  if user is None:
    # Possible ghost user. Return the only data we know; the login
    return login
  if user["name"] is None:
    user["name"] = login
  return user["name"]

<commit_msg>remove unused varw<commit_after>import os
import sys
import atexit
import json
from .connection import Connection, Pager
from .exceptions import ResponseError
from functools import wraps

## System Startup tasks

if "--no-cache" not in sys.argv:
  # Always run on start import
  cache_file = "cache_file.json"
  cache = {}

  if os.path.isfile(cache_file):
    with open(cache_file, "r") as f:
      try:
        cache = json.load(f)
      except ValueError:
        pass

  # Always run on exit
  def save_cache():
    with open(cache_file, 'w') as f:
      json.dump(cache, f)

  atexit.register(save_cache)

  def memoise(wrapped):

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
      key = args[0]
      if key not in cache:
        cache[key] = wrapped(*args, **kwargs)
      return cache[key]

    return wrapper

else:
  # Disable memoisation, force all calls to happen regardless
  def memoise(wrapped):

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
      return wrapped(*args, **kwargs)

    return wrapper

token = os.environ.get("GITHUB_TOKEN")
debug = os.environ.get("DEBUG")

if token is None:
  print("Warning: No GITHUB_TOKEN found - Unauthenticated "
        "requests are rate limited to 60 requests per hour.")
else:
  if debug:
    print("GITHUB_TOKEN found of length %d" % len(token))

conn = Connection(token)

# Walk a json endpoint where pagination is link driven
@memoise
def get_paged_json(uri):
  json = []
  try:
    pager = Pager(conn, uri, params={}, max_pages=0)
    for response in pager:
      progress_advance()
      json += response.json()
  except ResponseError:
    pass

  return json

# Walk a json endpoint where pagination is integer driven
@memoise
def get_page_int_json(uri):
   json = []
   page = 1
   while True:
      progress_advance()
      response = get_data("%s?page=%d" % (uri, page))
      if len(response) == 0:
         break
      else:
         page = page + 1
         json += response
   return json

# Get the users defined by GitHub as contributors
def get_api_contributors(repo_name):
  progress("Collecting API contributors")
  users = []
  response = get_page_int_json("/repos/%s/contributors" % repo_name)
  for entry in response:
    user = get_user_data(entry)
    if user is not None:
      users.append(user)
  progress_complete()

  return users

# Get all Pull Requests and Issues (PRI) users
def get_pri_contributors(repo_name, limit):
  progress("Collecting all repo contributors")

  pri_count = get_pri_count(repo_name)
  if limit == 0:
    minimum = 1
  else:
    minimum = max(1, pri_count - limit)

  users = []
  for index in range(minimum, pri_count + 1):
    user = get_user("/repos/%s/pulls/%d" % (repo_name, index))
    if user is not None:
      users.append(user)

    user = get_user("/repos/%s/issues/%d" % (repo_name, index))
    if user is not None:
      users.append(user)

    for entry in get_paged_json("/repos/%s/pulls/%d/comments" %
                                (repo_name, index)):
        user = get_user_data(entry)
        if user is not None:
          users.append(user)

    for entry in get_paged_json("/repos/%s/issues/%d/comments" %
                                (repo_name, index)):
        user = get_user_data(entry)
        if user is not None:
          users.append(user)

  progress_complete()

  return users

def unique_users(a, b, c, d):
  f = a + b + c + d
  array = [x for x in f if x is not None]
  return list({v['user_name']: v for v in array}.values())

@memoise
def get_data(uri):
  try:
    resp = conn.send("GET", uri)
    return resp.json()
  except ResponseError:
    return None

# Get the number of Pull Requests and Issues
def get_pri_count(repo_name):
  prs = get_data("/repos/%s/pulls?state=all" % repo_name)
  issues = get_data("/repos/%s/issues?state=all" % repo_name)

  if not prs:
    pr_count = 0
  else:
    pr_count = prs[0]["number"]

  if not issues:
    issue_count = 0
  else:
    issue_count = issues[0]["number"]

  return max(pr_count, issue_count)

def get_user_data(entry):
  if "user" in entry.keys():
    if entry['user'] is None:
      return None
    return {"user_name": entry["user"]["login"],
            "avatar": "%s&s=128" % entry["user"]["avatar_url"],
            "name": get_user_name(entry["user"]["login"])}
  else:
    return {"user_name": entry["login"],
            "avatar": "%s&s=128" % entry["avatar_url"],
            "name": get_user_name(entry["login"])}

@memoise
def get_user(uri):
  progress_advance()
  entry = get_data(uri)
  if entry is not None:
    return get_user_data(entry)

@memoise
def repo_exists(repo_name):
  try:
    conn.send("GET", "/repos/%s" % repo_name)
    return True
  except ResponseError:
    return False

def progress(message):
  sys.stdout.write("%s..." % message)
  sys.stdout.flush()

def progress_advance():
  sys.stdout.write(".")
  sys.stdout.flush()

def progress_complete():
  sys.stdout.write("\n")

def display_results(repo_name, api_contributors, all_contributors):
    print("")

    print("GitHub Contributors:")
    display_users(api_contributors)
    print("")

    print("All Contributors:")
    display_users(all_contributors)
    print("")

    print("Repo: %s" % repo_name)
    print("GitHub Contributors: %s" % len(api_contributors))
    print("All Contributors: %s" % len(all_contributors))

def display_users(user_list, array=False):
  if array:
    print("\n".join(user_list))
  else:
    for user in sorted(user_list,  key=lambda k: k['user_name'].lower()):
      if user["name"] != user["user_name"]:
        print("%s (%s)" % (user["user_name"], user['name']))
      else:
        print(user["user_name"])

def get_user_name(login):
  user = get_data("/users/%s" % login)
  if user is None:
    # Possible ghost user. Return the only data we know; the login
    return login
  if user["name"] is None:
    user["name"] = login
  return user["name"]

<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Daniel Wilson
Credit:

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.UPON)
        SpaceGame.listenKeyEvent("keyup", "s", self.stop)
        SpaceGame.listenKeyEvent("keydown", "w", self.DOWNON)
        SpaceGame.listenKeyEvent("keyup", "w", self.stop)
        SpaceGame.listenKeyEvent("keydown", "a", self.Left)
        SpaceGame.listenKeyEvent("keyup", "a", self.stop)
        SpaceGame.listenKeyEvent("keydown", "d", self.Right)
        SpaceGame.listenKeyEvent("keyup", "d", self.stop)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def UPON(self, event):
        self.vy=1
    def DOWNON(self, event):
        self.vy=-1
    def Right(self, event):
        self.vx = 1
    def Left(self, event):
        self.vx = -1
    def stop(self, event):
        self.vy=0
        self.vx=0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0)
        SpaceShip((100,100))
        SpaceShip((500,100))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

def registerKeys(self, keys):
        commands = ["left", "right", "forward", "fire"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<commit_msg>Updated from Brython Server: 3/22/2016 2:21:06 PM<commit_after>"""
spaceshooter.py
Author: Daniel Wilson
Credit:

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.UPON)
        SpaceGame.listenKeyEvent("keyup", "s", self.stop)
        SpaceGame.listenKeyEvent("keydown", "w", self.DOWNON)
        SpaceGame.listenKeyEvent("keyup", "w", self.stop)
        SpaceGame.listenKeyEvent("keydown", "a", self.Left)
        SpaceGame.listenKeyEvent("keyup", "a", self.stop)
        SpaceGame.listenKeyEvent("keydown", "d", self.Right)
        SpaceGame.listenKeyEvent("keyup", "d", self.stop)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def UPON(self, event):
        self.vy=1
    def DOWNON(self, event):
        self.vy=-1
    def Right(self, event):
        self.vx = 1
    def Left(self, event):
        self.vx = -1
    def stop(self, event):
        self.vy=0
        self.vx=0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        SpaceShip((100,100))
        SpaceShip((500,100))

    def step(self):
        step.x += self.vx
        step.y += self.vy
        step.rotation += self.vr

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

def registerKeys(self, keys):
        commands = ["left", "right", "forward", "fire"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<|endoftext|>


<commit_before>#!/usr/bin/env python
from utils.gargoyle_admin_wrapper import *
import argparse

W  = '\033[0m'  # white (normal)
R  = '\033[31m' # red
G  = '\033[32m' # green
P  = '\033[35m' # purple
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

def blocked(blockedIps):
    print(R+"Blocked IPs".ljust(24)+ R+"Time Blocked".ljust(28)+ R+"Time Unblocked"+W)
    print(P+"\n*Note: this does not take into account manual unblocking or adding to white list\n"+W)
    for ip in blockedIps.keys():
        if blockedIps[ip][1] == 0:
            print ip.ljust(23), blockedIps[ip][0].ljust(27), "When removed from black list"
        else:
            print ip.ljust(23), blockedIps[ip][0].ljust(27), blockedIps[ip][1]
    print '\n'

def whiteListed(whiteList):
    print(R+"White Listed IPs".ljust(24) + R+"Time White Listed"+W)
    for ip in whiteList.keys():
        print ip.ljust(23) , whiteList[ip]
    print '\n'

def blackListed(blackList):
    print(R+"Black Listed IPs".ljust(24) + R+"Time Black Listed"+W)
    for ip in blackList:
        print ip.ljust(23), blackList[ip]
    print '\n'

def daemons(daemonStats):

    daemons = ["gargoyle_pscand","gargoyle_pscand_analysis","gargoyle_pscand_monitor","gargoyle_lscand_ssh_bruteforce"]
    print(R+"Daemon Information:"+W)
    running = ''.join(daemonStats["runningDaemons"])
    for daemon in daemons:
        if daemon in running:
            print(daemon+G+' - Running'+W)
        else:
            print(daemon+R+' - Not Running'+W)
    print '\n'
    print("Last Analysis Process - " + daemonStats["last_analysis"])
    print("Last Monitor Process - " + daemonStats["last_monitor"])
    print("Next Analysis Process - " + daemonStats["next_analysis"])
    print("Next Monitor Process - " + daemonStats["next_monitor"])

    print '\n'

def main():

    parser = argparse.ArgumentParser(description='Display Gargoyle Statistics.', prog="status.py")
    parser.add_argument('--blocked',  dest='blocked', action='store_const', const='blocked',
                   help='Display list of blocked ips, time they were blocked, and when they will be unblocked')
    parser.add_argument('--whitelist',  dest='whitelist', action='store_const', const='whitelist',
                   help='Display list of white listed ips')
    parser.add_argument('--blacklist',  dest='blacklist', action='store_const', const='blacklist',
                   help='Display list of black listed ips')
    parser.add_argument('--daemonstats', dest='daemons', action='store_const', const='daemons',
                   help='Activity of daemons(gargoyle_pscand, gargoyle_pscand_monitor, gargoyle_pscand_analysis, gargoyle_lscand_ssh_bruteforce')
    parser.add_argument('--all',  dest='all', action='store_const', const='all',
                   help='Display all statistics listed above')

    args = parser.parse_args()

    if args.all != None:
        showAll = True
    else:
        showAll = False
    daemonStats = daemon_stats()

    print (G+"\n******************** Gargoyle Statistics ********************\n"+W)
    print (G+daemonStats["Active"]+W + '\n')

    if os.getuid() != 0:
        print (R+"Program must be run as root user...exiting\n"+W)
        exit(1)

    if 'running' in daemonStats['Active']:

        try:
            db_loc = os.environ["GARGOYLE_DB"]
        except:
            print(R+'Error: '+W + er.message+ "\nPlease set an environment variable 'GARGOYLE_DB' to the correct database path.")
            exit(1)

        try:
            blockedIps = blocked_time()
            whiteList = get_current_white_list()
            blackList = get_current_black_list()
        except:
            print(R+"Are you sure you set your envinronment variable, GARGOYLE_DB, to the correct path?"+W)

        if args.blocked == None and args.whitelist == None and args.blacklist == None and args.daemons == None and args.all == None:
            showAll = True

        if showAll:
            blocked(blockedIps)
            whiteListed(whiteList)
            blackListed(blackList)
            daemons(daemonStats)
        else:
            if args.blocked != None:
                blocked(blockedIps)
            if args.whitelist != None:
                whiteListed(whiteList)
            if args.blacklist != None:
                blackListed(blackList)
            if args.daemons != None:
                daemons(daemonStats)

main()

<commit_msg>Exceptions<commit_after>#!/usr/bin/env python
from utils.gargoyle_admin_wrapper import *
import argparse

W  = '\033[0m'  # white (normal)
R  = '\033[31m' # red
G  = '\033[32m' # green
P  = '\033[35m' # purple
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

def blocked(blockedIps):
    print(R+"Blocked IPs".ljust(24)+ R+"Time Blocked".ljust(28)+ R+"Time Unblocked"+W)
    print(P+"\n*Note: this does not take into account manual unblocking or adding to white list\n"+W)
    for ip in blockedIps.keys():
        if blockedIps[ip][1] == 0:
            print ip.ljust(23), blockedIps[ip][0].ljust(27), "When removed from black list"
        else:
            print ip.ljust(23), blockedIps[ip][0].ljust(27), blockedIps[ip][1]
    print '\n'

def whiteListed(whiteList):
    print(R+"White Listed IPs".ljust(24) + R+"Time White Listed"+W)
    for ip in whiteList.keys():
        print ip.ljust(23) , whiteList[ip]
    print '\n'

def blackListed(blackList):
    print(R+"Black Listed IPs".ljust(24) + R+"Time Black Listed"+W)
    for ip in blackList:
        print ip.ljust(23), blackList[ip]
    print '\n'

def daemons(daemonStats):

    daemons = ["gargoyle_pscand","gargoyle_pscand_analysis","gargoyle_pscand_monitor","gargoyle_lscand_ssh_bruteforce"]
    print(R+"Daemon Information:"+W)
    running = ''.join(daemonStats["runningDaemons"])
    for daemon in daemons:
        if daemon in running:
            print(daemon+G+' - Running'+W)
        else:
            print(daemon+R+' - Not Running'+W)
    print '\n'
    print("Last Analysis Process - " + daemonStats["last_analysis"])
    print("Last Monitor Process - " + daemonStats["last_monitor"])
    print("Next Analysis Process - " + daemonStats["next_analysis"])
    print("Next Monitor Process - " + daemonStats["next_monitor"])

    print '\n'

def main():

    parser = argparse.ArgumentParser(description='Display Gargoyle Statistics.', prog="status.py")
    parser.add_argument('--blocked',  dest='blocked', action='store_const', const='blocked',
                   help='Display list of blocked ips, time they were blocked, and when they will be unblocked')
    parser.add_argument('--whitelist',  dest='whitelist', action='store_const', const='whitelist',
                   help='Display list of white listed ips')
    parser.add_argument('--blacklist',  dest='blacklist', action='store_const', const='blacklist',
                   help='Display list of black listed ips')
    parser.add_argument('--daemonstats', dest='daemons', action='store_const', const='daemons',
                   help='Activity of daemons(gargoyle_pscand, gargoyle_pscand_monitor, gargoyle_pscand_analysis, gargoyle_lscand_ssh_bruteforce')
    parser.add_argument('--all',  dest='all', action='store_const', const='all',
                   help='Display all statistics listed above')

    args = parser.parse_args()

    if args.all != None:
        showAll = True
    else:
        showAll = False
    daemonStats = daemon_stats()

    print (G+"\n******************** Gargoyle Statistics ********************\n"+W)
    print (G+daemonStats["Active"]+W + '\n')

    if os.getuid() != 0:
        print (R+"Program must be run as root user...exiting\n"+W)
        exit(1)

    if 'running' in daemonStats['Active']:

        try:
            db_loc = os.environ["GARGOYLE_DB"]
        except Exception as er:
            print(R+'Error: '+W + er.message+ "\nPlease set an environment variable 'GARGOYLE_DB' to the correct database path.")
            exit(1)

        try:
            blockedIps = blocked_time()
            whiteList = get_current_white_list()
            blackList = get_current_black_list()
        except Exception as er:
            print(R+"Error: " + W + er.message + "\nAre you sure you set your envinronment variable GARGOYLE_DB to the correct db path?"+W)
            exit(1)

        if args.blocked == None and args.whitelist == None and args.blacklist == None and args.daemons == None and args.all == None:
            showAll = True

        if showAll:
            blocked(blockedIps)
            whiteListed(whiteList)
            blackListed(blackList)
            daemons(daemonStats)
        else:
            if args.blocked != None:
                blocked(blockedIps)
            if args.whitelist != None:
                whiteListed(whiteList)
            if args.blacklist != None:
                blackListed(blackList)
            if args.daemons != None:
                daemons(daemonStats)

main()

<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code,

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

    col= self.collidingWithSprites(Sunthing)
    if col:
        self.explode()

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def explode(self):
        self.visible=False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((400,360))
        SpaceShip((100,100))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<commit_msg>Updated from Brython Server: 3/9/2016 1:58:05 PM<commit_after>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code,

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode()

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def explode(self):
        self.visible=False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((400,360))
        SpaceShip((100,100))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<|endoftext|>


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

from bottle import default_app, route, response, run, request

app = default_app()

def get_number_of_people():
    """
    Return an integer or None.
    """
    people = None
    try:
        with open('people.txt', 'r') as f:
            people = int(f.read().strip())
    except:
        pass
    return people

@route('/')
def json_out():
    response.set_header('Access-Control-Allow-Origin', '*')
    response.set_header('Cache-Control', 'no-cache')
    response.set_header('Content-Type', 'application/json')

    data = {
        'api': '0.13',
        'space': 'coredump',
        'logo': 'https://www.coredump.ch/logo.png',
        'url': 'https://www.coredump.ch/',
        'location': {
            'address': 'Spinnereistrasse 2, 8640 Rapperswil, Switzerland',
            'lat': 47.22936,
            'lon': 8.82949
        },
        'spacefed': {
            'spacenet': False,
            'spacesaml': False,
            'spacephone': False
        },
        'state': {
            'open': False,
            'message': 'Open every monday from 20:00',
        },
        'contact': {
            'irc': 'irc://freenode.net/#coredump',
            'twitter': '@coredump_ch',
            'foursquare': '525c20e5498e875d8231b1e5',
            'email': 'danilo@coredump.ch',
        },
        'issue_report_channels': ['email', 'twitter'],
        'feeds': {
            'blog': {
                'type': 'rss',
                'url': 'https://www.coredump.ch/feed/',
            },
        },
        'cache': {
            'schedule': 'm.02',
        },
        'projects': [
            'https://www.coredump.ch/projekte/',
            'https://discourse.coredump.ch/c/projects',
            'https://github.com/coredump-ch/',
        ],
        'sensors': {
            'people_now_present': [
                {'value': 0},
            ],
        },
    }

    people = get_number_of_people()
    if people and people > 0:
        data['state']['open'] = True
        data['sensors']['people_now_present']['value'] = people
        base_msg = '1 person' if people == 1 else '%s people' % people
        data['state']['message'] = base_msg + ' present right now'

    return json.dumps(data)

@route('/update', method='POST')
def update():
    """
    Update the data in a text file.
    TODO: Public / Private key crypto.
    """
    people = int(request.POST.get('people'))
    with open('people.txt', 'w') as f:
        f.write(str(people))
    return 'OK'

@route('/sensors/people_now_present/html')
def sensor_people_html():
    """
    Show a HTML version of the opening status.
    """
    people = get_number_of_people()
    html = []
    if people and people > 0:
        html.append('
Open
')
        msg = '1 person' if people == 1 else '%s people' % people
        html.append('
%s present
' % msg)
    else:
        html.append('
Closed
')
    return '\n'.join(html)

if __name__ == '__main__':
    run(host='localhost', port=8080)
<commit_msg>Fixed bug in assigning present people<commit_after># -*- coding: utf-8 -*-
import json

from bottle import default_app, route, response, run, request

app = default_app()

def get_number_of_people():
    """
    Return an integer or None.
    """
    people = None
    try:
        with open('people.txt', 'r') as f:
            people = int(f.read().strip())
    except:
        pass
    return people

@route('/')
def json_out():
    response.set_header('Access-Control-Allow-Origin', '*')
    response.set_header('Cache-Control', 'no-cache')
    response.set_header('Content-Type', 'application/json')

    data = {
        'api': '0.13',
        'space': 'coredump',
        'logo': 'https://www.coredump.ch/logo.png',
        'url': 'https://www.coredump.ch/',
        'location': {
            'address': 'Spinnereistrasse 2, 8640 Rapperswil, Switzerland',
            'lat': 47.22936,
            'lon': 8.82949
        },
        'spacefed': {
            'spacenet': False,
            'spacesaml': False,
            'spacephone': False
        },
        'state': {
            'open': False,
            'message': 'Open every monday from 20:00',
        },
        'contact': {
            'irc': 'irc://freenode.net/#coredump',
            'twitter': '@coredump_ch',
            'foursquare': '525c20e5498e875d8231b1e5',
            'email': 'danilo@coredump.ch',
        },
        'issue_report_channels': ['email', 'twitter'],
        'feeds': {
            'blog': {
                'type': 'rss',
                'url': 'https://www.coredump.ch/feed/',
            },
        },
        'cache': {
            'schedule': 'm.02',
        },
        'projects': [
            'https://www.coredump.ch/projekte/',
            'https://discourse.coredump.ch/c/projects',
            'https://github.com/coredump-ch/',
        ],
        'sensors': {
            'people_now_present': [
                {'value': 0},
            ],
        },
    }

    people = get_number_of_people()
    if people and people > 0:
        data['state']['open'] = True
        data['sensors']['people_now_present'][0]['value'] = people
        base_msg = '1 person' if people == 1 else '%s people' % people
        data['state']['message'] = base_msg + ' present right now'

    return json.dumps(data)

@route('/update', method='POST')
def update():
    """
    Update the data in a text file.
    TODO: Public / Private key crypto.
    """
    people = int(request.POST.get('people'))
    with open('people.txt', 'w') as f:
        f.write(str(people))
    return 'OK'

@route('/sensors/people_now_present/html')
def sensor_people_html():
    """
    Show a HTML version of the opening status.
    """
    people = get_number_of_people()
    html = []
    if people and people > 0:
        html.append('
Open
')
        msg = '1 person' if people == 1 else '%s people' % people
        html.append('
%s present
' % msg)
    else:
        html.append('
Closed
')
    return '\n'.join(html)

if __name__ == '__main__':
    run(host='localhost', port=8080)
<|endoftext|>


<commit_before># Copyright (c) 2014 bivio Software, Inc.  All rights reserved.

from publicprize.controller import db
from publicprize import controller
from publicprize import biv

class Contest(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('contest_s', start=1002, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    tag_line = db.Column(db.String(500))
    # TODO(pjm): move logo and founder_avatar to separate model BivImage
    contest_logo = db.Column(db.LargeBinary)
    logo_type = db.Column(db.Enum('gif', 'png', 'jpeg', name='logo_type'))

    def contestant_count(self):
        # TODO(pjm): count related Contestant records
        return 12

    def donor_count(self):
        # TODO(pjm): count related Donor records
        return 802

class Contestant(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('contestant_s', start=1003, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    youtube_code = db.Column(db.String(500))
    slideshow_code = db.Column(db.String(500))
    contestant_desc = db.Column(db.String)
    tax_id = db.Column(db.Numeric(9))

class Founder(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('founder_s', start=1004, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    founder_desc = db.Column(db.String)
    founder_avatar = db.Column(db.LargeBinary)
    avatar_type = db.Column(db.Enum('gif', 'png', 'jpeg', name='avatar_type'))

Contest.BIV_MARKER = biv.register_marker(2, Contest)
Contestant.BIV_MARKER = biv.register_marker(3, Contestant)
Founder.BIV_MARKER = biv.register_marker(4, Founder)
<commit_msg>added Contestant.website<commit_after># Copyright (c) 2014 bivio Software, Inc.  All rights reserved.

from publicprize.controller import db
from publicprize.contest.form import ContestantForm
from publicprize import controller
from publicprize import biv

class Contest(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('contest_s', start=1002, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    tag_line = db.Column(db.String(500))
    # TODO(pjm): move logo and founder_avatar to separate model BivImage
    contest_logo = db.Column(db.LargeBinary)
    logo_type = db.Column(db.Enum('gif', 'png', 'jpeg', name='logo_type'))

    def contestant_count(self):
        # TODO(pjm): count related Contestant records
        return 12

    def donor_count(self):
        # TODO(pjm): count related Donor records
        return 802

class Contestant(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('contestant_s', start=1003, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    youtube_code = db.Column(db.String(500))
    slideshow_code = db.Column(db.String(500))
    contestant_desc = db.Column(db.String)
    tax_id = db.Column(db.Numeric(9))
    website = db.Column(db.String(100))

class Founder(db.Model, controller.Model):
    biv_id = db.Column(
        db.Numeric(18),
        db.Sequence('founder_s', start=1004, increment=1000),
        primary_key=True
    )
    display_name = db.Column(db.String(100), nullable=False)
    founder_desc = db.Column(db.String)
    founder_avatar = db.Column(db.LargeBinary)
    avatar_type = db.Column(db.Enum('gif', 'png', 'jpeg', name='avatar_type'))

Contest.BIV_MARKER = biv.register_marker(2, Contest)
Contestant.BIV_MARKER = biv.register_marker(3, Contestant)
Founder.BIV_MARKER = biv.register_marker(4, Founder)
<|endoftext|>


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

from odin.utils import force_tuple, getmeta

from .base import BaseField

__all__ = ('ConstantField', 'CalculatedField', 'calculated_field', 'MultiPartField')

class VirtualField(BaseField):
    """
    Base class for virtual fields. A virtual fields is treated like any other field during encoding/decoding (provided
    it can be written to).
    """
    data_type_name = None

    def __init__(self, verbose_name=None, verbose_name_plural=None, name=None, data_type_name=None, doc_text='',
                 is_attribute=False, key=False):
        """
        Initialisation of virtual field

        :param verbose_name: Display name of field.
        :param verbose_name_plural: Plural display name of field.
        :param name: Name of the serialised field.
        :param data_type_name: A name for the data type this field returns (used for generating documentation)
        :param doc_text: Documentation for the field, replaces help text
        :param is_attribute: Special flag for codecs that support attributes on nodes (ie XML)
        """
        super(VirtualField, self).__init__(verbose_name, verbose_name_plural, name, doc_text)

        self.data_type_name = data_type_name
        self.is_attribute = is_attribute
        self.key = key

        self.resource = None

    def __get__(self, instance, owner):
        raise NotImplementedError

    def __set__(self, instance, value):
        raise AttributeError("Read only")

    def contribute_to_class(self, cls, name):
        self.set_attributes_from_name(name)
        self.resource = cls
        getmeta(cls).add_virtual_field(self)
        setattr(cls, name, self)

    def prepare(self, value):
        """
        Prepare a value for serialisation.

        :param value:
        :return:
        """
        return value

    def value_from_object(self, obj):
        """
        Returns the value of this field in the given resource instance.
        """
        return getattr(obj, self.attname)

class ConstantField(VirtualField):
    """
    A field that provides a constant value.
    """
    def __init__(self, value, *args, **kwargs):
        super(ConstantField, self).__init__(*args, **kwargs)
        self.value = value

    def __get__(self, instance, owner):
        return self.value

class CalculatedField(VirtualField):
    """
    A field whose that is calculated by an expression.

    The expression should accept a single "self" parameter that is a Resource instance.
    """
    def __init__(self, expr, *args, **kwargs):
        assert callable(expr)
        super(CalculatedField, self).__init__(*args, **kwargs)
        self.expr = expr

    def __get__(self, instance, owner):
        return self.expr(instance)

def calculated_field(method=None, **kwargs):
    """
    Converts an instance method into a calculated field.
    """
    def inner(expr):
        return CalculatedField(expr, **kwargs)
    return inner if method is None else inner(method)

class MultiPartField(VirtualField):
    """
    A field whose value is the combination of several other fields.

    This field should be included after the field that make up the multipart value.
    """
    def __init__(self, field_names, separator='', **kwargs):
        """
        :param field_names: Name(s) of fields to make up key
        :type field_names: str | tuple[str] | list[str]
        :param separator: Separator to use between values.
        :type separator: str
        :param kwargs: Additional kwargs for VirtualField

        """
        kwargs.setdefault('data_type_name', 'String')
        super(MultiPartField, self).__init__(**kwargs)
        self.field_names = force_tuple(field_names)
        self.separator = separator
        self._fields = None

    def __get__(self, instance, owner):
        values = [f.prepare(f.value_from_object(instance)) for f in self._fields]
        return self.separator.join(str(v) for v in values)

    def on_resource_ready(self):
        # Extract reference to fields
        meta = getmeta(self.resource)
        try:
            self._fields = tuple(meta.field_map[name] for name in self.field_names)
        except KeyError as ex:
            raise AttributeError("Attribute `{}` not found on {!r}".format(ex.message, self.resource))
<commit_msg>Tweak multipart field to have a generate_value method<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import

from odin.utils import force_tuple, getmeta

from .base import BaseField

__all__ = ('ConstantField', 'CalculatedField', 'calculated_field', 'MultiPartField')

class VirtualField(BaseField):
    """
    Base class for virtual fields. A virtual fields is treated like any other field during encoding/decoding (provided
    it can be written to).
    """
    data_type_name = None

    def __init__(self, verbose_name=None, verbose_name_plural=None, name=None, data_type_name=None, doc_text='',
                 is_attribute=False, key=False):
        """
        Initialisation of virtual field

        :param verbose_name: Display name of field.
        :param verbose_name_plural: Plural display name of field.
        :param name: Name of the serialised field.
        :param data_type_name: A name for the data type this field returns (used for generating documentation)
        :param doc_text: Documentation for the field, replaces help text
        :param is_attribute: Special flag for codecs that support attributes on nodes (ie XML)
        """
        super(VirtualField, self).__init__(verbose_name, verbose_name_plural, name, doc_text)

        self.data_type_name = data_type_name
        self.is_attribute = is_attribute
        self.key = key

        self.resource = None

    def __get__(self, instance, owner):
        raise NotImplementedError

    def __set__(self, instance, value):
        raise AttributeError("Read only")

    def contribute_to_class(self, cls, name):
        self.set_attributes_from_name(name)
        self.resource = cls
        getmeta(cls).add_virtual_field(self)
        setattr(cls, name, self)

    def prepare(self, value):
        """
        Prepare a value for serialisation.

        :param value:
        :return:
        """
        return value

    def value_from_object(self, obj):
        """
        Returns the value of this field in the given resource instance.
        """
        return getattr(obj, self.attname)

class ConstantField(VirtualField):
    """
    A field that provides a constant value.
    """
    def __init__(self, value, *args, **kwargs):
        super(ConstantField, self).__init__(*args, **kwargs)
        self.value = value

    def __get__(self, instance, owner):
        return self.value

class CalculatedField(VirtualField):
    """
    A field whose that is calculated by an expression.

    The expression should accept a single "self" parameter that is a Resource instance.
    """
    def __init__(self, expr, *args, **kwargs):
        assert callable(expr)
        super(CalculatedField, self).__init__(*args, **kwargs)
        self.expr = expr

    def __get__(self, instance, owner):
        return self.expr(instance)

def calculated_field(method=None, **kwargs):
    """
    Converts an instance method into a calculated field.
    """
    def inner(expr):
        return CalculatedField(expr, **kwargs)
    return inner if method is None else inner(method)

class MultiPartField(VirtualField):
    """
    A field whose value is the combination of several other fields.

    This field should be included after the field that make up the multipart value.
    """
    def __init__(self, field_names, separator='', **kwargs):
        """
        :param field_names: Name(s) of fields to make up key
        :type field_names: str | tuple[str] | list[str]
        :param separator: Separator to use between values.
        :type separator: str
        :param kwargs: Additional kwargs for VirtualField

        """
        kwargs.setdefault('data_type_name', 'String')
        super(MultiPartField, self).__init__(**kwargs)
        self.field_names = force_tuple(field_names)
        self.separator = separator
        self._fields = None

    def __get__(self, instance, owner):
        return self.generate_value(instance)

    def generate_value(self, instance):
        """
        Generate a key based on other values.
        """
        values = [f.prepare(f.value_from_object(instance)) for f in self._fields]
        return self.separator.join(str(v) for v in values)

    def on_resource_ready(self):
        # Extract reference to fields
        meta = getmeta(self.resource)
        try:
            self._fields = tuple(meta.field_map[name] for name in self.field_names)
        except KeyError as ex:
            raise AttributeError("Attribute `{}` not found on {!r}".format(ex.message, self.resource))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
""" OAuth support, facebook and google.

Session variables:

user.biv_id: User's id, survives after log out
user.oauth_type, User's oauth_type, cleared during log out
user.is_logged_in, User's logged in status
user.display_name, User's full name

oauth.next_uri, redirect uri after successful login,
    cleared after authorize_complete()
oauth.state, oauth state var, cleared after authorize_complete()
oauth.<oauth_type>.token, user's oauth token, cleared during log out

    :copyright: Copyright (c) 2014 Bivio Software, Inc.  All Rights Reserved.
    :license: Apache, see LICENSE for more details.
"""

import flask
import flask_oauthlib.client
from publicprize import controller
from publicprize.auth.model import User
import werkzeug

def _oauth_provider(name, **kwargs):
    """Creates a OAuth client for the named provider."""
    config = controller.app().config
    return flask_oauthlib.client.OAuth(controller.app()).remote_app(
        name,
        consumer_key=config['PP_{}_APP_ID'.format(name.upper())],
        consumer_secret=config['PP_{}_APP_SECRET'.format(name.upper())],
        request_token_url=None,
        **kwargs
    )

_OAUTH_PROVIDER = {
    'facebook': _oauth_provider(
        'facebook',
        request_token_params={'scope': 'email'},
        base_url='https://graph.facebook.com',
        access_token_url='/oauth/access_token',
        authorize_url='https://www.facebook.com/dialog/oauth'
    ),
    'google': _oauth_provider(
        'google',
        request_token_params={
            'scope': 'https://www.googleapis.com/auth/userinfo.email'
        },
        base_url='https://www.googleapis.com/oauth2/v1/',
        access_token_method='POST',
        access_token_url='https://accounts.google.com/o/oauth2/token',
        authorize_url='https://accounts.google.com/o/oauth2/auth',
    )
}

_OAUTH_PROVIDER_DATA_PATH = {
    'facebook': 'me',
    'google': 'userinfo',
}

def add_user_to_session(user):
    """Store user info on session"""
    controller.db.session.add(user)
    controller.db.session.flush()
    flask.session['user.biv_id'] = user.biv_id
    flask.session['user.oauth_type'] = user.oauth_type
    flask.session['user.is_logged_in'] = True
    flask.session['user.display_name'] = user.display_name

def authorize(oauth_type, callback):
    """Call the OAuth provider's server which returns to the callback
    on completion or failer.
    Store the "next" or referrer page to return to after callback."""
    flask.session['oauth.next_uri'] = flask.request.args.get('next') \
        or flask.request.referrer or None
    # state variable is uri randomizer, verfied in authorize_complete()
    state = werkzeug.security.gen_salt(64)
    flask.session['oauth.state'] = state
    return _OAUTH_PROVIDER[oauth_type].authorize(
        callback=callback,
        state=state
    )

def authorize_complete(oauth_type):
    """Handle oauth callback, validate the response and update the user
    model."""
    resp = _OAUTH_PROVIDER[oauth_type].authorized_response()
    next_uri = None
    if 'oauth.next_uri' in flask.session:
        next_uri = flask.session['oauth.next_uri']
        del flask.session['oauth.next_uri']
    if _validate_auth(resp, oauth_type):
        flask.session['oauth.{}.token'.format(oauth_type)] = (
            resp['access_token'], '')
        _user_from_info(
            oauth_type,
            _OAUTH_PROVIDER[oauth_type].get(
                _OAUTH_PROVIDER_DATA_PATH[oauth_type]).data
        )
    return flask.redirect(next_uri or '/')

def logout():
    """Clear the login state from the session and redirect to root."""
    _clear_session()
    flask.flash('You have successfully logged out.')
    return flask.redirect('/')

def _clear_session():
    """Clear the login state from the session"""
    flask.session['user.is_logged_in'] = False
    if 'oauth.state' in flask.session:
        del flask.session['oauth.state']
    oauth_type = flask.session.get('user.oauth_type')
    if oauth_type:
        key = 'oauth.{}.token'.format(oauth_type)
        if flask.session.get(key):
            del flask.session[key]
        del flask.session['user.oauth_type']

def _client_error(oauth_type, message=None):
    _clear_session()
    flask.flash(message \
        or '{} has denied access to this App.'.format(oauth_type))

def _user_from_info(oauth_type, info):
    """Saves oauth provider user info to user model.
    info arg contains email, id, name."""
    controller.app().logger.info(info)
    if not info.get('email'):
        _client_error(
            oauth, 'Your email must be provided to this App to login.')
        return
    user = User.query.filter_by(
        oauth_type=oauth_type,
        oauth_id=info['id']
    ).first()
    if user:
        user.display_name = info['name']
        user.user_email = info['email']
    else:
        user = User(
            display_name=info['name'],
            user_email=info['email'],
            oauth_type=oauth_type,
            oauth_id=info['id']
        )
    # TODO(pjm): download user avatar
    # facebook: https://graph.facebook.com/{id}/picture?type=square
    # google: image url provided in info.picture field
    add_user_to_session(user)

def _validate_auth(resp, oauth_type):
    """Validates oauth providers's auth response"""
    app = controller.app()

    if resp is None or isinstance(resp, flask_oauthlib.client.OAuthException):
        _client_error(oauth_type)
        app.logger.warn(
            'Access denied: {}, resp: {}'.format(flask.request.args, resp))
        return False
    state = flask.session['oauth.state']
    del flask.session['oauth.state']
    if state != flask.request.args.get('state'):
        _client_error(oauth_type)
        app.logger.warn(
            'Invalid oauth state, expected: {} response: {}'.format(
                state,
                flask.request.args.get('state'))
        )
        return False
    return True

_FACEBOOK = _OAUTH_PROVIDER['facebook']
_GOOGLE = _OAUTH_PROVIDER['google']

@_FACEBOOK.tokengetter
def _get_facebook_oauth_token():
    """Callback for facebook auth"""
    return flask.session.get('oauth.facebook.token')

@_GOOGLE.tokengetter
def _get_google_access_token():
    """Callback for google auth"""
    return flask.session.get('oauth.google.token')
<commit_msg>user.oauth_type session var now survives log out<commit_after># -*- coding: utf-8 -*-
""" OAuth support, facebook and google.

Session variables:

user.biv_id: User's id, survives after log out
user.oauth_type, User's oauth_type, survives after log out
user.is_logged_in, User's logged in status
user.display_name, User's full name

oauth.next_uri, redirect uri after successful login,
    cleared after authorize_complete()
oauth.state, oauth state var, cleared after authorize_complete()
oauth.<oauth_type>.token, user's oauth token, cleared during log out

    :copyright: Copyright (c) 2014 Bivio Software, Inc.  All Rights Reserved.
    :license: Apache, see LICENSE for more details.
"""

import flask
import flask_oauthlib.client
from publicprize import controller
from publicprize.auth.model import User
import werkzeug

def _oauth_provider(name, **kwargs):
    """Creates a OAuth client for the named provider."""
    config = controller.app().config
    return flask_oauthlib.client.OAuth(controller.app()).remote_app(
        name,
        consumer_key=config['PP_{}_APP_ID'.format(name.upper())],
        consumer_secret=config['PP_{}_APP_SECRET'.format(name.upper())],
        request_token_url=None,
        **kwargs
    )

_OAUTH_PROVIDER = {
    'facebook': _oauth_provider(
        'facebook',
        request_token_params={'scope': 'email'},
        base_url='https://graph.facebook.com',
        access_token_url='/oauth/access_token',
        authorize_url='https://www.facebook.com/dialog/oauth'
    ),
    'google': _oauth_provider(
        'google',
        request_token_params={
            'scope': 'https://www.googleapis.com/auth/userinfo.email'
        },
        base_url='https://www.googleapis.com/oauth2/v1/',
        access_token_method='POST',
        access_token_url='https://accounts.google.com/o/oauth2/token',
        authorize_url='https://accounts.google.com/o/oauth2/auth',
    )
}

_OAUTH_PROVIDER_DATA_PATH = {
    'facebook': 'me',
    'google': 'userinfo',
}

def add_user_to_session(user):
    """Store user info on session"""
    controller.db.session.add(user)
    controller.db.session.flush()
    flask.session['user.biv_id'] = user.biv_id
    flask.session['user.oauth_type'] = user.oauth_type
    flask.session['user.is_logged_in'] = True
    flask.session['user.display_name'] = user.display_name

def authorize(oauth_type, callback):
    """Call the OAuth provider's server which returns to the callback
    on completion or failer.
    Store the "next" or referrer page to return to after callback."""
    flask.session['oauth.next_uri'] = flask.request.args.get('next') \
        or flask.request.referrer or None
    # state variable is uri randomizer, verfied in authorize_complete()
    state = werkzeug.security.gen_salt(64)
    flask.session['oauth.state'] = state
    return _OAUTH_PROVIDER[oauth_type].authorize(
        callback=callback,
        state=state
    )

def authorize_complete(oauth_type):
    """Handle oauth callback, validate the response and update the user
    model."""
    resp = _OAUTH_PROVIDER[oauth_type].authorized_response()
    next_uri = None
    if 'oauth.next_uri' in flask.session:
        next_uri = flask.session['oauth.next_uri']
        del flask.session['oauth.next_uri']
    if _validate_auth(resp, oauth_type):
        flask.session['oauth.{}.token'.format(oauth_type)] = (
            resp['access_token'], '')
        _user_from_info(
            oauth_type,
            _OAUTH_PROVIDER[oauth_type].get(
                _OAUTH_PROVIDER_DATA_PATH[oauth_type]).data
        )
    return flask.redirect(next_uri or '/')

def logout():
    """Clear the login state from the session and redirect to root."""
    _clear_session()
    flask.flash('You have successfully logged out.')
    return flask.redirect('/')

def _clear_session():
    """Clear the login state from the session"""
    flask.session['user.is_logged_in'] = False
    if 'oauth.state' in flask.session:
        del flask.session['oauth.state']
    oauth_type = flask.session.get('user.oauth_type')
    if oauth_type:
        key = 'oauth.{}.token'.format(oauth_type)
        if flask.session.get(key):
            del flask.session[key]

def _client_error(oauth_type, message=None):
    _clear_session()
    flask.flash(message \
        or '{} has denied access to this App.'.format(oauth_type))

def _user_from_info(oauth_type, info):
    """Saves oauth provider user info to user model.
    info arg contains email, id, name."""
    controller.app().logger.info(info)
    if not info.get('email'):
        _client_error(
            oauth, 'Your email must be provided to this App to login.')
        return
    user = User.query.filter_by(
        oauth_type=oauth_type,
        oauth_id=info['id']
    ).first()
    if user:
        user.display_name = info['name']
        user.user_email = info['email']
    else:
        user = User(
            display_name=info['name'],
            user_email=info['email'],
            oauth_type=oauth_type,
            oauth_id=info['id']
        )
    # TODO(pjm): download user avatar
    # facebook: https://graph.facebook.com/{id}/picture?type=square
    # google: image url provided in info.picture field
    add_user_to_session(user)

def _validate_auth(resp, oauth_type):
    """Validates oauth providers's auth response"""
    app = controller.app()

    if resp is None or isinstance(resp, flask_oauthlib.client.OAuthException):
        _client_error(oauth_type)
        app.logger.warn(
            'Access denied: {}, resp: {}'.format(flask.request.args, resp))
        return False
    state = flask.session['oauth.state']
    del flask.session['oauth.state']
    if state != flask.request.args.get('state'):
        _client_error(oauth_type)
        app.logger.warn(
            'Invalid oauth state, expected: {} response: {}'.format(
                state,
                flask.request.args.get('state'))
        )
        return False
    return True

_FACEBOOK = _OAUTH_PROVIDER['facebook']
_GOOGLE = _OAUTH_PROVIDER['google']

@_FACEBOOK.tokengetter
def _get_facebook_oauth_token():
    """Callback for facebook auth"""
    return flask.session.get('oauth.facebook.token')

@_GOOGLE.tokengetter
def _get_google_access_token():
    """Callback for google auth"""
    return flask.session.get('oauth.google.token')
<|endoftext|>


<commit_before>import json
import re
import sys
import time
from findspam import FindSpam
from datahandling import *
from parsing import get_user_from_url
from bayesianfuncs import *

def get_spam_reasons(title, body, user_name, site):
    reasons = []
    if title is not None:
        reasons += FindSpam.testpost(title, user_name, site)
    if body is not None:
        reasons += FindSpam.testbody(body, site)
    return reasons

def checkifspam(title, body, user_name, user_url, post_site, post_id, post_url):
    test = get_spam_reasons(title, body, user_name, post_site)
    if 0 < len(test):
        if is_blacklisted_user(get_user_from_url(user_url)):
            test.append("Blacklisted user")
        if 0 < len(test):
            if has_already_been_posted(post_site, post_id, title) or is_false_positive(post_id, post_site) \
                    or is_whitelisted_user(get_user_from_url(user_url)) \
                    or is_ignored_post(post_id, post_site) \
                    or is_auto_ignored_post((post_id, post_site)):
                return False # Don't repost. Reddit will hate you.
            append_to_latest_questions(post_site, post_id, title)
            if len(test) == 1 and "All-caps title" in test:
                add_auto_ignored_post(post_id, post_site, datetime.now())
            try:
                owner = user_url
                users_file = open("users.txt", "a")
                users_file.write(post_site + " " + owner + " " + title + " " + post_url + "\n")
                users_file.close()
            except Exception as e:
                print e
            return True
        return False

def checkifspam_json(data):
    d = json.loads(json.loads(data)["data"])
    try:
        _ = d["ownerUrl"]
    except:
        return False # owner's account doesn't exist anymore, no need to post it in chat:
                     # http://chat.stackexchange.com/transcript/message/18380776#18380776
    title = d["titleEncodedFancy"]
    poster = d["ownerDisplayName"]
    url = d["url"]
    print time.strftime("%Y-%m-%d %H:%M:%S"),GlobalVars.parser.unescape(title).encode("ascii",errors="replace")
    quality_score = bayesian_score(title)
    print quality_score
    if quality_score < 0.3 and d["siteBaseHostAddress"] == "stackoverflow.com":
        print GlobalVars.bayesian_testroom.send_message("[ SmokeDetector | BayesianBeta ] Quality score " + str(quality_score * 100) + ": [" + title + "](" + url + ")")
    site = d["siteBaseHostAddress"]
    site = site.encode("ascii",errors="replace")
    sys.stdout.flush()
    return checkifspam(title, None, poster, d["ownerUrl"], site, str(d["id"]), url)

def handlespam(title, body, poster, site, post_url, poster_url):
    try:
        reason = ", ".join(get_spam_reasons(title, body, poster, site))
        s = "[ [SmokeDetector](https://github.com/Charcoal-SE/SmokeDetector) ] %s: [%s](%s) by [%s](%s) on `%s`" % \
          (reason, title.strip(), post_url, poster.strip(), poster_url, site)
        print GlobalVars.parser.unescape(s).encode('ascii',errors='replace')
        if time.time() >= GlobalVars.blockedTime:
            GlobalVars.charcoal_hq.send_message(s)
            GlobalVars.tavern_on_the_meta.send_message(s)
            for specialroom in GlobalVars.specialrooms:
                sites = specialroom["sites"]
                if site in sites and reason not in specialroom["unwantedReasons"]:
                    specialroom["room"].send_message(s)
    except:
        print "NOP"

def handlespam_json(data):
    try:
        d=json.loads(json.loads(data)["data"])
        title = d["titleEncodedFancy"]
        poster = d["ownerDisplayName"]
        site = d["siteBaseHostAddress"]
        url = d["url"]
        poster_url = d["ownerUrl"]
        title_to_post = GlobalVars.parser.unescape(re.sub(r"([_*\\`\[\]])", r"\\\1", title)).strip()
        handlespam(title_to_post, None, poster, site, url, poster_url)
    except:
        print "NOP"<commit_msg>Fix TypeError<commit_after>import json
import re
import sys
import time
from findspam import FindSpam
from datahandling import *
from parsing import get_user_from_url
from bayesianfuncs import *

def get_spam_reasons(title, body, user_name, site):
    reasons = []
    if title is not None:
        reasons += FindSpam.testpost(title, user_name, site)
    if body is not None:
        reasons += FindSpam.testbody(body, site)
    return reasons

def checkifspam(title, body, user_name, user_url, post_site, post_id, post_url):
    test = get_spam_reasons(title, body, user_name, post_site)
    if 0 < len(test):
        if is_blacklisted_user(get_user_from_url(user_url)):
            test.append("Blacklisted user")
        if 0 < len(test):
            if has_already_been_posted(post_site, post_id, title) or is_false_positive(post_id, post_site) \
                    or is_whitelisted_user(get_user_from_url(user_url)) \
                    or is_ignored_post((post_id, post_site)) \
                    or is_auto_ignored_post((post_id, post_site)):
                return False # Don't repost. Reddit will hate you.
            append_to_latest_questions(post_site, post_id, title)
            if len(test) == 1 and "All-caps title" in test:
                add_auto_ignored_post(post_id, post_site, datetime.now())
            try:
                owner = user_url
                users_file = open("users.txt", "a")
                users_file.write(post_site + " " + owner + " " + title + " " + post_url + "\n")
                users_file.close()
            except Exception as e:
                print e
            return True
        return False

def checkifspam_json(data):
    d = json.loads(json.loads(data)["data"])
    try:
        _ = d["ownerUrl"]
    except:
        return False # owner's account doesn't exist anymore, no need to post it in chat:
                     # http://chat.stackexchange.com/transcript/message/18380776#18380776
    title = d["titleEncodedFancy"]
    poster = d["ownerDisplayName"]
    url = d["url"]
    print time.strftime("%Y-%m-%d %H:%M:%S"),GlobalVars.parser.unescape(title).encode("ascii",errors="replace")
    quality_score = bayesian_score(title)
    print quality_score
    if quality_score < 0.3 and d["siteBaseHostAddress"] == "stackoverflow.com":
        print GlobalVars.bayesian_testroom.send_message("[ SmokeDetector | BayesianBeta ] Quality score " + str(quality_score * 100) + ": [" + title + "](" + url + ")")
    site = d["siteBaseHostAddress"]
    site = site.encode("ascii",errors="replace")
    sys.stdout.flush()
    return checkifspam(title, None, poster, d["ownerUrl"], site, str(d["id"]), url)

def handlespam(title, body, poster, site, post_url, poster_url):
    try:
        reason = ", ".join(get_spam_reasons(title, body, poster, site))
        s = "[ [SmokeDetector](https://github.com/Charcoal-SE/SmokeDetector) ] %s: [%s](%s) by [%s](%s) on `%s`" % \
          (reason, title.strip(), post_url, poster.strip(), poster_url, site)
        print GlobalVars.parser.unescape(s).encode('ascii',errors='replace')
        if time.time() >= GlobalVars.blockedTime:
            GlobalVars.charcoal_hq.send_message(s)
            GlobalVars.tavern_on_the_meta.send_message(s)
            for specialroom in GlobalVars.specialrooms:
                sites = specialroom["sites"]
                if site in sites and reason not in specialroom["unwantedReasons"]:
                    specialroom["room"].send_message(s)
    except:
        print "NOP"

def handlespam_json(data):
    try:
        d=json.loads(json.loads(data)["data"])
        title = d["titleEncodedFancy"]
        poster = d["ownerDisplayName"]
        site = d["siteBaseHostAddress"]
        url = d["url"]
        poster_url = d["ownerUrl"]
        title_to_post = GlobalVars.parser.unescape(re.sub(r"([_*\\`\[\]])", r"\\\1", title)).strip()
        handlespam(title_to_post, None, poster, site, url, poster_url)
    except:
        print "NOP"<|endoftext|>