from __future__ import absolute_import, division, print_function, unicode_literals

import unittest
from discogs_client import Client
from discogs_client.tests import DiscogsClientTestCase
from discogs_client.exceptions import ConfigurationError, HTTPError
from datetime import datetime

class CoreTestCase(DiscogsClientTestCase):
    def test_user_agent(self):
        """User-Agent should be properly set"""
        self.d.artist(1).name

        bad_client = Client('')

        self.assertRaises(ConfigurationError, lambda: bad_client.artist(1).name)

        try:
            bad_client.artist(1).name
        except ConfigurationError as e:
            self.assertTrue('User-Agent' in str(e))

    def test_caching(self):
        """Only perform a fetch when requesting missing data"""
        a = self.d.artist(1)

        self.assertEqual(a.id, 1)
        self.assertTrue(self.d._fetcher.last_request is None)

        self.assertEqual(a.name, 'Persuader, The')
        self.assertGot('/artists/1')

        self.assertEqual(a.real_name, 'Jesper Dahlb\u00e4ck')
        self.assertEqual(len(self.d._fetcher.requests), 1)

        # Get a key that's not in our cache
        a.fetch('blorf')
        self.assertEqual(len(self.d._fetcher.requests), 2)
        self.assertTrue('blorf' in a._known_invalid_keys)

        # Now we know artists don't have blorves
        a.fetch('blorf')
        self.assertEqual(len(self.d._fetcher.requests), 2)

    def test_equality(self):
        """APIObjects of the same class are equal if their IDs are"""
        a1 = self.d.artist(1)
        a1_ = self.d.artist(1)
        self.d.artist(2)

        r1 = self.d.release(1)

        self.assertEqual(a1, a1_)
        self.assertEqual(a1, r1.artists[0])
        self.assertNotEqual(a1, r1)
        self.assertNotEqual(r1, ':D')

    def test_transform_datetime(self):
        """String timestamps are converted to datetimes"""
        registered = self.d.user('example').registered
        self.assertTrue(isinstance(registered, datetime))

    def test_object_field(self):
        """APIObjects can have APIObjects as properties"""
        self.assertEqual(self.d.master(4242).main_release, self.d.release(79))

    def test_read_only_simple_field(self):
        """Can't write to a SimpleField when writable=False"""
        u = self.d.user('example')

        def fail():
            u.rank = 9001
        self.assertRaises(AttributeError, fail)

    def test_read_only_object_field(self):
        """Can't write to an ObjectField"""
        m = self.d.master(4242)

        def fail():
            m.main_release = 'lol!'
        self.assertRaises(AttributeError, fail)

    def test_pagination(self):
        """PaginatedLists are parsed correctly, indexable, and iterable"""
        results = self.d.artist(1).releases

        self.assertEqual(results.per_page, 50)
        self.assertEqual(results.pages, 2)
        self.assertEqual(results.count, 57)

        self.assertEqual(len(results), 57)
        self.assertEqual(len(results.page(1)), 50)

        self.assertRaises(HTTPError, lambda: results.page(42))

        try:
            results.page(42)
        except HTTPError as e:
            self.assertEqual(e.status_code, 404)

        self.assertRaises(IndexError, lambda: results[3141592])

        self.assertEqual(results[0].id, 20209)
        self.assertTrue(self.d.release(20209) in results)

        # Changing pagination settings invalidates the cache
        results.per_page = 10
        self.assertTrue(results._num_pages is None)

def suite():
    suite = unittest.TestSuite()
    suite = unittest.TestLoader().loadTestsFromTestCase(CoreTestCase)
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')


import requests
import numpy as np
import cv2
import sys, os, shutil
import json

sys.path.append("../")
from PIL import Image

# input_img = r"E:\data\starin-diode\diode-0605\images\20200605_5.jpg"
# input_img = "diode.jpg"
input_imgs = r"E:\data\diode-opt\imgs/"
# input_imgs = r"E:\pycharm_project\Data-proessing\break-group-yolo\test01\result/"
files = os.listdir(input_imgs)
save_path = r"out_imgs"
if os.path.exists(save_path):
    shutil.rmtree(save_path)
os.makedirs(save_path)
for file in files:
    # input_img = r"E:\data\diode-opt\imgs\20200611_84.jpg"
    input_img = input_imgs + file
    img = Image.open(input_img)
    print(np.array(img))
    img1 = img.resize((416, 416))
    # img1 = img.resize((224, 224))
    image_np = np.array(img1)
    print(image_np.shape)
    image_np = image_np.transpose([2,0,1])
    print(image_np.shape)
    # print(image_np[np.newaxis,:].shape)
    img_data = image_np[np.newaxis, :].tolist()
    print(image_np[np.newaxis,:].shape)
    data = {"instances": img_data}
    # data = {"inputs": img_data}
    # data = {"data": img_data}

    # http://172.20.112.102:8701/v1/models/model-fish/metadata
    preds1 = requests.post("http://172.20.112.102:9101/v1/models/model-diode:predict", json=data)
    # preds1 = requests.post("http://172.20.112.102:4000/predictions/resnet34", json=data)
    print(preds1.json())
    predictions1 = json.loads(preds1.content.decode('utf-8'))
    print(predictions1)
    exit()

    preds = requests.post("http://172.20.112.102:9101/v1/models/model-diode:predict", json=data)
    print(preds)
    predictions = json.loads(preds.content.decode('utf-8'))["predictions"][0]
    print(predictions)
    print(np.array(predictions)[:,4].max())
    pred = np.array(predictions)
    print(pred.shape)
    # exit()
    a = pred[:, 4] > 0.25
    print(pred[a])
    print(len(pred[a]))
    # exit()
    im = cv2.imread(input_img)
    # print(im.shape) # hwc
    h_s = im.shape[0] / 416
    w_s = im.shape[1] / 416

    box = []
    for i in range(len(pred[a])):
        # print(pred[a][i])
        x1 = pred[a][i][0]
        y1 = pred[a][i][1]
        x2 = pred[a][i][2]
        y2 = pred[a][i][3]
        xx1 = (x1 - x2 / 2)
        yy1 = (y1 - y2 / 2)
        xx2 = (x1 + x2 / 2)
        yy2 = (y1 + y2 / 2)
        box.append([xx1, yy1, xx2, yy2, pred[a][i][4], pred[a][i][5:]])

        cv2.rectangle(im, (int(xx1 * w_s), int(yy1 * h_s)), (int(xx2 * w_s), int(yy2 * h_s)), (255, 0, 0))
    # print(box)
    # cv2.imshow('ss1', im)
    cv2.imwrite(save_path + '/' + file, im)
    # cv2.waitKey(0)

# filtered_boxes = np.array([[6.64219894e+01,3.38672394e+02,1.29818487e+01,1.43017712e+01]])
# draw_boxes(filtered_boxes, img, "classes", (416, 416), True)
# img.show()

# im = cv2.imread(input_img)
# # print(im.shape) # hwc
# x_ = im.shape[0]/416
# y_ = im.shape[1]/416
# # a = min(x_,y_)
# # p = 0.5*(im.shape[:2] - a*np.array([416,416]))
# # s = (np.array([66,338])-p)/a
# # print(s)
# # s1 = (np.array([12,14])-p)/a
# # print(s1)
# # w,h,cx,cy
# img = cv2.resize(im,(416,416))
# # cv2.rectangle(img,(79,182),(9,15),(0,0,255))
# # cv2.rectangle(img,(int((79-9/2)),int((182-15/2))),(int((79+9/2)),int((182+15/2))),(0,0,255))
# # cv2.rectangle(im,(int((338/2-12)*y_),int((66/2-14)*x_)),(int((12+338/2)*y_),int((14+66/2)*x_)),(0,0,255))
# h_s = im.shape[0]/416
# w_s = im.shape[1]/416
# x1 = 79
# y1 = 182
# x2 = 9
# y2 = 15
# xx1 = (x1 - x2/2)
# yy1 = (y1 - y2/2)
# xx2 = (x1 + x2/2)
# yy2 = (y1 + y2/2)

# cv2.rectangle(img,(xx1,yy1),(xx2,yy2),(0,0,255))
# cv2.rectangle(im,(int(xx1*w_s),int(yy1*h_s)),(int(xx2*w_s),int(yy2*h_s)),(255,0,0))
# x1,y1,x2,y2  x1- x2/2    y1- y2/2    x1+x2/2  y1 + y2/2
# cv2.imshow("ss",img)
# cv2.imshow('ss1',im)
# cv2.waitKey(0)


'''
Created on Nov 28, 2012

@author: cosmin
'''
from google.appengine.ext import webapp
import logging
import jinja2
import os
from models import Trend
from models import TopJobs

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class SplitTrend:
    def __init__(self, job, values):
        self.job = job
        logging.info(values)
        self.values = [int(val) for val in values]

class Trends(webapp.RequestHandler):

    def get(self):
        '''
        The class serving the page for the trends.
        '''
        months = ["2012-11", "2012-10", "2012-09", "2012-08", "2012-07",
        "2012-06", "2012-05", "2012-04", "2012-03", "2012-02", "2012-01",
        "2011-12", "2011-11", "2011-10", "2011-09", "2011-08", "2011-07",
        "2011-06", "2011-05", "2011-04", "2011-03", "2011-02", "2011-01",
        "2010-12", "2010-11", "2010-10", "2010-09", "2010-08", "2010-07",
        "2010-06", "2010-05", "2010-04", "2010-03", "2010-02", "2010-01",
        "2009-12", "2009-11", "2009-10", "2009-09", "2009-08", "2009-07",
        "2009-06", "2009-05", "2009-04", "2009-03", "2009-02", "2009-01",
        "2008-12", "2008-11", "2008-10", "2008-09", "2008-08", "2008-07",
        "2008-06", "2008-05", "2008-04", "2008-03", "2008-02", "2008-01"]
        months.reverse()

        #Get jobs for trends
        jobs = self.request.get_all("job")
        jobs = [j for j in jobs if len(j) > 0]
        logging.info("Trends for jobs: " + ','.join(jobs))

        #Also get the total counts for months
        jobs.append('total')

        #Get the trends from the database
        split_trends = []
        if len(jobs) > 1:
            trends = Trend.all()
            trends.filter("job IN", jobs)
            for t in trends:
                nt = SplitTrend(t.job, t.monthly_count.split(';'))
                if nt.job == 'total':
                    total = nt
                    logging.info("Total - " + str(t))
                else:
                    split_trends.append(nt)
                    logging.info(t)
        trends_names = [t.job for t in split_trends]

        #Compute percentages
        for t in split_trends:
            t.values = [val * 100.0 / total.values[idx] for idx, val in enumerate(t.values)]

        #Generate the page
        template_values = { 'jobs': TopJobs, 'trends': split_trends, 'trends_names': trends_names, 'count': len(split_trends), 'months': months}

        template = jinja_environment.get_template('templates/trends.html')
        self.response.out.write(template.render(template_values))


from django.contrib import admin as dj_admin
from django.contrib import admin
from myapp.models import Project, ModelGroup, AutodeskExtractorRule, BimModel, Job
from myapp.models import URN, ActiveLink

class WorkAdmin(dj_admin.ModelAdmin):
    list_display = ("id", "name")

class ProjectAdmin(admin.ModelAdmin):
    list_display = (
        "name",
        "description",
        "created_at",
        "updated_at",
        "created_by",
        "updated_by",
        "deleted_at",
        "deleted_by",
    )

class ModelGroupAdmin(admin.ModelAdmin):
    list_display = (
        "name",
        "description",
        "created_at",
        "updated_at",
        "created_by",
        "updated_by",
        "deleted_at",
        "deleted_by",
    )

class AutodeskExtractorRuleAdmin(admin.ModelAdmin):
    list_display = (
        "project",
        "model_group",
        "name",
        "description",
        "created_at",
        "updated_at",
        "created_by",
        "updated_by",
        "deleted_at",
        "deleted_by",
    )

class BimModelAdmin(admin.ModelAdmin):
    list_display = (
        "project",
        "model_group",
        "name",
        "description",
        "created_at",
        "updated_at",
        "created_by",
        "updated_by",
        "deleted_at",
        "deleted_by",
    )

class JobAdmin(admin.ModelAdmin):
    list_display = (
        "project",
        "task_type",
        "created_at",
        "task_id",
    )

admin.site.register(Project, ProjectAdmin)
admin.site.register(ModelGroup, ModelGroupAdmin)
admin.site.register(AutodeskExtractorRule, AutodeskExtractorRuleAdmin)
admin.site.register(BimModel, BimModelAdmin)
admin.site.register(Job, JobAdmin)

dj_admin.site.register(ActiveLink)
dj_admin.site.register(URN)


from flask import Flask, request, jsonify
from tf_idf import get_text, scrape_google, tf_idf_analysis

app = Flask(__name__)

@app.route('/get_text')
def get_text_endpoint():
    url = request.args.get('url')
    text = get_text(url)
    return jsonify(text=text)

@app.route('/scrape_google')
def scrape_google_endpoint():
    query = request.args.get('query')
    links = scrape_google(query)
    return jsonify(links=links)

@app.route('/tf_idf_analysis')
def tf_idf_analysis_endpoint():
    keyword = request.args.get('keyword')
    result = tf_idf_analysis(keyword)
    return jsonify(result=result)

if __name__ == '__main__':
    app.run(debug=True)


import json
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import joblib
import sys

def train_model():
    jsondata = json.loads(sys.argv[1])

    # Create a dictionary to store models for each variable
    models = {}

    for variable_data in jsondata:
        variable_name = variable_data['dataName']
        df = pd.DataFrame(variable_data['dataSource'])

        df['timeStamp'] = pd.to_datetime(df['timeStamp'])

        df['hour'] = df['timeStamp'].dt.hour
        df['minute'] = df['timeStamp'].dt.minute
        df['second'] = df['timeStamp'].dt.second

        target = 'dataValue'

        X = df[['hour', 'minute', 'second']]
        y = df[target]

        model = LinearRegression()
        model.fit(X, y)

        models[variable_name] = model

        joblib.dump(model, f'trained_model_{variable_name}.joblib')

    response_data = {"models": models, "status": "trained"}

    try:
        print(json.dumps(response_data))
    except Exception as e:
        print(f"An error occurred: {e}")

train_model()


import random
import tensorflow as tf
from AI.agent import Agent
from AI.ROSEnvironment import ArmControlPlateform
from config import get_config

flags = tf.app.flags

# Model
flags.DEFINE_string('model', 'DQN', 'Type of model')
# Environment
#flags.DEFINE_string('env_name', 'Acrobot-v1', 'The name of gym environment to use')
# Etc
#flags.DEFINE_boolean('display', True, 'Whether to do display the game screen or not')
flags.DEFINE_integer('random_seed', 123, 'Value of random seed')

FLAGS = flags.FLAGS

# Set random seed
tf.set_random_seed(FLAGS.random_seed)
random.seed(FLAGS.random_seed)

def main(_):
    config = get_config(FLAGS) or FLAGS
    env = ArmControlPlateform(config)
    for _ in range(1):
        env.reset()
        agent = Agent(config, env)
        agent.activate(learn=True)

def test():
    config = get_config(FLAGS) or FLAGS
    env = ArmControlPlateform(config)
    env.reset()
    for i in range(30):
        sleep(0.1)
        action = env.action_space.sample()
        ob,re,ter = env.step(action)
        print(ob,re,ter)

if __name__ == '__main__':
    tf.app.run()
    #test()


from tests.baseTest import *
from lib.random_generator import RandomGenerator
from lib.api_requests import RequestManager
from grappa import should
from api_endpoints.signup_endpoint import SignupMethods
from api_endpoints.threads_endpoint import ThreadsMethods
from lib.data_encoder import Encoder

class ViewThreadsTest(BaseTest):
    rand = RandomGenerator()
    rm = RequestManager()
    encoder = Encoder()

    @classmethod
    def setUpClass(cls):
        BaseTest.setUpClass()
        account_data = SignupMethods().create_test_account(generate_fields=True)[0]
        data_to_encode = account_data['username'] + ':' + account_data['password']
        encoded_credentials = cls.encoder.encode_data(data_to_encode)
        cls.thread_auth_headers = {'Authorization': 'Basic ' + encoded_credentials}
        sample_thread = cls.rand.generate_random_string(10)
        ThreadsMethods().create_sample_thread(authorization=cls.thread_auth_headers, thread_name=sample_thread,
                                              private=False)

    def setUp(self):
        BaseTest.setUp(self)
        self.threads_url = self.CONFIG['API_ADDRESS'] + '/threads'

    def test_01_get_last_threads(self):
        logging.info('Trying to get last threads')
        result = ThreadsMethods().get_threads(authorization=self.thread_auth_headers)
        logging.info('Server responded with %s' % result)
        result['code'] | should.be.equal.to(200)
        result['response']['itemsFound'] | should.be.a(int)
        result['response']['limit'] | should.be.a(int)
        result['response']['limit'] | should.be.equal.to(100)
        len(result['response']['items']) | should.be.higher.than(0)
        len(result['response']['items']) | should.be.lower.than(101)
        result['response']['items'][0]['createdAt'] | should.be.a(int)
        result['response']['items'][0]['updatedAt'] | should.be.a(int)
        result['response']['items'][0]['id'] | should.be.a(str)
        result['response']['items'][0]['id'] | should.not_be.none
        result['response']['items'][0]['modelType'] | should.be.equal.to('ThreadModel')
        result['response']['items'][0]['name'] | should.be.a(str)
        result['response']['items'][0]['owner'] | should.be.a(str)
        result['response']['items'][0]['users'] | should.be.a(list)
        result['response']['items'][0]['private'] | should.be.a(bool)
        result['response']['items'][0]['deleted'] | should.be.a(bool)

    def test_02_get_last_100_threads(self):
        logging.info('Generating 100 threads')
        for i in range(0, 102):
            sample_thread = self.rand.generate_random_string(10)
            ThreadsMethods().create_sample_thread(authorization=self.thread_auth_headers, thread_name=sample_thread,
                                                  private=False)
        logging.info('Trying to get last 100 threads')
        result = ThreadsMethods().get_threads(authorization=self.thread_auth_headers)
        logging.info('Server responded with %s' % result)
        result['code'] | should.be.equal.to(200)
        len(result['response']['items']) | should.be.equal.to(100)


from typing import List, Tuple

import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor, nn

def get_cnn_output_dim(
    input_size: int, conv_kernel_size: int, padding_size: int, conv_stride_size: int
) -> int:
    return (input_size + 2 * padding_size - conv_kernel_size) / conv_stride_size + 1

def get_pool_output_dim(
    input_size, pool_kernel_size: int, pool_stride_size: int
) -> int:
    return np.floor((input_size - pool_kernel_size) / pool_stride_size + 1)

def get_cnn_layer_output_dim(
    n_layers: int,
    input_size: int,
    conv_kernel_size: int,
    padding_size: int = 0,
    conv_stride_size: int = 1,
    pool_kernel_size: int = 2,
    pool_stride_size: int = 2,
) -> int:
    if n_layers > 1:
        cnn_output = get_cnn_output_dim(
            input_size, conv_kernel_size, padding_size, conv_stride_size
        )
        pool_output = get_pool_output_dim(
            cnn_output, pool_kernel_size, pool_stride_size
        )
        n_layers -= 1
        return int(
            get_cnn_layer_output_dim(
                n_layers,
                pool_output,
                conv_kernel_size,
                padding_size,
                conv_stride_size,
                pool_kernel_size,
                pool_stride_size,
            )
        )
    else:
        cnn_output = get_cnn_output_dim(
            input_size, conv_kernel_size, padding_size, conv_stride_size
        )
        pool_output = get_pool_output_dim(
            cnn_output, pool_kernel_size, pool_stride_size
        )
        return int(pool_output)

class MultivariateMLP(nn.Module):
    def __init__(
        self,
        input_dimension: Tuple,
        in_channels: int,
        n_outputs: int,
    ):
        super().__init__()
        self.in_channels = in_channels
        self.encoder = nn.Sequential(
            FlattenMLP(),
            nn.Linear(input_dimension[0] * input_dimension[1] * 1 * in_channels, 564),
            # nn.BatchNorm1d(256),
            nn.ReLU(),
            nn.Dropout(0.5),
        )
        self.linear_classifiers = [
            nn.Linear(564, n_outputs) for _ in range(in_channels)
        ]

    def forward(self, x):
        out = self.encoder(x)
        outputs = [
            F.softmax(classifier(out), dim=-1) for classifier in self.linear_classifiers
        ]
        return outputs

class Flatten(nn.Module):
    """A custom layer that views an input as 1D."""

    def forward(self, input):
        return input.view(input.size(0), -1)

class FlattenMLP(nn.Module):
    """A custom layer that views an input as 1D."""

    def forward(self, input):
        return input.reshape(-1)

class MultivariateCNN(nn.Module):
    """https://github.com/ArminBaz/UTK-Face/blob/master/src/MultNN.py"""

    def __init__(
        self,
        input_dimension: Tuple,
        in_channels: int,
        n_outputs: int,
        n_cnn_layers: int = 2,
        conv_kernel_size: int = 2,
        pool_kernel_size: int = 2,
        conv_channels_1: int = 256,
        conv_channels_2: int = 512,
        linear_hidden_cells: int = 256,
        linear_dropout: float = 0.5,
    ):
        super(MultivariateCNN, self).__init__()
        self.in_channels = in_channels
        linear_dim1 = get_cnn_layer_output_dim(
            n_layers=n_cnn_layers,
            input_size=input_dimension[0],
            conv_kernel_size=conv_kernel_size,
            pool_kernel_size=pool_kernel_size,
        )
        linear_dim2 = get_cnn_layer_output_dim(
            n_layers=n_cnn_layers,
            input_size=input_dimension[1],
            conv_kernel_size=conv_kernel_size,
            pool_kernel_size=pool_kernel_size,
        )
        self.encoder = nn.Sequential(
            nn.Conv2d(
                in_channels=in_channels,
                out_channels=conv_channels_1,
                kernel_size=conv_kernel_size,
            ),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=pool_kernel_size),
            nn.Conv2d(
                in_channels=conv_channels_1,
                out_channels=conv_channels_2,
                kernel_size=conv_kernel_size,
            ),
            # nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=pool_kernel_size),
            #               nn.Conv2d(in_channels, out_channels=8, kernel_size=conv_kernel_size),
            #               nn.ReLU(),
            #               nn.MaxPool2d(kernel_size=pool_kernel_size),
            Flatten(),
            nn.Linear(linear_dim1 * linear_dim2 * conv_channels_2, linear_hidden_cells),
            # nn.BatchNorm1d(256),
            nn.ReLU(),
            nn.Dropout(linear_dropout),
        )
        self.linear_classifiers = [
            nn.Linear(linear_hidden_cells, n_outputs) for _ in range(in_channels)
        ]

    def forward(self, x):
        out = self.encoder(x)
        outputs = [
            F.softmax(classifier(out), dim=-1) for classifier in self.linear_classifiers
        ]
        return outputs


from collections import Counter
class Solution:
    def longestPalindrome(self, s: str) -> int:
        counter = Counter(s)
        ans = 0
        odd = False

        for k,v in counter.items():
            ans += v // 2 * 2
            if v % 2:
                odd = True
        if odd: ans += 1

        return ans


#!/usr/bin/python3

from PyQt5 import QtCore, QtGui, QtWidgets
import webbrowser
import os
import subprocess

class Ui_WelcomeScreen(object):
    ######################### CUSTOM ACTIONS ##########################
    def forumButtonAction(self):
        webbrowser.open("https://forum.namiblinux.org/categories")
    def chatButtonAction(self):
        webbrowser.open("https://www.namiblinux.org/support/chat/")
    def donateButtonAction(self):
        webbrowser.open("https://www.namiblinux.org/donate/")
    def wikiButtonAction(self):
        webbrowser.open("https://wiki.namiblinux.org/")
    def newsButtonAction(self):
        webbrowser.open("https://forum.namiblinux.org/c/announcements")
    def helpButtonAction(self):
        webbrowser.open("https://github.com/namiblinux")
    def installButtonAction(self):
        subprocess.Popen(["calamares_polkit"])
    def startCheckAction(self):
        if self.launchAtStartCheck.isChecked():
            homedir = os.path.expanduser('~')
            autostartfile = os.path.join(homedir, ".config/autostart/namib-welcome.desktop")
            subprocess.Popen(["cp", "/usr/share/applications/namib-welcome.desktop", autostartfile])
        else:
            homedir = os.path.expanduser('~')
            autostartfile = os.path.join(homedir, ".config/autostart/namib-welcome.desktop")
            subprocess.Popen(["rm", autostartfile])
    #####################################################################

    def setupUi(self, WelcomeScreen):
        WelcomeScreen.setObjectName("WelcomeScreen")
        WelcomeScreen.resize(640, 480)
        WelcomeScreen.setMinimumSize(640, 480)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/namib-welcome.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        WelcomeScreen.setWindowIcon(icon)
        self.MainWidget = QtWidgets.QWidget(WelcomeScreen)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.MainWidget.sizePolicy().hasHeightForWidth())
        self.MainWidget.setSizePolicy(sizePolicy)
        self.MainWidget.setAutoFillBackground(False)
        self.MainWidget.setObjectName("MainWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.MainWidget)
        self.gridLayout.setObjectName("gridLayout")
        self.mainGrid = QtWidgets.QGridLayout()
        self.mainGrid.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.mainGrid.setObjectName("mainGrid")
        self.wikiButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.wikiButton.sizePolicy().hasHeightForWidth())
        self.wikiButton.setSizePolicy(sizePolicy)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/wiki.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.wikiButton.setIcon(icon1)
        self.wikiButton.setObjectName("wikiButton")

        ######################### WIKI BUTTON ##########################
        self.wikiButton.clicked.connect(self.wikiButtonAction)
        ################################################################

        self.mainGrid.addWidget(self.wikiButton, 7, 0, 1, 1)
        self.lineTop = QtWidgets.QFrame(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineTop.sizePolicy().hasHeightForWidth())
        self.lineTop.setSizePolicy(sizePolicy)
        self.lineTop.setFrameShape(QtWidgets.QFrame.HLine)
        self.lineTop.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.lineTop.setObjectName("lineTop")
        self.mainGrid.addWidget(self.lineTop, 4, 0, 1, 3)
        self.logoLayout = QtWidgets.QHBoxLayout()
        self.logoLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.logoLayout.setObjectName("logoLayout")
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.logoLayout.addItem(spacerItem)
        self.Logo = QtWidgets.QLabel(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.Logo.sizePolicy().hasHeightForWidth())
        self.Logo.setSizePolicy(sizePolicy)
        self.Logo.setMaximumSize(QtCore.QSize(64, 64))
        self.Logo.setText("")
        self.Logo.setPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/logo.png"))
        self.Logo.setScaledContents(True)
        self.Logo.setWordWrap(False)
        self.Logo.setObjectName("Logo")
        self.logoLayout.addWidget(self.Logo)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.logoLayout.addItem(spacerItem1)
        self.mainGrid.addLayout(self.logoLayout, 0, 0, 1, 3)
        self.linksLabel = QtWidgets.QLabel(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.linksLabel.sizePolicy().hasHeightForWidth())
        self.linksLabel.setSizePolicy(sizePolicy)
        self.linksLabel.setScaledContents(True)
        self.linksLabel.setWordWrap(True)
        self.linksLabel.setObjectName("linksLabel")
        self.mainGrid.addWidget(self.linksLabel, 5, 0, 1, 3)
        self.donateButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.donateButton.sizePolicy().hasHeightForWidth())
        self.donateButton.setSizePolicy(sizePolicy)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/donate.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.donateButton.setIcon(icon2)
        self.donateButton.setObjectName("donateButton")

        ######################### DONATE BUTTON ########################
        self.donateButton.clicked.connect(self.donateButtonAction)
        ################################################################

        self.mainGrid.addWidget(self.donateButton, 7, 2, 1, 1)
        self.chatButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.chatButton.sizePolicy().hasHeightForWidth())
        self.chatButton.setSizePolicy(sizePolicy)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/chat.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.chatButton.setIcon(icon3)
        self.chatButton.setObjectName("chatButton")

        ######################### CHAT BUTTON ##########################
        self.chatButton.clicked.connect(self.chatButtonAction)
        ###############################################################

        self.mainGrid.addWidget(self.chatButton, 7, 1, 1, 1)
        self.installationLabel = QtWidgets.QLabel(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.installationLabel.sizePolicy().hasHeightForWidth())
        self.installationLabel.setSizePolicy(sizePolicy)
        self.installationLabel.setObjectName("installationLabel")

        ######################### INSTALL LABEL ##########################
        self.installationLabel.setVisible(False)
        ##################################################################

        self.mainGrid.addWidget(self.installationLabel, 8, 1, 1, 1)
        self.installButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.installButton.sizePolicy().hasHeightForWidth())
        self.installButton.setSizePolicy(sizePolicy)
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/install.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.installButton.setIcon(icon4)
        self.installButton.setObjectName("installButton")

        ######################### INSTALL BUTTON ##########################
        self.installButton.clicked.connect(self.installButtonAction)
        self.installButton.setVisible(False)
        ###################################################################

        self.mainGrid.addWidget(self.installButton, 9, 1, 1, 1)
        self.welcomeLabel = QtWidgets.QLabel(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.welcomeLabel.sizePolicy().hasHeightForWidth())
        self.welcomeLabel.setSizePolicy(sizePolicy)
        self.welcomeLabel.setObjectName("welcomeLabel")
        self.mainGrid.addWidget(self.welcomeLabel, 1, 0, 1, 3)
        self.lineBottom = QtWidgets.QFrame(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineBottom.sizePolicy().hasHeightForWidth())
        self.lineBottom.setSizePolicy(sizePolicy)
        self.lineBottom.setFrameShape(QtWidgets.QFrame.HLine)
        self.lineBottom.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.lineBottom.setObjectName("lineBottom")
        self.mainGrid.addWidget(self.lineBottom, 10, 0, 1, 3)
        self.forumsButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.forumsButton.sizePolicy().hasHeightForWidth())
        self.forumsButton.setSizePolicy(sizePolicy)
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/forums.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.forumsButton.setIcon(icon5)
        self.forumsButton.setObjectName("forumsButton")

        ######################### FORUM BUTTON #########################
        self.forumsButton.clicked.connect(self.forumButtonAction)
        ################################################################

        self.mainGrid.addWidget(self.forumsButton, 6, 1, 1, 1)
        self.settingsLayout = QtWidgets.QHBoxLayout()
        self.settingsLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
        self.settingsLayout.setObjectName("settingsLayout")
        self.languageSelector = QtWidgets.QComboBox(self.MainWidget)
        self.languageSelector.setObjectName("languageSelector")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.languageSelector.addItem("")
        self.settingsLayout.addWidget(self.languageSelector)
        self.languageSelector.hide()
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.settingsLayout.addItem(spacerItem2)
        self.launchAtStartCheck = QtWidgets.QCheckBox(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.launchAtStartCheck.sizePolicy().hasHeightForWidth())
        self.launchAtStartCheck.setSizePolicy(sizePolicy)
        self.launchAtStartCheck.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.launchAtStartCheck.setObjectName("launchAtStartCheck")

        ######################### LAUNCH AT START BUTTON #########################
        self.launchAtStartCheck.clicked.connect(self.startCheckAction)
        ##########################################################################

        self.settingsLayout.addWidget(self.launchAtStartCheck)
        self.mainGrid.addLayout(self.settingsLayout, 11, 0, 1, 3)
        self.helpButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.helpButton.sizePolicy().hasHeightForWidth())
        self.helpButton.setSizePolicy(sizePolicy)
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/helpus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.helpButton.setIcon(icon6)
        self.helpButton.setObjectName("helpButton")

        ######################### HELP BUTTON #########################
        self.helpButton.clicked.connect(self.helpButtonAction)
        ###############################################################

        self.mainGrid.addWidget(self.helpButton, 6, 2, 1, 1)
        self.newsButton = QtWidgets.QPushButton(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.newsButton.sizePolicy().hasHeightForWidth())
        self.newsButton.setSizePolicy(sizePolicy)
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap("/usr/share/namib-welcome/img/news.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.newsButton.setIcon(icon7)
        self.newsButton.setObjectName("newsButton")

        ######################### NEWS BUTTON ##########################
        self.newsButton.clicked.connect(self.newsButtonAction)
        ################################################################

        self.mainGrid.addWidget(self.newsButton, 6, 0, 1, 1)
        self.infoLabel = QtWidgets.QLabel(self.MainWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.infoLabel.sizePolicy().hasHeightForWidth())
        self.infoLabel.setSizePolicy(sizePolicy)
        self.infoLabel.setScaledContents(True)
        self.infoLabel.setWordWrap(True)
        self.infoLabel.setObjectName("infoLabel")
        self.mainGrid.addWidget(self.infoLabel, 2, 0, 1, 3)
        self.gridLayout.addLayout(self.mainGrid, 0, 0, 1, 1)
        WelcomeScreen.setCentralWidget(self.MainWidget)

        self.retranslateUi(WelcomeScreen)
        self.languageSelector.setCurrentIndex(12)
        QtCore.QMetaObject.connectSlotsByName(WelcomeScreen)

        ######################### LIVEUSER ? ##########################
        if os.path.isfile("/usr/bin/calamares_polkit"):
            self.installButton.setVisible(True)
            self.installationLabel.setVisible(True)
        ###############################################################

        ######################### IS AUTOSTART ? ######################
        homedir = os.path.expanduser('~')
        autostartfile = os.path.join(homedir, ".config/autostart/namib-welcome.desktop")
        if os.path.isfile(autostartfile):
            self.launchAtStartCheck.setChecked(True)
        ###############################################################

    def retranslateUi(self, WelcomeScreen):
        _translate = QtCore.QCoreApplication.translate
        WelcomeScreen.setWindowTitle(_translate("WelcomeScreen", "Welcome Screen"))
        self.wikiButton.setText(_translate("WelcomeScreen", "Wiki"))
        self.linksLabel.setText(_translate("WelcomeScreen", "
LINKS :
"))
        self.donateButton.setText(_translate("WelcomeScreen", "Donate"))
        self.chatButton.setText(_translate("WelcomeScreen", "Chat room"))
        self.installationLabel.setText(_translate("WelcomeScreen", "
INSTALLATION :
"))
        self.installButton.setText(_translate("WelcomeScreen", "Install Now"))
        self.welcomeLabel.setText(_translate("WelcomeScreen", "
Welcome to Namib GNU/Linux !
"))
        self.forumsButton.setText(_translate("WelcomeScreen", "Forums"))
        self.languageSelector.setCurrentText(_translate("WelcomeScreen", "English"))
        self.languageSelector.setItemText(0, _translate("WelcomeScreen", "Albanian"))
        self.languageSelector.setItemText(1, _translate("WelcomeScreen", "Arabic"))
        self.languageSelector.setItemText(2, _translate("WelcomeScreen", "Asturian (Spain)"))
        self.languageSelector.setItemText(3, _translate("WelcomeScreen", "Belarusian"))
        self.languageSelector.setItemText(4, _translate("WelcomeScreen", "Bulgarian"))
        self.languageSelector.setItemText(5, _translate("WelcomeScreen", "Catalan"))
        self.languageSelector.setItemText(6, _translate("WelcomeScreen", "Chinese (China)"))
        self.languageSelector.setItemText(7, _translate("WelcomeScreen", "Chinese (Taiwan)"))
        self.languageSelector.setItemText(8, _translate("WelcomeScreen", "Croatian"))
        self.languageSelector.setItemText(9, _translate("WelcomeScreen", "Czech"))
        self.languageSelector.setItemText(10, _translate("WelcomeScreen", "Danish"))
        self.languageSelector.setItemText(11, _translate("WelcomeScreen", "Dutch"))
        self.languageSelector.setItemText(12, _translate("WelcomeScreen", "English"))
        self.languageSelector.setItemText(13, _translate("WelcomeScreen", "French"))
        self.languageSelector.setItemText(14, _translate("WelcomeScreen", "German"))
        self.languageSelector.setItemText(15, _translate("WelcomeScreen", "Georgian"))
        self.languageSelector.setItemText(16, _translate("WelcomeScreen", "Greek (Greece)"))
        self.languageSelector.setItemText(17, _translate("WelcomeScreen", "Hebrew"))
        self.languageSelector.setItemText(18, _translate("WelcomeScreen", "Hindi (India)"))
        self.languageSelector.setItemText(19, _translate("WelcomeScreen", "New Item"))
        self.languageSelector.setItemText(20, _translate("WelcomeScreen", "Hungarian"))
        self.languageSelector.setItemText(21, _translate("WelcomeScreen", "Icelandic"))
        self.languageSelector.setItemText(22, _translate("WelcomeScreen", "Indonesian (Indonesia)"))
        self.languageSelector.setItemText(23, _translate("WelcomeScreen", "Italian"))
        self.languageSelector.setItemText(24, _translate("WelcomeScreen", "Japanese"))
        self.languageSelector.setItemText(25, _translate("WelcomeScreen", "Korean (Korea)"))
        self.languageSelector.setItemText(26, _translate("WelcomeScreen", "Lithuanian"))
        self.languageSelector.setItemText(27, _translate("WelcomeScreen", "Norwegian Bokmål"))
        self.languageSelector.setItemText(28, _translate("WelcomeScreen", "Persian (Iran)"))
        self.languageSelector.setItemText(29, _translate("WelcomeScreen", "Polish"))
        self.languageSelector.setItemText(30, _translate("WelcomeScreen", "Portuguese (Brazil)"))
        self.languageSelector.setItemText(31, _translate("WelcomeScreen", "Portuguese (Portugal)"))
        self.languageSelector.setItemText(32, _translate("WelcomeScreen", "Romanian (Romania)"))
        self.languageSelector.setItemText(33, _translate("WelcomeScreen", "Russian"))
        self.languageSelector.setItemText(34, _translate("WelcomeScreen", "Slovak"))
        self.languageSelector.setItemText(35, _translate("WelcomeScreen", "Slovenian (Slovenia)"))
        self.languageSelector.setItemText(36, _translate("WelcomeScreen", "Slovenian"))
        self.languageSelector.setItemText(37, _translate("WelcomeScreen", "Spanish"))
        self.languageSelector.setItemText(38, _translate("WelcomeScreen", "Serbian (Serbia)"))
        self.languageSelector.setItemText(39, _translate("WelcomeScreen", "Serbian"))
        self.languageSelector.setItemText(40, _translate("WelcomeScreen", "Swedish"))
        self.languageSelector.setItemText(41, _translate("WelcomeScreen", "THai"))
        self.languageSelector.setItemText(42, _translate("WelcomeScreen", "Turkish (Turkey)"))
        self.languageSelector.setItemText(43, _translate("WelcomeScreen", "Turkish"))
        self.languageSelector.setItemText(44, _translate("WelcomeScreen", "Ukrainian"))
        self.languageSelector.setItemText(45, _translate("WelcomeScreen", "Vietnamese (Viet Nam)"))
        self.launchAtStartCheck.setText(_translate("WelcomeScreen", "Launch at start"))
        self.helpButton.setText(_translate("WelcomeScreen", "Help us"))
        self.newsButton.setText(_translate("WelcomeScreen", "News"))
        self.infoLabel.setText(_translate("WelcomeScreen", "
Welcome to Namib GNU/Linux. The links below will help you get started with Namib. So enjoy the experience, and don\'t hesitate to send us your feedback.
"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    WelcomeScreen = QtWidgets.QMainWindow()
    ui = Ui_WelcomeScreen()
    ui.setupUi(WelcomeScreen)
    WelcomeScreen.show()
    sys.exit(app.exec_())


import os
import streamlit as st
import openai
from dotenv import load_dotenv

def load_guidelines(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()

def save_guidelines(filepath, content):
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)

load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
# print(api_key)
openai.api_key = api_key

def chat_with_model(prompt, guidelines):
    messages = [
        {"role": "system", "content": guidelines},
        {"role": "user", "content": prompt},
        {"role": "assistant", "content": ""}
    ]
    response = openai.ChatCompletion.create(
        model="gpt-4",
        max_tokens=1536,
        messages=messages,
        temperature=0,
        stream=True
    )
    return response['choices'][0]['message']['content']

# Load Guidelines from a file
guidelines_path = "system.txt"  # Replace with your file path
guidelines = load_guidelines(guidelines_path)

# Streamlit App
st.title("OpenAI Chat Assistant for Text Improvement")

with st.expander("Guidelines ein-/ausblenden"):
    guidelines = st.text_area("Content Guidelines:", guidelines)
    if st.button("Speichern"):
        save_guidelines(guidelines_path, guidelines)

# st.write("Bitte geben Sie Ihr Textbeispiel ein.")

user_input = st.text_area("Bitte geben Sie Ihr Textbeispiel ein.")

if user_input:
    assistant_reply = chat_with_model(user_input, guidelines)
    st.write(f"Assistant: {assistant_reply}")


from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect,JsonResponse
from .forms import NameForm
from .models import NameFormModel
import json, os, requests
from datetime import datetime
# Create your views here.
database = []
def moviemanagerView(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        #year_model = Year(request.POST)
        if form.is_valid():
            #Not initializing db here, instead storing cleaned data for manipulation
            cleanForm = form.cleaned_data
            print(cleanForm)
            print(type(cleanForm))
            #obj = NameFormModel.objects.create(**form.cleaned_data)
            movies_json = JsonResponse(cleanForm, safe = False)
            #Always have to futz with dates for one reason or another. This prevents the db from having datetime() instead of your actual date.
            cleanForm["date_watched_field"] = cleanForm["date_watched_field"].strftime("%m/%d/%Y")
            #Check to see if your db already exists, if it doesn't you need to do some more work. If it does you can just continue
            if os.path.exists('moviedatabase.json'):
                with open('moviedatabase.json') as outfile:
                    data = json.load(outfile)
            if not os.path.exists('moviedatabase.json'):
                data = []
            data.append(cleanForm)
            with open('moviedatabase.json','w') as outfile:
                json.dump(data,outfile)
            # This is just to show a response to the user. You can render another form here instead of the default form. This is your chance to return a templated list instead but this should get you on the right road.
            return HttpResponse(str(data))
            #return render (request, 'form.html',{'form':form})
    else:
        form = NameForm()
    return render (request, 'form.html',{'form':form})

def moviemanager(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            form = NameForm()
            #return redirect('home:home')
            return render (request, 'form.html',{'form':form})
    else:
        form = NameForm()
    return render (request, 'form.html',{'form':form})

def about_page(request):
    page_tile = "About title"
    return render(request, "about.html",{"title":page_tile})

def contact_page(request):
    contact_title = "Contact title"
    return render(request, "contact.html",{"title":contact_title})


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Base track file data.
"""
from    typing      import (
    Type, Optional, Union, Dict, Tuple, Any, List,
    Sequence, Iterable, Iterator, cast, overload
)
from    datetime    import datetime
from    pathlib     import Path
from    copy        import deepcopy, copy
from    enum        import Enum
import  numpy       as     np

from    taskmodel       import levelprop, Level, InstrumentType
from    taskmodel.level import PHASE
from    utils           import initdefaults, NoArgs
from   .views           import Beads, Cycles, isellipsis, TrackView
from   .trackio         import opentrack, PATHTYPES, instrumentinfo
from   .beadstats       import (
    RawPrecisionCache  as _RawPrecisionCache,
    beadextension as _beadextension,
    phaseposition as _phaseposition,
)

IDTYPE       = Union[None, int, range]  # missing Ellipsys as mypy won't accept it
PIDTYPE      = Union[IDTYPE, slice, Sequence[int]]

DATA         = Dict[int, np.ndarray]
BEADS        = Dict[int, 'Bead']
DIMENSIONS   = Tuple[Tuple[float, float], Tuple[float, float]]

def _doc(tpe: type) -> str:
    if tpe.__doc__:
        doc = cast(str, tpe.__doc__).strip()
        return doc[0].lower()+doc[1:].replace('\n', '\n    ')+"\n"
    return ''

def _lazies():
    return ('_data', '_rawprecisions') + tuple(LazyProperty.LIST)

class Axis(Enum):
    "which axis to look at"
    Xaxis = 'Xaxis'
    Yaxis = 'Yaxis'
    Zaxis = 'Zaxis'
    @classmethod
    def _missing_(cls, name):
        if name in 'xyz':
            name = name.upper()
        if name in 'XYZ':
            name += 'axis'
        return cls(name)

class Bead:
    """
    Characteristics of a bead:

    * `position` is the bead's (X, Y, Z) position
    * `image` is the bead's calibration image
    """
    position: Tuple[float, float, float] = (0., 0., 0.)
    image:    np.ndarray                 = np.zeros(0, dtype = np.uint8)

    @initdefaults(locals())
    def __init__(self, **_):
        pass

    def thumbnail(self, size, fov):
        "extracts a thumbnail around the bead position"
        pos  = fov.topixel(np.array(list(self.position[:2])))
        ind  = np.int32(np.round(pos))-size//2  # type: ignore
        return fov.image[ind[1]:ind[1]+size,ind[0]:ind[0]+size]

class FoV:
    """
    The data concerning the field of view:

    * `image` is one image of the field of view
    * `dim` are conversion factors from pixel to nm in the format:
    "(X slope, X bias), (Y slope, Y bias)".
    * `beads` is a dictionnary of information per bead:
    """
    if __doc__:
        __doc__ += ''.join(f'    {i}\n' for i in cast(str, Bead.__doc__).split('\n')[-4:])

    image                       = np.empty((0,0), dtype = np.uint8)
    beads:         BEADS        = {}
    dim:           DIMENSIONS   = ((1., 0.), (1., 0.))

    @initdefaults(locals())
    def __init__(self, **kwa):
        pass

    def bounds(self, pixel = False):
        "image bounds in nm (*pixel == False*) or pixels"
        rng = self.image.shape[1], self.image.shape[0]
        return (0, 0) + rng if pixel else self.tonm((0,0)) + self.tonm(rng)

    def size(self, pixel = False):
        "image size in nm (*pixel == False*) or pixels"
        if self.image is None:
            xpos = [i.position[0] for i in self.beads.values()]
            ypos = [i.position[1] for i in self.beads.values()]
            if len(xpos) and len(ypos):
                return (max(1., np.nanmax(ypos)-np.nanmin(ypos)),
                        max(1., np.nanmax(xpos)-np.nanmin(xpos)))
            return 1., 1.

        rng = self.image.shape[1], self.image.shape[0]
        return rng if pixel else self.tonm(rng)

    def tonm(self, arr):
        "converts pixels to nm"
        return self.__convert(arr, self.dim)

    def topixel(self, arr):
        "converts pixels to nm"
        return self.__convert(arr, tuple((1./i, -j/i) for i, j in self.dim))

    @property
    def scale(self):
        "The pixel scale: error occurs if the pixel is not square"
        if abs(self.dim[0][0]-self.dim[1][0]) > 1e-6:
            raise ValueError("Pixel is not square")
        return self.dim[0][0]

    @staticmethod
    def __convert(arr, dim):
        if len(arr) == 0:
            return arr

        (sl1, int1), (sl2, int2) = dim
        if isinstance(arr, np.ndarray):
            return [sl1, sl2] * arr + [int1, int2]

        if isinstance(arr, tuple) and len(arr) == 2 and np.isscalar(arr[0]):
            return tuple(i*k+j for (i, j), k in zip(dim, arr))

        tpe = iter if hasattr(arr, '__next__') else type(arr)
        return tpe([(sl1*i+int1, sl2*j+int2) for i, j in arr])  # type: ignore

class Secondaries:
    """
    Consists in arrays of sparse measures:

    * `track.secondaries.tservo` is the servo temperature
    * `track.secondaries.tsample` is the sample temperature
    * `track.secondaries.tsink` is the heat sink temperature
    * `track.secondaries.vcap` is a measure of magnet altitude using voltages
    * `track.secondaries.zmag` is a measure of magnet altitude provided by its motor
    * `track.secondaries.seconds` is the time axis
    """
    def __init__(self, track):
        self.__track = track

    data    = property(lambda self: self.__track._secondaries,
                       doc = "returns all the data")
    tservo  = cast(np.ndarray, property(lambda self: self.__value("Tservo"),
                                        doc = "the servo temperature"))
    tsample = cast(np.ndarray, property(lambda self: self.__value("Tsample"),
                                        doc = "the sample temperature"))
    tsink   = cast(np.ndarray, property(lambda self: self.__value("Tsink"),
                                        doc = "the sink temperature"))
    vcap    = cast(np.ndarray, property(lambda self: self.data.get("vcap"),
                                        doc = "the magnet position: vcap"))
    frames  = cast(np.ndarray, property(lambda self: self.__track._secondaries["t"],
                                        doc = "the time axis (frame count)"))
    seconds = cast(
        np.ndarray,
        property(
            lambda self: (self.__track._secondaries["t"] / self.__track.framerate),
            doc = "the time axis (s)"
        )
    )
    zmag    = cast(np.ndarray, property(lambda self: self.__track._secondaries["zmag"],
                                        doc = "the magnet altitude sampled at frame rate"))

    @property
    def cid(self) -> np.ndarray:
        "return the cycle per frame"
        arr = np.zeros(self.__track.nframes, dtype = 'i4')
        for i, j  in enumerate(np.split(
                arr,
                self.__track.phases[:,0]-self.__track.phases[0,0]
        )[1:]):
            j[:] = i
        return arr

    @property
    def cycleframe(self) -> np.ndarray:
        "return the frame-number per cycle, with each cycle starting at 0"
        arr = np.zeros(self.__track.nframes, dtype='i4')
        for j in np.split(
                arr,
                self.__track.phases[:, 0]-self.__track.phases[0, 0]
        )[1:]:
            j[:] = np.arange(len(j))
        return arr

    @property
    def cidcycles(self) -> Cycles:
        "return the phases per frame in cycles"
        return self.__track.cycles.withdata({"cid": self.cid})

    @property
    def phase(self) -> np.ndarray:
        "return the phases per frame"
        arr = np.zeros(self.__track.nframes, dtype = 'i1')
        nph = self.__track.nphases
        for i, j  in enumerate(np.split(
                arr,
                self.__track.phases.ravel()-self.__track.phases[0,0]
        )[1:]):
            j[:] = i % nph
        return arr

    @property
    def phasecycles(self) -> Cycles:
        "return the phases per frame in cycles"
        return self.__track.cycles.withdata({"phase": self.phase})

    @property
    def zmagcycles(self) -> Cycles:
        "the magnet altitude sampled at frame rate"
        return self.__track.cycles.withdata({"zmag": self.zmag})

    @property
    def cycles(self) -> Cycles:
        "return zmag, phase and cid per cycle"
        return self.__track.cycles.withdata({
            i: getattr(self, i) for i in ('cid', 'zmag', 'phase')
        })

    def keys(self):
        "return the available secondaries"
        return set(self.data.keys()) | {"tservo", "tsample", "tsink", "vcap", "seconds", "zmag"}

    def __getitem__(self, name):
        "returns a secondary value"
        if hasattr(self, name):
            return getattr(self, name)

        return self.__value(name) if name.startswith("T") else self.data[name]

    def __value(self, name):
        val = getattr(self.__track, '_secondaries')
        if val is None or name not in val:
            return None
        arr           = np.copy(val[name])
        arr['index'] -= self.__track.phases[0,0]
        arr           = arr[arr['index'] >= 0]
        arr           = arr[arr['index'] < self.__track.nframes]
        return arr

class LazyProperty:
    "Checks whether the file was opened prior to returning a value"
    LIST: List[str] = []

    def __init__(self, name: str = '', tpe: type = None) -> None:
        self._name = ''
        self._type = tpe
        if tpe and getattr(tpe, '__doc__', None):
            self.__doc__ = tpe.__doc__
        if name:
            self._name = '_'+name
            self.LIST.append(self._name)

    def __set_name__(self, _, name):
        self.__init__(name, self._type)

    @staticmethod
    def _load(inst):
        inst.load()

    def __get__(self, inst: 'Track', owner):
        if inst is not None:
            self._load(inst)

        return (self._type(inst) if self._type and inst else
                getattr(owner if inst is None else inst, self._name))

    def __set__(self, obj: 'Track', val):
        self._load(obj)
        setattr(obj, self._name, val)
        return getattr(obj, self._name)

class InstrumentProperty(LazyProperty):
    "Checks whether the file was opened prior to returning a value"
    def _load(self, inst):
        if not inst.isloaded:
            info = instrumentinfo(inst)
            info['type'] = InstrumentType(info['type'])
            setattr(inst, self._name, info)

class ResettingProperty:
    "Resets all if this attribute is changed"
    def __init__(self):
        self._name = ''

    def __set_name__(self, _, name):
        self._name = '_'+name

    def __get__(self, obj: 'Track', _):
        return getattr(obj, self._name) if obj else self

    def __set__(self, obj: 'Track', val):
        setattr(obj, self._name, val)
        obj.unload()
        return getattr(obj, self._name)

class ViewDescriptor:
    "Access to views"
    tpe:  Optional[type] = None
    args: Dict[str, Any] = dict()

    def __get__(self, instance, owner):
        return self if instance is None else instance.view(self.tpe, **self.args)

    def __set_name__(self, _, name):
        self.tpe  = Cycles if name.startswith('cycles') else Beads
        self.args = dict(copy = False)
        setattr(self, '__doc__', getattr(self.tpe, '__doc__', None))

class PhaseManipulator:
    """
    Helper class for manipulating phases.
    """
    def __init__(self, track):
        self._track = track

    def __getitem__(self, value):
        return PHASE[value]

    def cut(self, cid:PIDTYPE = None) -> Tuple[np.ndarray, np.ndarray]:
        """
        Returns a selection of phases, *reindexed* to zero, with a list of
        frame ids corresponding to theses phases.

        This can be used to create a track containing a fraction of the original data.
        """
        trk = self._track
        if isellipsis(cid):
            cycs = slice(None, None)

        if isinstance(cid, (slice, range)):
            cycs = slice(0               if cid.start is None else cid.start,
                         len(trk.phases) if cid.stop  is None else cid.stop,
                         1               if cid.step  is None else cid.step)
        else:
            cycs = np.array(cid, dtype = 'i4')

        phases = trk.phases[cycs]
        first  = phases[:,0]
        if isinstance(cycs, slice):
            last = trk.phases[cycs.start+1:cycs.stop+1:cycs.step,0]  # type: ignore
        else:
            tmp  = cycs+1
            last = trk.phases[tmp[tmp < len(trk.phases)],0]
        if len(last) < len(first):
            last = np.append(last, trk.nframes+trk.phases[0,0])

        inds   = np.concatenate([np.arange(j, dtype = 'i4')+i for i, j in zip(first, last-first)])
        inds  -= self._track.phases[0, 0]
        phases = (np.insert(np.cumsum(np.diff(np.hstack([phases, last[:,None]]))), 0, 0)
                  [:-1].reshape((-1, phases.shape[1])))
        return inds, phases

    def duration(self, cid:PIDTYPE = None, pid:IDTYPE = None) -> Union[np.ndarray, int]:
        """
        Returns the duration of a phase per cycle.
        """
        if isinstance(pid, (tuple, list, np.ndarray)):
            return np.vstack([self.__duration(cid, i) for i in cast(list, pid)]).T
        return self.__duration(cid, pid)

    def select(self, cid:PIDTYPE = None, pid:PIDTYPE = None) -> Union[np.ndarray, int]:
        """
        Returns the start time of the cycle and phase.

        If pid >= nphases, the end time of cycles is returned.
        if pid is a sequence of ints, a table is returned.
        """
        if isinstance(pid, (tuple, list, np.ndarray)):
            return np.vstack([self.__select(cid, i) for i in cast(list, pid)]).T
        return self.__select(cid, pid)

    nframes  = cast(int, property(lambda self: self._track.nframes))
    ncycles  = cast(int, property(lambda self: self._track.ncycles))
    nphases  = cast(int, property(lambda self: self._track.nphases))
    if __doc__:
        __doc__ += "   * `cut`: "      + cast(str, cut.__doc__)     .strip()+"\n"
        __doc__ += "   * `duration`: " + cast(str, duration.__doc__).strip()+"\n"
        __doc__ += "   * `select`: "   + cast(str, select.__doc__)  .strip()+"\n"

    def __duration(self, cid:PIDTYPE = None, pid:IDTYPE = None) -> Union[np.ndarray, int]:
        phases = self._track.phases
        if isinstance(pid, str):
            pid = self[pid]

        if isinstance(pid, int):
            pid  = range(pid, cast(int, None if pid == -1 else pid+1))
        elif isellipsis(pid):
            pid  = range(phases.shape[1])
        elif isinstance(pid, (slice, range)):
            pid = range(
                None if pid.start is None else self[pid.start],
                None if pid.stop  is None else self[pid.stop]
            )
        else:
            raise TypeError()

        start = 0 if pid.start is None else pid.start
        if pid.stop == start:
            return np.zeros(len(phases), dtype = 'i4')[cid]
        return self.select(cid, pid.stop) - self.select(cid, pid.start)

    def __select(self, cid:PIDTYPE = None, pid:PIDTYPE = None) -> Union[np.ndarray, int]:
        phases = self._track.phases
        ells   = isellipsis(cid), isellipsis(pid)
        if not ells[1]:
            pid = self[pid]
        if np.isscalar(pid) and pid >= self._track.nphases:
            if np.isscalar(cid):
                return (self._track.nframes if cid >= self._track.ncycles-1 else
                        phases[1+cast(int, cid),0]-phases[0,0])

            tmp = np.append(phases[1:,0]-phases[0,0], np.int32(self._track.nframes))
            return tmp[None if ells[0] else cid]

        return (phases        if all(ells) else
                phases[:,pid] if ells[0]   else
                phases[cid,:] if ells[1]   else
                phases[cid,pid]) - phases[0,0]

class PathInfo:
    """
    Provides information on the path itself:

    * `paths`: a tuple of paths
    * `trackpath`: the main path, i.e. not the grs
    * `size` (*megabytes*) is the size in bytes (megabytes) of *trackpath*
    * `stat`: stats on the *trackpath*
    * `modification`: the date oflast modification. This is basically the
    time of experiment.
    * `creation`: the creation date. **DISCARD** when using PicoTwist tracks.
    """
    track: 'Track'

    def __get__(self, inst, tpe):
        if inst is None:
            return self
        cpy       = PathInfo()
        cpy.track = inst
        return cpy

    @property
    def paths(self) -> List[Path]:
        "returns all paths"
        path = self.track.path
        return (
            [Path(path)] if isinstance(path, str)  else
            [path]       if isinstance(path, Path) else
            []           if path is None           else
            [Path(str(i)) for i in cast(Iterable, path)]
        )

    @property
    def trackpath(self) -> Path:
        "returns all paths"
        path = self.track.path
        return Path(str(path[0])) if isinstance(path, (list, tuple)) else Path(str(path))

    pathcount    = property(lambda self: len(self.paths))
    stat         = property(lambda self: self.trackpath.stat())
    size         = property(lambda self: self.stat.st_size)
    megabytes    = property(lambda self: self.size >> 20)
    creation     = property(lambda self: datetime.fromtimestamp(self.stat.st_ctime))

    @property
    def modification(self):
        "return the modification date of the **original** track file."
        date = getattr(self.track, '_modificationdate', None)
        if date is None and self.trackpath.exists():
            date = self.stat.st_mtime
        else:
            date = 0
        return datetime.fromtimestamp(date)

@levelprop(Level.project)
class Track:
    """
    The data from a track file, accessed lazily (only upon request).

    The data can be read as:

    ```python
    >>> raw = Track(path =  "/path/to/a/file.trk")
    >>> grs = Track(path =  ("/path/to/a/file.trk",
    ...                      "/path/to/a/gr/directory",
    ...                      "/path/to/a/specific/gr"))
    ```

    The data can then be accessed as follows:

    * for the *time* axis: `raw.beads['t']`
    * for the magnet altitude: `raw.beads['zmag']`
    * specific beads: `raw.beads[0]` where 0 can be any bead number
    * specific cycles: `raw.cycles[1,5]` where 1 and 5 can be any bead or cycle number.

    Some slicing is possible:

    * `raw.cycles[:,range(5,10)]` accesses cycles 5 though 10 for all beads.
    * `raw.cycles[[2,5],...]` accesses all cycles for beads 5 and 5.

    Only data for the Z axis is available. Use the `axis = 'X'` or `axis = 'Y'`
    options in the constructor to access other data.

    Other attributes are:

    * `framerate` is this experiment's frame rate
    * `phases` is a 2D array with one row per cycle and one column per phase
    containing the first index value of each cycle and phase.
    * `path` is the path(s) to the data
    * `axis` (Є {{'X', 'Y', 'Z'}}) is the data axis
    * `ncycles` is the number of cycles
    * `nphases` is the number of phases
    * `secondaries` {secondaries}
    * `fov` {fov}
    * `pathinfo` {pathinfo}
    """
    if __doc__:
        __doc__ = __doc__.format(
            secondaries = _doc(Secondaries),
            fov         = _doc(FoV),
            pathinfo    = _doc(PathInfo)
        )

    key: Optional[str] = None
    instrument         = cast(Dict[str, Any],      InstrumentProperty())
    phases             = cast(np.ndarray,          LazyProperty())
    framerate          = cast(float,               LazyProperty())
    fov                = cast(FoV,                 LazyProperty())
    secondaries        = cast(Secondaries,         LazyProperty(tpe = Secondaries))
    path               = cast(Optional[PATHTYPES], ResettingProperty())
    axis               = cast(Axis,                ResettingProperty())
    data               = cast(
        DATA,
        property(lambda self: self.getdata(), lambda self, val: self.setdata(val))
    )

    @initdefaults('key',
                  **{i: '_' for i in locals() if i != 'key' and i[0] != '_'})
    def __init__(self, **kwa):
        self._rawprecisions: _RawPrecisionCache = _RawPrecisionCache()
        if 'rawprecisions' in kwa and isinstance(kwa['rawprecisions'], _RawPrecisionCache):
            self._rawprecisions = kwa['rawprecisions']
        elif 'rawprecisions' in kwa:
            self._rawprecisions.computer = kwa['rawprecisions']

    ncycles  = cast(int,                 property(lambda self: len(self.phases)))
    nphases  = cast(int,                 property(lambda self: self.phases.shape[1]))
    beads    = cast(Beads,               ViewDescriptor())
    cycles   = cast(Cycles,              ViewDescriptor())
    phase    = property(PhaseManipulator, doc = PhaseManipulator.__doc__)
    pathinfo = PathInfo()

    def getdata(self) -> DATA:
        "returns the dataframe with all bead info"
        self.load()
        return cast(DATA, self._data)

    def setdata(self, data: Optional[Dict[int, np.ndarray]]):
        "sets the dataframe"
        if data is None:
            self.unload()
        else:
            self._data = data

    @property
    def nframes(self) -> int:
        "returns the number of frames"
        return len(next(iter(self.data.values()), []))

    @property
    def isloaded(self) -> bool:
        "returns whether the data was already acccessed"
        return self._data is not None

    def load(self, cycles: Optional[slice] = None) -> 'Track':
        "Loads the data"
        if self._data is None and self._path is not None:
            opentrack(self, cycles)
        return self

    def unload(self):
        "Unloads the data"
        for name in _lazies():
            setattr(self, name, deepcopy(getattr(type(self), name)))

    def view(self, tpe:Union[Type[TrackView], str], **kwa):
        "Creates a view of the suggested type"
        viewtype = (tpe     if isinstance(tpe, type) else
                    Cycles  if tpe.lower() == 'cycles' else
                    Beads)
        kwa.setdefault('parents', (self.key,) if self.key else (self.path,))
        kwa.setdefault('track',   self)
        return viewtype(**kwa)

    @overload       # noqa: F811
    def rawprecision(
            self,
            ibead:  int,
            phases: Union[None, Dict[int, float], Tuple[int, int]],
    ):
        "Obtain the raw precision for a given bead"

    @overload       # noqa: F811
    def rawprecision(self, computertype: str) -> None:
        "Set the raw precision computer"

    @overload       # noqa: F811
    def rawprecision(self) -> str:
        "Obtain the raw precision computer"

    @overload       # noqa: F811
    def rawprecision(
            self,
            ibead:  Optional[Iterable[int]],
            phases: Union[None, Dict[int, float], Tuple[int, int]],
    ) -> Iterator[Tuple[int,float]]:
        "Obtain the raw precision for a number of beads"

    def rawprecision(self, ibead = NoArgs, phases = None):   # noqa: F811
        "Obtain the raw precision for a number of beads"
        if ibead is NoArgs:
            return self._rawprecisions.computer
        if isinstance(ibead, (type, str)):
            self._rawprecisions.computer = ibead
            return None
        return self._rawprecisions.get(self, ibead, phases)

    if __doc__ is not None:
        setattr(rawprecision, '__doc__', getattr(_RawPrecisionCache.get, '__doc__', None))

    beadextension = _beadextension
    phaseposition = _phaseposition

    def shallowcopy(self):
        "make a shallow copy of the track: different containers but for the true data"
        cpy = self.__class__()
        cpy.__dict__.update({i: copy(j) for i, j in self.__dict__.items()})
        return cpy

    def __getstate__(self):
        keys = set(_lazies()+('_path', '_axis'))

        test = dict.fromkeys(keys, lambda i, j: j != getattr(type(self), i))  # type: ignore
        test.update(_phases = lambda _, i: len(i),
                    key     = lambda _, i: i is not None)

        cnv  = dict.fromkeys(keys | {'key'}, lambda i: i)  # type: ignore
        cnv.update(_secondaries = lambda i: getattr(i, 'data', None),
                   _axis        = lambda i: getattr(i, 'value', i)[0])

        info = self.__dict__.copy()
        if self._lazydata_:
            for i in ('_data', '_secondaries', '_fov'):
                info.pop(i, None)

        for name in set(cnv) & set(info):
            val = info.pop(name)
            if test[name](name, val):
                info[name[1:] if name[0] == '_' else name] = cnv[name](val)
        return info

    def __setstate__(self, values):
        if isinstance(values.get('fov', None), dict):
            fov           = values['fov']
            fov["beads"]  = {i: Bead(**j) for i, j in fov.get('beads', {}).items()}
            values['fov'] = FoV(**fov)

        if isinstance(values.get('instrument', {}).get("type", None), str):
            values['instrument']['type'] = InstrumentType(values['instrument']['type'])

        self.__init__(**values)
        keys = frozenset(self.__getstate__().keys()) | frozenset(('data', 'secondaries'))
        self.__dict__.update({i: j for i, j in values.items() if i not in keys})

    @property
    def _lazydata_(self):
        """
        Used internally to discard the data from __getstate__, or not
        """
        return self.__dict__.get('_lazydata_', self.path is not None)

    @_lazydata_.setter
    def _lazydata_(self, val):
        if val is None:
            self.__dict__.pop('_lazydata_', None)
        else:
            self.__dict__['_lazydata_'] = val

    _framerate:       float                = 30.
    _fov:             Optional[FoV]        = None
    _instrument:      Dict[str, Any]       = {
        "type": InstrumentType.picotwist.name,
        "name": None
    }
    _phases:          np.ndarray           = np.empty((0,9), dtype = 'i4')
    _data:            Optional[DATA]       = None  # type: ignore
    _secondaries:     Optional[DATA]       = None
    _rawprecisions:   _RawPrecisionCache   = _RawPrecisionCache()
    _path:            Optional[PATHTYPES]  = None
    _axis:            Axis                 = Axis.Zaxis


from typing import Any, Dict, Optional

import httpx

from ...client import Client
from ...models.wallet_module_response import WalletModuleResponse
from ...types import UNSET, Response

def _get_kwargs(
    *,
    client: Client,
    did: str,
) -> Dict[str, Any]:
    url = "{}/wallet/did/local/rotate-keypair".format(client.base_url)

    headers: Dict[str, str] = client.get_headers()
    cookies: Dict[str, Any] = client.get_cookies()

    params: Dict[str, Any] = {}
    params["did"] = did

    params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

    return {
        "method": "patch",
        "url": url,
        "headers": headers,
        "cookies": cookies,
        "timeout": client.get_timeout(),
        "params": params,
    }

def _parse_response(*, response: httpx.Response) -> Optional[WalletModuleResponse]:
    if response.status_code == 200:
        response_200 = WalletModuleResponse.from_dict(response.json())

        return response_200
    return None

def _build_response(*, response: httpx.Response) -> Response[WalletModuleResponse]:
    return Response(
        status_code=response.status_code,
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(response=response),
    )

def sync_detailed(
    *,
    client: Client,
    did: str,
) -> Response[WalletModuleResponse]:
    """Rotate keypair for a DID not posted to the ledger

    Args:
        did (str):

    Returns:
        Response[WalletModuleResponse]
    """

    kwargs = _get_kwargs(
        client=client,
        did=did,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)

def sync(
    *,
    client: Client,
    did: str,
) -> Optional[WalletModuleResponse]:
    """Rotate keypair for a DID not posted to the ledger

    Args:
        did (str):

    Returns:
        Response[WalletModuleResponse]
    """

    return sync_detailed(
        client=client,
        did=did,
    ).parsed

async def asyncio_detailed(
    *,
    client: Client,
    did: str,
) -> Response[WalletModuleResponse]:
    """Rotate keypair for a DID not posted to the ledger

    Args:
        did (str):

    Returns:
        Response[WalletModuleResponse]
    """

    kwargs = _get_kwargs(
        client=client,
        did=did,
    )

    async with httpx.AsyncClient(verify=client.verify_ssl) as _client:
        response = await _client.request(**kwargs)

    return _build_response(response=response)

async def asyncio(
    *,
    client: Client,
    did: str,
) -> Optional[WalletModuleResponse]:
    """Rotate keypair for a DID not posted to the ledger

    Args:
        did (str):

    Returns:
        Response[WalletModuleResponse]
    """

    return (
        await asyncio_detailed(
            client=client,
            did=did,
        )
    ).parsed


import pygame
from random import randint

pygame.init()

#game window
WIDTH = 600
HEIGHT = 400
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Shot Clock")
pygame.display.set_icon(pygame.image.load('icon.png'))

#gmae font
pygame.font.init()
GAME_FONT = pygame.font.Font('gamera.TTF', 35)

#game start and timing variables
game_start = False  # boolean that controls main loop
start_time = 0  # Start time for game timer
TIME_ALLOWED = 60  # amount of time player has (1 minute)

#ball properties
MAX_BALL_SPEED = 17
MIN_BALL_SPEED = 4

#game colors
BLACK = (0, 0, 0)
ORANGE = (252, 102, 0)
WHITE  = (255, 255, 255)

#sprites
HOOP = pygame.image.load('hoop.png')
BASKETBALL = pygame.image.load('ball.png')

class Ball:
    def __init__(self,x, y,vel):
        self.x = x
        self.y = y
        self.vel = vel

    def draw_ball(self, surface):
        surface.blit(BASKETBALL,(self.x, self.y))

    def update_position(self):
        self.y += self.vel

    def is_off_screen(self):
        return self.y > 420

# game start loop
def start_game():
    global game_start
    global start_time

    line1 = GAME_FONT.render("Make Shots! You Have 60s!!", True, ORANGE)
    line2 = GAME_FONT.render("Press SPACE To Start!!", True, ORANGE)
    line3 = GAME_FONT.render("ESC to Exit  R to Reset", True, ORANGE)
    line4 = GAME_FONT.render("A:Left   D:Right", True, ORANGE)

    win.blit(line1, (50, 50))
    win.blit(line2, (80, 130))
    win.blit(line3, (80, 210))
    win.blit(line4, (150, 290))

    pygame.display.update()

    while not game_start:

        if game_start:
            break

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    game_start = True
                    start_time = pygame.time.get_ticks()
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    exit()

def is_time_left():
    return TIME_ALLOWED > int((pygame.time.get_ticks() - start_time) / 1000)

game_balls = [
    Ball(randint(30, 570), 0, randint(1, MAX_BALL_SPEED)),
    Ball(randint(30, 570), 0, randint(1, MAX_BALL_SPEED)),
    Ball(randint(30, 570), 0, randint(1, MAX_BALL_SPEED)),
    Ball(randint(30, 570), 0, randint(1, MAX_BALL_SPEED))
]

def new_ball(index):
    global MAX_BALL_SPEED
    global MIN_BALL_SPEED

    game_balls[index].x = randint(30, 570)
    game_balls[index].y = 0
    game_balls[index].vel = randint(MIN_BALL_SPEED, MAX_BALL_SPEED)

    if MIN_BALL_SPEED < MAX_BALL_SPEED:
        MIN_BALL_SPEED += 1

def main():

    global game_start
    global start_time

    hoop_x = 260
    hoop_y = 360

    hitbox_x = 280
    hitbox_y = 380

    clock = pygame.time.Clock()
    SCORE = 0  # player score

    start_game()
    if not game_start:
        print("\nYou Didn't Press Space :( ")
    else:
        print("\nGame starting....")

    while game_start and is_time_left():
        TIME_LEFT = TIME_ALLOWED -  int((pygame.time.get_ticks() - start_time) / 1000)
        clock.tick(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_start = False

        keys = pygame.key.get_pressed()

        # if press left(A):
        # move the basket to left (-1 to y value)
        if keys[pygame.K_a]:
            hoop_x -= 40
            hitbox_x -= 40
            # after moving the platform. if its x or y match those of the platform
            # they have collided/touched (the ball is caught) add one

        # if press right(D):
        # move the basket to the right(+1 to y value)
        if keys[pygame.K_d]:
            hoop_x += 30
            hitbox_x += 30

        # if press escape(ESC)
        # quit game
        if keys[pygame.K_ESCAPE]:
            print("Exiting Game......")
            game_start = False

        # if press reset(R)
        # resets timer to 60s
        if keys[pygame.K_r]:
            start_time = pygame.time.get_ticks()
            SCORE = 0

        win.fill((0, 0, 0))

        # basket/hoop
        win.blit(HOOP, (hoop_x,hoop_y))

        # balls
        # Loop the same (4) balls with a new speed and position each time they come back.
        # ball is looped after it registers as a point or falls off screen
        for i in range(4):

            if game_balls[i].is_off_screen():
                new_ball(i)

            game_balls[i].draw_ball(win)
            game_balls[i].update_position()

            # if any part of the hoop/platform is touched by a ball as a collision
            # ball is cleared from the display and new ball appears
            if (hitbox_y) < game_balls[i].y < (hitbox_y + 20) and (hitbox_x) < \
                    game_balls[i].x < (hoop_x + 120):
                    # hitbox is simplified to be 120x20 rectangle starting from the top left corner of the rim
                    # if a ball falls within this region it is considered a score.
                SCORE += 1
                new_ball(i)

        # prints time on screen
        time_tracker = GAME_FONT.render(F"Time:{TIME_LEFT}", True, ORANGE)
        win.blit(time_tracker, (455, 0))

        # prints score on screen
        score_tracker = GAME_FONT.render(F"Score:{SCORE}", True, ORANGE)
        win.blit(score_tracker, (0, 0))

        pygame.display.update()

    # End Game Loop
    # End screen lasts for 10 secs and exits automatically
    close_window = False
    while not close_window:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    close_window = True

                if event.key == pygame.K_r:
                    win.fill(BLACK)
                    main()

        win.fill(BLACK)

        game_over = GAME_FONT.render("Game Over!", True, ORANGE)
        win.blit(game_over, (215, 50))

        final_score = GAME_FONT.render(F"Final Score: {SCORE} ", True, WHITE)
        win.blit(final_score, (185, 130))

        new_game = GAME_FONT.render("Press R to Start New Game", True, ORANGE)
        win.blit(new_game, (50,210))

        exit_game = GAME_FONT.render("Press ESC to Close Game", True, ORANGE)
        win.blit(exit_game, (70, 290))

        pygame.display.update()

    # gg
    pygame.quit()

if __name__ == "__main__":
     main()


#SNAKE MENU
import pygame
import time

ANSI_HOME_CURSOR = u"\u001B[0;0H\u001B[2"
RESET_COLOR = u"\u001B[0m\u001B[2D"

def snake_print(position):
  snake = ["                     ____", "                    / . .\ ", "                    \   ---<", "   _________________/ /", "  \__________________/"]
  print(ANSI_HOME_CURSOR)
  print(RESET_COLOR)
  sp = " " * position
  for line in snake:
    print("\033[1;33;93m" + sp +  line)
  print(RESET_COLOR)

def snake():

  start = 0
  end = 50
  step = 2

  for position in range(start, end, step):
    snake_print(position)
    time.sleep(0.3)

#main menu
def main():
  snake()
  print(" ")
  print("SNAKE REMAKE!")
  print(" ")
  print("1: Tutorial")
  print("2: Play")
  print("0: Exit")

  try:
    answer = int(input("SELECT A NUMBER: "))
    if answer >= 4:
      print("INVALID NUMBER:", answer)
      return

    while answer < 4:
      if answer == 1:
        print("Tutorial: Control the snake using your arrow keys. Eat the fruit, and avoid moving off the screen or bumping into yourself. Get the as many fruits as you can!")
        answer = int(input("SELECT A NUMBER TO CONTINUE: "))
      elif answer == 2:
        print(" ")
        print("E: Easy")
        print("M: Medium")
        print("H: Hard")
        leveltype = input("SELECT A LEVEL: ")
        setlevel(leveltype)
        return
      elif answer == 0:
        return
      else:
        print("INVALID NUMBER: {answer}")
        return
  except ValueError:
    print("NOT A NUMBER")

def easy():
  import easy
  pygame.init()
def medium():
  import medium
  pygame.init()
def hard():
  import hard
  pygame.init()

def setlevel(leveltype):
  if leveltype == "E":
    print("Welcome to Easy Mode!")
    easy()
  elif leveltype == "M":
    print("Welcome to Medium Mode!")
    medium()
  elif leveltype == "H":
    print("Welcome to Hard Mode!")
    hard()
  else:
    print("INVALID INPUT:", leveltype)

main()


from matplotlib import pyplot as plt
import torch
from torch.utils.data import Dataset as torchDataset
import pandas as pd
from transformers import BertTokenizer, BertModel
import Config

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased').to(Config.device)

class CsvDataset(torchDataset):
    def __init__(self,csv_path,read_columns = True,sp = ','):
        super(CsvDataset, self).__init__()
        self.dataTell = []
        if csv_path == None:
            return
        print("[npc report]read data...",end = '')
        self.raw_lines = open(csv_path,"r",encoding="utf8").read().split('\n')
        print("done.")

    def __splitLine__(line,sp = ','):
        exist_quotation = False
        ll = len(line)
        lst = 0
        res = []
        for i in range(1,ll):
            if line[i] == sp and not exist_quotation:
                res.append(line[lst:i])
                lst = i + 1
            elif line[i] == '"':
                exist_quotation = not exist_quotation
        res.append(line[lst:])
        return res

    def __getitem__(self, idx: int):
        try:
            label,txt = CsvDataset.__splitLine__(self.raw_lines[idx])
            tl = 1 if label == "True" else 0
            inputs = tokenizer(txt ,padding = 'max_length', return_tensors='pt',truncation  = True).to(Config.device)

            with torch.no_grad():
                embedding = model(**inputs).last_hidden_state

            return embedding,torch.Tensor([[tl,1-tl]]).to(Config.device)

        except Exception as e:
            print("[npc report] Unhandle Eorr:",e,"auto handle:","skip")
            return -1,-1

    def __len__(self) -> int:
        return len(self.raw_lines)

    def collate_func(self,batch_dic):
        xs,ys = [],[]
        for x,y in batch_dic:
            if type(x) == type(-1):
                continue
            xs.append(x.unsqueeze(0))
            ys.append(y)
        return torch.cat(xs,dim=0),torch.cat(ys,dim=0)

    def Split(self,testPor = 0.3):
        train,test = CsvDataset(None),CsvDataset(None)
        half = int(len(self)* 0.5) # 1000
        spl = int(half * (1 -testPor)) # 700
        train.raw_lines = self.raw_lines[:spl] + self.raw_lines[half:half + spl]

        test.raw_lines = self.raw_lines[spl:half] + self.raw_lines[-(half - spl):]

        return train,test

    def Merge(dtls:list):
        res = CsvDataset(None)
        res.raw_lines = []
        for dt in dtls:
            res.raw_lines += dt.raw_lines
        return res

class PdCsvDataset(torchDataset):
    def __init__(self,csv_path = None):
        super(PdCsvDataset, self).__init__()
        self.dataidx = []
        self.labels = []
        if csv_path != None:
            self.csv = pd.read_csv(csv_path,sep=',')
            self.statistics()

    def collate_func(self,batch_dic):
        xs,ys = [],[]
        for x,y in batch_dic:
            xs.append(x.unsqueeze(0).unsqueeze(0))
            ys.append(y.unsqueeze(0))
        return torch.cat(xs,dim=0),torch.cat(ys,dim=0)

    def statistics(self,read_num = 1000,cls = "reviews.doRecommend"):
        tabu = {}
        for idx,cls in enumerate(self.csv[cls]):
            if type(cls) != type(True):
                continue
            print(self.csv.iloc[idx]["reviews.text"])
            inputs = tokenizer(self.csv.iloc[idx]["reviews.text"], return_tensors='pt')
            if len(inputs) > 47:
                continue
            if cls in tabu.keys():
                if tabu[cls] <= read_num:
                    self.dataidx.append(idx)
                    self.labels.append(cls)
                    tabu[cls] += 1
            else:
                tabu.setdefault(cls,1)
                self.labels.append(cls)
        self.clses = list(tabu.keys())
        self.tabu = tabu
        print("[npc report] PdCsvDataset stat :",tabu)

    def __getitem__(self, index: int):
        idx = self.dataidx[index]
        tl = 1 if self.labels[index] else 0
        inputs = tokenizer(self.csv.iloc[idx]["reviews.text"], return_tensors='pt')
        with torch.no_grad():
            embedding = model(**inputs).last_hidden_state

        c,h,w = embedding.shape
        if  h < 46:
            embedding = torch.cat([embedding,torch.zeros(1,46- h,w)],dim = 1)
        return embedding[0,:46,:],torch.Tensor([tl,1-tl])

    def __len__(self) -> int:
        return len(self.dataidx)

    def Split(self,testPor = 0.3):
        train,test = PdCsvDataset(None),PdCsvDataset(None)
        half = int(len(self)* 0.5) # 1000
        spl = int(half * (1 -testPor)) # 700
        train.labels = self.labels[:spl] + self.labels[half:half + spl]
        train.dataidx = self.dataidx[:spl] + self.dataidx[half:half + spl]
        train.csv = self.csv

        test.labels = self.labels[spl:half] + self.labels[-(half - spl):]
        test.dataidx = self.dataidx[spl:half] + self.dataidx[-(half - spl):]
        test.csv = self.csv

        return train,test

if __name__ == "__main__":
    count = 0
    pcsv = PdCsvDataset("../dataset.csv")
    print(len(pcsv))

    # txt,cls = pcsv[0]
    # inputs = tokenizer("It is the time you have wasted for your rose that makes your rose so important.", return_tensors='pt')
    # with torch.no_grad():
    #     all_encoder_layers = model(**inputs)
    #     print(all_encoder_layers.last_hidden_state)

    plty1 = []
    plty2 = []
    x = []
    count = 0
    for txt,cls in pcsv:
        x.append(count)
        count+=1
        plty1.append(txt.shape[1])
        plty2.append(txt.shape[2])

    print(sum(plty1)/len(plty1),sum(plty2)/len(plty2))
    plt.plot(x,plty1,color = 'red')
    plt.plot(x,plty2,color = 'green')
    plt.show()


from django.core.mail import EmailMessage

TITLE = [
    ('Mr', 'Mr'),
    ('Mrs', 'Mrs'),
    ('Ms', 'Ms'),
    ('Dr', 'Dr'),
]

EXPERTISE = [
    ('UI/UX Design', 'UI/UX Design'),
    ('Product Design', 'Product Design'),
    ('AI Design', 'AI Design'),
]

MENTORSHIP_AREAS = [
    ('Career Advice', 'Career Advice'),
    ('Portfolio Review', 'Portfolio Review'),
    ('Interview Techniques', 'Interview Techniques'),
]

USER_TYPE = [('mentor', 'mentor'), ('member', 'member')]

MENTOR_STATUS = [('n/a', 'not applicable'), ('pending', 'pending'),
                 ('approved', 'approved'), ('denied', 'denied')]

class Util:

    @staticmethod
    def send_email(data):
        email = EmailMessage(
            subject=data['email_subject'],
            body=data['email_body'],
            to=(data['to_email'],))
        email.send()