<commit_before>import pygame
import time
import random

pygame.init()

# display dimension
display_width = 800
display_height = 600

# Color definitions
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Race')
clock = pygame.time.Clock()

carImg = pygame.image.load('img/racecar.png')
car_width = 57

def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(game_display, color, [thingx, thingy, thingw, thingh])

def car(location):
    game_display.blit(carImg, location)

def text_objects(text, font):
    text_surface = font.render(text, True, red)
    return text_surface, text_surface.get_rect()

def message_display(text):
    large_text = pygame.font.Font('freesansbold.ttf', 115)
    text_surf, text_rect = text_objects(text, large_text)
    text_rect.center = ((display_width / 2), (display_height / 2))
    game_display.blit(text_surf, text_rect)
    pygame.display.update()
    time.sleep(2)
    game_loop()

def crash():
    message_display('You Crashed')

def game_loop():
    game_exit = False
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    x_change = 0
    car_speed = 5

    thing_starty = -600
    thing_speed = 5
    thing_widh = 100
    thing_height = 100
    thing_startx = random.randrange(0, display_width - thing_widh)

    while not game_exit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quite()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -car_speed
                elif event.key == pygame.K_RIGHT:
                    x_change = car_speed
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
        x += x_change
        game_display.fill(white)

        things(thing_startx, thing_starty, thing_widh, thing_height, green)
        thing_starty += thing_speed
        car((x, y))

        if x > display_width - car_width or x < 0:
            crash()
        if thing_starty > display_height:
            thing_startx = random.randrange(0, display_width - thing_widh)
            thing_starty = 0 - thing_height
        # y crossover
        if y < thing_starty + thing_height:
            # x crossover
            if thing_startx < x < thing_startx + thing_widh or thing_startx < x + car_width < thing_startx + thing_widh:
                crash()

        pygame.display.update()
        clock.tick(60)

game_loop()<commit_msg>Added scoring and increased difficulty<commit_after>import pygame
import time
import random

pygame.init()

# display dimension
display_width = 800
display_height = 600

# Color definitions
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Race')
clock = pygame.time.Clock()

carImg = pygame.image.load('img/racecar.png')
car_width = 57

def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(game_display, color, [thingx, thingy, thingw, thingh])

def things_dodged(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Dodged: " + str(count), True, black)
    game_display.blit(text, (0, 0))

def car(location):
    game_display.blit(carImg, location)

def text_objects(text, font):
    text_surface = font.render(text, True, red)
    return text_surface, text_surface.get_rect()

def message_display(text):
    large_text = pygame.font.Font('freesansbold.ttf', 115)
    text_surf, text_rect = text_objects(text, large_text)
    text_rect.center = ((display_width / 2), (display_height / 2))
    game_display.blit(text_surf, text_rect)
    pygame.display.update()
    time.sleep(2)
    game_loop()

def crash():
    message_display('You Crashed')

def game_loop():
    game_exit = False
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    x_change = 0
    car_speed = 5
    dodged = 0

    thing_starty = -600
    thing_speed = 3
    thing_widh = 100
    thing_height = 100
    thing_startx = random.randrange(0, display_width - thing_widh)

    while not game_exit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -car_speed
                elif event.key == pygame.K_RIGHT:
                    x_change = car_speed
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
        x += x_change
        game_display.fill(white)

        things(thing_startx, thing_starty, thing_widh, thing_height, green)
        thing_starty += thing_speed
        car((x, y))
        things_dodged(dodged)

        if x > display_width - car_width or x < 0:
            crash()
        if thing_starty > display_height:
            thing_startx = random.randrange(0, display_width - thing_widh)
            thing_starty = 0 - thing_height
            dodged += 1
            thing_speed += 1

        # y crossover
        if y < thing_starty + thing_height:
            # x crossover
            if thing_startx < x < thing_startx + thing_widh or thing_startx < x + car_width < thing_startx + thing_widh:
                crash()

        pygame.display.update()
        clock.tick(60)

game_loop()<|endoftext|>


<commit_before>import subprocess
import os

subprocess.call(" figlet FosWink", shell=True)

#Config Vars

SteamDir = "steam"
GmodDir = "gmod"
GmodID = 4020
login = "anonymous"
SteamCMD = "http://media.steampowered.com/client/steamcmd_linux.tar.gz"
SystemOS = "Ubuntu"

## Functions

def startserver():
    #TODO, Start screen run command to start server
    print("Starting Server")

def stopserver():
    #TODO, Stop server then end screen
    print("Stoping Server")

def bans():
    print("Ban Manager")

def config():
    print("Config this server!")

def console():
    print("Console Text")

def logs():
    print("Catch the Tail for the logs")

def installer():
    if os.path.exists(SteamDir):
        print("Directory {} Already Exist Skipping".format(SteamDir))
    else:
        print("Directory {} Not Dectected Creating {}".format(SteamDir, SteamDir))
        os.makedirs(SteamDir)
        print("Directory {} Created!".format(SteamDir))

        print("Getting SteamCMD")
        subprocess.call("wget -P {} {}".format(SteamDir, SteamCMD), shell=True)

        print("Extracting SteamCMD")
        subprocess.call("tar -zxvf {}/steamcmd_linux.tar.gz -C {}/".format(SteamDir, SteamDir), shell=True)

        print("Getting 32bit Libs\n")

        if SystemOS == "Ubuntu":
            subprocess.call("sudo apt-get -y install lib32stdc++6", shell=True)
        elif SystemOS == "Centos":
            subprocess.call("yum install -y glibc.i686 libstdc++.i686", shell=True)
        elif SystemOS == "Arch":
            subprocess.call("pacman -S lib32-gcc-libs", shell=True);
        else:
            print("You have to set SystemOS to ether Ubuntu, Centos, or Arch\n")
        else:
            print("32Bit System No need to install Libs\n")

    print("Running SteamCMD\n")
    subprocess.call("bash {}/steamcmd.sh +login {} +force_install_dir {} +app_update {} +quit".format(SteamDir, login, GmodDir, GmodID), shell=True)

    print("Completed: Gmod is Located in {}\n".format)

def update():
    print("Updating Gmod")
    subprocess.call("bash {}/steamcmd.sh +login {} +force_install_dir {} +app_update {} +quit".format(login, GmodDir, GmodID), shell=True)

def mountgames():
    print("Mounting Games")

# Main Loop for MainMenu

print("FosWink Main Menu")

ans = True

while ans:
    ans = raw_input("[FosWink]~> ")

    if ans == "help":

        print("start : Start Gmod server ")
        print("stop : Stop Gmod server ")
        print("bans : Opens Ban Manager")
        print("config : Change server parameters ")
        print("console : Opens server console ")
        print("logs : Opens Log Manager ")
        print("installer : Install Gmod")
        print("mount : Mount Games to Gmod")
        print("exit : Exit FosWink ")

    elif ans == "start":

        startserver()

    elif ans == "stop":

        stopserver()

    elif ans == "ban":

        bans()

    elif ans == "config":

        config()

    elif ans == "console":

        console()

    elif ans == "logs":

        logs()

    elif ans == "installer":

        installer()

    elif ans == "update":

        update()

    elif ans == "mount":

        mountgames()

    elif ans == "exit":
        break

    else:
        print("Not A Valid Choice, Try again or run help")

<commit_msg>removed extra else<commit_after>import subprocess
import os

subprocess.call(" figlet FosWink", shell=True)

#Config Vars

SteamDir = "steam"
GmodDir = "gmod"
GmodID = 4020
login = "anonymous"
SteamCMD = "http://media.steampowered.com/client/steamcmd_linux.tar.gz"
SystemOS = "Ubuntu"

## Functions

def startserver():
    #TODO, Start screen run command to start server
    print("Starting Server")

def stopserver():
    #TODO, Stop server then end screen
    print("Stoping Server")

def bans():
    print("Ban Manager")

def config():
    print("Config this server!")

def console():
    print("Console Text")

def logs():
    print("Catch the Tail for the logs")

def installer():
    if os.path.exists(SteamDir):
        print("Directory {} Already Exist Skipping".format(SteamDir))
    else:
        print("Directory {} Not Dectected Creating {}".format(SteamDir, SteamDir))
        os.makedirs(SteamDir)
        print("Directory {} Created!".format(SteamDir))

        print("Getting SteamCMD")
        subprocess.call("wget -P {} {}".format(SteamDir, SteamCMD), shell=True)

        print("Extracting SteamCMD")
        subprocess.call("tar -zxvf {}/steamcmd_linux.tar.gz -C {}/".format(SteamDir, SteamDir), shell=True)

        print("Getting 32bit Libs\n")

        if SystemOS == "Ubuntu":
            subprocess.call("sudo apt-get -y install lib32stdc++6", shell=True)
        elif SystemOS == "Centos":
            subprocess.call("yum install -y glibc.i686 libstdc++.i686", shell=True)
        elif SystemOS == "Arch":
            subprocess.call("pacman -S lib32-gcc-libs", shell=True);
        else:
            print("You have to set SystemOS to ether Ubuntu, Centos, or Arch\n")
            print("32Bit System No need to install Libs\n")

    print("Running SteamCMD\n")
    subprocess.call("bash {}/steamcmd.sh +login {} +force_install_dir {} +app_update {} +quit".format(SteamDir, login, GmodDir, GmodID), shell=True)

    print("Completed: Gmod is Located in {}\n".format)

def update():
    print("Updating Gmod")
    subprocess.call("bash {}/steamcmd.sh +login {} +force_install_dir {} +app_update {} +quit".format(login, GmodDir, GmodID), shell=True)

def mountgames():
    print("Mounting Games")

# Main Loop for MainMenu

print("FosWink Main Menu")

ans = True

while ans:
    ans = raw_input("[FosWink]~> ")

    if ans == "help":

        print("start : Start Gmod server ")
        print("stop : Stop Gmod server ")
        print("bans : Opens Ban Manager")
        print("config : Change server parameters ")
        print("console : Opens server console ")
        print("logs : Opens Log Manager ")
        print("installer : Install Gmod")
        print("mount : Mount Games to Gmod")
        print("exit : Exit FosWink ")

    elif ans == "start":

        startserver()

    elif ans == "stop":

        stopserver()

    elif ans == "ban":

        bans()

    elif ans == "config":

        config()

    elif ans == "console":

        console()

    elif ans == "logs":

        logs()

    elif ans == "installer":

        installer()

    elif ans == "update":

        update()

    elif ans == "mount":

        mountgames()

    elif ans == "exit":
        break

    else:
        print("Not A Valid Choice, Try again or run help")

<|endoftext|>


<commit_before>import csv
from PIL import Image, ImageDraw,ImageFont

# Main image from base.jpg
im = Image.open('base.jpg').convert('RGBA')
W, H = im.size

MaxSize = 200
maxFontW = W * .90

# Open the Local Hack Day CSV
with open('data.csv', 'rb') as attendance:
	#Set the reader
    reader = csv.reader(attendance)
    #Iterate through
    for row in reader:

    	#Grab name and surname
    	first_name = row[0].upper()
    	last_name = row[1].upper()
    	full_name = first_name + " " + last_name

    	# Set font and size
        NameFont = ImageFont.truetype('fonts/Outage.ttf', venueSize)
        address = ImageFont.truetype('fonts/Lato.ttf', addressSize)

<commit_msg>added some code from original source and cleaned it up<commit_after>import csv
from PIL import Image, ImageDraw,ImageFont

# Open the Local Hack Day CSV
with open('data.csv', 'rb') as attendance:
	#Set the reader
    reader = csv.reader(attendance)

    #Iterate through
    for row in reader:

		# Main image from base.jpg
		im = Image.open('base.jpg').convert('RGBA')
		W, H = im.size

		MaxSize = 200
		maxFontW = W * .90

		nameSize = MaxSize
        congrats = MaxSize/2

    	#Grab name and surname
    	first_name = row[0].upper()
    	last_name = row[1].upper()
    	full_name = first_name + " " + last_name

    	# Set font and size
        venue = ImageFont.truetype('fonts/Outage.ttf', nameSize)
        address = ImageFont.truetype('fonts/Lato.ttf', congrats)

        draw = ImageDraw.Draw(im)

        # Find size of text
        wVenue, hVenue = draw.textsize(venueName,font=venue)

        # Make size smaller until width is less than size of maxFontW
        while (wVenue > maxFontW):
            nameSize = nameSize - 10
            venue = ImageFont.truetype('fonts/Outage.ttf', nameSize)
            wVenue, hVenue = draw.textsize(venueName,font=venue)

        wAddress, hAddress = draw.textsize(addressDetails,font=address)

        while (wAddress > maxFontW):
            congrats = congrats - 10
            address = ImageFont.truetype('fonts/OpenSansRegular.ttf', congrats)
            wAddress, hAddress = draw.textsize(addressDetails,font=address)

<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import jinja2
import os
import webapp2

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

class BaseHandler(webapp2.RequestHandler):

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, file_name, **params):
        template = jinja_env.get_template(file_name)
        return template.render(params)

    def render(self, file_name, **kw):
        self.write(self.render_str(file_name, **kw))

class MainHandler(BaseHandler):

    def get(self):
        self.render("main.html", title = "AI Experiments")

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)
<commit_msg>adding handlers for search and slide<commit_after>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import jinja2
import os
import webapp2

template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

class BaseHandler(webapp2.RequestHandler):

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, file_name, **params):
        template = jinja_env.get_template(file_name)
        return template.render(params)

    def render(self, file_name, **kw):
        self.write(self.render_str(file_name, **kw))

class MainHandler(BaseHandler):
    def get(self):
        self.render("main.html", title = "AI Experiments")

class SearchHandler(BaseHandler):
    def get(self):
        self.render("search.html", title = "AI Experiments - Search")

class SlidePuzzleHandler(BaseHandler):
    def get(self):
        self.render("slide-puzzle.html", title = "AI Experiments - Slide Puzzle")

html_re = r'(.html)?'
app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/search' + html_re, SearchHandler),
    ('/slide-puzzle', SlidePuzzleHandler)
], debug=True)
<|endoftext|>


<commit_before>"""small utility for dumping out Sentry event trends"""
import ConfigParser
from sentry_stats import SentryStats

def deep_get(dictionary, *keys):
    """
    deep get for nested dictionaries, great for getting stuff from
    REST api_keys
    Courtesy of:
    http://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary  # noqa
    """
    return reduce(lambda d, key: d.get(key) if d else None, keys, dictionary)

def main():
    """main command line entry point"""
    parser = ConfigParser.ConfigParser()
    parser.read("config.ini")
    sentry_key = parser.get("api_keys", "sentry")
    organization = parser.get("event_filters", "organization")
    project = parser.get("event_filters", "project")
    days = parser.getint("event_filters", "days")

    print "Sentry Key: " + sentry_key[0:5] + "..."
    print "Organization: " + organization
    print "Project: " + project

    stats = SentryStats(sentry_key, organization)
    events = stats.retrieve_events(project, days)

    print "\n\nDate Created, Date Received, User ID, Type, Message"
    for event in events:
        row = [
            event["dateCreated"],
            event["dateReceived"],
            deep_get(event, "user", "id") or "",
            event["type"],
            event["message"]
        ]
        print ", ".join(row)

if __name__ == "__main__":
    main()
<commit_msg>now printing out the total events at the end<commit_after>"""small utility for dumping out Sentry event trends"""
import ConfigParser
from sentry_stats import SentryStats

def deep_get(dictionary, *keys):
    """
    deep get for nested dictionaries, great for getting stuff from
    REST api_keys
    Courtesy of:
    http://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary  # noqa
    """
    return reduce(lambda d, key: d.get(key) if d else None, keys, dictionary)

def main():
    """main command line entry point"""
    parser = ConfigParser.ConfigParser()
    parser.read("config.ini")
    sentry_key = parser.get("api_keys", "sentry")
    organization = parser.get("event_filters", "organization")
    project = parser.get("event_filters", "project")
    days = parser.getint("event_filters", "days")

    print "Sentry Key: " + sentry_key[0:5] + "..."
    print "Organization: " + organization
    print "Project: " + project

    stats = SentryStats(sentry_key, organization)
    events = stats.retrieve_events(project, days)

    print "\n\nDate Created, Date Received, User ID, Type, Message"
    for event in events:
        row = [
            event["dateCreated"],
            event["dateReceived"],
            deep_get(event, "user", "id") or "",
            event["type"],
            event["message"]
        ]
        print ", ".join(row)

    print "\n\nTotal: " + str(len(events))

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


<commit_before>#!/usr/bin/python

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.textinput import TextInput
from kivy.uix.scrollview import ScrollView
from kivy.uix.floatlayout import FloatLayout
from kivy.factory import Factory
from kivy.uix.popup import Popup

from kivy.core.window import Window
from kivy.graphics import Color, Rectangle
from kivy.properties import StringProperty, ObjectProperty
from getpass import getuser
from socket import gethostname
import JsonInfoReader, State, Outputer
import time
import os

file = JsonInfoReader.JsonInfoReader("info.json")
state = State.State()

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

class TitleBar(BoxLayout):

    def __init__(self, **kwargs):
        super(TitleBar, self).__init__(**kwargs)
        self.orientation = 'horizontal'

class Prompt(Label):

    def __init__(self, **kwargs):
        super(Prompt, self).__init__(**kwargs)
        self.text = getuser() + "@" + gethostname()

class SwitchScreen(BoxLayout):
#    global file
#    inst = file
    accordion = ObjectProperty(None)
    infos = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(SwitchScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'
        self.create()
#        self.scrollinfo.add_widget(InfoScreen(self.inst.listCategories()[0]))

    def viewitem(self, object, text):
        self.remove_widget(self.infos)
        self.infos = InfoScreen(text)
        self.add_widget(self.infos)

    def create(self):
        self.accordion.bind(selected=self.viewitem)

class InfoScreen(BoxLayout):

    def __init__(self, value = "", **kwargs):
        super(InfoScreen, self).__init__(**kwargs)
        if not value: return
        self.orientation = "vertical"
        width = self.width
        height = self.height

        self.add_widget(HeadInfo(value))

        global file
        inst = file
        inf = inst.getInfo(value)
        txts = TextInput(text = inf, background_color = (0.15, 0.15, 0.15, 1),
            foreground_color = (1, 1, 1, 1), multiline = True, readonly = False,
            size_hint = (1.0, None))
        txts.bind(minimum_height=txts.setter('height'))
        scroll = ScrollView(size_hint = (1, 1),
                size = (width, height*0.9))
        scroll.add_widget(txts)
        self.add_widget(scroll)
        comments = TextInput(multiline=True, foreground_color = (1, 1, 1, 1),
            size_hint=(1.0,None), background_color = (0.15, 0.15, 0.15))
        if value in state.comments.keys():
            comments.text = state.comments[value]
        self.add_widget(comments)

        self.add_widget(ButtonBar())

class HeadInfo(Widget):
    header = ObjectProperty(None)

    def __init__(self, value, **kwargs):
        super(HeadInfo, self).__init__(**kwargs)
        self.header.text = value
#        self.add_widget(Label(text = value, font_size = "28sp",
#            size_hint_y = 0.05))

class AccordionThing(Accordion):
    selected = StringProperty("")

    def __init__(self, **kwargs):
        super(AccordionThing, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.draw()

    def switch(self, object):
        self.selected = object.text

    def draw(self):
        global file
        inst = file
        blades = []
        for cat in inst.listCategories():
            blades.append(AccordionItem(title = cat, font_size = "20sp"))
            box = BoxLayout(orientation = 'vertical')
            subs = inst.listInsideCategories(cat)
            for sub in subs:
                butt = Button(text = sub, background_color = [0.35, 0.35, 0.35,
                    1], font_size = "16sp")
                butt.bind(on_press = self.switch)
                box.add_widget(butt)
            blades[-1].add_widget(box)
            self.add_widget(blades[-1])
        blades[-1].collapse = True
        blades[0].collapse = False

class ButtonBar(BoxLayout):

    def __init__(self, **kwargs):
        super(ButtonBar, self).__init__(**kwargs)
        self.orientation = 'horizontal'

    def showImport(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9,
            0.9))
        self._popup.open()

    def load(self, path, filename):
        state.load(os.path.join(path,filename[0]))
        self.dismiss_popup()

    def dismiss_popup(self):
        self._popup.dismiss()

class MainScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'
        titleb = TitleBar()
        switch = SwitchScreen()
        self.add_widget(titleb)
        self.add_widget(switch)

class RiceApp(App):

    def build(self):
        win = MainScreen()
        Window.clearcolor = (0.15, 0.15, 0.15, 1)
        return win

if __name__ == '__main__':
  RiceApp().run()
<commit_msg>fixing up code with cosmetic changes and some other stuff, comments are scroll-boxed<commit_after>#!/usr/bin/python

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.textinput import TextInput
from kivy.uix.scrollview import ScrollView
from kivy.uix.floatlayout import FloatLayout
from kivy.factory import Factory
from kivy.uix.popup import Popup

from kivy.core.window import Window
from kivy.graphics import Color, Rectangle
from kivy.properties import StringProperty, ObjectProperty
from getpass import getuser
from socket import gethostname
import JsonInfoReader, State, Outputer
import time
import os

file = JsonInfoReader.JsonInfoReader("info.json")
state = State.State()

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

class TitleBar(BoxLayout):

    def __init__(self, **kwargs):
        super(TitleBar, self).__init__(**kwargs)
        self.orientation = 'horizontal'

class Prompt(Label):

    def __init__(self, **kwargs):
        super(Prompt, self).__init__(**kwargs)
        self.text = getuser() + "@" + gethostname()

class SwitchScreen(BoxLayout):
#    global file
#    inst = file
    accordion = ObjectProperty(None)
    infos = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(SwitchScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'
        self.create()
#        self.scrollinfo.add_widget(InfoScreen(self.inst.listCategories()[0]))

    def viewitem(self, object, text):
        self.remove_widget(self.infos)
        self.infos = InfoScreen(text)
        self.add_widget(self.infos)

    def create(self):
        self.accordion.bind(selected=self.viewitem)

class InfoScreen(BoxLayout):

    def __init__(self, value = "", **kwargs):
        super(InfoScreen, self).__init__(**kwargs)
        if not value: return
        self.orientation = "vertical"
        width = self.width
        height = self.height

        self.add_widget(HeadInfo(value))

        global file
        inst = file
        inf = inst.getInfo(value)
        txts = TextInput(text = inf, background_color = (0.15, 0.15, 0.15, 1),
            foreground_color = (1, 1, 1, 1), multiline = True, readonly = True,
            size_hint = (1.0, None))
        txts.bind(minimum_height=txts.setter('height'))
        scroll = ScrollView(size_hint = (1, 0.8),
                size = (width, height))
        scroll.add_widget(txts)
        self.add_widget(scroll)
        scroll2 = ScrollView(size_hint = (1, 0.2),
                size = (width, height))
        comments = TextInput(multiline=True, foreground_color = (1, 1, 1, 1),
            size_hint = (1.0, None), background_color = (0.15, 0.15, 0.15))
        comments.bind(minimum_height=comments.setter('height'))
        if value in state.comments.keys():
            comments.text = state.comments[value]
        else: comments.text = "Put some text here, bruh."
        scroll2.add_widget(comments)
        self.add_widget(scroll2)
#        self.add_widget(comments)

        self.add_widget(ButtonBar())

class HeadInfo(Widget):
    header = ObjectProperty(None)

    def __init__(self, value, **kwargs):
        super(HeadInfo, self).__init__(**kwargs)
        self.header.text = value
#        self.add_widget(Label(text = value, font_size = "28sp",
#            size_hint_y = 0.05))

class AccordionThing(Accordion):
    selected = StringProperty("")

    def __init__(self, **kwargs):
        super(AccordionThing, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.draw()

    def switch(self, object):
        self.selected = object.text

    def draw(self):
        global file
        inst = file
        blades = []
        for cat in inst.listCategories():
            blades.append(AccordionItem(title = cat, font_size = "20sp"))
            box = BoxLayout(orientation = 'vertical')
            subs = inst.listInsideCategories(cat)
            for sub in subs:
                butt = Button(text = sub, background_color = [0.35, 0.35, 0.35,
                    1], font_size = "16sp")
                butt.bind(on_press = self.switch)
                box.add_widget(butt)
            blades[-1].add_widget(box)
            self.add_widget(blades[-1])
        blades[-1].collapse = True
        blades[0].collapse = False

class ButtonBar(BoxLayout):

    def __init__(self, **kwargs):
        super(ButtonBar, self).__init__(**kwargs)
        self.orientation = 'horizontal'

    def showImport(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9,
            0.9))
        self._popup.open()

    def load(self, path, filename):
        state.load(os.path.join(path,filename[0]))
        self.dismiss_popup()

    def dismiss_popup(self):
        self._popup.dismiss()

class MainScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'
        titleb = TitleBar()
        switch = SwitchScreen()
        self.add_widget(titleb)
        self.add_widget(switch)

class RiceApp(App):

    def build(self):
        win = MainScreen()
        Window.clearcolor = (0.15, 0.15, 0.15, 1)
        return win

if __name__ == '__main__':
  RiceApp().run()
<|endoftext|>


<commit_before>import echopy

def handler(event, context):
    return echopy.handler(event, context)

echopy.application_id = 'amzn1.ask.skill.[unique-value-here]'

@echopy.on_session_launch
def session_started(event):
    output_speech = echopy.OutputSpeech(text="Test!")
    return echopy.Response(output_speech=output_speech)

@echopy.on_session_end
def session_ended(event):
    output_speech = echopy.OutputSpeech("Seeya!")
    return echopy.Response(output_speech=output_speech)

@echopy.on_intent('SomeIntent')
def some_intent(event):
    output_speech = echopy.OutputSpeech("Some intent thing!")
    return echopy.Response(output_speech=output_speech)
<commit_msg>Delete main.py<commit_after><|endoftext|>


<commit_before># coding=gbk

from pprint import pprint
import random
import multiprocessing

import settings
import test
import ga

mutate_ratio = 0.2
crossover_ratio = 0.4
population = 100
population_limit = int((1 + crossover_ratio / 2) * population)
generation_count = 10000

thread_pool = None

generation = 0
matrix_list = []
score_list = []
top_score = 0
top_title = ''

def print_list(name_list):
    for i in range(0, len(name_list)):
        # print str(i) + ":\t" + name_list[i]
        print str(i) + ": " + name_list[i]
        i += 1

def print_result_from_matrix(m):
    row_size, col_size = m.shape
    res = []

    for i in range(0, row_size):
        row_api_list = []
        for j in range(0, col_size):
            if m[i, j] == 1:
                row_api_list.append(settings.api_list[j])
        if len(row_api_list) != 0:
            res.append(row_api_list)

    pprint(res)
    print "Category number = " + str(len(res))

def sort_matrix_list():
    global score_list
    global matrix_list

    together = zip(score_list, matrix_list)
    sorted_together = sorted(together, lambda a, b: b[0] - a[0])

    score_list = [x[0] for x in sorted_together]
    matrix_list = [x[1] for x in sorted_together]

def print_result_from_matrix_list():
    valid_score_list = score_list[:population]
    print "matrix list of %d instances result, generation = %d, average = %d, max = %d, min = %d" %\
          (len(valid_score_list), generation, sum(valid_score_list) / len(valid_score_list), max(valid_score_list), min(valid_score_list))
    print valid_score_list

def do_init():
    test.init_from_test()

    # Print the test dictionary.
    # pprint(test_dict)

    test.init_lists()

    # Initialize the test matrix.
    settings.test_matrix = test.init_test_matrix()

    print "\n*****************************************************"
    print "cleansed test matrix:"
    # Remove the duplicated rows in the test matrix.
    settings.test_matrix, settings.case_list = test.cleanse_test_matrix(settings.test_matrix, settings.case_list)
    # Remove the shadow-covered rows in the test matrix.
    # settings.test_matrix, settings.case_list = test.cleanse_test_matrix2(settings.test_matrix, settings.case_list)
    settings.case_count = len(settings.case_list)

    ga.print_matrix(settings.test_matrix)

    print "\n*****************************************************"
    print "case list:"
    print_list(settings.case_list)

    print "\n*****************************************************"
    print "API list:"
    print_list(settings.api_list)

    print "\n*****************************************************"
    print "case number = " + str(settings.case_count)
    print "API number = " + str(settings.api_count)

def do_demo():
    m = ga.init_random_matrix(settings.category_max_count, settings.api_count)

    ga.print_matrix(m)

    print "\n*****************************************************"
    print "After mutation:"

    ga.mutate_matrix(m)
    ga.print_matrix(m)

    # print "\n*****************************************************"
    # evaluate_matrix(m)

    # print_result_from_matrix(m)

    # a = [1, 32]
    # b = [3, 4]
    # c = np.array([a, b])
    #
    # print c[:,1]

    # print c

def do_init_generation():
    global score_list

    for i in range(population_limit):
        matrix_list.append(ga.init_random_matrix(settings.category_max_count, settings.api_count))
    score_list = [0] * population_limit
    # do_evaluate()
    # sort_matrix_list()
    # print "\n*****************************************************"
    # print_result_from_matrix_list()

    init_thread_pool()

def do_mutate(start, end):
    for i in range(start, end):
        ga.mutate_matrix(matrix_list[i])
        # Evaluate the matrix: i
        score_list[i] = int(ga.evaluate_matrix(matrix_list[i]))

def do_crossover(start, end):
    for i in range(start, end, 2):
        new_i = population + int((i - (1 - crossover_ratio) * population) / 2)
        matrix_list[new_i] = ga.crossover_matrix(matrix_list[i], matrix_list[i + 1])
        # Evaluate the matrix: new_i
        score_list[new_i] = int(ga.evaluate_matrix(matrix_list[new_i]))

def do_evaluate(start, end):
    global score_list

    for i in range(start, end):
        score_list[i] = int(ga.evaluate_matrix(matrix_list[i]))

# def do_eliminate():
#     eliminate_size = len(matrix_list) - population
#     del matrix_list[-eliminate_size:]
#     del score_list[-eliminate_size:]

# 20% - mutate
# 40% - crossover
# 40% - no change
def do_evolve_once():
    global generation
    generation += 1

    # random.shuffle(matrix_list)
    matrix_list[:population] = random.sample(matrix_list[:population], population)

    do_mutate(0, int(mutate_ratio * population))
    do_crossover(int((1 - crossover_ratio) * population), population)
    # do_evaluate(0, population_limit)

    sort_matrix_list()
    # do_eliminate()

def init_thread_pool():
    global thread_pool
    thread_pool = multiprocessing.Pool(processes=10)

def do_evolve_once_multi_thread():
    global generation
    generation += 1

    matrix_list[:population] = random.sample(matrix_list[:population], population)

    thread_pool.apply_async(do_mutate, (0, int(mutate_ratio * population)))
    thread_pool.apply_async(do_crossover, (int((1 - crossover_ratio) * population), population))

    # thread_pool.close()
    # thread_pool.join()

    # do_mutate(0, int(mutate_ratio * population))
    # do_crossover(int((1 - crossover_ratio) * population), population)

    sort_matrix_list()

def do_evolve_generation(set_data_func, set_title_func):
    global top_score, top_title

    for i in range(generation_count):
        do_evolve_once()
        # do_evolve_once_multi_thread()
        print_result_from_matrix_list()
        if set_data_func:
            if top_score < score_list[0]:
                top_score = score_list[0]
                top_title = "top generation: %d, top score: %d/%d, %s" % (i + 1, top_score, settings.full_score, ga.get_matrix_description(matrix_list[0]))
                set_data_func(ga.remove_empty_rows_from_matrix(matrix_list[0]))
            set_title_func("input: %s, population: %d, current: %d/%d, %s" % (settings.filename, population, i + 1, generation_count, top_title))

if __name__ == '__main__':
    do_init()
    do_demo()

    do_init_generation()
    do_evolve_generation(None, None)
<commit_msg>Showed max/min score in title.<commit_after># coding=gbk

from pprint import pprint
import random
import multiprocessing

import settings
import test
import ga

mutate_ratio = 0.2
crossover_ratio = 0.4
population = 100
population_limit = int((1 + crossover_ratio / 2) * population)
generation_count = 10000

thread_pool = None

generation = 0
matrix_list = []
score_list = []
top_score = 0
top_title = ''
max_score = 0
min_score = 0

def print_list(name_list):
    for i in range(0, len(name_list)):
        # print str(i) + ":\t" + name_list[i]
        print str(i) + ": " + name_list[i]
        i += 1

def print_result_from_matrix(m):
    row_size, col_size = m.shape
    res = []

    for i in range(0, row_size):
        row_api_list = []
        for j in range(0, col_size):
            if m[i, j] == 1:
                row_api_list.append(settings.api_list[j])
        if len(row_api_list) != 0:
            res.append(row_api_list)

    pprint(res)
    print "Category number = " + str(len(res))

def sort_matrix_list():
    global score_list
    global matrix_list

    together = zip(score_list, matrix_list)
    sorted_together = sorted(together, lambda a, b: b[0] - a[0])

    score_list = [x[0] for x in sorted_together]
    matrix_list = [x[1] for x in sorted_together]

def print_result_from_matrix_list():
    global max_score, min_score

    valid_score_list = score_list[:population]
    max_score = max(valid_score_list)
    min_score = min(valid_score_list)

    print "matrix list of %d instances result, generation = %d, average = %d, max = %d, min = %d" %\
          (len(valid_score_list), generation, sum(valid_score_list) / len(valid_score_list), max_score, min_score)
    print valid_score_list

def do_init():
    test.init_from_test()

    # Print the test dictionary.
    # pprint(test_dict)

    test.init_lists()

    # Initialize the test matrix.
    settings.test_matrix = test.init_test_matrix()

    print "\n*****************************************************"
    print "cleansed test matrix:"
    # Remove the duplicated rows in the test matrix.
    settings.test_matrix, settings.case_list = test.cleanse_test_matrix(settings.test_matrix, settings.case_list)
    # Remove the shadow-covered rows in the test matrix.
    # settings.test_matrix, settings.case_list = test.cleanse_test_matrix2(settings.test_matrix, settings.case_list)
    settings.case_count = len(settings.case_list)

    ga.print_matrix(settings.test_matrix)

    print "\n*****************************************************"
    print "case list:"
    print_list(settings.case_list)

    print "\n*****************************************************"
    print "API list:"
    print_list(settings.api_list)

    print "\n*****************************************************"
    print "case number = " + str(settings.case_count)
    print "API number = " + str(settings.api_count)

def do_demo():
    m = ga.init_random_matrix(settings.category_max_count, settings.api_count)

    ga.print_matrix(m)

    print "\n*****************************************************"
    print "After mutation:"

    ga.mutate_matrix(m)
    ga.print_matrix(m)

    # print "\n*****************************************************"
    # evaluate_matrix(m)

    # print_result_from_matrix(m)

    # a = [1, 32]
    # b = [3, 4]
    # c = np.array([a, b])
    #
    # print c[:,1]

    # print c

def do_init_generation():
    global score_list

    for i in range(population_limit):
        matrix_list.append(ga.init_random_matrix(settings.category_max_count, settings.api_count))
    score_list = [0] * population_limit
    # do_evaluate()
    # sort_matrix_list()
    # print "\n*****************************************************"
    # print_result_from_matrix_list()

    init_thread_pool()

def do_mutate(start, end):
    for i in range(start, end):
        ga.mutate_matrix(matrix_list[i])
        # Evaluate the matrix: i
        score_list[i] = int(ga.evaluate_matrix(matrix_list[i]))

def do_crossover(start, end):
    for i in range(start, end, 2):
        new_i = population + int((i - (1 - crossover_ratio) * population) / 2)
        matrix_list[new_i] = ga.crossover_matrix(matrix_list[i], matrix_list[i + 1])
        # Evaluate the matrix: new_i
        score_list[new_i] = int(ga.evaluate_matrix(matrix_list[new_i]))

def do_evaluate(start, end):
    global score_list

    for i in range(start, end):
        score_list[i] = int(ga.evaluate_matrix(matrix_list[i]))

# def do_eliminate():
#     eliminate_size = len(matrix_list) - population
#     del matrix_list[-eliminate_size:]
#     del score_list[-eliminate_size:]

# 20% - mutate
# 40% - crossover
# 40% - no change
def do_evolve_once():
    global generation
    generation += 1

    # random.shuffle(matrix_list)
    matrix_list[:population] = random.sample(matrix_list[:population], population)

    do_mutate(0, int(mutate_ratio * population))
    do_crossover(int((1 - crossover_ratio) * population), population)
    # do_evaluate(0, population_limit)

    sort_matrix_list()
    # do_eliminate()

def init_thread_pool():
    global thread_pool
    thread_pool = multiprocessing.Pool(processes=10)

def do_evolve_once_multi_thread():
    global generation
    generation += 1

    matrix_list[:population] = random.sample(matrix_list[:population], population)

    thread_pool.apply_async(do_mutate, (0, int(mutate_ratio * population)))
    thread_pool.apply_async(do_crossover, (int((1 - crossover_ratio) * population), population))

    # thread_pool.close()
    # thread_pool.join()

    # do_mutate(0, int(mutate_ratio * population))
    # do_crossover(int((1 - crossover_ratio) * population), population)

    sort_matrix_list()

def do_evolve_generation(set_data_func, set_title_func):
    global top_score, top_title

    for i in range(generation_count):
        do_evolve_once()
        # do_evolve_once_multi_thread()
        print_result_from_matrix_list()
        if set_data_func:
            if top_score < score_list[0]:
                top_score = score_list[0]
                top_title = "top generation: %d, top score: %d/%d, %s" % (i + 1, top_score, settings.full_score, ga.get_matrix_description(matrix_list[0]))
                set_data_func(ga.remove_empty_rows_from_matrix(matrix_list[0]))
            set_title_func("input: %s, population: %d, min/max: (%d, %d), current: %d/%d, %s" % (settings.filename, population, min_score, max_score, i + 1, generation_count, top_title))

if __name__ == '__main__':
    do_init()
    do_demo()

    do_init_generation()
    do_evolve_generation(None, None)
<|endoftext|>


<commit_before>import web

# Map out the URLs
urls = (
    '/', 'Index',
)

# Set the debugging messages
web.config.debug = True

### Define the globals
t_globals = {
}
render = web.template.render('templates', base='base', globals=t_globals)

# Create the web application
app = web.application(urls, globals())

##------------------------------------------------------------------------
## Form Definitions

zoomvalues = []
for i in range(5, 20):
    tup = (str(i), str(i))
    zoomvalues.append(tup)

map_form = web.form.Form(web.form.Checkbox('By Coordinates', checked=True, id="coordcheck", onClick='handleCheck(this);'),
                         web.form.Textbox('Address', id='addressbox', disabled=False),
                         web.form.Textbox('City', id='citybox', disabled=False),
                         web.form.Textbox('State', id='statebox', disabled=False),
                         web.form.Textbox('Latitude', id='latbox'),
                         web.form.Textbox('Longitude', id='lonbox'),
                         web.form.Dropdown('Zoom', zoomvalues, id='zoomdrop'),
                         web.form.Button('Get My Map', id='formbutton', type='button', onClick='handleGetMap()'))

##------------------------------------------------------------------------
## Web Page Class Definitions

class Index:
    '''Main index page'''
    def GET(self):
        form = map_form()
        return render.index(form)

def notfound():
    ''' Create the not found page '''
    return web.notfound('Sorry, the page you were looking for was not found.')
    # You can use template result like below, either is ok:
    #return web.notfound(render.notfound())
    #return web.notfound(str(render.notfound()))

def internalerror():
    ''' Create the internal error page '''
    return web.internalerror('The server says: No soup for you!')

### Create the not found app
app.notfound = notfound
app.internalerror = internalerror

main = app.cgirun()<commit_msg>SOme formatting fixes<commit_after>import web

# Map out the URLs
urls = (
    '/', 'Index',
)

# Set the debugging messages
web.config.debug = True

# Define the globals
t_globals = {
}
render = web.template.render('templates', base='base', globals=t_globals)

# Create the web application
app = web.application(urls, globals())

# ------------------------------------------------------------------------
# Form Definitions

zoomvalues = []
for i in range(5, 20):
    tup = (str(i), str(i))
    zoomvalues.append(tup)

map_form = web.form.Form(web.form.Checkbox('By Coordinates', checked=True, id="coordcheck", onClick='handleCheck(this);'),
                         web.form.Textbox('Address', id='addressbox', disabled=False),
                         web.form.Textbox('City', id='citybox', disabled=False),
                         web.form.Textbox('State', id='statebox', disabled=False),
                         web.form.Textbox('Latitude', id='latbox'),
                         web.form.Textbox('Longitude', id='lonbox'),
                         web.form.Dropdown('Zoom', zoomvalues, id='zoomdrop'),
                         web.form.Button('Get My Map', id='formbutton', type='button', onClick='handleGetMap()'))

# ------------------------------------------------------------------------
# Web Page Class Definitions

class Index:
    '''Main index page'''
    def GET(self):
        form = map_form()
        return render.index(form)

def notfound():
    ''' Create the not found page '''
    return web.notfound('Sorry, the page you were looking for was not found.')
    # You can use template result like below, either is ok:
    # return web.notfound(render.notfound())
    # return web.notfound(str(render.notfound()))

def internalerror():
    ''' Create the internal error page '''
    return web.internalerror('The server says: No soup for you!')

# Create the not found app
app.notfound = notfound
app.internalerror = internalerror

main = app.cgirun()<|endoftext|>


<commit_before>from Tkinter import *
import tkFont
import sys

win = Tk()

myFont = tkFont.Font(family = 'Helvetica', size = 36, weight = 'bold')

def helloPress():
	print("Hey there, lovely human!")

def exitProgram():
	print("Exit button pressed")
	win.quit()

win.title("ReFilament PLA recycler") #shows up on the top bar
win.geometry('800x480') #This seems to be good for the touchscreen, so I'm not gonna mess with it

exitButton = Button(win, text = "Exit", font = myFont, command = exitProgram, height = 2, width = 6)
exitButton.pack(side = BOTTOM) #if not attached to a specific side, Exit will appear on top as the first button initialized

helloButton = Button(win, text = "Hiii!", font = myFont, command = helloPress, height = 2, width = 8)
helloButton.pack() #initializes the button at the top b/c it's the first button not attached to a side

mainloop() #Window doesn't open without this<commit_msg>Final comments on GUI example<commit_after>from Tkinter import *
import tkFont
import sys

win = Tk()

myFont = tkFont.Font(family = 'Roboto', size = 36, weight = 'bold') #this font makes Isaac happy

def helloPress():
	print("Hey there, lovely human!") #prints to the console. I'm curious about printing to the GUI itself...but that might not be relevant right now

def exitProgram():
	print("Exit button pressed")
	win.quit() #closes the window

win.title("ReFilament PLA recycler") #shows up on the top bar
win.geometry('800x480') #This seems to be good for the touchscreen, so I'm not gonna mess with it

exitButton = Button(win, text = "Exit", font = myFont, command = exitProgram, height = 2, width = 6)
exitButton.pack(side = BOTTOM) #if not attached to a specific side, Exit will appear on top as the first button initialized

helloButton = Button(win, text = "Hiii!", font = myFont, command = helloPress, height = 2, width = 8)
helloButton.pack() #initializes the button at the top b/c it's the first button not attached to a side

mainloop() #Window doesn't open without this<|endoftext|>


<commit_before>'''A GUI program to analyze data from the geiger counter experiment'''

# The GUI package for python
import Tkinter as tk
import tkFileDialog as tkfd
import tkMessageBox as tkmb
import tkSimpleDialog as tksd

# Our analysis tools
import analyzeData as ad
import PlotData as pd

class App:
    '''The driver class for the program, which contains all of the methods and
    GUI elements for the program'''

    def __init__(self, master):
        '''Creates a new App window from scratch'''

        #save the root TK frame
        self.root = master

        #create a frame for all of the buttons
        frame = tk.Frame(self.root)
        frame.pack()

        #Quit button
        self.quitButton = tk.Button(frame, text="Quit", fg="red", command=frame.quit)
        self.quitButton.pack(side=tk.LEFT)

        #label to display the name of the currently loaded file
        self.fileName = tk.Label(frame, text="No File")
        self.fileName.pack(side=tk.BOTTOM)

        #frame to hold the analysis buttons
        buttonFrame = tk.Frame(frame)

        #add all of the buttons for analysis
        self.addMenuButtons(frame)
        buttonFrame.pack(side=tk.LEFT)

        #the DataSet that is being analyzed
        self.dataSet = None

        #label for .wav file import progress
        self.progressLabel = None

    def addMenuButtons(self, master):
        '''Add the standard set of analysis buttons to the given master frame.'''

        #list of buttons and associated actions to execute on click
        buttons = [
            ("Import .wav File", self.importWavFile),
            ("Import Saved Data", self.openBinary),
            ("Save Data to Disk", self.saveBinary),
            ("Plot Count Rate vs. Time", self.getCountRate),
            ("Plot Count Rate Histogram", self.getCountRateHist),
            ("Plot Intervals Histogram", self.getIntervals),
            ("Get Total Counts", self.getTotalCounts)
        ]

        #create the buttons
        for label, cmd in buttons:
            b = tk.Button(master, text=label, command=cmd)
            b.pack(anchor=tk.S)

    def importWavFile(self):
        '''Get the data from a .wav file. Prompts the user with a file dialog.
        Prompts the user for a threshold value.  This is the value of the .wav
        data that will trigger a count (higher = stricter, fewer counts detected).'''

        #prompt for file name
        filename = tkfd.askopenfilename(title="Pick your .wav file", initialdir=".", parent=self.root)
        print filename

        #grab the data rate (points per second) and a list of data
        rate, wavData = ad.DataSet.readWaveFile(filename)

        #grab threshold from user
        labelText = "Enter the threshold for detecting a count"
        threshold = tksd.askinteger("Threshold", labelText, parent=self.root, minvalue=0)
        if not threshold:
            return

        #grab samples per count from user
        labelText = "Enter the samples per count for detecting multiple counts faster than the discriminator will tell you"
        samplesPerCount = tksd.askinteger("Samples per Count", labelText, parent=self.root, minvalue=0)
        if not samplesPerCount:
            return

        #list of the time of each count
        times = []

        # label for showing import progress
        if self.progressLabel: # if it already exists
            pass
        else:
            self.progressLabel = tk.Label(self.root)
            self.progressLabel.pack(side=tk.BOTTOM)

        #boolean for if the current data is during a count or not during a count
        # 0 means no count, 1 means count
        aboveThreshold = 0

        #loop through data and grab count times
        for i, level in enumerate(wavData):
            #update the progress label every second (i % rate == 0)
            if i % rate == 0:
                self.updateFileProgress(self.progressLabel, i, len(wavData))
                self.root.update_idletasks()
                print "gui reached ", i, "data points"

            #check if the current data level is above the threshold
            aboveThreshold = ad.DataSet.fromWaveData(i, level, aboveThreshold, times, rate, samplesPerCount, threshold)

        #when the loop is finished, update the label one last time
        self.progressLabel.configure(text="Import Progress: 100%")

        print "numCounts = " + str(len(times))

        #length of file (in seconds) is used in class ad.DataSet
        fileLength = float(len(wavData))/float(rate)

        # create DataSet
        self.dataSet = ad.DataSet(times, rate, fileLength)
        print "imported"

        #display the name of the current file in a label
        self.updateFileLabel(filename)

    def updateFileProgress(self, label, value, maximum):
        '''Updates the label with the expression "Progress: <percent complete>%",
        where <percent complete> is the first two characters of value/maximum'''

        text = "Progress: " + str(value/float(maximum) * 100)[0:2] + "%"
        label.configure(text=text)

    def getCountRate(self):
        '''Plots the count rate as a function of time. The rates are calculated
        for each "bin" (i.e. independent sample)'''

        #Check if data has been imported. if not, give a warning
        if self.dataSet:

            #prompt for desired bin spacing
            labelText = "Enter the desired sample length in seconds"
            binSpacing = tksd.askfloat("Count Rate", labelText, parent=self.root, minvalue=0)
            if not binSpacing:
                return

            #plot the count rate in matplotlib
            pd.plotCountRate(self.dataSet, binSpacing)

        else:
            #say that you need to import data first
            self.showImportAlert()

    def getCountRateHist(self):
        '''Plots a histogram of the count rate.  The number of bins is
        for the histogram, and the sample length is how long the count rate
        is averaged over (equivalent to "sample length" for the count rate
        vs. time graph.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #ask for number of bins for histogram
            labelText = "Enter the number of bins"
            numBins = tksd.askinteger("Count Rate Histogram", labelText, parent=self.root, minvalue=1)
            if not numBins:
                return

            #ask for length of sample to calculate count rate
            labelText = "Enter the sample length (seconds)"
            sampleLength = tksd.askfloat("Sample Length", labelText, parent=self.root, minvalue=0)
            if not sampleLength:
                return

            #plot histogram in matplotlib
            pd.plotHistOfCountRates(self.dataSet, sampleLength, numBins)

        else:
            self.showImportAlert()

    def getIntervals(self):
        '''Plots a histogram of the time interval length between consecutive
        counts.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #ask for the number of bins for the histogram
            labelText = "Enter the desired number of bins in the histogram"
            numBins = tksd.askinteger("Intervals Histogram", labelText, parent=self.root, minvalue=1)
            if not numBins:
                return

            #plot the histogram in matplotlib
            pd.plotHistOfIntervals(self.dataSet, numBins)

        else:
            self.showImportAlert()

    def getTotalCounts(self):
        '''Displays the total number of counts in a given sample'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #fetch the value from the stored data
            totalCounts = self.dataSet.getTotalCounts()

            #display the value in a window
            print totalCounts
            tkmb.showinfo("Total counts", str(totalCounts) + " counts total")

        else:
            self.showImportAlert()

    def saveBinary(self):
        '''Saves the currently imported data in a binary file for easy import
        in the future. Prompts for a file name in a dialog.
        This is much faster than importing from .wav file so it should be
        used every time except for the first that the data is imported.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #prompt for the save location
            filename = tkfd.asksaveasfilename(initialdir=".", title="Save Data")
            self.dataSet.save(filename)
            print "saved"

        else:
            #say that you need to import data first
            self.showImportAlert()

    def openBinary(self):
        '''Imports a previously-saved binary file containing a data set.
        This is much faster than importing from .wav file so it should be
        used every time except for the first that the data is imported.'''

        #prompt for file name
        filename = tkfd.askopenfilename(initialdir=".", title="Open File")

        #import the file and record the DataSet
        self.dataSet = ad.DataSet.fromSavedFile(filename)
        print "opened"

        #update the label showing the current file
        self.updateFileLabel(filename)

    def showImportAlert(self):
        '''Show an alert dialog indicating there is no active data.'''

        #show the alert dialog
        tkmb.showerror("No Data", "You need to import data first!")

    def updateFileLabel(self, filename):
        '''Update the label that displays the currently active file.'''

        #show the first directory in the path and the file name:
        # e.g. Users/.../data.wav
        # or Users\...\data.wav

        #different file separator for windows and unix
        #first, unix
        if(filename.find("/") >= 0):
            path = filename.split("/")
            self.fileName.configure(text=path[1] + "/.../" + path[len(path)-1])
        else:
            #escape backslashes! \ => \\
            path = filename.split("\\")
            self.fileName.configure(text=path[1] + "\\...\\" + path[len(path)-1])

# Create the Tk application window
root = tk.Tk()

# Create the App which is defined above
app = App(root)

# Give the app window a title
app.root.title("Geiger Counter Analysis")

# Run the app (mainloop is tk syntax for "go")
root.mainloop()
<commit_msg>Updated default values and labels for import .wav<commit_after>'''A GUI program to analyze data from the geiger counter experiment'''

# The GUI package for python
import Tkinter as tk
import tkFileDialog as tkfd
import tkMessageBox as tkmb
import tkSimpleDialog as tksd

# Our analysis tools
import analyzeData as ad
import PlotData as pd

class App:
    '''The driver class for the program, which contains all of the methods and
    GUI elements for the program'''

    def __init__(self, master):
        '''Creates a new App window from scratch'''

        #save the root TK frame
        self.root = master

        #create a frame for all of the buttons
        frame = tk.Frame(self.root)
        frame.pack()

        #Quit button
        self.quitButton = tk.Button(frame, text="Quit", fg="red", command=frame.quit)
        self.quitButton.pack(side=tk.LEFT)

        #label to display the name of the currently loaded file
        self.fileName = tk.Label(frame, text="No File")
        self.fileName.pack(side=tk.BOTTOM)

        #frame to hold the analysis buttons
        buttonFrame = tk.Frame(frame)

        #add all of the buttons for analysis
        self.addMenuButtons(frame)
        buttonFrame.pack(side=tk.LEFT)

        #the DataSet that is being analyzed
        self.dataSet = None

        #label for .wav file import progress
        self.progressLabel = None

    def addMenuButtons(self, master):
        '''Add the standard set of analysis buttons to the given master frame.'''

        #list of buttons and associated actions to execute on click
        buttons = [
            ("Import .wav File", self.importWavFile),
            ("Import Saved Data", self.openBinary),
            ("Save Data to Disk", self.saveBinary),
            ("Plot Count Rate vs. Time", self.getCountRate),
            ("Plot Count Rate Histogram", self.getCountRateHist),
            ("Plot Intervals Histogram", self.getIntervals),
            ("Get Total Counts", self.getTotalCounts)
        ]

        #create the buttons
        for label, cmd in buttons:
            b = tk.Button(master, text=label, command=cmd)
            b.pack(anchor=tk.S)

    def importWavFile(self):
        '''Get the data from a .wav file. Prompts the user with a file dialog.
        Prompts the user for a threshold value.  This is the value of the .wav
        data that will trigger a count (higher = stricter, fewer counts detected).'''

        #prompt for file name
        filename = tkfd.askopenfilename(title="Pick your .wav file", initialdir=".", parent=self.root)
        print filename

        #grab the data rate (points per second) and a list of data
        rate, wavData = ad.DataSet.readWaveFile(filename)

        #grab threshold from user
        labelText = "Enter the threshold for detecting a count. If you don't know what this means, read the lab manual!"
        threshold = tksd.askinteger("Threshold", labelText, parent=self.root, minvalue=0, initialvalue=15000)
        if not threshold:
            return

        #grab samples per count from user
        labelText = "Enter the samples per count for detecting multiple counts faster than the discriminator will tell you. If you don't know what this means, read the lab manual!"
        samplesPerCount = tksd.askinteger("Samples per Count", labelText, parent=self.root, minvalue=0, initialvalue=25)
        if not samplesPerCount:
            return

        #list of the time of each count
        times = []

        # label for showing import progress
        if self.progressLabel: # if it already exists
            pass
        else:
            self.progressLabel = tk.Label(self.root)
            self.progressLabel.pack(side=tk.BOTTOM)

        #boolean for if the current data is during a count or not during a count
        # 0 means no count, 1 means count
        aboveThreshold = 0

        #loop through data and grab count times
        for i, level in enumerate(wavData):
            #update the progress label every second (i % rate == 0)
            if i % rate == 0:
                self.updateFileProgress(self.progressLabel, i, len(wavData))
                self.root.update_idletasks()
                print "gui reached ", i, "data points"

            #check if the current data level is above the threshold
            aboveThreshold = ad.DataSet.fromWaveData(i, level, aboveThreshold, times, rate, samplesPerCount, threshold)

        #when the loop is finished, update the label one last time
        self.progressLabel.configure(text="Import Progress: 100%")

        print "numCounts = " + str(len(times))

        #length of file (in seconds) is used in class ad.DataSet
        fileLength = float(len(wavData))/float(rate)

        # create DataSet
        self.dataSet = ad.DataSet(times, rate, fileLength)
        print "imported"

        #display the name of the current file in a label
        self.updateFileLabel(filename)

    def updateFileProgress(self, label, value, maximum):
        '''Updates the label with the expression "Progress: <percent complete>%",
        where <percent complete> is the first two characters of value/maximum'''

        text = "Progress: " + str(value/float(maximum) * 100)[0:2] + "%"
        label.configure(text=text)

    def getCountRate(self):
        '''Plots the count rate as a function of time. The rates are calculated
        for each "bin" (i.e. independent sample)'''

        #Check if data has been imported. if not, give a warning
        if self.dataSet:

            #prompt for desired bin spacing
            labelText = "Enter the desired sample length in seconds"
            binSpacing = tksd.askfloat("Count Rate", labelText, parent=self.root, minvalue=0)
            if not binSpacing:
                return

            #plot the count rate in matplotlib
            pd.plotCountRate(self.dataSet, binSpacing)

        else:
            #say that you need to import data first
            self.showImportAlert()

    def getCountRateHist(self):
        '''Plots a histogram of the count rate.  The number of bins is
        for the histogram, and the sample length is how long the count rate
        is averaged over (equivalent to "sample length" for the count rate
        vs. time graph.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #ask for number of bins for histogram
            labelText = "Enter the number of bins"
            numBins = tksd.askinteger("Count Rate Histogram", labelText, parent=self.root, minvalue=1)
            if not numBins:
                return

            #ask for length of sample to calculate count rate
            labelText = "Enter the sample length (seconds)"
            sampleLength = tksd.askfloat("Sample Length", labelText, parent=self.root, minvalue=0)
            if not sampleLength:
                return

            #plot histogram in matplotlib
            pd.plotHistOfCountRates(self.dataSet, sampleLength, numBins)

        else:
            self.showImportAlert()

    def getIntervals(self):
        '''Plots a histogram of the time interval length between consecutive
        counts.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #ask for the number of bins for the histogram
            labelText = "Enter the desired number of bins in the histogram"
            numBins = tksd.askinteger("Intervals Histogram", labelText, parent=self.root, minvalue=1)
            if not numBins:
                return

            #plot the histogram in matplotlib
            pd.plotHistOfIntervals(self.dataSet, numBins)

        else:
            self.showImportAlert()

    def getTotalCounts(self):
        '''Displays the total number of counts in a given sample'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #fetch the value from the stored data
            totalCounts = self.dataSet.getTotalCounts()

            #display the value in a window
            print totalCounts
            tkmb.showinfo("Total counts", str(totalCounts) + " counts total")

        else:
            self.showImportAlert()

    def saveBinary(self):
        '''Saves the currently imported data in a binary file for easy import
        in the future. Prompts for a file name in a dialog.
        This is much faster than importing from .wav file so it should be
        used every time except for the first that the data is imported.'''

        #check if data has been imported. if not, give a warning
        if self.dataSet:

            #prompt for the save location
            filename = tkfd.asksaveasfilename(initialdir=".", title="Save Data")
            self.dataSet.save(filename)
            print "saved"

        else:
            #say that you need to import data first
            self.showImportAlert()

    def openBinary(self):
        '''Imports a previously-saved binary file containing a data set.
        This is much faster than importing from .wav file so it should be
        used every time except for the first that the data is imported.'''

        #prompt for file name
        filename = tkfd.askopenfilename(initialdir=".", title="Open File")

        #import the file and record the DataSet
        self.dataSet = ad.DataSet.fromSavedFile(filename)
        print "opened"

        #update the label showing the current file
        self.updateFileLabel(filename)

    def showImportAlert(self):
        '''Show an alert dialog indicating there is no active data.'''

        #show the alert dialog
        tkmb.showerror("No Data", "You need to import data first!")

    def updateFileLabel(self, filename):
        '''Update the label that displays the currently active file.'''

        #show the first directory in the path and the file name:
        # e.g. Users/.../data.wav
        # or Users\...\data.wav

        #different file separator for windows and unix
        #first, unix
        if(filename.find("/") >= 0):
            path = filename.split("/")
            self.fileName.configure(text=path[1] + "/.../" + path[len(path)-1])
        else:
            #escape backslashes! \ => \\
            path = filename.split("\\")
            self.fileName.configure(text=path[1] + "\\...\\" + path[len(path)-1])

# Create the Tk application window
root = tk.Tk()

# Create the App which is defined above
app = App(root)

# Give the app window a title
app.root.title("Geiger Counter Analysis")

# Run the app (mainloop is tk syntax for "go")
root.mainloop()
<|endoftext|>


<commit_before>import sys
import json
import random
import io
import os
# One more thing - Bing Han

def random_modulo():
  return random.randint(5,15)

def gen_quote():
# We are what we repeatedly do; excellence, then, is not an act but a habit. - Kane
  random_author = random.randint(0,len(author)-1)
  random_quote = random.randint(0,len(bajson_quotes)-1)
  return bajson_quotes[random_quote] + " - " + author[random_author]

def write_file(stringy_string,namy_name):
# The richest man is not he who has the most, but he who needs the least. - Soulja Boy
	os.remove(namy_name) #removes file path from name_name
	text_file = open(namy_name, "w")
	text_file.write(stringy_string)
	text_file.close()

# Snow mexicans, you're getting a wall too! - Undertaker
def do_the_whole_shabang(filename):
  counter = 0
  modulo = random_modulo()
  full_file = ""
  for line in open(filename):
# It's not a muslim ban - Ch@tM@n
    counter += 1
    full_file = full_file + line
    if (counter % modulo == 0):
    	full_file = full_file + smajson[filename[filename.index('.')+1:]] + " " + gen_quote() + "\n"
  write_file(full_file,filename)
# What is a private email server? - Operah Winfrey

def smajson():
	return {"java":"//","py":"#","rb":"#","cpp":"//","tex":"%","js":"//","o":"#"}

def author():
# YES we can - Sarah Palin
	return ["Ivanka Trump","The Purple Teletubby","Dog The Bount Hunter","Master Yoda","Abe Lincoln","Stev-o","Wee-man","Albus Dumbledore","Satan","Momo Taleb","Clyde Frog","Undertaker","John Cena","Triple H","Kane","Big Show","The Rock","Bing Han","Big Cass","Sarah Palin","Dj Khaled","21 Savage","Sugar Ray Robinson","Soulja Boy","Betsy DeVos","The Red Power Ranger","Oprah Winfrey"]

def bajson_quotes():
	return [
	  "The ode lives upon the ideal, the epic upon the grandiose, the drama upon the real."
# You must not lose faith in humanity. Humanity is an ocean; if a few drops of the ocean are dirty, the ocean does not become dirty. - Betsy DeVos
	  ,"If we don't study the mistakes of the future we're doomed to repeat them for the first time."
	  ,"I love hookers and blow."
	  ,"C++ supports OOP"
	  ,"You can do anything, but not everything."
	  ,"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."
	  ,"The richest man is not he who has the most, but he who needs the least."
	  ,"You miss 100 percent of the shots you never take."
# I love hookers and blow. - Dj Khaled
	  ,"Courage is not the absence of fear, but rather the judgement that something else is more important than fear."
	  ,"You must be the change you wish to see in the world."
	  ,"When hungry, eat your rice; when tired, close your eyes. Fools may laugh at me, but wise men will know what I mean."
	  ,"To the man who only has a hammer, everything he encounters begins to look like a nail."
	  ,"We are what we repeatedly do; excellence, then, is not an act but a habit."
# One more thing - The Rock
	  ,"You must be the change you wish to see in the world."
	  ,"The weak can never forgive. Forgiveness is the attribute of the strong."
	  ,"Happiness is when what you think, what you say, and what you do are in harmony."
	  ,"An eye for eye only ends up making the whole world blind."
# First they ignore you, then they laugh at you, then they fight you, then you win. - John Cena
	  ,"Live as if you were to die tomorrow; learn as if you were to live forever."
	  ,"First they ignore you, then they laugh at you, then they fight you, then you win."
	  ,"You must not lose faith in humanity. Humanity is an ocean; if a few drops of the ocean are dirty, the ocean does not become dirty."
	  ,"The best way to find yourself is to lose yourself in the service of others."
	  ,"Strength does not come from physical capacity. It comes from an indomitable will."
# It's local on the the remote server - Soulja Boy
	  ,"A man is but the product of his thoughts; what he thinks, he becomes."
	  ,"YES we can"
	  ,"No we can't"
	  ,"Those were alternative facts"
	  ,"Don't force me to give you the D"
# Those were alternative facts - Undertaker
	  ,"You can't see me"
	  ,"I have a dream"
	  ,"In god we trust"
	  ,"Thou shall not pass"
	  ,"What is a private email server?"
# An eye for eye only ends up making the whole world blind. - Operah Winfrey
	  ,"It's local on the the remote server"
	  ,"It's not a muslim ban"
	  ,"Snow mexicans, you're getting a wall too!"
	  ,"Don't ever play yourself"
	  ,"Just play. Have fun. Enjoy the game."
# The ode lives upon the ideal, the epic upon the grandiose, the drama upon the real. - Famingo
	  ,"'Sexy' is being independent, being confident and having fun."
	  ,"It's kind of fun to do the impossible."
	  ,"We gucci Fam - Ghandi"
	  ,"I want my world to be fun."
	  ,"Everyone gets a car"
# When hungry, eat your rice; when tired, close your eyes. Fools may laugh at me, but wise men will know what I mean. - Ch@tM@n
	  ,"One more thing"
	  ,"Wrong"
	  ,"Such a nasty woman"
	  ,"Bazinga!"
	  ,"You shall not pass!"
	  ,"Wingardium leviosa"
	]
# We are what we repeatedly do; excellence, then, is not an act but a habit. - W@rri0r

smajson = smajson()
author = author()
bajson_quotes = bajson_quotes()

# Wrong - Sarah Palin
if (len(sys.argv) > 1):
  do_the_whole_shabang(sys.argv[1])
<commit_msg>Delete main.py<commit_after><|endoftext|>


<commit_before>import os
import json
import threading
from flask import Response, request, Flask, render_template, send_from_directory, redirect
from decorators import crossdomain
from config.config import CONFIG_VARS as cvar
from flask.ext.sqlalchemy import SQLAlchemy
from urlparse import urlparse

# Initialize daily/hourly tasks queue loop
if not cvar['DEBUG']:
    from tasks.maintainence import queue_daily_tasks
    threading.Thread(target=queue_daily_tasks).start()
    threading.Timer(60*60*24, queue_daily_tasks).start()

app = Flask(__name__, static_folder='static')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['HEROKU_POSTGRESQL_ONYX_URL']
db = SQLAlchemy(app)

@app.route("/", methods=['GET', 'POST'])
def apps_index():
    try:
        client_id = os.environ['IONITRON_ISSUES_CLIENT_ID']
        client_secret = os.environ['IONITRON_ISSUES_CLIENT_SECRET']
        code = request.args.get('code')
        if not code:
            # not signed in
            return redirect('https://github.com/login/oauth/authorize?client_id=%s' % (client_id))

        payload = {
            "client_id": client_id,
            "client_secret": client_secret,
            "code": code
        }
        url = 'https://github.com/login/oauth/access_token'
        rsp = requests.get(url, payload=payload)
        rsp_dict = urlparse.parse_qs(rsp)
        print rsp_dict

        return render_template('index.html')
    except Exception as ex:
        print 'index %s' % ex

@app.route('/<path:filename>')
def send_file(filename):
    return send_from_directory(app.static_folder, filename)

@app.route("/api/<path:repo_username>/<path:repo_id>/<path:number>/maintainence", methods=['GET', 'POST'])
def issue_maintainence(repo_username, repo_id, number):
    data = {}
    try:
        from tasks.maintainence import issue_maintainence_number
        data = issue_maintainence_number(repo_username, repo_id, number)
    except Exception as ex:
        print 'issue_maintainence error: %s' % ex
        data['error'] = '%s' % ex
    return Response(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')), mimetype='application/json')

@app.route("/api/maintainence", methods=['GET', 'POST'])
def all_issues_maintainence():
    data = {}
    try:
        from tasks.maintainence import run_maintainence_tasks
        t = threading.Thread(target=run_maintainence_tasks)
        t.start()
        data['message'] = 'all_issues_maintainence task forked to background'
    except Exception as ex:
        print 'all_issues_maintainence error: %s' % ex
        data['error'] = '%s' % ex
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/api/<path:repo_username>/<path:repo_id>/issue-scores", methods=['GET', 'POST'])
def get_issue_scores(repo_username, repo_id):
    """
    Gets the scores calculated for all open issues.
    """
    data = {}
    try:
        from tasks.issue_scores import get_issue_scores
        data = get_issue_scores(repo_username, repo_id)
    except Exception as ex:
        print 'get_issue_scores error: %s' % ex
        data = { 'error' : '%s' % ex }
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/api/<path:repo_username>/<path:repo_id>/issue-response", methods=['POST'])
def issue_response(repo_username, repo_id):
    data = {}
    try:
        from tasks.send_response import submit_issue_response
        payload = json.loads(request.data)
        data = submit_issue_response(repo_username,
                                     repo_id,
                                     payload.get('number'),
                                     payload.get('action_type'),
                                     payload.get('message_type'),
                                     payload.get('custom_message'))
    except Exception as ex:
        print 'issue_response error: %s' % ex
        data = { 'error' : '%s' % ex }
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/webhook", methods=['GET', 'POST', 'OPTIONS'])
@crossdomain(origin='*', headers=['Content-Type', 'X-Github-Event'])
def github_webhook():
    data = {}
    try:
        event_type = request.headers.get('X-Github-Event')
        if event_type and request.data:
            from tasks.webhooks import receive_webhook
            data = receive_webhook(event_type, json.loads(request.data))
        else:
            data['error'] = 'missing event_type or request.data'

    except Exception as ex:
        print 'github_webhook error: %s' % ex
        data['error'] = '%s' % ex

    return Response(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')), mimetype='application/json')

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    print 'Server started, port %s' % port
    app.run(host='0.0.0.0', port=port)
<commit_msg>import requests<commit_after>import os
import json
import threading
from flask import Response, request, Flask, render_template, send_from_directory, redirect
from decorators import crossdomain
from config.config import CONFIG_VARS as cvar
from flask.ext.sqlalchemy import SQLAlchemy
from urlparse import urlparse
import requests

# Initialize daily/hourly tasks queue loop
if not cvar['DEBUG']:
    from tasks.maintainence import queue_daily_tasks
    threading.Thread(target=queue_daily_tasks).start()
    threading.Timer(60*60*24, queue_daily_tasks).start()

app = Flask(__name__, static_folder='static')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['HEROKU_POSTGRESQL_ONYX_URL']
db = SQLAlchemy(app)

@app.route("/", methods=['GET', 'POST'])
def apps_index():
    try:
        client_id = os.environ['IONITRON_ISSUES_CLIENT_ID']
        client_secret = os.environ['IONITRON_ISSUES_CLIENT_SECRET']
        code = request.args.get('code')
        if not code:
            # not signed in
            return redirect('https://github.com/login/oauth/authorize?client_id=%s' % (client_id))

        payload = {
            "client_id": client_id,
            "client_secret": client_secret,
            "code": code
        }
        url = 'https://github.com/login/oauth/access_token'
        rsp = requests.get(url, payload=payload)
        rsp_dict = urlparse.parse_qs(rsp)
        print rsp_dict

        return render_template('index.html')
    except Exception as ex:
        print 'index %s' % ex

@app.route('/<path:filename>')
def send_file(filename):
    return send_from_directory(app.static_folder, filename)

@app.route("/api/<path:repo_username>/<path:repo_id>/<path:number>/maintainence", methods=['GET', 'POST'])
def issue_maintainence(repo_username, repo_id, number):
    data = {}
    try:
        from tasks.maintainence import issue_maintainence_number
        data = issue_maintainence_number(repo_username, repo_id, number)
    except Exception as ex:
        print 'issue_maintainence error: %s' % ex
        data['error'] = '%s' % ex
    return Response(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')), mimetype='application/json')

@app.route("/api/maintainence", methods=['GET', 'POST'])
def all_issues_maintainence():
    data = {}
    try:
        from tasks.maintainence import run_maintainence_tasks
        t = threading.Thread(target=run_maintainence_tasks)
        t.start()
        data['message'] = 'all_issues_maintainence task forked to background'
    except Exception as ex:
        print 'all_issues_maintainence error: %s' % ex
        data['error'] = '%s' % ex
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/api/<path:repo_username>/<path:repo_id>/issue-scores", methods=['GET', 'POST'])
def get_issue_scores(repo_username, repo_id):
    """
    Gets the scores calculated for all open issues.
    """
    data = {}
    try:
        from tasks.issue_scores import get_issue_scores
        data = get_issue_scores(repo_username, repo_id)
    except Exception as ex:
        print 'get_issue_scores error: %s' % ex
        data = { 'error' : '%s' % ex }
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/api/<path:repo_username>/<path:repo_id>/issue-response", methods=['POST'])
def issue_response(repo_username, repo_id):
    data = {}
    try:
        from tasks.send_response import submit_issue_response
        payload = json.loads(request.data)
        data = submit_issue_response(repo_username,
                                     repo_id,
                                     payload.get('number'),
                                     payload.get('action_type'),
                                     payload.get('message_type'),
                                     payload.get('custom_message'))
    except Exception as ex:
        print 'issue_response error: %s' % ex
        data = { 'error' : '%s' % ex }
    return Response(json.dumps(data), mimetype='application/json')

@app.route("/webhook", methods=['GET', 'POST', 'OPTIONS'])
@crossdomain(origin='*', headers=['Content-Type', 'X-Github-Event'])
def github_webhook():
    data = {}
    try:
        event_type = request.headers.get('X-Github-Event')
        if event_type and request.data:
            from tasks.webhooks import receive_webhook
            data = receive_webhook(event_type, json.loads(request.data))
        else:
            data['error'] = 'missing event_type or request.data'

    except Exception as ex:
        print 'github_webhook error: %s' % ex
        data['error'] = '%s' % ex

    return Response(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')), mimetype='application/json')

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    print 'Server started, port %s' % port
    app.run(host='0.0.0.0', port=port)
<|endoftext|>


<commit_before># Genetic algorithm to generate 6 sided shapes. Fitness score is determined by
# regularity of angles. That is, it should generate a near perfect hexagon.

# Chromosones are a list of XY coordinates.
# More or less 6 genes, each with an XY pair defining the vertex.

# Simple roulette wheel selection.

# Fitness score in pseudocode. Lower is better.
# for genes in chromosone:
#   total_deviation += math.abs(gene_vertex.angle)

# There'll be 32 members of the population per generation.

import random
import math
from collections import namedtuple

Vertex = namedtuple('vertex', 'x y')
# This'll make the vertex tuple that we'll use for the chromosones.

# Example chromosone
# [vertex(1, 5), vertex(2, 6), vertex(8, 3), vertex(2, 1), vertex(8, 7),
#  vertex(3, 2)]

# class A(object):
#     def __init__(self):
#         pass

class Individual():
    'Individuals for genetic algorithm. Has chromosone and related functions.'
    def chromosonegen():
        """Make random chromosones, coord x, y | 0 < x < 10 """
        vert1 = Vertex(random.random()*10,
                       random.random()*10)
        vert2 = Vertex(random.random()*10,
                       random.random()*10)
        vert3 = Vertex(random.random()*10,
                       random.random()*10)
        vert4 = Vertex(random.random()*10,
                       random.random()*10)
        vert5 = Vertex(random.random()*10,
                       random.random()*10)
        vert6 = Vertex(random.random()*10,
                       random.random()*10)
        return [vert1, vert2, vert3, vert4, vert5, vert6]

    def __init__(self, input_chromosone=chromosonegen()):
        self.chromosone = input_chromosone
        self.mutation_rate = 0.02

def point_swap(input_chromosone, outside_chromosone):
    """Swaps genes between two points in an input and output chromosone"""
    swap_pos = random.randrange(1, 5, 1)  # Randomly picks pos to swap at
    return input_chromosone[:swap_pos] + outside_chromosone[swap_pos:]  # swaps

def evaluator(to_eval):
    x = to_eval.chromosone
    angle_set = [find_angle(x[5], x[0], x[1]),  # Run the find angle function
                 find_angle(x[0], x[1], x[2]),  # with all the vertcies
                 find_angle(x[1], x[2], x[3]),
                 find_angle(x[2], x[3], x[4]),
                 find_angle(x[3], x[4], x[5]),
                 find_angle(x[4], x[5], x[0])]
    total_error = 0
    for y in angle_set:
        total_error += math.fabs(60-y)  # Calculate total error with abs(60-y)
    return total_error

def find_angle(vertA, vertB, vertC):
    # AB and BC is leg, CA is hypotenuse
    # Find distance of segments between that vertex and neightboring ones
    ab_dist = math.sqrt((vertB.x-vertA.x)**2 + (vertB.y - vertA.y)**2)
    bc_dist = math.sqrt((vertC.x-vertB.x)**2 + (vertC.y - vertB.y)**2)
    ca_dist = math.sqrt((vertA.x-vertC.x)**2 + (vertA.y - vertC.y)**2)
    # Calculate the angle (in radians)
    rad_angle = math.acos((ab_dist**2 + bc_dist**2 - ca_dist**2) /
                          (2*(ab_dist*bc_dist)))
    deg_angle = rad_angle * (180/math.pi)  # Change angle to degrees

    return deg_angle

# Just some tests
test_case = Individual()
print test_case.chromosone
print evaluator(test_case)
<commit_msg>Moved to python 3.4, added functionality for roulette wheel selection<commit_after># Genetic algorithm to generate 6 sided shapes. Fitness score is determined by
# regularity of angles. That is, it should generate a near perfect hexagon.

# Chromosones are a list of XY coordinates.
# More or less 6 genes, each with an XY pair defining the vertex.

# Simple roulette wheel selection.

# Fitness score in pseudocode. Lower is better.
# for genes in chromosone:
#   total_deviation += math.abs(gene_vertex.angle)

# There'll be 32 members of the population per generation.

import random
import math
from collections import namedtuple
Vertex = namedtuple('vertex', 'x y')
# This'll make the vertex tuple that we'll use for the chromosones.

# Example chromosone
# [vertex(1, 5), vertex(2, 6), vertex(8, 3), vertex(2, 1), vertex(8, 7),
#  vertex(3, 2)]

# class A(object):
#     def __init__(self):
#         pass

def varstore():
    varstore.mutation_rate = 0.02

class Individual():
    'Individuals for genetic algorithm. Has chromosone and related functions.'
    def chromosonegen():
        """Make random chromosones, coord x, y | 0 < x < 10 """
        vert1 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        vert2 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        vert3 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        vert4 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        vert5 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        vert6 = Vertex(round(random.random()*10, 3),
                       round(random.random()*10, 3))
        return [vert1, vert2, vert3, vert4, vert5, vert6]

    def __init__(self, input_chromosone=chromosonegen()):
        self.chromosone = input_chromosone

def point_swap(input_chromosone, outside_chromosone):
    """Swaps genes between two points in an input and output chromosone"""
    swap_pos = random.randrange(1, 5, 1)  # Randomly picks pos to swap at
    return input_chromosone[:swap_pos] + outside_chromosone[swap_pos:]  # swaps

def fragment_return(chromosone, startpos, endpos):
    return chromosone[startpos:endpos]

def evaluator(to_eval):
    x = to_eval.chromosone
    angle_set = [find_angle(x[5], x[0], x[1]),  # Run the find angle function
                 find_angle(x[0], x[1], x[2]),  # with all the vertcies
                 find_angle(x[1], x[2], x[3]),
                 find_angle(x[2], x[3], x[4]),
                 find_angle(x[3], x[4], x[5]),
                 find_angle(x[4], x[5], x[0])]
    total_error = 0
    for y in angle_set:
        total_error += math.fabs(60-y)  # Calculate total error with abs(60-y)
    return total_error

def find_angle(vertA, vertB, vertC):
    # AB and BC is leg, CA is hypotenuse
    # Find distance of segments between that vertex and neightboring ones
    ab_dist = math.sqrt((vertB.x-vertA.x)**2 + (vertB.y - vertA.y)**2)
    bc_dist = math.sqrt((vertC.x-vertB.x)**2 + (vertC.y - vertB.y)**2)
    ca_dist = math.sqrt((vertA.x-vertC.x)**2 + (vertA.y - vertC.y)**2)
    # Calculate the angle (in radians)
    rad_angle = math.acos((ab_dist**2 + bc_dist**2 - ca_dist**2) /
                          (2*(ab_dist*bc_dist)))
    deg_angle = rad_angle * (180/math.pi)  # Change angle to degrees

    return deg_angle

def roulette_gene_select(obj_set):  # obj_set is 1d matrix/list with all objects
    fitness_set = {}                # of current generation
    for x in obj_set:
        fitness_set[evaluator(x)] = x

def fitness_select(fitness_dict):
    # How to roulette wheel select:
    # 1. Compute "inverse" fitness score (360 - fitness)
    # 2. Sort list from low to high fitness (maybe high to low, maybe random)
    # 3. find sum of all fitness scores, S
    # 4. Find random number r between 0 and S
    # 5. If fitness value of first object is smaller than r, add second object
    # fitness score. Repeat until greater than r
    # 6. Winner = last object whose fitness score was added (first to go over r)
    print ("")
    adjusted_fitness_list = []
    for x in sorted(fitness_dict):  # step one & 2, sorting high-low
        adjusted_fitness_list = 360-x
    S = 0
    for x in adjusted_fitness_list:  # Step 3
        S += x
    r = random.random()*360  # Step 4
    s = 0  # Used for summing up values until greater than r
    x = 0  # Used for setting lastobj and summing up list stuff
    while s < r:  # Step 5
        s += adjusted_fitness_list[x]  # Step 5 cont
        lastobj = fitness_dict[(adjusted_fitness_list[x]-360) * -1]  # Lastobj
        # used for determining step6
        x += 1
    winner = lastobj  # Step 6
    return winner

# Just some tests
test_case = Individual()
print (test_case.chromosone)
print (evaluator(test_case))
<|endoftext|>