from sys import argv
from os.path import exists

script, from_file, to_file = argv

print( f"Copying from {from_file} to {to_file}." )

lInput = open(from_file).read()

print( f"The input file {len(lInput)} bytes long" )

print( f"Does the output file already exist? {exists(to_file)}" )
print("Read? Hit RETURN to continue or CTRL-C to abort." )

input()

lOutput = open( to_file, 'w' )
lOutput.write( lInput )

print("Alright, all done, just close the files now." )

lOutput.close()


# 2번
output = [i for i in range(1, 101) if "{:b}".format(i).count("0") == 1]
#list_bin = {}
#for j in output:
#    if "{:b}".format(j).count("0") == 1:
#        list_bin[j] = "{:b}".format(j)

print(sum(output))

# 시험 1번
# 구구단을 출력하는 함수( dan(num) )를 작성하고 dan(4) 결과를 아래와 같이 출력하시오.
def dan(num):
    print("==== {}단 ====".format(num))
    for i in range(1, 10):
        print("{} * {} = {}".format(num, i, num*i))

dan(4)

# 시험 2번
def gu_gu_dan(start, end):
    for j in range(start, end + 1):
        dan(j)

gu_gu_dan(2, 4)

#시험 5번
list_a = []

for i in range(11):
    list_a.append(i)

print("list_a = ", list_a)

list_even = [e for e in list_a if e % 2 == 0]
list_odd = [o for o in list_a if o % 2 == 1]

print("list_even = ", list_even)
print("list_odd = ", list_odd)


from django.utils.translation import ugettext as _

import activity
from activity import ActivityForModel
from activity.feeds import ChangesOnItemFeed
from localwiki.utils.urlresolvers import reverse

from models import Page, PageFile, slugify

class PageChanges(ActivityForModel):
    classname = 'page'

    def queryset(self, start_at=None):
        if self.region:
            qs = Page.versions.filter(region=self.region)
        else:
            qs = Page.versions.all()

        if start_at:
            qs = qs.filter(version_info__date__gte=start_at)

        return qs.defer('content')

    def page(self, obj):
        return obj

activity.register(PageChanges)

class PageFileChanges(ActivityForModel):
    classname = 'file'

    def queryset(self, start_at=None):
        if self.region:
            qs = PageFile.versions.filter(region=self.region)
        else:
            qs = PageFile.versions.all()

        if start_at:
            qs = qs.filter(version_info__date__gte=start_at)
        return qs

    def page(self, obj):
        try:
            page = Page.objects.get(slug=obj.slug, region=obj.region)
        except Page.DoesNotExist:
            page = Page(slug=obj.slug, region=obj.region, name=obj.slug.capitalize())
        return page

    def title(self, obj):
        return _('File %(filename)s on page "%(pagename)s"') % {
            'filename': obj.name, 'pagename': self.page(obj).name}

    def diff_url(self, obj):
        return reverse('pages:file-compare-dates', kwargs={
            'slug': self.page(obj).pretty_slug,
            'region': obj.region.slug,
            'date1': obj.version_info.date,
            'file': obj.name,
        })

    def as_of_url(self, obj):
        return reverse('pages:file-as_of_date', kwargs={
            'slug': self.page(obj).pretty_slug,
            'region': obj.region.slug,
            'date': obj.version_info.date,
            'file': obj.name,
        })

activity.register(PageFileChanges)

class PageChangesFeed(ChangesOnItemFeed):
    activity_class = PageChanges

    def get_object(self, request, region='', slug=''):
        self.setup_region(region)

        obj = Page(slug=slugify(slug), region=self.region)
        obj.title = obj.versions.most_recent().name
        obj.page = obj
        return obj

class PageFileChangesFeed(ChangesOnItemFeed):
    activity_class = PageFileChanges

    def get_object(self, request, region='', slug='', file=''):
        self.setup_region(region)

        obj = PageFile(slug=slugify(slug), region=self.region, name=file)
        page = Page(slug=slugify(slug), region=self.region)
        obj.page = page.versions.most_recent()
        obj.title = _('File %(filename)s on page "%(pagename)s"') % {
            'filename': obj.name, 'pagename': obj.page.name}
        return obj


import socket

s = socket.socket()
host = socket.gethostname()
port = 8800
s.bind((host,port))
s.listen(1)
print(host)
print("Menunggu konensi......")
conn, addr = s.accept()
print(addr, "sudah terkoneksi dengan server")

filename=input(str("silahkan masukan nama file yang akan di kirim: "))
file = open(filename,'rb')
file_data = file.read(1024)
conn.send(file_data)
print("Data sudah berhasil di kirim")
print (" Terima kasih :) ")


from functools import reduce

pessoas = [
    {'nome': 'Pedro', 'idade': 11},
    {'nome': 'Mariana', 'idade': 18},
    {'nome': 'Arthur', 'idade': 26},
    {'nome': 'Rebeca', 'idade': 6},
    {'nome': 'Tiago', 'idade': 19},
    {'nome': 'Gabriela', 'idade': 17},
]

menores = filter(lambda p: p['idade'] < 18, pessoas)
soma_idades_dos_menores = reduce(
    lambda idades, p: idades + p['idade'], menores, 0)
print(soma_idades_dos_menores)

soma_idades = reduce(lambda idades, p: idades + p['idade'], pessoas, 0)
print(soma_idades)

so_idades = map(lambda p: p['idade'], pessoas)
so_menores = filter(lambda idade: idade < 18, so_idades)
soma_so_das_idades = reduce(
    lambda idades, idade: idades + idade, so_menores, 0)
print(soma_so_das_idades)


js_import = ('''
import { connect } from 'react-redux'
import Follow from './components/Follow'
import { follow, unfollow } from './actions'
''')

__pragma__('noalias', 'keys') # use js_keys

def mapStateToProps(state):
    # console.log('state.handles ' + JSON.stringify(state.handles))
    return {
        'following': Object.keys(state.follows).map(
            lambda handle: { 'handle': handle }),

        'notFollowing': Object.keys(state.handles).filter(
            lambda handleHash:
                not state.follows[state.handles[handleHash].handle] and
                    state.handles[handleHash].handle is not state.handle
                    ).map(
            lambda handleHash: {
                'handleHash': handleHash,
                'handle': state.handles[handleHash].handle
                })
        }

mapDispatchToProps = lambda dispatch: {
    'follow': lambda handle, then: dispatch(follow(handle, then)),
    'unfollow': lambda handle, then: dispatch(unfollow(handle, then))
    }

__pragma__('js',
    'export default connect(mapStateToProps, mapDispatchToProps)(Follow)')


location_choices = {
  '1':'Mwiyogo/EndaraSha',
  '2':'Gatarakwa',
  '3':'Thegu River',
  '4':'Kabaru',
  '5':'Gakawa',
  '6':'Mathira	Ruguru',
  '7':'Magutu',
  '8':'Iriani',
  }

sublocation_choices = {
  '1':'Tetu',
  '2':'Kieni',
  '3':'Mathira',
  '4':'Othaya',
  '5':'Mukurweini',
  '6':'Nyeri Town',
  '7':'Ndia',
  '8':'Muks',
}

subcounty_choices = {
        'Ba': 'Baragoi',
        'AL': 'Bungoma',
        'AR': 'Busia',
        'AS': 'Butere',
        'AZ': 'Dadaab',
        'CA': 'Diani Beach',
        'CO': 'Eldoret',
        'CT': 'Emali',
        'DC': 'Embu',
        'DE': 'Garissa',
        'FL': 'Hola',
        'GA': 'Homa Bay',
        'GU': 'Guam',
        'HI': 'Isiolo',
        'IA': 'Kitui',
        'ID': 'Kibwezi',
        'IL': 'Kajiado',
        'IN': 'Kakuma',
        'KS': 'Kapenguria',
        'KY': 'Keroka',
        'LA': 'Kiambu',
        'MA': 'Kilifi',
        'MD': 'Kisii',
        'ME': 'Kisumu',
        'MI': 'Kitale',
        'MN': 'Mandera',
        'MO': 'Malindi',
        'MP': 'Makindu',
        'MS': 'Machakos',
        'MT': 'Loyangalani',
        'NA': 'Londiani',
        'NC': 'Lokichoggio',
        'WY': 'Lodwar'
}


import time

from selenium import webdriver
import random
import Selenium

def main():
    #Open web page
    driver = Selenium.open_page()
    #See if tix are available for adult
    tickets_found = False
    while tickets_found == False:
        result = Selenium.check_for_tickets(driver)
        if result == False:
            pause_interval = random.randrange(2,5)
            print("No tickets found, pausing for " + pause_interval.__str__() + " seconds.")
            time.sleep((pause_interval))
            Selenium.refresh_page(driver)
        else:
            tickets_found == True

if __name__ == "__main__":
    main()


import utils
import context
import operator
import view.context as ctx

class Keymap(dict):
    def __init__(self, name, *a, **k):
        dict.__init__(self, *a, **k)
        self.NAME = name
        KeymapManager.register_keymap(self)

class KeymapManager():
    """KeymapManager

    Instance of this class helps to map OS specific events
    to application methods.
    Application actions (aka Operators) are mapped on events,
    using a function as key. This function is used to match events.
    Another feature is the multi maps handling: at any moments
    the KeymapManager instance can uses another map,
    that permit to implement modal handling.

    Requiers 2.7
    """

    __metaclass__ = utils.MetaSingleton
    __kmd = {} # all registered keymaps

    def __init__(self, default):
        self._km = None # active keymap
        self._filters = None # current keymap's keys view used as filters
        self._mapstack = []
        self.use(default)
        self._locals = {}

    def process(self, *args):
        assert self._km is not None # need a valid keymap
        self._locals['event'] = args[1]
        done = self._process(self._km, self._filters, self._locals, args)
        if not done and self._mapstack:
            km = KeymapManager.__kmd.get(self._mapstack[-1])
            if km:
                done = self._process(km, km.viewkeys(), self._locals, args)
        return done

    def _process(self, km, filters, locals, args):
        opl = [ km[f] for f in filters if f(*args) ]
        for op in opl:
            eval(op, operator.ope_globals, locals)
        return bool(opl)

    def use(self, name):
        m = KeymapManager.__kmd.get(name, self._km)
        if m is not self._km:
            ctx.keymap = self
            self._km = m
            self._filters = m.viewkeys()

    def use_default(self):
        assert self._default is not None
        self.use(self._default)

    def push(self, name):
        self._mapstack.append(self._km.NAME)
        self.use(name)

    def pop(self):
        if self._mapstack:
            self.use(self._mapstack.pop())

    @classmethod
    def register_keymap(cls, km):
        """Transform each keymap dictionnary key (string)
        into a callable with following prototype:

        "lambda evt_type, evt: bool"

        Note: this operation destroy original contents of the keymap.
        """

        for k in km.keys():
            km[eval("lambda evt_type, evt:" + k)] = compile(km.pop(k), 'keymap', 'exec')
        cls.__kmd[km.NAME] = km


# Build Model
from transformers import BertModel
import torch.nn as nn

class BERT_Model(nn.Module):
  def __init__(self):
    super(BERT_Model, self).__init__()
    self.bert = BertModel.from_pretrained('bert-base-uncased') # use bert pretrained on hugging face
    self.drop = nn.Dropout(p=0.1) # dropout layer to avoid overfit

    # after bert, we make a fully connect layer to do the final regression output
    self.ffc = nn.Sequential(
      nn.Linear(768, 512),
      nn.ReLU(),
      nn.Linear(512, 256),
      nn.ReLU(),
      nn.Linear(256, 2),
    )

  def __call__(self, input_ids, attention_mask):
    output = self.bert(input_ids, attention_mask)
    output = output.pooler_output
    output = self.drop(output)
    output = self.ffc(output)
    return output.double()


#!/usr/bin/python3
"""
Module 8-rectangle
"""

BaseGeometry = __import__('7-base_geometry').BaseGeometry

class Rectangle(BaseGeometry):
    """
    inherits from BaseGeometry
    """
    def __init__(self, width, height):
        """validate and initialize width and height
        Arguments
        """
        super().integer_validator("width", width)
        self.__width = width
        super().integer_validator("height", height)
        self.__height = height


from cv2 import *
import numpy as np
import matplotlib.pyplot as plt

def Gaussian_pyrimid(img):
    copy_img = img.copy()

    titles = ['Original', 'Level1', 'Level2', 'Level3']
    g_down = []
    g_up = []

    g_down.append(copy_img)

    for i in range(3):
        temp1 = pyrDown(copy_img)
        g_down.append(temp1)
        copy_img = temp1

    imshow('Level3', copy_img)

    for i in range(4):
        imshow(titles[i], g_down[i])

    waitKey(0)
    destroyAllWindows()

def Gaussian_upsampling(img):
    copy_img = img.copy()

    titles = ['Original', 'Level1', 'Level2', 'Level3']
    g_down = []
    g_up = []

    g_down.append(copy_img)

    for i in range(3):
        temp1 = pyrDown(copy_img)
        g_down.append(temp1)
        copy_img = temp1

    imshow('Level3', copy_img)

    for i in range(3):
        copy_img = g_down[i+1]
        temp1 = pyrUp(copy_img)
        g_up.append(temp1)

    for i in range(3):
        imshow(titles[i], g_up[i])

    waitKey(0)
    destroyAllWindows()

def Laplacian_pyramid(img):
    copy_img = img.copy()

    titles = ['Original', 'Level1', 'Level2', 'Level3']
    g_down = []
    g_up = []
    image_append = []

    g_down.append(copy_img)
    image_append.append(copy_img.shape)

    for i in range(3):
        temp1 = pyrDown(copy_img)
        g_down.append(temp1)
        image_append.append(temp1.shape)
        copy_img = temp1

    for i in range(3):
        copy_img = g_down[i+1]
        temp1 = pyrUp(copy_img)
        copy_img = resize(temp1, dsize=(image_append[i][1], image_append[i][0]), interpolation=INTER_CUBIC)
        g_up.append(copy_img)

    for i in range(3):
        copy_img = subtract(g_down[i], g_up[i])
        imshow(titles[i], copy_img)

        #cc = add(g_up[i], copy_img)
        #imshow(titles[i], cc)
        #imshow("titles[i]", img)

    waitKey(0)
    destroyAllWindows()

def fourier(img):
    f = np.fft.fft2(img)
    fshift = np.fft.fftshift(f) #주파수 영역 한군데로 모으기
    m_specturm = 20 * np.log(np.abs(fshift))

    plt.subplot(121), plt.imshow(img, cmap='gray')
    plt.title('input image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122), plt.imshow(m_specturm, cmap='gray')
    plt.title('m_specturm'), plt.xticks([]), plt.yticks([])
    plt.show()
    #저주파 영역 60*60

    #imshow('title', img)
    #imshow('changed', m_specturm)
    #waitKey(0)
    #destroyAllWindows()

def LPF(img):
    dft = cv2.dft(np.float32(img), flags=DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)

    magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0], dft_shift[:,:,1]))

if __name__ == "__main__":
    #IMREAD_GRAYSCALE
    img = imread('123.jpg', IMREAD_GRAYSCALE)
    #Gaussian_pyrimid(img)
    #Gaussian_upsampling(img)
    #Laplacian_pyramid(img)
    #fourier(img)
    LPF(img)


#!/usr/bin/env python3

import os
import glob
import requests

host = 'pyrite.abudhabi.nyu.edu:3005'
# host = 'localhost:5010'
uri = 'http://{}/tf_counts/1.0/api/count_worms'.format(host)

def health_check():
    uri = 'http://{}/tf_counts/1.0/api/health'.format(host)
    res = requests.get(uri, json={})
    print(res.json())

def push_counts_to_queue(dirs):
    print('Pushing {}'.format(os.path.dirname(dirs[0])))
    # dirs = [dirs[0]]
    for d in dirs:
        dd = os.path.join('/mnt/image', d, os.path.basename(d) + '-tf_counts.csv')
        data = {
            'image_path': os.path.join('/mnt/image', d),
            'counts': dd
        }

        res = requests.post(uri, json=data)
        print('Data : {}'.format(data))
        print('Res: {}'.format(res.json()))

    print('Finished {}'.format(os.path.dirname(dirs[0])))

def sanity_check():
    data = {}
    data['image_path'] = '/home/webuser/images/'
    data['counts'] = '/home/webuser/images/counts.csv'
    res = requests.post(uri, json=data)
    print('Data : {}'.format(data))
    print('Res: {}'.format(res.json()))

def sanity_check_real_world():

    dirs = [
        '2014Dec15/1155',
        '2014Dec08/966',
        '2015Nov09/3716',
        '2015Nov09/3620',
        '2015Oct26/3149',
        '2015Oct26/3053',
        '2015Oct26/3052']

    for d in dirs:
        dd = os.path.join('/mnt/image', d, os.path.basename(d) + '-tf_counts.csv')
        data = {
            'image_path': os.path.join('/mnt/image', d),
            'counts': dd
        }
        print(data)
        res = requests.post(uri, json=data)
        print(res.json())

def push_dirs_to_queue(d):
    dirs = glob.glob(d)
    for d in dirs:
        if os.path.isdir(d):
            ds = glob.glob('{}/*'.format(d))
            push_counts_to_queue(ds)

print('Health Check!')
health_check()
print('Sanity check!')
sanity_check()
# sanity_check_real_world()

print('Ok starting real world!')

push_dirs_to_queue('/mnt/image/2015*')
push_dirs_to_queue('/mnt/image/2014*')
push_dirs_to_queue('/mnt/image/2016*')
push_dirs_to_queue('/mnt/image/2017*')
push_dirs_to_queue('/mnt/image/2018*')


import imageio
import math
cnt=0
sm=0
var=0

test = [1,2,3,4]

im = imageio.imread("HDR.jpg")
img = im.tolist()
imgsum = sum(img, [])
ls = [0 for i in range(256)]
for i in imgsum:
	ls[i]+=1

print(len(imgsum))

ls[0]=ls[0]/len(imgsum)
for i in range(1,256):
	ls[i]=ls[i-1]+ls[i]/len(imgsum)

for i in range(len(img)):
	for j in range(len(img[i])):
		im[i][j]=math.floor((256)*ls[im[i][j]])

imageio.imwrite('HDRCOM.jpg',im)


import imprimir
import bbcwebscrapper  # https://www.bbc.com/news/world
from tkinter import *

def sendUrl():
    url = url_entry.get()
    bbcwebscrapper.BBCWebScrapper(url)

janela = Tk()
janela.title("Webscrapper de Notícias")
janela.configure(background='#1e3743', highlightbackground='white', highlightthickness=3, highlightcolor='white')
janela.geometry("400x300+760+180")
janela.resizable(False,  False)
#janela.resizable(True, True)
#janela.maxsize(width= 900, height= 700)
#janela.minsize(width=400, height=300)

frame_1 = Frame(janela)
frame_1.configure(background='#d9d8da', highlightbackground='#adc1c9', highlightthickness=3,highlightcolor='#adc1c9')
frame_1.place(relx=0.1,rely=0.2, relwidth=0.8,relheight=0.2)

texto_url = Label(janela, text="Insira a URL no campo abaixo", font='Calibri, 11')
texto_url.configure(background='#1e3743', foreground='white')
texto_url.place(relx=0.24,rely=0.1)

url_entry = Entry(frame_1)
url_entry.configure(background='#d9d8da', selectbackground='black', selectforeground='white')
url_entry.place(relx=0,rely=0, relwidth=1,relheight=1)

botao_arquivo = Button(janela, text="Gerar Arquivo", command=sendUrl)
botao_arquivo.configure(background='#efe4b1')
botao_arquivo.place(relx=0.4,rely=0.5)

botao_imprimir = Button(janela, text="Imprimir", command=imprimir.Imprimir)
botao_imprimir.configure(background='#efe4b1', highlightbackground='#b1efe6', highlightthickness=2)
botao_imprimir.place(relx=0.43,rely=0.63)

janela.mainloop()


from uuid import UUID

from gql import gql
from gql.client import AsyncClientSession
from pydantic import BaseModel
from pydantic import parse_obj_as
from structlog import get_logger

from os2mo_init.config import ConfigFacet

logger = get_logger(__name__)

class Class(BaseModel):
    uuid: UUID
    user_key: str
    name: str
    scope: str | None

class Facet(BaseModel):
    uuid: UUID
    user_key: str
    classes: list[Class]

async def get_classes(graphql_session: AsyncClientSession) -> list[Facet]:
    """
    Get all classes in OS2mo.

    Args:
        graphql_session: MO GraphQL client session.

    Returns:
        List of Facets, which contain Classes.
    """
    logger.info("Getting classes")
    query = gql(
        """
        query ClassesQuery {
          facets {
            objects {
              current {
                uuid
                user_key
                classes {
                  uuid
                  user_key
                  name
                  scope
                }
              }
            }
          }
        }
    """
    )
    result = await graphql_session.execute(query)
    return parse_obj_as(
        list[Facet], [f["current"] for f in result["facets"]["objects"]]
    )

async def ensure_classes(
    graphql_session: AsyncClientSession,
    config_classes: dict[str, ConfigFacet],
) -> None:
    """Ensure that the given classes exists.

    Args:
        graphql_session: MO GraphQL client session.
        config_classes: Desired facets and their classes.
    """
    logger.info("Ensuring classes", classes=config_classes)

    existing_classes = await get_classes(graphql_session)
    logger.debug("Existing classes", existing=existing_classes)
    facet_uuids = {f.user_key: f.uuid for f in existing_classes}
    existing_classes_by_user_key = {
        f.user_key: {c.user_key: c for c in f.classes} for f in existing_classes
    }

    create_mutation = gql(
        """
        mutation CreateClassMutation(
          $facet_uuid: UUID!,
          $user_key: String!
          $name: String!,
          $scope: String!,
        ) {
          class_create(
            input: {
              facet_uuid: $facet_uuid,
              user_key: $user_key,
              name: $name,
              scope: $scope,
            }
          ) {
            uuid
          }
        }
        """
    )
    update_mutation = gql(
        """
        mutation UpdateClassMutation(
          $facet_uuid: UUID!,
          $uuid: UUID!,
          $user_key: String!,
          $name: String!,
          $scope: String!
        ) {
          class_update(
            uuid: $uuid
            input: {
              facet_uuid: $facet_uuid,
              user_key: $user_key
              name: $name,
              scope: $scope,
            }
          ) {
            uuid
          }
        }
    """
    )

    for facet_user_key, classes in config_classes.items():
        for class_user_key, class_data in classes.items():
            try:
                existing = existing_classes_by_user_key[facet_user_key][class_user_key]
            except KeyError:
                logger.info("Creating class", data=class_data)
                await graphql_session.execute(
                    create_mutation,
                    {
                        "facet_uuid": str(facet_uuids[facet_user_key]),
                        "user_key": class_user_key,
                        "name": class_data.title,
                        "scope": class_data.scope,
                    },
                )
                continue
            if existing.name != class_data.title or existing.scope != class_data.scope:
                logger.info("Updating class", data=class_data)
                await graphql_session.execute(
                    update_mutation,
                    {
                        "facet_uuid": str(facet_uuids[facet_user_key]),
                        "uuid": str(existing.uuid),
                        "user_key": class_user_key,
                        "name": class_data.title,
                        "scope": class_data.scope,
                    },
                )


# This is a Python version of the game Deal or No Deal.
import math
import random
import statistics
import time

import sqlite3 as sl
db = "dond.db"

id_list = []  # new id list

class datarow:
    # just a super class from which game and round inherit because both are types of data
    def __init__(self, game_id, player_id, game_mode):
        self.game_id = game_id
        self.player_id = player_id
        self.game_mode = game_mode

class game(datarow):
    """
    holds data about one played game
    """
    def __init__(self, game_id, player_id, game_mode, end_result, stop_round, winnings):
        super().__init__(game_id, player_id, game_mode)
        self.stop_round = stop_round
        self.end_result = end_result
        self.winnings = winnings

    def save(self):
        # append to data file
        # with open("played_data.txt", "a") as f_in:
        #     f_in.write(str(self.game_id) + "\t" + str(self.player_id) + "\t" + "\t" + str(self.game_mode) + "\t" +
        #                self.end_result + "\t" + str(self.stop_round) + "\t" + str(self.winnings) + "\n")
        # open a connection
        conn = sl.connect(db)
        # get a cursor
        curs = conn.execute("INSERT INTO games (game_id, player_id, game_mode, end_result, stop_round, winnings)"
                            f"VALUES ({self.game_id}, {self.player_id}, {self.game_mode}, '{self.end_result}', {self.stop_round}, {self.winnings})")
        conn.commit()
        curs.close()
        conn.close()

class _round(datarow):
    """
    holds data about one round played by a player
    """
    def __init__(self, game_id, player_id, game_mode, round, offer, remaining_cases):
        super().__init__(game_id, player_id, game_mode)
        self.round = round
        self.offer = offer
        self.remaining_cases = remaining_cases

    def save(self):
        # append to data file
        # with open("round_data.txt", "a") as f_in:
        #     f_in.write(str(self.game_id) + "\t" + str(self.player_id) + "\t" + "\t" + str(self.game_mode) + "\t" +
        #                str(self.round) + "\t" + str(self.bankers_offer) + "\t" + str(self.remaining_cases) + "\n")
        conn = sl.connect(db)
        curs = conn.execute("INSERT INTO rounds (game_id, player_id, game_mode, round, offer, remaining_cases)"
                            f"VALUES ({self.game_id}, {self.player_id}, {self.game_mode}, {self.round}, {self.offer}, '{self.remaining_cases}')")
        conn.commit()
        curs.close()
        conn.close()

class error(datarow):
    """
    holds data about a player's offer entry mistake
    """
    def __init__(self, game_id, player_id, game_mode, round, error_descr):
        super().__init__(game_id, player_id, game_mode)  # won't use game_mode
        self.round = round
        self.error_descr = error_descr

    def save(self):
        # # append to data file
        # with open("errors.txt", "a") as f_in:
        #     f_in.write(str(self.game_id) + "\t" + str(self.player_id) + "\t" + str(self.round) + "\t" +
        #                str(self.error_descr) + "\n")
        conn = sl.connect(db)
        stmt = "INSERT INTO errors (game_id, player_id, round, error_descr) " \
                f"VALUES ({self.game_id}, {self.player_id}, {self.round}, '{self.error_descr}')"
        curs = conn.execute(stmt)
        conn.commit()
        curs.close()
        conn.close()

def pick_case(case_id_list_display, game_id, player_id, game_mode, round):
    """
    this function returns a case chosen by the player
    :param case_id_list_display: list of cases left
    :return: chosen case
    """
    print("Enter a case:")
    keepAsking = True
    while keepAsking:
        case_choice = input("> ").strip() # remove whitespace
        if case_choice.isnumeric(): # if a number was entered
            case_choice = int(case_choice) # convert to int
            if case_choice < 1 or case_choice > 26: # outside case id range
                print("Please enter a valid number.")
                new_error = error(game_id, player_id, game_mode, round, "chose case #" + str(case_choice) + " not in range")
                new_error.save()
            else:
                if case_choice in case_id_list_display: # not in list of cases left
                    keepAsking = False
                    return case_choice
                else: # is not in list of cases left
                    print("Case", case_choice, "was already chosen.")
                    new_error = error(game_id, player_id, game_mode, round, "chose case #" + str(case_choice) + " not available")
                    new_error.save()
        else:
            new_error = error(game_id, player_id, game_mode, round, "chose case #" + str(case_choice) + " not numeric")
            new_error.save()
            print("Please enter a valid number.")

def remove_id_from_display(chosen_case, case_id_list_display):
    """
    This function replaces the case id in the display with a space
    :param chosen_case: id of case choen
    :param case_id_list_display:
    :return: nothing
    """
    for id in case_id_list_display: # go through every id in the list
        if id == chosen_case: # find the one that matches players_case
            if id < 10:
                case_id_list_display[case_id_list_display.index(id)] = " " # one char, one space
            else:
                case_id_list_display[case_id_list_display.index(id)] = "  " # 2 chars, 2 spaces

def remove_prize_from_display(chosen_case, list_of_prizes_display, case_values):
    """
    this function replaces prizes in the display with spaces
    :param chosen_case: case id
    :param list_of_prizes_display: the thing being displayed
    :param case_values: to match case id to prize value
    :return: none
    """
    value_to_remove = case_values[chosen_case] # whatever prize at the case id in the dictionary
    for prize in list_of_prizes_display: # loop through prizes in the display
        if prize == value_to_remove: # find the prize
            spacestring = ""
            for i in range(len(str(prize))):
                spacestring += " " # make the string the same number of characters as the prize it's replacing
            list_of_prizes_display[list_of_prizes_display.index(prize)] = spacestring # replace it with a space

def displayBoard(case_id_list_display, list_of_prizes_display):
    """
    This function prints the board and prizes left
    This was adapted from the function written by @DrewSkotarczak on replit
    :param case_id_list_display: list with case id's left
    :param list_of_prizes_display: list with prizes left
    :return: nothing
    """
    print("Board:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRemaining Prizes:")
    print(' -----      -----      -----      -----      -----      -----      ----- ')
    print('| ', case_id_list_display[0], ' |    | ', case_id_list_display[1], ' |    | ', case_id_list_display[2], ' |    | ',
    case_id_list_display[3], ' |    | ', case_id_list_display[4], ' |    | ', case_id_list_display[5], ' |    | ',
    case_id_list_display[6], ' |         ', list_of_prizes_display[0], '           ', list_of_prizes_display[13])
    print(' -----      -----      -----      -----      -----      -----      -----             ', list_of_prizes_display[1],
          '           ', list_of_prizes_display[14])
    print('                                                                                ', list_of_prizes_display[2],
          '          ', list_of_prizes_display[15])
    print('      -----      -----      ------     ------     ------     ------                 ', list_of_prizes_display[3],
          '          ', list_of_prizes_display[16])
    print('     | ', case_id_list_display[7], ' |    | ', case_id_list_display[8], ' |    | ', case_id_list_display[9], ' |   | ',
          case_id_list_display[10], ' |   | ', case_id_list_display[11], ' |   | ', case_id_list_display[12], ' |                ',
          list_of_prizes_display[4], '          ', list_of_prizes_display[17])
    print('      -----      -----      ------     ------     ------     ------                 ', list_of_prizes_display[5],
          '          ', list_of_prizes_display[18])
    print('                                                                                ', list_of_prizes_display[6],
          '         ', list_of_prizes_display[19])
    print(' ------     ------     ------     ------     ------     ------     ------          ', list_of_prizes_display[7],
          '         ', list_of_prizes_display[20])
    print('| ', case_id_list_display[13], ' |   | ', case_id_list_display[14], ' |   | ', case_id_list_display[15], ' |   | ',
          case_id_list_display[16], ' |   | ', case_id_list_display[17], ' |   | ', case_id_list_display[18], ' |   | ',
          case_id_list_display[19], ' |         ', list_of_prizes_display[8], '         ', list_of_prizes_display[21])
    print(' ------     ------     ------     ------     ------     ------     ------          ', list_of_prizes_display[9],
          '         ', list_of_prizes_display[22])
    print('                                                                                ', list_of_prizes_display[10],
          '         ', list_of_prizes_display[23])
    print('      ------     ------     ------     ------     ------     ------                ', list_of_prizes_display[11],
          '         ', list_of_prizes_display[24])
    print('     | ', case_id_list_display[20], ' |   | ', case_id_list_display[21], ' |   | ', case_id_list_display[22], ' |   | ',
          case_id_list_display[23], ' |   | ', case_id_list_display[24], ' |   | ', case_id_list_display[25], ' |               ',
          list_of_prizes_display[12], '        ', list_of_prizes_display[25])
    print('      ------     ------     ------     ------     ------     ------ ')

def displayPrizes(list_of_prizes_display):
    """
    This function prints the prizes left
    :param list_of_prizes_display: list with prizes left
    :return: nothing
    """
    print("Remaining Prizes:")
    print()
    print(list_of_prizes_display[0], '           ', list_of_prizes_display[13])
    print(list_of_prizes_display[1], '           ', list_of_prizes_display[14])
    print(list_of_prizes_display[2], '          ', list_of_prizes_display[15])
    print(list_of_prizes_display[3], '          ', list_of_prizes_display[16])
    print(list_of_prizes_display[4], '          ', list_of_prizes_display[17])
    print(list_of_prizes_display[5], '          ', list_of_prizes_display[18])
    print(list_of_prizes_display[6], '         ', list_of_prizes_display[19])
    print(list_of_prizes_display[7], '         ', list_of_prizes_display[20])
    print(list_of_prizes_display[8], '         ', list_of_prizes_display[21])
    print(list_of_prizes_display[9], '         ', list_of_prizes_display[22])
    print(list_of_prizes_display[10], '         ', list_of_prizes_display[23])
    print(list_of_prizes_display[11], '         ', list_of_prizes_display[24])
    print(list_of_prizes_display[12], '        ', list_of_prizes_display[25])
    print()

def fill_case_values(case_id_list, list_of_prizes, case_values):
    """
    randomly assigns each case id to a prize and saves it to case_values dictionary
    :param case_id_list: ints 1 to 26
    :param list_of_prizes: list of prizes
    :param case_values: empty dictionary
    :return: none
    """
    list_of_prizes_copy = [] # create a copy so that the prizes don't actually get removed from list_of_prizes
    for prize in list_of_prizes:
        list_of_prizes_copy.append(prize)
    for case_id in case_id_list: # go through every case id in the list
        value = random.choice(list_of_prizes_copy) # randomly select one of the prizes
        case_values[case_id] = value # assign that value to the case id
        list_of_prizes_copy.remove(value) # remove that value from the list of prizes so it doesn't get picked again

def eliminate_case(num_cases_to_eliminate, case_id_list_display, list_of_prizes_display, case_values, game_id, player_id, game_mode, round):
    """
    this function is called everytime the player chooses a case to remove from the board
    :param num_cases_to_eliminate: number of times a case will be chosen
    :param case_id_list_display: for display
    :param list_of_prizes_display: for display
    :param case_values: for display
    :return: none
    """
    print("You must choose ", num_cases_to_eliminate, "case(s) to eliminate this round")
    for i in range(num_cases_to_eliminate):  # do this num_cases_to_eliminate times
        eliminated_case = pick_case(case_id_list_display, game_id, player_id, game_mode, round)  # pick case
        print("You chose case # " + str(eliminated_case))
        print("Opening case:")
        drumroll()
        print("The", case_values[eliminated_case], "point prize has been eliminated from the board.")
        userinput = input("Press enter to continue.\n")
        # update displays:
        remove_id_from_display(eliminated_case, case_id_list_display)
        remove_prize_from_display(eliminated_case, list_of_prizes_display, case_values)
        if (num_cases_to_eliminate - 1 - i) != 0: # if that wasn't the last case to be chosen
            displayBoard(case_id_list_display, list_of_prizes_display)
            print("Choose", num_cases_to_eliminate - 1 - i, "more.")

def get_prizes_left(list_of_prizes_display):
    """
    This function creats a list of remaining prizes without the blank spaces
    :param list_of_prizes_display: list of remaining prizes with blank spaces
    :return: prizes_left, no blank spaces
    """
    prizes_left = []
    for prize in list_of_prizes_display: # go through display prize list
        if str(prize).isnumeric() or prize == 0.01: # if entry contains number (ie still in play)
            prizes_left.append(prize) # add to list
    return prizes_left

def get_bank_offer(list_of_prizes_display, game_mode, round):
    """
    This function calculates the banker's offer.
    :param list_of_prizes_display: list of prizes displayed
    :return: banker's offer
    """
    prizes_left = get_prizes_left(list_of_prizes_display)
    sum = 0
    for prize in prizes_left:
        sum += prize

    ev = sum / len(prizes_left)  # find average case value
    # basic 0.8 algorithm:
    if game_mode == 1:
        return int(ev*0.8)
    # banker's offer algorithm from Chen and John 2018
    elif game_mode == 2 or game_mode == 4:
        sd = statistics.pstdev(prizes_left)
        cv = sd/ev
        log10ev = math.log10(ev)
        log10bo = 0.195 + 0.991*log10ev - 0.057*cv - 0.037*len(prizes_left)
        bo = math.pow(10, log10bo)
        return int(bo)
    # constantly increase ratio
    else: # game mode 3
        ratio = 0.5 + round/20.0
        return int(ev*ratio)

def drumroll():
    # creates a little countdown for dramatic effect
    for i in range(3):
        time.sleep(0.25)
        print(".")
        time.sleep(0.25)

def create_id():
    """
    This function generates a number 10000-99999 as a unique game id.
    It checks if ID was used before.
    :return: a unique ID
    """
    # with open("played_data.txt", "r") as f_in: # from past game data
    #     for line in f_in: # loop through lines
    #         id = line[:5] # set id as first 5 characters of the line
    #         id_list.append(id)

    # TODO: retrieve list of all previously used id's
    conn = sl.connect(db)
    curs = conn.execute("SELECT game_id, player_id FROM games")
    cols = curs.fetchall()
    game_ids = [cols[i][0] for i in range(len(cols))]
    player_ids = [cols[i][1] for i in range(len(cols))]
    id_list = game_ids + player_ids

    generateNew = True # true if need to generate a new id
    while generateNew: # while id has been used
        id = random.randrange(10000, 100000)  # get a number 10000-99999
        if id in id_list:
            generateNew = True
        else: # unique id was generated
            return id
            generateNew = False # no need to generate another one

def early_round_eliminate_cases(r, case_id_list_display, list_of_prizes_display, case_values, game_id, player_id, game_mode):
    """
    eliminating cases during rounds 1-6
    :param r: round (int)
    :param case_id_list_display: list of cases for gui display
    :param list_of_prizes_display: list of prizes on right hand side
    :param case_values: dict w/case values
    :return: none
    """
    print("Round", r, "\n")
    if r < 6:  # first 5 rounds, when more than 1 case will have to be eliminated
        num_cases_to_eliminate = 7 - r  # number of cases decreases as rounds increase
    elif r >= 6:  # at round 6 and later
        num_cases_to_eliminate = 1  # only 1 to eliminate
    displayBoard(case_id_list_display, list_of_prizes_display)  # show board
    eliminate_case(num_cases_to_eliminate, case_id_list_display, list_of_prizes_display,
                   case_values, game_id, player_id, game_mode, r)  # remove needed cases

def get_player_offer(case_values, game_id, player_id, round):
    """
    obtains player offer
    :return: player offer (int)
    """
    userinput = input("You will make an offer to the banker. Press enter to continue.\n")
    print("Enter an offer for the banker. If the banker accepts, you will win whatever amount of points you have entered.\
    \nIf your offer is too high, the banker will reject your offer.")
    player_offer = input("> ")
    while not player_offer.isnumeric(): # while non-int
        print("Please enter an integer.")
        player_offer = input("> ")
    while (int(player_offer) > max(case_values.values())) or (int(player_offer) < min(case_values.values())):
        if int(player_offer) > max(case_values.values()): # greater than max possible prize
            new_error = error(game_id, player_id, 4, round, "player offer > max prize = " +
                              str(max(case_values.values())))
            new_error.save()
            print("Your offer must be less than the biggest prize left in play. Try again.")
            player_offer = input("> ")
        elif int(player_offer) < min(case_values.values()): # less than min possible prize
            new_error = error(game_id, player_id, 4, round, "player offer < min prize = " +
                              str(min(case_values.values())))
            new_error.save()
            print("Your offer must be greater than the smallest prize left in play. Try again.")
            player_offer = input("> ")
    return int(player_offer)

def deal(offer, case_values, players_case, game_id, player_id, r, game_mode):
    time.sleep(1)
    print("You won", offer, "points!")
    time.sleep(1)
    print("Your case contained", case_values[players_case])
    print()
    new_game = game(game_id, player_id, game_mode, "D", r, offer)  # create game object
    new_game.save()  # write that object into the file

def print_instructions(game_mode):
    print("\nHere's how the game works: \
    \nThere are 26 briefcases on the board. Each case contains an unknown amount of points,\n \
ranging from 0.01 to 1,000,000 points. An unopened case will look like this:")
    print(" ---- ")
    print("| 19 |")
    print(" ---- ")
    print("The remaining prizes will be displayed to the right of the cases.")
    print("Press enter to continue.")
    userinput = input("")
    print("At the very beginning, you will choose one case to be your case. \n\
You will not know what is in it until the end of the game.\n \
It will be labeled on the board with an asterisk:")
    print(" --- ")
    print("| * |")
    print(" --- ")
    print("Press enter to continue. ")
    userinput = input("") # ask something
    print("Every round, you will have to eliminate a number of cases from the board.\n\
The case will be opened, revealing the number of points it contained. By eliminating a\n\
case, you eliminate the possibility of winning that prize.\nPress enter to continue. ")
    userinput = input("")
    if game_mode == 4:
        print("PLAYER'S OFFER MODE: You will make an offer at the end of every round after\nyou have \
eliminated cases. The banker will choose to accept\nyour deal and you will win whatever \
amount you offered (at which point the game ends),\nor he will decline your offer, and you must continue \
eliminating more cases from the board.\nPress enter to continue")
        userinput = input("")
        print("When/if the banker accepts the your offer, you will\n \
also find out how much was in the case you originally chose.\nPress enter to continue. ")
        userinput = input("")
    else:
        print("BANKER'S OFFER MODE: The banker will make you an offer at the end of\nevery round after you have \
eliminated cases. You may either choose \nto accept his deal and walk away with whatever \
amount he offers (at which point the game ends), \nor you can decline his offer and continue \
eliminating more cases from the board.\nPress enter to continue")
        userinput = input("")
        print("When/if you accept the banker’s offer, you will \
also find out how much was in the case you originally chose.\nPress enter to continue. ")
        userinput = input("")
    print("If you keep eliminating cases until there is one left on the board, \nyou can choose \
to either walk away with the case you originally chose or \nswitch with the one left on the \
board. Whichever one you choose will contain your prize winnings. \
\nPress enter to start the game. ")
    userinput = input("")

def play(game_mode, first_time, player_id):
    print("Press enter to begin the ", end="")
    if first_time:
        print("first", end="")
    else:
        print("second", end="")
    print(" game.")
    userinput = input("")
    game_id = create_id()
    if game_mode == 1:
        print("You are now playing the banker's offer version")
        game_mode = random.randint(1, 3)  # pick from 3 algorithms to generate banker's offer
    elif game_mode == 2:
        print("You are now playing the player's offer version.")
        game_mode = 4 # no alg
    time.sleep(1)

    print_instructions(game_mode)

    # INITIALIZE STUFF

    # create a list of case id's
    case_id_list = []  # will contain ints 1-26
    case_id_list = [i for i in range(1, 27)] # populate with ints 1-26

    # create copy for display
    case_id_list_display = [case_id for case_id in case_id_list]
        # in this copy, the case id's will be replaced by spaces once chosen by the player

    list_of_prizes = [0.01, 1, 5, 10, 25, 50, 75, 100, 200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000,
                      100000, 200000, 300000, 400000, 500000, 750000, 1000000]
    case_values = {}  # dict with key = case_id, value=prize values
    fill_case_values(case_id_list, list_of_prizes, case_values)  # randomly populate cases

    list_of_prizes_display = []  # create a copy so that the prizes don't actually get removed from list_of_prizes
    for prize in list_of_prizes:
        list_of_prizes_display.append(prize)

    # player picks case
    displayBoard(case_id_list_display, list_of_prizes_display)
    print("Pick your case. You'll keep this case for the whole game.")
    players_case = pick_case(case_id_list_display, game_id, player_id, game_mode, 0)
    print("You chose case #", players_case, "\n")
    userinput = input("Press enter to begin.\n")
    if players_case < 10:
        case_id_list_display[case_id_list_display.index(players_case)] = "*"  # to distinguish it in display
    else:
        case_id_list_display[case_id_list_display.index(players_case)] = "* " # adjust for 2 digits
    remove_id_from_display(players_case, case_id_list_display)

    # START ROUNDS

    r = 1  # initialize round number
    gameOn = True  # stays true until player accepts deal or there is one case left
    while gameOn:
        if r < 10:
            early_round_eliminate_cases(r, case_id_list_display, list_of_prizes_display, case_values,
                                        game_id, player_id, game_mode)  # play rounds 1-6
            bank_offer = get_bank_offer(list_of_prizes_display, game_mode, r)  # obtain bank offer
            if game_mode == 4:  # player offer mode
                displayPrizes(list_of_prizes_display)
                player_offer = get_player_offer(case_values, game_id, player_id, r)  # obtain player offer
                offer = player_offer  # so it can be saved to a new round
                print("Banker deciding...")
                drumroll()
                if player_offer < bank_offer / 3:  # extremely low offer
                    # deal
                    print("Offer accepted.")
                    winnings = player_offer
                    gameOn = False  # stop looping through the rounds
                    deal(player_offer, case_values, players_case, game_id, player_id, r, game_mode)
                else:
                    # no deal
                    print("Offer rejected.")
                    time.sleep(1)
            else:  # bank offer mode
                displayPrizes(list_of_prizes_display)
                print("Banker making offer")
                drumroll()
                print("Offer:", bank_offer)
                offer = bank_offer  # so it can be saved to a new round
                dond = "m"  # get into while loop
                while dond != "1" and dond != "0":
                    dond = input("Deal or No Deal? Enter 1 for Deal. Enter 0 for No Deal.\n> ")
                    if dond == "1":
                        print("You chose Deal.")
                        winnings = bank_offer
                        gameOn = False  # stop looping through the rounds
                        deal(bank_offer, case_values, players_case, game_id, player_id, r, game_mode)
                    elif dond == "0":
                        print("You chose No Deal.")
                        userinput = input("Press enter to continue.\n")
                        displayBoard(case_id_list_display, list_of_prizes_display)
                    else:
                        new_error = error(game_id, player_id, game_mode, r, "entered neither 1 or 0 for DOND")
                        new_error.save()
                        print("Please enter either 1 or 0. ")
            # save new round data
            new_round = _round(game_id, player_id, game_mode, r, offer, get_prizes_left(list_of_prizes_display))
            new_round.save()
        else:
            # find last case:
            for case_id in case_id_list_display:
                if str(case_id).isnumeric():
                    lastcase = case_id
            print("There is 1 case left on the board, case # " + str(lastcase) + " . You chose case #", players_case,
                  "at the beginning.")
            print(
                "Do you wish to walk away with the amount in your case or switch it with case # " + str(lastcase) + "?")
            userswitch = "m"
            while userswitch != "1" and userswitch != "0":  # keep asking until user enters either 1 or 0
                userswitch = input("Enter 1 to switch or enter 0 to keep your case.\n> ")
                if userswitch == "1":
                    print("Switching cases...")
                    players_case = lastcase
                    print("Your case is now case # " + str(players_case))
                    winnings = case_values[players_case]
                    print("You won...")
                    drumroll()
                    print(winnings, "points!")
                    new_game = game(game_id, player_id, game_mode, "ND", r, winnings)  # create game object
                    new_game.save()  # write that object into the file
                    gameOn = False
                elif userswitch == "0":
                    print("You chose to keep your case.")
                    winnings = case_values[players_case]
                    print("You won...")
                    drumroll()
                    print(winnings, "points!")
                    new_game = game(game_id, player_id, game_mode, "ND", r, winnings)  # create game object
                    new_game.save()  # write that object into the file
                    gameOn = False
                else:
                    print("Please enter either 1 or 0.")
        r += 1
    print("You have finished playing the ", end="")
    if game_mode == 4:
        print("player's ", end="")
    else:
        print("banker's ", end="")
    print("offer mode. ")
    if first_time:
        print("You will now play the ", end="")
        if game_mode == 4:
            print("banker's ", end="")
        else:
            print("player's ", end="")
        print("offer mode. ")
        time.sleep(2)
    return winnings, game_id

def print_intro():
    print("\nWe thank you for participating in our study. \nToday you will play 2 modified versions of Deal or No Deal. \
Instructions on how to play will follow. \nClick the blank space below so that a blinking cursor appears and press enter to continue.")
    userinput = input("")
    print("Playing this game is voluntary, and you may stop at any time, though you will not receive\n\
compensation unless you reach the end of both games.\nPress enter to continue.")
    userinput = input("")
    print("In each game, you can win up to 1,000,000 points. Your final score will be divided by 100,000,\n\
converted to dollars, and added to your compensation for your participation.\nFor example, if you win a total \
of 623,211 points, you will be awarded an additional $6.23.\nPress enter to continue.")
    userinput = input("")
    print("Please do not refresh the web browser page or click the \"Stop\" button while you play.\
\nDoing so will cause you to lose your progress.\nPress enter to continue.")
    userinput = input("")

def main():
    # WELCOME
    print("Welcome to Deal or No Deal! Please zoom out in your browser (ctrl -) for a better display")
    time.sleep(1)
    print_intro()

    player_id = create_id()

    game_mode1 = random.randint(1, 2)  # randomly generate order in which to play
    if game_mode1 == 1:
        game_mode2 = 2
    elif game_mode1 ==2:
        game_mode2 = 1

    # play the games
    winnings1, game_id1 = play(game_mode1, True, player_id)
    winnings2, game_id2 = play(game_mode2, False, player_id)

    # concluding message.
    print("This concludes your participation in the study. Because you won", winnings1, "points during the first game\n\
and", winnings2, "in the second game for a total of", str(winnings1+winnings2), "points, you will be compensated\nan \
additional $" + str(round(0.00001*(winnings1+winnings2),2)) + ". Thanks for playing!")
    time.sleep(1)
    print("Your player ID was saved as", player_id, "and your game ID's were saved as", game_id1, "and", str(game_id2)
          + ". \nThese serve as confirmation that you have completed two games. ")

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 10:30:08 2017

@author: jbrugger
"""

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

#plotdata = [{"West" : [1,2,3,4,5]}, {"East" : [6,7,8,9,10]}]
plotdata = [[1,2,3,4,5], [6,7,8,9,10]]

ax.boxplot(plotdata)
plt.show()


help_message = 'Для того, чтобы изменить текущее состояние пользователя, ' \
               'отправь команду "/hand ,/stat, /conf"' \
               'Чтобы сбросить текущее состояние, отправь "/setstate".'

start_message = 'Привет!\n' + help_message
invalid_key_message = 'Ключ "{key}" не подходит.\n' + help_message
hand_mode_msg = 'Введите сумму'
stat_mode_msg = 'Статистика'
config_mode_msg = 'Настройки'
state_reset_message = 'Состояние успешно сброшено'
state_change_success_message = 'Текущее состояние успешно изменено'

MESSAGES = {
    'start': start_message,
    'help': help_message,
    'invalid_key': invalid_key_message,
    'hand_mode': hand_mode_msg,
    'stat': stat_mode_msg,
    'state_change': state_change_success_message,
    'config': config_mode_msg,
    'state_reset': state_reset_message,

}


#   Exercício Python 049 - Tabuada v.2.0
#   Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.

# cores
cor = {'azul': '\033[34m',
       'lilas': '\033[35m'}

n = int(input("Informe um número para ver sua tabuada: "))
print("{}-=".format(cor['lilas'])*7)

for i in range(1, 11):
    print("{}{} x {:2} = {:3}".format(cor['azul'], n, i, n * i))
    i += 1

print("{}-=".format(cor['lilas'])*7)


import glob

ip = set()

for file_name in glob.glob('C:\\Users\\am.bakin\\Documents\\!ОБУЧЕНИЕ\\Python\\config_files\\*.txt'):
    with open(file_name) as f:
        for line in f:
            if line.find("ip address")==1:
                ip.add(line.replace("ip address","").strip())

for i in ip:
    print(i)


# eulers_formula.py

"""
This program carries out a mathematical operation that cannot be done without
the complex number system, for this reason we need to import the cmath module
"""

# this module contains mathematics with complex numbers, for most cases
# just import math - but we need cmath here
import cmath

# the famous result of eulers formula with x = -1
# the formula uses a special type of number system called complex numbers,
# to use complex numbers we use functions from cmath
magic_number = cmath.exp(cmath.sqrt(-1) * cmath.pi)

# print out the result and notice how there are slight errors in the computation
print("A fancy maths equation euler discovered was e^i(pi) = "
      + str(magic_number))

# let's explain the little oddity in the results
print("Okay, this looks less fancy now, but the number is actually -1,"
      + "computers just don't have enough accuracy to deal with trancendental"
      + " numbers")


#%% Imported Libraries
import cv2
import numpy as np

#%% Functions
def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

def doEdges():
    edges = cv2.Canny(imGray,v1,v2)
    edges = cv2.cvtColor(edges,cv2.COLOR_GRAY2BGR)
    res = np.concatenate((im1,edges),axis = 1)
    cv2.imshow('Result',res)

def setVal1(val):
    global v1
    v1 = val
    doEdges()

def setVal2(val):
    global v2
    v2 = val
    doEdges()

if __name__ == '__main__' :
    #%% Preprocessing of the image

    im = cv2.imread(cv2.samples.findFile("lego-rot0-1a.jpg"))
    im1 = ResizeWithAspectRatio(im, width=500)
    im2 = cv2.bilateralFilter(im1,25,75,75)
    im3 = cv2.medianBlur(im2, 5)
    imGray = cv2.cvtColor(im3, cv2.COLOR_BGR2GRAY)

    #%% Adjust Canny-Thresholds interactively with Trackbar

    #initial values
    v1 = 0
    v2 = 0

    #create trackbar
    cv2.namedWindow('Result') #IMPORTANT: namedWindow before createTrackbar
    cv2.createTrackbar('Val1','Result',0,200,setVal1)
    cv2.createTrackbar('Val2','Result',0,200,setVal2)

    initIm = np.concatenate((im1,im1),axis = 1)
    cv2.imshow('Result',initIm)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import stat
from conans import ConanFile, tools, CMake, AutoToolsBuildEnvironment

class ZlibConan(ConanFile):
    name = "zlib"
    version = "1.2.11"
    homepage = "https://zlib.net/fossils"
    author = "Jean-Mathieu Vermosen"
    license = "Zlib"
    description = ("A Massively Spiffy Yet Delicately Unobtrusive Compression Library "
                  "(Also Free, Not to Mention Unencumbered by Patents)")
    settings = "os", "arch", "compiler", "build_type"
    options = {"shared": [True, False], "fPIC": [True, False]}
    default_options = "shared=False", "fPIC=True"
    exports = "LICENSE"
    exports_sources = ["CMakeLists.txt"]
    generators = ["cmake", "compiler_args"]
    _source_subfolder  = "src"

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        del self.settings.compiler.libcxx

    def source(self):
        tools.get("{}/{}-{}.tar.gz".format(self.homepage, self.name, self.version))
        os.rename("{}-{}".format(self.name, self.version), self._source_subfolder )
        if not tools.os_info.is_windows:
            configure_file = os.path.join(self._source_subfolder , "configure")
            st = os.stat(configure_file)
            os.chmod(configure_file, st.st_mode | stat.S_IEXEC)
        else:
            pass

    def build(self):
        with tools.chdir(self._source_subfolder ):
            for filename in ['zconf.h', 'zconf.h.cmakein', 'zconf.h.in']:
                tools.replace_in_file(filename,
                                      '#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */',
                                      '#if defined(HAVE_UNISTD_H) && (1-HAVE_UNISTD_H-1 != 0)')
                tools.replace_in_file(filename,
                                      '#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */',
                                      '#if defined(HAVE_STDARG_H) && (1-HAVE_STDARG_H-1 != 0)')
            tools.mkdir("_build")
            with tools.chdir("_build"):
                if not tools.os_info.is_windows:
                    env_build = AutoToolsBuildEnvironment(self)
                    if self.settings.arch in ["x86", "x86_64", "broadwell"] and self.settings.compiler in ["clang", "gcc"]:
                        env_build.flags.append('-mstackrealign')

                        if self.settings.arch == "broadwell":
                            env_build.flags.append('-mavx2')

                    # configure passes CFLAGS to linker, should be LDFLAGS
                    tools.replace_in_file("../configure", "$LDSHARED $SFLAGS", "$LDSHARED $LDFLAGS")
                    # same thing in Makefile.in, when building tests/example executables
                    tools.replace_in_file("../Makefile.in", "$(CC) $(CFLAGS) -o", "$(CC) $(LDFLAGS) -o")

                    env_build_vars = env_build.vars

                    # we need to build only libraries without test example and minigzip
                    if self.options.shared:
                        make_target = "libz.so.%s" % self.version
                    else:
                        make_target = "libz.a"
                    env_build.configure("../", build=False, host=False, target=False, vars=env_build_vars)
                    env_build.make(target=make_target)
                else:
                    cmake = CMake(self)
                    self.output.info("sources %s" % self.source_folder)
                    self.output.info("build %s" % self.build_folder)
                    cmake.configure(source_folder=os.path.join(self.source_folder, self._source_subfolder), build_folder=os.getcwd())
                    # we need to build only libraries without test example/example64 and minigzip/minigzip64
                    if self.options.shared:
                        make_target = "zlib"
                    else:
                        make_target = "zlibstatic"
                    print(os.getcwd())
                    cmake.build(target=make_target)

    def package(self):
        self.output.warn("local cache: %s" % self.in_local_cache)
        self.output.warn("develop: %s" % self.develop)
        # Extract the License/s from the header to a file
        with tools.chdir(os.path.join(self.source_folder, self._source_subfolder )):
            tmp = tools.load("zlib.h")
            license_contents = tmp[2:tmp.find("*/", 1)]
            tools.save("LICENSE", license_contents)

        # Copy the license files
        self.copy("LICENSE", src=self._source_subfolder , dst="licenses")

        # Copy pc file
        self.copy("*.pc", dst="", keep_path=False)

        # Copy headers
        # HAP tweak: gzguts.h is supposed to be an internal header
        for header in ["*zlib.h", "*zconf.h", "gzguts.h"]:
            self.copy(pattern=header, dst="include", src=self._source_subfolder , keep_path=False)
            self.copy(pattern=header, dst="include", src="_build", keep_path=False)

        # Copying static and dynamic libs
        build_dir = os.path.join(self._source_subfolder , "_build")
        lib_path = os.path.join(self.package_folder, "lib")
        suffix = "d" if self.settings.build_type == "Debug" else ""
        if self.settings.os == "Windows":
            if self.options.shared:
                self.output.warning("Not tested, probably bugged...")
                build_dir = os.path.join(self._source_subfolder , "_build")
                self.copy(pattern="*.dll", dst="bin", src=build_dir, keep_path=False)
                build_dir = os.path.join(self._source_subfolder , "_build/lib")
                self.copy(pattern="*zlibd.lib", dst="lib", src=build_dir, keep_path=False)
                self.copy(pattern="*zlib.lib", dst="lib", src=build_dir, keep_path=False)
                self.copy(pattern="*zlib.dll.a", dst="lib", src=build_dir, keep_path=False)
                current_lib = os.path.join(lib_path, "zlib%s.lib" % suffix)
                os.rename(current_lib, os.path.join(lib_path, "zlib.lib"))
            else:
                build_dir = os.path.join(os.getcwd(), self._source_subfolder)
                build_dir = os.path.join(build_dir, "_build")
                build_dir = os.path.join(build_dir, str(self.settings.build_type))
                self.copy(pattern="zlibstaticd.lib", dst="lib", src=build_dir, keep_path=False)
                self.copy(pattern="zlibstatic.lib", dst="lib", src=build_dir, keep_path=False)
                current_lib = os.path.join(lib_path, "zlibstatic%s.lib" % suffix)
                os.rename(current_lib, os.path.join(lib_path, "zlib.lib"))
        else:
            if self.options.shared:
                self.copy(pattern="*.so*", dst="lib", src=build_dir, keep_path=False, symlinks=True)
            else:
                self.copy(pattern="*.a", dst="lib", src=build_dir, keep_path=False)

    def package_info(self):
        if self.settings.os == "Windows" and not tools.os_info.is_linux:
            self.cpp_info.libs.append('zlib')
        else:
            self.cpp_info.libs.append('z')


import numpy as np
import matplotlib.pyplot as plt

from exp_fam_lik_normal_fixed_var import (
    calc_likelihood_sufficient_statistics_ND,
    calc_likelihood_reference_measure_N)

from exp_fam_prior_normal_fixed_var import (
    ExpFamPrior_NormalFixedVariance, calc_prior_cumulant)

from scipy.special import logsumexp

def calc_ELBO_per_token(h_N, sx_ND, resp_NK, qdist_list, prior_dist, after_mstep=True):
    _, K = resp_NK.shape
    N, D = sx_ND.shape

    stats_dict = estep__update_summary_stats_dict(sx_ND, resp_NK)

    unif_pi_K = 1.0/K * np.ones(K)
    L_alloc = (
        np.dot(stats_dict['N_K'], unif_pi_K)
        )
    L_entropy = np.sum(stats_dict['H_K'])
    L_obs = (
        np.sum(h_N)
        - K * prior_dist.calc_cumulant()
        + np.sum([q_dist_k.calc_cumulant() for q_dist_k in qdist_list])
        )
    if not after_mstep:
        for k in range(K):
            nu_diff = stats_dict['N_K'][k] + prior_dist.nu_1[0] - qdist_list[k].nu_1[0]
            tau_diff_D = stats_dict['S_KD'][k] + prior_dist.tau_D - qdist_list[k].tau_D

            L_obs += nu_diff * qdist_list[k].calc_E_negative_c_of_phi()
            L_obs += np.dot(tau_diff_D, qdist_list[k].calc_E_phi_D())

    assert np.isscalar(L_alloc)
    assert np.isscalar(L_obs)
    return (L_alloc + L_entropy + L_obs) / (N * D)

def estep__update_resp_NK(sx_ND, qdist_list):

    logpdf_x_NK = np.zeros((N, K))
    for k in range(K):
        E_phi_k_D = qdist_list[k].calc_E_phi_D()
        E_negative_cumulant_k = qdist_list[k].calc_E_negative_c_of_phi()
        logpdf_x_NK[:,k] = np.dot(sx_ND, E_phi_k_D) + E_negative_cumulant_k

    logpdf_x_NK -= logsumexp(logpdf_x_NK, axis=1)[:,np.newaxis]
    resp_NK = logpdf_x_NK
    np.exp(resp_NK, out=resp_NK)
    assert np.allclose(np.sum(resp_NK, axis=1), 1.0)
    return resp_NK

def estep__update_summary_stats_dict(sx_ND, resp_NK, stats_dict=None):
    if stats_dict is None:
        stats_dict = dict()
    stats_dict['N_K'] = np.sum(resp_NK, axis=0)
    stats_dict['S_KD'] = np.dot(resp_NK.T, sx_ND)
    stats_dict['H_K'] = -1 * np.sum(resp_NK * np.log(1e-100 + resp_NK), axis=0)
    return stats_dict

def mstep__update_q(stats_dict, prior_dist):
    qdist_list = list()
    for k in range(K):
        qdist_k = ExpFamPrior_NormalFixedVariance(
            tau_D=stats_dict['S_KD'][k] + prior_dist.tau_D,
            nu_1=stats_dict['N_K'][k] + prior_dist.nu_1,
            v_D=prior_dist.v_D,
            )
        qdist_list.append(qdist_k)
    return qdist_list

def run_coordinate_ascent(data_ND, prior_dist,
        init_resp_NK=None, K=10,
        n_iters=100, random_state=0):
    N, D = data_ND.shape

    ## Randomly assign a few data points to given clusters K
    if init_resp_NK is None:
        prng = np.random.RandomState(random_state)
        chosen_ids_K = prng.choice(np.arange(N), K)

        init_resp_NK = np.zeros((N,K))
        for k in range(K):
            init_resp_NK[chosen_ids_K[k], :] = 0.01
            init_resp_NK[chosen_ids_K[k], k] = 1.00 - 0.01 * (K-1)

    h_N = calc_likelihood_reference_measure_N(data_ND, prior_dist.v_D)
    sx_ND = calc_likelihood_sufficient_statistics_ND(data_ND, prior_dist.v_D)

    # Initialize other parameters just by running updates from the given resp
    stats_dict = estep__update_summary_stats_dict(sx_ND, init_resp_NK)
    qdist_list = mstep__update_q(stats_dict, prior_dist)

    elbo_history = list()

    for iterid in range(n_iters):

        resp_NK = estep__update_resp_NK(sx_ND, qdist_list)
        elbo = calc_ELBO_per_token(
            h_N, sx_ND, resp_NK, qdist_list, prior_dist, after_mstep=False)
        elbo_history.append(elbo)
        print("%4d/%d after estep % 11.6f" % (iterid, n_iters, elbo))
        if len(elbo_history) >= 2:
            assert (elbo_history[-1] - elbo_history[-2]) >= -1e-8

        stats_dict = estep__update_summary_stats_dict(sx_ND, resp_NK, stats_dict)
        qdist_list = mstep__update_q(stats_dict, prior_dist)
        elbo = calc_ELBO_per_token(
            h_N, sx_ND, resp_NK, qdist_list, prior_dist, after_mstep=True)
        elbo_history.append(elbo)
        print("%4d/%d after mstep % 11.6f" % (iterid, n_iters, elbo))

        if len(elbo_history) >= 2:
            assert (elbo_history[-1] - elbo_history[-2]) >= -1e-8

    return (resp_NK, stats_dict, qdist_list), elbo_history

if __name__ == '__main__':
    prng = np.random.RandomState(0)

    K = 3
    D = 2
    true_v_D = np.asarray([0.15, 0.3])

    os_KD = prng.choice(np.asarray([-1.0, +1.0]), size=K*D, replace=True).reshape((K,D))
    true_phi_KD = np.asarray([1.337, -2.0, 3.0]).reshape((K, 1)) * os_KD

    N = 3000
    data_list = list()
    for k in range(K):
        data_k_ND = (
            true_phi_KD[k][np.newaxis,:]
            + true_v_D[np.newaxis,:] * prng.randn(N//K, D))
        data_list.append(data_k_ND)
    data_ND = np.vstack(data_list)

    prior_dist = ExpFamPrior_NormalFixedVariance(
        nu_1=0.25, tau_D=1.0 * np.ones(D), v_D=true_v_D)

    elbo_history_list = list()
    config_list = list()
    for run in range(25):
        final_config, elbo_history = run_coordinate_ascent(
            data_ND, prior_dist,
            K=K,
            n_iters=50, random_state=np.random.randint(100))
        elbo_history_list.append(elbo_history)
        config_list.append(final_config)

    fig, ax = plt.subplots(nrows=1, ncols=1)
    elbo_SR = np.vstack(elbo_history_list).T
    ax.plot(elbo_SR)

    ymax = elbo_SR.max()
    ymin = elbo_SR[-1,:].min()
    R = ymax - ymin
    ax.set_ylim(ymin - R, ymax + 0.1 * R)
    ax.set_xlabel('number of update iterations')
    ax.set_ylabel('log p(x) per token')

    fig, ax = plt.subplots(nrows=5, ncols=5, sharex=True, sharey=True)
    for row in range(5):
        for col in range(5):
            ax[row, col].plot(data_ND[:,0], data_ND[:,1], 'k.', alpha=0.1)

            k = 5 * row + col
            _, _, q_list = config_list[k]
            for k in range(K):
                E_phi_k_D = q_list[k].calc_E_phi_D()
                ax[row, col].plot(E_phi_k_D[0], E_phi_k_D[1], '+')

    plt.show()


#2021-10-13 10:15:15.250000+00:00
"""Given a Sudoku data structure with size `NxN, N > 0 and √N == integer`, write a method to validate if it has been filled out correctly.

The data structure is a multi-dimensional Array, i.e:
```
[
  [7,8,4,  1,5,9,  3,2,6],
  [5,3,9,  6,7,2,  8,4,1],
  [6,1,2,  4,3,8,  7,5,9],

  [9,2,8,  7,1,5,  4,6,3],
  [3,5,7,  8,4,6,  1,9,2],
  [4,6,1,  9,2,3,  5,8,7],

  [8,7,6,  3,9,4,  2,1,5],
  [2,4,3,  5,6,1,  9,7,8],
  [1,9,5,  2,8,7,  6,3,4]
]
```

**Rules for validation**

- Data structure dimension: `NxN` where `N > 0` and `√N == integer`
- Rows may only contain integers: `1..N (N included)`
- Columns may only contain integers: `1..N (N included)`
- *'Little squares'* (`3x3` in example above) may also only contain integers: `1..N (N included)`
"""

from math import sqrt
from itertools import chain

class Sudoku(object):
    def __init__(self, data):
        self.data = data
    def is_valid(self):
        length = len(self.data)
        root = int(sqrt(length))
        if not all(len(row) == length for row in self.data) \
        or not all((type(i) == int and i in range(1, length + 1) for i in chain(*(self.data)))):
            return False
        else:
            for i in range(0,length):
                if len(set(self.data[i])) != length:
                    return False
                if len(set([nr[i] for nr in self.data])) != length:
                    return False
            for i in range(0, length, root):
                for j in range(0,length, root):
                    if len(set(chain(*(self.data[i+k][j:j+root] for k in range(root))))) != length:
                        return False
            return True


import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

"""
    Calculate IC, IC025, PRR and ROR values from the contingency tables for each sex
"""

def get_ic(a, b, c, d):
    aexp = ((a + b) * (a + c)) / (a + b + c + d)
    ic = np.log2(((a + 0.5) / (aexp + 0.5)))
    IC025 = ic - 3.3 * np.power((a + 0.5), (-1/2)) - 2 * np.power((a + 0.5), (-3/2))
    #print(['IC', ic, IC025])
    return ic, IC025

def get_prr(a, b, c, d):
    prr = (a/(a + c)) / (b/(b + d)) # from mdpi paper
    #prr = (a / (a+b)) / (c/(c+d))
    #print(['PRR', prr, prr2])
    return prr

def get_ror(a, b, c, d):
    ROR = (a*d) / (b*c)
    #print(['ROR', ROR])
    return ROR

def main():
    df_m = pd.read_csv('C:\\Users\\TARIQOPLATA\\PycharmProjects\\FAERS_final\\create_dataset\\contingency_table_HP_M.csv')
    df_f = pd.read_csv('C:\\Users\\TARIQOPLATA\\PycharmProjects\\FAERS_final\\create_dataset\\contingency_table_HP_F.csv')
    dis_m = pd.DataFrame(columns=['DRUG', 'AE', 'IC', 'IC025', 'PRR', 'ROR', 'Reports'])
    dis_f = pd.DataFrame(columns=['DRUG', 'AE', 'IC', 'IC025', 'PRR', 'ROR', 'Reports'])
    i = 0
    for index, row in df_m.iterrows():
        if row['A'] == 0:
            continue
        if row['B'] == 0:
            continue
        print([row['A'], row['B'], row['C'], row['D'], row['DRUG'], row['AE']])
        prr = get_prr(row['A'], row['B'], row['C'], row['D'])
        ic, ic025 = get_ic(row['A'], row['B'], row['C'], row['D'])
        ror = get_ror(row['A'], row['B'], row['C'], row['D'])
        #bpcn = get_bpcn(row['A'], row['B'], row['C'], row['D'])
        df_new = pd.DataFrame([{'DRUG': row['DRUG'], 'AE': row['AE'], 'IC': ic, 'IC025': ic025, 'PRR': prr,
                                'ROR': ror, 'Reports': row['A']}])
        dis_m = pd.concat([dis_m, df_new], axis=0, ignore_index=True)
        #dis_m = dis_m.append({'DRUG': row['DRUG'], 'AE': row['AE'], 'IC': ic, 'IC025': ic025,
        #                      'PRR': prr, 'ROR': ror, 'Reports': row['A']}, ignore_index=True)
        i += 1
        #print(i)
        if i == 1000:
            print(dis_m)
    print('MALE DONE')
    dis_m.to_csv('Disproportionate_analysis_male_HP.csv')
    for index, row in df_f.iterrows():
        if row['A'] == 0:
            continue
        if row['B'] == 0:
            continue
        prr = get_prr(row['A'], row['B'], row['C'], row['D'])
        ic, ic025 = get_ic(row['A'], row['B'], row['C'], row['D'])
        ror = get_ror(row['A'], row['B'], row['C'], row['D'])
        #bpcn = get_bpcn(row['A'], row['B'], row['C'], row['D'])
        df_new = pd.DataFrame([{'DRUG': row['DRUG'], 'AE': row['AE'], 'IC': ic, 'IC025': ic025, 'PRR': prr,
                                'ROR': ror, 'Reports': row['A']}])
        dis_f = pd.concat([dis_f, df_new], axis=0, ignore_index=True)
        #dis_f = dis_f.append({'DRUG': row['DRUG'], 'AE': row['AE'], 'IC': ic, 'IC025': ic025,
        #                      'PRR': prr, 'ROR': ror, 'Reports': row['A']}, ignore_index=True)
    print('FEMALE DONE')
    dis_f.to_csv('Disproportionate_analysis_female_HP.csv')

if __name__ == '__main__':
    main()


"""
Zmodyfikowana dijkstra. Relaksujemy najpierw po długości a następnie (jeżeli porównywane długości są sobie równe)
relaksujemy po ilości krawędzi do tego wierzchołka od wierzchołka s.
"""

import queue

def sciezki(G: list[list[tuple[int, int]]], s: int, e: int) -> list[int]:
    V = len(G)
    q = queue.PriorityQueue()
    visited = [False for _ in range(V)]
    parent = [-1 for _ in range(V)]
    distance = [10**5 for _ in range(V)]
    edges = [-1 for _ in range(V)]
    q.put((0, s))
    distance[s] = 0
    edges[s] = 0
    while not q.empty():
        value, current = q.get()  # value is not used
        if not visited[current]:
            for v, w in G[current]:
                if distance[current] + w < distance[v]:  # relaxation
                    distance[v] = distance[current] + w
                    edges[v] = edges[current] + 1
                    parent[v] = current
                    q.put((distance[v], v))
                elif distance[current] + w == distance[v]:
                    if edges[current] + 1 < edges[v]:
                        edges[v] = edges[current] + 1
                        parent[v] = current
        visited[current] = True
    print(distance)
    print(edges)

if __name__ == "__main__":
    G = [[(1, 6), (9, 1), (2, 4), (5, 2)],
         [(7, 5), (0, 6), (8, 3)],
         [(0, 4), (3, 5)],
         [(2, 5), (4, 4), (5, 12)],
         [(3, 4), (6, 4), (5, 7)],
         [(0, 2), (3, 12), (6, 3), (4, 7)],
         [(5, 3), (4, 4)],
         [(8, 3), (1, 5)],
         [(7, 3), (10, 2), (1, 3)],
         [(10, 2), (0, 1)],
         [(8, 2), (9, 2)]]
    print(sciezki(G, 0, 8))

zadania z bit/bit 8/5_superfajne_sciezki.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

INPUT_FILE = 'input.txt'

def get_path(orbits, start, to='COM'):
    path = []
    item = orbits[start]
    while item != to:
        path.append(item)
        item = orbits[item]
    return list(reversed(path))

def get_same_count(path_1, path_2):
    for count, pair in enumerate(zip(path_1, path_2)):
        if pair[0] != pair[1]:
            break
    return count

def main():
    with open(INPUT_FILE, 'r') as fp:
        lines = [x.strip().split(')') for x in fp]
    orbits = {val: key for key, val in lines}
    you_path = get_path(orbits, 'YOU')
    san_path = get_path(orbits, 'SAN')
    same_count = get_same_count(you_path, san_path)
    print(same_count)
    print(len(you_path[same_count:]) + len(san_path[same_count:]))

if __name__ == '__main__':
    main()


from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.core.paginator import Paginator

#추가
from .recommend_process import *
import os

def get_songs(my_songs, tag_list, sample_index):
    if len(my_songs) == 0:
        my_songs_df = []
        return my_songs_df
    train_data_appended = settings.TRAIN_DATA.copy()
    train_data_appended = train_data_appended.loc[sample_index]
    train_data_appended = train_data_appended.reset_index(drop=True)
    user_row = [tag_list, my_songs, 1]
    user_row_df = pd.DataFrame([user_row], columns=['tags', 'song_id', 'like_cnt'])
    train_data_appended = pd.concat([train_data_appended, user_row_df], ignore_index=True)

    train_data_sample = train_data_appended.copy()
    train_data_sample = train_data_sample.explode('song_id', ignore_index=True)
    train_dict = dict()

    for i in range(len(train_data_sample)):
        song = train_data_sample['song_id'][i]
        tag = train_data_sample['tags'][i]
        if song in train_dict:
            for j in tag:
                train_dict[song].add(j)
        else:
            train_dict[song] = set(tag)

    train_data_sample.drop_duplicates(subset='song_id', keep='first', inplace=True)

    for i in range(len(train_data_sample)):
        song = train_data_sample['song_id'].iloc[i]
        train_data_sample['tags'].iloc[i] = list(train_dict[song])

    song_data = settings.SONG_DATA.copy()
    song_data.rename(columns={'id': 'song_id', 'song_gn_dtl_gnr_basket': 'gnr'}, inplace=True)
    song_data = song_data.astype({'issue_date': 'int64'})
    song_tag_appended = pd.merge(train_data_sample, song_data)
    song_tag_appended = song_tag_appended.astype({'song_id': 'int64'})
    my_songs_df = song_tag_appended[song_tag_appended['song_id'].isin(my_songs)]
    print(my_songs_df)
    return my_songs_df.values.tolist()
#추가
@csrf_exempt
def clear_session(request):
    if 'tag_clear' in request.POST and 'tag_list' in request.session:
        del request.session['tag_list']
    elif 'song_clear' in request.POST and 'selected_song_ids' in request.session:
        del request.session['selected_song_ids']
        #request.session['selected_song_ids'] = [394031,195524,540149,287984,440773,100335,556301,655561,534818,695032,516602,521739,97057,703323,295250,25155,24275,273672,334095]
    elif 'sample_clear' in request.POST:
        train_data = settings.TRAIN_DATA
        temp_df = train_data.sample(n=100)
        print('==============New Samples================')
        print(temp_df)
        print('=========================================')
        request.session['samples'] = temp_df.reset_index().to_json(orient='records')
    song_list = request.session.get('selected_song_ids', [])
    #print(song_list)
    tag_list = request.session.get('tag_list', [])

    train_data_json = request.session.get('samples')
    train_data_sample = pd.read_json(train_data_json, orient='records')
    sample_index = train_data_sample['index'].to_list()
    my_songs_df = get_songs(song_list, tag_list, sample_index)
    return render(request, 'polls/recommend.html', {'my_tags': tag_list, 'my_songs': song_list})

def recommend(request):
    if request.method == 'POST':
        tag_list = request.session.get('tag_list', [])
        song_list = request.session.get('selected_song_ids', [])
        song_data = settings.SONG_DATA
        train_data_json = request.session.get('samples')
        train_data_sample = pd.read_json(train_data_json, orient='records')
        sample_index = train_data_sample['index'].to_list()
        selected_checkboxes = request.POST.getlist('checkboxes')
        if len(selected_checkboxes) == 0:
            print("Empty Checkbox")
        prepro_para = [0, False, False, 'cv']
        para_output = ""
        for checkbox in selected_checkboxes:
            if checkbox == 'kor':
                para_output += "한국어 전처리, "
                prepro_para[0] = 1
            elif checkbox == 'eng':
                para_output += "영어 전처리, "
                prepro_para[0] = 2
            elif checkbox == 'tag_imb':
                para_output += "태그 불균형 처리, "
                prepro_para[1] = True
            elif checkbox == 'gnr_imb':
                para_output += "장르 불균형 처리, "
                prepro_para[2] = True
            elif checkbox == 'gnr_cv_tf':
                para_output += "장르 임베딩 방식 전환(TF), "
                prepro_para[3] = 'tf'
            print(f'Selected checkbox: {checkbox}')
        if len(para_output) != 0:
            para_output = para_output[:len(para_output) - 2]
        #recommend_res = song_data[song_data['id'].isin(pred_list)].values.tolist()
        if prepro_para[0] == 1:
            pred_df = main_process_kor(sample_index, tag_list, song_list, prepro_para)
        elif prepro_para[0] == 2:
            pred_df = main_process_eng(sample_index, tag_list, song_list, prepro_para)
        else:
            pred_df = main_process_no(sample_index, tag_list, song_list, prepro_para)
        print(pred_df)
        recommend_res = pred_df.values.tolist()
        eval_list = []
        precision_k = get_precision_k(song_list, pred_df['song_id'].tolist())
        eval_list.append(precision_k)
        my_songs_df = get_songs(song_list, tag_list, sample_index)
        #임시
        #recommend_res = song_data[song_data['id'].isin(song_list)].values.tolist()

    return render(request, 'polls/recommend.html', {'recommend_res': recommend_res, 'my_tags': tag_list, 'my_songs_df': my_songs_df, 'eval_list': eval_list, 'para_output': para_output})

@csrf_exempt
def recommend_music(request):
    tag_list = request.session.get('tag_list', [])
    song_list = request.session.get('selected_song_ids', [])

    train_data_json = request.session.get('samples')
    train_data_sample = pd.read_json(train_data_json, orient='records')
    sample_index = train_data_sample['index'].to_list()
    # 추가
    if request.method == 'POST':
        if 'tag_name' in request.POST:
            tag_name = request.POST.get('tag_name', '').split(',')
            tag_list = request.session.get('tag_list', [])
            tag_list.extend(tag_name)
            request.session['tag_list'] = list(set(tag_list))
            print(request.session.get('tag_list', []))
            my_songs_df = get_songs(song_list, tag_list, sample_index)
            return render(request, 'polls/recommend.html', {'my_tags': tag_list, 'my_songs_df': my_songs_df})

        song_name = request.POST.get('song_name', '')
        # 노래 이름을 사용하여 검색 결과를 데이터베이스에서 가져옴
        song_data = settings.SONG_DATA
        search_results = song_data[song_data['song_name'].str.contains(song_name, case=False, na=False)]
        #search_results = search_results.to_json(orient='records')
        print(search_results)
        selected_song_ids = request.session.get('selected_song_ids', [])  # 기존 선택한 노래 ID 리스트를 가져옴
        search_results = search_results.values.tolist()

        if 'selected_song' in request.POST:
            selected_song_id = int(request.POST['selected_song'])
            if selected_song_id in selected_song_ids:
                return render(request, 'polls/recommend.html' , {'my_tags': tag_list, 'my_songs': song_list})

            # 선택한 노래 ID를 리스트에 추가

            selected_song_ids.append(selected_song_id)

            # 세션에 선택한 노래 ID 리스트를 저장
            request.session['selected_song_ids'] = selected_song_ids
            print(selected_song_ids)

            # 여기에서 선택한 노래 ID를 사용하여 추가 작업을 수행
            # 선택한 노래 ID(selected_song_id)를 활용하여 추천된 음악을 찾거나 처리
            song_list = request.session.get('selected_song_ids', [])
            my_songs_df = get_songs(song_list, tag_list, sample_index)
            return render(request, 'polls/recommend.html', {'my_tags': tag_list, 'my_songs_df': my_songs_df})
        my_songs_df = get_songs(song_list, tag_list, sample_index)
        return render(request, 'polls/recommend.html', {'search_results': search_results, 'my_tags': tag_list, 'my_songs_df': my_songs_df})
    my_songs_df = get_songs(song_list, tag_list, sample_index)
    return render(request, 'polls/recommend.html', {'my_tags': tag_list, 'my_songs_df': my_songs_df})


word = "secret"

# list to store guess letter or _ underscore
guesses = []

# number of lives
lives = 7

# setting end of game
end_of_game = False

while not end_of_game:
    for letter in word:
        if letter in guesses:
            print(letter,end=" ")
        else:
            print('_',end=" ")
    print('')

    guess = input(f"Lives left {lives}, Guess the letter : ")
    guesses.append(guess)

    if guess not in word:
        lives -= 1
        if lives == 0:
            break

    end_of_game = True

    for letter in word:
        if letter not in guesses:
            end_of_game = False

if end_of_game:
    print("You found the word it was {}".format(word))
else:
    print("Game Over, The word was {}".format(word))


import datetime
import json
from decimal import Decimal

from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import ListView

from store.models import Product, Order, OrderItem, Customer, ShippingAddress

class ProductListView(ListView):
    model = Product

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            customer, created = Customer.objects.get_or_create(user=request.user)
            customer.save()
            return super().get(request, *args, **kwargs)

def cart_view(request, *args, **kwargs):
    order_items = OrderItem.objects.filter(order__customer__user=request.user)
    order = Order.objects.get(customer=request.user.customer)
    return render(request, 'store/cart.html', context={'order_items': order_items, 'order': order})

def checkout_view(request, *args, **kwargs):
    order_items = OrderItem.objects.filter(order__customer__user=request.user)
    order = Order.objects.get(customer=request.user.customer)
    return render(request, 'store/checkout.html', context={'order_items': order_items, 'order': order})

def update_cart_view(request, *args, **kwargs):
    data = json.loads(request.body)
    product_id, action = data['productId'], data['action']
    if request.user.is_authenticated:
        order, created = Order.objects.get_or_create(customer=request.user.customer)
        order_item, created = OrderItem.objects.get_or_create(order=order, product_id=product_id)
        if action == 'add':
            order_item.quantity += 1
        elif action == 'remove':
            order_item.quantity -= 1
        order_item.save()
        if order_item.quantity == 0:
            order_item.delete()
    return JsonResponse('We receive data on the back-end', safe=False)

def process_order_view(request, *args, **kwargs):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, is_completed=False)
        total = Decimal(data['user_form']['total'])
        order.transaction_id = transaction_id

        if total == order.get_total_price:
            order.is_completed = True
        order.save()
        if order.need_shipping:
            ShippingAddress.objects.create(customer=customer, order=order, address=data['shipping_form']['address'],
                                           city=data['shipping_form']['city'], state=data['shipping_form']['state'],
                                           zip_code=data['shipping_form']['zipCode'])
    else:
        print('User is not logged in')
    return JsonResponse('Payment complete', safe=False)


# https://www.geeksforgeeks.org/subarray-whose-sum-is-closest-to-k/
# Question : Given an array of positive and negative integers and an integer K. The task is
# to find the subarray which has its sum closest to k. In case of multiple answers,
# print anyone. Closest here means abs(sum-k) should be minimal.
#
# Input: a = [-5, 12, -3, 4, -15, 6, 1 ], K = 2
# Output: 1
# The subarray [-3, 4] or [1] has sum = 1 which is the closest to K.
#
# Question Type : Asked
# Used : Sort the given array
#        Use two pointers, start and end set at 0.
#        If sum is less than target, increment start.
#        If sum is more than target, increment end.
#        Maintain min diff : abs(curr_sum - k)
# Complexity : O(n log n)

def subarray_closest_sum(arr, k):
    n = len(arr)
    # Initialize start and end pointers, current sum, and minimum difference
    start = 0
    end = 0
    arr_1 = sorted(arr)
    curr_sum = arr_1[0]
    min_diff = float('inf')
    # Initialize the minimum difference between the subarray sum and K
    min_diff = abs(curr_sum - k)

    closest_sum = curr_sum
    # Traverse through the array
    while end < n - 1 and start < n - 1:
        # If the current sum is less than K, move the end pointer to the right
        if curr_sum < k:
            end += 1
            curr_sum += arr_1[end]
        # If the current sum is greater than or equal to K, move the start pointer to the right
        else:
            curr_sum -= arr_1[start]
            start += 1

        # Update the minimum difference between the subarray sum and K
        if abs(curr_sum - k) < min_diff:
            min_diff = abs(curr_sum - k)
            closest_sum = curr_sum

    return closest_sum

if __name__ == "__main__":
    arr = [-5, 12, -3, 4, -15, 6, 1]
    k = 2
    print(subarray_closest_sum(arr, k))

    arr = [-46, 44, -90]
    k = -90
    print(subarray_closest_sum(arr, k))


"""Contains UI methods for Nginx operations."""
import logging
from typing import Iterable
from typing import List
from typing import Optional

from certbot.display import util as display_util
from certbot_nginx._internal.obj import VirtualHost

logger = logging.getLogger(__name__)

def select_vhost_multiple(vhosts: Optional[Iterable[VirtualHost]]) -> List[VirtualHost]:
    """Select multiple Vhosts to install the certificate for
    :param vhosts: Available Nginx VirtualHosts
    :type vhosts: :class:`list` of type `~obj.Vhost`
    :returns: List of VirtualHosts
    :rtype: :class:`list`of type `~obj.Vhost`
    """
    if not vhosts:
        return []
    tags_list = [vhost.display_repr()+"\n" for vhost in vhosts]
    # Remove the extra newline from the last entry
    if tags_list:
        tags_list[-1] = tags_list[-1][:-1]
    code, names = display_util.checklist(
        "Which server blocks would you like to modify?",
        tags=tags_list, force_interactive=True)
    if code == display_util.OK:
        return_vhosts = _reversemap_vhosts(names, vhosts)
        return return_vhosts
    return []

def _reversemap_vhosts(names: Iterable[str], vhosts: Iterable[VirtualHost]) -> List[VirtualHost]:
    """Helper function for select_vhost_multiple for mapping string
    representations back to actual vhost objects"""
    return_vhosts = []

    for selection in names:
        for vhost in vhosts:
            if vhost.display_repr().strip() == selection.strip():
                return_vhosts.append(vhost)
    return return_vhosts