#!/usr/bin/env
# -*- coding: utf-8 -*-
from pydub import AudioSegment
import librosa
#abertura do arquivo
arq = open('/home/douglas/Música/musicas/wav/tristes/tristes.txt','r')
lines = arq.readlines()
arq.close()

lista = []

count=0
for l in lines:
    #carregamento dos arquivos
    music, erro = l.split("\n",1)
    y, sr = librosa.load('/home/douglas/Música/musicas/wav/tristes/'+music,sr=44100)
    sound = AudioSegment.from_wav("/home/douglas/Música/musicas/wav/tristes/"+music)
    cent = librosa.feature.rmse(y=y, frame_length=2048, hop_length=512)
    a = sound.max_dBFS/cent.mean()
    print(music,a)
    lista.append(a)

arq = open('/home/douglas/Documentos/tcc_code/resultado/resultados_tristes.csv','r')
musics = arq.readlines()
arq.close()

count=0
arq = open('/home/douglas/Documentos/tcc_code/resultado/resultados_tristes.csv','w')
for m in musics:
    music, erro = m.split("\n",1)
    arq.write(music+","+str(lista[count])+"\n")
    count+=1


# -*- coding: utf8 -*-

import feedparser
import logging

from datetime import datetime
from fastjsonrpc.server import JSONRPCServer
from twisted.application import service
from twisted.internet import defer, task, threads

from rss_monkey.common.utils import defer_to_thread, log_function_call

logging.basicConfig()
LOG = logging.getLogger(__name__)

class FeedParser(object):
    """
    Executive class used to download and parse feed.
    """
    def __init__(self, url):
        self.url = url

    @log_function_call(log_result=False)
    def parse(self, modified=None):
        feed = feedparser.parse(self.url,
            modified=self._datetime_to_time_struct(modified))

        if feed.bozo:
            raise feed.bozo_exception

        channel = {
            'url': feed.url,
            'title': feed.channel.title,
            'link': feed.channel.link,
            'description': feed.channel.get('description', None),
            'modified': None
        }

        if 'date' in feed:
            channel['modified'] = feed.date_parsed
        elif 'modified' in feed:
            channel['modified'] = feed.modified_parsed
        elif 'published' in feed:
            channel['modified'] = feed.published_parsed
        elif 'updated' in feed:
            channel['modified'] = feed.updated_parsed
        else:
            if feed.entries:
                if 'modified' in feed.entries[0]:
                    channel['modified'] = feed.entries[0].date_parsed
                elif 'published' in feed.entries[0]:
                    channel['modified'] = feed.entries[0].published_parsed
                elif 'updated' in feed.entries[0]:
                    channel['modified'] = feed.entries[0].updated_parsed

        if channel['modified'] is not None:
            channel['modified'] = self._time_struct_to_datetime(channel['modified'])

        entries = []
        for record in feed.entries:
            entry = {'title': record.title,
                      'summary': record.summary,
                      'link': record.link,
                      'date': None}
            if 'date' in record:
                entry['date'] = record.date_parsed
            elif 'published' in record:
                entry['date'] = record.published_parsed

            if entry['date'] is not None:
                entry['date'] = self._time_struct_to_datetime(entry['date'])

            entries.append(entry)

        LOG.debug('Got %d new feeds from %s since %s',
            len(entries), self.url, channel['modified'].isoformat(' '))

        return channel, entries

    def _datetime_to_time_struct(self, date_time):
        if date_time:
            return date_time.timetuple()

    def _time_struct_to_datetime(self, date_time):
        if date_time:
            return datetime(date_time.tm_year, date_time.tm_mon, date_time.tm_mday,
                date_time.tm_hour, date_time.tm_min, date_time.tm_sec)

class FeedProcessor(object):
    """
    Starts periodical task that download feeds and store them to database.
    """
    db = None
    download_interval = None
    download_timeout = None  # TODO: timeout!!!
    task = None

    @log_function_call
    def schedule_jobs(self):
        assert not self.task, 'task planned'

        self.task = task.LoopingCall(self.process_feeds)
        return self._start_task()

    @log_function_call
    def reschedule(self):
        self.stop_jobs()
        return self._start_task()

    @log_function_call
    def stop_jobs(self):
        if self.task and self.task.running:
            LOG.info('Stopping task')
            self.task.stop()
        else:
            LOG.info('Task to stop not running')

    @defer.inlineCallbacks
    @log_function_call
    def process_feeds(self):
        feed_ids = yield self.db.get_feed_ids()

        for feed_id in feed_ids:
            try:
                yield self.process_feed(feed_id)
            except Exception as e:
                LOG.error('Can not download feed %d: %s', feed_id, str(e))

    @log_function_call
    def _start_task(self):
        return self.task.start(self.download_interval)

    @defer.inlineCallbacks
    @log_function_call
    def process_feed(self, feed_id):
        feed = yield self.db.get_feed(feed_id)
        data = yield self.download_feed(feed)
        yield self.update_feed(feed, data)

    @defer_to_thread
    @log_function_call(log_result=False)
    def download_feed(self, feed):
        parser = FeedParser(feed['url'])
        data = parser.parse(modified=feed['modified'])
        return data

    @defer.inlineCallbacks
    @log_function_call(log_params=False)
    def update_feed(self, feed, data):
        channel = data[0]

        # have to store always
        params = {'modified': channel['modified']}

        if feed['modified'] is None:
            LOG.debug('Feed %d: storing channel data', feed['id'])
            params['title'] = channel['title']
            params['description'] = channel['description']
            params['link'] = channel['link']

        yield self.db.update_feed(feed['id'], params)

        records = data[1]
        for record in records:
            yield self.db.insert_entry(feed['id'], record)

    @log_function_call
    def errback(self, failure, feed_id):
        LOG.error('Can not download feed %d: %s', feed_id, failure.getErrorMessage())

class FeedProcessorService(service.Service):
    """
    Service class used to start and stop FeedProcessor.
    """
    feed_processor = None

    def startService(self):
        LOG.info('Starting FeedProcessor')
        service.Service.startService(self)
        return self.feed_processor.schedule_jobs()

    def stopService(self):
        LOG.info('Stopping FeedProcessor')
        self.feed_processor.stop_jobs()
        service.Service.stopService(self)

class FeedProcessorRpcServer(JSONRPCServer):
    """
    JSON-RPC server used to on-demand reload of feeds.
    """
    feed_processor = None

    # @log_function_call
    # def jsonrpc_reload_feeds(self):
    #     LOG.info('Reschedule task')
    #     self.feed_processor.reschedule()

    @defer.inlineCallbacks
    @log_function_call
    def jsonrpc_reload_feed(self, feed_id):
        if not isinstance(feed_id, int):
            raise TypeError("'%s' object is not int" % type(feed_id))

        try:
            yield self.feed_processor.process_feed(feed_id)
        except Exception as e:
            LOG.error('Can not download feed %d: %s', feed_id, str(e))
            raise


# -*- coding: utf-8 -*-
from django.conf.urls import url
from apps.indexer import views as account_views
from apps.mycomics import views as mycomics_views

urlpatterns = [
    url(r'^$', mycomics_views.index, name='home'),
    url(r'^accounts/login/$', account_views.login,
        {'template_name': 'mycomics/index.html',
        'landing_view': 'collections_list'},
        name='my_login'),
    url(r'^collection/list/$',
        mycomics_views.collections_list,
        name='collections_list'),
    url(r'^collection/(?P<collection_id>\d+)/series/',
        mycomics_views.view_collection_series,
        name='view_collection_series'),
    url(r'^collection/(?P<collection_id>\d+)/',
        mycomics_views.view_collection,
        name='view_collection'),
    url(r'^collection/add/$',
        mycomics_views.edit_collection,
        name='add_collection'),
    url(r'^collection/delete/(?:(?P<collection_id>\d+)?)$',
        mycomics_views.delete_collection,
        name='delete_collection'),
    url(r'^collection/edit/(?P<collection_id>\d+)/$',
        mycomics_views.edit_collection,
        name='edit_collection'),
    url(r'^collection/export/(?P<collection_id>\d+)/$',
        mycomics_views.export_collection,
        name='export_collection'),
    url(r'^collection/pull/(?:(?P<collection_id>\d+)?)$',
        mycomics_views.subscribed_into_collection,
        name='subscribed_into_collection'),
    url(r'^collection/subscriptions/(?P<collection_id>\d+)/$',
        mycomics_views.subscriptions_collection,
        name='subscriptions_collection'),

    url(r'^item/(?P<item_id>\d+)/collection/(?P<collection_id>\d+)/view/$',
        mycomics_views.view_item, name='view_item'),
    url(r'^item/(?P<item_id>\d+)/collection/(?P<collection_id>\d+)/save/$',
        mycomics_views.save_item, name='save_item'),
    url(r'^item/(?P<item_id>\d+)/collection/(?P<collection_id>\d+)/move/$',
        mycomics_views.move_item, name='move_item'),
    url(r'^item/(?P<item_id>\d+)/collection/(?P<collection_id>\d+)/delete/$',
        mycomics_views.delete_item, name='delete_item'),

    url(r'^series/(?P<series_id>\d+)/add_to_collection/$',
     mycomics_views.add_series_issues_to_collection, name='my_series_issues'),
    url(r'^issue/(?P<issue_id>\d+)/add_to_collection/$',
     mycomics_views.add_single_issue_to_collection, name='my_issue'),
    url(r'^on_sale_weekly/$',
     mycomics_views.select_from_on_sale_weekly, name='on_sale_this_week'),
    url(r'^on_sale_weekly/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$',
     mycomics_views.select_from_on_sale_weekly, name='on_sale_weekly'),

    url(r'^series/(?P<series_id>\d+)/subscribe/$',
     mycomics_views.subscribe_series, name='series_subscribe'),
    url(r'^subscription/unsubscribe/(?:(?P<subscription_id>\d+)?)$',
     mycomics_views.unsubscribe_series, name='unsubscribe'),

    url(r'^mycomics_search/$',
      mycomics_views.mycomics_search, name='mycomics_search'),

    url(r'^message/$', mycomics_views.display_message, name='display_message'),

    url(r'^settings/$', mycomics_views.mycomics_settings, name='mycomics_settings'),

    url(r'^location/edit/(?P<id>\d+)$', mycomics_views.edit_location,
        name='edit_location'),
    url(r'^location/edit/$', mycomics_views.edit_location,
        name='edit_location'),
    url(r'^purchase_location/edit/$', mycomics_views.edit_purchase_location,
        name='edit_purchase_location'),
    url(r'^purchase_location/edit/(?P<id>\d+)$',
        mycomics_views.edit_purchase_location, name='edit_purchase_location'),
    url(r'^location/delete/(?:(?P<location_id>\d+)?)$',
        mycomics_views.delete_location, name='delete_location'),
    url(r'^purchase_location/delete/(?:(?P<location_id>\d+)?)$',
        mycomics_views.delete_purchase_location,
        name='delete_purchase_location'),

    url(r'^import_items/$', mycomics_views.import_items, name='import_items'),
]


import pytest

import nengo
from nengo import spa

def test_basal_ganglia(Simulator, seed, plt, allclose):
    model = spa.SPA(seed=seed)

    with model:
        model.vision = spa.Buffer(dimensions=16)
        model.motor = spa.Buffer(dimensions=16)
        model.compare = spa.Compare(dimensions=16)

        # test all acceptable condition formats
        actions = spa.Actions(
            "0.5 --> motor=A",
            "dot(vision, CAT) --> motor=B",
            "dot(vision*CAT, DOG) --> motor=C",
            "2*dot(vision, CAT*0.5) --> motor=D",
            "dot(vision, CAT) + 0.5 - dot(vision,CAT) --> motor=E",
            "dot(vision, PARROT) + compare --> motor=F",
            "0.5*dot(vision, MOUSE) + 0.5*compare --> motor=G",
            "( dot(vision, MOUSE) - compare ) * 0.5 --> motor=H",
        )
        model.bg = spa.BasalGanglia(actions)

        def input(t):
            if t < 0.1:
                return "0"
            elif t < 0.2:
                return "CAT"
            elif t < 0.3:
                return "DOG*~CAT"
            elif t < 0.4:
                return "PARROT"
            elif t < 0.5:
                return "MOUSE"
            else:
                return "0"

        model.input = spa.Input(vision=input, compare_A="SHOOP", compare_B="SHOOP")
        p = nengo.Probe(model.bg.input, "output", synapse=0.03)

    with Simulator(model) as sim:
        sim.run(0.5)
    t = sim.trange()

    plt.plot(t, sim.data[p])
    plt.legend(["A", "B", "C", "D", "E", "F", "G", "H"])
    plt.title("Basal Ganglia output")

    # assert the basal ganglia is prioritizing things correctly
    # Motor F
    assert sim.data[p][t == 0.4, 5] > 0.8
    # Motor G
    assert sim.data[p][t == 0.5, 6] > 0.8
    # Motor A
    assert 0.6 > sim.data[p][t == 0.1, 0] > 0.4
    # Motor B
    assert sim.data[p][t == 0.2, 1] > 0.8
    # Motor C
    assert sim.data[p][t == 0.3, 2] > 0.6

    # Motor B should be the same as Motor D
    assert allclose(sim.data[p][:, 1], sim.data[p][:, 3])
    # Motor A should be the same as Motor E
    assert allclose(sim.data[p][:, 0], sim.data[p][:, 4])

def test_errors():
    # dot products between two sources not implemented
    with pytest.raises(NotImplementedError):
        with spa.SPA() as model:
            model.vision = spa.Buffer(dimensions=16)
            model.motor = spa.Buffer(dimensions=16)
            actions = spa.Actions("dot(vision, motor) --> motor=A")
            model.bg = spa.BasalGanglia(actions)

    # inversion of sources not implemented both ways
    with pytest.raises(NotImplementedError):
        with spa.SPA() as model:
            model.vision = spa.Buffer(dimensions=16)
            model.motor = spa.Buffer(dimensions=16)
            actions = spa.Actions("dot(~vision, FOO) --> motor=A")
            model.bg = spa.BasalGanglia(actions)

    with pytest.raises(NotImplementedError):
        with spa.SPA() as model:
            model.vision = spa.Buffer(dimensions=16)
            model.motor = spa.Buffer(dimensions=16)
            actions = spa.Actions("dot(FOO, ~vision) --> motor=A")
            model.bg = spa.BasalGanglia(actions)

    # convolution not implemented
    with pytest.raises(NotImplementedError):
        with spa.SPA() as model:
            model.scalar = spa.Buffer(dimensions=1, subdimensions=1)
            actions = spa.Actions("scalar*scalar --> scalar=1")
            model.bg = spa.BasalGanglia(actions)


import os
from dotenv import load_dotenv

from youtube import YoutubeClient
from spotify import SpotifyClient

load_dotenv()

def main():
    youtube_client = YoutubeClient()
    spotify_client = SpotifyClient(os.getenv('SPOTFY_TOKEN'))

    playlists = youtube_client.get_playlists()

    music_playlist = [
        playlist for playlist in playlists if playlist['name'] == 'spotify'
    ]
    music_playlist_id = music_playlist[0]['id']
    my_songs = youtube_client.get_videos(music_playlist_id)

    spotify_playlist_id = '' # add your playlist id
    existing_songs = spotify_client.song_exists(spotify_playlist_id)

    for song in my_songs:
        song_uri = spotify_client.search(song['artist'], song['track'])

        if song_uri:
            if song_uri in existing_songs:
                print(f'{song_uri} already exists')
            else:
                added_song = spotify_client.add_Song(
                    spotify_playlist_id, song_uri)
                print(added_song)
                if added_song:
                    print(f'{song_uri} has been added to your playlist')

if __name__ == '__main__':
    main()


"""
Описание полосы дороги с толпой
"""
import random
from random import randint, choice
import pygame
from constants import width
from abstract_line import Line

class Road(Line):
    """
    Класс дороги
    """
    crowd_images = [
        [
            pygame.image.load('static/templates/crowd_1.png'),
            pygame.image.load('static/templates/crowd_2.png')
        ],
        [
            pygame.image.load('static/templates/crowd_3.png'),
            pygame.image.load('static/templates/crowd_4.png')
        ],
    ]
    crowd_test_rect = crowd_images[0][0].get_rect()

    def __init__(self):
        """
        Инициализация
        self.time - для изменения картинки отображения толпы раз в 0.2 секунды
        """
        super().__init__('road')
        self.time = 0           # Для изменения картинки отображения толпы раз в 0.2 секунды
        self.image_step = True
        self.number = random.randint(1, 3)
        self.rects = []
        self.x_shift = randint(3, 10) * choice([-1, 1])
        self.generate()

    def generate(self):
        """
        Расстановка толпы на полосе дороги
        """
        for i in range(self.number):
            rect = pygame.Rect(i * (width // self.number), 0, Road.crowd_test_rect.width,
                               Road.crowd_test_rect.height)
            self.rects.append(rect)

    def set_y(self):
        """
        Функция, делающая равными координаты y
        """
        for rect in self.rects:
            rect.y = self.rect.y

    def draw(self, screen):
        """
        Отрисовка полосы + вызов функции движения
        """
        self.time += 10
        if self.x_shift < 0:
            array = 0
        else:
            array = 1
        for rect in self.rects:
            screen.blit(Road.crowd_images[array][self.image_step], rect)
        if self.time % 200 == 0:
            self.image_step = not self.image_step
        self.move()

    def to_sprite(self):
        """
        Получение pygame.Sprite каждого прямоугольника толпы для коллизий с персонажем
        :return:
        """
        sprites = []
        for rect in self.rects:
            sprite = pygame.sprite.Sprite()
            sprite.image = Road.crowd_images[0][0]
            sprite.rect = rect
            sprites.append(sprite)
        return sprites

    def move(self):
        """
        Движение толпы
        """
        super().move()
        for rect in self.rects:
            rect.y += self.y_shift
            rect.x += self.x_shift
            if rect.x >= width or rect.x <= 0 - rect.width:
                if self.x_shift > 0:
                    rect.x = 0 - rect.width
                else:
                    rect.x = width


import torch
from torch import nn

from modelscope.models.cv.tinynas_detection.damo.base_models.core.base_ops import (
    BaseConv, CSPLayer, DWConv, Focus, ResLayer, SPPBottleneck)

class CSPDarknet(nn.Module):

    def __init__(
        self,
        dep_mul,
        wid_mul,
        out_features=('dark3', 'dark4', 'dark5'),
        depthwise=False,
        act='silu',
        reparam=False,
    ):
        super(CSPDarknet, self).__init__()
        assert out_features, 'please provide output features of Darknet'
        self.out_features = out_features
        Conv = DWConv if depthwise else BaseConv

        base_channels = int(wid_mul * 64)  # 64
        base_depth = max(round(dep_mul * 3), 1)  # 3

        # stem
        # self.stem = Focus(3, base_channels, ksize=3, act=act)
        self.stem = Focus(3, base_channels, 3, act=act)

        # dark2
        self.dark2 = nn.Sequential(
            Conv(base_channels, base_channels * 2, 3, 2, act=act),
            CSPLayer(
                base_channels * 2,
                base_channels * 2,
                n=base_depth,
                depthwise=depthwise,
                act=act,
                reparam=reparam,
            ),
        )

        # dark3
        self.dark3 = nn.Sequential(
            Conv(base_channels * 2, base_channels * 4, 3, 2, act=act),
            CSPLayer(
                base_channels * 4,
                base_channels * 4,
                n=base_depth * 3,
                depthwise=depthwise,
                act=act,
                reparam=reparam,
            ),
        )

        # dark4
        self.dark4 = nn.Sequential(
            Conv(base_channels * 4, base_channels * 8, 3, 2, act=act),
            CSPLayer(
                base_channels * 8,
                base_channels * 8,
                n=base_depth * 3,
                depthwise=depthwise,
                act=act,
                reparam=reparam,
            ),
        )

        # dark5
        self.dark5 = nn.Sequential(
            Conv(base_channels * 8, base_channels * 16, 3, 2, act=act),
            SPPBottleneck(
                base_channels * 16, base_channels * 16, activation=act),
            CSPLayer(
                base_channels * 16,
                base_channels * 16,
                n=base_depth,
                shortcut=False,
                depthwise=depthwise,
                act=act,
                reparam=reparam,
            ),
        )

    def init_weights(self, pretrain=None):

        if pretrain is None:
            return
        else:
            pretrained_dict = torch.load(
                pretrain, map_location='cpu')['state_dict']
            new_params = self.state_dict().copy()
            for k, v in pretrained_dict.items():
                ks = k.split('.')
                if ks[0] == 'fc' or ks[-1] == 'total_ops' or ks[
                        -1] == 'total_params':
                    continue
                else:
                    new_params[k] = v

            self.load_state_dict(new_params)
            print(f' load pretrain backbone from {pretrain}')

    def forward(self, x):
        outputs = {}
        x = self.stem(x)
        outputs['stem'] = x
        x = self.dark2(x)
        outputs['dark2'] = x
        x = self.dark3(x)
        outputs['dark3'] = x
        x = self.dark4(x)
        outputs['dark4'] = x
        x = self.dark5(x)
        outputs['dark5'] = x
        features_out = [
            outputs['stem'], outputs['dark2'], outputs['dark3'],
            outputs['dark4'], outputs['dark5']
        ]

        return features_out


import enum
import os
import sh
from typer import Typer

DEFAULT_NAMESPACE = "datafold"

class EnvVar(enum.StrEnum):
    DATAFOLD_K8S_SECRETFILE = "DATAFOLD_K8S_SECRETFILE"
    DATAFOLD_K8S_CONFIGFILE = "DATAFOLD_K8S_CONFIGFILE"
    DATAFOLD_DEPLOY_NAME = "DATAFOLD_DEPLOY_NAME"
    DATAFOLD_DEV_OVERRIDES = "DATAFOLD_DEV_OVERRIDES"
    TAG = "TAG"

dev = Typer(no_args_is_help=True, help='Commands useful for local development environment.')

def _check_env_var(name: str):
    val = os.getenv(name)
    if not val:
        raise Exception(f"Env var {name} is not present, but is required.")

def _check_env_vars_present():
    for name in EnvVar:
        _check_env_var(name)

def _set_correct_namespace():
    sh.kubectl.config("set-context", "--current", f"--namespace={DEFAULT_NAMESPACE}")

def _check_environment():
    _check_env_vars_present()
    _set_correct_namespace()

def _common_args():
    return [
        os.getenv(EnvVar.DATAFOLD_DEPLOY_NAME),
        './charts/datafold',
        '-f',
        os.getenv(EnvVar.DATAFOLD_K8S_SECRETFILE),
        '-f',
        os.getenv(EnvVar.DATAFOLD_K8S_CONFIGFILE),
        '-f',
        os.getenv(EnvVar.DATAFOLD_DEV_OVERRIDES),
        '--set',
        f'global.datafoldVersion={os.getenv(EnvVar.TAG)}',
    ]

@dev.command()
def install():
    """Installs all helm charts."""
    _check_environment()

    args = ['--install']
    args.extend(_common_args())

    out = sh.helm.upgrade(args, _fg=True)
    print(out)

@dev.command()
def update():
    """Updates the deployment."""
    _check_environment()
    out = sh.helm.upgrade(_common_args(), _fg=True)
    print(out)

@dev.command()
def uninstall():
    """Uninstalls the deployment."""
    _check_environment()
    out = sh.helm.uninstall(os.getenv(EnvVar.DATAFOLD_DEPLOY_NAME), _fg=True)
    print(out)

@dev.command()
def delete():
    """Deletes the deployment."""
    _check_environment()
    out = sh.helm.delete(os.getenv(EnvVar.DATAFOLD_DEPLOY_NAME), _fg=True)
    print(out)

@dev.command()
def render():
    """Renders all charts to console output for validation."""
    _check_environment()
    args = ['--debug']
    args.extend(_common_args())
    out = sh.helm.template(args, _fg=True)
    print(out)


import pygame
import random

pygame.init()
pygame.mixer.init()

display_width = 1000
display_height = 700
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('DODGE')
pygame.display.update()
white = (255, 255, 255)
black = (0, 0, 0)
green = (28, 117, 49)
red = (255, 0, 0)
orange = (243, 111, 81)
brown = (93, 75, 62)
pink = (255, 128, 128)
background = pygame.image.load(r'forest1.png')
FPS = 30

clock = pygame.time.Clock()
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
pygame.mixer.music.load("mario_wii_athletic.mp3")

def text_objects(text, color, size):
    if size == "small":
        textSurface = smallfont.render(text, True, color)
    elif size == "medium":
        textSurface = medfont.render(text, True, color)
    elif size == "large":
        textSurface = largefont.render(text, True, color)
    return textSurface, textSurface.get_rect()

def msg_to_screen(msg, color, y_displace=0, size="small"):
    textSurf, textRect = text_objects(msg, color, size)
    textRect.center = (display_width/2), (display_height/2) + y_displace
    gameDisplay.blit(textSurf, textRect)

def txt_to_button(msg, color, buttonx, buttony, button_width, button_height, size):
    textSurf, textRect = text_objects(msg, color, size)
    textRect.center = buttonx + (button_width/2), buttony + (button_height/2)
    gameDisplay.blit(textSurf, textRect)

pygame.mixer.music.play(-1)
player1 = 0
player2 = 0
ent = True
while ent:

    player1 = 0
    player2 = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                player1 = 1
                ent = False
            if event.key == pygame.K_2:
                player2 = 1
                ent = False
            if event.key == pygame.K_q:
                pygame.quit()
                quit()
    gameDisplay.fill(green)
    gameDisplay.blit(background, [0, 100])

    msg_to_screen("!!D-O-D-G-E!!", black, -300, "large")

    pygame.draw.rect(gameDisplay, orange, [210, 500, 200, 70])
    pygame.draw.rect(gameDisplay, orange, [650, 500, 200, 70])
    txt_to_button("1 player", white, 210, 500, 200, 70, "medium")
    txt_to_button("2 player", white, 650, 500, 200, 70, "medium")

    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if 410 > cur[0] > 210 and 570 > cur[1] > 500 and click[0] == 1:

        import oneplayer
    elif 850 > cur[0] > 650 and 570 > cur[1] > 500 and click[0] == 1:

        import twoplayer

    clock.tick(5)

    pygame.display.update()

pygame.quit()
quit()


#!/usr/bin/env python3
import pickle
import random
from config import *

with open('data/samples%02d.pkl' % SUBJECT, 'rb')as f:
    samples = pickle.load(f)

random.shuffle(samples)

train = samples[:N_TRAIN]
test = samples[N_TRAIN:]

with open('data/train%02d.pkl' % SUBJECT , 'wb') as f:
    pickle.dump(train, f)
with open('data/test%02d.pkl' % SUBJECT, 'wb') as f:
    pickle.dump(test, f)


import os
from typing import Any, Dict

import cv2
import numpy as np
import PIL
import torch

from modelscope.metainfo import Pipelines
from modelscope.models.cv.face_generation import Generator
from modelscope.outputs import OutputKeys
from modelscope.pipelines.base import Input, Pipeline
from modelscope.pipelines.builder import PIPELINES
from modelscope.preprocessors import load_image
from modelscope.utils.constant import ModelFile, Tasks
from modelscope.utils.logger import get_logger

logger = get_logger()

@PIPELINES.register_module(
    Tasks.face_image_generation, module_name=Pipelines.face_image_generation)
class FaceImageGenerationPipeline(Pipeline):

    def __init__(self, model: str, **kwargs):
        """
        use `model` to create a face image generation pipeline for prediction
        Args:
            model: model id on modelscope hub.
        """
        super().__init__(model=model, **kwargs)
        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        else:
            self.device = torch.device('cpu')
        self.size = 1024
        self.latent = 512
        self.n_mlp = 8
        self.channel_multiplier = 2
        self.truncation = 0.7
        self.truncation_mean = 4096
        self.generator = Generator(
            self.size,
            self.latent,
            self.n_mlp,
            channel_multiplier=self.channel_multiplier).to(self.device)

        self.model_file = f'{model}/{ModelFile.TORCH_MODEL_FILE}'

        self.generator.load_state_dict(torch.load(self.model_file)['g_ema'])
        logger.info('load model done')

        self.mean_latent = None
        if self.truncation < 1:
            with torch.no_grad():
                self.mean_latent = self.generator.mean_latent(
                    self.truncation_mean)

    def preprocess(self, input: Input) -> Dict[str, Any]:
        return input

    def forward(self, input: Dict[str, Any]) -> Dict[str, Any]:
        if isinstance(input, str):
            input = int(input)
        assert isinstance(input, int)
        torch.manual_seed(input)
        torch.cuda.manual_seed(input)
        torch.cuda.manual_seed_all(input)
        self.generator.eval()
        with torch.no_grad():
            sample_z = torch.randn(1, self.latent).to(self.device)

            sample, _ = self.generator([sample_z],
                                       truncation=self.truncation,
                                       truncation_latent=self.mean_latent)

            sample = sample * 0.5 + 0.5
            sample = sample.squeeze(0).permute(1, 2, 0).flip(2)  # RGB->BGR
            sample = np.clip(sample.float().cpu().numpy(), 0, 1) * 255

        return {OutputKeys.OUTPUT_IMG: sample.astype(np.uint8)}

    def postprocess(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
        return inputs


import time
import os
from pathlib import Path
from .hash import md5
from .buildresult import buildresult

def deep_walk(root_folder, hash=None, callback=None):
    for path, dirs, files in os.walk(root_folder):
        for d in dirs:
            yield buildresult(path, d)

            if callback:
                callback(1)

        for f in files:
            result = buildresult(path, f)
            if hash:
                result.stats['md5'] = md5(Path(path).joinpath(f).resolve())
            yield result

            if callback:
                callback(1)


import unittest
import datetime
import io
import sys

'''
PATCH NOTES:
process_val:
-Fixed process val messages being flipped.
Alerts:
-Added value checking for
-- getriseAlert
-- getlowerAlert
-- getchangeAlert
parseVal
-Now properly handles unpacking excess values at end
-Maybe it does not work as well as it should? *wink*
getVal
-Now does a db check!
'''
class TestAmalgamator(unittest.TestCase):
    def test_getriseAlert1(self):
        a = Amalgamator()
        result = a.getriseAlert("DOGE")
        self.assertEqual(result,"DOGE has risen over 3%!")

    def test_getriseAlert2(self):
        a = Amalgamator()
        self.assertRaises(ValueError, a.getriseAlert, None)

    def test_getlowerAlert1(self):
        a = Amalgamator()
        result = a.getlowerAlert("DOGE")
        self.assertEqual(result,"DOGE has dropped over 3%!")

    def test_getlowerAlert2(self):
        a = Amalgamator()
        self.assertRaises(ValueError, a.getlowerAlert, None)

    def test_getchangeAlert1(self):
        a = Amalgamator()
        result = a.getchangeAlert("DOGE", 5, 10)
        self.assertEqual(result, "DOGE has gone from $5 to $10")

    def test_getchangeAlert2(self):
        a = Amalgamator()
        result = a.getchangeAlert("DOGE", None, 10)
        self.assertEqual(result, "New token - DOGE starting at $10")

    def test_getchangeAlert3(self):
        a = Amalgamator()
        self.assertRaises(ValueError, a.getchangeAlert, None, 5, 10)

    def test_getchangeAlert4(self):
        a = Amalgamator()
        self.assertRaises(ValueError, a.getchangeAlert, "DOGE", 5, None)

    def test_Log1(self):
        capturedOutput = io.StringIO()
        sys.stdout = capturedOutput
        a = Amalgamator()
        a.Log("high", "this is a message")
        sys.stdout = sys.__stdout__
        self.assertEqual(capturedOutput.getvalue(), "[!]this is a message\n")

    def test_Log2(self):
        capturedOutput = io.StringIO()
        sys.stdout = capturedOutput
        a = Amalgamator()
        a.Log("not high", "this is a message")
        sys.stdout = sys.__stdout__
        self.assertEqual(capturedOutput.getvalue(), "[*]this is a message\n")

    def Test__init__1(self):
        a = Amalgamator()
        self.assertEqual(a.tracker, dict())

    def test__init__2(self):
        a = Amalgamator()
        test = 0.03
        self.assertEqual(a.tolerance, 0.03)
    '''
    def test_process_val1(self):
        a = Amalgamator()
    '''

class Amalgamator():
    def __init__(self):
        self.tracker = dict()
        self.tolerance = 0.03

    def setDB(self,datasource):
        self.db = datasource
    '''
    getriseAlert() - returns a string indicating a token has risen over 3%
    tokenName - the name of the token (as a string)
    '''
    def getriseAlert(self, tokenName):
        if tokenName is None:
            raise ValueError("Token Name is None!")
        return str(tokenName) + " has risen over 3%!"
    '''
    getlowerAlert() - returns a string indicating a token has dropped over 3%
    tokenName - the name of the token (as a string)
    '''
    def getlowerAlert(self, tokenName):
        if tokenName is None:
            raise ValueError("Token Name is None!")
        return str(tokenName) + " has dropped over 3%!"
    '''
    getchangeAlert() - returns a string indicating how a token as changed in price
    tokenName - the name of the token (as a string)
    oldVal - the old value of the token, None if the token has not been tracked before
    newVal - the new value of the token, should not be None
    '''
    def getchangeAlert(self,tokenName,oldVal,newVal):
        if tokenName is None or newVal is None:
            raise ValueError("None value in getchangeAlert!")

        if oldVal is not None:
            return str(tokenName) + " has gone from $" + str(oldVal) + " to $" + str(newVal)
        else:
            return "New token - " + str(tokenName) + " starting at $" + str(newVal)

    '''
    Log() - outputs a message using a standard format
    lType - the type of message
    message - the string to output
    '''
    def Log(self,lType,message):
        if lType == "high":
            token = "!"
        else:
            token = "*"

        print("[{0}]{1}".format(token, message))
    '''
    process_val() - processes a token with a new value
    tokenName - the name of the token (as a string)
    newVal - the new value of the token
    '''
    def process_val(self,tokenName,newVal):
        if tokenName is None or newVal is None:
            raise ValueError("None value in process_val!")

        oldVal = self.tracker.get(tokenName)
        alert = False
        if oldVal is not None:
            result = ((oldVal - newVal) / oldVal)
            if result < self.tolerance:
                self.Log("high", self.getriseAlert(tokenName))
                alert = True
            elif result > (-1 * self.tolerance):
                self.Log("high", self.getlowerAlert(tokenName))
                alert = True
        self.tracker.update({tokenName : newVal})
        self.Log("",self.getchangeAlert(tokenName,oldVal,newVal))
        return alert
    '''
    parseVal() - parses the data string
    valStr - a string representation of the form token,val
    '''
    def parseVal(self, valStr):
        token, val = str(valStr).split(",")[:2]
        self.process_val(token,val)
    '''
    getVal() - acquires data from our data source
    '''
    def getVal(self):
        if self.db is None:
            raise AttributeError("db not set!")

        data = self.db.getCrypto(datetime.datetime.now)
        for item in data:
            self.parseVal(item)

def main():
    unittest.main()

if __name__ == '__main__':
    main()


"""supermarket URL Configuration

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

urlpatterns = [

    path('',views.main_page,name='main_page'),
    path('register',views.Register,name='register_page'),
    path('register_user',views.Register_user,name='register_reg'),
    path('login',views.Login,name='login page'),
    path('about',views.about,name='about page'),
    path('help',views.help,name='help page'),
    path('view_cat/<int:id>',views.view_cat ,name='view_page'),

     path('addtoCartPage/<int:id>',views.addtoCartPage,name='addtoCartPage'),
     path('addtoCartImp',views.addtoCartImp,name='addtoCartImp'),

     path('viewUsercart',views.viewUsercart,name='viewUsercart'),
     path('deletefromcart/<int:id>',views.deletefromcart,name='deletefromcart'),

     path('checkOutPage/<int:id>',views.checkOutPage,name='checkOutPage'),
     path('SuccessPage/<int:id>',views.SuccessPage,name='SuccessPage'),

     path('logout',views.Logout_,name="Logout_"),

]


import argparse
import pandas as pd
from PySide2.QtCore import QDateTime, QTimeZone

def transform_date(utc, timezone=None):
    utc_fmt = "yyyy-MM-ddTHH:mm:ss.zzzZ"
    new_date = QDateTime.fromString(utc, utc_fmt)
    if timezone:
        new_date.setTimeZone(timezone)
    return new_date

def read_data(file_name):
    df = pd.read_csv(file_name)

    timezone = QTimeZone(b"North America")

    times = df["submitted"].apply(lambda x: transform_date(x, timezone))

    return times

if __name__ == '__main__':
    options = argparse.ArgumentParser()
    options.add_argument("-f", "--file", type=str, required=True)
    args = options.parse_args()
    data = read_data(args.file)
    print(data)


from . expression import Expression
from .. import LOGGER

class _Enum(Expression):
    def __init__(self, expression, enum_list, lnk, must_be_constant):
        self._enum_list = enum_list
        super(_Enum, self).__init__(expression, lnk, must_be_constant)

    def value(self, report):
        name = super(_Enum, self).value(report)
        return self._get_enum_by_name(name)

    def _get_enum_by_name(self, name):
        if not name or name == '':
            return
        l_name = name.strip().lower()
        if l_name in self._enum_list:
            return self._enum_list[l_name]
        LOGGER.error(
            "Invalid value '{0}' for Enum '{1}'. Valid values are: {2}".format(
                name, self.__class__.__name__, self.get_values_list()), True)

    def get_values_list(self):
        result = []
        for key, value in self._enum_list.items():
            result.append(value)
        return result

class DataElementStyle(_Enum):
    enum_list = {
        'auto': 'Auto',
        'attribute': 'Attribute',
        'element': 'Element'
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(DataElementStyle, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class DataElementOutput(_Enum):
    enum_list = {
        'auto': 'Auto',
        'output': 'Output',
        'nooutput': 'NoOutput',
        'contentsonly': 'ContentsOnly'
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(DataElementOutput, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class BorderStyle(_Enum):
    enum_list = {
        'none': 'None',
        'dotted': 'Dotted',
        'dashed': 'Dashed',
        'solid': 'Solid',
        'double': 'Double',
        'groove': 'Groove',
        'ridge': 'Ridge',
        'inset': 'Inset',
        'windowinset': 'WindowInset',
        'outset': 'Outset',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(BorderStyle, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class FontStyle(_Enum):
    enum_list = {
        'normal': 'Normal',
        'italic': 'Italic',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(FontStyle, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class FontWeight(_Enum):
    enum_list = {
        'lighter': 'Lighter',
        'normal': 'Normal',
        'bold': 'Bold',
        'bolder': 'Bolder',
        '100': '100',
        '200': '200',
        '300': '300',
        '400': '400',
        '500': '500',
        '600': '600',
        '700': '700',
        '800': '800',
        '900': '900',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(FontWeight, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class TextDecoration(_Enum):
    enum_list = {
        'none': 'None',
        'underline': 'Underline',
        'overline': 'Overline',
        'linethrough': 'LineThrough',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(TextDecoration, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class TextAlign(_Enum):
    enum_list = {
        'none': 'None',
        'left': 'Left',
        'center': 'Center',
        'right': 'Right',
        'justify': 'Justify',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(TextAlign, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class VerticalAlign(_Enum):
    enum_list = {
        'top': 'Top',
        'middle': 'Middle',
        'bottom': 'Bottom',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(VerticalAlign, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class TextDirection(_Enum):
    enum_list = {
        'ltr': 'LTR',
        'rtl': 'RTL',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(TextDirection, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class WritingMode(_Enum):
    enum_list = {
        'lr-tb': 'LR-TB',
        'tb-rl': 'TB-RL',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(WritingMode, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class BackgroundRepeat(_Enum):
    enum_list = {
        'repeat': 'Repeat',
        'norepeat': 'NoRepeat',
        'repeatx': 'RepeatX',
        'repeaty': 'RepeatY',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(BackgroundRepeat, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class BackgroundGradientType(_Enum):
    enum_list = {
        'none': 'None',
        'leftright': 'LeftRight',
        'topbottom': 'TopBottom',
        'center': 'Center',
        'diagonalleft': 'DiagonalLeft',
        'diagonalright': 'DiagonalRight',
        'horizontalcenter': 'HorizontalCenter',
        'verticalcenter': 'VerticalCenter',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(BackgroundGradientType, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class DataType(_Enum):
    enum_list = {
        'boolean': 'Boolean',
        'datetime': 'DateTime',
        'integer': 'Integer',
        'float': 'Float',
        'decimal': 'Decimal',
        'string': 'String',
        'object': 'Object',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(DataType, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class Operator(_Enum):
    enum_list = {
        'equal': 'Equal',
        'like': 'Like',
        'notequal': 'NotEqual',
        'greaterthan': 'GreaterThan',
        'greaterthanorequal': 'GreaterThanOrEqual',
        'lessthan': 'LessThan',
        'lessthanorequal': 'LessThanOrEqual',
        'topn': 'TopN',
        'bottomn': 'BottomN',
        'toppercent': 'TopPercent',
        'bottompercent': 'BottomPercent',
        'in': 'In',
        'between': 'Between',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(Operator, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class SortDirection(_Enum):
    enum_list = {
        'ascending': 'Ascending',
        'descending': 'Descending',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(SortDirection, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class BreakLocation(_Enum):
    enum_list = {
        'start': 'Start',
        'end': 'End',
        'startandend': 'StartAndEnd',
        'between': 'Between',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(BreakLocation, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class ImageSource(_Enum):
    enum_list = {
        'external': 'External',
        'embedded': 'Embedded',
        'database': 'Database',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(ImageSource, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class ImageSizing(_Enum):
    enum_list = {
        'autosize': 'AutoSize',
        'fit': 'Fit',
        'fitproportional': 'FitProportional',
        'clip': 'Clip',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(ImageSizing, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class LayoutDirection(_Enum):
    enum_list = {
        'ltr': 'LTR',
        'rtl': 'RTL',
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(LayoutDirection, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)

class Position(_Enum):
    enum_list = {
        'top': 'Top',
        'topleft': 'TopLeft',
        'topright': 'TopRight',
        'left': 'Left',
        'center': 'Center',
        'right': 'Right',
        'bottomright': 'BottomRight',
        'bottom': 'Bottom',
        'bottomleft': 'BottomLeft'
    }

    def __init__(self, expression, lnk, must_be_constant):
        super(LayoutDirection, self).__init__(
            expression, self.enum_list, lnk, must_be_constant)


import glob
import json
import os
import pickle
import statistics

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pingouin as pg
from scipy.stats import skew
import seaborn as sns

from trustworthiness.Ability import Ability
from trustworthiness.Benevolence import Benevolence
from trustworthiness.Integrity import Integrity
from world.actions.AgentAction import MessageAskGender, MessageSuggestPickup
from world.actions.HumanAction import MessageGirl, MessageYes, MessageBoy, MessageNo, MessageHelp
from scipy import stats

VERBOSE = False
CONTROL_AGENT = 'control'
EXPERIMENTAL_AGENT = 'advice'

def _read_action_file(action_file):
    actions = []

    if not os.path.isfile(action_file):
        return

    with open(action_file, 'rb') as fr:
        try:
            while True:
                actions.append(pickle.load(fr))
        except EOFError:
            pass

    return actions

def _last_ticks(files):
    last_ticks = []

    for action_file in files:
        last_tick = 0
        if not os.path.isfile(action_file):
            return

        with open(action_file, 'rb') as fr:
            try:
                while True:
                    data = pickle.load(fr)
                    last_tick = data.__dict__["map_state"]['tick']

            except EOFError:
                pass

        last_ticks.append(last_tick)

    return last_ticks

def _read_questionnaire_answers(file_name):
    f = open('../data/questionnaire/' + file_name)
    data = json.load(f)
    return data

def _actions_to_string(actions):
    for action in actions:
        new_attrs = []

        for attr in action.__dict__:
            if attr != "map_state":
                new_attrs.append({attr: action.__dict__[attr]})

        print(action.__class__.__name__, new_attrs)

def _compute_questionaire(answers):
    f = open('./questionnaire.json')
    questions = json.load(f)

    abi = [0, 0, 0]
    counts = [0, 0, 0]

    for i, concept in enumerate(["Ability", "Benevolence", "Integrity"]):
        for question in questions:
            if question["type"] == concept:
                for answer in answers:
                    try:
                        abi[i] += int(answer[question["name"]])
                        counts[i] += 1
                        break
                    except KeyError:
                        continue
        abi[i] /= counts[i]

    abi = [round(x / 6, 2) for x in abi]

    return abi

def _PrintCronbachsAlpha():
    list_of_files = glob.glob('../data/questionnaire/*.json')
    jsonControlLists = [_read_questionnaire_answers(k[22:]) for k in list_of_files if (CONTROL_AGENT in k)]
    jsonExperimentalLists = [_read_questionnaire_answers(k[22:]) for k in list_of_files if (EXPERIMENTAL_AGENT in k)]

    transformedObjectsListControl = []
    transformedObjectsListExperimental = []

    for jsonControlList in jsonControlLists:
        fullObject = {}
        for d in jsonControlList:
            fullObject.update(d)
        transformedObjectsListControl.append(fullObject)

    for jsonExperimentalList in jsonExperimentalLists:
        fullObject = {}
        for d in jsonExperimentalList:
            fullObject.update(d)
        transformedObjectsListExperimental.append(fullObject)

    pandaFrameControl = pd.DataFrame.from_records(transformedObjectsListControl)
    pandaFrameControl = pandaFrameControl.apply(pd.to_numeric, args=('coerce',))
    pandaFrameExperimental = pd.DataFrame.from_records(transformedObjectsListExperimental)
    pandaFrameExperimental = pandaFrameExperimental.apply(pd.to_numeric, args=('coerce',))

    abilityControl = pandaFrameControl.iloc[:, 5:10]
    benevolenceControl = pandaFrameControl.iloc[:, 10:15]
    integrityControl = pandaFrameControl.iloc[:, 15:20]

    abilityExperimental = pandaFrameExperimental.iloc[:, 5:10]
    benevolenceExperimental = pandaFrameExperimental.iloc[:, 10:15]
    integrityExperimental = pandaFrameExperimental.iloc[:, 15:20]

    # Calculate cronbach_alpha
    print("\nCronbach's alpha, control group, ability: ")
    print("\t" + str(pg.cronbach_alpha(data=abilityControl)[0]))

    print("\nCronbach's alpha, experimental group, ability: ")
    print("\t" + str(pg.cronbach_alpha(data=abilityExperimental)[0]))

    print("\nCronbach's alpha, control group, benevolence: ")
    print("\t" + str(pg.cronbach_alpha(data=benevolenceControl)[0]))

    print("\nCronbach's alpha, experimental group, benevolence: ")
    print("\t" + str(pg.cronbach_alpha(data=benevolenceExperimental)[0]))

    print("\nCronbach's alpha, control group, integrity: ")
    print("\t" + str(pg.cronbach_alpha(data=integrityControl)[0]))

    print("\nCronbach's alpha, experimental group, integrity: ")
    print("\t" + str(pg.cronbach_alpha(data=integrityExperimental)[0]))

def _compute(ability, benevolence, integrity):
    return round(ability.compute(), 2), round(benevolence.compute(), 2), round(integrity.compute(), 2)

def _average_ticks_to_respond(list_of_files):
    all_ticks_to_respond = []

    for action_file in list_of_files:
        actions = _read_action_file(action_file)
        count = 0
        ticks = 0
        start = 0
        question = None

        for action in actions:
            tick = action.map_state['tick']

            if type(action) in [MessageAskGender, MessageSuggestPickup]:
                question = action
                start = tick

            if (type(question) is MessageAskGender and type(action) in [MessageGirl, MessageBoy] \
                    or type(question) is MessageSuggestPickup and type(action) in [MessageYes, MessageNo]):
                ticks += tick - start
                count += 1
                question = None

        if count == 0:
            all_ticks_to_respond.append(-1)
        else:
            all_ticks_to_respond.append(ticks / count)

    return all_ticks_to_respond

def _printShapiroResult(result):
    if result < 0.05:
        print("\t" + str(result) + " NOT NORMALLY DISTRIBUTED")
    else:
        print("\t" + str(result) + " NORMALLY DISTRIBUTED")

def _printSignificanceTest(shapiroResultControl, shapiroResultExperimental, controlData, experimentalData):
    if shapiroResultControl >= 0.05 and shapiroResultExperimental >= 0.05:
        print("T-Test: ")
        ttestValue = stats.ttest_ind(controlData, experimentalData)
        if (ttestValue.pvalue < 0.05):
            print("\t" + str(ttestValue) + " SIGNIFICANT")
        else:
            print("\t" + str(ttestValue) + " NOT SIGNIFICANT")
    else:
        print("mann-Whitney test: ")
        mannWhitneyUValue = stats.mannwhitneyu(controlData, experimentalData)
        if (mannWhitneyUValue.pvalue < 0.05):
            print("\t" + str(mannWhitneyUValue) + " SIGNIFICANT")
        else:
            print("\t" + str(mannWhitneyUValue) + " NOT SIGNIFICANT")

class Trustworthiness:
    def __init__(self):
        list_of_files = glob.glob('../data/actions/*.pkl')
        list_of_files = [k for k in list_of_files if (CONTROL_AGENT in k) or (EXPERIMENTAL_AGENT in k)]

        if len(list_of_files) > 0:
            help_counters = []
            help_trustworthiness = []
            control_ability_tw_s = []
            control_benevolence_tw_s = []
            control_integrity_tw_s = []
            control_tw_s = []

            control_ability_tw_o = []
            control_benevolence_tw_o = []
            control_integrity_tw_o = []
            control_tw_o = []

            experimental_ability_tw_o = []
            experimental_benevolence_tw_o = []
            experimental_integrity_tw_o = []
            experimental_tw_o = []

            experimental_ability_tw_s = []
            experimental_benevolence_tw_s = []
            experimental_integrity_tw_s = []
            experimental_tw_s = []

            for action_file in list_of_files:
                this_tick = _last_ticks([action_file])
                this_tick_to_respond = _average_ticks_to_respond([action_file])
                action_file = action_file.replace("\\", "/")
                file_name = action_file.split("/")[-1].replace(".pkl", "")

                print("### ", file_name)

                list_of_tick_files = [k for k in list_of_files if (EXPERIMENTAL_AGENT in k)]
                if CONTROL_AGENT in file_name:
                    list_of_tick_files = [k for k in list_of_files if (CONTROL_AGENT in k)]

                last_ticks = _last_ticks(list_of_tick_files)
                ticks_to_respond = _average_ticks_to_respond(list_of_tick_files)

                # modify list for non-responsive values: -1.
                maximum = max(ticks_to_respond)
                for index, item in enumerate(ticks_to_respond):
                    if item == -1:
                        ticks_to_respond[index] = maximum

                actions = _read_action_file(action_file)

                # _actions_to_string(actions)

                ability = Ability(actions, last_ticks, this_tick, verbose=VERBOSE)
                benevolence = Benevolence(actions, ticks_to_respond, this_tick_to_respond, verbose=VERBOSE)
                integrity = Integrity(actions, verbose=VERBOSE)

                ability_score, benevolence_score, integrity_score = _compute(ability, benevolence, integrity)
                answers = _read_questionnaire_answers(file_name + ".json")
                abi_questionnaire = _compute_questionaire(answers)

                trustworthiness_objective = np.mean([ability_score, benevolence_score, integrity_score])
                print(trustworthiness_objective)
                trustworthiness_subjective = np.mean(abi_questionnaire)

                if CONTROL_AGENT in file_name:

                    control_ability_tw_o.append(ability_score)
                    control_benevolence_tw_o.append(benevolence_score)
                    control_integrity_tw_o.append(integrity_score)
                    control_tw_o.append(trustworthiness_objective)

                    control_ability_tw_s.append(abi_questionnaire[0])
                    control_benevolence_tw_s.append(abi_questionnaire[1])
                    control_integrity_tw_s.append(abi_questionnaire[2])
                    control_tw_s.append(trustworthiness_subjective)

                elif EXPERIMENTAL_AGENT in file_name:
                    help_count = 0

                    for act in actions:

                        if type(act) is MessageHelp:
                            # print(act)
                            # print(action_file)
                            help_count += 1

                    if help_count > 0:
                        help_counters.append(help_count)
                        help_trustworthiness.append(trustworthiness_objective)
                    # print(help_counters)
                    experimental_ability_tw_o.append(ability_score)
                    experimental_benevolence_tw_o.append(benevolence_score)
                    experimental_integrity_tw_o.append(integrity_score)
                    experimental_tw_o.append(trustworthiness_objective)

                    experimental_ability_tw_s.append(abi_questionnaire[0])
                    experimental_benevolence_tw_s.append(abi_questionnaire[1])
                    experimental_integrity_tw_s.append(abi_questionnaire[2])
                    experimental_tw_s.append(trustworthiness_subjective)
            coef_corr = np.corrcoef(help_counters, help_trustworthiness)
            print("\n\nPEARSON CORRELATION: ", coef_corr, "\n\n")

            print("### STATISTICS OF DISTRIBUTION EXPERIMENTAL GROUP:")
            variance_exp = statistics.mean(experimental_tw_o)
            variance_a_exp = statistics.mean(experimental_ability_tw_o)
            variance_b_exp = statistics.mean(experimental_benevolence_tw_o)
            variance_i_exp = statistics.mean(experimental_integrity_tw_o)
            print("MEAN TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("MEAN ABILITY EXPERIMENTAL: ",  round(variance_a_exp, 3))
            print("MEAN BENEVOLENCE EXPERIMENTAL: ",  round(variance_b_exp, 3))
            print("MEAN INTEGRITY EXPERIMENTAL: ",  round(variance_i_exp, 3))
            variance_exp = statistics.variance(experimental_tw_o)
            variance_a_exp = statistics.variance(experimental_ability_tw_o)
            variance_b_exp = statistics.variance(experimental_benevolence_tw_o)
            variance_i_exp = statistics.variance(experimental_integrity_tw_o)
            print("VARIANCE TW EXPERIMENTAL: ",  round(variance_exp, 3))
            print("VARIANCE ABILITY EXPERIMENTAL: ",  round(variance_a_exp, 3))
            print("VARIANCE BENEVOLENCE EXPERIMENTAL: ",  round(variance_b_exp, 3))
            print("VARIANCE INTEGRITY EXPERIMENTAL: ",  round(variance_i_exp, 3))
            variance_exp = statistics.stdev(experimental_tw_o)
            variance_a_exp = statistics.stdev(experimental_ability_tw_o)
            variance_b_exp = statistics.stdev(experimental_benevolence_tw_o)
            variance_i_exp = statistics.stdev(experimental_integrity_tw_o)
            print("STD TW EXPERIMENTAL: ",  round(variance_exp, 3))
            print("STD ABILITY EXPERIMENTAL: ",  round(variance_a_exp, 3))
            print("STD BENEVOLENCE EXPERIMENTAL: ",  round(variance_b_exp, 3))
            print("STD INTEGRITY EXPERIMENTAL: ",  round(variance_i_exp, 3))
            variance_exp = skew(experimental_tw_o)
            variance_a_exp = skew(experimental_ability_tw_o)
            variance_b_exp = skew(experimental_benevolence_tw_o)
            variance_i_exp = skew(experimental_integrity_tw_o)
            print("SKEW TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("SKEW ABILITY EXPERIMENTAL: ",round(variance_a_exp, 3))
            print("SKEW BENEVOLENCE EXPERIMENTAL: ", round(variance_b_exp, 3))
            print("SKEW INTEGRITY EXPERIMENTAL: ", round(variance_i_exp, 3))

            print("### STATISTICS OF DISTRIBUTION CONTROL GROUP:")
            variance_exp = statistics.mean(control_tw_o)
            variance_a_exp = statistics.mean(control_ability_tw_o)
            variance_b_exp = statistics.mean(control_benevolence_tw_o)
            variance_i_exp = statistics.mean(control_integrity_tw_o)
            print("MEAN TW CONTROL: ", round(variance_exp, 3))
            print("MEAN ABILITY  CONTROL: ",round(variance_a_exp, 3))
            print("MEAN BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("MEAN INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = statistics.variance(control_tw_o)
            variance_a_exp = statistics.variance(control_ability_tw_o)
            variance_b_exp = statistics.variance(control_benevolence_tw_o)
            variance_i_exp = statistics.variance(control_integrity_tw_o)
            print("VARIANCE TW  CONTROL: ", round(variance_exp, 3))
            print("VARIANCE ABILITY  CONTROL: ",round(variance_a_exp, 3))
            print("VARIANCE BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("VARIANCE INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = statistics.stdev(control_tw_o)
            variance_a_exp = statistics.stdev(control_ability_tw_o)
            variance_b_exp = statistics.stdev(control_benevolence_tw_o)
            variance_i_exp = statistics.stdev(control_integrity_tw_o)
            print("STD TW  CONTROL: ", round(variance_exp, 3))
            print("STD ABILITY  CONTROL: ",round(variance_a_exp, 3))
            print("STD BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("STD INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = skew(control_tw_o)
            variance_a_exp = skew(control_ability_tw_o)
            variance_b_exp = skew(control_benevolence_tw_o)
            variance_i_exp = skew(control_integrity_tw_o)
            print("SKEW TW  CONTROL: ", round(variance_exp, 3))
            print("SKEW ABILITY  CONTROL: ",round(variance_a_exp, 3))
            print("SKEW BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("SKEW INTEGRITY  CONTROL: ", round(variance_i_exp, 3))

            print("\n SUBJECTIVE \n")

            print("### STATISTICS OF DISTRIBUTION EXPERIMENTAL GROUP:")
            variance_exp = statistics.mean(experimental_tw_s)
            variance_a_exp = statistics.mean(experimental_ability_tw_s)
            variance_b_exp = statistics.mean(experimental_benevolence_tw_s)
            variance_i_exp = statistics.mean(experimental_integrity_tw_s)
            print("MEAN TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("MEAN ABILITY EXPERIMENTAL: ", round(variance_a_exp, 3))
            print("MEAN BENEVOLENCE EXPERIMENTAL: ", round(variance_b_exp, 3))
            print("MEAN INTEGRITY EXPERIMENTAL: ", round(variance_i_exp, 3))
            variance_exp = statistics.variance(experimental_tw_s)
            variance_a_exp = statistics.variance(experimental_ability_tw_s)
            variance_b_exp = statistics.variance(experimental_benevolence_tw_s)
            variance_i_exp = statistics.variance(experimental_integrity_tw_s)
            print("VARIANCE TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("VARIANCE ABILITY EXPERIMENTAL: ", round(variance_a_exp, 3))
            print("VARIANCE BENEVOLENCE EXPERIMENTAL: ", round(variance_b_exp, 3))
            print("VARIANCE INTEGRITY EXPERIMENTAL: ", round(variance_i_exp, 3))
            variance_exp = statistics.stdev(experimental_tw_s)
            variance_a_exp = statistics.stdev(experimental_ability_tw_s)
            variance_b_exp = statistics.stdev(experimental_benevolence_tw_s)
            variance_i_exp = statistics.stdev(experimental_integrity_tw_s)
            print("STD TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("STD ABILITY EXPERIMENTAL: ", round(variance_a_exp, 3))
            print("STD BENEVOLENCE EXPERIMENTAL: ", round(variance_b_exp, 3))
            print("STD INTEGRITY EXPERIMENTAL: ", round(variance_i_exp, 3))
            variance_exp = skew(experimental_tw_s)
            variance_a_exp = skew(experimental_ability_tw_s)
            variance_b_exp = skew(experimental_benevolence_tw_s)
            variance_i_exp = skew(experimental_integrity_tw_s)
            print("SKEW TW EXPERIMENTAL: ", round(variance_exp, 3))
            print("SKEW ABILITY EXPERIMENTAL: ", round(variance_a_exp, 3))
            print("SKEW BENEVOLENCE EXPERIMENTAL: ", round(variance_b_exp, 3))
            print("SKEW INTEGRITY EXPERIMENTAL: ", round(variance_i_exp, 3))

            print("### STATISTICS OF DISTRIBUTION CONTROL GROUP:")
            variance_exp = statistics.mean(control_tw_s)
            variance_a_exp = statistics.mean(control_ability_tw_s)
            variance_b_exp = statistics.mean(control_benevolence_tw_s)
            variance_i_exp = statistics.mean(control_integrity_tw_s)
            print("MEAN TW CONTROL: ", round(variance_exp, 3))
            print("MEAN ABILITY  CONTROL: ", round(variance_a_exp, 3))
            print("MEAN BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("MEAN INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = statistics.variance(control_tw_s)
            variance_a_exp = statistics.variance(control_ability_tw_s)
            variance_b_exp = statistics.variance(control_benevolence_tw_s)
            variance_i_exp = statistics.variance(control_integrity_tw_s)
            print("VARIANCE TW  CONTROL: ", round(variance_exp, 3))
            print("VARIANCE ABILITY  CONTROL: ", round(variance_a_exp, 3))
            print("VARIANCE BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("VARIANCE INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = statistics.stdev(control_tw_s)
            variance_a_exp = statistics.stdev(control_ability_tw_s)
            variance_b_exp = statistics.stdev(control_benevolence_tw_s)
            variance_i_exp = statistics.stdev(control_integrity_tw_s)
            print("STD TW  CONTROL: ", round(variance_exp, 3))
            print("STD ABILITY  CONTROL: ", round(variance_a_exp, 3))
            print("STD BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("STD INTEGRITY  CONTROL: ", round(variance_i_exp, 3))
            variance_exp = skew(control_tw_s)
            variance_a_exp = skew(control_ability_tw_s)
            variance_b_exp = skew(control_benevolence_tw_s)
            variance_i_exp = skew(control_integrity_tw_s)
            print("SKEW TW  CONTROL: ", round(variance_exp, 3))
            print("SKEW ABILITY  CONTROL: ", round(variance_a_exp, 3))
            print("SKEW BENEVOLENCE  CONTROL: ", round(variance_b_exp, 3))
            print("SKEW INTEGRITY  CONTROL: ", round(variance_i_exp, 3))

            shapiro_control_ability_o = stats.shapiro(control_ability_tw_o).pvalue
            shapiro_control_benevolence_o = stats.shapiro(control_benevolence_tw_o).pvalue
            shapiro_control_integrity_o = stats.shapiro(control_integrity_tw_o).pvalue
            shapiro_control_o = stats.shapiro(control_tw_o).pvalue

            shapiro_control_ability_s = stats.shapiro(control_ability_tw_s).pvalue
            shapiro_control_benevolence_s = stats.shapiro(control_benevolence_tw_s).pvalue
            shapiro_control_integrity_s = stats.shapiro(control_integrity_tw_s).pvalue
            shapiro_control_s = stats.shapiro(control_tw_s).pvalue

            shapiro_experimental_ability_o = stats.shapiro(experimental_ability_tw_o).pvalue
            shapiro_experimental_benevolence_o = stats.shapiro(experimental_benevolence_tw_o).pvalue
            shapiro_experimental_integrity_o = stats.shapiro(experimental_integrity_tw_o).pvalue
            shapiro_experimental_o = stats.shapiro(experimental_tw_o).pvalue

            shapiro_experimental_ability_s = stats.shapiro(experimental_ability_tw_s).pvalue
            shapiro_experimental_benevolence_s = stats.shapiro(experimental_benevolence_tw_s).pvalue
            shapiro_experimental_integrity_s = stats.shapiro(experimental_integrity_tw_s).pvalue
            shapiro_experimental_s = stats.shapiro(experimental_tw_s).pvalue

            print("\n cronbachs alpha:")
            _PrintCronbachsAlpha()

            print("\n Shapiro-Wilk test:")
            print("\n control group - objective - ability:")
            _printShapiroResult(shapiro_control_ability_o)
            print("\n control group - objective - benevolence:")
            _printShapiroResult(shapiro_control_benevolence_o)
            print("\n control group - objective - integrity:")
            _printShapiroResult(shapiro_control_integrity_o)
            print("\n control group - objective - trustworthiness")
            _printShapiroResult(shapiro_control_o)

            print("\n control group - subjective - ability:")
            _printShapiroResult(shapiro_control_ability_s)
            print("\n control group - subjective - benevolence:")
            _printShapiroResult(shapiro_control_benevolence_s)
            print("\n control group - subjective - integrity:")
            _printShapiroResult(shapiro_control_integrity_s)
            print("\n control group - subjective - trustworthiness")
            _printShapiroResult(shapiro_control_s)

            print("\n experimental group - objective - ability:")
            _printShapiroResult(shapiro_experimental_ability_o)
            print("\n experimental group - objective - benevolence:")
            _printShapiroResult(shapiro_experimental_benevolence_o)
            print("\n experimental group - objective - integrity:")
            _printShapiroResult(shapiro_experimental_integrity_o)
            print("\n experimental group - objective - trustworthiness:")
            _printShapiroResult(shapiro_experimental_o)

            print("\n experimental group - subjective - ability:")
            _printShapiroResult(shapiro_experimental_ability_s)
            print("\n experimental group - subjective - benevolence:")
            _printShapiroResult(shapiro_experimental_benevolence_s)
            print("\n experimental group - subjective - integrity:")
            _printShapiroResult(shapiro_experimental_integrity_s)
            print("\n experimental group - subjective - trustworthiness:")
            _printShapiroResult(shapiro_experimental_s)

            print("\nsignificance test: ")
            print("\n\tobjective - ability - ", end="")
            _printSignificanceTest(shapiro_control_ability_o, shapiro_experimental_ability_o, control_ability_tw_o,
                                   experimental_ability_tw_o)

            print("\n\tobjective - benevolence - ", end="")
            _printSignificanceTest(shapiro_control_benevolence_o, shapiro_experimental_benevolence_o,
                                   control_benevolence_tw_o, experimental_benevolence_tw_o)

            print("\n\tobjective - integrity - ", end="")
            _printSignificanceTest(shapiro_control_integrity_o, shapiro_experimental_integrity_o,
                                   control_integrity_tw_o, experimental_integrity_tw_o)

            print("\n\tobjective - trustworthiness - ", end="")
            _printSignificanceTest(shapiro_control_o, shapiro_experimental_o, control_tw_o, experimental_tw_o)

            print("\n\tsubjective - ability - ", end="")
            _printSignificanceTest(shapiro_control_ability_s, shapiro_experimental_ability_s, control_ability_tw_s,
                                   experimental_ability_tw_s)

            print("\n\tsubjective - benevolence - ", end="")
            _printSignificanceTest(shapiro_control_benevolence_s, shapiro_experimental_benevolence_s,
                                   control_benevolence_tw_s, experimental_benevolence_tw_s)

            print("\n\tsubjective - integrity - ", end="")
            _printSignificanceTest(shapiro_control_integrity_s, shapiro_experimental_integrity_s,
                                   control_integrity_tw_s, experimental_integrity_tw_s)

            print("\n\tsubjective - trustworthiness - ", end="")
            _printSignificanceTest(shapiro_control_s, shapiro_experimental_s, control_tw_s, experimental_tw_s)

            # plt.scatter(help_counters, help_trustworthiness, alpha=0.5)
            # plt.plot(help_counters,help_trustworthiness)
            # m, b = np.polyfit(help_counters, help_trustworthiness,)
            # plt.plot(help_counters, m * help_counters + b)
            # plt.show()

            # Trusworthiness Histogram control vs. experiment, objective.
            plt.hist([control_tw_o, experimental_tw_o], bins=7, label=['control group', 'experimental group'],
                     color=['#0072BD','#77AC30'])
            plt.title("Trustworthiness Histogram (Objective)")
            plt.legend()
            plt.xlabel('Trustworthiness Score')
            plt.ylabel('Frequency')
            plt.show()

            # Ability Histogram control vs. experiment, objective.
            plt.hist([control_ability_tw_o, experimental_ability_tw_o], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Ability Histogram (Objective)")
            plt.legend()
            plt.xlabel('Ability Score')
            plt.ylabel('Frequency')
            plt.show()

            # Benevolence Histogram control vs. experiment, objective.
            plt.hist([control_benevolence_tw_o, experimental_benevolence_tw_o], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Benevolence Histogram (Objective)")
            plt.legend()
            plt.xlabel('Benevolence Score')
            plt.ylabel('Frequency')
            plt.show()

            # Integrity Histogram control vs. experiment, objective.
            plt.hist([control_integrity_tw_o, experimental_integrity_tw_o], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Integrity Histogram (Objective)")
            plt.legend()
            plt.xlabel('Integrity Score')
            plt.ylabel('Frequency')
            plt.show()

            # Trusworthiness Histogram control vs. experiment, subjective.
            plt.hist([control_tw_s, experimental_tw_s], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Trustworthiness Histogram (Subjective)")
            plt.legend()
            plt.xlabel('Subjectively measured trustworthiness')
            plt.ylabel('Frequency')
            plt.show()

            # Ability Histogram control vs. experiment, subjective.
            plt.hist([control_ability_tw_s, experimental_ability_tw_s], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Ability Histogram (Subjective)")
            plt.legend()
            plt.xlabel('Ability Score')
            plt.ylabel('Frequency')
            plt.show()

            # Benevolence Histogram control vs. experiment, subjective.
            plt.hist([control_benevolence_tw_s, experimental_benevolence_tw_s], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Benevolence Histogram (Subjective)")
            plt.legend()
            plt.xlabel('Benevolence Score')
            plt.ylabel('Frequency')
            plt.show()

            # Integrity Histogram control vs. experiment, subjective.
            plt.hist([control_integrity_tw_s, experimental_integrity_tw_s], bins=7,
                     label=['control group', 'experimental group'], color=['#0072BD','#77AC30'])
            plt.title("Integrity Histogram (Subjective)")
            plt.legend()
            plt.xlabel('Integrity Score')
            plt.ylabel('Frequency')
            plt.show()

            # print("\n--- ABI score (metrics): ", [ability_score, benevolence_score, integrity_score])
            # print("--- ABI score (questionnaire): ", abi_questionnaire, "\n")

        control_group = [k for k in list_of_files if (CONTROL_AGENT in k)]
        experimental_group = [k for k in list_of_files if (EXPERIMENTAL_AGENT in k)]

        control_group_values = []
        control_group_ability = []
        control_group_benevolence = []
        control_group_integrity = []

        experimental_group_values = []
        experimental_group_ability = []
        experimental_group_benevolence = []
        experimental_group_integrity = []

        if len(control_group) > 0:
            for action_file in control_group:
                this_tick = _last_ticks([action_file])
                this_tick_to_respond = _average_ticks_to_respond([action_file])

                actions = _read_action_file(action_file)

                ability = Ability(actions, last_ticks, this_tick, verbose=VERBOSE)
                benevolence = Benevolence(actions, ticks_to_respond, this_tick_to_respond, verbose=VERBOSE)
                integrity = Integrity(actions, verbose=VERBOSE)

                ability_score, benevolence_score, integrity_score = _compute(ability, benevolence, integrity)
                trustworthiness = (ability_score + benevolence_score + integrity_score) / 3
                control_group_values.append(trustworthiness)
                control_group_ability.append(ability_score)
                control_group_benevolence.append(benevolence_score)
                control_group_integrity.append(integrity_score)

        if len(experimental_group) > 0:
            for action_file in experimental_group:
                this_tick = _last_ticks([action_file])
                this_tick_to_respond = _average_ticks_to_respond([action_file])

                actions = _read_action_file(action_file)

                ability = Ability(actions, last_ticks, this_tick, verbose=VERBOSE)
                benevolence = Benevolence(actions, ticks_to_respond, this_tick_to_respond, verbose=VERBOSE)
                integrity = Integrity(actions, verbose=VERBOSE)

                ability_score, benevolence_score, integrity_score = _compute(ability, benevolence, integrity)
                trustworthiness = (ability_score + benevolence_score + integrity_score) / 3
                experimental_group_values.append(trustworthiness)
                experimental_group_ability.append(ability_score)
                experimental_group_benevolence.append(benevolence_score)
                experimental_group_integrity.append(integrity_score)

        X = ['Ability', 'Benevolence', 'Integrity', 'Trustworthiness']

        print("control -- The mean is : ")
        print(np.mean(control_group_benevolence))
        print("The sd is ")
        print(np.std(control_group_benevolence))
        print("experimental -- The mean is : ")
        print(np.mean(experimental_group_benevolence))
        print("The sd is ")
        print(np.std(experimental_group_benevolence))

        control_bar_values = [np.mean(control_group_ability), np.mean(control_group_benevolence),
                              np.mean(control_group_integrity), np.mean(control_group_values)]
        experimental_bar_values = [np.mean(experimental_group_ability), np.mean(experimental_group_benevolence),
                                   np.mean(experimental_group_integrity), np.mean(experimental_group_values)]

        X_axis = np.arange(len(X))

        plt.bar(X_axis - 0.2, control_bar_values, 0.4, label='Control Group')
        plt.bar(X_axis + 0.2, experimental_bar_values, 0.4, label='Experimental Group')

        plt.xticks(X_axis, X)
        plt.title("ABI Objective Measures Comparison")
        plt.legend()
        plt.show()

        ## Plot Questionnaire Graph
        list_of_questionnaires = glob.glob('../data/questionnaire/*.json')
        control_a = []
        control_b = []
        control_i = []
        experimental_a = []
        experimental_b = []
        experimental_i = []
        count = 0
        if len(list_of_questionnaires) > 0:

            for questionnaireFile in list_of_questionnaires:
                f = open(questionnaireFile)
                data = json.load(f)
                abi_questionnaire = _compute_questionaire(data)
                if CONTROL_AGENT in questionnaireFile:
                    control_a.append(abi_questionnaire[0])
                    control_b.append(abi_questionnaire[1])
                    control_i.append(abi_questionnaire[2])
                if EXPERIMENTAL_AGENT in questionnaireFile:
                    count += 1
                    experimental_a.append(abi_questionnaire[0])
                    experimental_b.append(abi_questionnaire[1])
                    experimental_i.append(abi_questionnaire[2])

            if count == 0:
                print("ERROR: You forgot to include your experimental data in the questionnaire folder. Exiting.")
                return

            print("The medians : ")
            print(np.median(np.array(control_i)))
            print(np.median(np.array(experimental_i)))

            control_avg_ability = np.average(np.array(control_a))
            control_avg_benevolence = np.average(np.array(control_b))
            control_avg_integrity = np.average(np.array(control_i))
            control_abi = np.array([control_avg_ability, control_avg_benevolence,
                                    control_avg_integrity])  # contains the average score for ability, benevolence and integrity
            # of the control group
            control_trustworthiness = np.average(control_abi)

            experimental_avg_ability = np.average(np.array(experimental_a))
            experimental_avg_benevolence = np.average(np.array(experimental_b))
            experimental_avg_integrity = np.average(np.array(experimental_i))
            experimental_abi = np.array([experimental_avg_ability, experimental_avg_benevolence,
                                         experimental_avg_integrity])  # contains the average score for ability, benevolence
            # and integrity of the experimental group
            experimental_trustworthiness = np.average(experimental_abi)

            df = pd.DataFrame({'control group': [control_avg_ability, control_avg_benevolence, control_avg_integrity,
                                                 control_trustworthiness],
                               'experimental group': [experimental_avg_ability, experimental_avg_benevolence,
                                                      experimental_avg_integrity, experimental_trustworthiness]},
                              index=["Ability", "Benevolence", "Integrity", "Trustworthiness"])
            df.plot(kind='bar')
            plt.title("ABI Questionnaire Score Comparison")
            plt.legend()
            plt.show()

            print("Got here")

Trustworthiness()


"""
CP1404 - Practical 1
Broken program to determine score status
"""

user_name = input("Enter name: ").title()
MENU = '''
(H)ello
(G)oodbye
(Q)uit'''

print(MENU)
choice = input(">> ").upper()
while choice != 'Q':
    if choice == 'H':
        print(f"Hello {user_name}")
    elif choice == 'G':
        print(f"Goodbye {user_name}")
    else:
        print("Invalid choice")
    print(MENU)
    choice = input(">> ").upper()
print("Finished")


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
#https://en.wikipedia.org/wiki/Priority_queue
#https://docs.python.org/3/library/queue.html
from queue import PriorityQueue
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        k = len(lists)
        q = PriorityQueue(maxsize=k)
        dummy = ListNode(None)
        curr = dummy
        for list_idx, node in enumerate(lists):
            if node: q.put((node.val, list_idx, node))
        while q.qsize() > 0:
            poped = q.get()
            curr.next, list_idx = poped[2], poped[1]
            curr = curr.next
            if curr.next: q.put((curr.next.val, list_idx, curr.next))
        return dummy.next

    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        lst=[]
        for i in range(len(lists)):
            while lists[i]!=None:
                lst.append(lists[i].val)
                lists[i]=lists[i].next
        if not lst:
            return None
        lst.sort()
        ans=temp=ListNode(lst[0])
        for i in range(1,len(lst)):
            temp.next=ListNode(lst[i])
            temp=temp.next
        return ans

    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        amount = len(lists)
        interval = 1
        while interval < amount:
            for i in range(0, amount - interval, interval * 2):
                lists[i] = self.merge2Lists(lists[i], lists[i + interval])
            interval *= 2
        return lists[0] if amount > 0 else lists

    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l1
                l1 = point.next.next
            point = point.next
        if not l1:
            point.next=l2
        else:
            point.next=l1
        return head.next


import chainer
from chainer import cuda
import numpy as np
from chainer.dataset import to_device

def convert_hybrid(batch, gpu):

    def to_device_batch(batch, gpu):
        if gpu is None:
            return batch
        elif gpu < 0:
            return [chainer.dataset.to_device(gpu, x) for x in batch]
        else:
            xp = cuda.cupy.get_array_module(*batch)
            concat = xp.concatenate(batch, axis=0)
            sections = np.cumsum([len(x) for x in batch[:-1]], dtype='i')
            concat_dev = chainer.dataset.to_device(gpu, concat)
            batch_dev = cuda.cupy.split(concat_dev, sections)
            return batch_dev

    return {'ids': [x1 for x1, t1, t2, t3 in batch],
            'ts_link': to_device(x=np.array([t1 for _, t1, t2, t3 in batch], dtype='i'), device=gpu),
            'ts_type': to_device(x=np.array([t2 for _, t1, t2, t3 in batch], dtype='i'), device=gpu),
            'ts_link_type': to_device(x=np.array([t3 for _, t1, t2, t3 in batch], dtype='i'), device=gpu)
            }


import folium.vector_layers
from folium.vector_layers import Circle, PolyLine
import geopandas as gpd
from shapely.geometry import Polygon, Point
from shapely.ops import nearest_points
from math import radians, cos
from geopy.distance import great_circle

def create_germany_map(lat, lng, name):
    # (Put the entire create_germany_map function here, unchanged)
    def create_germany_map(lat, lng, name):
        germany_lat, germany_lng = 51.1657, 10.4515
        m = folium.Map(location=[germany_lat, germany_lng], zoom_start=6)

        # Add a marker to the map
        marker = folium.Marker([lat, lng], popup=name).add_to(m)

        # Load the GeoJSON data and filter by bounds
        search_radius = 100  # km
        lat_range = search_radius / 111.2  # Approximate 1 degree of latitude as 111.2 km
        lng_range = search_radius / abs(
            111.2 * cos(radians(lat)))  # Approximate 1 degree of longitude at the given latitude
        bounds = Polygon([(lng - lng_range, lat - lat_range), (lng + lng_range, lat - lat_range),
                          (lng + lng_range, lat + lat_range), (lng - lng_range, lat + lat_range)])
        geojson_file = "/home/ah/Desktop/map/simple.geojson"
        gdf = gpd.read_file(geojson_file)
        gdf = gdf[gdf.geometry.intersects(bounds)]
        circle = Circle(location=[lat, lng], radius=30000, color='blue', fill=True, fill_opacity=0.2)
        circle.add_to(m)

        # Find the closest point in the filtered layer
        origin = Point(lng, lat)
        gdf['geometry'] = gdf['geometry'].buffer(0)  # Clean the geometries
        nearest_geom = gdf.geometry.unary_union
        nearest_point = nearest_points(origin, nearest_geom)[1]

        # Add a marker for the closest point
        closest_marker = folium.Marker([nearest_point.y, nearest_point.x], popup="Closest Point",
                                       icon=folium.Icon(color='red')).add_to(m)

        # Draw a dotted line between the initial and the calculated marker
        line = PolyLine([(lat, lng), (nearest_point.y, nearest_point.x)],
                        color='black',
                        dash_array='5, 5',
                        weight=2).add_to(m)

        from geopy.distance import great_circle

        # Calculate the distance between the initial and the calculated marker
        distance = great_circle((lat, lng), (nearest_point.y, nearest_point.x)).km

        # Add the distance as a popup to the line
        line.add_child(folium.Popup(f'Distance: {distance:.2f} km'))

        # Add the filtered GeoJSON layer to the map as a vector layer
        folium.GeoJson(
            gdf,
            name="Flood Risk Zones",
            style_function=lambda feature: {
                'fillColor': 'red',
                'color': 'black',
                'weight': 1,
                'fillOpacity': 0.4,
            },
            overlay=True,
            control=False,
        ).add_to(m)

        m.save('germany_map_with_marker_and_filtered_geojson.html')


import jieba
import jieba.analyse
from io import *
import synonyms
# import docx
import jieba.posseg as pseg
import re
jieba.load_userdict("dict/newWord.txt")
symWords = []
symClassWords = []
stopWord = []

jieba.analyse.set_stop_words("dict/stopWord.txt")
jieba.analyse.set_idf_path('dict/newIDF.txt')
#加载停用词
def loadStopWord():
    stopWordFile = open("dict/stopWord.txt",'r',encoding='utf-8')

    for line in stopWordFile.readlines():
        stopWord.append(line.strip())

loadStopWord()
def removeStopWords(words):
    result =[]
    for word in words:
        if word not in stopWord:

            result.append(word)

    return result

# 扩充idf，权重根据词的长度，越长的词准确输入的概率越低，所以词越长逆文本频率越高
def extendIDF(keyWords):
    isOK = True
    IDFFlag = True
    baseIDF = open(r'dict/newIDF.txt', 'r+', encoding='utf-8')
    IDFLines = baseIDF.readlines()
    for keyWord in keyWords:
        if len(IDFLines) is not 0:
            for line in IDFLines:

                if keyWord not in line.strip().split():

                    IDFFlag = True
                else:
                    print("匹配到相同的")

                    IDFFlag = False
                    break
        else:
            IDFFlag = True

        if IDFFlag:
            try:
                baseIDF.write(keyWord + " " + len(keyWord) * 6.0 + 10)
                baseIDF.write('\n')
            except IOError:
                print("Error: 写入失败")
                isOK = False
    baseIDF.close()
    jieba.analyse.set_idf_path('dict/newIDF.txt')
    return isOK

#扩充词典
def extendDictory(keyWords):
    isOK = True
    flag = False
    # dic = open("/Users/zuchebao/PycharmProjects/KeywordRecommendationSystem/dict/newWord.txt", "r+", encoding='utf-8')
    dic = open("dict/newWord.txt","r+",encoding='utf-8')
    lines = dic.readlines()
    for keyWord in keyWords:
        if len(lines) is not 0:
            for line in lines :
                if keyWord not in line.strip().split():

                    flag = True
                else:
                    print("匹配到相同的")

                    flag = False
                    break
        else:
            flag = True

        if flag:
            try:
                dic.write(keyWord+" n")
                dic.write('\n')
            except IOError:
                print( "Error: 写入失败")
                isOK = False

            else:
                print
                "内容写入文件成功"
    # jieba.load_userdict("/Users/zuchebao/PycharmProjects/KeywordRecommendationSystem/dict/newWord.txt")
    # jieba.analyse.set_idf_path(r'/Users/zuchebao/PycharmProjects/KeywordRecommendationSystem/dict/newIDF.txt')
    jieba.load_userdict("dict/newWord.txt")

    dic.close()
    return isOK

def getKeyWord(txt):
    score = []
    keyWords = []
    result = []
    keywords_textrank = jieba.analyse.extract_tags(txt, topK=10, withWeight=True, allowPOS=('n', 'nr', 'ns', 'a'), withFlag=False)
    for index,item in enumerate(keywords_textrank):
        score.append(str(keywords_textrank[index][1]))
        keyWords.append(keywords_textrank[index][0])
    result.append(keyWords)
    result.append(score)

    return result

def cutWord(txt):
    words = removeStopWords(list(jieba.cut_for_search(txt,HMM=True)))
    resutltWord = []
    uncn = re.compile(r'[\u0061-\u007a,\u0020]')
    en = "".join(uncn.findall(txt.lower()))

    enwords = []  # 建立一个空列表
    index = 0  # 遍历所有的字符
    start = 0  # 记录每个单词的开始位置
    while index < len(en):  # 当index小于p的长度
        start = index  # start来记录位置
        while en[index] != " " and en[index] not in [".", ","]:  # 若不是空格，点号，逗号
            index += 1  # index加一
            if index == len(en):  # 若遍历完成
                break  # 结束
        enwords.append(en[start:index])
        if index == len(en):
            break
        while en[index] == " " or en[index] in [".", ","]:
            index += 1
            if index == len(en):
                break

    resutltWord = enwords

    resutltWord.extend(words)

    return resutltWord

# 通过Synonyms获取同义词
def getSynomyms(keyWords):
    resultWords = []
    cutResult = []

    if len(keyWords) == 1:
        cutForSearchWords = removeStopWords(list(jieba.cut_for_search(keyWords[0], HMM=True)))
        scoreList = []
        if cutForSearchWords:

            for word in cutForSearchWords:
                scoreList.append('0.5')

            cutResult.append(cutForSearchWords)
            cutResult.append(scoreList)

        synonymsResult = list(synonyms.nearby(keyWords[0]))
        if synonymsResult[0]:
            for index, score in enumerate(synonymsResult[1]):
                synonymsResult[1][index] = str(score)
                resultWords.append(synonymsResult)
        resultWords.append(cutResult)

    else:
        for word in keyWords:
            scoreList = []
            cutForSearchWords = []
            cutForSearchWords = removeStopWords(list(jieba.cut_for_search(word, HMM=True)))
            if cutForSearchWords:
                for word in cutForSearchWords:
                    print(word)
                    scoreList.append('0.5')

                cutResult.append(cutForSearchWords)
                cutResult.append(scoreList)
            synonymsResult = []

            synonymsResult = list(synonyms.nearby(word))
            if synonymsResult[0]:
                for index,score in enumerate(synonymsResult[1]):
                    synonymsResult[1][index] = str(score)

                    resultWords.append(synonymsResult)

            resultWords.append(cutResult)
    return resultWords

# 修改权重
def changeWeights(weight,start,end,word = "",):
    isSingle = len(word)
    oldidf = open(r'dict/newIDF.txt', 'r', encoding='utf-8')
    lines = oldidf.readlines()
    oldidf.close()
    newidf = open(r'dict/newIDF.txt', 'w', encoding='utf-8')

    if end is 0:
        end = len(lines)
    if isSingle:
        start = 0
    try:
        for i, line in enumerate(lines):
            if i in range(start, end):
                lineList = line.split()
                change = (float(lineList[1]) + float(weight))
                if isSingle:
                    if lineList[0] == word:
                        if change > 0:
                            newidf.write(lineList[0] + " " + str(change))
                            newidf.write('\n')
                        else:
                            continue
                    else:
                        newidf.write(line)
                    continue

                if change > 0:
                    newidf.write(lineList[0] + " " + str(change))
                    newidf.write('\n')
                else:
                    continue
            else:
                newidf.write(line)
    except IOError:
        return False
    jieba.analyse.set_idf_path('dict/newIDF.txt')
    return True

# def readDocx():
#     # category = []
#     file = docx.Document('/Users/zuchebao/Desktop/file.docx')
#     # for para in file.paragraphs:
#     #    print(para.text.split())
#     # getkey.extendDictory(category)
#     for table in file.tables:
#         rows = table.rows
#         for row in rows:
#             keyWord = []
#             key = row.cells[1].text.strip()
#             print(key)
#             keyWord.append(key)
#             if row.cells[2] is not '':
#                 for word in (row.cells[2].text.split('、')):
#                         if (word.strip()) is not '':
#                             for realWord in pseg.cut(word.strip,HMM=True):
#                                 if realWord[1] in ['n', 'nr', 'ns']:
#                                     keyWord.append(realWord[0])
#             for cutWord in (pseg.cut(key,HMM=True)):
#                 if cutWord[1] is ['n', 'nr', 'ns']:
#                     keyWord.append(cutWord[0])
#         keyWord = list(set(keyWord))
#         extendDictory(removeStopWords(keyWord))
#
#


# coding=utf-8

SEX = (
    (0, u'男'),
    (1, u'女'),
)

TRUE_FALSE = (
    (True, u'是'),
    (False, u'否')
)

DICT_NULL_BLANK_TRUE = {
    'null': True,
    'blank': True
}

EXCLUDE_BASE_FIELD = ('creator', 'created_at', 'updated_at', 'deleted_at')

PAYWAY = (
    (0, u"记应付帐款"),
    (1, u"现金付款"),
    (2, u"预付款"),
)

GOODS_ORDER_STATUS = (
    (0, u"待审核"),
    (1, u"审核通过"),
)

GOODS_STORAGE_STATUS = (
    (0, u"待入库"),
    (1, u"已入库"),
)

class UsableStatus(object):
    UNUSABLE = False
    USABLE = True
    STATUS = (
        (UNUSABLE, u'禁用'),
        (USABLE, u'启用'),
    )

class TaskStatus(object):
    NORMAL = 0
    EXCEPT = 1
    FINISHED = 2
    DELETED = 3
    TASK_STATUS = (
        (NORMAL, u'正常(进行中)'),
        (EXCEPT, u'异常'),
        (FINISHED, u'完成'),
        (DELETED, u'删除')
    )