"""blog URL Configuration

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', v1.index,name='home'),
    path('search/', v1.search,name='search'),
    path('blog/',v1.blog,name='post-list'),
    path('<int:pk>',v1.PostDetail.as_view()),
    path('pcreate/',v1.PostAdd.as_view()),
    path('update/<int:pk>',v1.PostUpdate.as_view()),
    path('delete/<int:pk>',v1.PostDelete.as_view()),
    path('ckeditor/', include('ckeditor_uploader.urls')),

    path('sports/',v1.sports),
    path('business/',v1.business),
    path('food/',v1.food),
    path('travel/',v1.travel),
    path('gym/',v1.gym),
    path('gamming/',v1.gamming),

    path('draft/',v1.draft),
    path('authform/',v1.AuthorAdd),

    path('authorpost/',v1.view,name='post-list'),
    path('post/<id>/',v1.post,name='post-detail'),

    path('signup/',v1.Signup,name='signup'),

    path('logout/',v1.logout_view),
    path('accounts/',include('django.contrib.auth.urls')),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)


from datetime import datetime
from flask import Flask, request

from Models import db
from Models.deal import Deal
from Models.item import Item
from Models.user import User
from utils import check_deal_availed, update_customer_deal_list

app = Flask(__name__)

app.config['MONGODB_SETTINGS'] = {
    'db': 'your_database',
    'host': 'localhost',
    'port': 27017
}

db.init_app(app)

@app.route("/")
def welcome():
    item = Item(_id=1, name="Item1").save()
    user = User(_id=1, name="Shubham", position="Seller", deals_availed=[]).save()
    print(item,user)
    return "Welcome"

@app.route("/deals/create/", methods = ['POST'])
def create_deals():
    price = request.args.get('price', default=0, type=int)
    item_id = request.args.get('item_id', default='', type=str)
    seller_id = request.args.get('item_id', default='', type=str)
    number_of_items = request.args.get('number_of_items', default=0, type=int)
    end_time = request.args.get('price', default=0, type=str)
    # end_time need to be parsed
    item = Item.objects(id=item_id).first()
    seller = User.objects(id=seller_id).first()
    deal = Deal(id= item_id, price= price, item = item, seller = seller, number_of_items = number_of_items,
                end_time = datetime.now(), status= "Active").save()
    return deal

@app.route("/deals/end/", methods = ['POST'])
def end_deals():
    deal_id = request.args.get('deal_id', default=0, type=str)
    deal = Deal.objects(id=deal_id).first()
    deal.update(status="Deactivate")
    return deal

@app.route("/deals/update/", methods = ['POST'])
def update_deals():
    deal_id = request.args.get('deal_id', default='', type=str)
    new_number_of_items = request.args.get('new_number_of_items', default=0, type=int)
    new_end_time = request.args.get('new_end_time', default=0, type=str)
    deal = Deal.objects(id=deal_id).first()
    if deal.number_of_items<new_number_of_items and deal.end_time<new_end_time:
        deal.update(number_of_items=new_number_of_items, end_time=new_end_time)
    else:
        return "Wrong input given"

@app.route("/deals/claim/", methods = ['POST'])
def claim_deal():
    deal_id = request.args.get('deal_id', default='', type=str)
    item_id = request.args.get('item_id', default='', type=str)
    customer_id = request.args.get('customer_id', default='', type=str)
    deal = Deal.objects(id=deal_id).first()
    item = Item.objects(id=item_id).first()
    customer = User.objects(id=customer_id).first()
    if deal.number_of_items>0 and deal.end_time>datetime.now() and not(check_deal_availed(deal, customer)) and deal.status=="Active":
        update_customer_deal_list(customer, deal)
        return "Deal availed"
    else:
        return "Deal can't be availed"


#!/usr/bin/python3
"""
Python script that takes in a URL and an email, sends a POST
request to the passed URL with the email as a parameter, and
displays the body of the response
"""
from urllib import request, parse
import sys

if __name__ == '__main__':
    if len(sys.argv) > 2:
        url = sys.argv[1]
        email = sys.argv[2]
        form_data = bytes(parse.urlencode([('email', email)]), 'utf-8')
        with request.urlopen(sys.argv[1], data=form_data) as response:
            print(response.read().decode('utf-8'))


import csv
from whisper_automatic_test.scenario import Scenario
from whisper_automatic_test.request import Request

def get_scenarios_from_csv_file(scenario_csv_file_path):
    scenarios = []
    with open(scenario_csv_file_path, newline='') as csv_file:
        scenario_reader = csv.reader(csv_file, delimiter=',')
        next(scenario_reader)
        current_scenario_id = None
        current_requests = []
        for row in scenario_reader:
            if row[0] != current_scenario_id:
                update_scenarios(scenarios, current_requests)
                current_scenario_id = row[0]
                current_requests = []
            request = Request(row[1], row[2], row[3], row[4])
            current_requests.append(request)
        update_scenarios(scenarios, current_requests)
    return scenarios

def update_scenarios(scenarios, requests):
    if not requests:
        return

    scenario = Scenario(requests)
    scenarios.append(scenario)


"""=================================================================================================
mirdeep produces an output file that includes duplicates.  Typically the duplicates are due to
the presence of identical precursor/star/mature miRNA sequences at multiple positions in the
reference genome.  This leads to overcounting of certain RNAs so it is desirable to merge the
identical probes into a single entry

input: all sample CSV file produced by quantify.pl

Michael Gribskov     30 December 2021
================================================================================================="""
import sys

def read_mirdeep_csv(filename):
    """---------------------------------------------------------------------------------------------
    Read the fields into a dict using the column headings in the file as keys
    below
    Add a field 'type': 'novel' or 'known'
    Add a field 'sid': with the provisional id or tag id for novel and known miRNAs respectively
    Add a field 'group': used later for skipping merged miRNAs

    :param filename:
    :return: list of dict, all columns of information for each miRNA
    ---------------------------------------------------------------------------------------------"""
    fp = None
    try:
        fp = open(filename, 'r')
    except OSError:
        sys.stderr.write(f'read_mirdeep_csv - unable to open file ({filename}')
        exit(1)

    # read down to section titled
    # novel miRNAs predicted by miRDeep2

    for line in fp:
        if line.startswith('novel miRNAs'):
            break

    header = fp.readline()
    title = header.rstrip().split('\t')

    # read the predicted (novel) miRNAs
    mirna = []
    for line in fp:
        if line == '\n':
            # section ends with blank line
            break

        thismirna = {'type': 'novel', 'group': False}
        field = line.rstrip().split('\t')
        f = 0
        for value in field:
            thismirna[title[f]] = field[f]
            f += 1
        thismirna['sid'] = thismirna['provisional id']
        mirna.append(thismirna)

    nnovel = len(mirna)
    print(f'Novel miRNAs: {nnovel}')

    # skip to the known miRNA section which begins with
    # mature miRBase miRNAs detected by miRDeep2

    for line in fp:
        if line.startswith('mature miRBase'):
            break

    header = fp.readline()
    title = header.rstrip().split('\t')

    # read the known miRNAs
    for line in fp:
        if line == '\n':
            # section ends with blank line
            break

        thismirna = {'type': 'known', 'group': False}
        field = line.rstrip().split('\t')
        f = 0
        for value in field:
            thismirna[title[f]] = field[f]
            f += 1
        thismirna['sid'] = thismirna['tag id']
        mirna.append(thismirna)

    nknown = len(mirna) - nnovel
    print(f'Known miRNAs: {nknown}')
    print(f'Total miRNAs: {len(mirna)}')

    return mirna

def findmerges(mirna):
    """---------------------------------------------------------------------------------------------
    find which miRNAs are mergable because they have identical precursor sequences

    :param mirna: list of dict, see read_mirdeep_csv()
    :return:
    ---------------------------------------------------------------------------------------------"""
    seqp = ''
    merges = [[-1]]

    for m in sorted(range(len(mirna)), key=lambda x: (mirna[x]['consensus precursor sequence'],
                                                      mirna[x]['sid'])):
        # this sorts by the precursor sequence and the mirdeep id, e.g., 4_6597
        if mirna[m]['consensus precursor sequence'] == seqp:
            merges[-1].append(m)
            mirna[m]['group'] = True

        else:
            if len(merges[-1]) == 1:
                merges[-1] = [m]
            else:
                merges.append([m])
            seqp = mirna[m]['consensus precursor sequence']

    # last item will probably be unmerged
    if len(merges[-1]) == 1:
        merges.pop()

    return merges

def get_id(thismirna):
    """---------------------------------------------------------------------------------------------
    get the primary and alternate ID depending on whether it is a known or novel miRNA

    :param thismirna: dict, one record from mirDeep2 result
    :return: string, string - primary and alternate IDs
    ---------------------------------------------------------------------------------------------"""
    if thismirna['type'] == 'known':
        id = thismirna["mature miRBase miRNA"]
        alt = thismirna['tag id']
    else:
        id = thismirna['provisional id']
        alt = thismirna['example miRBase miRNA with the same seed']

    return id, alt

# --------------------------------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------------------------------
if __name__ == '__main__':

    min_mirdeep_score = 0
    min_count = 330

    mirna = read_mirdeep_csv('../data/result_23_01_2021_t_06_45_02.csv')
    merges = findmerges(mirna)

    # print(f'{mirna[-1]}')
    for i in range(len(merges)):
        print(f'\ngroup {i}: {merges[i]}')
        for g in merges[i]:
            m = mirna[g]
            id, alt = get_id(m)

            count = m['total read count']
            seq = m['consensus precursor sequence']
            group = m['group']
            print(f'{g}\t{group}\t{id}\t{alt}\t\t{count}\t\t{seq}')

    pre = open('precursor.fa', 'w')
    mat = open('mature.fa', 'w')
    star = open('star.fa', 'w')

    count_all = {t: 0 for t in ('known', 'novel')}
    count_undup = {t: 0 for t in ('known', 'novel')}
    count_mirdeep = {t: 0 for t in ('known', 'novel')}
    count_count = {t: 0 for t in ('known', 'novel')}
    for m in mirna:

        count_all[m['type']] += 1
        if m['group']:
            continue

        count_undup[m['type']] += 1
        if float(m['miRDeep2 score']) < min_mirdeep_score:
            continue

        count_mirdeep[m['type']] += 1
        if int(m['total read count']) < min_count:
            continue

        count_count[m['type']] += 1

        # write out fasta sequences for those that pass the mirdeep and count cutoffs
        id, alt = get_id(m)
        pre.write(f">{id} {alt}\n{m['consensus precursor sequence']}\n")
        mat.write(f">{id} {alt}\n{m['consensus mature sequence']}\n")
        star.write(f">{id} {alt}\n{m['consensus star sequence']}\n")

    print('!summary')
    print('!Count\tCount')
    print('!Known\tNovel\tID')
    print(f"{count_all['known']}\t\t{count_all['novel']}\t\t total miRNA analyzed")
    print(f"{count_undup['known']}\t\t{count_undup['novel']}\t\t un-duplicated miRNA")
    print(f"{count_mirdeep['known']}\t\t{count_mirdeep['novel']}\t\t mirDeep > {min_mirdeep_score}")
    print(f"{count_count['known']}\t\t{count_count['novel']}\t\t count > {min_count}")

    pre.close()
    mat.close()
    star.close()

    exit(0)


import torch

class ReplayBuffer():
    def __init__(self, buffer_size, device):
        self._head = 0
        self._total_count = 0
        self._buffer_size = buffer_size
        self._device = device
        self._data_buf = None
        self._sample_idx = torch.randperm(buffer_size)
        self._sample_head = 0

        return

    def reset(self):
        self._head = 0
        self._total_count = 0
        self._reset_sample_idx()
        return

    def get_buffer_size(self):
        return self._buffer_size

    def get_total_count(self):
        return self._total_count

    def store(self, data_dict):
        if (self._data_buf is None):
            self._init_data_buf(data_dict)

        n = next(iter(data_dict.values())).shape[0]
        buffer_size = self.get_buffer_size()
        assert(n < buffer_size)

        for key, curr_buf in self._data_buf.items():
            curr_n = data_dict[key].shape[0]
            assert(n == curr_n)

            store_n = min(curr_n, buffer_size - self._head)
            curr_buf[self._head:(self._head + store_n)] = data_dict[key][:store_n]

            remainder = n - store_n
            if (remainder > 0):
                curr_buf[0:remainder] = data_dict[key][store_n:]

        self._head = (self._head + n) % buffer_size
        self._total_count += n

        return

    def sample(self, n):
        total_count = self.get_total_count()
        buffer_size = self.get_buffer_size()

        idx = torch.arange(self._sample_head, self._sample_head + n)
        idx = idx % buffer_size
        rand_idx = self._sample_idx[idx]
        if (total_count < buffer_size):
            rand_idx = rand_idx % self._head

        samples = dict()
        for k, v in self._data_buf.items():
            samples[k] = v[rand_idx]

        self._sample_head += n
        if (self._sample_head >= buffer_size):
            self._reset_sample_idx()

        return samples

    def _reset_sample_idx(self):
        buffer_size = self.get_buffer_size()
        self._sample_idx[:] = torch.randperm(buffer_size)
        self._sample_head = 0
        return

    def _init_data_buf(self, data_dict):
        buffer_size = self.get_buffer_size()
        self._data_buf = dict()

        for k, v in data_dict.items():
            v_shape = v.shape[1:]
            self._data_buf[k] = torch.zeros((buffer_size,) + v_shape, device=self._device)

        return


from .Animal import Animal
from Action import Action
from ActionEnum import ActionEnum
from Organisms.Plant import Plant
import random

class Wolf(Animal):

	def __init__(self, wolf=None, position=None, world=None):
		super(Wolf, self).__init__(wolf, position, world)

	def clone(self):
		return Wolf(self, None, None)

	def initParams(self):
		self.power = 8
		self.initiative = 5
		self.liveLength = 20
		self.powerToReproduce = 16
		self.sign = 'W'

	def move(self):
		result = []
		pomPositions = self.getNeighboringPosition()
		newPosition = None

		if pomPositions:
			newPosition = random.choice(pomPositions)
			result.append(Action(ActionEnum.A_MOVE, newPosition, 0, self))
			self.lastPosition = self.position
			metOrganism = self.world.getOrganismFromPosition(newPosition)
			if metOrganism is not None and not isinstance(metOrganism, Plant):
				result.extend(metOrganism.consequences(self))
		return result

	def getNeighboringPositions(self):
		return self.world.filterPositionsWithOtherSpecies(self.world.getNeighboringPositions(self.position), Wolf)


'''
Trainer for knapsack problem. This implements the "x" version of the problem where the training
data is pairs (d, x(d)).

Daniel McKenzie
June 2023

'''
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import Dataset, TensorDataset, DataLoader
import time as time
import torch.nn as nn
from src.knapsack.knapsack_utils import RegretLoss, Compute_Test_Loss
import pyepo
import numpy as np
import os

def Trainer_x(net, train_dataset, test_dataset, val_dataset, num_item, num_knapsack, max_epochs,
            learning_rate, model_type, device='cuda:0'):
    '''
    Train network net using given parameters, for shortest path
    problem on a grid_size-by-grid_size grid graph.
    Training data is automatically loaded.
    type should be either vertex or edge.
    '''

    ## Training setup
    batch_size = 200 # 256
    loader_train = DataLoader(dataset=train_dataset, batch_size=batch_size,
                                  shuffle=True)
    loader_test = DataLoader(dataset=test_dataset, batch_size=batch_size,
                                 shuffle=False)
    loader_val = DataLoader(dataset=val_dataset, batch_size=batch_size,
                                 shuffle=False)

    optimizer = optim.Adam(net.parameters(), lr=learning_rate, weight_decay = 5e-4)

    # Initialize loss function and evaluation metric
    regret = RegretLoss(num_item, num_knapsack, device=device)
    metric = regret
    criterion = nn.MSELoss()
    # SPO+ is not admissable as a model here. Nor is the Fenchel-Young loss (maybe).

    if model_type == "BBOpt":
        dbb = pyepo.func.blackboxOpt(net.knapsack_solver, lambd=20, processes=1)
    elif model_type == "PertOpt":
        ptb = pyepo.func.perturbedOpt(net.knapsack_solver, n_samples=10, sigma=0.5, processes=1)
    elif model_type == "DYS":
        pass
    else:
        raise TypeError("Please choose a supported model!")

    scheduler = ReduceLROnPlateau(optimizer, 'min')

    ## Initialize arrays that will be returned and checkpoint directory
    val_loss_hist= []
    epoch_time_hist = []
    max_time = 1200
    checkpt_path = './src/knapsack/saved_weights/' + model_type + '/'
    if not os.path.exists(checkpt_path):
        os.makedirs(checkpt_path)

     ## Compute initial validation loss
    # if model_type == "DYS":
    #     metric = regret # criterion
    # elif model_type == "BBOpt" or model_type == "PertOpt":
    #     metric = criterion
    # else:
    #     metric = regret
    metric = regret

    best_val_loss = Compute_Test_Loss(net,loader_val, model_type, metric, num_knapsack, num_item, device)

    print('Initial validation loss is ', best_val_loss)
    val_loss_hist.append(best_val_loss)
    time_till_best_val_loss = 0

     ## Compute initial test loss
    best_test_loss = Compute_Test_Loss(net,loader_test, model_type, metric, num_knapsack, num_item, device)

    ## Train!
    epoch=1
    train_time=0
    train_loss_ave = 0

    while epoch <= max_epochs and train_time <= max_time:
        start_time_epoch = time.time()
        # Iterate the training batch
        for d_batch, w_batch, opt_sol, opt_value in loader_train:
            d_batch = d_batch.to(device)
            w_batch = w_batch.to(device)
            opt_sol = opt_sol.to(device)
            opt_value = opt_value.to(device)
            net.train()
            optimizer.zero_grad()
            predicted = net(d_batch)
            if model_type == "DYS":
                loss = criterion(opt_sol, predicted[:,:-(num_knapsack + num_item)])
            elif model_type == "BBOpt":
                x_predicted = dbb(predicted)
                loss = criterion(opt_sol, x_predicted)
            elif model_type == "PertOpt":
                x_predicted = ptb(predicted)
                loss = criterion(opt_sol, x_predicted)

            loss.backward()
            optimizer.step()
            train_loss_ave = 0.95*train_loss_ave + 0.05*loss.item()

        end_time_epoch = time.time()
        epoch_time =  end_time_epoch - start_time_epoch
        train_time += epoch_time
        epoch_time_hist.append(epoch_time)

        ## Now compute loss on validation set
        val_loss = Compute_Test_Loss(net,loader_val, model_type, metric, num_knapsack, num_item, device)

        if val_loss < best_val_loss:
            state_save_name = checkpt_path+'best.pth'
            torch.save(net.state_dict(), state_save_name)
            # If we have achieved lowest validation thus far, this will be the model selected.
            # So, we compute test loss
            best_test_loss = Compute_Test_Loss(net,loader_test, model_type, metric, num_knapsack, num_item, device)
            best_val_loss = val_loss
            print('Best validation loss achieved at epoch ' + str(epoch))
            time_till_best_val_loss = sum(epoch_time_hist)

        # scheduler.step(val_loss)
        val_loss_hist.append(val_loss)

        print('epoch: ', epoch, 'validation loss is ', val_loss, 'epoch time: ', epoch_time)
        epoch += 1

    state_save_name = checkpt_path+'last.pth'
    torch.save(net.state_dict(), state_save_name)
    if time_till_best_val_loss < 1e-6:
        time_till_best_val_loss = sum(epoch_time_hist)

    return val_loss_hist, epoch_time_hist, best_test_loss, time_till_best_val_loss


__author__ = 'emmaachberger'

import pandas as pd
import numpy as np
from sqlalchemy import create_engine

from helperfunctions import returnTable, droplevel
import sqlqueries
import instance

database = instance.getDatabase()
engine = create_engine(database)

def spendingdata():

    a = sqlqueries.sqlmonthlyexpenses()
    multiplier = "* - 1"
    string = "WHERE categories.Spending"

    df = pd.read_sql(a %(multiplier, string), engine, parse_dates='Date')

    return returnTable(df)

def netincomedata():

    a = sqlqueries.sqlmonthlyexpenses()
    string = ""
    multiplier = ""

    df = pd.read_sql(a %(string, multiplier), engine, parse_dates='Date')

    return returnTable(df)

def balanceData():

    a = sqlqueries.sqlmonthlybalances() ### bankaccounts, balances

    df = pd.read_sql(a, engine, parse_dates='transdate')

    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["balance"],columns=['AccountName'],fill_value=0).reset_index()
    ### takes daily balance data and returns dataframe with each account as separate column

    droplevel(df) # adjusts column names that occurred from pivoting
    return returnTable(df)

def currentbalancedata():

    a = sqlqueries.sqlcurrentbalance()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def stockData():

    a = sqlqueries.sqlstockgain()

    df = pd.read_sql(a, engine, parse_dates='transdate')

    df['Gain/Loss'] = np.cumsum(df.groupby(['owner', 'description'])['Gain/Loss'])
    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["Gain/Loss"],columns=['description']).reset_index()

    owners = getowners().values.tolist()

    for owner in owners:
        df[df.owner==owner[0]] = df[df.owner==owner[0]].sort(['transdate']).fillna(method='pad')

    df = df.fillna(0)

    droplevel(df)

    return returnTable(df)

def stockPricesData():

    a = sqlqueries.sqlstocksprices()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["Price"],columns=['symbol']).reset_index()

    owners = getowners().values.tolist()

    for owner in owners:
        df[df.owner==owner[0]] = df[df.owner==owner[0]].sort(['transdate']).fillna(method='pad')

    df = df.fillna(0)

    droplevel(df)

    return returnTable(df)

def budgetData():

    a = sqlqueries.sqlbudget()

    df = pd.read_sql(a, engine)

    return returnTable(df)

def overallbudgetData():

    a = sqlqueries.sqloverallbudget()

    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def NIFXdata():
    ### returns net income data with fx

    df = pd.read_sql_table('googlechartsmonthlynetincome', engine, parse_dates='Date')

    return returnTable(df)

def indtransactions(a, page, limit):

    if a == "Combined":
        b = ""
    else: b = 'and bankaccounts.owner = "%s"' %a

    a = sqlqueries.sqlindtransactions()
    df = pd.read_sql(a %(b, limit, (page-1)*limit), engine, parse_dates='transdate')

    return df.values.tolist(), df.columns.tolist()

def stocktabledata():

    a = sqlqueries.sqlStockTable()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def accruals():

    a = sqlqueries.accruals()
    df = pd.read_sql(a, engine, parse_dates='transdate')
    return returnTable(df)

def sumstockdata():

    a = sqlqueries.sqlSumStockTable()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def sumstockPricesData():

    a = sqlqueries.sqlSumStockData()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["Price"],columns=['symbol']).reset_index()

    droplevel(df)

    df4 = df
    df4 = df4.iloc[:2,3:]
    df4 = pd.DataFrame(df4.sum())
    df3 = df.iloc[:,3:]
    initial = df3.ix[0:1]
    initial = initial.sum()
    df2 = df3.divide(initial / 100)
    df.iloc[:,3:] = df2
    df4 = df4.reset_index()
    df4.columns = ['Stock','Price']
    df = df.fillna(0)
    df4 = df4.fillna(0)

    return returnTable(df), returnTable(df4)

def sumstockPricesOriginalData():

    a = sqlqueries.sqlSumStockData()
    df = pd.read_sql(a, engine, parse_dates='transdate')

    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["Price"],columns=['symbol']).reset_index()

    df = df.fillna(0)

    droplevel(df)

    return returnTable(df)

def sumspendingdata():

    a = sqlqueries.sqlSumSpendTable()

    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def getowners(): ### return list of owners

    a = sqlqueries.sqlowners()

    df = pd.read_sql(a, engine)

    return df

def accountbalancesbyaccount():

    a = sqlqueries.sqlcurrentbalancebyaccount()

    df = pd.read_sql(a, engine, parse_dates='transdate')

    return returnTable(df)

def owners():
    return returnTable(getowners())

def owners2(): ### return list of owners

    import sqlite3
    conn = sqlite3.connect('money.db')

    a = sqlqueries.sqlowners()

    c = conn.cursor()
    c.execute(a)
    owners = c.fetchall()
    conn.close()
    return owners

def goalData():

    a = sqlqueries.sqlGoalChart()

    df = pd.read_sql(a, engine, parse_dates='transdate')

    df = pd.pivot_table(df, index=['transdate','owner', 'FXRate'],values=["balance"],columns=['AccountName'],fill_value=0).reset_index()
    ### takes daily balance data and returns dataframe with each account as separate column

    droplevel(df) # adjusts column names that occurred from pivoting

    return returnTable(df)


import pygame as pg
import numpy as np
from math import sqrt

class Node:
    def __init__(self, data, level, f_score, parent, direct):
        self.data = data
        self.n = sqrt(len(data))
        if parent == None:
            self.level = 1
        else:
            self.level = level * 2
        self.f_score = f_score
        self.parent = parent
        self.thisdirect = direct
    def find_index(self, num):
        index = self.data.index(num)
        i = index // self.n
        j = index - (i * self.n)
        return i, j
    def possible_moves(self):
        i, j = self.find_index("2")
        directions = [(-1,0), (1,0), (0,-1), (0,1)]
        directions_name = ["Up", "Down", "Left", "Right"]
        all_directions = {directions[i]:directions_name[i] for i in range(4)}

        possible_moves = []
        for k in directions:
            if not ((i+k[0]<0) or (i+k[0]>self.n-1) or (j+k[1]<0) or (j+k[1]>self.n-1)):
                possible_moves.append((all_directions[k]))
        left =  int(((i*self.n)+j)-1)
        right = int(((i*self.n)+j)+1)
        top = int(((i-1)*self.n)+j)
        bottom = int(((i+1)*self.n)+j)
        for i in possible_moves:
            if i=="Up":
                if top<0 or self.data[top]=="1":
                    possible_moves.remove("Up")
            elif i=="Down":
                if (bottom>=self.n**2) or (self.data[bottom]=="1"):
                    possible_moves.remove("Down")
            elif i=="Left":
                if left<0 or self.data[left]=="1":
                    possible_moves.remove("Left")
            else:
                if (right>=self.n**2) or (self.data[right]=="1"):
                    possible_moves.remove("Right")
        index = self.data.find("2")
        if "Left" in possible_moves and index%self.n==0:
            possible_moves.remove("Left")
        elif "Right" in possible_moves and (index+1)%self.n==0:
            possible_moves.remove("Right")

        return possible_moves
    def generate_children(self):
        directions = [(-1,0), (1,0), (0,-1), (0,1)]
        directions_name = ["Up", "Down", "Left", "Right"]
        all_directions = {directions_name[i]:directions[i] for i in range(4)}

        possible_directions = self.possible_moves()

        i,j = self.find_index("2")

        left =  int(((i*self.n)+j)-1)
        right = int(((i*self.n)+j)+1)
        top = int(((i-1)*self.n)+j)
        bottom = int(((i+1)*self.n)+j)

        children = []
        for p in possible_directions:
            puzzle_list = list(self.data)
            zero_index = puzzle_list.index("2")
            if p == "Up":
                if puzzle_list[top]!="4":
                    puzzle_list[zero_index], puzzle_list[top]= "1", "2"
                    di = "Up"
                else:
                    continue
            elif p=="Down":
                if puzzle_list[bottom]!="4":
                    puzzle_list[zero_index], puzzle_list[bottom]= "1", "2"
                    di = "Down"
                else:
                    continue
            elif p=="Right":
                if puzzle_list[right]!="4":
                    puzzle_list[zero_index], puzzle_list[right]= "1", "2"
                    di = "Right"
                else:
                    continue
            elif p=="Left":
                if puzzle_list[left]!="4":
                    puzzle_list[zero_index], puzzle_list[left]= "1", "2"
                    di = "Left"
                else:
                    continue
            children.append(("".join(puzzle_list),di))

        children_obj = []
        for i in children:
            children_obj.append(Node(i[0],self.level+1,0,self,i[1]))
        return children_obj

class Puzzle:
    def __init__(self, current, goal):
        self.puzzle = current
        self.open = []
        self.closed = []
        self.visited = {}
        self.goal = goal

    def find_index(self, cur, num):
        index = cur.find(num)
        i = index // (sqrt(len(cur)))
        j = index - (i * (sqrt(len(cur))))
        return i, j
    def f_score(self, current, goal):
        return self.h_score(current.data, goal) + current.level
    def h_score(self, current, goal):
        total = 0
        i,j= self.find_index(current, str(2))
        x,y= self.find_index(goal, str(2))
        total+= abs(i-x) + abs(j-y)
        return total
    def process(self):
        start = Node(self.puzzle, 0, 0, None,None)

        self.open.append(start)

        while True:
            cur = self.open[0]
            if (cur.data[self.goal.find("2")]=="2"):
                _list = []
                _list.append(cur)
                while cur.parent != None:
                    _list.append(cur.parent)
                    cur = cur.parent
                else:
                    _list.append(cur.parent)
                _list = _list[::-1]
                """t = 0
                for i in _list:
                    if i!=None:
                        length_list = int(sqrt(len(i.data)))
                        for q in range(0,len(i.data),length_list):
                            for w in range(length_list):
                                print(i.data[q+w],end=" ")
                            print()
                        print(i.thisdirect)
                        print("********************")
                    t+=1
                print("Total-steps:",t-2)"""
                return _list
                break
            for i in cur.generate_children():
                i.fval = self.f_score(i,self.goal)
                if i.data not in self.visited or self.visited[i.data]>i.fval:
                    self.open.append(i)
                    self.visited[i.data]=i.fval
            self.closed.append(cur)
            self.visited[cur.data]=self.h_score(cur.data,self.goal)
            del self.open[0]

            self.open.sort(key = lambda x:x.fval, reverse=False)

import pygame as pg
pg.init()

print("Hello, and welcome to Maze solver!")
n = 20

white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 166, 147)
red = (122, 0, 0)

width = n * 10 - 10
height = n * 10 + 50

gameDisplay = pg.display.set_mode((width, height))
pg.display.set_caption("Maze")

x = 0
y = 0
for i in range((n*n)):
    exec(f"""sq{i} = pg.draw.rect(gameDisplay,white,({x},{y},10,10),1)""")
    exec(f"sq{i}_x, sq{i}_y = {x},{y}")
    x+=10
    if x>=n*10:
        x=0
        y+=10

start_key = pg.draw.rect(gameDisplay,white,(30,n*10+10,60,30),2)

def clicker(x,y,logic_board,point):
    pg.draw.line(gameDisplay, (255,0,0),(x,y),(x + 10,y + 10),1)
    pg.draw.line(gameDisplay, (255,0,0),(x,y + 10),(x + 10, y),1)
    logic_board[point//n][point%n]="4"
    return logic_board

game_logic_board = []
for i in range(0,n*n,n):
    row = []
    for j in range(n):
        row.append("0")
    game_logic_board.append(row)
game = True
while game:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            game = False
        if event.type == pg.MOUSEBUTTONUP:
            click_pos = pg.mouse.get_pos()
            if start_key.collidepoint(click_pos):
                game = False
            for i in range(0,n*n):
                exec(f"""if sq{i}.collidepoint(click_pos):
   game_logic_board = clicker(sq{i}_x,sq{i}_y,game_logic_board,{i})""")
            x = ""
            for t in range(len(game_logic_board)):
                for y in range(len(game_logic_board)):
                    x+=str(game_logic_board[t][y])
    pg.display.update()
pg.quit()

import pygame as pg
pg.init()
goal = ["0" for i in range(n*n)]
goal[(n*n)-1]="2"
goal = "".join(goal)
x = list(x)
x[0]="2"
x = "".join(x)
x = Puzzle(x,goal)
solution = x.process()

width = n * 10
height = n * 10

gameDisplay = pg.display.set_mode((width, height))
pg.display.set_caption("solution")

x = 0
y = 0
for row in game_logic_board:
    x=0
    for cell in row:
        if cell=="0":
            pg.draw.rect(gameDisplay,black,(x,y,10,10),1)
        elif cell=="1":
            pg.draw.rect(gameDisplay,green,(x,y,10,10),0)
        elif cell=="2":
            pg.draw.rect(gameDisplay,red,(x,y,10,10),0)
        elif cell=="4":
            pg.draw.rect(gameDisplay,white,(x,y,10,10),1)
        x+=10
    y+=10

game = True
while game:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            game = False
    pg.display.update()
pg.quit()


import re
hand = open('mbox-short.txt')
numlist = list()

for line in hand:
  line = line.rstrip()
  stuff = re.findall('^X-DSPAM-Confidence: ([0-9.]+)', line)
  # print(stuff)
  if len(stuff) != 1: continue
  # print(stuff)  # 값이 있는 리스트들만 추출
  num = float(stuff[0])   # 리스트에 있는 스트링에서 숫자로 전환
  # print(num)
  numlist.append(num)
# print(numlist)
print("Maximum: ", max(numlist))   # 0.9907


n=int(input("enter no:"))
temp=n
i=1
sum=0
while i<n:
    if n%i==0:
        sum=sum+i
    i=i+1
print(sum)
if sum==temp:
    print("it is a perfect number")
else:
    print("it is not perfect number")


import gensim
import numpy
import pandas as pd
from gensim.models.ldamodel import LdaModel
from gensim.models.coherencemodel import CoherenceModel
import gensim.corpora as corpora

df = pd.read_csv('../data/tweets_cutoff0.01_sorted.csv',sep='\t')

texts = df['text'].values
texts = [x.split(' ') for x in texts]

id2word = corpora.Dictionary(texts)

corpus = [id2word.doc2bow(text) for text in texts]

num_topics=[2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50]
coh_scores = []
for ntop in num_topics:
    lda_model = LdaModel(corpus=corpus,
                           id2word=id2word,
                           num_topics=ntop,
                           random_state=42,
                           update_every=1,
                           chunksize=100,
                           passes=10,
                           alpha='auto',
                           per_word_topics=True)

    coherence_model_lda = CoherenceModel(model=lda_model, texts=texts, dictionary=id2word, coherence='c_uci')

    coherence_lda = coherence_model_lda.get_coherence()

    coh_scores.append(coherence_lda)

df_out = pd.DataFrame.from_dict({'ntop':num_topics,'coh':coh_scores})

df_out.to_csv('lda_coh.csv',index=False)


import numpy as np

def	dijkstra(node):

	dist = [100000000 for i in range(vertices_num)]
	parent = [-1 for i in range(vertices_num)]
	nodes_queue= [{'src':node ,'dest':node,'weight':0}]

	while len(nodes_queue) != 0:
		current_node=nodes_queue[0]['src']
		prev_node=nodes_queue[0]['dest']
		cur_dist=nodes_queue[0]['weight']
		nodes_queue.pop(0)
		if dist[current_node] != 100000000:
			continue
		dist[current_node]=cur_dist
		parent[current_node]=prev_node

		for i in adj_list[current_node]:
			distance=cur_dist+adj_list[current_node][i]
			temp={'src':i ,'dest':current_node,'weight':distance}
			if dist[i] !=100000000:
				continue
			nodes_queue.append(temp.copy())

		nodes_queue.sort(key=lambda i: i['weight'])

	return dist,parent


import os
import skimage.io
from skimage.metrics import variation_of_information, adapted_rand_error, contingency_table
from collections import defaultdict
import pandas as pd
import argparse
import jseg.evaluation
import numpy as np
import logging

# Identifiers
GT_IDENTIFIER = 'gt'
PRED_IDENTIFIER = 'pred'

def evaluate_segmentation(ground_truth, prediction, background_label=1):
    """
    Calculates meassures over the ground truth and prediction.

    Current implemented measures:
    -----------------------------
    variation of information: Measure over and under segmentation of an image.
                             - VoI-over: Meassure of over segmentation
                             - VoI-under: Meassure of under segmentation
                             - VoI: Meassure of total segmentation.

    Adapted Rand Error: Measure quality of segmentation
                        - ar-predcision: Precision according to the Adaptive rand error
                        - ar-recall: Recall of the predicted segmentation according to Adaptive rand error
                        - ar-error: Harmonic mean of the precision and recall.

    parameters:
    -----------
    ground_truth: Image array with int16 values.
                    0 - Unknown
                    1 - Background
                    >1 - Clusters (cells)

    returns:
    --------
        Dictionary mapping name of measure to value.

    """
    data = {}

    num_gt = len(np.unique(ground_truth))-1
    data['num-cells'] = num_gt

    ignore_labels = (0,1)

    # Variation of information
    under_seg, over_seg = variation_of_information(ground_truth, prediction, ignore_labels = ignore_labels)
    data['VoI-over'] = over_seg
    data['VoI-under'] = under_seg
    data['VoI'] = over_seg + under_seg

    # addaptive rand error
    are, prec, rec = adapted_rand_error(image_true=ground_truth, image_test=prediction, ignore_labels=ignore_labels)
    data['ar-error'] = are
    data['ar-precision'] = prec
    data['ar-recall'] = rec

    # Quality
    full_conttable = contingency_table(im_true = ground_truth, im_test= prediction, normalize=False)
    (correct_rate, over_rate, under_rate, miss_rate, divergent_rate) = jseg.evaluation.segmentation_type(full_conttable, num_gt, background_label=background_label)
    data['qual-correct'] = correct_rate
    data['qual-over'] = over_rate
    data['qual-under'] = under_rate
    data['qual-miss'] = miss_rate
    data['qual-divergent'] = divergent_rate

    # Add your own functions

    return data

def get_extention(file_path):
    return file_path.split('.')[-1]

def get_type(filename):
    """
    Return the type of the file.

    Given naming convention '<name>_<type>.<ext>' where none of the variables contains '_'.
    """
    return filename.split('.')[0].split('_')[-1]
def get_name(filename):
    """
    Return the name of the file.

    Given naming convention '<name>_<type>.<ext>' where none of the variables contains '_'.
    """
    return filename.split('.')[0].split('_')[0]

def is_gt(filename):
    """ Is file ground truth or not"""
    return get_type(filename) == GT_IDENTIFIER
def is_pred(filename):
    """ Is file a prediciton or not"""
    return get_type(filename) == PRED_IDENTIFIER

def eval_dataset(gt_path, pred_path):
    """
    Evaluate the predicted segmentations

    Find matching files in 'gt_path' and 'pred_path' which are then compared to create a
    dictionary with the results.
    Matches are found if they share the same name given that they follow the naming
    convention <name>_<type>.tif.

    gt_path: Complete path to dictionary with ground truth files.
    pred_path: Complete path to dictionary with ground pred files.

    """
    # find matches
    matched_files = []
    for gt_file in os.listdir(gt_path):
        if not is_gt(gt_file): continue
        if not get_extention(gt_file) != 'tif': continue
        for pred_file in os.listdir(pred_path):
            if not is_pred(pred_file):                   continue
            if not get_extention(pred_file) != 'tif':    continue
            if get_name(gt_file) != get_name(pred_file): continue
            matched_files.append((gt_file, pred_file))

    # Log matches
    log_msg = ""
    log_msg += f"Found {len(matched_files)} matches to evaluate:"
    for gt_name, pred_name in matched_files:
        log_msg += f"\n\t{gt_name} <--> {pred_name}"
    logging.info(log_msg)

    # go through matches
    result = list()
    for label_file, pred_file in matched_files:
        logging.info(f"Evaluating: {get_name(label_file)}")
        gt = skimage.io.imread(os.path.join(gt_path, label_file))
        pred = skimage.io.imread(os.path.join(pred_path, pred_name))

        ## evaluate
        sample_result = evaluate_segmentation(gt, pred)
        sample_result['sample_name'] = get_name(label_file)
        result.append(sample_result)
    return result

import time
if __name__ == '__main__':
    # parse input
    parser = argparse.ArgumentParser(description='Evaluation')
    parser.add_argument('--gt_dir', type=str)
    parser.add_argument('--pred_dir', type = str)
    parser.add_argument('--save_path', type = str)
    parser.add_argument('--gt_identifier', type = str, default='label')
    parser.add_argument('--pred_identifier', type = str, default='pred')
    args = parser.parse_args()

    logging.basicConfig(level= logging.INFO, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')

    # SET GLOBAL CONSTANTS
    GT_IDENTIFIER = args.gt_identifier
    PRED_IDENTIFIER = args.pred_identifier

    # get results from directories
    result = eval_dataset(args.gt_dir, args.pred_dir)
    df = pd.json_normalize(result)
    df.to_csv(args.save_path, index = False)


# 트리의 부모 찾기 (BOJ 11725)
import sys
from collections import deque, defaultdict

In = sys.stdin.readline
n = int(In())
tree = defaultdict(list)

def bfs(tree):
    visited = [False] * (n+1)
    answer = dict()

    queue = deque()
    queue.append(1)
    visited[1] = True

    while queue:
        node = queue.popleft()

        for x in tree[node]:
            if not visited[x]:
                answer[x] = node
                visited[x] = True
                queue.append(x)

    return answer

def main():

    for _ in range(n-1):
        n1, n2 = map(int, In().split())
        tree[n1].append(n2)
        tree[n2].append(n1)

    answer = bfs(tree)
    for i in range(2, n+1):
        print(answer[i])

if __name__ == "__main__":
    main()


from __future__ import division

__all__ = ['CRC_RI_organic', 'RI_methods', 'refractive_index',
           'polarizability_from_RI', 'molar_refractivity_from_RI',
           'RI_from_molar_refractivity']

import os
import pandas as pd
from thermo.utils import pi
from thermo.utils import N_A

folder = os.path.join(os.path.dirname(__file__), 'Misc')

CRC_RI_organic = pd.read_csv(os.path.join(folder, 'CRC Handbook Organic RI.csv'),
                             sep='\t', index_col=0)

CRC = 'CRC'
NONE = 'NONE'
RI_methods = [CRC]

def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None,
                     full_info=True):
    r'''This function handles the retrieval of a chemical's refractive
    index. Lookup is based on CASRNs. Will automatically select a data source
    to use if no Method is provided; returns None if the data is not available.

    Function has data for approximately 4500 chemicals.

    Parameters
    ----------
    CASRN : string
        CASRN [-]

    Returns
    -------
    RI : float
        Refractive Index on the Na D line, [-]
    T : float, only returned if full_info == True
        Temperature at which refractive index reading was made
    methods : list, only returned if AvailableMethods == True
        List of methods which can be used to obtain RI with the given inputs

    Other Parameters
    ----------------
    Method : string, optional
        A string for the method name to use, as defined by constants in
        RI_methods
    AvailableMethods : bool, optional
        If True, function will determine which methods can be used to obtain
        RI for the desired chemical, and will return methods instead of RI
    full_info : bool, optional
        If True, function will return the temperature at which the refractive
        index reading was made

    Notes
    -----
    Only one source is available in this function. It is:

        * 'CRC', a compillation of Organic RI data in [1]_.

    Examples
    --------
    >>> refractive_index(CASRN='64-17-5')
    (1.3611, 293.15)

    References
    ----------
    .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of
       Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.
    '''
    def list_methods():
        methods = []
        if CASRN in CRC_RI_organic.index:
            methods.append(CRC)
        methods.append(NONE)
        return methods
    if AvailableMethods:
        return list_methods()
    if not Method:
        Method = list_methods()[0]

    if Method == CRC:
        _RI = float(CRC_RI_organic.at[CASRN, 'RI'])
        if full_info:
            _T = float(CRC_RI_organic.at[CASRN, 'RIT'])
    elif Method == NONE:
        _RI, _T = None, None
    else:
        raise Exception('Failure in in function')
    if full_info:
        return _RI, _T
    else:
        return _RI

def polarizability_from_RI(RI, Vm):
    r'''Returns the polarizability of a fluid given its molar volume and
    refractive index.

    .. math::
        \alpha = \left(\frac{3}{4\pi N_A}\right)
        \left(\frac{n^2-1}{n^2+2}\right)V_m

    Parameters
    ----------
    RI : float
        Refractive Index on Na D line, [-]
    Vm : float
        Molar volume of fluid, [m^3/mol]

    Returns
    -------
    alpha : float
        Polarizability [m^3]

    Notes
    -----
    This Lorentz-Lorentz-expression is most correct when van der Waals
    interactions dominate. Alternate conversions have been suggested.
    This is often expressed in units of cm^3 or Angstrom^3. To convert to these
    units, multiply by 1E9 or 1E30 respectively.

    Examples
    --------
    >>> polarizability_from_RI(1.3611, 5.8676E-5)
    5.147658123614415e-30

    References
    ----------
    .. [1] Panuganti, Sai R., Fei Wang, Walter G. Chapman, and Francisco M.
       Vargas. "A Simple Method for Estimation of Dielectric Constants and
       Polarizabilities of Nonpolar and Slightly Polar Hydrocarbons."
       International Journal of Thermophysics 37, no. 7 (June 6, 2016): 1-24.
       doi:10.1007/s10765-016-2075-8.
    '''
    return 3/(4*pi*N_A)*(RI**2-1)/(RI**2+2)*Vm

def molar_refractivity_from_RI(RI, Vm):
    r'''Returns the molar refractivity of a fluid given its molar volume and
    refractive index.

    .. math::
        R_m = \left(\frac{n^2-1}{n^2+2}\right)V_m

    Parameters
    ----------
    RI : float
        Refractive Index on Na D line, [-]
    Vm : float
        Molar volume of fluid, [m^3/mol]

    Returns
    -------
    Rm : float
        Molar refractivity [m^3/mol]

    Notes
    -----

    Examples
    --------
    >>> molar_refractivity_from_RI(1.3611, 5.8676E-5)
    1.2985217089649597e-05

    References
    ----------
    .. [1] Panuganti, Sai R., Fei Wang, Walter G. Chapman, and Francisco M.
       Vargas. "A Simple Method for Estimation of Dielectric Constants and
       Polarizabilities of Nonpolar and Slightly Polar Hydrocarbons."
       International Journal of Thermophysics 37, no. 7 (June 6, 2016): 1-24.
       doi:10.1007/s10765-016-2075-8.
    '''
    return (RI**2 - 1.)/(RI**2 + 2.)*Vm

def RI_from_molar_refractivity(Rm, Vm):
    r'''Returns the refractive index of a fluid given its molar volume and
    molar refractivity.

    .. math::
        RI = \sqrt{\frac{-2R_m - V_m}{R_m-V_m}}

    Parameters
    ----------
    Rm : float
        Molar refractivity [m^3/mol]
    Vm : float
        Molar volume of fluid, [m^3/mol]

    Returns
    -------
    RI : float
        Refractive Index on Na D line, [-]

    Notes
    -----

    Examples
    --------
    >>> RI_from_molar_refractivity(1.2985e-5, 5.8676E-5)
    1.3610932757685672

    References
    ----------
    .. [1] Panuganti, Sai R., Fei Wang, Walter G. Chapman, and Francisco M.
       Vargas. "A Simple Method for Estimation of Dielectric Constants and
       Polarizabilities of Nonpolar and Slightly Polar Hydrocarbons."
       International Journal of Thermophysics 37, no. 7 (June 6, 2016): 1-24.
       doi:10.1007/s10765-016-2075-8.
    '''
    Rm = ((-2*Rm - Vm)/(Rm-Vm))**0.5
    return Rm

### Mixtures

#def Lorentz_Lorenz(ws=None, RIs=None, rhos=None, rho=None):
#    if not length_check([ws, RIs, rhos]):
#        raise Exception('Input dimentions are inconsistent')


from django.urls import path,include
from . import views

urlpatterns = [
    path('',views.home),
    path('reset/',views.reset),
    path('about/',views.about),
    path('contact/',views.contact),
    path('signup/',views.signup_view, name='signup'),
    path('login/',views.login_view,name='login'),
    path('logout/',views.logout_view,name='logout'),
    path('account/',views.account_view,name='account'),
]


import tkinter
import tkinter.ttk
import tkinter.messagebox

# ------------------------------------------------------------------------
class Form1:
    def add(self):
        if self.textbox1.get() == "":
            tkinter.messagebox.showinfo("", "** Fields are mandatory")

        else:

            obj = open("E:\\python vmm\\group_record.txt", "a")
            group_name = self.textbox1.get()
            description = self.textbox2.get()
            obj.write(group_name)
            obj.write("\n")
            obj.write(description)
            obj.write("\n")
            obj.write("*******\n")
            obj.close()
            tkinter.messagebox.showinfo("", "Group Created Successfully")

    def __init__(self):
        self.root = tkinter.Tk()
        self.lb1 = tkinter.Label(self.root, text="Create a new group")
        self.lb2 = tkinter.Label(self.root, text="Group Name**")
        self.textbox1 = tkinter.Entry(self.root)
        self.lb3 = tkinter.Label(self.root, text="description")
        self.textbox2 = tkinter.Entry(self.root)
        self.bt1 = tkinter.Button(self.root, text="Submit", command=self.add)
        # this is the grid code
        self.lb1.grid(row=0, column=0)
        self.lb2.grid(row=1, column=0)
        self.textbox1.grid(row=1, column=1)
        self.lb3.grid(row=2, column=0)
        self.textbox2.grid(row=2, column=1)
        self.bt1.grid(row=3, column=1)
        self.root.mainloop()

# ---------------------------------------------------------------------------------------------------
def showresult():
    root = tkinter.Tk()
    t = tkinter.ttk.Treeview(root, columns=("Group_Name", "Description"))
    t.heading("Group_Name", text="Group Name")
    t.heading("Description", text="Description")
    rd = open("E:\python vmm\\group_record.txt", "r")
    i = 0
    while True:
        Group_Name = rd.readline()
        if Group_Name == "":
            break
        description = rd.readline()
        seperator = rd.readline()
        t.insert("", i, values=(Group_Name, description))
        i = i + 1
    t.pack()

# -------------------------------------------------------------------------------------------------------
root = tkinter.Tk()
mymenu = tkinter.Menu(root)
root.config(menu=mymenu)
submenu1 = tkinter.Menu(mymenu, tearoff=0)
mymenu.add_cascade(label="File", menu=submenu1)
submenu1.add_command(label="Create Group", command=form1)
submenu1.add_command(label="View list of Groups", command=showresult)
root.mainloop()


with open('problem1_input.txt') as file:
    inputs = file.readlines()

inputs = [int(i.strip()) for i in inputs]

complement_map = {}
target = 2020

for i in inputs:
    if i in complement_map:
        complement = 2020 - i
        print(i * complement)
    else:
        complement_map[2020 - i] = i


# Variables
letters = ' abcdefghijklmnopqrstuvwxyz'
values = []
val=0

# Function to get letter value
for i in range(0,len(letters)):
    values.append(val)
    val += 1

# Function
def letter_value(letter):
    position = letters.index(letter)
    return values[position]

play = 'yes'
while play == 'yes' or play == 'y':
    # INPUT
    word = input('Please input a word to calculate:')

    # Reset Total
    total = 0

    # Loop to calculate
    for i in range(0,len(word)):
        total = total + letter_value(word[i])

    # Print Total
    print(total)

    # Play again?
    play = input('Play again?').lower()


# -*- coding: utf-8 -*-
# Question 4
# Author: Weining Qu (wq2155)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from evaluation import *

def GaussianTrain(data, target):
    """
    :param data: Input data
    :param mu: mean of X|y
    :param Sigma: covariance matrix of X|y
    :return: prob of X
    """

    Y = data[target].values
    X_all = data[[col for col in data.columns if col != target]]
    X_pos = X_all[Y == 1].values
    X_neg = X_all[Y == 0].values

    phi = (Y.sum()+1) / (len(Y)+2)  # Laplace Param phi for Bernoulli distribution of y (Prior)
    mu_pos = np.sum(X_pos, axis=0) / Y.sum()  # Param mean of X for X|y=1 (Multivariate Gaussian)
    mu_neg = np.sum(X_neg, axis=0) / (len(Y)-Y.sum())  # Param mean of X for X|y=0 (Multivariate Gaussian)

    X_pos_submu = X_pos - mu_pos
    X_neg_submu = X_neg - mu_neg

    Sigma_all = []
    for X_i in X_pos_submu:
        X_i = X_i.reshape(X_pos_submu.shape[1], 1)
        sigma_i = X_i.dot(X_i.T)
        Sigma_all.append(sigma_i)
    for X_i in X_neg_submu:
        X_i = X_i.reshape(X_neg_submu.shape[1], 1)
        sigma_i = X_i.dot(X_i.T)
        Sigma_all.append(sigma_i)
    Sigma_all = np.array(Sigma_all)
    Sigma = np.sum(Sigma_all, axis=0) / len(Y)  # Param - Covariance matrix (Multivariate Gaussian)

    return phi, mu_pos, mu_neg, Sigma

def GaussianProb(x, mu, Sigma):

    col = np.shape(Sigma)[0]
    Sigma_det = np.linalg.det(Sigma + np.eye(col) * 0.001)
    Sigma_inv = np.linalg.inv(Sigma + np.eye(col) * 0.001)
    x_mu = (x - mu).reshape((1, col))
    # P(X|y) follows Gaussian distribution
    prob = 1.0 / (np.power(np.power(2 * np.pi, col) * np.abs(Sigma_det), 0.5)) * \
           np.exp(-0.5 * x_mu.dot(Sigma_inv).dot(x_mu.T))[0][0]
    return prob

def GaussianPredict(testX, phi, mu_pos, mu_neg, Sigma):
    """

    :param data: testdata (only features)
    :param phi: P(Y=1)
    :param mu_pos: mean of X|y=1
    :param mu_neg: mean of X|y=0
    :param Sigma: Covariance matrix
    :return: predicted label array
    """
    testX = testX.values
    predY = []
    predY_prob = []
    for i in range(testX.shape[0]):
        prob_pos = GaussianProb(testX[i], mu_pos, Sigma) * phi
        prob_neg = GaussianProb(testX[i], mu_neg, Sigma) * (1-phi)
        if prob_pos >= prob_neg:
            predY.append(1)
            predY_prob.append(1-prob_pos)
        else:
            predY.append(0)
            predY_prob.append(prob_neg)
    predY = np.array(predY)
    predY_prob = np.array(predY_prob)
    return predY, predY_prob

################ Evaluation ###########################################################
def Accuracy(pred, true):
        return sum(pred==true) / len(pred)

def Test_trainsize(traindata, testdata, target):
    accu_pair = []
    for s in range(1,11):
        N = int(traindata.shape[0] * s/10)
        tr_part = traindata.iloc[:N,:]
        # print(tr_part)
        phi, mean_pos, mean_neg, Sigma = GaussianTrain(tr_part, target)
        testX = testdata[[col for col in testdata.columns if col != target]]
        testY = testdata[target]
        predY, probY = GaussianPredict(testX, phi, mean_pos, mean_neg, Sigma)
        accuracy_test = Accuracy(predY, testY)
        accu_pair.append((N, accuracy_test))
    x, y = zip(*accu_pair)
    y_max = np.argmax(y)
    plt.figure()
    plt.plot(x,y)
    plt.scatter(x[y_max],y[y_max], c='red')
    plt.xlabel("Training sample size")
    plt.ylabel("Accuracy")
    plt.title("MLE")
    plt.savefig("./Fig/MLE_trainsizetest.png")
    plt.show()

    return accu_pair

if __name__ == '__main__':
    traindata = pd.read_csv("propublicaTrain.csv", sep=',')
    testdata = pd.read_csv("propublicaTest.csv", sep=',')
    target = 'two_year_recid'

    phi, mean_pos, mean_neg, Sigma = GaussianTrain(traindata, target)
    testX = testdata[[col for col in testdata.columns if col != target]]
    testY = testdata[target]

    predY, probY = GaussianPredict(testX, phi, mean_pos, mean_neg, Sigma)
    accuracy_test = Accuracy(predY, testY)
    print("Testdata accuracy: {:.4f}".format(accuracy_test))

    plot_roc(testY, probY, "MLE")  # ROC Curve and AUC

    accu_diffsize = Test_trainsize(traindata, testdata, target)  # Test training sample size effect

    ############## Fairness analysis ################################################################
    df = pd.concat([testX['race'],pd.Series(predY), testY],axis=1)
    df.columns = ['race','ypred','ytrue']
    # Demographic parity
    df_race0 = df[df['race']==0]
    df_race1 = df[df['race']==1]
    p_race0_0 = (df_race0.shape[0]-df_race0['ypred'].sum())/df_race0.shape[0]
    p_race0_1 = df_race0['ypred'].sum() / df_race0.shape[0]
    p_race1_0 = (df_race1.shape[0]-df_race1['ypred'].sum())/df_race1.shape[0]
    p_race1_1 = df_race1['ypred'].sum() / df_race1.shape[0]

    # Equalized Odds (EO)
    df_race0_y0 = df_race0[df_race0['ytrue'] == 0]
    eo_race0_00 = (df_race0_y0.shape[0] - df_race0_y0['ypred'].sum()) / df_race0_y0.shape[0]
    df_race0_y1 = df_race0[df_race0['ytrue'] == 1]
    eo_race0_11 = df_race0_y1['ypred'].sum() / df_race0_y1.shape[0]
    df_race1_y0 = df_race1[df_race1['ytrue'] == 0]
    eo_race1_00 = (df_race1_y0.shape[0] - df_race1_y0['ypred'].sum()) / df_race1_y0.shape[0]
    df_race1_y1 = df_race1[df_race1['ytrue'] == 1]
    eo_race1_11 = df_race1_y1['ypred'].sum() / df_race1_y1.shape[0]

    # Predictive Parity (PP)
    df_race0_hy0 = df_race0[df_race0['ypred'] == 0]
    pp_race0_00 = (df_race0_hy0.shape[0] - df_race0_hy0['ytrue'].sum()) / df_race0_hy0.shape[0]
    df_race0_hy1 = df_race0[df_race0['ypred'] == 1]
    pp_race0_11 = df_race0_hy1['ytrue'].sum() / df_race0_hy1.shape[0]
    df_race1_hy0 = df_race1[df_race1['ypred'] == 0]
    pp_race1_00 = (df_race1_hy0.shape[0] - df_race1_hy0['ytrue'].sum()) / df_race1_hy0.shape[0]
    df_race1_hy1 = df_race1[df_race1['ypred'] == 1]
    pp_race1_11 = df_race1_y1['ytrue'].sum() / df_race1_y1.shape[0]


from argparse import ArgumentParser

from commands import dedup, snapshot
from commands.sync import sync
from drive.auth import connect

COMMANDS = [snapshot, dedup, sync]

def main():
    # Monkeypatches httplib2 to avoid issues with connection polling and oauth2client
    # (https://github.com/googleapis/google-api-python-client/issues/218)
    import httplib2shim
    httplib2shim.patch()

    parser = ArgumentParser()
    subparsers = parser.add_subparsers()
    subparsers.required = True
    subparsers.dest = 'command'
    for command in COMMANDS:
        command.register_parser(subparsers)

    args = parser.parse_args()
    actual = {
        'service': connect(),
        'args': args
    }
    if 'api_key' in args:
        actual['service'] = connect(args.api_key)

    args.func(**actual)

if __name__ == '__main__':
    main()


import pygame as pg, random as rd
from pygame.locals import *
#defines the objects in game. like the snake and the apple (could be more than one)
class Stuff:
    def __init__(self, position, body, color, points = None, record = None, direction = None):
        self.position = position
        self.body = body
        self.color = color
        self.points = points
        self.record = record
        self.direction = direction
#defines the apple coordinates
def on_grid_random():
    x, y = rd.randint(0, 690), rd.randint(0, 690)
    return (x//10 * 10, y//10 * 10)
#keeps snake moving
def move(wich_snake):
    for i in range(len(wich_snake.position) - 1, 0, -1):
        wich_snake.position[i] = (wich_snake.position[i-1][0], wich_snake.position[i-1][1])
    if wich_snake.direction == up:
        wich_snake.position[0] = (wich_snake.position[0][0], wich_snake.position[0][1] - 10)
    if wich_snake.direction == down:
        wich_snake.position[0] = (wich_snake.position[0][0], wich_snake.position[0][1] + 10)
    if wich_snake.direction == left:
        wich_snake.position[0] = (wich_snake.position[0][0] - 10, wich_snake.position[0][1])
    if wich_snake.direction == right:
        wich_snake.position[0] = (wich_snake.position[0][0] + 10, wich_snake.position[0][1])
#changes snake direction
def key_verify(wich_snake):
    for event in pg.event.get():
        if event.type == QUIT:
            pg.quit()
        if event.type == KEYDOWN:
            if event.key == K_UP:
                if wich_snake.direction != down:
                    wich_snake.direction = up
            if event.key == K_DOWN:
                if wich_snake.direction != up:
                    wich_snake.direction = down
            if event.key == K_LEFT:
                if wich_snake.direction != right:
                    wich_snake.direction = left
            if event.key == K_RIGHT:
                if wich_snake.direction != left:
                    wich_snake.direction = right
#verify colissions and defines the pontuation
def colission(wich_snake):
    if wich_snake.points > wich_snake.record: wich_snake.record += 1

    if wich_snake.position[0] == apple.position:
        wich_snake.position.append([700, 700])
        apple.position = on_grid_random()
        wich_snake.points += 1

    if wich_snake.position[0][0] in wall or wich_snake.position[0][1] in wall:
        wich_snake.direction = right
        snake.position = [(200, 200), (210, 200), (220, 200)]
        apple.position = on_grid_random()
        wich_snake.points = 0
        wich_snake.direction = hit_wall

    if cnt > 2:
        if wich_snake.position[0] in wich_snake.position[1:-2]:
            wich_snake.position = [(200, 200), (210, 200), (220, 200)]
            apple.position = on_grid_random()
            wich_snake.points = 0
            wich_snake.direction = ate_itself
#variables used in game
up, down, left, right, ate_itself, hit_wall = 0, 1, 2, 3, 4, 5
snake = Stuff(([(200, 200), (210, 200), (220, 200)]), pg.Surface((10, 10)), (255, 215, 0), 0, 0, right)
apple = Stuff(on_grid_random(), pg.Surface((10, 10)), (50, 205, 50))
wall = [700, -10]
clock = pg.time.Clock()
cnt = 0
pg.init()
screen = pg.display.set_mode((700, 700))
#game running
while True:
    caption = 'Snake size ' + str(snake.points) + ' | record: ' + str(snake.record)
    if snake.direction == ate_itself:
        caption = 'Ate itself! Choose a new direction'
    if snake.direction == hit_wall:
        caption = 'It hit the wall! choose a new direction'
    cnt += 1
    clock.tick(35)
    screen.fill((255, 255, 250))
    apple.body.fill(apple.color)
    snake.body.fill(snake.color)
    screen.blit(apple.body, apple.position)

    pg.display.set_caption(caption)

    key_verify(snake)
    move(snake)
    colission(snake)

    for pos in snake.position:
        screen.blit(snake.body, pos)
    pg.display.update()


class Trie:
    def __init__(self):
        # initial pointer
        self.root = {}

    def add_word(self, word):
        curr_node = self.root
        for letter in word:
            if letter not in curr_node:
                curr_node[letter] = {}
            curr_node = curr_node[letter]
        curr_node["*"] = "*"

    def common_prefix(self, word):
        lcp = ""
        curr = self.root
        for char in word:
            if char in curr and len(curr) == 1:
                lcp += char
                curr = curr[char]
        return lcp

class Solution:
    #
    #     Write a function to find the longest common prefix string amongst an array of strings.

    #     If there is no common prefix, return an empty string "".

    #     Example 1:

    #     Input: strs = ["flower","flow","flight"]
    #     Output: "fl"
    #     Example 2:

    #     Input: strs = ["dog","racecar","car"]
    #     Output: ""
    #     Explanation: There is no common prefix among the input strings.
    #

    def longestCommonPrefix(self, strs: List[str]) -> str:
        trie = Trie()
        for word in strs:
            trie.add_word(word)

        return trie.common_prefix(strs[0])


"""
This module contains tools and functions to monitor performance of a model
"""
from typing import Dict, Any, Union
import pandas as pd
from pathlib import Path

from starter import common
from sklearn.metrics import fbeta_score, precision_score, recall_score

class PerformanceEvaluator:
    def __init__(self, dataframe: pd.DataFrame, label_column: str, prediction_column: str = 'pred'):
        """

        Args:
            dataframe: the input dataset. It must include the label and prediction columns
            label_column: column of the binary encoded labels
            prediction_column: column of the binary encoded predictions
        """
        self.df = dataframe
        self.label_column = label_column
        self.prediction_column = prediction_column

    def compute_performance_on_slice(self, feature: str) -> Dict[Any, common.BinaryConfusionMatrix]:
        """ Slices the data based on the input feature and compute the common.BinaryConfusionMatrix for each slice

        Args:
            feature: the feature (column name) used to generate the data slices

        Returns:
            a confusion matrix for each category of the selected feature.
            The output is provided as dictionary with
            {key: value} ---> {category for the slice: confusion matrix on the category}

        """
        label_column = self.label_column
        prediction_column = self.prediction_column
        return {x[0]: common.BinaryConfusionMatrix(common.confusion_matrix_df(x[1], label_column, prediction_column))
                for x in self.df.groupby(feature)}

    def get_summary_slice(self, feature: str, output_file: Union[str, None]) -> pd.DataFrame:
        """ Merges together the performance on each category for the input feature.
        Each category has a different number of samples.
        To get the total number of sample for each category is sufficient to sum up the number of true/false
        positives/negatives (in the output dataframe ['tp', 'fp', 'tn', 'fn']

        Args:
            feature: the feature (column name) used to generate the data slices
            output_file: if not None, writes the summary to the specified file

        Returns:
            the summary of the performance for each category of the given slice (as pd.DataFrame)

        """
        cm_dict = self.compute_performance_on_slice(feature)
        slice_perf = pd.concat(list(map(lambda x: x.to_df(), cm_dict.values())), ignore_index=True)
        slice_perf.index = cm_dict.keys()

        if output_file:
            if not Path(output_file).parent.is_dir():
                Path(output_file).mkdir(parents=True)
            slice_perf.to_csv(output_file)
        return slice_perf

def compute_model_metrics(y, preds):
    """
    Validates the trained machine learning model using precision, recall, and F1.

    Inputs
    ------
    y : np.array
        Known labels, binarized.
    preds : np.array
        Predicted labels, binarized.
    Returns
    -------
    precision : float
    recall : float
    fbeta : float
    """
    fbeta = fbeta_score(y, preds, beta=1, zero_division=1)
    precision = precision_score(y, preds, zero_division=1)
    recall = recall_score(y, preds, zero_division=1)
    return precision, recall, fbeta


from itertools import combinations
from copy import deepcopy
# 벽세우기
def wall(k):
    new_arr = deepcopy(arr)
    for i in walls_comb[k]:
        new_arr[i[0]][i[1]] = 1
    return new_arr

# virus 살포
def bfs(new_arr, r, c):
    visited[r][c] = 1
    Q = []
    Q.append([r,c])
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]
    while len(Q):
        s = Q.pop(0)
        for i in range(4):
            nr = s[0] + dr[i]
            nc = s[1] + dc[i]
            if 0 <= nr < N and 0 <= nc < M:
                if new_arr[nr][nc] == 0 and visited[nr][nc] == 0:
                    new_arr[nr][nc] = 2
                    Q.append([nr, nc])
                elif new_arr[nr][nc] == 1:
                    continue
    return new_arr

#안전영역 구하기
def safe(new_arr):
    cnt = 0
    for i in range(N):
        for j in range(M):
            if new_arr[i][j] == 0:
                cnt += 1
    return cnt

N, M = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
visited = [[0]*M for _ in range(N)]
#바이러스 초기 위치 tc: 1 - [[0, 0], [1, 5]]
virus = []  #바이러스 위치
walls = []  #벽 설치 가능 위치
for i in range(N):
    for j in range(M):
        if arr[i][j] == 2:
            virus.append([i, j])
        elif arr[i][j] == 0:
            walls.append([i, j])
# 벽 3개 설치 조합
walls_comb = list(combinations(walls, 3))
# wall -> virus -> safety cnt
safety = []     #안전영역 크기 종합 리스트
walls_arr = []
# wall함수를 돌면서 return 되는 new_arr를 walls_arr에 append
for i in range(len(walls_comb)):
    temp = wall(i)
    walls_arr.append(temp)
# 벽을 세운 모든 경우의 수에서 virus bfs를 한 뒤 safety에 append
for i in range(len(walls_arr)):
    new_arr = walls_arr[i]
    for j in virus:
        result = bfs(new_arr, j[0], j[1])
        if j == virus[-1]:
            safe_cnt = safe(result)
            safety.append(safe_cnt)
print(max(safety))


from collections import deque
m, n = map(int, input().split())
field = [list(map(int, input().split())) for _ in range(m)]
visited = [[-1]*n for _ in range(m)]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]

def dfs(start):
    x, y = start
    if x == m-1 and y == n-1:
        return 1
    if visited[x][y] != -1:
        return visited[x][y]
    count = 0
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or ny < 0 or nx >= m or ny >= n:
            continue
        if field[nx][ny] < field[x][y]:
           count += dfs([nx,ny])
    visited[x][y] = count
    return visited[x][y]
print(dfs([0,0]))
# 500 X 500의 이동영역을 계산은 시간 초과 발생
# 시간을 줄이기 위해서 DP를 적용해서 문제 풀이를 진행해야 함
# visited를 0으로 초기화한 경우 해당 0인 경우에 대한 처리가 되지 않아서 시간 초과 발생


2 == 1 + 1

14 < 13

12 <= 6 + 6

9 == 3**2 and 12 - 3 != 9

9 == 3**2 or 12 - 3 != 9

if True:
    print('bidibix')

if 2 == 4:
    print('problème') #ne sera pas affiché car le test est faux#

if 4 < 5:
    print('zêta')

k = int(input('Rentrer une valeur :')) #permet à l'utilisateur de choisir la valeur de k#

if k <= 0:
    print('k est négatif')
elif k <= 10:
    print('k est plus petit que 10')
else:
    print('k est strictement plus grand que 10')

def styl_vt(n): #n nb de stylos#
    if n < 20:
        return 0.7*n
    if n < 250: #on met un if à la place du elif#
        return 0.9 * (0.7*n)
    return 0.85 * (0.7*n)
    #pas de else & on aligne ce dernier return avec les if#

print(styl_vt(10), styl_vt(50), styl_vt(300))

liste = [2, 4, 7.8 , 'plop'] #exemple de liste#

cpt = 1
for k in range(5):
    cpt = 3*cpt #à chaque passage de boucle, cpt est multiplié par 3#
    print(cpt)

def livret(n):
    s = 600 #somme à l'ouverture#
    for t in range(n): #sert à décompter les années#
        s = 1.0115*s - 4.2
    return round(s, 2) #arrondit au centime s#

print(livret(5), livret(10), livret(20))


import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

class Cmapper:

    def __init__(self, cmap, maximum=None, minimum=None):
        self.maximum = maximum
        self.minimum = minimum

        self.cmapper = cm.get_cmap(cmap)

    def color_bar(self):
        # generate color bar image
        depth = np.linspace((self.minimum, ), (self.maximum, ), 1000, axis=1)
        # resize
        # depth = np.expand_dims(depth, axis=0)
        depth = np.resize(depth, (100, 1000))
        # generate color bar
        depth = self(depth)
        # plot
        img = plt.imshow(depth)
        # adjust axis
        img.axes.get_yaxis().set_visible(False)
        # new x axis
        plt.xticks(np.linspace(0, 1000, 11), np.linspace(self.minimum, self.maximum, 11))
        return img

    def __call__(self, depth):
        # normalize
        if self.minimum is None:
            self.minimum = depth.min()
        if self.maximum is None:
            self.maximum = depth.max()

        depth = (depth - self.minimum) / (self.maximum - self.minimum)

        depth = self.cmapper(depth, bytes=True)[:, :, :3]
        return depth


from __future__ import unicode_literals, annotations
import discord
from discord.ext.commands import Bot
import random
import asyncio

admins = []

def load_admin_commands(bot: Bot, fixed_response: str, name: str) -> str:
    # fixed response = "I work and speak only for my MASTER!"

    # ==== Say Command ====
    help_string = "Admin Commands: \n"

    global admins

    command = ("bite", "The " + name + " bites the target.")

    @bot.command(name=command[0], help=command[1])
    async def bite(context, arg: str):
        if context.message.author.id in admins:
            await context.message.channel.send("*The Goose Bites " + arg + "," +
                                               " die heathen!*")
        else:
            await context.message.channel.send("...")
            await asyncio.sleep(3)
            await context.message.channel.send("*The Goose bites " +
                                               context.message.author.name +
                                               " instead!*")

    help_string += "\t" + ": ".join(command) + "\n"

    command = ("admin", "Emily can grant admin.")

    @bot.command(name=command[0], help=command[1])
    async def admin(context, target: discord.User):
        if context.message.author.id == 397458781665230848:
            if target.id not in admins:
                admins.append(target.id)
                await context.message.channel.send("Successfully granted " +
                                                   target.name
                                                   + " admin for this session.")
            else:
                await context.message.channel.send(target.name +
                                                   " is already registered.")

    help_string += "\t" + ": ".join(command) + "\n"

    command = ("remove_admin", "Emily can remove admin.")

    @bot.command(name=command[0], help=command[1])
    async def remove_admin(context, target: discord.User):
        if context.message.author.id == 397458781665230848:
            if target.id in admins:
                admins.remove(target.id)
                await context.message.channel.send("Successfully removed " +
                                                   target.name
                                                   + " admin for this session.")
            else:
                await context.message.channel.send(target.name +
                                                   " is not admin.")

    help_string += "\t" + ": ".join(command) + "\n"

    return help_string


def print_pairs(arr, N):
    # hash set
    hash_set = set()

    for i in range(0, len(arr)):
        val = N - arr[i]
        if (val in hash_set):  # check if N-x is there in set, print the pair
            print("Pairs " + str(arr[i]) + ", " + str(val))
        hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 5
print_pairs(arr, N)

from collections import Counter
d1 = {'key1': 50, 'key2': 100, 'key3':200}
d2 = {'key1': 200, 'key2': 100, 'key4':300}
new_dict = Counter(d1) + Counter(d2)
print(new_dict)


import base64
#后门基本配置
class Description:

    def __init__(self,immortalTrojFilename,subTrojFileName,trojKey,immortalTrojContent):
        self.immortalTrojFilename=immortalTrojFilename
        self.subTrojFilename=subTrojFileName
        self.trojKey=trojKey
        self.trojContent=immortalTrojContent

    @property
    def subTrojectParam(self):
        return self.trojKey[:5]


import sys
import os
import numpy as np
from pandas import DataFrame
from scipy import stats

words = ["hicha", "hishu", "hisa", "hivu"]
distractors = ["hichu", "hisha", "hisu", "hiva"]

timecourse_types = ["dw_dd", "w1_d1", "w2_d2"]

time_lbls = ["220_495","285_295", "300-360"]
time_periods = [[220, 495], [285, 295], [300, 360]]

behav_parameters = ["learning_criterion", "false_alarms"]

stc_table_path = "/data/programs/razoral/insula_timecourses/target_timecourses/corr_tables_insula/corr_table_insula_{}_{}.tsv"
behavioral_table_path = "/data/programs/razoral/insula_timecourses/examples/active1_{}_per_subject.tsv"

def calc_corr(beh_table_path, stc_table_path, timecourse_types, behav_parameter, time_period, time_lbl, words):

	corr_table = np.zeros(shape = (len(timecourse_types) , len(words), 2))

	for timecourse_type_id, timecourse_type in enumerate(timecourse_types):

		beh_df = DataFrame.from_csv(beh_table_path.format(behav_parameter), sep = "\t")
		stc_df = DataFrame.from_csv(stc_table_path.format(timecourse_type, time_lbl), sep = "\t")

		# exclude subjects
		sub_list = beh_df.index
		actual_sub_list = stc_df.index
		sub_to_del = sub_list.difference(actual_sub_list)
		beh_df = beh_df.drop(sub_to_del)

		# calc correlation
		for word_id, word in enumerate(words):
			corr_cur = stats.pearsonr(beh_df[word],stc_df[word])
			corr_table[timecourse_type_id, word_id, :] = corr_cur

		# form corr table

	os.makedirs("/data/programs/razoral/insula_timecourses/target_timecourses/behave_correlations_insula", exist_ok=True)
	f = open("/data/programs/razoral/insula_timecourses/target_timecourses/behave_correlations_insula/pearson_corr_insula_{}_{}.tsv".format(behav_parameter, time_lbl), "w")
	f.write("timecourse_type")
	for word in words:
		f.write("\t{}_corr\t{}_p-val".format(word, word))
	f.write("\n")
	for timecourse_type_id, timecourse_type in enumerate(timecourse_types):
		f.write("{}".format(timecourse_type))
		for word_id, word in enumerate(words):
			f.write("\t{:e}\t{:e}".format(corr_table[timecourse_type_id, word_id, 0], corr_table[timecourse_type_id, word_id, 1]))
		f.write("\n")
	f.close()

for t, time_period in enumerate(time_periods):
	for behav_parameter in behav_parameters:
		calc_corr(behavioral_table_path, stc_table_path, timecourse_types, behav_parameter, time_period, time_lbls[t], words)


import re
from collections import defaultdict
from collections import deque

filename = '2020/day7/day7.txt'
puzzle_input = open(filename).readlines()

def get_containers():
    """ returns a dictionary that maps a string to a set of strings
    with all bags that can contain that string """
    containers = defaultdict(set)
    for rule in puzzle_input:
        outer_bag = re.match('([A-Za-z ]+) bags', rule)[1]
        inner_bags = re.findall(r'(\d+) ([A-Za-z ]+?) bags?', rule)
        for bag in inner_bags:
            containers[bag[1]].add(outer_bag)
    return containers

def get_num_containing():
    """ returns a dictionary that maps a string to a set of tuples (n, b)
    such that the key must contain n bags of type b """
    containing = {}
    for rule in puzzle_input:
        outer_bag = re.match(r'([A-Za-z ]+) bags', rule)[1].split(" bags contain no other")[0]
        inner_bags = re.findall(r'(\d+) ([A-Za-z ]+?) bags?', rule)
        containing[outer_bag] = {(int(t[0]), t[1]) for t in inner_bags}
    return containing

def get_all_possible_containers(color):
    containers = get_containers()
    possible = set()
    seen = set()
    queue = deque()
    queue.append(color)
    while queue:
        c = queue.pop()
        for container in containers[c]:
            if container not in seen: # prevents cycles
                possible.add(container)
                seen.add(container)
                queue.append(container)
    return possible

def get_total_num_containing(color, containing):
    num_containing = 0
    for t in containing[color]:
        num_containing += t[0]*(1 + get_total_num_containing(t[1], containing))
    return num_containing

def part_1():
    return len(get_all_possible_containers('shiny gold'))

def part_2():
    return get_total_num_containing('shiny gold', get_num_containing())

print("Part 1: {}".format(part_1()))
print("Part 2: {}".format(part_2()))


# a = [1,3,5,'a',"aniket",[1,2,3,4],(1,2,3,4),{'name':'pyton'}]

# print(isinstance(a,list))
# print(a)

# print(a[0:3])
# print(a[5:])
# print(a[:5])
# print(a[4]+' likes '+a[-1]['name'])
# print(a[5]*5)

mobileBrand = []
no = int(input('Enter number  of value you want to enter : '))

for i in range(0,no):
    mobileBrand.append(input("Enter element : "))

print("Mobile brands : ")
for i in mobileBrand:
    print(i)


'''Lv.1 시저 암호'''

# 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12926

# 풀이 1
def solution(s, n):
    answer = ''
    temp = ''
    for word in s:
        if word == ' ': answer += ' '
        else:
            temp = chr(ord(word) + n)
            if 'a' <= word and word <= 'z' and temp > 'z':
                temp = chr(ord(temp) - 26)
            elif 'A' <= word and word <= 'Z' and temp > 'Z':
                temp = chr(ord(temp) - 26)
            answer += temp

    return answer

# 풀이 2
def solution2(s, n):
    s = list(s)
    for i in range(len(s)):
        if s[i].isupper():
            s[i] = chr((ord(s[i]) - ord('A') + n) % 26 + ord('A'))
        elif s[i].islower():
            s[i] = chr((ord(s[i]) - ord('a') + n) % 26 + ord('a'))

    return "".join(s)


import numpy as np
import sympy
from pytest import approx

from analysis import Analysis
from fexc import WeightCalculator, WeightedDensity, WD
from test_weighted_density_analytic import calculate_analytic

def test_weighted_densities_simple() -> None:
    dr = 2 ** -3
    n = 32
    ana = Analysis(dr, n)
    wc = WeightCalculator()

    # expect this to take a while
    wd = WeightedDensity(ana, wc)
    rho_bulk = 0.1
    rho = rho_bulk * np.ones(n)

    n3 = wd.calc_density(WD.N3, rho)
    # the edge is tricky, need to extrapolate
    assert n3 == approx(rho_bulk * np.ones(n) * np.pi / 6)

    n2 = wd.calc_density(WD.N2, rho)
    assert n2 == approx(rho_bulk * np.ones(n) * np.pi)

    n2v = wd.calc_density(WD.N2V, rho)
    assert n2v == approx(np.zeros(n), abs=1e-13)

    n11 = wd.calc_density(WD.N11, rho)
    assert n11 == approx(np.zeros(n), abs=1e-13)

    psi2 = wd.calc_density(WD.PSI2, rho)
    assert psi2 == approx(rho_bulk * np.ones(n) * np.pi)

    psi3 = wd.calc_density(WD.PSI3, rho)
    assert psi3 == approx(rho_bulk * np.ones(n) * np.pi / 6)

    r = np.arange(n) * dr
    r[0] = 1  # it's not, but it avoids the division warning
    R = 0.5
    psi2v_ana = np.pi * (-(R - r) ** 2 * abs(R - r) + (R + r) ** 3 + 3 * (R + r) * (R ** 2 - r ** 2) - 3 * (
                R ** 2 - r ** 2) * abs(R - r)) / (3 * r)
    psi2v_ana[0] = np.pi
    psi2v = wd.calc_density(WD.PSI2V, rho)
    assert psi2v[:-8] == approx(rho_bulk * psi2v_ana[:-8])

def test_weighted_densities() -> None:
    R = sympy.Rational(1, 2)
    r, rp = sympy.symbols('r rp', real=True)

    rho = sympy.Rational(2, 10) + sympy.sin(sympy.pi*rp)/1000
    rho_eval = sympy.lambdify([rp], rho)

    n11, n2, n2v, n3, psi11, psi2v = calculate_analytic(R, r, rp, rho)

    dr = 2 ** -6
    n = 256
    r = np.array(np.arange(n)*dr, dtype=np.longdouble)
    ana = Analysis(dr, n)
    wc = WeightCalculator()
    wd = WeightedDensity(ana, wc)

    rho_discrete = np.array([rho_eval(i * dr) for i in range(n)])

    n3_discrete, n2_discrete, n2v_discrete, n11_discrete, \
        psi3_discrete, psi2_discrete, psi2v_discrete, psi11_discrete \
        = wd.calc_densities([WD.N3, WD.N2, WD.N2V, WD.N11, WD.PSI3, WD.PSI2, WD.PSI2V, WD.PSI11], rho_discrete)

    n3_ana = n3(r)
    n2_ana = n2(r)
    n2v_ana = n2v(r)
    n11_ana = n11(r)
    psi2_ana = n2_ana
    psi3_ana = n3_ana
    psi2v_ana = psi2v(r)
    psi11_ana = psi11(r)

    mask = int(0.5/dr)
    np.savetxt("n3.dat", np.hstack((r.reshape(-1, 1), n3_discrete.reshape(-1, 1), n3_ana.reshape(-1, 1))))
    np.savetxt("n2.dat", np.hstack((r.reshape(-1, 1), n2_discrete.reshape(-1, 1), n2_ana.reshape(-1, 1))))
    np.savetxt("n2v.dat", np.hstack((r.reshape(-1, 1), n2v_discrete.reshape(-1, 1), n2v_ana.reshape(-1, 1))))
    np.savetxt("n11.dat", np.hstack((r.reshape(-1, 1), n11_discrete.reshape(-1, 1), n11_ana.reshape(-1, 1))))
    np.savetxt("psi3.dat", np.hstack((r.reshape(-1, 1), psi3_discrete.reshape(-1, 1), psi3_ana.reshape(-1, 1))))
    np.savetxt("psi2.dat", np.hstack((r.reshape(-1, 1), psi2_discrete.reshape(-1, 1), psi2_ana.reshape(-1, 1))))
    np.savetxt("psi2v.dat", np.hstack((r.reshape(-1, 1), psi2v_discrete.reshape(-1, 1), psi2v_ana.reshape(-1, 1))))
    np.savetxt("psi11.dat", np.hstack((r.reshape(-1, 1), psi11_discrete.reshape(-1, 1), psi11_ana.reshape(-1, 1))))

    assert n3_discrete[:-mask] == approx(n3_ana[:-mask], rel=1e-5)
    assert n2_discrete[:-mask] == approx(n2_ana[:-mask], rel=1e-5)
    assert n2v_discrete[mask // 2:-mask] == approx(n2v_ana[mask // 2:-mask], rel=2e-3)
    assert n11_discrete[mask // 2:-mask] == approx(n11_ana[mask // 2:-mask], rel=2e-3)
    assert psi3_discrete[:-mask] == approx(psi3_ana[:-mask], rel=1e-5)
    assert psi2_discrete[:-mask] == approx(psi2_ana[:-mask], rel=1e-5)
    assert psi2v_discrete[mask // 2:-mask] == approx(psi2v_ana[mask // 2:-mask], rel=2e-3)
    assert psi11_discrete[mask // 2:-mask] == approx(psi11_ana[mask // 2:-mask], rel=2e-3)


import openai
import pickle
import os

def cut_message(message,turns):
    return message[max(0,len(message)-turns*2+1):]

def add_assistant_message_latest(message):
    if message[0]["role"] == "assistant":
        message_assistant = message.pop(0)
        message.insert(len(message)-1,message_assistant)
    return message

def preprocess(message,turns,support):
    if support:
        message = add_assistant_message_latest(message)
    message = cut_message(message,turns)
    return message

print("タイトルを入力してください")
title = input()
print("保存する対話ターン数を指定してください。指定しない場合は5です。")
turns = input()
if turns == "":
    turns = 5
else:
    turns = int(turns)
if os.path.isfile("history/pic/{}.pic".format(title)):
    with open("history/pic/{}.pic".format(title), 'rb') as f:
        dialogue_message = pickle.load(f)
    print("前回の対話です。")
    for line in dialogue_message:
        print("role:{} context:{}".format(line["role"],line["content"]))
else:
    dialogue_message = []
    print("ChatGPTに設定を入力してください。不要の場合はenterを押してください")
    system_setting = input()
    if system_setting != "":
        dialogue_message.append({"role": "system","content": system_setting})
    print("エージェントへの支持を直前に持っていきますか？(yes/no)、指定しない場合はnoです。")
    support = input()
    if support == "yes":
        support = True
    else:
        support = False

flag=True

while flag:
    print("モデルを選択してください。3.5を入力するとGPT-3.5,4を入力するとGPT-4を使用します。")
    input_model = input()
    if input_model == "3.5":
        model = "gpt-3.5-turbo"
        flag=False
    elif input_model == "4":
        model = "gpt-4"
        flag=False

flag=True
print("質問を入力してください")
while flag:
    text = input()
    if text == "exit":
        exit()
    else:
        dialogue_message.append({"role": "user","content": text})

    send_text_data = preprocess(dialogue_message,turns,support)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=send_text_data
        )
    print(response["choices"][0]["message"]["content"])
    dialogue_message.append({"role": "assistant","content": response["choices"][0]["message"]["content"]})
    # オブジェクト保存
    with open("history/pic/{}.pic".format(title),"wb") as f:
        pickle.dump(dialogue_message,f)
    # textファイル用
    text_data = ""
    for line in dialogue_message:
        text_data += "role:{}\ncontext:{}\n".format(line["role"],line["content"])
    with open("history/text/{}.txt".format(title),"w",encoding="utf-8") as f:
        f.write(text_data)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from sklearn.metrics import accuracy_score, \
    f1_score, \
    precision_score, \
    recall_score

def print_config(config):

    print(" |   MODEL:          | %s |" % config.__class__.__name__)

    keys = [x for x in dir(config) if not x.startswith('__')]

    for x in keys:
        print(" | %-*s | %-*s |" % (16, x, 8, str(getattr(config, x))[:6]))

def evaluate(p, y, print_it=True):

    precision = precision_score(y, p, average="samples")
    recall = recall_score(y, p, average="weighted")
    f1 = f1_score(y, p, average="weighted")
    accuracy = accuracy_score(y, p)

    if print_it:
        print("F1 Score: ", f1)
        print("Recall: ", recall)
        print("Precision: ", precision)
        print("Accuracy: ", accuracy)

    return [f1, recall, precision, accuracy]

def evaluate_multilabel(predictions, y_data, threshold, print_it = True):
    for pred in predictions:
        pred[pred > threshold] = 1
        pred[pred < threshold] = 0

    p = np.array([x.astype(int).tolist() for x in predictions])
    y = np.array([x.astype(int).tolist() for x in y_data])

    if print_it:
        print("Threshold: %.6f" % threshold)

    return evaluate(p, y, print_it)

def evaluate_multiclass(predictions, y_data, print_it=True):

    y = np.array([x.astype(int).tolist() for x in y_data])
    pred = [[0 for x in range(len(y[0]))] for z in range(len(y))]
    print(predictions.shape)
    print(len(pred))
    for index in range(0, predictions.shape[0]):
        pred[index][predictions[index].argmax()] = 1

    p = np.array([x for x in pred])

    return evaluate(p, y, print_it)

def make_loss_graph(CONST):
    from util.utils import load_pickle as load
    gru = load(CONST.DATA_DIR + 'GRU')
    lstm = load(CONST.DATA_DIR + 'LSTM')
    birnn = load(CONST.DATA_DIR + 'BiRNN')

    cutoff = 105

    gru = gru[:cutoff]
    lstm = lstm[:cutoff]
    birnn= birnn[:cutoff]

    import matplotlib.pyplot as plt
    x = [i for i in range(cutoff)]
    plt.plot(np.array(x), np.array(gru))
    plt.plot(np.array(x), np.array(lstm))
    plt.plot(np.array(x), np.array(birnn))
    plt.legend(['GRU', 'LSTM', 'BiRNN LSTM'], loc='upper right')
    plt.savefig("losses_all.png")
    print("all losses plot saved")

def re_evalute_slot3(CONST):

    from util.utils import load_pickle as load
    birnn = load(CONST.DATA_DIR + "BiRNNslot3" + "_predictions")
    evaluate_multiclass(birnn["predictions"], birnn["y"], True)

def re_evalute(CONST):
    threshold = float(CONST.THRESHOLD)

    from util.utils import load_pickle as load
    gru = load(CONST.DATA_DIR + "GRU" + "predictions")
    lstm = load(CONST.DATA_DIR + "LSTM" + "predictions")
    biRNN = load(CONST.DATA_DIR + "BiRNN" + "predictions")

    print("###########  GRU ###############")
    find_best_slot1("gru", gru["predictions"], gru["y"])
    print("########### LSTM ##############")
    find_best_slot1("lstm", lstm["predictions"], lstm["y"])
    print("########### BiRNN LSTM ##############")
    find_best_slot1("birnn", biRNN["predictions"], biRNN["y"])

def find_best_slot1(name, pred, y):

    max_threshhold_result = 0
    score = 0
    results = {}
    f1 = []
    recall = []
    precision = []
    thresholds = np.arange(0.04001, 0.20000, 0.001)
    for t in thresholds:
        pred_copy = np.copy(pred)
        t_result = evaluate_multilabel(pred_copy, y, t, print_it=False)

        if t_result[0] > score:
            score = t_result[0]
            max_threshhold_result = t
            results = t_result

        f1.append(t_result[0])
        recall.append(t_result[1])
        precision.append(t_result[2])

    print("Threshold: %.6f" % max_threshhold_result)
    print("F1 Score: ", results[0])
    print("Recall: ", results[1])
    print("Precision: ", results[2])

    import matplotlib.pyplot as plt
    plt.plot(np.array(thresholds), np.array(f1), '--')
    plt.plot(np.array(thresholds), np.array(recall))
    plt.plot(np.array(thresholds), np.array(precision), ':')
    plt.legend(['F1', 'Recall', 'Precision'], loc='upper right')
    plt.savefig("score_" + name + ".png")
    try:
        plt.close()
    except AttributeError as e:
        pass
    print("Saved BiRNN F1, Recall, and Precision")

if __name__ == "__main__":

    import argparse
    from read.config_reader import CONST
    CONST.parse_argument(argparse.ArgumentParser())

    #make_loss_graph(CONST)

    re_evalute(CONST)

    # slot 3
    re_evalute_slot3(CONST)


#Python if else, for loop, and range() Exercises with Solutions
#Execise 1: Print first 10 natural numbers using while loop
#Extremely simple. A good warmup.
print("Exercise 1!")
counter = 1
while counter <=10:
    print(counter)
    counter += 1

#Exercise 2: Print the following pattern
#They then provide a picture. It shouldn't be too hard.
print("Exercise 2!")
row = 5
for counter1 in range(1, row + 1, 1):
    for counter2 in range(1, counter1 + 1):
        print(counter2, end=' ')
    print("")

# #Exercise 3: Calculate the sum of all numbers from 1 to a given number
# #just a simple bit of math between the loop and range
# print("Exercise 3!")
# s = 0
# n = int(input("Enter a number to be added all the way from 1: "))
# for i in range(1, n + 1, 1):
#     s += i
# print("\n")
# print("Sum is:", s)
#Commented out for expediency

#Exercise 4: Write a program to print multiplication table of a given number
#They actually meant the first 10, so good thing I read ahead
print("Exercise 4!")
n = 2
for i in range(1, 11, 1):
    product = n * i
    print(product)

#Exercise 5: Display numbers from a list using a loop
'''They then give a series of instructions:
    The number must be divisible by five
    If the number is greater than 150, then skip it and move to the next number
    If the number is greater than 500, then stop the loop
    numbers = [12, 75, 150, 180, 145, 525, 50]
'''
print("Exercise 5!")
numbers = [12, 75, 150, 180, 145, 525, 50]
for item in numbers:
    if item > 500:
        break
    elif item > 150:
        continue
    elif item % 5 == 0:
        print(item)

#Exercise 6: Count the total number of digits in a number
numberToCount = 75869
count = 0
while numberToCount != 0:
    numberToCount = numberToCount // 10
    count = count + 1
print("Total digits are:", count)

#Exercise 7: Print the following pattern.
#Just a simple counter.
n = 5
k = 5
for x in range(0,n+1):
    for y in range(k-x,0,-1):
        print(y,end=' ')
    print()

#Exercise 8: Print list in reverse order using a loop
list1 = [10, 20, 30, 40, 50]
new_list = reversed(list1)
for item in new_list:
    print(item)

#Exercise 9: Display numbers from -10 to -1 using for loop
for num in range(-10, 0, 1):
    print(num)