<commit_before>import scipy.stats
import matplotlib.pyplot as plt
import matplotlib.colors
from sar_data import *
from plotting import *

# Ranges defining the forest region of the image
no_change_i = range(307, 455)
no_change_j = range(52, 120)

def aregion(X):
    return X[np.ix_(no_change_i, no_change_j)]

class Gamma(object):
    """
    Test statistic on equality of two Gamma parameters
    Use for change detection between two single channel SAR images X and Y
    n, m are Equivalent Number of Looks (ENL)
    """

    def __init__(self, X, Y, n, m):
        self.X = X
        self.Y = Y
        self.n = n
        self.m = m
        self.Q = Y/X # Test statistic

    def histogram(self, percentile):
        f, ax = plt.subplots(1, 1)
        ax.hist(self.Q.flatten(), bins=100, normed=True, range=(0,5))

        # Fisher's F overlay
        F = scipy.stats.f(2*self.m, 2*self.n)
        x = np.linspace(0, 5, 500)
        ax.plot(x, F.pdf(x))

        # Select threshold from distrib quantile
        t_inf, t_sup = F.ppf(percentile/2), F.ppf(1 - percentile/2)

        ax.axvline(t_inf, 0, 1, color='black', linestyle='--')
        # ax.text(t_inf, 1.12, " 5% percentile")
        ax.axvline(t_sup, 0, 1, color='black', linestyle='--')
        # ax.text(t_sup, 1.12, " 95% percentile")

        return f, ax

    def image_binary(self, percentile):
        F = scipy.stats.f(2*self.m, 2*self.n)
        t_inf, t_sup = F.ppf(percentile/2), F.ppf(1 - percentile/2)

        im = np.zeros_like(self.Q)
        im[self.Q < t_inf] = 1
        im[self.Q > t_sup] = 1

        return im

    def image_linear(self, percentile):
        pass

class Wishart(object):
    def __init__(self, X, Y, n, m):
        self.X = X
        self.Y = Y
        self.n = n
        self.m = m

        p = 3
        detX = determinant(X)
        detY = determinant(Y)
        detXY = determinant(sar_sum(X, Y))

        # Test statistic
        self.lnq = (p*(n+m)*np.log(n+m) - p*n*np.log(n) - p*m*np.log(m)
                + n*np.log(detX) + m*np.log(detY) - (n+m)*np.log(detXY))

        self.rho = 1 - (2*p*p - 1)/(6*p) * (1/n + 1/m - 1/(n+m))

        self.w2 = (-(p*p/4)*(1-1/self.rho)**2
                + p*p*(p*p - 1)/24 * (1/(n*n) + 1/(m*m) - 1/((n+m)**2))*1/(p*p))

    def histogram(self, percent):
        f, ax = plt.subplots(1, 1)
        ax.hist(-2*self.rho*self.lnq.flatten(), bins=100, normed=True)

        # Overlay pdf
        p = 3
        x = np.linspace(0, 50, 1000)
        chi2 = scipy.stats.chi2
        y = chi2.pdf(x, p**2) + self.w2*(chi2.pdf(x, p**2+4) - chi2.pdf(x, p**2))
        ax.plot(x, y)

        return f, ax

    def image_binary(self, percent):
        threshold = 30
        im = np.zeros_like(self.lnq)
        im[-2*self.rho*self.lnq > threshold] = 1
        return im

if __name__ == "__main__":

    # Load data
    april = SARData().load_april()
    may = SARData().load_may()

    # No change region
    april_no_change = region(april, no_change_i, no_change_j)
    may_no_change = region(may, no_change_i, no_change_j)

    # Color composites
    plt.imsave("fig/april.png", color_composite(april))
    plt.imsave("fig/may.png", color_composite(may))

    def gamma_test(april, may, channel, ENL, percent):
        # Data
        X = april.__dict__[channel]
        Y = may.__dict__[channel]
        Xno = aregion(X)
        Yno = aregion(Y)

        # Name variables
        short_channel = channel[:2].upper()
        hist_title = ("Likelihood ratio distribution of no change region {} ENL={}"
            .format(short_channel, ENL))
        hist_filename = "fig/gamma.hist.ENL{0}.{1}.{2:.2f}.png".format(ENL, short_channel, percent)
        im_filename = "fig/gamma.im.ENL{0}.{1}.{2:.2f}.png".format(ENL, short_channel, percent)

        # No change region histogram
        gno = Gamma(Xno, Yno, ENL, ENL)
        f, ax = gno.histogram(percent)
        ax.set_title(hist_title)
        f.savefig(hist_filename)

        # Binary image
        g = Gamma(X, Y, ENL, ENL)
        im = g.image_binary(percent)
        plt.imsave(im_filename, im, cmap='gray')

    gamma_test(april, may, "hhhh", 13, 0.01)
    gamma_test(april, may, "hvhv", 13, 0.01)
    gamma_test(april, may, "vvvv", 13, 0.01)

    gamma_test(april, may, "hhhh", 12, 0.01)
    gamma_test(april, may, "hvhv", 12, 0.01)
    gamma_test(april, may, "vvvv", 12, 0.01)

    # Wishart test

    april_no = region(april, no_change_i, no_change_j)
    may_no = region(may, no_change_i, no_change_j)

    w = Wishart(april, may, 13, 13)
    wno = Wishart(april_no, may_no, 13, 13)

    f, ax = wno.histogram(0.01)
    ax.set_title(r"$-2 \rho \ln Q$ distribution in no change region")
    f.savefig("fig/lnq.hist.png")

    im = w.image_binary(0.30)
    plt.imsave("fig/lnq.png", im, cmap="gray")

    # plt.imsave("fig/lnq.png", im, cmap='gray')
    # plt.close('all')

<commit_msg>added wishart tests with diff ENLs<commit_after>import scipy.stats
import matplotlib.pyplot as plt
import matplotlib.colors
from sar_data import *
from plotting import *

# Ranges defining the forest region of the image
no_change_i = range(307, 455)
no_change_j = range(52, 120)

def aregion(X):
    return X[np.ix_(no_change_i, no_change_j)]

class Gamma(object):
    """
    Test statistic on equality of two Gamma parameters
    Use for change detection between two single channel SAR images X and Y
    n, m are Equivalent Number of Looks (ENL)
    """

    def __init__(self, X, Y, n, m):
        self.X = X
        self.Y = Y
        self.n = n
        self.m = m
        self.Q = Y/X # Test statistic

    def histogram(self, percentile):
        f, ax = plt.subplots(1, 1)
        ax.hist(self.Q.flatten(), bins=100, normed=True, range=(0,5))

        # Fisher's F overlay
        F = scipy.stats.f(2*self.m, 2*self.n)
        x = np.linspace(0, 5, 500)
        ax.plot(x, F.pdf(x))

        # Select threshold from distrib quantile
        t_inf, t_sup = F.ppf(percentile/2), F.ppf(1 - percentile/2)

        ax.axvline(t_inf, 0, 1, color='black', linestyle='--')
        # ax.text(t_inf, 1.12, " 5% percentile")
        ax.axvline(t_sup, 0, 1, color='black', linestyle='--')
        # ax.text(t_sup, 1.12, " 95% percentile")

        return f, ax

    def image_binary(self, percentile):
        F = scipy.stats.f(2*self.m, 2*self.n)
        t_inf, t_sup = F.ppf(percentile/2), F.ppf(1 - percentile/2)

        im = np.zeros_like(self.Q)
        im[self.Q < t_inf] = 1
        im[self.Q > t_sup] = 1

        return im

    def image_linear(self, percentile):
        pass

class Wishart(object):
    def __init__(self, X, Y, n, m):
        self.X = X
        self.Y = Y
        self.n = n
        self.m = m

        p = 3
        detX = determinant(X)
        detY = determinant(Y)
        detXY = determinant(sar_sum(X, Y))

        # Test statistic
        self.lnq = (p*(n+m)*np.log(n+m) - p*n*np.log(n) - p*m*np.log(m)
                + n*np.log(detX) + m*np.log(detY) - (n+m)*np.log(detXY))

        self.rho = 1 - (2*p*p - 1)/(6*p) * (1/n + 1/m - 1/(n+m))

        self.w2 = (-(p*p/4)*(1-1/self.rho)**2
                + p*p*(p*p - 1)/24 * (1/(n*n) + 1/(m*m) - 1/((n+m)**2))*1/(p*p))

    def histogram(self, percent):
        f, ax = plt.subplots(1, 1)
        ax.hist(-2*self.rho*self.lnq.flatten(), bins=100, normed=True)

        # Overlay pdf
        p = 3
        x = np.linspace(0, 50, 1000)
        chi2 = scipy.stats.chi2
        y = chi2.pdf(x, p**2) + self.w2*(chi2.pdf(x, p**2+4) - chi2.pdf(x, p**2))
        ax.plot(x, y)

        return f, ax

    def image_binary(self, percent):
        threshold = 30
        im = np.zeros_like(self.lnq)
        im[-2*self.rho*self.lnq > threshold] = 1
        return im

if __name__ == "__main__":

    # Load data
    april = SARData().load_april()
    may = SARData().load_may()

    # No change region
    april_no_change = region(april, no_change_i, no_change_j)
    may_no_change = region(may, no_change_i, no_change_j)

    # Color composites
    plt.imsave("fig/april.png", color_composite(april))
    plt.imsave("fig/may.png", color_composite(may))

    def gamma_test(april, may, channel, ENL, percent):
        # Data
        X = april.__dict__[channel]
        Y = may.__dict__[channel]
        Xno = aregion(X)
        Yno = aregion(Y)

        # Name variables
        short_channel = channel[:2].upper()
        hist_title = ("Likelihood ratio distribution of no change region {} ENL={}"
            .format(short_channel, ENL))
        hist_filename = "fig/gamma.hist.ENL{0}.{1}.{2:.2f}.png".format(ENL, short_channel, percent)
        im_filename = "fig/gamma.im.ENL{0}.{1}.{2:.2f}.png".format(ENL, short_channel, percent)

        # No change region histogram
        gno = Gamma(Xno, Yno, ENL, ENL)
        f, ax = gno.histogram(percent)
        ax.set_title(hist_title)
        f.savefig(hist_filename)

        # Binary image
        g = Gamma(X, Y, ENL, ENL)
        im = g.image_binary(percent)
        plt.imsave(im_filename, im, cmap='gray')

    gamma_test(april, may, "hhhh", 13, 0.01)
    gamma_test(april, may, "hvhv", 13, 0.01)
    gamma_test(april, may, "vvvv", 13, 0.01)

    gamma_test(april, may, "hhhh", 12, 0.01)
    gamma_test(april, may, "hvhv", 12, 0.01)
    gamma_test(april, may, "vvvv", 12, 0.01)

    april_no = region(april, no_change_i, no_change_j)
    may_no = region(may, no_change_i, no_change_j)

    def wishart_test(ENL, percent):
        w = Wishart(april, may, ENL, ENL)
        wno = Wishart(april_no, may_no, ENL, ENL)

        f, ax = wno.histogram(0.01)
        hist_title = (r"$-2 \rho \ln Q$ distribution in no change region ENL={}"
                .format(ENL))
        hist_filename = "fig/lnq.hist.ENL{}.png".format(ENL)

        ax.set_title(hist_title)
        f.savefig(hist_filename)

        im = w.image_binary(0.30)
        plt.imsave("fig/lnq.png", im, cmap="gray")

    wishart_test(11, 0.30)
    wishart_test(12, 0.30)
    wishart_test(13, 0.30)
    wishart_test(14, 0.30)

    plt.close('all')

<|endoftext|>


<commit_before>import cv2

def solve_sudoku_in_picture(filename):
    # read
    original = cv2.imread(filename, cv2.CV_LOAD_IMAGE_GRAYSCALE)

    # blur
    img = cv2.medianBlur(original, 3)

    # threshold
    img = cv2.adaptiveThreshold(
        img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

    # invertieren
    img = cv2.bitwise_not(img)

    # find bigged contour
    contours, hierarchy = cv2.findContours(
        img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # select biggest contour
    biggest_contour = contours[0]
    for c in contours:
        if cv2.contourArea(c) > cv2.contourArea(biggest_contour):
            biggest_contour = c
    cv2.drawContours(original, [biggest_contour], 0, (255, 255, 255))
    cv2.imshow('Sudoku', original)

    # # resize
    # normed_size = cv2.resize(img, (450, 450))
    # cv2.imshow('winname', normed_size)

    # # ocr all letters
    # for y in range(0, 450, 50):
    #     for x in range(0, 450, 50):
    #         roi = normed_size[y + 5:y + 45, x + 5:x + 45]
    #         cv_roi = array2cv(roi)
    #         tesseract.SetCvImage(cv_roi, api)
    #         number = api.GetUTF8Text().strip()
    #         if number == '':
    #             print '_',
    #         else:
    #             print number,
    #     print('')

    # histogram
    # hist = cv2.calcHist([img], [0], None, [256], [0, 256])
    # plt.plot(hist)
    # plt.show()
    # binary

if __name__ == '__main__':
    solve_sudoku_in_picture('sudoku.jpg')
    cv2.waitKey(0)
    cv2.destroyAllWindows()
<commit_msg>apply mask<commit_after>import cv2
import numpy as np

def solve_sudoku_in_picture(filename):
    # read
    original = cv2.imread(filename, cv2.CV_LOAD_IMAGE_GRAYSCALE)

    # blur
    img = cv2.medianBlur(original, 3)

    # threshold
    img = cv2.adaptiveThreshold(
        img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

    # invert
    img = cv2.bitwise_not(img)

    # find bigged contour
    contours, hierarchy = cv2.findContours(
        img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # select biggest contour
    biggest_contour = contours[0]
    for c in contours:
        if cv2.contourArea(c) > cv2.contourArea(biggest_contour):
            biggest_contour = c

    # create mask
    mask = np.zeros(img.shape, np.uint8)
    cv2.drawContours(mask, [biggest_contour], 0, 255, -1)

    # apply mask
    img = cv2.bitwise_and(original, mask)
    cv2.imshow('winname', img)

    # resize
    # normed_size = cv2.resize(img, (450, 450))
    # cv2.imshow('winname', normed_size)

    # ocr all letters
    # for y in range(0, 450, 50):
    #     for x in range(0, 450, 50):
    #         roi = normed_size[y + 5:y + 45, x + 5:x + 45]
    #         cv_roi = array2cv(roi)
    #         tesseract.SetCvImage(cv_roi, api)
    #         number = api.GetUTF8Text().strip()
    #         if number == '':
    #             print '_',
    #         else:
    #             print number,
    #     print('')

    # histogram
    # hist = cv2.calcHist([img], [0], None, [256], [0, 256])
    # plt.plot(hist)
    # plt.show()
    # binary

if __name__ == '__main__':
    solve_sudoku_in_picture('sudoku.jpg')
    cv2.waitKey(0)
    cv2.destroyAllWindows()
<|endoftext|>


<commit_before>#!/usr/bin/python
# This code is an example for a tutorial on Ubuntu Unity/Gnome AppIndicators:
# http://candidtim.github.io/appindicator/2014/09/13/ubuntu-appindicator-step-by-step.html
# icons from https://materialdesignicons.com/

import os
import signal

from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify

APPINDICATOR_ID = 'myappindicator'

def build_menu():
  menu = gtk.Menu()
  item_quit = gtk.MenuItem('Quit')
  item_quit.connect('activate', quit)
  menu.append(item_quit)
  menu.show_all()
  return menu

def quit(_):
  notify.uninit()
  gtk.main_quit()

def main():
  indicator = appindicator.Indicator.new(
    APPINDICATOR_ID, os.path.abspath('ic_battery_charging_white_48dp.png'),
    appindicator.IndicatorCategory.SYSTEM_SERVICES)
  indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
  indicator.set_menu(build_menu())
  notify.init(APPINDICATOR_ID)
  gtk.main()

if __name__ == "__main__":
  signal.signal(signal.SIGINT, signal.SIG_DFL)
  main()
<commit_msg>formatting pep8<commit_after>#!/usr/bin/python
# This code is an example for a tutorial on Ubuntu Unity/Gnome AppIndicators:
# http://candidtim.github.io/appindicator/2014/09/13/ubuntu-appindicator-step-by-step.html
# icons from https://materialdesignicons.com/

import os
import signal

from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify

APPINDICATOR_ID = 'myappindicator'

def build_menu():
    menu = gtk.Menu()
    item_quit = gtk.MenuItem('Quit')
    item_quit.connect('activate', quit)
    menu.append(item_quit)
    menu.show_all()
    return menu

def quit(_):
    notify.uninit()
    gtk.main_quit()

def main():
    indicator = appindicator.Indicator.new(
        APPINDICATOR_ID, os.path.abspath('ic_battery_charging_white_48dp.png'),
        appindicator.IndicatorCategory.SYSTEM_SERVICES)
    indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
    indicator.set_menu(build_menu())
    notify.init(APPINDICATOR_ID)
    gtk.main()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
<|endoftext|>


<commit_before>from PIL import Image # pip install pillow
import os
from datetime import datetime
import shutil
import pymongo

"""
1. semua image yg belum dimasukkan ke database ditaruh ke dalam folder "temp"
2. masing-masing image kemudian di-extract info nya sebagai input untuk dbase
3. setiap image yang selesai di-extract dimasukkan ke dalam folder img
4. done!

data

{
'filename': 'thefilename',
'title': 'thetitle',
'size': 'imgsize',
'dim': 'img_dimension', # tuple
'format': 'img_type', # jpeg, png
'added': datetime.now(),
'hits': 0,
}

shutil.move(src, dest)
"""

c = pymongo.Connection()
c.drop_database('autoimg')
db = c['autoimg']

for fn in os.listdir('img'):
    filename, filext = os.path.splitext(fn)
    im = Image.open('img/' + fn)
    if db.image.find_one({'title': filename.replace('_', ' ')}) is None:
        db.image.insert({
            'filename': filename+filext,
            'title': filename.replace('_', ' '),
            'size': os.stat('img/' + fn).st_size,
            'format': im.format,
            'dim': im.size,
            'added': datetime.now(),
            'hits': 0,
            })
    # move the image into img folder
    # shutil.move('temp/filename', 'img/filename')

from pprint import pprint
pprint(db.image.find_one())
<commit_msg>adding todo<commit_after>from PIL import Image # pip install pillow
import os
from datetime import datetime
import shutil
import pymongo

"""
1. semua image yg belum dimasukkan ke database ditaruh ke dalam folder "temp"
2. masing-masing image kemudian di-extract info nya sebagai input untuk dbase
3. deteksi resolusi image resize menjadi lebih kecil, misal
resolusi asli:
1920 x 1200, maka resize:
800x600
1024x768
1152x864
1280x960
1400x1050
1600x1200
1360x768
1366x768
1600x900
1920x1080
1280x800
1440x900
1680x1050
4. setiap image yang selesai di-extract & resize dimasukkan ke dalam folder img
5. done!

data

{
'filename': 'thefilename',
'title': 'thetitle',
'size': 'imgsize',
'dim': 'img_dimension', # tuple
'format': 'img_type', # jpeg, png
'added': datetime.now(),
'hits': 0,
}

shutil.move(src, dest)
"""

c = pymongo.Connection()
c.drop_database('autoimg')
db = c['autoimg']

for fn in os.listdir('img'):
    filename, filext = os.path.splitext(fn)
    im = Image.open('img/' + fn)
    if db.image.find_one({'title': filename.replace('_', ' ')}) is None:
        db.image.insert({
            'filename': filename+filext,
            'title': filename.replace('_', ' '),
            'size': os.stat('img/' + fn).st_size,
            'format': im.format,
            'dim': im.size,
            'added': datetime.now(),
            'hits': 0,
            })
    # move the image into img folder
    # shutil.move('temp/filename', 'img/filename')

from pprint import pprint
pprint(db.image.find_one())
<|endoftext|>


<commit_before>import math

from Modul6 import ann
import theano.tensor as T
import numpy as np
from Modul6.gui_from_instructor import *
import copy
import random
import requests

class aiwindow(GameWindow):

    def __init__(self,player,control):
        super(aiwindow, self).__init__()
        self.control = control
        self.player = player
        self.movedict ={}
        self.movedict[0] = 'up'
        self.movedict[1] = 'down'
        self.movedict[2] = 'left'
        self.movedict[3] = 'right'
        self.weight_matrix = [[0,1,2,3],
            [6,5,5,4],
            [7,9,12,15],
            [55,35,25,20]]

    def onKeyPress(self,direction):
        if self.board.move(direction, self.board.state):
            self.update_view(self.board.state.board)
            self.board.place_tile(self.board.state)
            self.update_view(self.board.state.board)
            return True
        return False

    def play(self):
        boolean_var = True
        while (boolean_var):
            directions = list(self.player.net.predict([self.convertBoard()])[0])
            boolean_var = self.playBestMove(directions)

    def playBestMove(self,directions):
        dir = directions
        dir_val_tups=[]
        for i in range(len(directions)):
            dir_val_tups.append((dir[i],i))
        dir_val_tups.sort()
        for elem in dir_val_tups:
            if self.onKeyPress(self.movedict[elem[1]]):
               return True
        self.restart(self.board.get_highest_tile())
        return False

    def play_random(self):
        boolean_var = True
        while (boolean_var):

            boolean_var = self.play_random_move()
    def play_random_move(self):
        directions = [0,1,2,3]
        moves = []
        for i in directions:
            rand = random.randint(0,len(directions)-1)
            moves.append(directions[rand])
        for num in directions:
            if self.onKeyPress(self.movedict[num]):
                return True
        self.restart(self.board.get_highest_tile())
        return False

    def calculate_heuristic(self,node):
        value =0
        for i in range(len(node.board)):
            for j in range(len(node.board[i])):
                value += self.weight_matrix[i][j]
        return value

    #ConvertBoard for expectimax cases
    def convertBoard(self):
        returnboard =[]
        boards= []
        for i in range(4):
            boards.append(copy.deepcopy(self.board.state))

        self.board.move('up',boards[0])
        self.board.move('down',boards[1])
        self.board.move('left',boards[2])
        self.board.move('right',boards[3])
        for i in range(4):
            returnboard.append(self.calculate_heuristic(boards[i]))
        return np.array(returnboard)

    #
    # def convertBoard(self):
    #     returnboard = []
    #     for listelem in self.board.board:
    #         for elem in listelem:
    #             returnboard.append(elem)
    #     return np.array(returnboard)
    def restart(self,result):
        self.control.new_game(result)

class NNplayer(object):

    def __init__(self,training_set,topology,lr,epochs,batch_size,activation_functions):
        self.training_set = training_set
        self.topology = topology
        self.lr = lr
        self.epochs = epochs
        self.batch_size = batch_size
        self.activation_functions =activation_functions
        self.train_boards= None
        self.train_moves = None
        #Different number of in nodes because of different test set
        if self.training_set ==1:
            self.input = 16
        else:
            self.input=4
        self.net = ann.ANN(self.input,self.topology,activation_functions,4, lr)

    def load_test_cases(self):
        if self.training_set ==1:
            f = open('myfile1.txt','r' )
        else:
            f = open('myfile3.txt','r' )
        boards=[]
        moves =[]
        lines = f.readlines()
        for line in lines:
            case = line.split('$')
            board = case[0]
            move = case[1]
            board = board.split(',')
            move = move.strip('\n').split(',')
            boards.append(board)
            moves.append(move)
        boards = np.asarray(boards, dtype=np.float)
        self.scale(boards)
        moves = np.array(moves)
        self.train_boards = boards
        self.train_moves = moves

    def scale(self, seq):
        """
        Scales a list of board states by first getting the log2 value of every cell,
        and then dividing every cell by the log2 value of the maximum cell in that board state.

        Example:
            Input   = [[0, 2, 4, 8, 2, 16, 256], [4, 8, 512]]
            Log2    = [[0, 1, 2, 3, 1, 4, 8], [2, 3, 9]
            Scaled  = [[0, 0.125, 0.25, 0.375, 0.125, 0.5, 1], [0.222, 0.333, 1]] (by dividing by max(Log2))

        :param seq: A list of board states, formatted as float (important!)
        :return: A scaled list of board states, ranging from 0 to 1
        """
        for i in range(len(seq)):
            for j in range(len(seq[i])):
                if seq[i][j] != 0:
                    seq[i][j] = np.log2(seq[i][j])
            seq[i] = seq[i] / max(seq[i])

    def train_model(self,epochs, minibatch_size):
        for epoch in range(epochs):
            print("Training epoch number {}...".format(epoch))
            cost = 0
            for i in range(0, len(self.train_boards), minibatch_size):
                image_batch = self.train_boards[i:i+minibatch_size]
                label_batch = self.train_moves[i:i+minibatch_size]
                cost += self.net.train(image_batch, label_batch)

            print("Cost after epoch {}: {}".format(epoch, cost/len(self.train_boards)))

    def test_model(self):
        correct =0
        wrong = 0
        for i in range(len(self.train_moves)):
            if(self.net.predict(self.train_boards)[i] == np.argmax(self.train_moves[i])):
                correct += 1
            else:
                wrong +=1
        print (correct)

class main:

    def __init__(self):
        self.gui_bool = str(input("Gui? y/n: \n"))
        self.training_set = str(input("What training set do you want to use?\n1: 16 dim vector, 2: 4 dim vector: \n"))
        self.lr = float(input("Specify learningrate: \n"))
        self.epochs = int(input('How many epochs do you want to train?:\n'))
        self.hidden = [x for x in map(int, input("Please specify a topology description on the form 40,20,60: ").strip().split(","))]
        self.minibatch = int(input('What batch size do you want to use?:\n'))
        self.activations = [self.activation_map(x) for x in list(map(int, input("Please specify activation functions for each layer on the form 0,2,1: ").strip().split(",")))]
        self.net_result=[]
        self.rand_result=[]
        self.count = 1
        self.player = NNplayer(self.training_set,self.hidden,self.lr,self.epochs,self.minibatch,self.activations)
        self.player.load_test_cases()
        self.player.train_model(self.epochs,self.minibatch)
        self.root = Tk()
        print('NNET playing round: '+ str(self.count))
        self.game = aiwindow(self.player,self)
        if self.gui_bool =='y':
            self.game.pack()
            self.root.bind('<a>', lambda x: self.game.play())
            self.root.mainloop()
        if self.gui_bool =='n':
            self.game.play()

        self.net_result=[]
        self.rand_result=[]
        self.count = 1

    def activation_map(self,x):
        return {
            0: T.tanh,
            1: T.nnet.sigmoid,
            2: lambda k: T.switch(k > 0, k, 0),  # Equivalent to T.nnet.relu (rectified linear unit)
            3: T.nnet.softmax,
        }.get(x, T.tanh)  # T.tanh is default if x is not found

    def new_game(self,result):
        self.game.pack_forget()
        if self.count < 50:
            self.net_result.append(result)
            print('Highest tile: ' + str(result))
            self.count +=1
            print('NNET playing round: '+ str(self.count))
            self.game = aiwindow(self.player,self)
            if self.gui_bool =='y':
                self.game.pack()
            self.game.play()

        elif self.count==50 :
            print('Highest tile: ' + str(result))
            self.net_result.append(result)
            self.count +=1
            print('NNET playing round: '+ str(self.count))
            self.game = aiwindow(self.player,self)
            if self.gui_bool =='y':
                self.game.pack()
            self.game.play_random()

        elif 50< self.count<100:
            print('Highest tile: ' + str(result))
            self.rand_result.append(result)
            self.count+=1

            print('Random playing round: '+ str(self.count-50))
            self.game = aiwindow(self.player,self)
            if self.gui_bool =='y':
                self.game.pack()
            self.game.play_random()

        elif self.count == 100:
           # self.count+=1
            self.rand_result.append(result)
            print(len(self.rand_result))
            print(len(self.net_result))
            print(self.welch(self.rand_result,self.net_result))

    def welch(self,list1, list2):
        params = {"results": str(list1) + " " + str(list2), "raw": "1"}
        resp = requests.post('http://folk.ntnu.no/valerijf/6/', data=params)
        return resp.text

if __name__ == '__main__':
    main()<commit_msg>PEP8 der PEP8-es kan<commit_after>from Modul6.ann import ANN
from Modul6.gui_from_instructor import *

import theano.tensor as T
import numpy as np

import copy
import random
import requests

class AiWindow(GameWindow):

    def __init__(self, player, control):
        super(AiWindow, self).__init__()
        self.control = control
        self.player = player
        self.movedict = {0: 'up', 1: 'down', 2: 'left', 3: 'right'}
        self.weight_matrix = [
            [0, 1, 2, 3],
            [6, 5, 5, 4],
            [7, 9, 12, 15],
            [55, 35, 25, 20]
        ]

    def onKeyPress(self, direction):
        if self.board.move(direction, self.board.state):
            self.update_view(self.board.state.board)
            self.board.place_tile(self.board.state)
            self.update_view(self.board.state.board)
            return True
        return False

    def play(self):
        boolean_var = True
        while boolean_var:
            directions = list(self.player.net.predict([self.convert_board()])[0])
            boolean_var = self.play_best_move(directions)

    def play_best_move(self, directions):
        dir = directions
        dir_val_tups = []
        for i in range(len(directions)):
            dir_val_tups.append((dir[i], i))
        dir_val_tups.sort()
        for elem in dir_val_tups:
            if self.onKeyPress(self.movedict[elem[1]]):
                return True
        self.restart(self.board.get_highest_tile())
        return False

    def play_random(self):
        boolean_var = True
        while boolean_var:
            boolean_var = self.play_random_move()

    def play_random_move(self):
        directions = [0, 1, 2, 3]
        moves = []
        for _ in directions:
            rand = random.randint(0, len(directions)-1)
            moves.append(directions[rand])
        for num in directions:
            if self.onKeyPress(self.movedict[num]):
                return True
        self.restart(self.board.get_highest_tile())
        return False

    def calculate_heuristic(self, node):
        value = 0
        for i in range(len(node.board)):
            for j in range(len(node.board[i])):
                value += self.weight_matrix[i][j]
        return value

    # ConvertBoard for expectimax cases
    def convert_board(self):
        returnboard = []
        boards = []
        for i in range(4):
            boards.append(copy.deepcopy(self.board.state))

        self.board.move('up', boards[0])
        self.board.move('down', boards[1])
        self.board.move('left', boards[2])
        self.board.move('right', boards[3])
        for i in range(4):
            returnboard.append(self.calculate_heuristic(boards[i]))
        return np.array(returnboard)

    #
    # def convertBoard(self):
    #     returnboard = []
    #     for listelem in self.board.board:
    #         for elem in listelem:
    #             returnboard.append(elem)
    #     return np.array(returnboard)

    def restart(self, result):
        self.control.new_game(result)

class NNplayer(object):

    def __init__(self, training_set, topology, lr, epochs, batch_size, activation_functions):
        self.training_set = training_set
        self.topology = topology
        self.lr = lr
        self.epochs = epochs
        self.batch_size = batch_size
        self.activation_functions = activation_functions
        self.train_boards = None
        self.train_moves = None
        # Different number of in nodes because of different test set
        if self.training_set == 1:
            self.input = 16
        else:
            self.input = 4
        self.net = ANN(self.input, self.topology, activation_functions, 4, lr)

    def load_test_cases(self):
        if self.training_set == 1:
            f = open('myfile1.txt', 'r')
        else:
            f = open('myfile3.txt', 'r')
        boards = []
        moves = []
        lines = f.readlines()
        for line in lines:
            case = line.split('$')
            board = case[0]
            move = case[1]
            board = board.split(',')
            move = move.strip('\n').split(',')
            boards.append(board)
            moves.append(move)
        boards = np.asarray(boards, dtype=np.float)
        scale(boards)
        moves = np.array(moves)
        self.train_boards = boards
        self.train_moves = moves

    def train_model(self, epochs, minibatch_size):
        for epoch in range(epochs):
            print("Training epoch number {}...".format(epoch))
            cost = 0
            for i in range(0, len(self.train_boards), minibatch_size):
                board_batch = self.train_boards[i:i+minibatch_size]
                move_batch = self.train_moves[i:i+minibatch_size]
                cost += self.net.train(board_batch, move_batch)

            print("Cost after epoch {}: {}".format(epoch, cost/len(self.train_boards)))

    def test_model(self):
        correct = 0
        for i in range(len(self.train_moves)):
            if self.net.predict(self.train_boards)[i] == np.argmax(self.train_moves[i]):
                correct += 1
        print(correct)

class main:

    def __init__(self):
        self.gui_bool = str(input("Gui? y/n: \n"))
        self.training_set = str(input("What training set do you want to use?\n1: 16 dim vector, 2: 4 dim vector: \n"))
        self.hidden = [x for x in map(int, input("Please specify a topology description on the form 40,20,60: ").strip().split(","))]
        self.activations = [activation_map(x) for x in list(map(int, input("Please specify activation functions for each layer on the form 0,2,1: ").strip().split(",")))]
        self.lr = float(input("Specify learning rate: "))
        self.epochs = int(input('How many epochs do you want to train?: '))
        self.minibatch = int(input('What batch size do you want to use?: '))
        self.net_result = []
        self.rand_result = []
        self.count = 1
        self.player = NNplayer(self.training_set, self.hidden, self.lr, self.epochs, self.minibatch, self.activations)
        self.player.load_test_cases()
        self.player.train_model(self.epochs, self.minibatch)
        self.root = Tk()
        print('NNET playing round: ' + str(self.count))
        self.game = AiWindow(self.player, self)
        if self.gui_bool == 'y':
            self.game.pack()
            self.root.bind('<a>', lambda x: self.game.play())
            self.root.mainloop()
        if self.gui_bool == 'n':
            self.game.play()

        self.net_result = []
        self.rand_result = []
        self.count = 1

    def new_game(self, result):
        self.game.pack_forget()
        if self.count < 50:
            self.net_result.append(result)
            print('Highest tile: ' + str(result))
            self.count += 1
            print('NNET playing round: ' + str(self.count))
            self.game = AiWindow(self.player, self)
            if self.gui_bool == 'y':
                self.game.pack()
            self.game.play()

        elif self.count == 50:
            print('Highest tile: ' + str(result))
            self.net_result.append(result)
            self.count += 1
            print('NNET playing round: ' + str(self.count))
            self.game = AiWindow(self.player, self)
            if self.gui_bool == 'y':
                self.game.pack()
            self.game.play_random()

        elif 50 < self.count < 100:
            print('Highest tile: ' + str(result))
            self.rand_result.append(result)
            self.count += 1

            print('Random playing round: ' + str(self.count-50))
            self.game = AiWindow(self.player, self)
            if self.gui_bool == 'y':
                self.game.pack()
            self.game.play_random()

        elif self.count == 100:
            # self.count+=1
            self.rand_result.append(result)
            print(len(self.rand_result))
            print(len(self.net_result))
            print(welch(self.rand_result, self.net_result))

def scale(seq):
        """
        Scales a list of board states by first getting the log2 value of every cell,
        and then dividing every cell by the log2 value of the maximum cell in that board state.

        Example:
            Input   = [[0, 2, 4, 8, 2, 16, 256], [4, 8, 512]]
            Log2    = [[0, 1, 2, 3, 1, 4, 8], [2, 3, 9]
            Scaled  = [[0, 0.125, 0.25, 0.375, 0.125, 0.5, 1], [0.222, 0.333, 1]] (by dividing by max(Log2))

        :param seq: A list of board states, formatted as float (important!)
        :return: A scaled list of board states, ranging from 0 to 1
        """
        for i in range(len(seq)):
            for j in range(len(seq[i])):
                if seq[i][j] != 0:
                    seq[i][j] = np.log2(seq[i][j])
            seq[i] = seq[i] / max(seq[i])

def activation_map(x):
        return {
            0: T.tanh,
            1: T.nnet.sigmoid,
            2: lambda k: T.switch(k > 0, k, 0),  # Equivalent to T.nnet.relu (rectified linear unit)
            3: T.nnet.softmax,
        }.get(x, T.tanh)  # T.tanh is default if x is not found

def welch(list1, list2):
        params = {"results": str(list1) + " " + str(list2), "raw": "1"}
        resp = requests.post('http://folk.ntnu.no/valerijf/6/', data=params)
        return resp.text

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


<commit_before>from flask import Flask, request
from pprint import pprint
import re
import json
import ConfigParser
import urllib2
import network
import os
import subprocess
import socket

def bitbucket(json):
  ret = {}
  ret['url'] = json['canon_url'] + json['repository']['absolute_url'][0:-1] # cut off trailing slash
  ret['clone'] = re.sub('bitbucket', json['repository']['owner'] + '@bitbucket', 1) + '.git'
  ret['raw'] = ret['url'] + '/raw'
  ret['config'] = ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = [{'message' : j['message'], 'branch': j['branch'], 'time': j['timestamp']} for j in json['commits']]

  return ret

def github(json):
  ret = {}
  ret['url'] = json['repository']['url']
  ret['clone'] = ret['url'] + '.git'
  ret['raw'] = re.sub('github', 'raw.github', ret['url'], 1)
  ret['config'] =  ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = []
  for j in json['commits']:
    d = {'message' : j['message'], 'time' : j['timestamp']}
    d['branch'] = re.sub(r'([^\/])$', r'\1', json['ref'])
    ret['commits'].append(d)

  return ret

def shellescape(s):
  return s.replace("\\", "\\\\").replace("'", "'\\''")

def log(s, level = 0):
  logfile.write(str(s))
  logfile.write("\n")
  logfile.flush()
  print s

sources = {
    ('131.103.20.165', 1) : bitbucket,
    ('131.103.20.166', 1) : bitbucket,
    ('204.232.175.64', 27) : github,
    ('192.30.252.0', 22) : github,
  }

app = Flask(__name__)
state = {}

logfile = open('integralgit.log', 'a')

log('Starting up...')

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/<repo>")
def latest(repo):
  return str(state.get(repo, "I don't recognize that repo name. Try committing something to it?"))

@app.route("/update", methods=["POST"])
def update():
  # Prevent requests from hosts we don't recognize
  source = request.remote_addr
  log('source: ' + str(source))
  decoder = None
  for n, d in sources.iteritems():
    if network.isAddressInNetwork(source, *n):
      log('Source IP is in network' + str(n))
      decoder = d
      break
  else:
    log('Update request from illegal ip ' + str(source))
    return "Unrecognized source IP"

  jd = json.JSONDecoder()
  payload = jd.decode(request.form['payload'])
  info = decoder(payload)
  log(info)
  state[repo] = info

  try:
    getConfigs(info)
    gitPull(info)
  except Exception as e:
    # Skip running host script...lessens chance of RCE
    return str(e)

  runHostScript(info)

  return "Good job"

# Get host configuration file from the integralgit branch
def getConfigs(info):
  config_data = None
  log('Host config location: ' + str(info['config']))
  try:
    page = urllib2.urlopen(info['config'])
    config_data = page.read()
    page.close()
  except:
    log("Host Config not found, quitting.")
    raise Exception("Could not load host config")

  jd = json.JSONDecoder()
  info['config'] = jd.decode(config_data)
  info['hostconfig'] = getHostConfig(info)

# Get specific host configuration
# by applying a base config (if it exists),
# applying configs for hostgroups in alphabetical order,
# then applying host-specific configs.
def getHostConfig(info):
  hostname = socket.gethostname()

  # get base config
  config = info['config'].get('configs',{}).get('base',{})

  # get hostgroup configs
  for group, hosts in iter(sorted(info['config'].get('groups', {}).iteritems())):
    if hostname in hosts:
      config.update(info['config'].get('configs', {}).get(group, {}))

  # get host specific config
  config.update(info['config'].get('configs', {}).get(hostname, {}))

  return config

def gitPull(info):
# Build repo folder
  repoFolder = info['hostconfig']['location']
  if repoFolder is None:
    log("No location found for repository!")
    raise Exception("No location found!")

  log("Checking if " + repoFolder + " is a git repository...")

  # Check for folder
  if(os.path.isdir(repoFolder)):
    # Check for git repo
    result = subprocess.call(['git', 'rev-parse'], cwd=repoFolder)
    if(result != 0):
      log("Folder exists but is not a git repository. Fix your shit.")
      raise Exception("Not a git repository")

    branch = info['hostconfig'].get('branch', 'master')
    remote = info['hostconfig'].get('remote', 'origin')

    # If local branch exists, checkout and pull
    result = subprocess.call(['git', 'show-branch', branch], cwd=repoFolder)
    if result == 0:
      log("Checking out branch...")
      result = subprocess.call(['git', 'checkout', branch], cwd=repoFolder)
      log("Checkout result: " + str(result))
      log("Doing git pull...")
      result = subprocess.call(['git', 'pull'], cwd=repoFolder)
      log("Pull result: " + str(result))

    # Local branch does not exist, fetch and track remote branch
    else:
      log("Local branch does not exist...")
      log("Doing git fetch...")
      result = subprocess.call(['git', 'fetch'], cwd=repoFolder)
      log("Fetch result: " + str(result))
      log("Checking out branch...")
      result = suprocess.call(['git', 'checkout', '--track', remote + '/' + branch], cwd=repoFolder)
      log("Checkout result: " + str(result))

  # Repo does not exist at all, clone and checkout
  else:
    log("Folder does not exist; doing git clone...")
    result = subprocess.call(['git', 'clone', info['clone']], cwd=os.path.basename(repoFolder))
    log("Clone result: " + str(result))
    log("Checking out local branch...")
    result = subprocess.call(['git', 'checkout', '-b', branch, remote + '/' + branch], cwd=repoFolder)
    log("Checkout result: " + str(result))

def runHostScript(info):
  script_name = info['hostconfig']['script']
  repo_folder = info['hostconfig']['location']

  if(script_name is not None):
    script_path = os.path.join(repo_folder, script_name)
    log("Got script file for host: " + str(script_path))

    log("Running script...")
    subprocess.call(['chmod', '+x', script_path])
    result = subprocess.call([script_path], cwd = repo_folder)
    log("Script result: " + str(result))

#TODO: fix
def parseConfig(filename):
  config = ConfigParser.SafeConfigParser()
  config.read(filename)

  for section in config.sections():
    lastCommit[section] = "No recorded commits!"

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

<commit_msg>Rearranging stuff<commit_after>from flask import Flask, request
from pprint import pprint
import re
import json
import ConfigParser
import urllib2
import network
import os
import subprocess
import socket

def bitbucket(json):
  ret = {}
  ret['url'] = json['canon_url'] + json['repository']['absolute_url'][0:-1] # cut off trailing slash
  ret['clone'] = re.sub('bitbucket', json['repository']['owner'] + '@bitbucket', 1) + '.git'
  ret['raw'] = ret['url'] + '/raw'
  ret['config'] = ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = [{'message' : j['message'], 'branch': j['branch'], 'time': j['timestamp']} for j in json['commits']]

  return ret

def github(json):
  ret = {}
  ret['url'] = json['repository']['url']
  ret['clone'] = ret['url'] + '.git'
  ret['raw'] = re.sub('github', 'raw.github', ret['url'], 1)
  ret['config'] =  ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = []
  for j in json['commits']:
    d = {'message' : j['message'], 'time' : j['timestamp']}
    d['branch'] = re.sub(r'([^\/])$', r'\1', json['ref'])
    ret['commits'].append(d)

  return ret

def shellescape(s):
  return s.replace("\\", "\\\\").replace("'", "'\\''")

def log(s, level = 0):
  logfile.write(str(s))
  logfile.write("\n")
  logfile.flush()
  print s

sources = {
    ('131.103.20.165', 1) : bitbucket,
    ('131.103.20.166', 1) : bitbucket,
    ('204.232.175.64', 27) : github,
    ('192.30.252.0', 22) : github,
  }

state = {}

logfile = open('integralgit.log', 'a')
log('Starting up...')

app = Flask(__name__)

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/<repo>")
def latest(repo):
  return str(state.get(repo, "I don't recognize that repo name. Try committing something to it?"))

@app.route("/update", methods=["POST"])
def update():
  # Prevent requests from hosts we don't recognize
  source = request.remote_addr
  log('source: ' + str(source))
  decoder = None
  for n, d in sources.iteritems():
    if network.isAddressInNetwork(source, *n):
      log('Source IP is in network' + str(n))
      decoder = d
      break
  else:
    log('Update request from illegal ip ' + str(source))
    return "Unrecognized source IP"

  jd = json.JSONDecoder()
  payload = jd.decode(request.form['payload'])
  info = decoder(payload)
  state[repo] = info
  log(info)

  try:
    getConfigs(info)
    gitPull(info)
  except Exception as e:
    # Skip running host script...lessens chance of RCE
    return str(e)

  runHostScript(info)

  return "Good job"

# Get host configuration file from the integralgit branch
def getConfigs(info):
  config_data = None
  log('Host config location: ' + str(info['config']))
  try:
    page = urllib2.urlopen(info['config'])
    config_data = page.read()
    page.close()
  except:
    log("Host Config not found, quitting.")
    raise Exception("Could not load host config")

  jd = json.JSONDecoder()
  info['config'] = jd.decode(config_data)
  info['hostconfig'] = getHostConfig(info)

# Get specific host configuration
# by applying a base config (if it exists),
# applying configs for hostgroups in alphabetical order,
# then applying host-specific configs.
def getHostConfig(info):
  hostname = socket.gethostname()

  # get base config
  config = info['config'].get('configs',{}).get('base',{})

  # get hostgroup configs
  for group, hosts in iter(sorted(info['config'].get('groups', {}).iteritems())):
    if hostname in hosts:
      config.update(info['config'].get('configs', {}).get(group, {}))

  # get host specific config
  config.update(info['config'].get('configs', {}).get(hostname, {}))

  return config

def gitPull(info):
# Build repo folder
  repoFolder = info['hostconfig']['location']
  if repoFolder is None:
    log("No location found for repository!")
    raise Exception("No location found!")

  log("Checking if " + repoFolder + " is a git repository...")

  # Check for folder
  if(os.path.isdir(repoFolder)):
    # Check for git repo
    result = subprocess.call(['git', 'rev-parse'], cwd=repoFolder)
    if(result != 0):
      log("Folder exists but is not a git repository. Fix your shit.")
      raise Exception("Not a git repository")

    branch = info['hostconfig'].get('branch', 'master')
    remote = info['hostconfig'].get('remote', 'origin')

    # If local branch exists, checkout and pull
    result = subprocess.call(['git', 'show-branch', branch], cwd=repoFolder)
    if result == 0:
      log("Checking out branch...")
      result = subprocess.call(['git', 'checkout', branch], cwd=repoFolder)
      log("Checkout result: " + str(result))
      log("Doing git pull...")
      result = subprocess.call(['git', 'pull'], cwd=repoFolder)
      log("Pull result: " + str(result))

    # Local branch does not exist, fetch and track remote branch
    else:
      log("Local branch does not exist...")
      log("Doing git fetch...")
      result = subprocess.call(['git', 'fetch'], cwd=repoFolder)
      log("Fetch result: " + str(result))
      log("Checking out branch...")
      result = suprocess.call(['git', 'checkout', '--track', remote + '/' + branch], cwd=repoFolder)
      log("Checkout result: " + str(result))

  # Repo does not exist at all, clone and checkout
  else:
    log("Folder does not exist; doing git clone...")
    result = subprocess.call(['git', 'clone', info['clone']], cwd=os.path.basename(repoFolder))
    log("Clone result: " + str(result))
    log("Checking out local branch...")
    result = subprocess.call(['git', 'checkout', '-b', branch, remote + '/' + branch], cwd=repoFolder)
    log("Checkout result: " + str(result))

def runHostScript(info):
  script_name = info['hostconfig']['script']
  repo_folder = info['hostconfig']['location']

  if(script_name is not None):
    script_path = os.path.join(repo_folder, script_name)
    log("Got script file for host: " + str(script_path))

    log("Running script...")
    subprocess.call(['chmod', '+x', script_path])
    result = subprocess.call([script_path], cwd = repo_folder)
    log("Script result: " + str(result))

#TODO: fix
def parseConfig(filename):
  config = ConfigParser.SafeConfigParser()
  config.read(filename)

  for section in config.sections():
    lastCommit[section] = "No recorded commits!"

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.

First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

from telegram import (ReplyKeyboardMarkup)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler)

import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

START, LOC_UNKNOWN, TIME_UNKNOWN, LOC_INCORRECT = range(4)

def start(bot, update):
    reply_keyboard = [['Boy', 'Girl', 'Other']]

    bot.sendMessage(update.message.chat_id,
                    text='Hi! My name is Professor Bot. I will hold a conversation with you. '
                         'Send /cancel to stop talking to me.\n\n'
                         'Are you a boy or a girl?',
                    reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))

    return GENDER

def gender(bot, update):
    user = update.message.from_user
    logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
    bot.sendMessage(update.message.chat_id,
                    text='I see! Please send me a photo of yourself, '
                         'so I know what you look like, or send /skip if you don\'t want to.')

    return PHOTO

def photo(bot, update):
    user = update.message.from_user
    photo_file = bot.getFile(update.message.photo[-1].file_id)
    photo_file.download('user_photo.jpg')
    logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
    bot.sendMessage(update.message.chat_id, text='Gorgeous! Now, send me your location please, '
                                                 'or send /skip if you don\'t want to.')

    return LOCATION

def skip_photo(bot, update):
    user = update.message.from_user
    logger.info("User %s did not send a photo." % user.first_name)
    bot.sendMessage(update.message.chat_id, text='I bet you look great! Now, send me your '
                                                 'location please, or send /skip.')

    return LOCATION

def location(bot, update):
    user = update.message.from_user
    user_location = update.message.location
    logger.info("Location of %s: %f / %f"
                % (user.first_name, user_location.latitude, user_location.longitude))
    bot.sendMessage(update.message.chat_id, text='Maybe I can visit you sometime! '
                                                 'At last, tell me something about yourself.')

    return BIO

def skip_location(bot, update):
    user = update.message.from_user
    logger.info("User %s did not send a location." % user.first_name)
    bot.sendMessage(update.message.chat_id, text='You seem a bit paranoid! '
                                                 'At last, tell me something about yourself.')

    return BIO

def bio(bot, update):
    user = update.message.from_user
    logger.info("Bio of %s: %s" % (user.first_name, update.message.text))
    bot.sendMessage(update.message.chat_id,
                    text='Thank you! I hope we can talk again some day.')

    return ConversationHandler.END

def cancel(bot, update):
    user = update.message.from_user
    logger.info("User %s canceled the conversation." % user.first_name)
    bot.sendMessage(update.message.chat_id,
                    text='Bye! I hope we can talk again some day.')

    return ConversationHandler.END

def error(bot, update, error):
    logger.warn('Update "%s" caused error "%s"' % (update, error))

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater("219296013:AAHENQyYMoWHSGs5bjPhhxHR2ai4uEHGQ7c")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            START: [RegexHandler('^(Boy|Girl|Other)$', gender)],

            LOC_UNKNOWN: [MessageHandler([Filters.photo], photo),
                    CommandHandler('skip', skip_photo)],

            TIME_UNKNOWN: [MessageHandler([Filters.location], location),
                       CommandHandler('skip', skip_location)],

            LOC_TIME_UNKNOWN: [MessageHandler([Filters.text], bio)]
        },

        fallbacks=[CommandHandler('cancel', cancel)]
    )

    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()
<commit_msg>Edited main.py<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.

First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import weather
import extractor

from telegram import (ReplyKeyboardMarkup)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler)

import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

START, REPLY, LOC_UNKNOWN, TIME_UNKNOWN, LOC_TIME_UNKNOWN = range(5)

TOKEN = "219296013:AAHENQyYMoWHSGs5bjPhhxHR2ai4uEHGQ7c" # token for telegram bot

def start(bot, update):

    bot.sendMessage(update.message.chat_id,
                    text='Hi! Ich bin dein Wetterbot 😍 Was willst du wissen?  '
                         'Antworte /cancel um mich zu stoppen 😉\n\n')

    return REPLY

def reply(bot, update):
    extr_request = extractor.get_args(request)
    bot.sendMessage(update.message.chat_id,text=weather.deliver(*extr_request))
    return START

def gender(bot, update):
    user = update.message.from_user
    logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
    bot.sendMessage(update.message.chat_id,
                    text='I see! Please send me a photo of yourself, '
                         'so I know what you look like, or send /skip if you don\'t want to.')

    return PHOTO

def photo(bot, update):
    user = update.message.from_user
    photo_file = bot.getFile(update.message.photo[-1].file_id)
    photo_file.download('user_photo.jpg')
    logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
    bot.sendMessage(update.message.chat_id, text='Gorgeous! Now, send me your location please, '
                                                 'or send /skip if you don\'t want to.')

    return LOCATION

def skip_photo(bot, update):
    user = update.message.from_user
    logger.info("User %s did not send a photo." % user.first_name)
    bot.sendMessage(update.message.chat_id, text='I bet you look great! Now, send me your '
                                                 'location please, or send /skip.')

    return LOCATION

def location(bot, update):
    user = update.message.from_user
    user_location = update.message.location
    logger.info("Location of %s: %f / %f"
                % (user.first_name, user_location.latitude, user_location.longitude))
    bot.sendMessage(update.message.chat_id, text='Maybe I can visit you sometime! '
                                                 'At last, tell me something about yourself.')

    return BIO

def skip_location(bot, update):
    user = update.message.from_user
    logger.info("User %s did not send a location." % user.first_name)
    bot.sendMessage(update.message.chat_id, text='You seem a bit paranoid! '
                                                 'At last, tell me something about yourself.')

    return BIO

def bio(bot, update):
    user = update.message.from_user
    logger.info("Bio of %s: %s" % (user.first_name, update.message.text))
    bot.sendMessage(update.message.chat_id,
                    text='Thank you! I hope we can talk again some day.')

    return ConversationHandler.END

def cancel(bot, update):
    user = update.message.from_user
    logger.info("User %s canceled the conversation." % user.first_name)
    bot.sendMessage(update.message.chat_id,
                    text='Bye! I hope we can talk again some day.')

    return ConversationHandler.END

def error(bot, update, error):
    logger.warn('Update "%s" caused error "%s"' % (update, error))

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            START: [RegexHandler('^(Boy|Girl|Other)$', gender)],

            REPLY: [MessageHandler([Filters.text], reply)],

            LOC_UNKNOWN: [MessageHandler([Filters.photo], photo),
                    CommandHandler('skip', skip_photo)],

            TIME_UNKNOWN: [MessageHandler([Filters.location], location),
                       CommandHandler('skip', skip_location)],

            LOC_TIME_UNKNOWN: [MessageHandler([Filters.text], bio)]

        },

        fallbacks=[CommandHandler('cancel', cancel)]
    )

    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

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


<commit_before>#!/usr/bin/env python

from engine import network

def main():
    network.listen('0.0.0.0', 5269)

if __name__ == '__main__':
    main()
<commit_msg>pep8 main.py<commit_after>#!/usr/bin/env python

from engine import network

def main():
    network.listen('0.0.0.0', 5269)

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


<commit_before>import os, sys
import requests
import json
import random
import argparse

# Set some initial constants
manifest_location = "http://1.webseed.robertsspaceindustries.com/FileIndex/sc-alpha-2.0.0/"
BUILD_RANGE = 10
VERSION = "0.0.2"

#############################################################
#                  -- Argument Parsing -                    #
# Description: 						    					#
# This block parses the commandline with the argparse 		#
# library. https://docs.python.org/3/library/argparse.html	#
#############################################################
parser = argparse.ArgumentParser(prog="stellar_avarice", description="An Automated Star Citizen Download Utility")
parser.add_argument('-l', '--latest',
					help="Display the latest version", action="store_true")
parser.add_argument('-v', '--version',
					help="Display program version", action="version", version='%(prog)s - v{}'.format(VERSION))
args = parser.parse_args()

#############################################################
#               ---- latest_version() ----                  #
# Description: 						    					#
# Function searches the current directory for *.json files  #
# It returns the highest number it finds		    		#
#############################################################
def latest_build(json_num = 0):
	dir_contents = [f for f in os.listdir('.') if os.path.isfile(f)]
	last_json = json_num
	for item in dir_contents:
		if item.split('.')[-1] == 'json':
			json_num = item.split('.')[0]
			if last_json < json_num:
				last_json = json_num
		else:
			continue
	return last_json
#############################################################
#               ---- new_build_check() ----                 #
# Description:												#
# Function checks the manifest_location for a new build		#
# it does this by utilizing the latest version information	#
# it currently has											#
#############################################################
def new_build_check():
	item_num = int(latest_build())
	print "Found Latest: " + str(item_num)

	for i in range (item_num + 1,item_num + BUILD_RANGE + 1):
		try:
			manifest_name = str(i) + ".json"

			# Print the latest json that we're trying to test for
			print '\rTrying: {}'.format(manifest_name),
			manifest_response = requests.get(manifest_location + manifest_name)
			manifest_response.raise_for_status()

			# If it finds the file, doesn't throw an exception and writes the file to disk
			print "\rWriting: {}".format(manifest_name),
			manifest_fh = open(manifest_name, "w")
			manifest_fh.write(manifest_response.content)
			manifest_fh.close()
		except Exception as e:
			if(manifest_response.status_code==404):
				print('%s: Page could not be found.' % e.reason)
			if(manifest_response.status_code>=500):
				print ('%s: Server error [%s]' % (e.reason, manifest_response.status_code))

#############################################################
#               ---- version_compare() ----                 #
# Description:												#
# Function compares two versions by each portion of the		#
# version number. This allows double digit parts to be 		#
# compared individually, such as 2.11.0, which would be a 	#
# newer version than 2.8.0									#
#############################################################
def version_compare(num_check):
	num_split = num_check.split('.')
	try:
		latest_num_list=latest_num.split('.')
		if(isinstance(latest_num_list,list)):
			for ind,part in enumerate(num_split):
				if(part>latest_num_list[ind]):
					latest_num_list=num_split
				elif(part==latest_num_list[ind]):
					continue
				else:
					break
		else:
			latest_num=num_check
	except:
		latest_num=num_check
	return latest_num

#############################################################
#               ---- parse_json() ----   	                #
# Description:												#
# Function grabs the latest json and parses it into an 		#
# object and then returns that parsed json object			#
#############################################################
def parse_json():

	latest_json = str(latest_build())
	print "Using: {}".format(latest_json)
	json_fh = open(latest_json + ".json", "r")
	parsed_json = json.load(json_fh)
	return parsed_json

#############################################################
#               ---- download_build() ----                  #
# Description:												#
# Function grabs latest json object and then uses this 		#
# to create directories it needs. It then starts to 		#
# download the build via a stream in blocks of 1024			#
#############################################################
def download_build():
	parsed_json = parse_json()

	# Choose a random webseed
	base_webseed_url = random.choice(parsed_json["webseed_urls"])
	# The key prefix is the build version that gets appended to the base seed location
	key_prefix = parsed_json["key_prefix"]
	build_name = parsed_json["key_prefix"].split("/")[2] #Grab Build # so that we store build's appropriately

	for file_name in parsed_json["file_list"]:
		list = [] # A list to hold temporary values

		# Construct the URI based on each file
		file_url = base_webseed_url + "/" + key_prefix + "/" + file_name

		# We iterate through the full file list to discover any folders that might be contained within
		# If we find a folder that doesn't exist, we create this folder
		if "/" in file_name:
			for item in file_name.split('/'):
				list.append(item)
			file_name = list.pop(-1)
			file_path = os.path.join(build_name, *list)
			if not os.path.isdir(file_path):
				try:
					os.makedirs(file_path)
				except OSError:
					print "\nError creating directory: " + file_path

		file = os.path.join(file_path, file_name)
		# Begin Downloading Part

		print("\rDownloading: %-100s" % file),

		# Create the response object, ensure that it's a stream
		# so we can start downloading right away
		response = requests.get(file_url, stream=True)

		# Let the user know if they're downloading a new file or not
		# This should have more functionality later
		if os.path.isfile(file):
			print "File Exists - Updating",
			# if <local hash matches remote>
				# print "Skipping..."
				# continue
			# else:
				# print "Updating..."
		else:
			pass
		# For each file start writing it.
		with open(file, "w") as fh:
		    if not response.ok:
		        print('File download was unsuccessful')
		    else:
		    	for block in response.iter_content(1024):
		        	fh.write(block)
def main():
	# Used for our just checking the latest build information
	if args.latest:
		print "Latest Build: {}".format(latest_build())
		sys.exit(0)
	else:
		## This isn't working right now
		new_build_check()
		print "\nLatest Build: {}".format(latest_build())
		prompt = raw_input("Would you like to download this version [y|n]?\n>").lower()
		if prompt.strip() == 'y':
			download_build()
		else:
			print "Exiting..."
		sys.exit(0)
main() #Run our code<commit_msg>fixed run-as-script execution<commit_after>import os, sys
import requests
import json
import random
import argparse

# Set some initial constants
manifest_location = "http://1.webseed.robertsspaceindustries.com/FileIndex/sc-alpha-2.0.0/"
BUILD_RANGE = 10
VERSION = "0.0.2"

#############################################################
#                  -- Argument Parsing -                    #
# Description: 						    					#
# This block parses the commandline with the argparse 		#
# library. https://docs.python.org/3/library/argparse.html	#
#############################################################
parser = argparse.ArgumentParser(prog="stellar_avarice", description="An Automated Star Citizen Download Utility")
parser.add_argument('-l', '--latest',
					help="Display the latest version", action="store_true")
parser.add_argument('-v', '--version',
					help="Display program version", action="version", version='%(prog)s - v{}'.format(VERSION))
args = parser.parse_args()

#############################################################
#               ---- latest_version() ----                  #
# Description: 						    					#
# Function searches the current directory for *.json files  #
# It returns the highest number it finds		    		#
#############################################################
def latest_build(json_num = 0):
	dir_contents = [f for f in os.listdir('.') if os.path.isfile(f)]
	last_json = json_num
	for item in dir_contents:
		if item.split('.')[-1] == 'json':
			json_num = item.split('.')[0]
			if last_json < json_num:
				last_json = json_num
		else:
			continue
	return last_json
#############################################################
#               ---- new_build_check() ----                 #
# Description:												#
# Function checks the manifest_location for a new build		#
# it does this by utilizing the latest version information	#
# it currently has											#
#############################################################
def new_build_check():
	item_num = int(latest_build())
	print "Found Latest: " + str(item_num)

	for i in range (item_num + 1,item_num + BUILD_RANGE + 1):
		try:
			manifest_name = str(i) + ".json"

			# Print the latest json that we're trying to test for
			print '\rTrying: {}'.format(manifest_name),
			manifest_response = requests.get(manifest_location + manifest_name)
			manifest_response.raise_for_status()

			# If it finds the file, doesn't throw an exception and writes the file to disk
			print "\rWriting: {}".format(manifest_name),
			manifest_fh = open(manifest_name, "w")
			manifest_fh.write(manifest_response.content)
			manifest_fh.close()
		except Exception as e:
			if(manifest_response.status_code==404):
				print('%s: Page could not be found.' % e.reason)
			if(manifest_response.status_code>=500):
				print ('%s: Server error [%s]' % (e.reason, manifest_response.status_code))

#############################################################
#               ---- version_compare() ----                 #
# Description:												#
# Function compares two versions by each portion of the		#
# version number. This allows double digit parts to be 		#
# compared individually, such as 2.11.0, which would be a 	#
# newer version than 2.8.0									#
#############################################################
def version_compare(num_check):
	num_split = num_check.split('.')
	try:
		latest_num_list=latest_num.split('.')
		if(isinstance(latest_num_list,list)):
			for ind,part in enumerate(num_split):
				if(part>latest_num_list[ind]):
					latest_num_list=num_split
				elif(part==latest_num_list[ind]):
					continue
				else:
					break
		else:
			latest_num=num_check
	except:
		latest_num=num_check
	return latest_num

#############################################################
#               ---- parse_json() ----   	                #
# Description:												#
# Function grabs the latest json and parses it into an 		#
# object and then returns that parsed json object			#
#############################################################
def parse_json():

	latest_json = str(latest_build())
	print "Using: {}".format(latest_json)
	json_fh = open(latest_json + ".json", "r")
	parsed_json = json.load(json_fh)
	return parsed_json

#############################################################
#               ---- download_build() ----                  #
# Description:												#
# Function grabs latest json object and then uses this 		#
# to create directories it needs. It then starts to 		#
# download the build via a stream in blocks of 1024			#
#############################################################
def download_build():
	parsed_json = parse_json()

	# Choose a random webseed
	base_webseed_url = random.choice(parsed_json["webseed_urls"])
	# The key prefix is the build version that gets appended to the base seed location
	key_prefix = parsed_json["key_prefix"]
	build_name = parsed_json["key_prefix"].split("/")[2] #Grab Build # so that we store build's appropriately

	for file_name in parsed_json["file_list"]:
		list = [] # A list to hold temporary values

		# Construct the URI based on each file
		file_url = base_webseed_url + "/" + key_prefix + "/" + file_name

		# We iterate through the full file list to discover any folders that might be contained within
		# If we find a folder that doesn't exist, we create this folder
		if "/" in file_name:
			for item in file_name.split('/'):
				list.append(item)
			file_name = list.pop(-1)
			file_path = os.path.join(build_name, *list)
			if not os.path.isdir(file_path):
				try:
					os.makedirs(file_path)
				except OSError:
					print "\nError creating directory: " + file_path

		file = os.path.join(file_path, file_name)
		# Begin Downloading Part

		print("\rDownloading: %-100s" % file),

		# Create the response object, ensure that it's a stream
		# so we can start downloading right away
		response = requests.get(file_url, stream=True)

		# Let the user know if they're downloading a new file or not
		# This should have more functionality later
		if os.path.isfile(file):
			print "File Exists - Updating",
			# if <local hash matches remote>
				# print "Skipping..."
				# continue
			# else:
				# print "Updating..."
		else:
			pass
		# For each file start writing it.
		with open(file, "w") as fh:
		    if not response.ok:
		        print('File download was unsuccessful')
		    else:
		    	for block in response.iter_content(1024):
		        	fh.write(block)
def main():
	# Used for our just checking the latest build information
	if args.latest:
		print "Latest Build: {}".format(latest_build())
		sys.exit(0)
	else:
		## This isn't working right now
		new_build_check()
		print "\nLatest Build: {}".format(latest_build())
		prompt = raw_input("Would you like to download this version [y|n]?\n>").lower()
		if prompt.strip() == 'y':
			download_build()
		else:
			print "Exiting..."
		sys.exit(0)

if __name__ == "__main__":
	main() #Run our code
<|endoftext|>


<commit_before>from kivy.app import App
from kivy.properties import *
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.core.audio import SoundLoader
from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition, SlideTransition, NoTransition
from kivy.uix.settings import SettingsWithSidebar
from kivy.uix.popup import Popup
from kivy.metrics import dp
from kivy import platform
from kivy.clock import Clock
from jsonConfig import settingsjson
import datetime
import pickle

from gameplay import GamePlayScreen
from PlayerNamePopup import PlayerNamePopup

class TutorialScreen(Popup):
    pass

class EndGameScreen(Screen):
    name_of_players = ListProperty(['','','',''])
    scores_of_players = ListProperty()
    screenManager = ObjectProperty()
    number_of_players = NumericProperty()
    game = ObjectProperty()

    def on_enter(self,*args):
        self.name_of_players = [x for y,x in sorted(zip(self.scores_of_players,self.name_of_players))][::-1]
        self.scores_of_players = sorted(self.scores_of_players)[::-1]

class PlayerSection(Button):
    myvalue = NumericProperty(4)

    def __init__(self, **kwargs):
        super(PlayerSection, self).__init__(**kwargs)
        self.size = Window.size[0] // 6, Window.size[1] // 6

class GameLayout(ScreenManager):
    ''' This class manages the movements between the various screen and the sound '''

    name_of_players = ListProperty(['Score', '', '', ''])
    number_of_players = NumericProperty(1)
    scores_of_players = ListProperty([0, 0, 0, 0])

    # True if there is a game going on
    active = BooleanProperty(False)
    soundActivated = BooleanProperty(False)

    directory = StringProperty()

    currentSong = StringProperty('set_song')

    def __init__(self, **kwargs):
        super(GameLayout, self).__init__(**kwargs)
        self.playscreen = self.get_screen('game')
        self.sound = SoundLoader.load(self.currentSong)
        self.transition = FadeTransition()

    # screen play navigation
    def goToIntro(self, *arg):
        self.transition = NoTransition()
        self.current = 'intro'

    def goToGameScreen(self, *arg):
        self.transition = FadeTransition()
        self.current = 'game'

    def on_currentSong(self, obj, value):
        self.playMusic()

    # Dealing with Sound
    def on_soundActivated(self, obj, value):
        ''' Turn the intro song on or off '''
        self.playMusic()

    def playMusic(self):
        if self.sound:
            self.sound.stop()
        self.sound = SoundLoader.load(self.currentSong + ".wav")
        if self.soundActivated:
            self.sound.loop = True
            self.sound.play()
        else:
            self.sound.stop()

    def pickleFile(self):
        return self.directory + "name_of_players.pkl"

    def on_name_of_players(self,value, obj):
        if platform == 'macosx' or platform == 'ios':
            with open(self.pickleFile(), "wb") as playersNamePickle:
                pickle.dump(list(self.name_of_players), playersNamePickle)

    def player_name_popup(self, numPlayers):
        '''called after selecting number of players'''
        self.number_of_players = numPlayers
        if self.number_of_players == 1:
            self.goToGameScreen()
            return
        tempNames = ['John', 'Sally', 'Sam', 'Joey']
        if platform == 'macosx' or platform == 'ios':
            try:
                names = pickle.load(open(self.pickleFile(), "rb"))
                for index, name in enumerate(names):
                    tempNames[index] = name
            except Exception as exception:
                print("Loading from Pickling went wrong, using default names")

        self.name_of_players = tempNames
        playername = PlayerNamePopup(self.name_of_players, numPlayers)
        playername.open()
        playername.bind(on_dismiss = self.goToGameScreen)

    def quit(self):
        ''' You are quiting the current game '''
        if self.active:
            #self.playscreen.scores_of_players = [0,0,0,0]
            self.playscreen.aiScore = 0
            self.goToIntro()
            self.playscreen.stopRotation()
            self.active = False

def boolFromJS(value):
    ''' JSON config returns '1' and '0' for True and False'''
    return True if value == '1' else False

class ShugouApp(App):
    active = BooleanProperty(False)

    def build(self):
        Clock.max_iteration = 50
        self.use_kivy_settings = False
        self.gamelayout = GameLayout()
        self.settings_cls = SettingsWithSidebar
        self.loadSettings()
        self.gamelayout.bind(active=self.changeActive)
        self.gamelayout.directory = self.whereToSave()
        return self.gamelayout

    def whereToSave(self):
        # Returns in which directory you can store files
        return self.get_application_config().rstrip("shugou.ini")

    def changeActive(self,instance,value):
        # This doesn't work.. crashes if the build_settings wasn't launched first
        #self.quitButton.disabled = not self.gamelayout.active
        pass

    def loadSettings(self):
        # Load the values already stored into the file
        self.gamelayout.soundActivated = boolFromJS(
            self.config.get('settings', 'sound'))
        speedSettings = {'slow':10, 'normal':5, 'fast':1, 'off': 0, 'True': 1}
        speed = speedSettings[self.config.get('settings', 'hint')]
        if speed != 0:
            self.gamelayout.playscreen.displayHintTimer = speed
            self.gamelayout.playscreen.hintActivated = True
        else:
            self.gamelayout.playscreen.hintActivated = False

        self.gamelayout.playscreen.aiActivated = boolFromJS(
            self.config.get('settings', 'ai'))
        self.gamelayout.currentSong = self.config.get('settings', 'song_title')

    def build_config(self, config):
        config.setdefaults('settings', {'sound': False,
                                        'ai': False,
                                        'hint': 'off',
                                        'song_title': 'shugou_song_main'})

    def build_settings(self, settings):
        self.settings = settings
        self.settings.interface.menu.width = dp(100)
        settings.add_json_panel('Settings', self.config, data=settingsjson)
        settingsCloseButton = settings.interface.ids.menu.ids.button
        self.settingsCloseButton = settingsCloseButton
        self.settingsCloseButton.text = "Return"
        settingsCloseButton.on_press = self.leaveSettingsPanel
        settings.interface.ids.menu.add_widget(Button(text="Tutorial",
                                                      size_hint = (None, None),
                                                      x= settingsCloseButton.x,
                                                      y = settingsCloseButton.top + 10,
                                                      size = settingsCloseButton.size,
                                                      on_press= self.moveToTutorial))

        self.quitButton = Button(text="Quit",
                              background_color = [1,0,0,1],
                              size_hint = (None, None),
                              x= settingsCloseButton.x,
                              y = settingsCloseButton.top + settingsCloseButton.height + 20,
                              size = settingsCloseButton.size,
                              disabled = False,
                              on_press= self.quit)

        settings.interface.ids.menu.add_widget(self.quitButton)
        settings.on_close = self.quit

    def quit(self, *arg):
        self.gamelayout.quit()
        self.settingsCloseButton.trigger_action()

    def moveToTutorial(self, buttonInstance):
        tutorial = TutorialScreen(title="Tutorial")
        tutorial.open()

    def leaveSettingsPanel(self, *arg):
        ''' activated when you exit the setting panels'''
        self.gamelayout.playscreen.setUpHint()
        self.gamelayout.playscreen.setUpAI()

    def on_config_change(self, config, section, key, value):
        if key == 'song_title':
            self.gamelayout.currentSong = value
            self.gamelayout.playMusic()
        elif key == 'sound':
            self.gamelayout.soundActivated = boolFromJS(value)
        elif key == 'hint':
            speedSettings = {u'slow':10, u'normal':5, u'fast':1, u'off': 0}
            speed = speedSettings[value]
            if speed != 0:
                self.gamelayout.playscreen.displayHintTimer = speed
                self.gamelayout.playscreen.hintActivated = True
            else:
                self.gamelayout.playscreen.hintActivated = False
        elif key == 'ai':
            self.gamelayout.playscreen.aiActivated = boolFromJS(value)

# To test the screen size you can use:
# kivy main.py -m screen:ipad3

if __name__ == '__main__':
    ShugouApp().run()
<commit_msg>Refactored the music playing into its own class<commit_after>from kivy.app import App
from kivy.properties import *
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.core.audio import SoundLoader
from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition, SlideTransition, NoTransition
from kivy.uix.settings import SettingsWithSidebar
from kivy.uix.popup import Popup
from kivy.metrics import dp
from kivy import platform
from kivy.clock import Clock
from jsonConfig import settingsjson
import datetime
import pickle

from gameplay import GamePlayScreen
from PlayerNamePopup import PlayerNamePopup

class TutorialScreen(Popup):
    pass

class EndGameScreen(Screen):
    name_of_players = ListProperty(['','','',''])
    scores_of_players = ListProperty()
    screenManager = ObjectProperty()
    number_of_players = NumericProperty()
    game = ObjectProperty()

    def on_enter(self,*args):
        self.name_of_players = [x for y,x in sorted(zip(self.scores_of_players,self.name_of_players))][::-1]
        self.scores_of_players = sorted(self.scores_of_players)[::-1]

class PlayerSection(Button):
    myvalue = NumericProperty(4)

    def __init__(self, **kwargs):
        super(PlayerSection, self).__init__(**kwargs)
        self.size = Window.size[0] // 6, Window.size[1] // 6

class Music(Widget):
    soundActivated = BooleanProperty(False)
    currentSong = StringProperty('set_song')
    sound = ObjectProperty()

    def on_currentSong(self, obj, value):
        self.playMusic()

    def on_soundActivated(self, obj, value):
        self.playMusic()

    def playMusic(self):
        if self.sound:
            self.sound.stop()
        self.sound = SoundLoader.load(self.currentSong + ".wav")
        if self.soundActivated:
            self.sound.loop = True
            self.sound.play()
        else:
            self.sound.stop()

class GameLayout(ScreenManager):
    ''' This class manages the movements between the various screen and the sound '''

    name_of_players = ListProperty(['Score', '', '', ''])
    number_of_players = NumericProperty(1)
    scores_of_players = ListProperty([0, 0, 0, 0])

    # True if there is a game going on
    active = BooleanProperty(False)

    directory = StringProperty()

    def __init__(self, **kwargs):
        super(GameLayout, self).__init__(**kwargs)
        self.playscreen = self.get_screen('game')
        self.transition = FadeTransition()

    # screen play navigation
    def goToIntro(self, *arg):
        self.transition = NoTransition()
        self.current = 'intro'

    def goToGameScreen(self, *arg):
        self.transition = FadeTransition()
        self.current = 'game'

    def pickleFile(self):
        return self.directory + "name_of_players.pkl"

    def on_name_of_players(self,value, obj):
        if platform == 'macosx' or platform == 'ios':
            with open(self.pickleFile(), "wb") as playersNamePickle:
                pickle.dump(list(self.name_of_players), playersNamePickle)

    def player_name_popup(self, numPlayers):
        '''called after selecting number of players'''
        self.number_of_players = numPlayers
        if self.number_of_players == 1:
            self.goToGameScreen()
            return
        tempNames = ['John', 'Sally', 'Sam', 'Joey']
        if platform == 'macosx' or platform == 'ios':
            try:
                names = pickle.load(open(self.pickleFile(), "rb"))
                for index, name in enumerate(names):
                    tempNames[index] = name
            except Exception as exception:
                print("Loading from Pickling went wrong, using default names")

        self.name_of_players = tempNames
        playername = PlayerNamePopup(self.name_of_players, numPlayers)
        playername.open()
        playername.bind(on_dismiss = self.goToGameScreen)

    def quit(self):
        ''' You are quiting the current game '''
        if self.active:
            #self.playscreen.scores_of_players = [0,0,0,0]
            self.playscreen.aiScore = 0
            self.goToIntro()
            self.playscreen.stopRotation()
            self.active = False

def boolFromJS(value):
    ''' JSON config returns '1' and '0' for True and False'''
    return True if value == '1' else False

class ShugouApp(App):
    active = BooleanProperty(False)

    def build(self):
        self.music = Music()
        Clock.max_iteration = 50
        self.use_kivy_settings = False
        self.gamelayout = GameLayout()
        self.settings_cls = SettingsWithSidebar
        self.loadSettings()
        self.gamelayout.bind(active=self.changeActive)
        self.gamelayout.directory = self.whereToSave()
        return self.gamelayout

    def whereToSave(self):
        # Returns in which directory you can store files
        return self.get_application_config().rstrip("shugou.ini")

    def changeActive(self,instance,value):
        # This doesn't work.. crashes if the build_settings wasn't launched first
        #self.quitButton.disabled = not self.gamelayout.active
        pass

    def loadSettings(self):
        # Load the values already stored into the file
        self.music.soundActivated = boolFromJS(
            self.config.get('settings', 'sound'))
        speedSettings = {'slow':10, 'normal':5, 'fast':1, 'off': 0, 'True': 1}
        speed = speedSettings[self.config.get('settings', 'hint')]
        if speed != 0:
            self.gamelayout.playscreen.displayHintTimer = speed
            self.gamelayout.playscreen.hintActivated = True
        else:
            self.gamelayout.playscreen.hintActivated = False

        self.gamelayout.playscreen.aiActivated = boolFromJS(
            self.config.get('settings', 'ai'))
        self.music.currentSong = self.config.get('settings', 'song_title')

    def build_config(self, config):
        config.setdefaults('settings', {'sound': False,
                                        'ai': False,
                                        'hint': 'off',
                                        'song_title': 'shugou_song_main'})

    def build_settings(self, settings):
        self.settings = settings
        self.settings.interface.menu.width = dp(100)
        settings.add_json_panel('Settings', self.config, data=settingsjson)
        settingsCloseButton = settings.interface.ids.menu.ids.button
        self.settingsCloseButton = settingsCloseButton
        self.settingsCloseButton.text = "Return"
        settingsCloseButton.on_press = self.leaveSettingsPanel
        settings.interface.ids.menu.add_widget(Button(text="Tutorial",
                                                      size_hint = (None, None),
                                                      x= settingsCloseButton.x,
                                                      y = settingsCloseButton.top + 10,
                                                      size = settingsCloseButton.size,
                                                      on_press= self.moveToTutorial))

        self.quitButton = Button(text="Quit",
                              background_color = [1,0,0,1],
                              size_hint = (None, None),
                              x= settingsCloseButton.x,
                              y = settingsCloseButton.top + settingsCloseButton.height + 20,
                              size = settingsCloseButton.size,
                              disabled = False,
                              on_press= self.quit)

        settings.interface.ids.menu.add_widget(self.quitButton)
        settings.on_close = self.quit

    def quit(self, *arg):
        self.gamelayout.quit()
        self.settingsCloseButton.trigger_action()

    def moveToTutorial(self, buttonInstance):
        tutorial = TutorialScreen(title="Tutorial")
        tutorial.open()

    def leaveSettingsPanel(self, *arg):
        ''' activated when you exit the setting panels'''
        self.gamelayout.playscreen.setUpHint()
        self.gamelayout.playscreen.setUpAI()

    def on_config_change(self, config, section, key, value):
        if key == 'song_title':
            self.music.currentSong = value
            self.music.playMusic()
        elif key == 'sound':
            self.music.soundActivated = boolFromJS(value)
        elif key == 'hint':
            speedSettings = {u'slow':10, u'normal':5, u'fast':1, u'off': 0}
            speed = speedSettings[value]
            if speed != 0:
                self.gamelayout.playscreen.displayHintTimer = speed
                self.gamelayout.playscreen.hintActivated = True
            else:
                self.gamelayout.playscreen.hintActivated = False
        elif key == 'ai':
            self.gamelayout.playscreen.aiActivated = boolFromJS(value)

# To test the screen size you can use:
# kivy main.py -m screen:ipad3

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


<commit_before>import asynchat,asyncore,socket,sys,os,time
try:
	import config
except ImportError:
	print("Please edit config.py.dist - rename it to config.py when you're done")
	exit()
class asynchat_bot(asynchat.async_chat):
	def __init__(self, host, port):
		asynchat.async_chat.__init__(self)
		self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
		self.set_terminator('\r\n')
		self.data=''
		self.remote=(host,port)
		self.connect(self.remote)
		#set vars
		self.versionnumber = 0.01
		self.version = "Solus "+str(self.versionnumber)+". (servername) [(protocol)]"
		#stuff to be set on a rehash
		self.remotehost = config.remotehost
		self.remoteport = config.remoteport
		self.protocolname = config.protocolname
		self.loglevel = config.loglevel
		self.reportchannel = config.reportchannel
		#end of stuff to be set on a rehash
		self.servername = config.servername
		self.debugmode = debugmode
		self.firstping = 1
		self.myclients = []
		try:
			__import__("modules.protocol."+config.protocolname)
			self.protocol = sys.modules[config.protocolname]
			self.protocol.modinit(self)
		except ImportError:
			print("Error: protocol \""+config.protocolname+"\" does not exist.")
			exit()
	#api
	def sendLine(self,data):
		if self.debugmode == 1:
			print("{"+str(time.time())+"} Send: "+data)
		self.push(data+"\r\n")
	def load(self,modname):
		module = __import__("modules.services."+modname)
		module.modinit(self)
		return module
	def sendNotice(self,sender,target,message):
		if self.myclients == [] or sender == "server":
			self.protocol.sendNotice(self,"server",target,message)
		else:
			self.protocol.sendNotice(self,sender,target,message)
	def sendNotice(self,sender,target,message):
		if self.myclients == [] or sender == "server":
			self.protocol.sendPrivmsg(self,"server",target,message)
		else:
			self.protocol.sendPrivmsg(self,sender,target,message)
	def log(self,level,data):
		if level.lower() in self.loglevel.lower():
			if self.myclients == []:
				self.sendNotice("server",self.reportchannel,data)
			else:
				self.sendNotice(self.myclients[0],self.reportchannel,data)
	def getVersion(self):
		version = self.version.replace("(servername)",self.servername).replace("(protocol)",self.protocolname)
		return version
	#end of api
	def handle_connect(self):
		self.protocol.handle_connect(self,config)
		self.startts = time.time()
	def handle_error(self):
		raise
	def get_data(self):
		r=self.data
		self.data=''
		return r
	def collect_incoming_data(self, data):
		self.data+=data
	def found_terminator(self):
		data=self.get_data()
		if self.debugmode == 1:
			print("{"+str(time.time())+"} Recv: "+data)
		self.protocol.handle_data(self,data)
if __name__ == '__main__':
	debugmode = 0
	for arg in sys.argv[1:]:
		if " " not in arg and "python" not in arg and "main.py" not in arg:
			if arg == "-d":
				debugmode = 1
				print "Starting in debug mode."
			else:
				print "Unknown argument: "+arg+" - ignoring"
	print("Solus started.  PID: "+str(os.getpid()))
	asynchat_bot(config.remotehost,int(config.remoteport))
	asyncore.loop()
<commit_msg>added self.mysid into __init__<commit_after>import asynchat,asyncore,socket,sys,os,time
try:
	import config
except ImportError:
	print("Please edit config.py.dist - rename it to config.py when you're done")
	exit()
class asynchat_bot(asynchat.async_chat):
	def __init__(self, host, port):
		asynchat.async_chat.__init__(self)
		self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
		self.set_terminator('\r\n')
		self.data=''
		self.remote=(host,port)
		self.connect(self.remote)
		#set vars
		self.versionnumber = 0.01
		self.version = "Solus "+str(self.versionnumber)+". (servername) [(protocol)]"
		#stuff to be set on a rehash
		self.remotehost = config.remotehost
		self.remoteport = config.remoteport
		self.protocolname = config.protocolname
		self.loglevel = config.loglevel
		self.reportchannel = config.reportchannel
		#end of stuff to be set on a rehash
		self.servername = config.servername
		self.mysid = config.sid
		self.debugmode = debugmode
		self.firstping = 1
		self.myclients = []
		try:
			__import__("modules.protocol."+config.protocolname)
			self.protocol = sys.modules[config.protocolname]
			self.protocol.modinit(self)
		except ImportError:
			print("Error: protocol \""+config.protocolname+"\" does not exist.")
			exit()
	#api
	def sendLine(self,data):
		if self.debugmode == 1:
			print("{"+str(time.time())+"} Send: "+data)
		self.push(data+"\r\n")
	def load(self,modname):
		module = __import__("modules.services."+modname)
		module.modinit(self)
		return module
	def sendNotice(self,sender,target,message):
		if self.myclients == [] or sender == "server":
			self.protocol.sendNotice(self,"server",target,message)
		else:
			self.protocol.sendNotice(self,sender,target,message)
	def sendNotice(self,sender,target,message):
		if self.myclients == [] or sender == "server":
			self.protocol.sendPrivmsg(self,"server",target,message)
		else:
			self.protocol.sendPrivmsg(self,sender,target,message)
	def log(self,level,data):
		if level.lower() in self.loglevel.lower():
			if self.myclients == []:
				self.sendNotice("server",self.reportchannel,data)
			else:
				self.sendNotice(self.myclients[0],self.reportchannel,data)
	def getVersion(self):
		version = self.version.replace("(servername)",self.servername).replace("(protocol)",self.protocolname)
		return version
	#end of api
	def handle_connect(self):
		self.protocol.handle_connect(self,config)
		self.startts = time.time()
	def handle_error(self):
		raise
	def get_data(self):
		r=self.data
		self.data=''
		return r
	def collect_incoming_data(self, data):
		self.data+=data
	def found_terminator(self):
		data=self.get_data()
		if self.debugmode == 1:
			print("{"+str(time.time())+"} Recv: "+data)
		self.protocol.handle_data(self,data)
if __name__ == '__main__':
	debugmode = 0
	for arg in sys.argv[1:]:
		if " " not in arg and "python" not in arg and "main.py" not in arg:
			if arg == "-d":
				debugmode = 1
				print "Starting in debug mode."
			else:
				print "Unknown argument: "+arg+" - ignoring"
	print("Solus started.  PID: "+str(os.getpid()))
	asynchat_bot(config.remotehost,int(config.remoteport))
	asyncore.loop()
<|endoftext|>