import psycopg2
from datetime import date

dbname = "" # Sett inn ditt UiO-brukernavn
user = "" # Sett inn ditt UiO-brukernavn + _priv
pwd = "" # Sett inn passorder til _priv-brukeren du fikk i email

# Samle all info i en streng
connection = \
    "host='dbpg-ifi-kurs01.uio.no' " + \
    "dbname='" + dbname + "' " + \
    "user='" + user + "' " + \
    "port='5432' " + \
    "password='" + pwd + "'"

def main():
    conn = psycopg2.connect(connection)
    today(conn)

    while(True):
        print("\n\n-- MENU --\n1. Add event\n2. Show events for date\n3. Exit")
        ch = get_int_from_user("Option: ", True)
        if (ch == 1):
            add_event(conn)
        elif (ch == 2):
            show_events(conn)
        else:
            return

def show(conn, day):
    cur = conn.cursor()
    cur.execute("select eid, event, starts::time, ends::time " + \
            "from calendar " + \
            "where (starts, ends) overlaps (%s, %s + '1 day'::interval);", (day, day))

    row = cur.fetchone()
    while row is not None:
        print("[" + str(row[0]) + "] " + row[1] + ": " + str(row[2]) + " - " + str(row[3]))
        row = cur.fetchone()
    # Kan også bruke cur.fetchall() for å hente ut alt, men bør kun gjøres dersom
    # det er få resultater, siden alt lastes inn i minne samtidig. Koden blir da:
    #
    # rows = cur.fetchall()
    # for row in rows:
    #     print("[" + str(row[0]) + "] " + row[1] + ": " + str(row[2]) + " - " + str(row[3]))

def today(conn):
    print("-- TODAY'S EVENTS --")
    show(conn, date.today())

def show_events(conn):
    print("-- SHOW EVENTS --")
    datestr = input("Date: ")
    show(conn, date.fromisoformat(datestr))

def add_event(conn):
    print("-- ADD EVENT --")
    event = input("Event: ")
    starts = input("Starts: ")
    ends = input("Ends: ")

    cur = conn.cursor()
    cur.execute("INSERT INTO calendar(event, starts, ends) VALUES (%s, %s, %s);", (event, starts, ends))
    conn.commit()
    print("Event added.")

def get_int_from_user(msg, needed):
    # Utility method that gets an int from the user with the first argument as message
    # Second argument is boolean, and if false allows user to not give input, and will then
    # return None
    while True:
        numStr = input(msg)
        if (numStr == "" and not needed):
            return None;
        try:
            return int(numStr)
        except:
            print("Please provide an integer or leave blank.");

if __name__ == "__main__":
    main()


import unittest
import warnings
import datetime

from unittest.mock import patch, MagicMock
from io import BytesIO

from control.account import (
    DropboxAccountWrapper, GoogleDriveAccountWrapper,
    InterruptibleGoogleDriveUploadFileHandle, InterruptibleGoogleDriveDownloadFileHandle,
    TaskInterruptedException, CloudAPIFactory
)
from model.account import AccountTypes, AccountData
from model.task import Task
from model.message import MessageTypes
from model.file import FilePart

from dropbox.files import FileMetadata, FolderMetadata
from Crypto.Cipher import AES

warnings.filterwarnings("ignore", category=DeprecationWarning)

class TestDropboxAccountWrapper(unittest.TestCase):

    def setUp(self):
        self.testAccountData = AccountData(
            AccountTypes.Dropbox,
            "testIdentifier",
            "sixteen byte key",
            {"apiToken": "testApiToken"},
            1
        )

    @patch("dropbox.Dropbox")
    def test_getFileList_returns_encrypted_files_recursively(self, mockDropbox):
        testCloudFiles = [
            FileMetadata(name="apple.txt__1__1.enc", size=5, client_modified=datetime.datetime(2020, 1, 1, 6, 10, 15), path_display="/apple.txt__1__1.enc"),
            FolderMetadata(name="thisFolderShouldBeIgnored"),
            FileMetadata(name="pear.txt__1__2.enc", size=10, client_modified=datetime.datetime(2020, 1, 1, 7, 10, 15), path_display="/subDir/pear.txt__1__2.enc"),
            FileMetadata(name="notAnEncodedFile.jpeg", size=20, client_modified=datetime.datetime(2020, 1, 1, 7, 10, 15), path_display="/notAnEncodedFile.jpeg"),
        ]
        mockDropbox.return_value.files_list_folder.return_value.entries = testCloudFiles
        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        files = cloudAccount.getFileList()

        self.assertEqual(len(files), 2)
        self.assertEqual(mockDropbox.return_value.files_list_folder.call_args[0][0], "")
        self.assertEqual(mockDropbox.return_value.files_list_folder.call_args[1], {"recursive": True})

        self.assertEqual(files[0].filename, testCloudFiles[0].name)
        self.assertEqual(files[0].modified, int(testCloudFiles[0].client_modified.timestamp()))
        self.assertEqual(files[0].size, testCloudFiles[0].size)
        self.assertEqual(files[0].path, "")
        self.assertEqual(files[0].fullPath, "apple.txt__1__1.enc")
        self.assertEqual(files[0].storingAccountID, self.testAccountData.id)

        self.assertEqual(files[1].filename, testCloudFiles[2].name)
        self.assertEqual(files[1].modified, int(testCloudFiles[2].client_modified.timestamp()))
        self.assertEqual(files[1].size, testCloudFiles[2].size)
        self.assertEqual(files[1].path, "subDir")
        self.assertEqual(files[1].fullPath, "subDir/pear.txt__1__2.enc")
        self.assertEqual(files[1].storingAccountID, self.testAccountData.id)

    @patch("dropbox.files.UploadSessionCursor")
    @patch("dropbox.Dropbox")
    def test_upload_writes_iv_and_encrypts_file_data(self, mockDropbox, mockUploadCursor):
        uploadSessionStarter = MagicMock()
        uploadSessionAppender = MagicMock()

        mockDropbox.return_value.files_upload_session_start = uploadSessionStarter
        mockDropbox.return_value.files_upload_session_finish = uploadSessionAppender

        testSecretData = b"secret test data"
        testFileHandle = BytesIO(testSecretData)
        testPartName = "testFile__1__1.enc"
        testClientModified = datetime.datetime(2020, 1, 1, 10, 5, 30)

        testFileData = {"userTimezone": "+0200", "utcModified": testClientModified.timestamp(), "path": "subDir"}
        testTask = Task(taskType=MessageTypes.UPLOAD_FILE, data=testFileData)

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        result = cloudAccount.upload(testFileHandle, len(testSecretData), testPartName, testTask)

        cipher = AES.new(self.testAccountData.cryptoKey.encode(), AES.MODE_CFB, iv=uploadSessionStarter.call_args[0][0])
        encoded = mockDropbox.return_value.files_upload_session_finish.call_args[0][0]

        self.assertNotEqual(encoded, testSecretData)
        self.assertEqual(cipher.decrypt(encoded), testSecretData)

    @patch("dropbox.files.UploadSessionCursor")
    @patch("dropbox.Dropbox")
    def test_upload_does_nothing_if_task_is_stale(self, mockDropbox, mockUploadCursor):
        uploadSessionStarter = MagicMock()
        uploadSessionAppender = MagicMock()

        mockDropbox.return_value.files_upload_session_start = uploadSessionStarter
        mockDropbox.return_value.files_upload_session_finish = uploadSessionAppender

        testSecretData = b"secret test data"
        testFileHandle = BytesIO(testSecretData)
        testPartName = "testFile__1__1.enc"
        testClientModified = datetime.datetime(2020, 1, 1, 10, 5, 30)

        testFileData = {"userTimezone": "+0200", "utcModified": testClientModified.timestamp(), "path": "subDir"}
        testTask = Task(taskType=MessageTypes.UPLOAD_FILE, data=testFileData, stale=True)

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        result = cloudAccount.upload(testFileHandle, len(testSecretData), testPartName, testTask)

        self.assertEqual(uploadSessionStarter.call_count, 0)
        self.assertEqual(uploadSessionAppender.call_count, 0)
        self.assertIsNone(result)

    @patch("requests.get")
    def test_download_file_decodes_content_if_not_interrupted(self, mockRequest):
        secretData = b"secret test data"
        testEncoder = AES.new(self.testAccountData.cryptoKey.encode(), AES.MODE_CFB)
        testIV = testEncoder.iv

        ivResponse = MagicMock()
        ivResponse.content = testIV

        encryptedDataResponse = MagicMock()
        encryptedDataResponse.content = testEncoder.encrypt(secretData)

        mockRequest.side_effect = [ivResponse, encryptedDataResponse]

        testDownloadFileHandle = BytesIO()
        testFilePartInfo = FilePart(
            filename="apple.txt__1__1.enc", modified=int(datetime.datetime(2020, 1, 1, 10, 10, 30).timestamp()),
            size=len(encryptedDataResponse.content) + len(testIV), path="", fullPath="apple.txt__1__1.enc",
            storingAccountID=self.testAccountData.id, extraInfo={}
        )

        testDownloadFileTask = Task(taskType=MessageTypes.DOWNLOAD_FILE)
        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        cloudAccount.download(testDownloadFileHandle, testFilePartInfo, testDownloadFileTask)

        testDownloadFileHandle.seek(0)

        self.assertEqual(secretData, testDownloadFileHandle.read())

    @patch("requests.get")
    def test_download_file_does_nothing_if_task_is_stale(self, mockRequest):
        secretData = b"secret test data"
        testEncoder = AES.new(self.testAccountData.cryptoKey.encode(), AES.MODE_CFB)
        testIV = testEncoder.iv

        ivResponse = MagicMock()
        ivResponse.content = testIV

        encryptedDataResponse = MagicMock()
        encryptedDataResponse.content = testEncoder.encrypt(secretData)

        mockRequest.side_effect = [ivResponse, encryptedDataResponse]

        testDownloadFileHandle = BytesIO()
        testFilePartInfo = FilePart(
            filename="apple.txt__1__1.enc", modified=int(datetime.datetime(2020, 1, 1, 10, 10, 30).timestamp()),
            size=len(encryptedDataResponse.content) + len(testIV), path="", fullPath="apple.txt__1__1.enc",
            storingAccountID=self.testAccountData.id, extraInfo={}
        )

        testDownloadFileTask = Task(taskType=MessageTypes.DOWNLOAD_FILE, stale=True)
        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        cloudAccount.download(testDownloadFileHandle, testFilePartInfo, testDownloadFileTask)

        testDownloadFileHandle.seek(0)

        self.assertEqual(b"", testDownloadFileHandle.read())

    @patch("dropbox.Dropbox")
    def test_deleteFile_delegates_call_properly(self, mockDropbox):

        mockDropbox.return_value.files_delete = MagicMock()
        testFilePartInfo = FilePart(
            filename="apple.txt__1__1.enc", modified=int(datetime.datetime(2020, 1, 1, 10, 10, 30).timestamp()),
            size=32, path="subDir", fullPath="subDir/apple.txt__1__1.enc",
            storingAccountID=self.testAccountData.id, extraInfo={}
        )

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        cloudAccount.deleteFile(testFilePartInfo)

        self.assertEqual(mockDropbox.return_value.files_delete.call_count, 1)
        self.assertEqual(mockDropbox.return_value.files_delete.call_args[0][0], f"/{testFilePartInfo.fullPath}")

    @patch("dropbox.Dropbox")
    def test_moveFile_delegates_call_properly(self, mockDropbox):
        mockDropbox.return_value.files_move = MagicMock()
        testFilePartInfo = FilePart(
            filename="apple.txt__1__1.enc", modified=int(datetime.datetime(2020, 1, 1, 10, 10, 30).timestamp()),
            size=32, path="", fullPath="apple.txt__1__1.enc",
            storingAccountID=self.testAccountData.id, extraInfo={}
        )
        destinationPath = "subDir/apple.txt__1__2.enc"

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        cloudAccount.moveFile(testFilePartInfo, destinationPath)

        self.assertEqual(mockDropbox.return_value.files_move.call_count, 1)
        self.assertEqual(mockDropbox.return_value.files_move.call_args[0][0], f"/{testFilePartInfo.fullPath}")
        self.assertEqual(mockDropbox.return_value.files_move.call_args[0][1], f"/{destinationPath}")

class TestInterruptibleGoogleDriveFileHandles(unittest.TestCase):

    def test_upload_fileHandle_raises_exception_if_task_is_stale(self):
        fakeFileHandle = BytesIO(b"lorem ipsum")
        testFileData = {"userTimezone": "+0200", "utcModified": datetime.datetime(2020, 1, 1, 10, 5, 30).timestamp(), "path": "subDir"}
        testTask = Task(taskType=MessageTypes.UPLOAD_FILE, data=testFileData, stale=True)

        testInterruptibleHandle = InterruptibleGoogleDriveUploadFileHandle(fakeFileHandle, testTask)
        try:
            testInterruptibleHandle.read(8192)
            self.fail("InterruptibleGoogleDriveUploadFileHandle failed to raise TaskInterruptedException on a stale task!")
        except TaskInterruptedException:
            pass

    def test_download_fileHandle_raises_exception_if_task_is_stale(self):
        fakeDownloadFileHandle = BytesIO()
        testDownloadFileTask = Task(taskType=MessageTypes.DOWNLOAD_FILE, stale=True)

        testInterruptibleHandle = InterruptibleGoogleDriveDownloadFileHandle(fakeDownloadFileHandle, "sixteen byte key", testDownloadFileTask)
        try:
            testInterruptibleHandle.write(b"fakeinitvectorrr")
            testInterruptibleHandle.write(b"fake file data should raise exception")
            self.fail("InterruptibleGoogleDriveDownloadFileHandle failed to raise TaskInterruptedException on a stale task!")
        except TaskInterruptedException:
            pass

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


import os

import torchvision.transforms as transforms
from torchvision import datasets

data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

data_dir = 'C:/Users/bieli_pc4qr7s/Documents/Code Parada.js/plantist/data/'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
class_names = image_datasets['train'].classes


import itertools
import numpy as np
from mpi4py import MPI

from . import constants

def get_global_test_points(workers_segments):
    test_points = []
    for i_seg in range(workers_segments.effective_n_seg):
        seg_bounds = workers_segments.get_seg_bounds(i_seg)
        pt_coord = [(s, s+1, s+2, (s+e) // 2, e-1, e-2, e-3)
                    for s, e in seg_bounds]
        test_points.extend(itertools.product(*pt_coord))
    return test_points

def main_check_beta(comm, workers_segments):
    """Check that beta computed in overlapping workers is identical.

    This check is performed only for workers overlapping with the first one.
    """
    global_test_points = get_global_test_points(workers_segments)
    for i_probe, pt_global in enumerate(global_test_points):
        sum_beta = np.empty(1, 'd')
        value = []
        for i_worker in range(workers_segments.effective_n_seg):

            pt = workers_segments.get_local_coordinate(i_worker, pt_global)
            if workers_segments.is_contained_coordinate(i_worker, pt):
                comm.Recv([sum_beta, MPI.DOUBLE], source=i_worker,
                          tag=constants.TAG_ROOT + i_probe)
                value.append(sum_beta[0])
        if len(value) > 1:
            # print("hello", pt_global)
            assert np.allclose(value[1:], value[0]), value

def worker_check_beta(rank, workers_segments, beta, D_shape):
    """Helper function for main_check_warm_beta, to be run in the workers."""

    assert beta.shape[0] == D_shape[0]

    global_test_points = get_global_test_points(workers_segments)
    for i_probe, pt_global in enumerate(global_test_points):
        pt = workers_segments.get_local_coordinate(rank, pt_global)
        if workers_segments.is_contained_coordinate(rank, pt):
            beta_slice = (Ellipsis,) + pt
            sum_beta = np.array(beta[beta_slice].sum(), dtype='d')

            comm = MPI.Comm.Get_parent()
            comm.Send([sum_beta, MPI.DOUBLE], dest=0,
                      tag=constants.TAG_ROOT + i_probe)