<commit_before>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

weather = int(input("Any weather? (1 for custom, 0 for none)"))
if weather == 1:
    rainny = int(input("Rain? (1 for rain, 0 for none)"))
    if rainny == 1:
        ar = .2
    else:
        ar = 0
    foggy = int(input("Fog? (1 for fog, 0 for none)"))
    if foggy == 1:
        af = .2
    else:
        af = 0
    snowy = int(input("Snow? (1 for snow, 0 for none)"))
    if snowy == 1:
        afs = .2
    else:
        afs = 0

else:
    rainny = 0
    ar = 0
    foggy = 0
    af = 0
    snowy = 0
    afs = 0

ss = 0-(int(input("Signal Strength (whole numbers only)")))
cpx = int(input("X Location of Plane"))
cpy = int(input("Y Location of Plane"))
#numplanes = int(input("Number of planes in air? (for future use)"))
'''

rainny = 0
foggy = 0
snowy = 0
'''

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 3
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
red9 = Color(0xff0000, 0.9)
red8 = Color(0xff0000, 0.8)
red7 = Color(0xff0000, 0.7)
red6 = Color(0xff0000, 0.6)
red5 = Color(0xff0000, 0.5)
red4 = Color(0xff0000, 0.4)
red3 = Color(0xff0000, 0.3)
red2 = Color(0xff0000, 0.2)
red1 = Color(0xff0000, 0.1)

green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
sun = Color(0xFFCC33,1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thinlinew= LineStyle(1, white)
thinlinesun = LineStyle(2, sun)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0

class snow(Sprite):
    asset = RectangleAsset(1,1,thinlinew,white)
    def __init__(self, position):
        super().__init__(snow.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0

class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    #asset = EllipseAsset(50,5,thinliner,red)
    asset = ImageAsset("images/Signalstrength-1.png", Frame(0,0,(959/29),300), 29, 'horizontal')
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.scale = .35
        #self.rotation=.55
        self.rotation = math.atan2(cpy,cpx)
        self.a = 0
        self.i = ss
        self.s = 0
        self.t = 0
        self.g = 0
    def step(self):
        if self.a != 2:
            self.t += 1
        if self.a == 0:
            self.i += .2 + afs + af + ar
            if self.i >= 0:
                self.setImage((self.i))
            else:
                self.setImage(0)
            self.x += 3*cpx
            self.y -= 1.5*cpy
            if self.x >= 900:
                self.a = 1
                if self.i >= 0:
                    self.i *= 2
                else:
                    self.i = ss - self.i
            if self.i >= 28:
                self.setImage(28)
                self.a = 2
                Sprite(TextAsset(text="Signal Is Not Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
        if self.a == 1:
            self.i += 0.2 + afs + af +ar
            if self.i >= 0:
                self.setImage((self.i))
            else:
                self.setImage(0)
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 72 and self.i <= 28:
                self.a = 2
                self.s = 1
            if self.i >= 28:
                self.setImage(28)
                self.a = 2
                Sprite(TextAsset(text="Signal Is Not Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
        if self.a == 2:
            Sprite(TextAsset(text = "Time Elapsed:", width = 200, align = 'center', style = '30px Arial', fill=black),(350,250))
            Sprite(TextAsset(text= self.t, width = 200, align = 'center', style = '30px Arial', fill=black),(550,250))
            self.x = 72
            self.y = 415
            self.setImage(0)
            if self.s == 1:
                Sprite(TextAsset(text="Signal Is Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.rotation = math.pi/2
    def step(self):
        self.x -= 0

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        dishtxt = TextAsset(text="Radar Dish", width = 200, align = 'center', style = '10px Arial', fill=black)
        signaltxt = TextAsset(text="Signal (moving)", width = 200, align = 'center', style = '10px Arial', fill=red)
        #suntxt = TextAsset(text="Random Sun", width = 200, align = 'center', style = '10px Arial', fill=black)
        #planetxt = TextAsset(text="Plane (will idealy move)", width = 200, align = 'center', style = '10px Arial', fill=black)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        if foggy == 1:
            fog((200,0))
        dish((100,450))
        Sprite(dishtxt,(45,450))
        signal((72,415))
        Sprite(signaltxt,(75,375))
        plane((cpx,cpy))
        #Sprite(planetxt,(865,25))
        if rainny == 1:
            for x in range(0,31):
                rain((random.randrange(400,800),random.randrange(0,500)))
        if snowy == 1:
            for x in range(0,31):
                snow((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
        Sprite(CircleAsset(20,thinlinesun,sun),(200,100))
        #Sprite(suntxt,(170,90))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()
        for snow1 in self.getSpritesbyClass(snow):
            snow1.step()
        for plane1 in self.getSpritesbyClass(plane):
            plane1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<commit_msg>Updated from Brython Server: 1/5/2017 1:43:49 PM<commit_after>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

weather = int(input("Any weather? (1 for custom, 0 for none)"))
if weather == 1:
    rainny = int(input("Rain? (1 for rain, 0 for none)"))
    if rainny == 1:
        ar = .2
    else:
        ar = 0
    foggy = int(input("Fog? (1 for fog, 0 for none)"))
    if foggy == 1:
        af = .2
    else:
        af = 0
    snowy = int(input("Snow? (1 for snow, 0 for none)"))
    if snowy == 1:
        afs = .2
    else:
        afs = 0

else:
    rainny = 0
    ar = 0
    foggy = 0
    af = 0
    snowy = 0
    afs = 0

ss = 0-(int(input("Signal Strength (whole numbers only)")))
cpx = int(input("X Location of Plane"))
cpy = int(input("Y Location of Plane"))
#numplanes = int(input("Number of planes in air? (for future use)"))
'''

rainny = 0
foggy = 0
snowy = 0
'''

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 3
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
red9 = Color(0xff0000, 0.9)
red8 = Color(0xff0000, 0.8)
red7 = Color(0xff0000, 0.7)
red6 = Color(0xff0000, 0.6)
red5 = Color(0xff0000, 0.5)
red4 = Color(0xff0000, 0.4)
red3 = Color(0xff0000, 0.3)
red2 = Color(0xff0000, 0.2)
red1 = Color(0xff0000, 0.1)

green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
sun = Color(0xFFCC33,1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thinlinew= LineStyle(1, white)
thinlinesun = LineStyle(2, sun)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0

class snow(Sprite):
    asset = RectangleAsset(1,1,thinlinew,white)
    def __init__(self, position):
        super().__init__(snow.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0

class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    #asset = EllipseAsset(50,5,thinliner,red)
    asset = ImageAsset("images/Signalstrength-1.png", Frame(0,0,(959/29),300), 29, 'horizontal')
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.scale = .35
        #self.rotation=.55
        self.rotation = math.atan2(cpy,cpx)
        self.a = 0
        self.i = ss
        self.s = 0
        self.t = 0
        self.g = 0
    def step(self):
        if self.a != 2:
            self.t += 1
        if self.a == 0:
            self.i += .2 + afs + af + ar
            if self.i >= 0:
                self.setImage((self.i))
            else:
                self.setImage(0)
            self.x += (cpx/1000)*speed
            self.y -= (cpy/1000)*speed
            if self.x >= 900:
                self.a = 1
                if self.i >= 0:
                    self.i *= 2
                else:
                    self.i = ss - self.i
            if self.i >= 28:
                self.setImage(28)
                self.a = 2
                Sprite(TextAsset(text="Signal Is Not Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
        if self.a == 1:
            self.i += 0.2 + afs + af +ar
            if self.i >= 0:
                self.setImage((self.i))
            else:
                self.setImage(0)
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 72 and self.i <= 28:
                self.a = 2
                self.s = 1
            if self.i >= 28:
                self.setImage(28)
                self.a = 2
                Sprite(TextAsset(text="Signal Is Not Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
        if self.a == 2:
            Sprite(TextAsset(text = "Time Elapsed:", width = 200, align = 'center', style = '30px Arial', fill=black),(350,250))
            Sprite(TextAsset(text= self.t, width = 200, align = 'center', style = '30px Arial', fill=black),(550,250))
            self.x = 72
            self.y = 415
            self.setImage(0)
            if self.s == 1:
                Sprite(TextAsset(text="Signal Is Strong Enough", width = 200, align = 'center', style = '30px Arial', fill=black),(350,350))
class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.rotation = math.pi/2
    def step(self):
        self.x -= 0

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        dishtxt = TextAsset(text="Radar Dish", width = 200, align = 'center', style = '10px Arial', fill=black)
        signaltxt = TextAsset(text="Signal (moving)", width = 200, align = 'center', style = '10px Arial', fill=red)
        #suntxt = TextAsset(text="Random Sun", width = 200, align = 'center', style = '10px Arial', fill=black)
        #planetxt = TextAsset(text="Plane (will idealy move)", width = 200, align = 'center', style = '10px Arial', fill=black)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        if foggy == 1:
            fog((200,0))
        dish((100,450))
        Sprite(dishtxt,(45,450))
        signal((72,415))
        Sprite(signaltxt,(75,375))
        plane((cpx,cpy))
        #Sprite(planetxt,(865,25))
        if rainny == 1:
            for x in range(0,31):
                rain((random.randrange(400,800),random.randrange(0,500)))
        if snowy == 1:
            for x in range(0,31):
                snow((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
        Sprite(CircleAsset(20,thinlinesun,sun),(200,100))
        #Sprite(suntxt,(170,90))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()
        for snow1 in self.getSpritesbyClass(snow):
            snow1.step()
        for plane1 in self.getSpritesbyClass(plane):
            plane1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<|endoftext|>


<commit_before>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 2
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += 5
        if self.y >= 500:
            self.y = 0
class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    asset = EllipseAsset(50,5,thinliner,white)
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1
        self.a = 0
    def step(self):
        if self.a == 0:
            self.x += 3*speed
            self.y -= 1.5*speed
            if self.x >= 900:
                self.a = 1
        if self.a == 1:
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 102:
                self.a = -1

class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.vx=0
        self.rotation= math.pi/2

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        fog((100,100))
        dish((100,450))
        signal((102,450))
        plane((900,100))
        for x in range(0,41):
            rain((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<commit_msg>Updated from Brython Server: 12/19/2016 10:06:37 PM<commit_after>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 2
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += 5
        if self.y >= 500:
            self.y = 0
class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    asset = EllipseAsset(50,5,thinliner,white)
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1
        self.a = 0
    def step(self):
        if self.a == 0:
            self.x += 3*speed
            self.y -= 1.5*speed
            if self.x >= 900:
                self.a = 1
        if self.a == 1:
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 102:
                self.a = -1

class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.vx=0
        self.rotation= math.pi/2

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        fog((100,0))
        dish((100,450))
        signal((102,450))
        plane((900,100))
        for x in range(0,41):
            rain((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<|endoftext|>


<commit_before>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

weather = int(input("Any weather? (1 for custom, 0 for none)"))
if weather == 1:
    rainny = int(input("Rain? (1 for rain, 0 for no rain)"))
    foggy = int(input("Fog? (1 for fog, 0 for no fog)"))
else:
    rainny = 0
    foggy = 0

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 2
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
red9 = Color(0xff0000, 0.9)
red8 = Color(0xff0000, 0.8)
red7 = Color(0xff0000, 0.7)
red6 = Color(0xff0000, 0.6)
red5 = Color(0xff0000, 0.5)
red4 = Color(0xff0000, 0.4)
red3 = Color(0xff0000, 0.3)
red2 = Color(0xff0000, 0.2)
red1 = Color(0xff0000, 0.1)

green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0
class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    asset = EllipseAsset(50,5,thinliner,red)
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1
        self.a = 0
    def step(self):
        if self.a == 0:
            self.x += 3*speed
            self.y -= 1.5*speed
            if self.x >= 900:
                self.a = 1
        if self.a == 1:
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 102:
                self.a = 0

class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.vx=0
        self.rotation= math.pi/2

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        if foggy == 1:
            fog((200,0))
        dish((100,450))
        signal((102,450))
        plane((900,100))
        if rainny == 1:
            for x in range(0,31):
                rain((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<commit_msg>Updated from Brython Server: 12/20/2016 7:33:10 PM<commit_after>"""
MMRadar.py
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, LineAsset
from ggame import ImageAsset, PolygonAsset, Frame, Sound, SoundAsset, TextAsset
import time
import random
import math

weather = int(input("Any weather? (1 for custom, anything for none)"))
if weather == 1:
    rainny = int(input("Rain? (1 for rain, anything for no rain)"))
    foggy = int(input("Fog? (1 for fog, anything for no fog)"))
else:
    rainny = 0
    foggy = 0

SCREEN_WINDOWX = 1000
SCREEN_WINDOWY = 1000
speed = 2
precipitation = 1

# colors
red = Color(0xff0000, 1.0)
red9 = Color(0xff0000, 0.9)
red8 = Color(0xff0000, 0.8)
red7 = Color(0xff0000, 0.7)
red6 = Color(0xff0000, 0.6)
red5 = Color(0xff0000, 0.5)
red4 = Color(0xff0000, 0.4)
red3 = Color(0xff0000, 0.3)
red2 = Color(0xff0000, 0.2)
red1 = Color(0xff0000, 0.1)

green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
skyblue = Color(0x87CEEB, 1.0)
black = Color(0x000000, 1.0)
orange = Color(0xffa500, 1.0)
skin =Color(0xFCD15B, 1.0)
wall=Color(0xE8E8E8, 1.0)
orange=Color(0xFFa500,1.0)
platc=Color(0xB9BDBB,1.0)
gooy=Color(0xCDF238,1.0)
white=Color(0xFFFFFF,1.0)
fog=Color(0xFFFFFF,0.4)
darkblue=Color(0x052099,1.0)

# lines
thinline= LineStyle(1, black)
thinliner= LineStyle(1, red)
thinlinesb=LineStyle(1, skyblue)
thinlinedb=LineStyle(1, darkblue)
thinlinewa=LineStyle(1, wall)
thin1line=LineStyle(2,black)
thickline= LineStyle(5, black)
thickliner= LineStyle(5, red)
thicklineb= LineStyle(5, blue)
thickishline= LineStyle(2.5, black)
noline= LineStyle(0, black)
portalline= LineStyle(1, blue)
portalline2= LineStyle(1, orange)

class dish(Sprite):
    asset = EllipseAsset(50,5,thin1line,white)
    def __init__(self, position):
        super().__init__(dish.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1

class rain(Sprite):
    asset = RectangleAsset(1,1,thinlinedb,darkblue)
    def __init__(self, position):
        super().__init__(rain.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=0
    def step(self):
        if self.y <= 500:
            self.y += random.randrange(2,7)
        if self.y >= 500:
            self.y = 0
class fog(Sprite):
    asset = RectangleAsset(500,500,thinlinewa,wall)
    def __init__(self, position):
        super().__init__(fog.asset, position)
        self.vx=0
        self.vy=0

class signal(Sprite):
    asset = EllipseAsset(50,5,thinliner,red)
    def __init__(self, position):
        super().__init__(signal.asset, position)
        self.vx=0
        self.vy=0
        self.rotation=-1
        self.a = 0
    def step(self):
        if self.a == 0:
            self.x += 3*speed
            self.y -= 1.5*speed
            if self.x >= 900:
                self.a = 1
        if self.a == 1:
            self.x -= 3*speed
            self.y += 1.5*speed
            if self.x <= 102:
                self.a = 0

class plane(Sprite):
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(plane.asset, position)
        self.vx=0
        self.rotation= math.pi/2

class radar(App):
    asset = ImageAsset("images/spritesforathletes.jpg", Frame(0,0,55,50), 8, 'horizontal')
    def __init__(self, width, height):
        super().__init__(width, height)
        Sprite(RectangleAsset(1000,500,thinlinesb,skyblue),(0,0))
        if foggy == 1:
            fog((200,0))
        dish((100,450))
        signal((102,450))
        plane((900,100))
        if rainny == 1:
            for x in range(0,31):
                rain((random.randrange(400,800),random.randrange(0,500)))
        Sprite(LineAsset(1000,1,thinline),(0,500))
    def step(self):
        for sig in self.getSpritesbyClass(signal):
            sig.step()
        for rain1 in self.getSpritesbyClass(rain):
            rain1.step()

myapp = radar(SCREEN_WINDOWX,SCREEN_WINDOWY)
myapp.run()
<|endoftext|>


<commit_before>import logging
import logging.config
import os
import re
import sys

from mtp_transaction_uploader import settings
from mtp_transaction_uploader.upload import main as transaction_uploader

def setup_monitoring():
    """
    Setup logging and exception reporting
    """
    logging_conf = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'simple': {
                'format': '%(asctime)s [%(levelname)s] %(message)s',
                'datefmt': '%Y-%m-%dT%H:%M:%S',
            },
            'elk': {
                '()': 'mtp_utils.logging.ELKFormatter'
            }
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple' if settings.ENV == 'local' else 'elk',
            },
        },
        'root': {
            'level': 'WARNING',
            'handlers': ['console'],
        },
        'loggers': {
            'mtp': {
                'level': 'INFO',
                'handlers': ['console'],
                'propagate': False,
            },
        },
    }
    sentry = None
    if os.environ.get('SENTRY_DSN'):
        from raven import Client

        sentry = Client(
            dsn=os.environ['SENTRY_DSN'],
            release=os.environ.get('APP_GIT_COMMIT', 'unknown'),
        )
        logging_conf['handlers']['sentry'] = {
            'level': 'ERROR',
            'class': 'raven.handlers.logging.SentryHandler',
            'client': sentry,
        }
        logging_conf['root']['handlers'].append('sentry')
        logging_conf['loggers']['mtp']['handlers'].append('sentry')
    logging.config.dictConfig(logging_conf)
    logger = logging.getLogger('mtp')

    return logger, sentry

def main():
    logger, sentry = setup_monitoring()

    if settings.UPLOADER_DISABLED:
        logger.info('Transaction uploader is disabled')
        sys.exit(0)

    # ensure all required parameters are set
    re_env_name = re.compile(r'^[A-Z_]+$')
    missing_params = []
    for param in dir(settings):
        if not re_env_name.match(param):
            continue
        if not getattr(settings, param):
            missing_params.append(param)
    if missing_params:
        logger.error('Missing environment variables: ' +
                     ', '.join(missing_params))
        sys.exit(1)

    try:
        # run the transaction uploader
        transaction_uploader()
    except:
        if sentry:
            sentry.captureException()
        else:
            logger.exception('Unhandled error')
        sys.exit(2)

if __name__ == '__main__':
    main()
<commit_msg>Require only vital settings to be set in the environment<commit_after>import logging
import logging.config
import os
import sys

from mtp_transaction_uploader import settings
from mtp_transaction_uploader.upload import main as transaction_uploader

def setup_monitoring():
    """
    Setup logging and exception reporting
    """
    logging_conf = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'simple': {
                'format': '%(asctime)s [%(levelname)s] %(message)s',
                'datefmt': '%Y-%m-%dT%H:%M:%S',
            },
            'elk': {
                '()': 'mtp_utils.logging.ELKFormatter'
            }
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple' if settings.ENV == 'local' else 'elk',
            },
        },
        'root': {
            'level': 'WARNING',
            'handlers': ['console'],
        },
        'loggers': {
            'mtp': {
                'level': 'INFO',
                'handlers': ['console'],
                'propagate': False,
            },
        },
    }
    sentry = None
    if os.environ.get('SENTRY_DSN'):
        from raven import Client

        sentry = Client(
            dsn=os.environ['SENTRY_DSN'],
            release=os.environ.get('APP_GIT_COMMIT', 'unknown'),
        )
        logging_conf['handlers']['sentry'] = {
            'level': 'ERROR',
            'class': 'raven.handlers.logging.SentryHandler',
            'client': sentry,
        }
        logging_conf['root']['handlers'].append('sentry')
        logging_conf['loggers']['mtp']['handlers'].append('sentry')
    logging.config.dictConfig(logging_conf)
    logger = logging.getLogger('mtp')

    return logger, sentry

def main():
    logger, sentry = setup_monitoring()

    if settings.UPLOADER_DISABLED:
        logger.info('Transaction uploader is disabled')
        sys.exit(0)

    # ensure all required parameters are set
    missing_params = []
    required_params = {'SFTP_HOST', 'SFTP_USER', 'SFTP_PRIVATE_KEY', 'ACCOUNT_CODE',
                       'API_URL', 'API_CLIENT_ID', 'API_CLIENT_SECRET',
                       'API_USERNAME', 'API_PASSWORD'}
    for param in dir(settings):
        if param in required_params and not getattr(settings, param):
            missing_params.append(param)
    if missing_params:
        logger.error('Missing environment variables: ' +
                     ', '.join(missing_params))
        sys.exit(1)

    try:
        # run the transaction uploader
        transaction_uploader()
    except:
        if sentry:
            sentry.captureException()
        else:
            logger.exception('Unhandled error')
        sys.exit(2)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>"""MoodJournal URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView

from rest_framework_jwt.views import refresh_jwt_token

from .AuthCust import views as auth_cust_views

urlpatterns = [
    url(r'^api/', include('entries.urls')),
    url(r'^admin/', admin.site.urls),

    url(r'^rest-auth/registration/resend-verification-email/$',
        auth_cust_views.resend_verification_email,
        name='resend-verification-email'),
    # per https://github.com/Tivix/django-rest-auth/issues/292
    url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        auth_cust_views.null_view,
        name='password_reset_confirm'),

    url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
    url(r'^refresh-token/', refresh_jwt_token),
    url('^$', TemplateView.as_view(template_name="index.html")),
]

urlpatterns += [
    url(r'^api-auth/', include('rest_framework.urls',
                               namespace='rest_framework')),
]<commit_msg>linking up password reset html page<commit_after>"""MoodJournal URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView

from rest_framework_jwt.views import refresh_jwt_token

from .AuthCust import views as auth_cust_views

urlpatterns = [
    url(r'^api/', include('entries.urls')),
    url(r'^admin/', admin.site.urls),

    url(r'^rest-auth/registration/resend-verification-email/$',
        auth_cust_views.resend_verification_email,
        name='resend-verification-email'),
    # per https://github.com/Tivix/django-rest-auth/issues/292
    url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        TemplateView.as_view(template_name="passwordreset.html"),
        name='password_reset_confirm'),

    url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
    url(r'^refresh-token/', refresh_jwt_token),
    url('^$', TemplateView.as_view(template_name="index.html")),
]

urlpatterns += [
    url(r'^api-auth/', include('rest_framework.urls',
                               namespace='rest_framework')),
]<|endoftext|>


<commit_before>#
# Interactively decide what to distribute
#
#
# The exclude file signals files to always exclude,
# The pattern file lines are of the form
# *.c
# This excludes all files ending in .c.
#
# The include file signals files and directories to include.
# Records are of the form
# ('Tools:bgen:AE:AppleEvents.py', 'Lib:MacToolbox:AppleEvents.py')
# This includes the specified file, putting it in the given place, or
# ('Tools:bgen:AE:AppleEvents.py', None)
# This excludes the specified file.
#
from MkDistr_ui import *
import fnmatch
import regex
import os
import sys
import macfs
import macostools

SyntaxError='Include/exclude file syntax error'

class Matcher:
	"""Include/exclude database, common code"""

	def __init__(self, filename):
		self.filename = filename
		self.rawdata = []
		self.parse(filename)
		self.rawdata.sort()
		self.rebuild()
		self.modified = 0

	def parse(self, dbfile):
		try:
			fp = open(dbfile)
		except IOError:
			return
		data = fp.readlines()
		fp.close()
		for d in data:
			d = d[:-1]
			if not d or d[0] == '#': continue
			pat = self.parseline(d)
			self.rawdata.append(pat)

	def save(self):
		fp = open(self.filename, 'w')
		self.savedata(fp, self.rawdata)
		self.modified = 0

	def add(self, value):
		if len(value) == 1:
			value = value + ('',)
		self.rawdata.append(value)
		self.rebuild1(value)
		self.modified = 1

	def delete(self, value):
		key = value
		for i in range(len(self.rawdata)):
			if self.rawdata[i][0] == key:
				del self.rawdata[i]
				self.unrebuild1(i, key)
				self.modified = 1
				return
		print 'Not found!', key

	def getall(self):
		return map(lambda x: x[0], self.rawdata)

	def get(self, value):
		for src, dst in self.rawdata:
			if src == value:
				return src, dst
		print 'Not found!', value

	def is_modified(self):
		return self.modified

class IncMatcher(Matcher):
	"""Include filename database and matching engine"""

	def rebuild(self):
		self.idict = {}
		self.edict = {}
		for v in self.rawdata:
			self.rebuild1(v)

	def parseline(self, line):
		try:
			data = eval(line)
		except:
			raise SyntaxError, line
		if type(data) <> type(()) or len(data) not in (1,2):
			raise SyntaxError, line
		if len(data) == 1:
			data = data + ('',)
		return data

	def savedata(self, fp, data):
		for d in self.rawdata:
			fp.write(`d`+'\n')

	def rebuild1(self, (src, dst)):
		if dst == '':
			dst = src
		if dst == None:
			self.edict[src] = None
		else:
			self.idict[src] = dst

	def unrebuild1(self, num, src):
		if self.idict.has_key(src):
			del self.idict[src]
		else:
			del self.edict[src]

	def match(self, patharg):
		removed = []
		# First check the include directory
		path = patharg
		while 1:
			if self.idict.has_key(path):
				# We know of this path (or initial piece of path)
				dstpath = self.idict[path]
				# We do want it distributed. Tack on the tail.
				while removed:
					dstpath = os.path.join(dstpath, removed[0])
					removed = removed[1:]
				# Finally, if the resultant string ends in a separator
				# tack on our input filename
				if dstpath[-1] == os.sep:
					dir, file = os.path.split(path)
					dstpath = os.path.join(dstpath, file)
				return dstpath
			path, lastcomp = os.path.split(path)
			if not path:
				break
			removed[0:0] = [lastcomp]
		# Next check the exclude directory
		path = patharg
		while 1:
			if self.edict.has_key(path):
				return ''
			path, lastcomp = os.path.split(path)
			if not path:
				break
			removed[0:0] = [lastcomp]
		return None

	def checksourcetree(self):
		rv = []
		for name in self.idict.keys():
			if not os.path.exists(name):
				rv.append(name)
		return rv

class ExcMatcher(Matcher):
	"""Exclude pattern database and matching engine"""

	def rebuild(self):
		self.relist = []
		for v in self.rawdata:
			self.rebuild1(v)

	def parseline(self, data):
		return (data, None)

	def savedata(self, fp, data):
		for d in self.rawdata:
			fp.write(d[0]+'\n')

	def rebuild1(self, (src, dst)):
		pat = fnmatch.translate(src)
		self.relist.append(regex.compile(pat))

	def unrebuild1(self, num, src):
		del self.relist[num]

	def match(self, path):
		comps = os.path.split(path)
		file = comps[-1]
		for pat in self.relist:
			if pat and pat.match(file) == len(file):
				return 1
		return 0

class Main:
	"""The main program glueing it all together"""

	def __init__(self):
		InitUI()
		fss, ok = macfs.GetDirectory('Source directory:')
		if not ok:
			sys.exit(0)
		os.chdir(fss.as_pathname())
		if not os.path.isdir(':Mac:Distributions'):
			os.mkdir(':Mac:Distributions')
		typedist = GetType()
		self.inc = IncMatcher(':Mac:Distributions:%s.include'%typedist)
		self.exc = ExcMatcher(':Mac:Distributions:%s.exclude'%typedist)
		self.ui = MkDistrUI(self)
		self.ui.mainloop()

	def check(self):
		return self.checkdir(':', 1)

	def checkdir(self, path, istop):
		files = os.listdir(path)
		rv = []
		todo = []
		for f in files:
			if self.exc.match(f):
				continue
			fullname = os.path.join(path, f)
			if self.inc.match(fullname) == None:
				if os.path.isdir(fullname):
					todo.append(fullname)
				else:
					rv.append(fullname)
		for d in todo:
			if len(rv) > 500:
				if istop:
					rv.append('... and more ...')
				return rv
			rv = rv + self.checkdir(d, 0)
		return rv

	def run(self, destprefix):
		missing = self.inc.checksourcetree()
		if missing:
			print '==== Missing source files ===='
			for i in missing:
				print i
			print '==== Fix and retry ===='
			return
		if not self.rundir(':', destprefix, 0):
			return
		self.rundir(':', destprefix, 1)

	def rundir(self, path, destprefix, doit):
		files = os.listdir(path)
		todo = []
		rv = 1
		for f in files:
			if self.exc.match(f):
				continue
			fullname = os.path.join(path, f)
			if os.path.isdir(fullname):
				todo.append(fullname)
			else:
				dest = self.inc.match(fullname)
				if dest == None:
					print 'Not yet resolved:', fullname
					rv = 0
				if dest:
					if doit:
						print 'COPY ', fullname
						print '  -> ', os.path.join(destprefix, dest)
						macostools.copy(fullname, os.path.join(destprefix, dest), 1)
		for d in todo:
			if not self.rundir(d, destprefix, doit):
				rv = 0
		return rv

	def save(self):
		self.inc.save()
		self.exc.save()

	def is_modified(self):
		return self.inc.is_modified() or self.exc.is_modified()

if __name__ == '__main__':
	Main()

<commit_msg>Added some debug prints (if enabled by setting DEBUG)<commit_after>#
# Interactively decide what to distribute
#
#
# The exclude file signals files to always exclude,
# The pattern file lines are of the form
# *.c
# This excludes all files ending in .c.
#
# The include file signals files and directories to include.
# Records are of the form
# ('Tools:bgen:AE:AppleEvents.py', 'Lib:MacToolbox:AppleEvents.py')
# This includes the specified file, putting it in the given place, or
# ('Tools:bgen:AE:AppleEvents.py', None)
# This excludes the specified file.
#
from MkDistr_ui import *
import fnmatch
import regex
import os
import sys
import macfs
import macostools

DEBUG=0

SyntaxError='Include/exclude file syntax error'

class Matcher:
	"""Include/exclude database, common code"""

	def __init__(self, filename):
		self.filename = filename
		self.rawdata = []
		self.parse(filename)
		self.rawdata.sort()
		self.rebuild()
		self.modified = 0

	def parse(self, dbfile):
		try:
			fp = open(dbfile)
		except IOError:
			return
		data = fp.readlines()
		fp.close()
		for d in data:
			d = d[:-1]
			if not d or d[0] == '#': continue
			pat = self.parseline(d)
			self.rawdata.append(pat)

	def save(self):
		fp = open(self.filename, 'w')
		self.savedata(fp, self.rawdata)
		self.modified = 0

	def add(self, value):
		if len(value) == 1:
			value = value + ('',)
		self.rawdata.append(value)
		self.rebuild1(value)
		self.modified = 1

	def delete(self, value):
		key = value
		for i in range(len(self.rawdata)):
			if self.rawdata[i][0] == key:
				del self.rawdata[i]
				self.unrebuild1(i, key)
				self.modified = 1
				return
		print 'Not found!', key

	def getall(self):
		return map(lambda x: x[0], self.rawdata)

	def get(self, value):
		for src, dst in self.rawdata:
			if src == value:
				return src, dst
		print 'Not found!', value

	def is_modified(self):
		return self.modified

class IncMatcher(Matcher):
	"""Include filename database and matching engine"""

	def rebuild(self):
		self.idict = {}
		self.edict = {}
		for v in self.rawdata:
			self.rebuild1(v)

	def parseline(self, line):
		try:
			data = eval(line)
		except:
			raise SyntaxError, line
		if type(data) <> type(()) or len(data) not in (1,2):
			raise SyntaxError, line
		if len(data) == 1:
			data = data + ('',)
		return data

	def savedata(self, fp, data):
		for d in self.rawdata:
			fp.write(`d`+'\n')

	def rebuild1(self, (src, dst)):
		if dst == '':
			dst = src
		if dst == None:
			self.edict[src] = None
		else:
			self.idict[src] = dst

	def unrebuild1(self, num, src):
		if self.idict.has_key(src):
			del self.idict[src]
		else:
			del self.edict[src]

	def match(self, patharg):
		removed = []
		# First check the include directory
		path = patharg
		while 1:
			if self.idict.has_key(path):
				# We know of this path (or initial piece of path)
				dstpath = self.idict[path]
				# We do want it distributed. Tack on the tail.
				while removed:
					dstpath = os.path.join(dstpath, removed[0])
					removed = removed[1:]
				# Finally, if the resultant string ends in a separator
				# tack on our input filename
				if dstpath[-1] == os.sep:
					dir, file = os.path.split(path)
					dstpath = os.path.join(dstpath, file)
				if DEBUG:
					print 'include', patharg, dstpath
				return dstpath
			path, lastcomp = os.path.split(path)
			if not path:
				break
			removed[0:0] = [lastcomp]
		# Next check the exclude directory
		path = patharg
		while 1:
			if self.edict.has_key(path):
				if DEBUG:
					print 'exclude', patharg, path
				return ''
			path, lastcomp = os.path.split(path)
			if not path:
				break
			removed[0:0] = [lastcomp]
		if DEBUG:
			print 'nomatch', patharg
		return None

	def checksourcetree(self):
		rv = []
		for name in self.idict.keys():
			if not os.path.exists(name):
				rv.append(name)
		return rv

class ExcMatcher(Matcher):
	"""Exclude pattern database and matching engine"""

	def rebuild(self):
		self.relist = []
		for v in self.rawdata:
			self.rebuild1(v)

	def parseline(self, data):
		return (data, None)

	def savedata(self, fp, data):
		for d in self.rawdata:
			fp.write(d[0]+'\n')

	def rebuild1(self, (src, dst)):
		pat = fnmatch.translate(src)
		if DEBUG:
			print 'PATTERN', `src`, 'REGEX', `pat`
		self.relist.append(regex.compile(pat))

	def unrebuild1(self, num, src):
		del self.relist[num]

	def match(self, path):
		comps = os.path.split(path)
		file = comps[-1]
		for pat in self.relist:
			if pat and pat.match(file) == len(file):
				if DEBUG:
					print 'excmatch', file, pat
				return 1
		return 0

class Main:
	"""The main program glueing it all together"""

	def __init__(self):
		InitUI()
		fss, ok = macfs.GetDirectory('Source directory:')
		if not ok:
			sys.exit(0)
		os.chdir(fss.as_pathname())
		if not os.path.isdir(':Mac:Distributions'):
			os.mkdir(':Mac:Distributions')
		typedist = GetType()
		self.inc = IncMatcher(':Mac:Distributions:%s.include'%typedist)
		self.exc = ExcMatcher(':Mac:Distributions:%s.exclude'%typedist)
		self.ui = MkDistrUI(self)
		self.ui.mainloop()

	def check(self):
		return self.checkdir(':', 1)

	def checkdir(self, path, istop):
		if DEBUG:
			print 'checkdir', path
		files = os.listdir(path)
		rv = []
		todo = []
		for f in files:
			if DEBUG:
				print 'checkfile', f
			if self.exc.match(f):
				if DEBUG:
					print 'exclude match', f
				continue
			fullname = os.path.join(path, f)
			if DEBUG:
				print 'checkpath', fullname
			matchvalue = self.inc.match(fullname)
			if matchvalue == None:
				if os.path.isdir(fullname):
					if DEBUG:
						print 'do dir', fullname
					todo.append(fullname)
				else:
					if DEBUG:
						print 'include', fullname
					rv.append(fullname)
			elif DEBUG:
				print 'badmatch', matchvalue
		for d in todo:
			if len(rv) > 500:
				if istop:
					rv.append('... and more ...')
				return rv
			rv = rv + self.checkdir(d, 0)
		return rv

	def run(self, destprefix):
		missing = self.inc.checksourcetree()
		if missing:
			print '==== Missing source files ===='
			for i in missing:
				print i
			print '==== Fix and retry ===='
			return
		if not self.rundir(':', destprefix, 0):
			return
		self.rundir(':', destprefix, 1)

	def rundir(self, path, destprefix, doit):
		files = os.listdir(path)
		todo = []
		rv = 1
		for f in files:
			if self.exc.match(f):
				continue
			fullname = os.path.join(path, f)
			if os.path.isdir(fullname):
				todo.append(fullname)
			else:
				dest = self.inc.match(fullname)
				if dest == None:
					print 'Not yet resolved:', fullname
					rv = 0
				if dest:
					if doit:
						print 'COPY ', fullname
						print '  -> ', os.path.join(destprefix, dest)
						try:
							macostools.copy(fullname, os.path.join(destprefix, dest), 1)
						except: #DBG
							print 'cwd', os.path.getcwd() #DBG
							print 'fsspec', macfs.FSSpec(fullname) #DBG
							sys.exit(1)
		for d in todo:
			if not self.rundir(d, destprefix, doit):
				rv = 0
		return rv

	def save(self):
		self.inc.save()
		self.exc.save()

	def is_modified(self):
		return self.inc.is_modified() or self.exc.is_modified()

if __name__ == '__main__':
	Main()

<|endoftext|>


<commit_before>import logging, os, praw, re, time, traceback, sys, urllib2;

linked = [];
linkedsrc = [];
skipped = [];
skippedsrc = [];

ARCHIVE_TIME = 15778463; # currently 6 months (in seconds)
CJ_HEADER = u"""This dank meme has been linked to from another place on le reddit.""";
HEADER = u"""This thread has been linked to from another place on reddit.""";
FOOTER = u"""[](#footer)*^If ^you ^follow ^any ^of ^the ^above ^links, ^respect ^the ^rules ^of ^reddit ^and ^don't ^vote. ^\([Info](/r/TotesMessenger/wiki/) ^/ ^[Contact](/message/compose/?to=\/r\/TotesMessenger))* [](#bot)""";

user = os.environ['REDDIT_USER'];
blacklist = ["anime", "asianamerican", "askhistorians", "askscience", "aww", "benfrick", "bmw", "chicagosuburbs",
             "cosplay", "cumberbitches", "d3gf", "deer", "depression", "depthhub", "drinkingdollars",
             "forwardsfromgrandma", "futurology", "geckos", "giraffes", "graphical_design", "grindsmygears",
             "indianfetish", "misc", "mixedbreeds", "news", "newtotf2", "omaha", "petstacking", "pigs",
             "politicaldiscussion", "programmingcirclejerk", "raerthdev", "rants", "salvia", "science",
             "seiko", "shoplifting", "sketches", "sociopath", "suicidewatch", "talesfromtechsupport", "unitedkingdom"];
# Do not edit

srcblacklist = ["depression", "lifeafternarcissists", "managedbynarcissists", "moderationlog", "raisedbynarcissists",
                "rbnathome", "rbnbookclub", "rbnchildcare", "rbnfavors", "rbngames", "rbnlifeskills", "rbnmovienight",
                "rbnrelationships", "rbnspouses", "suicidewatch", "switcharoo", "switcheroo", "trolledbynarcissists",
                "unremovable", "politic", "mlplite", "risingthreads", "uncensorship", "leagueofriot", "benlargefanclub",
                "fitnesscirclejerk", "taiwancirclejerk"];

banned = ["reddit.com", "minecraft", "adviceanimals", "askreddit", "worldnews", "femradebates", "pcmasterrace",
          "purplepilldebate", "slrep", "funny", "theredpill", "personalfinance", "india", "lifehacks", "kotakuinaction",
          "askmen", "smashbros", "android", "neutralpolitics", "dota2", "wet_shavers", "dogecoin", "askphilosophy",
          "suits", "japanlife", "photography", "hiphopheads", "apple", "lifeprotips", "nba"];

blockedusers = ["amprobablypooping", "evilrising", "frontpagewatch", "frontpagewatchmirror", "moon-done", "politicbot",
                "rising_threads_bot", "removal_rover", "drugtaker", "knowyourshit"];

# metabots = [user, "totesmessenger", "totes_meta_bot", "meta_bot", "meta_bot2", "originallinkbot"];

# Ban list:
# drugtaker - Meta bot NSFW marking evasion

nsfwreddits = ["srsshillwatch", "srsshillswatch", "srshillswatch", "srshillwatch", "gonewild"];

test_reddits = ["justcool393", "tmtest", "totesmessenger"];

def main():
    global linked;
    global linkedsrc;
    global skipped;
    global skippedsrc;
    create_files();

    linked = load_list("linked.lst");
    linkedsrc = load_list("linkedsrc.lst");
    skipped = load_list("skipped.lst");
    skippedsrc = load_list("skippedsrc.lst");

    r = praw.Reddit("Links to reddit posts from other places in reddit", domain="api.reddit.com", log_requests=0);
    r.login(user, os.environ['REDDIT_PASS']);
    logging.info("Logged in to reddit...");

    check_at = 3600;
    last_logged = 0;
    times_zero = 1;

    count = link_subs(r, 100, 120); # Check the last 100 posts on startup
    while True:
        if time.time() >= (last_logged + check_at):
            last_logged = time.time();
            save_list("linked.lst", linked);
            save_list("linkedsrc.lst", linkedsrc);
            save_list("skipped.lst", skipped);
            save_list("skippedsrc.lst", skippedsrc);
            if count == 0:
                times_zero += 1;
            else:
                logging.info("Linked " + str(count) + " in the last " + str((check_at * times_zero) / 60 / 60) + " hour(s)");
                count = 0;
                times_zero = 1;
        count += link_subs(r, 25, 60);

def create_files():
    f = open("linked.lst", "a");
    f.close();
    f = open("linkedsrc.lst", "a");
    f.close();
    f = open("skipped.lst", "a");
    f.close();
    f = open("skippedsrc.lst", "a");
    f.close();

def link_subs(r, count, delay):
    linked_count = 0;
    for submission in r.get_domain_listing('reddit.com', sort='new', limit=count):

        #if submission.subreddit.display_name.lower() not in test_reddits:  # For testing things
        #    continue;

        try:
            if link_submission(r, submission):
                linked_count += 1;
        except Exception:
            logging.error(exi());
        time.sleep(3);

    time.sleep(delay);
    return linked_count;

def link_submission(r, submission):
    url = submission.url;
    if not is_comment(url):
        return;
    linkedp = None;
    try:
        linkedp = get_object(r, url);
    except praw.errors.ClientException as e:
        logging.error("Link is not a reddit post (id: " + submission.id + ")");
        logging.error(exi());
        return;
    except Exception:
        logging.error("Could not get comment!");
        logging.error(exi());

    if linkedp is None:
        return;

    lid = linkedp.id;
    sid = submission.id;

    # Skip conditions: Already deleted, undelete/scraper/mod log bots, blacklisted, banned/archived,
    # archived, in source blacklist

    if linkedp is None or linkedp.subreddit is None:
        skipped.append(lid);
        return False;

    srlower = linkedp.subreddit.display_name.lower();

    if linkedp.author is None or srlower in blacklist or srlower in banned or linkedp.created < (time.time() - ARCHIVE_TIME):
        skipped.append(lid);
        return False;

    if submission.subreddit.display_name.lower() in srcblacklist or submission.author.name is None:
        skippedsrc.append(sid);
        return False;

    if submission.author.name.lower() in blockedusers:
        skippedsrc.append(sid);

    if lid in skipped or sid in skippedsrc:
        return False;

    if sid in linkedsrc:
        return False;

    if lid in linked or check_commmented(linkedp):
        success = edit_post(get_bot_comment(linkedp), submission);
        if success:
            linkedsrc.append(sid);
        linked.append(lid);
        return success;

    if check_commmented(linkedp):
        linked.append(lid);
        linkedsrc.append(sid);
        return False;

    if isinstance(linkedp, praw.objects.Comment):
        linked.append(lid);
        linkedsrc.append(sid);
        comment(linkedp, submission, srlower == "circlejerk");
    elif isinstance(linkedp, praw.objects.Submission):
        post(linkedp, submission, srlower == "circlejerk");
    else:
        logging.error("Not a Comment or Submission! (ID: " + id + ")");
        return False;

    linked.append(lid);
    linkedsrc.append(sid);
    return True;

def edit_post(totessubmission, original):
    if totessubmission is None:
        return False;
    text = re.sub("\[\]\(#footer\).{1,}", "", totessubmission.body); # sub. invisible link for easier footer changes
    text = re.sub("\*\^If.{1,}", "", text);
    text = re.sub("\^Please.{1,}", "", text); # substitute old footer as well
    text = re.sub("Do not vote.{1,}", "", text); # substitute original footer as well
    text = text + format_link(original) + u"""

""" + FOOTER;
    totessubmission.edit(text);
    return True;

def get_comment(r, s):
    return get_linked(r, s).comments[0];

def get_linked(r, link):
    return r.get_submission(link);

def check_commmented(c):
    if isinstance(c, praw.objects.Comment):
        comments = c.replies;
    elif isinstance(c, praw.objects.Submission):
        c.replace_more_comments(limit=None, threshold=0);
        comments = praw.helpers.flatten_tree(c.comments);

    for co in comments:
        if co.author is None:
            continue;
        if co.author.name.lower() == user.lower():
            return True;
    return False;

def get_bot_comment(s):
    if isinstance(s, praw.objects.Comment):
        for c in s.replies:
            if c.author is None:
                continue;
            if c.author.name.lower() == user.lower():
                return c;
    else:
        s.replace_more_comments(limit=None, threshold=0);
        flat_comments = praw.helpers.flatten_tree(s.comments);
        for c in flat_comments:
            if c.author is None:
                continue;
            if c.author.name.lower() == user.lower():
                return c;
    return None;

def format_comment(original, isrcirclejerk):
    if isrcirclejerk:
        cmt = CJ_HEADER;
    else:
        cmt = HEADER;
    cmt = cmt + u"""

{link}

""" + FOOTER;

    return cmt.format(link=format_link(original));

def post(s, original, isrcirclejerk):
    try:
        s.add_comment(format_comment(original, isrcirclejerk));
    except praw.errors.RateLimitExceeded:
        logging.debug("Can't comment (comment karma is too low)");
    except praw.errors.APIException as e:
        logging.warning(str(e));
    except Exception:
        logging.error("Error adding comment (SID: " + str(s.id) + ")");
        logging.error(exi());

def comment(c, original, isrcirclejerk):
    try:
        c.reply(format_comment(original, isrcirclejerk));
    except praw.errors.RateLimitExceeded:
        logging.debug("Can't comment (comment karma is too low)");
    except praw.errors.APIException as e:
        logging.warning(str(e));
    except Exception:
        logging.error("Error adding comment (CID: " + str(c.id) + ")");
        logging.error(str(e));

def format_link(post):
    srurl = post.subreddit.url;
    nsfw = post.subreddit.name.lower() in nsfwreddits or post.subreddit.over18 or post.over_18;
    text = u"- [" + srurl[:-1] + "] ";
    if nsfw:
        text = text + u"[NSFW] ";
    return text + u"[" + post.title + "](" + np(post.permalink) + ")\n";

def changesubdomain(link, sub):
    l = re.sub(r"http[s]?://[a-z]{0,3}\.?reddit\.com", "", link);
    return "http://" + sub + ".reddit.com" + l;

def unnp(link):
    return changesubdomain(link, "www");

def np(link):
    return changesubdomain(link, "np");

def get_cid(url):
    l = re.sub(r"http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.{6,8}/.*/", "", url);
    l = re.sub(r"\?.*", "", l);
    l = re.sub(r"\..*", "", l);
    return "t1_" + l;

def get_object(r, url):
    obj = praw.objects.Submission.from_url(r, unnp(url));
    a = re.compile("http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.{6,8}/.*/.{6,8}");

    if a.match(url):
        url = unnp(url);
        o = r.get_info(thing_id=get_cid(url));
        if o is None:
            raise Exception("Comment is none! (URL: " + url + ")");

        return o;
    else:
        return obj;

def is_comment(link):
    a = re.compile("http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.*");
    return a.match(link);

def load_list(file):
    f = open(file, "r");
    data = f.read();
    f.close();
    return data.split();

def save_list(file, list):
    f = open(file, "wb");
    str = "";
    for s in list:
        str = str + s + " ";
    f.write(str);
    f.close();

def log_crash():
    logging.error("Error occurred in the bot; restarting in 15 seconds...");
    logging.error("Details: ");
    logging.error(exi());
    time.sleep(15);
    sys.exit(1);

def exi():
    return traceback.format_exc();

def setup_logging():
    root = logging.getLogger();
    root.setLevel(logging.INFO);
    logging.getLogger("requests").setLevel(logging.WARNING);
    ch = logging.StreamHandler(sys.stdout);
    ch.setLevel(logging.INFO);

    root.addHandler(ch);

try:
    setup_logging();
    main();
except (AttributeError, NameError, SyntaxError, TypeError) as e:
    logging.error(exi());
    time.sleep(86400);  # Sleep for 1 day so we don't restart.
except Exception:
    log_crash();<commit_msg>Save in a different manner and fix /u/Know_Your_Shit's blacklist<commit_after>import logging, os, praw, re, time, traceback, sys, urllib2;

linked = [];
linkedsrc = [];
skipped = [];
skippedsrc = [];

ARCHIVE_TIME = 15778463; # currently 6 months (in seconds)
CJ_HEADER = u"""This dank meme has been linked to from another place on le reddit.""";
HEADER = u"""This thread has been linked to from another place on reddit.""";
FOOTER = u"""[](#footer)*^If ^you ^follow ^any ^of ^the ^above ^links, ^respect ^the ^rules ^of ^reddit ^and ^don't ^vote. ^\([Info](/r/TotesMessenger/wiki/) ^/ ^[Contact](/message/compose/?to=\/r\/TotesMessenger))* [](#bot)""";

user = os.environ['REDDIT_USER'];
blacklist = ["anime", "asianamerican", "askhistorians", "askscience", "aww", "benfrick", "bmw", "chicagosuburbs",
             "cosplay", "cumberbitches", "d3gf", "deer", "depression", "depthhub", "drinkingdollars",
             "forwardsfromgrandma", "futurology", "geckos", "giraffes", "graphical_design", "grindsmygears",
             "indianfetish", "misc", "mixedbreeds", "news", "newtotf2", "omaha", "petstacking", "pigs",
             "politicaldiscussion", "programmingcirclejerk", "raerthdev", "rants", "salvia", "science",
             "seiko", "shoplifting", "sketches", "sociopath", "suicidewatch", "talesfromtechsupport", "unitedkingdom"];
# Do not edit

srcblacklist = ["depression", "lifeafternarcissists", "managedbynarcissists", "moderationlog", "raisedbynarcissists",
                "rbnathome", "rbnbookclub", "rbnchildcare", "rbnfavors", "rbngames", "rbnlifeskills", "rbnmovienight",
                "rbnrelationships", "rbnspouses", "suicidewatch", "switcharoo", "switcheroo", "trolledbynarcissists",
                "unremovable", "politic", "mlplite", "risingthreads", "uncensorship", "leagueofriot", "benlargefanclub",
                "fitnesscirclejerk", "taiwancirclejerk"];

banned = ["reddit.com", "minecraft", "adviceanimals", "askreddit", "worldnews", "femradebates", "pcmasterrace",
          "purplepilldebate", "slrep", "funny", "theredpill", "personalfinance", "india", "lifehacks", "kotakuinaction",
          "askmen", "smashbros", "android", "neutralpolitics", "dota2", "wet_shavers", "dogecoin", "askphilosophy",
          "suits", "japanlife", "photography", "hiphopheads", "apple", "lifeprotips", "nba"];

blockedusers = ["amprobablypooping", "evilrising", "frontpagewatch", "frontpagewatchmirror", "moon-done", "politicbot",
                "rising_threads_bot", "removal_rover", "drugtaker", "know_your_shit"];

# metabots = [user, "totesmessenger", "totes_meta_bot", "meta_bot", "meta_bot2", "originallinkbot"];

# Ban list:
# drugtaker - Meta bot NSFW marking evasion

nsfwreddits = ["srsshillwatch", "srsshillswatch", "srshillswatch", "srshillwatch", "gonewild"];

test_reddits = ["justcool393", "tmtest", "totesmessenger"];

def main():
    global linked;
    global linkedsrc;
    global skipped;
    global skippedsrc;
    create_files();

    linked = load_list("linked.lst");
    linkedsrc = load_list("linkedsrc.lst");
    skipped = load_list("skipped.lst");
    skippedsrc = load_list("skippedsrc.lst");

    r = praw.Reddit("Links to reddit posts from other places in reddit", domain="api.reddit.com", log_requests=0);
    r.login(user, os.environ['REDDIT_PASS']);
    logging.info("Logged in to reddit...");

    check_at = 3600;
    save_at = 60;
    last_logged = 0;
    last_saved = 0;
    times_zero = 1;

    count = link_subs(r, 100, 120); # Check the last 100 posts on startup
    while True:
        if time.time() >= (last_saved + save_at):
            last_saved = time.time();
            save_list("linked.lst", linked);
            save_list("linkedsrc.lst", linkedsrc);
            save_list("skipped.lst", skipped);
            save_list("skippedsrc.lst", skippedsrc);

        if time.time() >= (last_logged + check_at):

            last_logged = time.time();
            if count == 0:
                times_zero += 1;
            else:
                logging.info("Linked " + str(count) + " in the last " + str((check_at * times_zero) / 60 / 60) + " hour(s)");
                count = 0;
                times_zero = 1;
        count += link_subs(r, 25, 60);

def create_files():
    f = open("linked.lst", "a");
    f.close();
    f = open("linkedsrc.lst", "a");
    f.close();
    f = open("skipped.lst", "a");
    f.close();
    f = open("skippedsrc.lst", "a");
    f.close();

def link_subs(r, count, delay):
    linked_count = 0;
    for submission in r.get_domain_listing('reddit.com', sort='new', limit=count):

        #if submission.subreddit.display_name.lower() not in test_reddits:  # For testing things
        #    continue;

        try:
            if link_submission(r, submission):
                linked_count += 1;
        except Exception:
            logging.error(exi());
        time.sleep(3);

    time.sleep(delay);
    return linked_count;

def link_submission(r, submission):
    url = submission.url;
    if not is_comment(url):
        return;
    linkedp = None;
    try:
        linkedp = get_object(r, url);
    except praw.errors.ClientException as e:
        logging.error("Link is not a reddit post (id: " + submission.id + ")");
        logging.error(exi());
        return;
    except Exception:
        logging.error("Could not get comment!");
        logging.error(exi());

    if linkedp is None:
        return;

    lid = linkedp.id;
    sid = submission.id;

    # Skip conditions: Already deleted, undelete/scraper/mod log bots, blacklisted, banned/archived,
    # archived, in source blacklist

    if linkedp is None or linkedp.subreddit is None:
        skipped.append(lid);
        return False;

    srlower = linkedp.subreddit.display_name.lower();

    if linkedp.author is None or srlower in blacklist or srlower in banned or linkedp.created < (time.time() - ARCHIVE_TIME):
        skipped.append(lid);
        return False;

    if submission.subreddit.display_name.lower() in srcblacklist or submission.author.name is None:
        skippedsrc.append(sid);
        return False;

    if submission.author.name.lower() in blockedusers:
        skippedsrc.append(sid);

    if lid in skipped or sid in skippedsrc:
        return False;

    if sid in linkedsrc:
        return False;

    if lid in linked or check_commmented(linkedp):
        success = edit_post(get_bot_comment(linkedp), submission);
        if success:
            linkedsrc.append(sid);
        linked.append(lid);
        return success;

    if check_commmented(linkedp):
        linked.append(lid);
        linkedsrc.append(sid);
        return False;

    if isinstance(linkedp, praw.objects.Comment):
        linked.append(lid);
        linkedsrc.append(sid);
        comment(linkedp, submission, srlower == "circlejerk");
    elif isinstance(linkedp, praw.objects.Submission):
        post(linkedp, submission, srlower == "circlejerk");
    else:
        logging.error("Not a Comment or Submission! (ID: " + id + ")");
        return False;

    linked.append(lid);
    linkedsrc.append(sid);
    return True;

def edit_post(totessubmission, original):
    if totessubmission is None:
        return False;
    text = re.sub("\[\]\(#footer\).{1,}", "", totessubmission.body); # sub. invisible link for easier footer changes
    text = re.sub("\*\^If.{1,}", "", text);
    text = re.sub("\^Please.{1,}", "", text); # substitute old footer as well
    text = re.sub("Do not vote.{1,}", "", text); # substitute original footer as well
    text = text + format_link(original) + u"""

""" + FOOTER;
    totessubmission.edit(text);
    return True;

def get_comment(r, s):
    return get_linked(r, s).comments[0];

def get_linked(r, link):
    return r.get_submission(link);

def check_commmented(c):
    if isinstance(c, praw.objects.Comment):
        comments = c.replies;
    elif isinstance(c, praw.objects.Submission):
        c.replace_more_comments(limit=None, threshold=0);
        comments = praw.helpers.flatten_tree(c.comments);

    for co in comments:
        if co.author is None:
            continue;
        if co.author.name.lower() == user.lower():
            return True;
    return False;

def get_bot_comment(s):
    if isinstance(s, praw.objects.Comment):
        for c in s.replies:
            if c.author is None:
                continue;
            if c.author.name.lower() == user.lower():
                return c;
    else:
        s.replace_more_comments(limit=None, threshold=0);
        flat_comments = praw.helpers.flatten_tree(s.comments);
        for c in flat_comments:
            if c.author is None:
                continue;
            if c.author.name.lower() == user.lower():
                return c;
    return None;

def format_comment(original, isrcirclejerk):
    if isrcirclejerk:
        cmt = CJ_HEADER;
    else:
        cmt = HEADER;
    cmt = cmt + u"""

{link}

""" + FOOTER;

    return cmt.format(link=format_link(original));

def post(s, original, isrcirclejerk):
    try:
        s.add_comment(format_comment(original, isrcirclejerk));
    except praw.errors.RateLimitExceeded:
        logging.debug("Can't comment (comment karma is too low)");
    except praw.errors.APIException as e:
        logging.warning(str(e));
    except Exception:
        logging.error("Error adding comment (SID: " + str(s.id) + ")");
        logging.error(exi());

def comment(c, original, isrcirclejerk):
    try:
        c.reply(format_comment(original, isrcirclejerk));
    except praw.errors.RateLimitExceeded:
        logging.debug("Can't comment (comment karma is too low)");
    except praw.errors.APIException as e:
        logging.warning(str(e));
    except Exception:
        logging.error("Error adding comment (CID: " + str(c.id) + ")");
        logging.error(str(e));

def format_link(post):
    srurl = post.subreddit.url;
    nsfw = post.subreddit.name.lower() in nsfwreddits or post.subreddit.over18 or post.over_18;
    text = u"- [" + srurl[:-1] + "] ";
    if nsfw:
        text = text + u"[NSFW] ";
    return text + u"[" + post.title + "](" + np(post.permalink) + ")\n";

def changesubdomain(link, sub):
    l = re.sub(r"http[s]?://[a-z]{0,3}\.?reddit\.com", "", link);
    return "http://" + sub + ".reddit.com" + l;

def unnp(link):
    return changesubdomain(link, "www");

def np(link):
    return changesubdomain(link, "np");

def get_cid(url):
    l = re.sub(r"http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.{6,8}/.*/", "", url);
    l = re.sub(r"\?.*", "", l);
    l = re.sub(r"\..*", "", l);
    return "t1_" + l;

def get_object(r, url):
    obj = praw.objects.Submission.from_url(r, unnp(url));
    a = re.compile("http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.{6,8}/.*/.{6,8}");

    if a.match(url):
        url = unnp(url);
        o = r.get_info(thing_id=get_cid(url));
        if o is None:
            raise Exception("Comment is none! (URL: " + url + ")");

        return o;
    else:
        return obj;

def is_comment(link):
    a = re.compile("http[s]?://[a-z]{0,3}\.?reddit\.com/r/.{1,20}/comments/.*");
    return a.match(link);

def load_list(file):
    f = open(file, "r");
    data = f.read();
    f.close();
    return data.split();

def save_list(file, list):
    f = open(file, "wb");
    str = "";
    for s in list:
        str = str + s + " ";
    f.write(str);
    f.close();

def log_crash():
    logging.error("Error occurred in the bot; restarting in 15 seconds...");
    logging.error("Details: ");
    logging.error(exi());
    time.sleep(15);
    sys.exit(1);

def exi():
    return traceback.format_exc();

def setup_logging():
    root = logging.getLogger();
    root.setLevel(logging.INFO);
    logging.getLogger("requests").setLevel(logging.WARNING);
    ch = logging.StreamHandler(sys.stdout);
    ch.setLevel(logging.INFO);

    root.addHandler(ch);

try:
    setup_logging();
    main();
except (AttributeError, NameError, SyntaxError, TypeError) as e:
    logging.error(exi());
    time.sleep(86400);  # Sleep for 1 day so we don't restart.
except Exception:
    log_crash();<|endoftext|>