import time
import pandas as pd

CITY_DATA = {'chicago': 'chicago.csv',
             'new york city': 'new_york_city.csv',
             'washington': 'washington.csv'}
# sets list of available answers to check input against
months = {"january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6}
reverse_months = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June'}
days_of_week = {0: "sunday", 1: "monday", 2: "tuesday", 3: "wednesday", 4: "thursday", 5: "friday", 6: "saturday"}

def month_data():
    month_name = ''
    month = ''
    months = {"january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6}
    while True:
        print('-' * 40)
        y = input("Please enter a month. (E.g. January)\nData is only available for January-June.\n")
        if y.lower() in months.keys():
            month = months[y.lower()]
            month_name = y.title()
            break
        else:
            print("\nMonth not recognized.\n")
            continue
    return month

def day_data():
    while True:
        print('-' * 40)
        try:
            z = int(input("Please enter the day of the week, in integer form, for which you would like data."
                          "\n(E.g. 0 for Sunday, 1 for Monday, ...)\n"))
            if int(z) in days_of_week.keys():
                day = z
                month = 'none'
                break
            else:
                print("\nDay not recognized.\n")
                continue
        except ValueError:
            print('\nDay not recognized.')
            print('\n')
    return day

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "none" to apply no month filter
        (str) day - name of the day of week to filter by, or "none" to apply no day filter
    """
    # Prints header
    print('\n')
    print('Hello! Let\'s explore some US bike sharing data!')
    print('-' * 40)
    print('\n')

    # gets user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    city = ''
    month = ''
    day = ''
    day_name = ''
    month_name = ''
    while True:
        print('Data is available for Chicago, New York City, and Washington.')
        x = input("Please enter a city.\n")
        if x.lower() in CITY_DATA.keys():
            city = x
            break
        else:
            print("\nCity not recognized.\n")
            continue

    # spacing
    print('\n' * 2)
    print('-' * 40)

    # prompts user to select desire to work with filtered data
    print("Data is available for January-June 2017.\nYou can choose to see all data, or filter the data by a specific "
          "month and/or the day of the week.\n")
    while True:
        x = input("Would you like to filter the data?\nType yes or no.\n")
        filter_choice = ''
        if x.lower() == 'yes':
            filter_choice = x
            break
        elif x.lower() == 'no':
            filter_choice = x
            break
        else:
            print("\nFilter choice not recognized.\n")
            continue

    # spacing
    print('\n' * 2)

    # No filter assignments
    if filter_choice.lower() == 'no':
        month = "none"
        day = "none"

    # secondary filtering
    elif filter_choice.lower() == 'yes':
        # gets user to input degree of data filtering
        while True:
            print('-' * 40)
            x = input('Would you like to filter data by month, day, or both?\n')
            if x.lower() == 'month':
                month = month_data()
                month_name = reverse_months[month]
                day = 'none'
                break
            elif x.lower() == 'day':
                day = day_data()
                day_name = days_of_week[day]
                month = 'none'
                break
            elif x.lower() == 'both':
                month = month_data()
                month_name = reverse_months[month]
                day = day_data()
                day_name = days_of_week[day]
                break
            else:
                print("\nChoice not recognized\n")
                continue

    # spacing
    print('\n')
    print('-' * 40)

    # returns final statement of filters
    print('\n' * 2)
    # no filters
    if month == 'none' and day == 'none':
        print('Thank you.\n\nHere is all the data available for {}'.format(city.title()))
    # day filter statement
    elif month == 'none' and day != 'none':
        print('Thank you.\n\nHere is all the data available for every {} in {}.'.format(day_name, city.title()))
    # month filter statement
    elif month != 'none' and day == 'none':
        print('Thank you.\n\nHere is all the data available for {} in {}.'.format(month_name, city.title()))
    # both filter statement
    else:
        print('Thank you.\n\nHere is all the data available for every {} in {} for {}.'.format(day_name, month_name,
                                                                                city.title()))
    print('-' * 40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "none" to apply no month filter
        (str) day - name of the day of week to filter by, or "none" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
    with open(CITY_DATA[city], 'r') as f:
        file = pd.read_csv(f)
        file['Start Time'] = pd.to_datetime(file['Start Time'])
        file['End Time'] = pd.to_datetime(file['End Time'])
        file['month'] = file['Start Time'].dt.month
        file['dow'] = file['Start Time'].dt.dayofweek
        file['Trip Duration'] = pd.to_numeric(file['Trip Duration'])
        # no filters chosen
        if month == 'none' and day == 'none':
            df = file
        # filters by day
        elif month == 'none' and day != 'none':
            file = file[file['dow'] == day]
            df = file
        # filters by month
        elif month != 'none' and day == 'none':
            file = file[file['month'] == month]
            df = file
        # filters by day and month
        else:
            file = file[file['dow'] == day]
            file = file[file['month'] == month]
            df = file
    return df

def time_stats(df, month, day):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # display the most common month
    if month == 'none':
        max_month = df.month.mode()
        print('The month with the most rides is', reverse_months[max_month[0]])

    # display the most common day of week
    if day == 'none':
        max_day = df.dow.mode()
        print('The day with the most rides is', days_of_week[max_day[0]].title())

    # display the most common start hour
    df['hour'] = df['Start Time'].dt.hour
    common_hour = df.hour.mode()
    if common_hour[0] < 10:
        print('The most common hour is 0' + str(common_hour[0]) + ':00')
    else:
        print('The most common hour is ' + str(common_hour[0]) + ':00')

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-' * 40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # display most commonly used start station
    fav_start = df['Start Station'].mode()
    print('The most popular starting station - ' + fav_start[0])

    # display most commonly used end station
    fav_end = df['End Station'].mode()
    print('The most popular ending station - ' + fav_end[0])
    print('\n')
    # display most frequent combination of start station and end station trip
    df['Round Trip'] = df['Start Station'] + ' : ' + df['End Station']
    top_combo = df['Round Trip'].mode()
    top_combo = top_combo[0].split(' : ')
    print('The most popular starting/ending station combination:\nStart Station - ' + top_combo[
        0] + '\nEnd Station - ' + top_combo[1])

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-' * 40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # display total travel time
    total_dur = int(sum(df['Trip Duration']))
    if total_dur >= 86400:
        day, rem = total_dur // 86400, total_dur % 86400
        hr, rem = rem // 3600, rem % 3600
        minutes, sec = rem // 60, rem % 60
        print('Bikes were rented for a total time of {} days, {} hours, {} minutes, and {} seconds.'.format(day, hr,
                                                                                minutes,
                                                                                sec))

    elif total_dur >= 3600:
        hr, rem = total_dur // 3600, total_dur % 3600
        minutes, sec = rem // 60, rem % 60
        print('Bikes were rented for a total time of {} hours, {} minutes, and {} seconds.'.format(hr, minutes, sec))
    elif total_dur >= 60:
        minutes, sec = total_dur // 60, total_dur % 60
        print('Bikes were rented for a total time of {} minutes, and {} seconds.'.format(minutes, sec))
    else:
        sec = total_dur
        print('Bikes were rented for a total time of {} seconds.'.format(sec))

    # display mean travel time
    total_trips = df['Trip Duration'].count()
    ave_dur = int(total_dur / total_trips)
    if ave_dur >= 86400:
        ave_day, rem = ave_dur // 86400, ave_dur % 86400
        ave_hr, rem = rem // 3600, rem % 3600
        ave_min, ave_sec = rem // 60, rem % 60
        print('The average length of a rental was {} days, {} hours, {} minutes, and {} seconds.'.format(ave_day,
                                                                                ave_hr,
                                                                                ave_min,
                                                                                ave_sec))

    elif ave_dur >= 3600:
        ave_hr, rem = ave_dur // 3600, ave_dur % 3600
        ave_min, ave_sec = rem // 60, rem % 60
        print('The average length of a rental was {} hours, {} minutes, and {} seconds.'.format(ave_hr, ave_min,
                                                                                ave_sec))
    elif ave_dur >= 60:
        ave_min, ave_sec = ave_dur // 60, ave_dur % 60
        print('The average length of a rental was {} minutes, and {} seconds.'.format(ave_min, ave_sec))
    else:
        ave_sec = ave_dur
        print('The average length of a rental was {} seconds.'.format(ave_sec))
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-' * 40)

def user_stats(df, city):
    """Displays statistics on bike share users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # Display counts of user types
    user_types = df.groupby('User Type')['Start Time'].count()
    print('Breakdown of user types:')
    for i in range(len(user_types)):
        print(user_types.index[i], '-', user_types[i])

    print('\n')

    # Display counts of gender
    print('Distribution of rider sexes:')
    if city != 'washington':
        gen_df = df.groupby('Gender')['Start Time'].count()
        for i in range(len(gen_df)):
            print(gen_df.index[i], '-', gen_df[i])

        print('\n')
    else:
        print('There is no gender data available for Washington.\n')

    # Display earliest, most recent, and most common year of birth
    # oldest rider
    print('Distribution of rider birth years:')
    if city != 'washington':
        print('The oldest rider to rent a bike was born in {}.'.format(int(min(df['Birth Year']))))
        print('The youngest rider to rent a bike was born in {}.'.format(int(max(df['Birth Year']))))
        print('The highest number of riders were born in {}.'.format(int(df['Birth Year'].mode())))
    else:
        print('There is no birth year data available for Washington.')

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-' * 40)

def see_data(df):
    while True:
        see_data_ans = input('\nWould you like to see a sample of the raw data? Enter yes or no.\n')
        if see_data_ans.lower() == 'yes':
            print('\n')
            print(df.head())
            print('\n')
            break
        elif see_data_ans.lower() == 'no':
            break
        else:
            print('Input not recognized.')

def restart():
    while True:
        restart_ans = input('\nWould you like to restart the program? Enter yes or no.\n')
        if restart_ans.lower() == 'yes':
            answer = 'yes'
            return answer
        elif restart_ans.lower() == 'no':
            answer = 'no'
            return answer
        else:
            print('Input not recognized.')

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)
        time_stats(df, month, day)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df, city)
        see_data(df)
        if restart() != 'yes':
            break

if __name__ == "__main__":
    main()


from Bot import Bot
from SuperBot import SuperBot
from FlyingBot import FlyingBot

test = Bot("Botty")

test.get_age()
test.get_energy()
test.get_name()
test.get_shield()

test.decrement_energy()
test.decrement_shield()

test.display_name()
test.display_age()
test.display_energy()
test.display_shield_level()
test.display_summary()
print(test.__str__())

test.increment_age()
test.increment_energy()
test.increment_shield()

test.set_name()

super_bot = SuperBot("John")

super_bot.get_super_power_level(3000)
super_bot.set_super_power_level(3000)

flying_bot = FlyingBot("Joe", 30)
flying_bot.get_hover_distance()
flying_bot.set_hover_distance()


from flask import Flask, render_template, jsonify, request
app = Flask(__name__)

from pymongo import MongoClient           # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017)  # mongoDB는 27017 포트로 돌아갑니다.
db = client.dbsparta

## HTML을 주는 부분
@app.route('/')
def home():
   return render_template('original.html')

## API 역할을 하는 부분
@app.route('/content', methods=['POST'])
def message_post():
   name_receive = request.form['name_give']
   select_receive = request.form['select_give']
   address_receive = request.form['address_give']
   number_receive = request.form['number_give']
   doc={'name': name_receive, 'select': select_receive,'address': address_receive,'number': number_receive}
   db.homework.insert_one(doc)
   return jsonify({'result':'success','msg': '리뷰가 성공적으로 작성되었습니다.'})

@app.route('/content', methods=['GET'])
def message_get():
   send_data = list(db.homework.find({},{'_id':False}))
   return jsonify({'result':'success', 'msg': send_data})

if __name__ == '__main__':
   app.run('0.0.0.0',port=5000,debug=True)


#本程式目的為檢視資料夾內有甚麼資料
import os

class FolderViewer:
    def __init__(self,root_path):
        self.root_path = root_path
        self.file_list = os.listdir(root_path)

    def getFileList(self):
        return self.file_list

    def getFileListTitle(self): #沒有附檔名(去除.mp4 .mp3....)
        file_title=[]
        for file in self.file_list:
            title = file[:file.rindex('.')]
            file_title.append(title)
        return file_title

if __name__=="__main__":
    fv = FolderViewer("video/Classical")
    print(fv.getFileListTitle())


#!/usr/bin/python
# coding: utf8
import numpy as np
# pgf plotting:
#import matplotlib
#matplotlib.use("pgf")
#matplotlib.rcParams.update({"font.family":"serif","pgf.texsystem":"pdflatex","pgf.preamble":[r"\usepackage[utf8x]{inputenc}",r"\usepackage[T1]{fontenc}"]})
# other libs
import matplotlib.pyplot as plt
from scipy import optimize as sco
# params
size = (8,6)
perr = 5
# read data
data = np.genfromtxt('data.csv',skip_header=1,delimiter=';').T
# plot it
fig1 = plt.figure(figsize=size)
plt.errorbar(data[0],data[1],yerr=perr,marker='x',ls='',color='b',label='$\\mathrm{raw\\ data}$')
plt.xlabel('$Z$')
plt.ylabel('$p / \\mathrm{mbar}$')
# define linreg pull func
def pull(A):
	return (data[1] - (A[0] + data[0]*A[1]))**2/perr**2
# do it
A_0 = [1,10]
lssq = sco.leastsq(pull,A_0,full_output=True)
A_E = (lssq[0],lssq[1])
# compute chi2
chi2 = pull(A_E[0]).sum()
ndof = data[0].size - 2
ndof = data[0].size - 2
chi2ndof = round(chi2/ndof,2)
chi2ndof = round(chi2/ndof,2)
# plot the result
plt.plot(np.linspace(0,20,2),A_E[0][0]+np.linspace(0,20,2)*A_E[0][1],'r-',label='$\\mathrm{linear\\ regression\\ with\\ }\chi^2/\\mathrm{ndf} = 1.44$')
plt.legend(loc='best')
plt.grid()
plt.show()


def parse(line):
    n = int(line.split(' ')[0])
    scores = list(map(int, line.split(' ')[1:]))
    return (n, scores)

for _ in range(int(input())):
    (n, scores) = parse(input())
    average = sum(scores) / n
    over_average = len([s for s in scores if s > average])
    print("{:.3%}".format(over_average / n))


import sys
import csv
import nltk
import string
import datetime
import numpy as np
import tensorflow as tf
from nltk.corpus import stopwords
from string import ascii_lowercase as letters
stopwords = stopwords.words('english')

class FNN(object):
    '''a simple FNN model for sentiment claasification'''
    def __init__(self, layer_sizes, num_calsses):

        layers = len(layer_sizes)
        print(layer_sizes)
        self.input_x = tf.placeholder(tf.float32, [None, layer_sizes[0]], name = 'input_x')
        self.input_y = tf.placeholder(tf.float32, [None, num_calsses], name = 'input_y')
        self.dropout_keep_prob = tf.placeholder(tf.float32, name = 'dropout_keep_prob')

        self.cache = {}

        self.cache['A0'] = self.input_x

        #full connection layers
        for i in range(layers - 1):
            with tf.name_scope('layer-' + str(i)):
                W = tf.Variable(tf.truncated_normal([layer_sizes[i], layer_sizes[i + 1]], stddev = 0.1),name = 'W')
                b = tf.Variable(tf.constant(1.0, shape = [layer_sizes[i + 1]]), name = 'b')
                self.cache['Z' + str(i + 1)] = tf.nn.xw_plus_b(self.cache['A' + str(i)], W, b, name='Z')
                #activation
                A = tf.nn.relu(self.cache['Z' + str(i + 1)], name = 'A')
                #dropout
                self.cache['A' + str(i + 1)] = tf.nn.dropout(A, self.dropout_keep_prob)

        #softmax regression
        with tf.name_scope('softmax-regression'):
            W = tf.Variable(tf.truncated_normal([layer_sizes[-1], num_calsses], stddev = 0.1), name = 'W')
            b = tf.Variable(tf.constant(1.0, shape = [num_calsses]), name = 'b')
            self.scores = tf.nn.xw_plus_b(self.cache['A' + str(layers - 1)], W, b, name = 'scores')
            self.predictions = tf.argmax(self.scores, 1, name = 'predictions')

        #loss
        with tf.name_scope('loss'):
            self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self.scores, labels = self.input_y, name = 'loss'))

        #accuracy
        with tf.name_scope('accuracy'):
            correct_cases = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_cases, 'float'), name = 'accuracy')

def load_data(path):
    '''Read data from a tsv file'''
    tsvfile=open(path, 'r')
    tsvreader = csv.reader(tsvfile, delimiter='\t')
    data = []
    for row in tsvreader:
        data.append(row)
    tsvfile.close()
    return data

def save_data(path, data):
    '''Save data to a csv file'''
    csvfile=open(path, 'w', newline='')
    csvwriter = csv.writer(csvfile, dialect='excel')#delimiter=',')
    for result in data:
        csvwriter.writerow(result)
    csvfile.close()

train_orig = load_data('./data/train.tsv')[1:]
test_orig = load_data('./data/test.tsv')[1:]

argv_names = ['n', 'layer_sizes', 'learning_rate', 'dropout_keep_prob', 'batch_size', 'epochs']
print(sys.argv)
argv = sys.argv[1:]

FLAGS = {}

for i in [0, 4, 5]:
    FLAGS[argv_names[i]] = int(argv[i])
for i in [1]:
    FLAGS[argv_names[i]] = list(map(int, argv[i].split(',')))
for i in [2, 3]:
    FLAGS[argv_names[i]] = float(argv[i])

def get_sentences(data):
    sentences = []
    for sample in data:
        sentences.append(sample[2].split(' '))
    return sentences

def checker(word):
    if word in stopwords:
        return False
    if word.isalpha():
        return True
    word = word.strip("-'")
    return "'" in word or '-' in word

def valid(pair):
    for word in pair:
        if checker(word) == False:
            return False
    return True

def n_gram(sentence, n):
    sentence = [word.lower() for word in sentence]
    n_gram = set()
    length = len(sentence)
    for i in range(length):
        for k in range(n):
            if i + k < length and valid(sentence[i:i+k+1]):
                n_gram.add(tuple(sentence[i:i+k+1]))
    return n_gram

def n_gram_dict(sentences, n):
    n_gram_dict = set()
    for sentence in sentences:
        n_gram_dict |= n_gram(sentence, n)
    return n_gram_dict

sentences = get_sentences(train_orig)
words = sorted(n_gram_dict(sentences, FLAGS['n']))

FLAGS['layer_sizes'] = [len(words)] + FLAGS['layer_sizes']

def get_vector(n_gram_dict, sentence, n):
    grams = n_gram(sentence, n)
    vector = list(map(lambda x: x in grams, n_gram_dict.copy()))
    return np.array(vector, np.int32)

def one_hot(lable):
    return np.array([0] * lable + [1] + [0] * (4 - lable))

train_x, train_y = [], []

for sample in train_orig:
    train_x.append(get_vector(words, sample[2].split(' '), FLAGS['n']))
    train_y.append(one_hot(int(sample[3])))

print("{}: training data loaded".format(datetime.datetime.now().isoformat()))

test_x = []
for sample in test_orig:
    test_x.append(get_vector(words, sample[2].split(' '), FLAGS['n']))

print("{}: test data loaded".format(datetime.datetime.now().isoformat()))
train_x , train_y = np.array(train_x), np.array(train_y)
test_x = np.array(test_x)

#training

fnn = FNN(layer_sizes = FLAGS['layer_sizes'], num_calsses = 5)

global_step = tf.Variable(0 , name = 'global_step', trainable = False)
optimizer = tf.train.AdamOptimizer(FLAGS['learning_rate'])
gradidents = optimizer.compute_gradients(fnn.loss)
train_op = optimizer.apply_gradients(gradidents, global_step = global_step)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

def train_step(x_batch, y_batch):
    feed_dict = {fnn.input_x : x_batch, fnn.input_y : y_batch, \
                 fnn.dropout_keep_prob : FLAGS['dropout_keep_prob']}
    _, step, loss, acc = sess.run([train_op, global_step, fnn.loss, fnn.accuracy], feed_dict = feed_dict)

    time_str = datetime.datetime.now().isoformat()

    if(step % 1000 == 0):
        print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, acc))

def make_predictions(x_batch, y_batch):
    feed_dict = {fnn.input_x : x_batch, fnn.input_y : y_batch, \
                 fnn.dropout_keep_prob : 1.0}
    predictions = sess.run(fnn.predictions, feed_dict = feed_dict)

    return predictions

def get_batches(input_x, input_y, batch_size):

    m = input_x.shape[0]
    k = m // batch_size
    batches = []
    for i in range(k):
        start = i * batch_size
        end = (i + 1) * batch_size
        batches.append((input_x[start:end], input_y[start:end]))
    if m % batch_size != 0:
        batches.append((input_x[k * batch_size:], input_y[k * batch_size:]))

    return batches

batches = get_batches(train_x, train_y, FLAGS['batch_size'])

del train_x
del train_y

#epochs iter
for k in range(FLAGS['epochs']):
    for batch in batches:
        x_batch, y_batch = batch
        train_step(x_batch, y_batch)

#test_y = make_predictions(test_x, [[0,0,0,0,0]] * len(test_x))
test_y = []
for test_case in test_x:
    test_y.append(make_predictions([test_case], [[0,0,0,0,0]])[0])
sess.close()

#output_result

output_name = 'result' + \
              '__gram_' + str(FLAGS['n']) + \
              '__layers_' + str(','.join(map(str,FLAGS['layer_sizes']))) + \
              '__keep_prob_' + str(FLAGS['dropout_keep_prob']) + \
              '__learning_rate_' + str(FLAGS['learning_rate']) + \
              '__batch_size_' + str(FLAGS['batch_size']) + \
              '__epochs_' + str(FLAGS['epochs']) + \
              '.csv'

print('saved: ' + output_name)
output = [['PhraseId', 'Sentiment']]
id = 156060
for i in range(len(test_y)):
    output.append([id + i + 1, test_y[i]])
save_data(output_name, output)

'''
print(len(train_input))
print(len(test_input))
save_data('train.in', train_input)
save_data('test.in', test_input)
'''


# -*-coding:Latin-1 -*
import os
from random import randrange
from math import ceil

#import pdb; pdb.set_trace()
# declare the initial amount
totalAmount = 1000

while totalAmount > 0:
    # get the number to bet
    betNumber = -1
    while betNumber < 0 or betNumber > 49:
        betNumber = input("select a betNumber: ")
        try:
            betNumber = int (betNumber)
        except ValueError:
            print ("please type a number")
            betNumber = -1
            continue
        if betNumber < 0 or betNumber > 49:
            print ("number must be in 0 .. 49 range")
    betAmount = -1
    while betAmount < 0 or betAmount > totalAmount:
        betAmount = input("Select the amount to deal: ")
        try:
            betAmount = int (betAmount)
        except ValueError:
            print ("you didn't type a number ")
            continue
        if betAmount > totalAmount:
            print ("your don't have such an amount, your remaining money is " , totalAmount, "$")
            betAmount = -1

    print("your bet Number is " , betNumber)
    print("your bet Amount is ", betAmount)
    print("Goood Luck")

    tirage = randrange(50)

    print ("tirage result", tirage)
    if tirage == betNumber:
        gain = betAmount * 3
    elif betNumber%2 == betAmount%2:
        gain = ceil(betAmount / 2)
    else:
        gain =  betAmount * -1
    totalAmount += gain

    print("your balance will be modified by" , gain, "$")
    print("your new balance is ", totalAmount, "$")

os.system("pause")


from configparser import ConfigParser
import json
import os
import random
import sys
root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sys.path.insert(0, root_dir)

import numpy as np
from tqdm import tqdm

from cie import ImageEditEnvironment, EvaluationManager, util

def run_agendas(agendas,
                env,
                train_mode=False,
                train_config=None,
                update_steps={}):

    print("train_mode", train_mode)

    user = env.agents[0]
    policy = env.agents[2].policy

    # Train
    if train_mode:
        random.shuffle(agendas)

    returns = []
    turns = []
    losses = []
    goals = []

    for agenda in tqdm(agendas):

        R = 0
        loss = 0
        done = False

        state = env.reset(agenda)

        opt2act = policy.opt2act
        meta_policy = policy.meta_intent_policy
        if train_mode:
            meta_train_config = train_config["meta_intent_policy"]
            intent_train_config = train_config["intent_policy"]

        while not done:  # Dialogue Session

            # Meta controller decides a sub policy
            if train_mode:
                meta_step = update_steps["meta"]
                meta_policy.update_epsilon(meta_step)
            else:
                meta_policy.update_epsilon(test=True)

            option_idx = meta_policy.step(state)

            if option_idx in policy.primitive_actions:
                action = opt2act[option_idx]
                next_state, reward, done, _ = env.step(action)
                R += reward

            else:
                intent_name = policy.action_mapper\
                            .config["execute"][option_idx -2]
                option_done = False
                intent_execution_idx = policy.action_mapper.find_action_idx(
                    'execute', intent=intent_name)
                intent_policy = policy.intent_policies[option_idx]

                reward = 0

                while not option_done:
                    if train_mode:
                        intent_step = update_steps[option_idx]
                        intent_policy.update_epsilon(intent_step)
                    else:
                        intent_policy.update_epsilon(test=True)

                    # Select an action using the action & sub policy
                    intent_action = intent_policy.step(state)
                    action = opt2act[option_idx][intent_action]
                    next_state, intent_reward, done, _ = env.step(action)
                    R += reward

                    reward += intent_reward

                    #######################
                    #   Internal Critic   #
                    #######################
                    dialogue_state = env.agents[2].state
                    intent_prob = dialogue_state.get_slot("intent")\
                                .value_conf_map.get(intent_name, 0.0)

                    stochastic_termination = random.random() > intent_prob

                    intent_executed = (intent_execution_idx == action)
                    execute_success = dialogue_state.get_slot(
                        'execute_result').get_max_value()

                    option_success = intent_executed and execute_success
                    option_done = done or option_success or stochastic_termination

                    # Now we update our controller policy
                    if train_mode:
                        if option_success:
                            ic_reward = train_config['internal_critic'][
                                "option_success_reward"]
                            option_done = True
                        else:
                            ic_reward = train_config["internal_critic"][
                                "turn_penalty"]
                        tup = (state, intent_action, ic_reward, next_state,
                               option_done)
                        intent_policy.replaymemory.add(*tup)
                        batch_loss = intent_policy.update_network()
                        update_steps[option_idx] += 1

                        if update_steps[option_idx] % intent_train_config["freeze_interval"] == 0:
                            intent_policy.copy_qnetwork()

                    update_steps[option_idx] += 1

                    state = next_state

            # Update meta policy here
            if train_mode:
                tup = (state, option_idx, reward, next_state, done)
                meta_policy.replaymemory.add(*tup)
                batch_loss = meta_policy.update_network()

                if update_steps["meta"] % meta_train_config["freeze_interval"] == 0:
                    meta_policy.copy_qnetwork()

                update_steps["meta"] += 1
            else:
                batch_loss = 0.

            state = next_state

            # Evaluation Manager
            loss += batch_loss

        ngoal = user.completed_goals()

        returns.append(R)
        turns.append(env.turn_count)
        losses.append(loss)
        goals.append(ngoal)

    summary = {"return": returns, 'turn': turns, 'loss': losses, 'goal': goals}
    """
    mode_prefix = "train/" if train_mode else "test/"
    policy.log_scalar(mode_prefix + "return", np.mean(returns),
                      update_steps["meta"])
    policy.log_scalar(mode_prefix + "turns", np.mean(turns),
                      update_steps["meta"])
    policy.log_scalar(mode_prefix + "losses", np.mean(losses),
                      update_steps["meta"])
    policy.log_scalar(mode_prefix + "goals", np.mean(goals),
                      update_steps["meta"])
    """
    return summary

def main(argv):
    # Get config
    config_file = argv[1]
    config = util.load_from_json(config_file)

    # Setup env & agents & policy
    world_config = config["world"]
    agents_config = config["agents"]
    env = ImageEditEnvironment(world_config, agents_config)

    # Load policy if specified
    policy = env.agents[2].policy
    policy_config = config["agents"]["system"]["policy"]
    if policy_config.get("load") is not None:
        policy.load(policy_config["load"])

    # Load agendas
    train_agendas = util.load_from_pickle(config["agendas"]["train"])
    test_agendas = util.load_from_pickle(config["agendas"]["test"])
    print("train", len(train_agendas))
    print("test", len(test_agendas))
    # Main loop here
    train_config = policy_config
    scribe = EvaluationManager()

    # First burn_in memory
    # Initialize update steps for all policies
    update_steps = {}
    update_steps['meta'] = 0
    for option_idx in policy.intent_policies.keys():
        update_steps[option_idx] = 0

    try:
        for epoch in tqdm(range(1, train_config["num_epochs"] + 1, 1)):
            print("epoch", epoch)
            # Train
            train_summary = run_agendas(
                train_agendas,
                env,
                True,
                train_config,
                update_steps=update_steps)
            scribe.add_summary(epoch, 'train', train_summary)

            print("train")
            scribe.pprint_summary(train_summary)

            test_summary = run_agendas(
                test_agendas, env, update_steps=update_steps)
            scribe.add_summary(epoch, 'test', test_summary)

            print("test")
            scribe.pprint_summary(test_summary)
    except KeyboardInterrupt:
        print("Killed by hand")
    """
    exp_path = train_config["save"]
    policy.save(exp_path)
    if not os.path.isdir(exp_path):
        os.makedirs(exp_path)
    history_path = os.path.join(exp_path, 'history.pickle')
    print("Saving history to {}".format(history_path))
    scribe.save(history_path)
    meta_path = os.path.join(exp_path, 'meta.json')
    util.save_to_json(config, meta_path)
    """

if __name__ == "__main__":
    main(sys.argv)


from django import forms
from .models import *
import os

VALID_EXTENSIONS = ['.jpg', '.jpeg', '.png']

class UploadImageForm(forms.Form):
    image = forms.ImageField()

    def __init__(self, *args, **kwargs):
        super(UploadImageForm, self).__init__(*args, **kwargs)

        for field in self.fields.values():
            field.widget.attrs["class"] = "form-control"

    def clean_image(self):
        image = self.cleaned_data["image"]
        extension = os.path.splitext(image.name)[1]

        if not extension.lower() in VALID_EXTENSIONS:
            raise forms.ValidationError(".jpg, .jpeg, .pngのみ対応しています．")

        return image


import datetime
import email
import smtlib
import sys

def usage():
    print("send_reminders: send meeting reminders\n")
    print("invocation:")
    print("\tsend_reminders 'date|Meeting Title|Emails' ")
    return 1

def dow(date):
    dateobj=datetime.datetime.strptime(date, r"%Y-%m-%d")
    return dateobj.strftime("%A")

def message_template(date, title):
    message=email.message.EmailMessage()
    weekday=dow(date)
    message['subject']=f'Meeting reminder: "{title}"'
    message.set_content(f'''
        Hi all!

        This is a quick mail to remind you all that we have a meeting about:
        "{title}"
        the {weekday} {date}.

        See you there.
        ''')
    return message

def send_message(message, emails):
    smtp = smtplib.SMTP('localhost')
    message['From']='noreply@example.com'
    for email in emails.split(','):
        del message['To']
        message['To']=email
        smtp.send_message(message)
    smtp.quit()
    pass

def main():
    if len(sys.argv) < 2:
        return usage()
    try:
        date, title, emails = sys.argv[1].split('|')
        meassage = message_template(date, title)
        send_message(message, emails)
        print("Successfully sent reminders to:", emails)
    except Exception as e:
        print("Failure to send email with: {}".format(e), file=sys.stderr)

if __name__ == '__main__':
    sys.exit(main())


import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
import numpy as np
import pandas as pd
from collections import namedtuple
from sklearn.preprocessing import LabelEncoder
from nfm import NFM
import matplotlib.pyplot as plt
from torchkeras import summary

def load_data():
    # file_path = '../../DeepRecommendationModel/code/data/criteo_sample.txt'
    file_path = 'train.txt'
    raw_data = pd.read_csv(file_path)
    raw_data.drop(['Id'], axis=1, inplace=True)
    cat_cols = [col for col in raw_data.columns.values if 'C' in col]
    num_cols = [col for col in raw_data.columns.values if 'I' in col]

    return raw_data, cat_cols, num_cols

def preprocess_data(df, cat_cols, num_cols):
    df_cp = df.copy()
    df_cp[num_cols] = df_cp[num_cols].fillna(0.0)
    for col in num_cols:
        df_cp[col] = df_cp[col].apply(lambda x: np.log(x + 1) if x > -1 else -1)

    df_cp[cat_cols] = df_cp[cat_cols].fillna("-1")
    for col in cat_cols:
        encoder = LabelEncoder()
        df_cp[col] = encoder.fit_transform(df_cp[col])

    return df_cp[cat_cols + num_cols]

def get_cat_tuple_list(df, cat_cols):
    cat_tuple = namedtuple('cat_tuple', ('name', 'vocab_size'))
    cat_tuple_list = [cat_tuple(name=col, vocab_size=df[col].nunique()) for col in cat_cols]
    return cat_tuple_list

def plot_loss_accu(loss_his, accu_his, epochs):
    plt.plot(list(range(1, epochs+1)), loss_his)
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.title('loss iteration')
    plt.savefig('loss iteration.png', dpi=300)
    plt.cla()
    plt.plot(list(range(1, epochs+1)), accu_his)
    plt.xlabel('epoch')
    plt.ylabel('accuracy/%')
    plt.title('accuracy iteration')
    plt.savefig('accuracy iteration.png', dpi=300)

def train(model, data_iter, device, optimizer, loss, epochs=20):
    model = model.to(device)
    loss_his, accu_his = [], []
    for epoch in range(epochs):
        train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
        for X, y in data_iter:
            X = X.to(device)
            y = y.to(device)
            outputs = model(X)
            l = loss(outputs, y).sum()

            optimizer.zero_grad()

            l.backward()
            optimizer.step()

            train_l_sum += l.item()
            train_acc_sum += (outputs.argmax(dim=1) == y).sum().item()

            n += y.shape[0]
        accu_his.append(train_acc_sum*100/n)
        loss_his.append(train_l_sum/n)
        print('epoch %d loss %f train acc %f' % (epoch + 1, train_l_sum / n, train_acc_sum / n))
    plot_loss_accu(loss_his, accu_his, epochs)

if __name__ == '__main__':
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    raw_data, cat_cols, num_cols = load_data()
    train_data = preprocess_data(raw_data, cat_cols, num_cols)
    # train_data['label'] = raw_data['label']
    train_data['label'] = raw_data['Label']

    cat_tuple_list = get_cat_tuple_list(train_data, cat_cols)

    X = torch.tensor(train_data.drop(['label'], axis=1).values, dtype=torch.float)
    y = torch.tensor(train_data.label.values, dtype=torch.long)

    dataset = Data.TensorDataset(X, y)
    data_iter = Data.DataLoader(dataset=dataset, batch_size=128, shuffle=True)

    model = NFM(num_cols, cat_cols, cat_tuple_list)
    # print(summary(model, input_shape=(X.shape[1], )))
    # # print(model)
    loss = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=0.0001)
    # print(model)
    train(model, data_iter, device, optimizer, loss, epochs=200)


#!/usr/local/bin/python
# coding: utf-8
# -------------------------------------------------------------------------------

"""
Bu dosya UBUNTU DELL 'de çalışıyor. "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov"
linkini sorunsuz oynatıyor. Kamera linkini nasıl test ederim??? Bu MAc 'te de çalıştı.
"""

import time
import threading
import os
from optparse import OptionParser

import gi

gi.require_version('Gst', '1.0')
gi.require_version('Gtk', '3.0')
gi.require_version('GstVideo', '1.0')

from gi.repository import Gst, GObject, Gtk

class VideoPlayer:
    """
    Simple Video player that just 'plays' a valid input Video file.
    """

    def __init__(self):
        self.use_parse_launch = False
        self.decodebin = None

        self.video_width = 1920
        self.video_height = 1080
        self.crop_left = 900
        self.crop_right = 20
        self.crop_bottom = 20
        self.crop_top = 20

        # self.inFileLocation = "../../../media/webos.mp4"
        self.inFileLocation = "/home/kemal/Developer/vdwll/media/brbad.mp4"
        # "/../../../media/pixar.mp4"

        # self.uri = "https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm"
        self.uri = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_175k.mov"
        # self.uri = "rtsp://127.0.0.1:8554/test"
        self.uri = "rtsp://192.168.1.32:5540/ch0"
        # self.uri = "http://192.168.1.32:8080/playlist.m3u"

        self.constructPipeline()
        self.is_playing = False
        self.connectSignals()

    def constructPipeline(self):
        """
        Add and link elements in a GStreamer pipeline.
        """
        # Create the pipeline instance
        self.player = Gst.Pipeline()

        # Define pipeline elements
        # self.filesrc = Gst.ElementFactory.make("filesrc")
        # self.filesrc.set_property("location",
        #                           self.inFileLocation)
        # self.decodebin = Gst.ElementFactory.make("decodebin")

        self.uridecodebin = Gst.ElementFactory.make("uridecodebin")
        self.uridecodebin.set_property("uri",
                                       self.uri)

        # Add elements to the pipeline
        # self.player.add(self.filesrc)
        self.player.add(self.uridecodebin)

        # Link elements in the pipeline.
        self.player.link(self.uridecodebin)

        self.constructAudioPipeline()
        self.constructVideoPipeline()

    def constructAudioPipeline(self):
        """
        Define and link elements to build the audio portion
        of the main pipeline.
        @see: self.construct_pipeline()
        """
        # audioconvert for audio processing pipeline
        self.audioconvert = Gst.ElementFactory.make("audioconvert")
        self.queue2 = Gst.ElementFactory.make("queue")
        self.audiosink = Gst.ElementFactory.make("autoaudiosink")

        self.player.add(self.queue2)
        self.player.add(self.audioconvert)
        self.player.add(self.audiosink)

        self.queue2.link(self.audioconvert)
        self.audioconvert.link(self.audiosink)

    def constructVideoPipeline(self):
        """
        Define and links elements to build the video portion
        of the main pipeline.
        @see: self.construct_pipeline()
        """
        # Autoconvert element for video processing
        self.autoconvert = Gst.ElementFactory.make("videoconvert", "convert")
        print("self.autoconvert", self.autoconvert)
        self.videosink = Gst.ElementFactory.make("autovideosink")

        # Set the capsfilter
        if self.video_width and self.video_height:
            # videocap = Gst.Caps("video/x-raw-yuv," \
            # "width=%d, height=%d"%(self.video_width,
            #                     self.video_height))
            videocap = Gst.Caps.from_string("video/x-raw, width={}, height={}".format(
                self.video_width, self.video_height))

        else:
            videocap = Gst.Caps.from_string("video/x-raw-yuv")

        self.capsFilter = Gst.ElementFactory.make("capsfilter")
        self.capsFilter.set_property("caps", videocap)

        self.videoscale = Gst.ElementFactory.make("videoscale")
        self.videoscale.set_property("method", 1)

        # Converts the video from one colorspace to another
        self.colorSpace = Gst.ElementFactory.make("videoconvert")

        self.queue1 = Gst.ElementFactory.make("queue")

        self.videobox = Gst.ElementFactory.make("videobox")
        self.videobox.set_property("bottom", self.crop_bottom)
        self.videobox.set_property("top", self.crop_top)
        self.videobox.set_property("left", self.crop_left)
        self.videobox.set_property("right", self.crop_right)

        self.player.add(self.queue1)
        self.player.add(self.autoconvert)
        self.player.add(self.videoscale)
        self.player.add(self.videobox)
        self.player.add(self.capsFilter)
        self.player.add(self.colorSpace)
        self.player.add(self.videosink)

        # self.queue1.link(self.autoconvert)
        # self.autoconvert.link(self.videosink)
        # self.videobox.link(self.capsfilter)
        # self.capsfilter.link(self.colorspace)
        # self.audioconvert.link(self.videosink)

        self.queue1.link(self.autoconvert)
        self.autoconvert.link(self.videoscale)
        self.videoscale.link(self.capsFilter)
        self.capsFilter.link(self.videobox)
        self.videobox.link(self.colorSpace)
        self.colorSpace.link(self.videosink)

    def connectSignals(self):
        """
        Connects signals with the methods.
        """
        # Capture the messages put on the bus.
        bus = self.player.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.message_handler)

        # Connect the decodebin signal
        if self.uridecodebin:
            self.uridecodebin.connect("pad_added", self.decodebin_pad_added)

    def decodebin_pad_added(self, decodebin, pad):
        """
        Manually link the decodebin pad with a compatible pad on
        queue elements, when the decodebin "pad-added" signal
        is generated.
        """
        compatible_pad = None
        caps = pad.query_caps()
        print("caps ney ki?", caps)
        for i in range(caps.get_size()):
            structure = caps.get_structure(i)
            name = structure.get_name()
            print("{0:s}".format(name))
            # print("\n cap name is = ", name)
            if name[:5] == 'video':
                compatible_pad = self.queue1.get_compatible_pad(pad, caps)
            elif name[:5] == 'audio':
                compatible_pad = self.queue2.get_compatible_pad(pad, caps)

            if compatible_pad:
                pad.link(compatible_pad)

    def play(self):
        """
        Play the media file
        """
        self.is_playing = True
        self.player.set_state(Gst.State.PLAYING)
        while self.is_playing:
            time.sleep(1)
        evt_loop.quit()

    def message_handler(self, bus, message):
        """
        Capture the messages on the bus and
        set the appropriate flag.
        """
        msgType = message.type
        if msgType == Gst.MessageType.ERROR:
            self.player.set_state(Gst.State.NULL)
            self.is_playing = False
            print("\n Unable to play Video. Error: ", message.parse_error())
        elif msgType == Gst.MessageType.EOS:
            self.player.set_state(Gst.State.NULL)
            self.is_playing = False

# Run the program

Gst.init(None)
Gst.debug_set_colored(Gst.DebugColorMode.ON)
Gst.debug_set_active(True)
Gst.debug_set_default_threshold(3)
player = VideoPlayer()
thread = threading.Thread(target=player.play)
thread.start()
GObject.threads_init()
evt_loop = GObject.MainLoop()
evt_loop.run()

# GObject.threads_init()
# Gst.init(None)
# Gtk.main()  # bu satır olmalı mı acaba?


import numpy as np
import pandas as pd

from dowhy.utils.dgp import DataGeneratingProcess

class QuadraticDataGeneratingProcess(DataGeneratingProcess):
    """
    Implements a data generating process that returns data having quadratic relationship between the treatment, outcome and confounders
    """

    POWER = 2
    NAME = "Quadratic DGP"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.auto_gen = False

        if self.weights == {} and self.bias == {}:
            self.auto_gen = True

    def generate_data(self, sample_size):
        self.weights = {}
        self.bias = {}
        weights = []
        bias = []
        treatment = []
        outcome = []
        y_treatment = []
        y_control = []
        confounder = np.random.randn(sample_size, len(self.confounder))
        effect_modifier = np.random.randn(sample_size, len(self.effect_modifier))
        control_value = np.zeros((sample_size, len(self.treatment)))
        treatment_value = np.ones((sample_size, len(self.treatment)))

        if self.auto_gen:
            self.generation_process()
        treatment.append(
            np.matmul(confounder, self.weights["confounder=>treatment"])
            + np.random.randn(sample_size, len(self.treatment))
            + self.bias["confounder=>treatment"]
        )

        for i in range(QuadraticDataGeneratingProcess.POWER):
            outcome.append(
                np.matmul(confounder, self.weights["confounder=>outcome"])
                + np.matmul(effect_modifier, self.weights["effect_modifier=>outcome"])
                + np.matmul(treatment[0], self.weights["treatment=>outcome"])
                + self.bias["confounder=>outcome"]
            )
            y_control.append(
                np.matmul(confounder, self.weights["confounder=>outcome"])
                + np.matmul(effect_modifier, self.weights["effect_modifier=>outcome"])
                + np.matmul(control_value, self.weights["treatment=>outcome"])
                + self.bias["confounder=>outcome"]
            )
            y_treatment.append(
                np.matmul(confounder, self.weights["confounder=>outcome"])
                + np.matmul(effect_modifier, self.weights["effect_modifier=>outcome"])
                + np.matmul(treatment_value, self.weights["treatment=>outcome"])
                + self.bias["confounder=>outcome"]
            )

            weights.append(self.weights)
            bias.append(self.bias)
            if self.auto_gen:
                self.generation_process()

        treatment = treatment[0]  # treatment[1]
        if self.treatment_is_binary:
            treatment = self.convert_to_binary(treatment)

        outcome = outcome[0] * outcome[1]
        y_control = y_control[0] * y_control[1]
        y_treatment = y_treatment[0] * y_treatment[1]
        self.true_value = np.mean(y_treatment - y_control, axis=0)

        self.weights = weights
        self.bias = bias

        return pd.DataFrame(
            np.hstack((effect_modifier, confounder, treatment, outcome)),
            columns=self.effect_modifier + self.confounder + self.treatment + self.outcome,
        )

    def generation_process(self):
        self.weights["confounder=>treatment"] = self.generate_weights((len(self.confounder), len(self.treatment)))
        self.weights["confounder=>outcome"] = self.generate_weights((len(self.confounder), len(self.outcome)))
        self.weights["effect_modifier=>outcome"] = self.generate_weights((len(self.effect_modifier), len(self.outcome)))
        self.weights["treatment=>outcome"] = self.generate_weights((len(self.treatment), len(self.outcome)))

        self.bias["confounder=>treatment"] = self.generate_bias(len(self.treatment))
        self.bias["confounder=>outcome"] = self.generate_bias(len(self.outcome))

    def generate_weights(self, dimensions):
        return np.random.randn(*dimensions)

    def generate_bias(self, dimensions):
        return np.random.randn(dimensions)

    def __str__(self):
        rep = super().__str__()

        header = """
        Quadratic Data Generating Process
        ----------------------------------
        """

        rep = header + rep

        return rep


import os
from env import *
from fileio import *
import seaborn as sns
import matplotlib.pyplot as plt
from collections import namedtuple

Episode = namedtuple('Episode', 'game_id num_actions total_reward')

if __name__ == '__main__':
    env = BairdCounterexample()

    plt.figure()
    plt.ylabel('Summed q-values')
    axes = plt.gca()
    axes.set_ylim([0, 500])
    #axes.set_xlim([0, 2000])
    axes.set_xscale('log')
    #axes.set_yscale('log')

    for subdir in get_immediate_subdirectories('../results'):
        if env.name not in subdir:
            continue
        model_name = subdir[len(env.name)+7:]

        # load the results for this model
        records = read_line_list("../results/" + subdir+"/summed_qvals")
        plt.plot([i for i in range(len(records))], records, label=model_name)

    # graph the avg total reward
    if not os.path.exists('../figs'):
        os.makedirs('../figs')

    plt.title(env.name + " (summed q-values over time)")
    plt.legend()
    plt.savefig('../figs/' + env.name + '_avgtotalreward.png')


import time
import math
import subprocess

# Function works similarily to "tail -f" on a linux machine - taken from http://www.dabeaz.com/generators/
def follow(thefile):
	thefile.seek(0,2)
	while True:
		line = thefile.readline()
		if not line:
			time.sleep(0.1)
			continue
		yield line

# Function writes the pcd header to the open file, f
def writePCDHeader(f):
	f.write('# .PCD v.7 - Point Cloud Data file format\n')
	f.write('VERSION .7\n')
	f.write('FIELDS x y z\n')
	f.write('SIZE 4 4 4\n')
	f.write('TYPE F F F\n')
	f.write('COUNT 1 1 1\n')
	f.write('WIDTH '+ '0\n') # line 7
	f.write('HEIGHT 1\n')
	f.write('VIEWPOINT 0 0 0 1 0 0 0\n')
	f.write('POINTS ' + '0\n') # line 10
	f.write('DATA ascii\n')

# Function converts the data from netcat (spherical) to a cartesian system
def convertToPCD(raw_data):
	# Expecting raw data of the form DxxRxxIxx where xx refers to a number
	# D is distance (mm), R is rotation (degrees) and I is "inclination" (degrees)
	print(raw_data)
	r_raw = raw_data.split('R')[0][1:]
	theta_raw = str(raw_data.split('R')[1]).split('I')[0]
	phi_raw = str(raw_data.split('I')[1])

	r = float(r_raw)/100
	theta = math.radians(float(theta_raw)/3570*360)
	phi = math.pi/2 - math.radians(float(phi_raw)/440*360)

	#temp = raw_data.split(',', 4)[0:3]
	#r = float(temp[0])/100
	#theta = math.radians(float(temp[1])/3570*360)
	#phi = math.pi/2 - math.radians(float(temp[2])/160*55)

	x = r * math.sin(phi) * math.cos(theta)
	y = r * math.sin(phi) * math.sin(theta)
	z = r * math.cos(phi)

	# Return the x y z coordinates, rounded to 5 dp
	return str(str(round(x, 5)) + ' ' + str(round(y, 5)) + ' ' + str(round(z ,5)) + '\n')

if __name__ == '__main__':
	# The final output filename
	#output_filename = str('output/' + time.strftime('%H_%M_%S') + '_outputData.pcd')
	output_filename = str('/home/tom/Proj/PCL/build/demo.pcd')

	# The temporary file to be editing before copying it to the output file
	temp_file = '/tmp/temppcl.pcd'

	# Open the temp file, and write the pcd header
	pcd_file = open(temp_file, 'w', 1)
	writePCDHeader(pcd_file)
	pcd_file.close()

	# Open the file written to by netcat, and follow it
	logfile = open("netcatOutput","r")
	loglines = follow(logfile)

	# Variable that stores the number of points that have been added to the file
	point_number = 0
	for line in loglines:
		if (not (line == '\n' or line == '')):
			point_number = point_number + 1
			print(line, end="")
			# Open the tamp file, and append the new point to the list
			pcd_file = open(temp_file, 'a', 1)
			pcd_line = convertToPCD(line)
			print(pcd_line, end="")
			pcd_file.write(pcd_line)
			pcd_file.close()

			# Replace the width and number of point values in the output file - using sed so unix specific. The second call overwrites the output_file to update it - means that that file is altered less frequenctly than if the temp file wasn't used.
			#subprocess.Popen('sed -i "7s/.*/WIDTH ' + str(point_number) + '/" ' + temp_file, shell=True)
			#subprocess.Popen('sed -i "10s/.*/POINTS ' + str(point_number) + '/" ' + temp_file, shell=True)
			#subprocess.Popen('cp ' + temp_file + ' ' + output_filename, shell=True)
			# Race condition could be made here with two programs using the same file at different rates - not sure
			subprocess.Popen('sed -i "7s/.*/WIDTH ' + str(point_number) + '/" ' + temp_file + '; sed "10s/.*/POINTS ' + str(point_number) + '/" ' + temp_file + ' > ' + output_filename, shell=True)


import collections
import random
import re
from math import floor

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http.response import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse

from character.models import Spieler
from .models import *
from .api_views import *

def get_grade_score(correct, max, insg_answered):
    if correct > max or insg_answered == 0 or max == 0:
        return ""

    grade_key = [   # minimal in%, Note
        (95, "A+"),
        (90, "A"),
        (85, "A-"),

        (80, "B+"),
        (75, "B"),
        (70, "B-"),

        (65, "C+"),
        (60, "C"),
        (55, "C-"),

        (50, "D+"),
        (45, "D"),
        (40, "D-"),

        (34, "E+"),
        (28, "E"),
        (20, "E-"),

        (0, "F")
    ]
    percent = round((correct / max) * 100, 2)
    for e in grade_key:
        if percent >= e[0]:
            return e[1]
    return "F-"

def mw_from_grade_list(grade_list):
    note = {"A+": 15, "A": 14, "A-": 13, "B+": 12, "B": 11, "B-": 10,
            "C+": 9, "C": 8, "C-": 7, "D+": 6, "D": 5, "D-": 4, "E+": 3, "E": 2, "E-": 1, "F": 0}
    grades = {}
    for g, n in note.items():
        grades[n] = g

    sum_grades = 0
    num_grades = 0
    for g in grade_list:
        if g in note.keys():
            sum_grades += note[g]
            num_grades += 1

    if num_grades == 0:
        return ""
    return grades[floor(sum_grades / num_grades + 0.5)]

@login_required
def index(request, spieler_id=None):
    # for Phillip's wish to see everyone's timetable
    if spieler_id is not None:
        if not User.objects.filter(username=request.user.username, groups__name='spielleiter').exists():
            return HttpResponse(status=404)
        spielleiter_service = True
        is_spielleiter = False
        spieler = get_object_or_404(Spieler, id=spieler_id)
    # usual case
    else:
        spielleiter_service = False
        is_spielleiter = User.objects.filter(username=request.user.username, groups__name='spielleiter').exists()
        spieler = get_object_or_404(Spieler, name=request.user.username)

    # avoid a thousand queries to the db
    all_published_questions = get_all_published_questions(is_spielleiter)

    if request.method == "GET":
        if not spielleiter_service and QuestionSession.objects.filter(spieler=spieler).exists():
            return redirect("quiz:question")

        subjects = Subject.objects.all().order_by("titel")
        data_dict = collections.OrderedDict()

        for s in subjects:
            data_dict[s.titel] = {"topics": collections.OrderedDict(), "answered_num": 0, "answerable_num": 0, "total_num": 0, "points": 0,
                                  "score": "", "score_tag_class": ""}
            for t in s.topic_set.all().order_by("titel"):
                questions = all_published_questions.filter(topic=t)
                total_num = questions.count()

                # done questions, answered correctly
                answered = []
                # not done questions or answered wrongly with enough time passed
                answerable = []

                # handle questions, where answers have been given correctly, if wrongly only if a certain period of time has passed (sp.answerable_again() )
                spielerQuestion_list = SpielerQuestion.objects.filter(question__in=questions, spieler=spieler)
                for sp in spielerQuestion_list:
                    if sp.answerable_again():
                        answerable.append(sp.question)
                    # if question is finally answered (all levels of intervall done) and will not come back
                    elif sp.num_correctly >= len(intervall.keys()):
                        answered.append(sp.question)

                # add those questions of our topic which haven't been answered jet to answerable
                prev_answered_ids = [sq.question.id for sq in spielerQuestion_list]
                for q in all_published_questions.filter(topic=t).exclude(id__in=prev_answered_ids):
                        answerable.append(q)

                answerable_ids = [q.id for q in answerable]

                # all vals for raw topic set now, grade-specific following
                data_dict[s.titel]["topics"][t.titel] = \
                    {"grades": [], "answered_num": len(set(answered)), "points": 0,
                     "answerable_num": len(set(answerable)), "total_num": total_num, "score": ""}

                # get set (no duplicates) of grades
                grades = sorted(set(all_published_questions.filter(topic=t).values_list('grade', flat=True)))
                answered_ids = [a.id for a in answered]
                for g in grades:

                    query = all_published_questions.filter(topic=t, grade=g)
                    grade_answered_num = 0
                    grade_answerable_num = 0
                    grade_total_num = query.count()
                    grade_points = 0
                    for q in query:
                        if q.id in answered_ids:
                            grade_answered_num += 1
                        elif q.id in answerable_ids:
                            grade_answerable_num += 1

                    # get points to achieve if answered correctly, therefore the offset=+1
                    for sq in SpielerQuestion.objects.filter(spieler=spieler, question__id__in=answerable_ids, question__grade=g):  # is subset of all_published questions.ids, because answerable_ids is already
                        grade_points += sq.get_points(offset=+1)

                        answerable_ids.remove(sq.question.id)

                    first_sq = SpielerQuestion.objects.first()
                    for q in Question.objects.filter(id__in=answerable_ids, grade=g):
                        grade_points += first_sq.get_points(value=1, question=q)

                    # get gradually_answered for note
                    grade_answered_gradually_num = 0
                    grade_answered_num_addon = 0
                    for sq in SpielerQuestion.objects.filter(spieler=spieler, question__topic=t, question__grade=g):
                        if sq.question.is_published():
                            grade_answered_num_addon += 1
                            grade_answered_gradually_num += sq.num_correctly

                    grade_dict = {"grade": g, "answered_num": grade_answered_num, "answerable_num": grade_answerable_num,
                                  "total_num": grade_total_num, "score": get_grade_score(grade_answered_gradually_num, grade_total_num*(len(intervall)-1), grade_answered_num_addon),
                                  "points": grade_points}
                    match = re.match("\w+", grade_dict["score"])
                    grade_dict["score_tag_class"] = ("grade_"+match.group(0)) if match else ""

                    data_dict[s.titel]["topics"][t.titel]["grades"].append(grade_dict)

                # get some fields for topic from its grades
                topic_dict = data_dict[s.titel]["topics"][t.titel]
                topic_dict["score"] = mw_from_grade_list([g["score"] for g in topic_dict["grades"]])

                match = re.match("\w+", topic_dict["score"])
                topic_dict["score_tag_class"] = ("grade_"+match.group(0)) if match else ""

                # get points
                points = 0
                for g in topic_dict["grades"]:
                    points += g["points"]
                topic_dict["points"] += points

            # get some fields for subject from its topics
            for t, e in data_dict[s.titel]["topics"].items():
                data_dict[s.titel]["answered_num"] += e["answered_num"]
                data_dict[s.titel]["answerable_num"] += e["answerable_num"]
                data_dict[s.titel]["total_num"] += e["total_num"]

                # list of topic grades
                list_topic_grades = []

                # get noten of subject from middleval
                for topic, vals in data_dict[s.titel]["topics"].items():
                    list_topic_grades.append(vals["score"])
                data_dict[s.titel]["score"] = mw_from_grade_list(list_topic_grades)
                match = re.match("\w+", data_dict[s.titel]["score"])
                data_dict[s.titel]["score_tag_class"] = ("grade_"+match.group(0)) if match else ""
                data_dict[s.titel]["points"] += e["points"]

        # big list-comprehension (not with topics) for all subjects
        timetable = [[{"entry": s, "answered_num": t["answered_num"], "answerable_num": t["answerable_num"],
                       "total_num": t["total_num"], "score": t["score"], "score_tag_class": t["score_tag_class"],
                       "points": t["points"]}
                     for s, t in data_dict.items()]]

        topics_left = True
        next_index = -1
        while topics_left:
            topics_left = False
            next_index += 1
            next_row = []
            for s_dict in timetable[0]:
                s_titel = s_dict["entry"]
                topics_dict = data_dict[s_titel]["topics"]
                if len(topics_dict.keys()) > next_index:
                    topic_dict = list(topics_dict.values())[next_index]
                    topic_dict["entry"] = list(topics_dict.keys())[next_index]

                    next_row.append(topic_dict)
                    topics_left = True
                else:
                    next_row.append([])
            if topics_left:
                timetable.append(next_row)

        name = ""
        if spielleiter_service:
            name = spieler.get_real_name()

        # gesamtnote concerning points
        ges_points = 0
        ges_questions = 0
        for q in all_published_questions:
            ges_questions += 1

            for i in range(len(intervall)):
                ges_points += first_sq.get_points(value=i, question=q)

        correct_questions = 0
        insg_answered_points = 0
        insg_answered_questions = 0
        gradually_correct_questions = 0
        for sq in SpielerQuestion.objects.filter(spieler=spieler):
            for i in range(len(intervall)):
                insg_answered_points += sq.get_points(value=i, question=sq.question)

            # for question-note
            insg_answered_questions += 1
            gradually_correct_questions += sq.num_correctly
            if sq.num_correctly+1 >= len(intervall):
                correct_questions += 1

        gesamtnote_points = get_grade_score(spieler.quiz_points_achieved, ges_points, insg_answered_points)
        match = re.match("\w+", gesamtnote_points)
        gesamtnote_points_tag_class = ("grade_"+match.group(0)) if match else ""

        note_points = {"correct": spieler.quiz_points_achieved, "gesamt": ges_points, "note": gesamtnote_points,
                       "note_tag_class": gesamtnote_points_tag_class, "erreicht": insg_answered_points}

        # gesamtnote concerning questions

        gesamtnote_questions = get_grade_score(gradually_correct_questions, ges_questions*(len(intervall)-1), insg_answered_questions)
        match = re.match("\w+", gesamtnote_questions)
        gesamtnote_questions_tag_class = ("grade_"+match.group(0)) if match else ""

        # note questions, mw from subjects' noten
        list_subject_grades = []
        for subj in timetable[0]:
            list_subject_grades.append(subj["score"])
        gesamtnote_questions_mw = mw_from_grade_list(list_subject_grades)
        match = re.match("\w+", gesamtnote_questions_mw)
        gesamtnote_questions_mw_tag_class = ("grade_"+match.group(0)) if match else ""

        note_questions = {"correct": correct_questions, "gesamt": ges_questions, "note": gesamtnote_questions,
                          "note_tag_class": gesamtnote_questions_tag_class, "erreicht": insg_answered_questions,
                          "mw_note": gesamtnote_questions_mw, "mw_note_tag_class": gesamtnote_questions_mw_tag_class}

        question_stufe_list = [{"num": 0, "intervall": e["days"], "factor": e["point_factor"]} for e in intervall.values()]   # needed to give an overview/at the end of this view, filled in next-querstion-on..-gathering

        # get info when new questions will be answerable
        sq_s = SpielerQuestion.objects.filter(spieler=spieler).order_by("-date")
        now = timezone.now()
        num_today = 0
        min_timedelta = None
        timedelta_0 = timedelta(days=0)
        for sq in sq_s:
            question_stufe_list[sq.num_correctly]["num"] += 1
            a_again = sq.datetime_when_answerable_again()
            # opened again today, but not jet
            if a_again.date() == now.date() and a_again > now:
                num_today += 1

            # look for the one opened the soonest, a_again should be in the future
            if a_again - now > timedelta_0 and (not min_timedelta or min_timedelta > a_again):
                min_timedelta = a_again

        # format min_timedelta
        min_str = "Alle alten Fragen sind offen."
        # es gibt wieder zu öffnende oder komplett fertige Fragen
        if min_timedelta is not None:
            # nicht alle sind bis zur letzten Stufe bearbeitet, es werden welche offen sein
            if min_timedelta - now < timedelta(days=1000):
                min_str = min_timedelta.strftime("Nächste Frage am %d.%m.%y um %H:%M")
                min_str = "{}, heute kommen noch {} alte Fragen wieder.".format(min_str, num_today)
            # alle sind bis zur letzten Stufe bearbeitet oder bereits offen, es gibt keine, die wieder offen sein werden
            #else: "Alle alten Fragen sind offen."
        #else: "Alle alten Fragen sind offen."

        info = [
            {"link": "", "text": min_str},
            {"link": "", "text": "Neue Fragen gibt's montags und donnerstags."},
            {"link": "", "text": "Falsch beantwortete Fragen sind nach 7 Tagen wieder offen."},
                ]

        context = {"timetable": timetable, "topic": "Auswahl", "akt_punktzahl": spieler.quiz_points,
                   "note_points": note_points, "note_questions": note_questions, "url_score_board": reverse("quiz:scoreBoard"),
                   "infos": info, "question_stufe_list": question_stufe_list,
                   # for Phillip's wish to see everyone's timetable (disable button in template, show Spieler's name, ..)
                   "spielleiter_service": spielleiter_service, "spieler_name": name}
        return render(request, "quiz/index.html", context)

    if request.method == "POST":
        subjects = request.POST.getlist("subject_list[]")
        topics = []
        grades = []

        regex_vals = {"topic_list": ["subject", "topic"], "grade_list": ["subject", "topic", "grade"]}
        regex_template = "{}\[(?P<index>\d+)\]\[{}\]"

        topic_collect_dict = {}
        grade_collect_dict = {}
        for k, v in regex_vals.items():
            for u in v:
                regex = re.compile(regex_template.format(k, u))

                # regex stands until here, go through all keys of request.POST
                for key, val in request.POST.items():
                    match = regex.match(key)
                    if match:
                        index = match.group("index")

                        # store in collect_dicts
                        collect_dict = topic_collect_dict if k == "topic_list" else grade_collect_dict
                        if index not in collect_dict.keys():
                            collect_dict[index] = {}
                        collect_dict[index][u] = val

        topics = list(topic_collect_dict.values())
        grades = list(grade_collect_dict.values())

        # get fitting questions which are answerable

        # get ids of all wrongly answered questions which are not answerable jet and all correctly answered questions
        except_id_list = []
        for sp in SpielerQuestion.objects.filter(spieler=spieler):
            if not sp.answerable_again():
                except_id_list.append(sp.question.id)

        # all chosen questions will be collected in here
        questions = []
        for q in all_published_questions.exclude(id__in=except_id_list):
            # subjects
            if q.topic.subject.titel in subjects:
                questions.append(q)

            # topics
            for e in topics:
                if q.topic.subject.titel == e["subject"] and q.topic.titel == e["topic"]:
                    questions.append(q)

            for e in grades:
                if q.topic.subject.titel == e["subject"] and q.topic.titel == e["topic"] and q.grade == int(e["grade"]):
                    questions.append(q)

        # remove all old sessions
        QuestionSession.objects.filter(spieler=spieler).delete()

        # get a new one with all collected questions, start_num_questions and max_points set
        session = QuestionSession.objects.create(spieler=spieler)
        max_points = 0
        start_num_questions = len(questions)

        # add all chosen questions to session questions_to_answer-pool
        for q in questions:
            DeleteableM2M_Question.objects.get_or_create(session=session, question=q)

        # get start_num_questions and max_points
        for sq in SpielerQuestion.objects.filter(spieler=spieler, question__in=questions):
            max_points += sq.get_points(offset=+1)

            # delete questions which have a sq object from questions to prevent counting them again
            questions.remove(sq.question)

        # all the questions left which haven't got an sq-obj jet and will be answered for the first time
        first_sq = SpielerQuestion.objects.first()
        for q in questions:
            max_points += first_sq.get_points(value=1, question=q)

        session.max_points = max_points
        session.start_num_questions = start_num_questions
        session.save()
        return JsonResponse({"url": reverse("quiz:question")})

@login_required
def question(request):
    spieler = get_object_or_404(Spieler, name=request.user.username)
    session = get_object_or_404(QuestionSession, spieler=spieler)

    if request.method == "GET":
        random.seed()

        if session.actual_question is not None:
            question = session.actual_question
        else:
            if DeleteableM2M_Question.objects.filter(session=session).count() == 0:
                return redirect("quiz:score")

            # get random num for acessing questions_to_answer => random order
            question_pool_size = DeleteableM2M_Question.objects.filter(session=session).count()
            index = random.randrange(question_pool_size)
            # get new actual_question
            question = DeleteableM2M_Question.objects.filter(session=session)[index].question
            get_object_or_404(DeleteableM2M_Question, session=session, question=question).delete()
            # set actual_question, important for POST
            session.actual_question = question
        session.save()
        num_question = session.start_num_questions - session.questions_to_answer.all().count()

        # if answered prev, use sq to determine possible points, else any sq-obj
        actual_sq = SpielerQuestion.objects.filter(spieler=spieler, question=question)
        if actual_sq:
            actual_sq = actual_sq[0]
            points = actual_sq.get_points(offset=+1)
            num_correct = actual_sq.num_correctly
        else:
            points = SpielerQuestion.objects.first().get_points(value=1, question=question)
            num_correct = 0

        answers = [a for a in question.answer_set.all()]
        random.shuffle(answers)

        context = {"topic": "Frage", "question": question, "answers": answers,
                   "start_num_questions": session.start_num_questions, "num_question": num_question,
                   "points": points, "num_correctly": num_correct, "achieved": session.achieved_points, "max_points": session.max_points,
                   # for debugging
                   "spielleiter": request.user.groups.filter(name__iexact="spielleiter").exists()
                   }
        return render(request, "quiz/question.html", context)

    if request.method == "POST":

        answer_ids = request.POST.getlist("answer_ids[]")
        answer_ids = [int(a) for a in answer_ids]
        selected_answers = Answer.objects.filter(id__in=answer_ids)

        # get actual question
        question = session.actual_question

        # case if >1 POST and no GET of "quiz:question" in between:
        if question is None:
            # reload from server in ajax.success
            return JsonResponse({"reload": 1})
        session.actual_question = None
        session.save()

        # check if answers belong to question
        all_answers = question.answer_set.all()

        all_answers_id = [a.id for a in all_answers]
        selected_answers_id = [a.id for a in selected_answers]
        for a in selected_answers:
            if a.id not in all_answers_id:
                return JsonResponse({"message": "Antwort: {} gehört nicht zu der Frage.".format(a.text)}, status=418)

        # collect answerres in lists ordered by given solution (example tt_list: should be true and is answered as true
        tt_list = []
        ff_list = []
        ft_list = []
        for a in all_answers:
            if a.id in selected_answers_id and a.correct:
                tt_list.append([a.id])
            elif a.id not in selected_answers_id and not a.correct:
                ff_list.append([a.id])
            else:
                ft_list.append([a.id, a.message_on_wrong_answered if a.message_on_wrong_answered else ""])

        # make spielerQuestion obj
        sq, _ = SpielerQuestion.objects.get_or_create(spieler=spieler, question=question)

        # add to session.results
        DeleteableM2M_SpielerQuestion.objects.get_or_create(spielerQuestion=sq, session=session)

        # get points, also negative if false answer given
        answered_correctly = len(ft_list) == 0
        sq.answered_correctly(answered_correctly)

        # save in every scenario, so the date is always reset to now, even if not necssary, because answered_correctly() is called
        sq.save()

        points = sq.get_points()
        session.achieved_points += points
        spieler.quiz_points += points
        spieler.save()

        session.save()
        return JsonResponse({"tt_list": tt_list, "ff_list": ff_list, "ft_list": ft_list})

@login_required
def score(request):
    spieler = get_object_or_404(Spieler, name=request.user.username)
    session = get_object_or_404(QuestionSession, spieler=spieler)

    if request.method == "GET":
        if session.start_num_questions == 0:
            session.delete()
            return redirect("quiz:index")

        if session.questions_to_answer.all().count() != 0 or session.actual_question is not None:
            return redirect("quiz:question")

        right_list = []
        wrong_list = []     # necessary?
        for dsq in DeleteableM2M_SpielerQuestion.objects.filter(session=session):
            sq = dsq.spielerQuestion
            if sq.correct and sq.num_correctly != 0:
                right_list.append(sq.question)
            else:
                wrong_list.append(sq.question)

        # list, grades of questions are indices
        score_list = []
        for d in range(14):
            score_list.append({"num": 0, "correct_num": 0, "points": 0})

        for sq in SpielerQuestion.objects.filter(question__in=wrong_list, spieler=spieler):
            score_grade_dict = score_list[sq.question.grade]

            score_grade_dict["num"] += 1
            score_grade_dict["points"] += sq.get_points()

        for sq in SpielerQuestion.objects.filter(question__in=right_list, spieler=spieler):
            score_grade_dict = score_list[sq.question.grade]

            score_grade_dict["num"] += 1
            score_grade_dict["correct_num"] += 1
            score_grade_dict["points"] += sq.get_points()

        percent = round((len(right_list) / session.start_num_questions) * 100, 2)
        score = get_grade_score(len(right_list), session.start_num_questions, session.start_num_questions)
        match = re.match("\w+", score)
        score_tag_class = ("grade_"+match.group(0)) if match else ""

        context = {"score_list": score_list, "topic": "Auswertung", "session": session, "sum_points": spieler.quiz_points_achieved,
                   "percent": percent, "score": score, "score_tag_class": score_tag_class, "right_num": len(right_list),
                   "total_num": session.start_num_questions, "url_mehr_fragen": reverse("quiz:index")}

        return render(request, "quiz/score.html", context)

    if request.method == "POST":
        QuestionSession.objects.filter(spieler=spieler).delete()
        return JsonResponse({})

def score_board(request):
    context = data_score_board(request);
    return render(request, "quiz/score_board.html", context)


# -*- coding: utf-8 -*-

""" Handler for views.info() """

import datetime, json, logging, os, subprocess
from bib_ourl_api_app import settings_app
from django.conf import settings

log = logging.getLogger(__name__)

def get_commit():
    """ Returns commit-string.
        Called by views.info() """
    original_directory = os.getcwd()
    log.debug( 'BASE_DIR, ```%s```' % settings.BASE_DIR )
    git_dir = settings.BASE_DIR
    log.debug( 'git_dir, ```%s```' % git_dir )
    os.chdir( git_dir )
    output_utf8 = subprocess.check_output( ['git', 'log'], stderr=subprocess.STDOUT )
    output = output_utf8.decode( 'utf-8' )
    os.chdir( original_directory )
    lines = output.split( '\n' )
    commit = lines[0]
    return commit

def get_branch():
    """ Returns branch.
        Called by views.info() """
    ( original_directory, branch ) = ( os.getcwd(), 'init' )
    os.chdir( settings.BASE_DIR )
    output_utf8 = subprocess.check_output( ['git', 'branch'], stderr=subprocess.STDOUT )
    output = output_utf8.decode( 'utf-8' )
    os.chdir( original_directory )
    lines = output.split( '\n' )
    for line in lines:
        if line[0:1] == '*':
            branch = line[2:]
            break
    return branch

def make_context( request, rq_now, info_txt, taken ):
    """ Builds and returns context.
        Called by views.info() """
    cntxt = {
        'request': {
            'url': '%s://%s%s' % (
                request.scheme,
                request.META.get( 'HTTP_HOST', '127.0.0.1' ),  # HTTP_HOST doesn't exist for client-tests
                request.META.get('REQUEST_URI', request.META['PATH_INFO']) ),
            'timestamp': str( rq_now )
            },
        'response': assemble_response_dct( request, info_txt, taken )
        }
    return cntxt

def assemble_response_dct( request, info_txt, taken ):
    """ Returns response part of context dct.
        Called by make_context() """

    response_dct = {
        'documentation': settings_app.README_URL,
        'version': info_txt,
        'elapsed_time': str( taken ),
        }
    if settings.DEBUG == True:
        response_dct['ip'] = request.META.get( 'REMOTE_ADDR', 'unavailable' )
        response_dct['user_agent'] = request.META.get( 'HTTP_USER_AGENT', 'unavailable' )
    return response_dct


from math import trunc

from django.utils import timezone

def slice_records(qs, *args, **kwargs):
    report_timespan = kwargs.get('report_timespan')
    minimum_count = kwargs.get('minimum_count')
    maximum_count = kwargs.get('maximum_count')

    if minimum_count and maximum_count:
        raise ValueError('Cannot use minimum_count and maximum_count at the same time.')

    if qs.count() == 0:
        return qs

    if report_timespan:
        result = qs.filter(timestamp__gte=timezone.now() - report_timespan)
    else:
        result = qs

    if minimum_count or maximum_count:
        num_records = result.count()

        if num_records > 0:
            if minimum_count and num_records < minimum_count:
                temp_slice = qs[:minimum_count]
                earliest_record = temp_slice[temp_slice.count() - 1]
                result = qs.filter(timestamp__gte=earliest_record.timestamp)

            if maximum_count and num_records > maximum_count:
                temp_slice = qs[:maximum_count]
                earliest_record = temp_slice[temp_slice.count() - 1]
                result = qs.filter(timestamp__gte=earliest_record.timestamp)

    return result

def floor_to_nearest(num, multiple_of):
    return num - num % multiple_of

def round_to_nearest(num, multiple_of):
    return multiple_of * round(num / multiple_of)

def ceil_to_nearest(num, multiple_of):
    return num + multiple_of - num % multiple_of

def replace_value_with_choice(data, replacements):
    """
    :param data: list of dictionaries
    :param replacements: dict of {attribute: choices} to replace
    :return: list of dictionaries
    """
    for attribute, choices in replacements.items():
        choice_dict = dict(choices)
        for item in data:
            if attribute in item:
                item[attribute] = choice_dict.get(
                    item[attribute],
                    item[attribute] if item[attribute] is not None else 'None'
                )

    return data

def transform_to_dict(data, value_key='count', **kwargs):
    dict_data = {}
    name_key = kwargs.get('name_key')
    transform = kwargs.get('transform')

    for item in data:
        if name_key is None:
            # Find the first key that is not the value_key and use that
            for key in item.keys():
                if key != value_key:
                    name_key = key
                    break

        if transform:
            dict_data[transform[item[name_key]]] = item[value_key]
        else:
            dict_data[item[name_key]] = item[value_key]

    return dict_data

def round_timedelta(input, to_nearest, direction='up'):
    if direction == 'up':
        return to_nearest * trunc(input / to_nearest) + to_nearest
    else:
        return to_nearest * trunc(input / to_nearest)


import random

# Настройки модели
N = random.randint(3, 7)  # количество филиалов
M = random.randint(1, 5)  # количество курьеров

time_start = 8 # время старта моделирования
time_finish = 20 # время окончания моделирования
time_step =0.3  # 0.5 - 30 минут
days = 100 # количество дней моделирования

# Частота заявок
cooldown = 20

# отклонение скорости курьера
def cour_speed_random():
    return random.randint(-20, 40)


#%%
import calendar
#%%

c = calendar.TextCalendar(calendar.MONDAY)
st = c.formatmonth(2008,1)
print(st)

#%%

# loop over the days of a month
# zeroes mean that the day of the week is in an overlapping month
for i in c.itermonthdays(2017,8):
    print(i)

#%%
for i in calendar.month_name:
    print(i)

for day in calendar.day_name:
    print(day)
# The Calendar module provides useful utilities for the given locale,
# such as the names of days and months in both full and abbreviated forms

#%%
# Calculate days based on a rule: For example, consider
# a team meeting on the first Friday of every month.
# To figure out what days that would be for each month,
# we can use this script:
cal = calendar.monthcalendar(2018,1)
print(calendar.FRIDAY)
print(cal)
print("Team meeting will be on:")
for m in range(1,13):
    cal = calendar.monthcalendar(2018,m)
    weekone = cal[0]
    weektwo = cal[1]

    if weekone[calendar.FRIDAY] !=0:
        meetday = weekone[calendar.FRIDAY]
    else:
        meetday = weektwo[calendar.FRIDAY]
    print("%10s %2d" % (calendar.month_name[m], meetday))

#%%

# to get the range of the month use monthrange()
# (2, 30) specify the weekday ie Wednesday (day for 1st of the month) and total days in the month
print(calendar.monthrange(2020, 4))


#-*- coding: utf-8 -*-
"""
@file
@brief Defines a set of modules for more machine learning or student projects.
"""
from ..installhelper.module_install import ModuleInstall

def cloud_set():
    """
    modules introduced by students or needed for student projects, it requires the modules in set *extended*
    """
    mod = [
        ModuleInstall("botocore", "pip", usage="AWS",
                      purpose="A low-level interface to a growing number of Amazon Web Services. " +
                      "The botocore package is the foundation for the AWS CLI as well as boto3."),
        ModuleInstall("s3transfer", "pip", usage="AWS",
                      purpose="An Amazon S3 Transfer Manager"),
        ModuleInstall("boto3", "pip", usage="AWS",
                      purpose="A Python interface to Amazon Web Services"),
        ModuleInstall("s3fs", "pip", usage="AWS",
                      purpose="Convenient Filesystem interface over S3"),
        ModuleInstall("boto", "pip",
                      purpose="Amazon Web Services Library"),
        ModuleInstall("google-api-python-client", "pip", mname="googleapiclient",
                      purpose="The Google API Client for Python is a client library for accessing the Plus, Moderator, and many other Google APIs."),
        ModuleInstall("googlemaps", "pip",
                      purpose="Python client library for Google Maps API Web Services"),
        ModuleInstall("python-gmaps", "pip", mname="gmaps",
                      purpose="Google Maps API client http://python-gmaps.readthedocs.org"),
        ModuleInstall("gdata", "pip", usage="GOOGLE",
                      purpose="Python client library for Google data APIs"),
    ]

    mod.append(ModuleInstall("adal", "pip",
                             purpose="The ADAL for Python library makes it easy for python application to authenticate " +
                             "to Azure Active Directory (AAD) in order to access AAD protected web resources."))
    mod.append(ModuleInstall("msrest", "pip",
                             purpose="AutoRest swagger generator Python client runtime."))
    mod.append(ModuleInstall("msrestazure", "pip",
                             purpose="AutoRest swagger generator Python client runtime. Azure-specific module."))
    for name in ['azure-nspkg',
                 'azure-common',
                 'azure-mgmt-nspkg',
                 'azure-mgmt-authorization',
                 'azure-mgmt-common',
                 'azure-storage',
                 'azure-mgmt-batch',
                 'azure-mgmt-cdn',
                 'azure-mgmt-cognitiveservices',
                 'azure-mgmt-commerce',
                 'azure-mgmt-compute',
                 'azure-mgmt-logic',
                 'azure-graphrbac',
                 'azure-mgmt-network',
                 'azure-mgmt-notificationhubs',
                 'azure-mgmt-powerbiembedded',
                 'azure-mgmt-redis',
                 'azure-mgmt-resource',
                 'azure-mgmt-scheduler',
                 'azure-mgmt-storage',
                 'azure-mgmt-web',
                 'azure-batch',
                 'azure-servicebus',
                 'azure-servicemanagement-legacy',
                 'azure-mgmt',
                 # addition 2017-05
                 "azure-keyvault",
                 "azure-datalake-store",
                 "azure-servicefabric",
                 "azure-mgmt-devtestlabs",
                 "azure-mgmt-documentdb",
                 "azure-mgmt-containerregistry",
                 "azure-mgmt-keyvault",
                 "azure-mgmt-dns",
                 "azure-mgmt-datalake-analytics",
                 "azure-mgmt-datalake-nspkg",
                 "azure-mgmt-trafficmanager",
                 "azure-mgmt-rdbms",
                 "azure-mgmt-datalake-store",
                 "azure-mgmt-iothub",
                 "azure-mgmt-sql",
                 "azure-mgmt-monitor",
                 # main package
                 'azure']:

        # azure part
        mname = name.replace("-", ".")
        if mname in ("azure.nspkg", "azure.mgmt.nspkg",
                     "azure.servicemanagement.legacy"):
            skip_import = True
        else:
            skip_import = False
        if mname == name:
            mname = None
        m = ModuleInstall(
            name, "pip", mname=mname, pip_options=["--pre"],
            purpose="Python wrapper for Azure API (HDInsight, Blog Storage)", usage="AZURE",
            skip_import=skip_import)
        mod.append(m)

    mod.append(ModuleInstall("azureml", "pip",
                             purpose="Microsoft Azure Machine Learning Python client library"))

    return [_ for _ in mod if _ is not None]


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=16)),
                ('phone', models.IntegerField(max_length=11)),
                ('email', models.EmailField(max_length=254)),
                ('age', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='VideoInfo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('video_path', models.URLField()),
                ('video_name', models.CharField(max_length=20)),
                ('video_zoom_img', models.URLField()),
                ('video_time', models.TimeField()),
            ],
        ),
    ]


from peewee import SqliteDatabase, CharField, IntegerField, Model, ForeignKeyField
from setting import DB_CONNECTION_URL

db = SqliteDatabase(DB_CONNECTION_URL)

class Translation(Model):
    post_id = CharField(primary_key=True)
    post_slug = CharField(unique=True)
    post_lang = CharField()
    o_post = ForeignKeyField('self', related_name='translations', null=True)

    class Meta:
        database = db