import csv
from sklearn.neighbors import KNeighborsClassifier

#Voter class representing voter
class Voter:
  def __init__(self, optimus_id, age, party, ethnicity, income, education, marital_status, occupation_industry,
              vh00p, vh00g, vh02p, vh02g,
              vh04p, vh04g, vh06p, vh06g,
              vh08p, vh08g, vh10p, vh10g, vh12p, vh12g, vh14p,
              net_worth, donates_to_liberal_causes, donates_to_conservative_causes, congressional_district, designated_market_area,
              g08_precinct_turnout, g10_precinct_turnout, g12_precinct_turnout,
              p08_precinct_turnout, p10_precinct_turnout, p12_precinct_turnout):
    self.optimus_id = optimus_id

    #Previous election data is coming as string
    #Converting string to integer value
    self.vh00p = int(vh00p)
    self.vh02p = int(vh02p)
    self.vh04p = int(vh04p)
    self.vh06p = int(vh06p)
    self.vh08p = int(vh08p)
    self.vh10p = int(vh10p)

    self.vh00g = int(vh00g)
    self.vh02g = int(vh02g)
    self.vh04g = int(vh04g)
    self.vh06g = int(vh06g)
    self.vh08g = int(vh08g)
    self.vh10g = int(vh10g)

    self.vh12p = int(vh12p)
    self.vh12g = int(vh12g)

    self.vh14p = int(vh14p)
    # Percint turnout information was missing on some voters
    # Checking if value string is "0.32" or ""
    if len(g08_precinct_turnout) == 0:
      g08_precinct_turnout = "0"
    if len(p08_precinct_turnout) == 0:
      p08_precinct_turnout = "0"
    if len(g10_precinct_turnout) == 0:
      g10_precinct_turnout = "0"
    if len(p10_precinct_turnout) == 0:
      p10_precinct_turnout = "0"
    if len(p12_precinct_turnout) == 0:
      p12_precinct_turnout = "0"
    if len(g12_precinct_turnout) == 0:
      g12_precinct_turnout = "0"
    self.g08_precinct_turnout = float(g08_precinct_turnout)
    self.g10_precinct_turnout = float(g10_precinct_turnout)
    self.g12_precinct_turnout = float(g12_precinct_turnout)
    self.p08_precinct_turnout = float(p08_precinct_turnout)
    self.p10_precinct_turnout = float(p10_precinct_turnout)
    self.p12_precinct_turnout = float(p12_precinct_turnout)

    # Also congressional_district was empty
    if len(congressional_district) == 0:
      congressional_district = 0
    self.congressional_district = float(congressional_district)

    # Representing values with integer values
    if "Married" in marital_status:
      self.marital_status = 1
    elif "Non-Traditional" in marital_status:
      self.marital_status = 2
    else:
      self.marital_status = 3

    # Representing values with integer values
    if "LAS VEGAS DMA (EST.)" in designated_market_area:
      self.designated_market_area = 1
    elif "RENO DMA (EST.)" in designated_market_area:
      self.designated_market_area = 2
    else:
      self.designated_market_area = 3

    # len(age) is zero when age = "" so age = 0
    if len(age) == 0:
      age = 0
    self.age = float(age)
    # Representing values with integer values
    if party == "Republican":
      self.party = 1
    elif party == "Democratic":
      self.party = 2
    elif party == "American Independent":
      self.party = 3
    else:
      self.party = 4

    # Representing values with integer values
    if ethnicity == "European":
      self.ethnicity = 1
    elif ethnicity == "African-American":
      self.ethnicity = 2
    elif ethnicity == "Asian":
      self.ethnicity = 3
    elif ethnicity == "Hispanic":
      self.ethnicity = 4
    elif ethnicity == "Other":
      self.ethnicity = 5
    else:
      self.ethnicity = 6

    # Representing values with integer values
    if "Medical" in occupation_industry:
      self.occupation_industry = 1
    elif "Manufacturing" in occupation_industry:
      self.occupation_industry = 2
    elif "Management" in occupation_industry:
      self.occupation_industry = 3
    elif "Clerical/Office" in occupation_industry:
      self.occupation_industry = 4
    elif "Other" in occupation_industry:
      self.occupation_industry = 5
    elif "Financial Services" in occupation_industry:
      self.occupation_industry = 6
    elif "Skilled Trades" in occupation_industry:
      self.occupation_industry = 7
    elif "Food Services" in occupation_industry:
      self.occupation_industry = 8
    elif "Engineering" in occupation_industry:
      self.occupation_industry = 9
    elif "Military" in occupation_industry:
      self.occupation_industry = 10
    elif "Computer Professional" in occupation_industry:
      self.occupation_industry = 11
    elif "Education" in occupation_industry:
      self.occupation_industry = 12
    elif "Financial Services" in occupation_industry:
      self.occupation_industry = 13
    else:
      self.occupation_industry = 14

    # Representing values with integer values
    if "Grad Degree" in education:
      self.education = 1
    elif "Bach Degree" in education:
      self.education = 2
    elif "Less than HS Diploma" in education:
      self.education = 3
    elif "HS Diploma" in education:
      self.education = 4
    elif "Some College" in education:
      self.education = 5
    else:
      self.education = 6

    # Representing values with integer values
    if "200k+" in income:
      self.income = 1
    elif "125k-200k" in income:
      self.income = 2
    elif "75k-125k" in income:
      self.income = 3
    elif "35k-75k" in income:
      self.income = 4
    elif "0-35k" in income:
      self.income = 5
    else:
      self.income = 6

    # Representing values with integer values
    if "$499999+" in net_worth:
      self.net_worth = 1
    elif "$250000-499999" in net_worth:
      self.net_worth = 2
    elif "$10000-24999" in net_worth:
      self.net_worth = 3
    elif "$50000-99999" in net_worth:
      self.net_worth = 4
    elif "$25000-49999" in net_worth:
      self.net_worth = 5
    elif "$10000-24999" in net_worth:
      self.net_worth = 6
    elif "$5000-9999" in net_worth:
      self.net_worth = 7
    elif "$1-4999" in net_worth:
      self.net_worth = 8
    else:
      self.net_worth = 9

    # Representing values with integer values
    if "Yes" in donates_to_liberal_causes:
      self.donates_to_liberal_causes = 1
    else:
      self.donates_to_liberal_causes = 2

    # Representing values with integer values
    if "Yes" in donates_to_conservative_causes:
      self.donates_to_conservative_causes = 1
    else:
      self.donates_to_conservative_causes = 2

  def __repr__(self):
    str = ""
    for k, v in self.__dict__.items():
      str += v + ", "
    return str

def makeVoter (args=[]):
  #returning new voter class with given arguments
  return Voter(optimus_id=args[0],
                age=args[1],
                party=args[2],
                ethnicity=args[3],
                marital_status=args[4],
                income=args[6],
                education=args[7],
                congressional_district=args[8],
                designated_market_area=args[9],
                occupation_industry=args[10],
                vh14p=args[11],
                vh12g=args[12],
                vh12p=args[13],
                vh10g=args[14],
                vh10p=args[15],
                vh08g=args[16],
                vh08p=args[17],
                vh06g=args[18],
                vh06p=args[19],
                vh04g=args[20],
                vh04p=args[21],
                vh02g=args[22],
                vh02p=args[23],
                vh00g=args[24],
                vh00p=args[25],
                net_worth=args[26],
                donates_to_liberal_causes=args[30],
                donates_to_conservative_causes=args[31],
                g08_precinct_turnout=args[33],
                g10_precinct_turnout=args[34],
                g12_precinct_turnout=args[35],
                p08_precinct_turnout=args[36],
                p10_precinct_turnout=args[37],
                p12_precinct_turnout=args[38]
                )

# choosing features for model training
def make_features(voters = []):
  features = []
  for voter in voters:
    entry = []
    entry.append(voter.age)
    entry.append(voter.party)
    entry.append(voter.ethnicity)
    entry.append(voter.income)
    entry.append(voter.marital_status)
    entry.append(voter.occupation_industry)
    entry.append(voter.vh02g)
    entry.append(voter.vh04g)
    entry.append(voter.vh06g)
    entry.append(voter.vh08g)
    entry.append(voter.vh10g)
    entry.append(voter.vh12g)
    entry.append(voter.donates_to_liberal_causes)
    entry.append(voter.congressional_district)
    features.append(entry)
  return features

# labeling training data
def make_labels(voters = []):
  labels = []
  for voter in voters:
    labels.append(voter.vh12p)
  return labels

# Returning trained model
def train_model(voters = []):
  clf = KNeighborsClassifier(n_neighbors=10)
  features = make_features(voters)
  labels = make_labels(voters)
  clf = clf.fit(features, labels)
  return clf

# Picking features of voter with given index
def pick_person (voters, index):
  person = []
  person.append(voters[index].age)
  person.append(voters[index].party)
  person.append(voters[index].ethnicity)
  person.append(voters[index].income)
  person.append(voters[index].marital_status)
  person.append(voters[index].occupation_industry)
  person.append(voters[index].vh02g)
  person.append(voters[index].vh04g)
  person.append(voters[index].vh06g)
  person.append(voters[index].vh08g)
  person.append(voters[index].vh10g)
  person.append(voters[index].vh12g)
  person.append(voters[index].donates_to_liberal_causes)
  person.append(voters[index].congressional_district)
  return person

#opening voterfile.csv file as csvfile
with open('voterfile.csv', 'r') as csvfile:
  spamreader = csv.reader(csvfile) #spamreader is now voterfile.csv
  next(spamreader) #skipping headers line
  voter_list = []
  #initializing Voter classes
  for row in spamreader:
    new_voter = makeVoter(args=row)
    voter_list.append(new_voter)

  # training model with voter data from csvfile
  model = train_model(voter_list)

  with open('results.csv', 'w') as csvfile:
    #filewriter is now results.csv file
    filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

    # headers of results.csv file
    headers = ["optimus_id", "age", "party", "ethnicity", "income", "marital_status", "occupation_industry", "vh02g", "vh04g", "vh06g", "vh08g", "vh10g", "vh12g"]
    headers.append("donates_to_liberal_causes")
    headers.append("congressional_district")
    headers.append("vote")
    headers.append("vote_prob")

    filewriter.writerow(headers)

    # writing all voter forecast with features used to forecast
    for i in range(len(voter_list)):
      v = voter_list[i]
      row = [v.optimus_id, v.age, v.party, v.ethnicity, v.income, v.marital_status, v.occupation_industry, v.vh02g, v.vh04g, v.vh06g, v.vh08g, v.vh10g, v.vh12g]
      row.append(v.donates_to_liberal_causes)
      row.append(v.congressional_district)
      example = pick_person(voter_list, i)
      outcome = model.predict([example])[0]
      prob = model.predict_proba([example])[0][1]
      row.append(outcome)
      row.append(prob)

      filewriter.writerow(row)


#!/usr/bin/env python3.4

import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

SITE = "https://coachella-weekend2.frontgatetickets.com/coachella2/captcha.html"
SITE = "https://www.coachella.com"

if __name__ == "__main__":
    driver = webdriver.Firefox()
    driver.get(SITE)

    while True:
        print("looping...")

         #         # Note: When selenium can't find the link, an exception is thrown.
         #         #       For our purposes, this means clicking the link was successful
         #         #       in the last iteration, and we have nagivated away. So, the
         #         #       script will exit here and the brower will be left open for
         #         #       a human user to enter the captcha.
         #         link = driver.find_element_by_link_text('click here')
         #
         #         link.click()
         #         time.sleep(5)

        driver.refresh()
        time.sleep(10)


from collections import Counter
from utils.text_utils import findallwords

class WordFrequencyAnalyzer:

    def calculate_highest_frequency(text):
        # checking if input is clean
        if not isinstance(text, str):
            raise TypeError("text should be a string")
        if len(text.strip()) == 0:
            raise ValueError("text is empty")
        # run the code to find the highest frequency word
        all_words = findallwords(text)
        count = Counter(sorted(all_words))
        most_common = count.most_common(1)
        return most_common

    def calculate_frequency_for_word(text, word):
        # checking if text is clean
        if not isinstance(text, str):
            raise TypeError("text should be a string")
        if len(text.strip()) == 0:
            raise ValueError("text is empty")
        # checking if word is clean
        if not isinstance(word, str):
            raise TypeError("word should be a string")
        if len(word.strip()) == 0:
            raise ValueError("word is empty")

        # run the code for find the frequency of a word
        all_words = findallwords(text)
        count = all_words.count(word)
        return count

    def calculate_most_frequent_n_words(text, n):
        # checking if text is clean
        if not isinstance(text, str):
            raise TypeError("text should be a string")
        if len(text.strip()) == 0:
            raise ValueError("text is empty")
        # checking if n is clean
        if not isinstance(n, int):
            raise TypeError("N should be a int")
        if n < 1:
            raise ValueError("N should be a positive int")

        # run the code to find the n most frequent words
        all_words = findallwords(text)
        count = Counter(sorted(all_words))
        n_frequently_encountered = count.most_common(n)
        return n_frequently_encountered


""" Haystack search indexes for models of the coupon app. """

import datetime

from django.conf import settings
from django.db import IntegrityError, transaction

from haystack import indexes, site
from gargoyle import gargoyle

from coupon.models import Coupon, SlotTimeFrame

# Realtime search indexing thrashes for fixture resests during tests builds.
# Override it for *all* Jenkins builds, and (locally) any EnhancedTestCase).
INDEX_CLASS = indexes.RealTimeSearchIndex
if not settings.SEARCH_REALTIME:
    INDEX_CLASS = indexes.SearchIndex
try:
    # This will cause gargoyle to create the switch in an inactive state if it
    # does not already exist:
    if not gargoyle.is_active('real-time-search-index'):
        INDEX_CLASS = indexes.SearchIndex
except IntegrityError:
    # Gargoyle can fail to do an insert under test conditions, if the test loads
    # a fixture containing a switch. If that is the case; fall back to
    # SearchIndex.
    transaction.commit_unless_managed()
    INDEX_CLASS = indexes.SearchIndex

class CouponIndex(INDEX_CLASS):
    """ An index of coupons for solr searches, via haystack. """
    text = indexes.CharField(document=True, use_template=True)
    pub_date = indexes.DateTimeField(model_attr='start_date')
    site_id = indexes.IntegerField()
    categories = indexes.MultiValueField()
    suggestions = indexes.CharField()

    class Meta:
        app_label = 'coupon'

    def index_queryset(self):
        """
        Select QuerySet for use when the entire index for model is updated.
        """
        return Coupon.objects.select_related('offer', 'offer__business',
            'custom_restrictions', 'coupon_type').filter(
            expiration_date__gte=datetime.date.today()).exclude(
            coupon_type__coupon_type_name__in=('In Progress', 'Abandoned'))

    def prepare(self, obj):
        """
        Populate suggestions from text field.
        Suggestions will not be indexed, but used for spellcheck.
        """
        prepared_data = super(CouponIndex, self).prepare(obj)
        prepared_data['suggestions'] = prepared_data['text']
        return prepared_data

    @classmethod
    def prepare_categories(cls, obj):
        """ Format categories m2m as MultiValueField. """
        return [category.id for category in obj.offer.business.categories.all()]

    @classmethod
    def prepare_site_id(cls, obj):
        """ Format site_id to ensure this coupon has an active slot. """
        active_time_frame = \
            SlotTimeFrame.current_slot_time_frames.get_query_set().filter(
                coupon=obj)
        if active_time_frame:
            site_id = active_time_frame[0].slot.site.id
        else:
            site_id = None
        return site_id

site.register(Coupon, CouponIndex)


from ImageMatrix import *
from Shape import *
from Fill import *
from GroupOfShapes import *

def transform(group_of_shapes):
    new_group_of_shapes = []
    gos_list = group_of_shapes.fetch_shape(['GroupOfShapes'])
    max_dot_count = 0
    largest_shape_index = None
    for index, shapes in enumerate(gos_list):
        dots = shapes.fetch_shape(['Dot'])
        if len(dots) > max_dot_count:
            max_dot_count = len(dots)
            largest_shape_index = index
    largest_shape = gos_list[largest_shape_index]
    new_group_of_shapes.append(largest_shape)
    return GroupOfShapes(new_group_of_shapes)


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        if not lists:
            return None

        queue = []

        dummy = ListNode(0)
        curr = dummy

        for node in lists:
            heapq.heappush(queue, (node.val, node))

        while queue:
            node = heapq.heappop(queue)
            curr.next = node[1]
            curr = curr.next

            if curr.next:
                heapq.heappush(queue, (curr.val, curr.next))

        return dummy.next


#!/usr/bin/env python3
# delete_unneeded.py - a program which traverses a folder and
#                   deletes files greater than MAX_SIZE

import os, shutil

# traverse current working directory
folder = os.path.abspath('.')

MAX_SIZE = 100000000     # allowed max size in bytes (100MB)

# Walk directory and delete(unlink) files > MAX_SIZE
for folder, subfolders, filenames in os.walk(folder):
    for filename in filenames:
        file_path = os.path.join(folder, filename)
        if os.path.getsize(file_path) > MAX_SIZE:
            #os.unlink(file_path)
            print(f'Deleted {file_path}')

print('Done')


#poniże jest gotowe całe pr hr, teraz trzeba je tylko ubrać w klasę i przepisać zręcznie do programu. ewentualnie sprawdzić
#i zastanowić się czy będzie się dobrze liczyło gdy zapuścimy taryfikator na procedurę albo świadczenidoawcę, albo ogólny na kod produktu

# Paweł Kosowski - jest to plik roboczy przeniesiony z shared.roboczy.py (org pytar). Plik jest do przeanalizowania i sprawdzenia co dkokladnie ma byc zrobione tutaj

import numpy as np
import pandas as pd

from pytar_calc.calc.pr import *

def excel(df):
    args = locals()
    import time
    df.to_excel(r'C:\Users\m.marczak\Documents\anitko\13lip\zb_%s.xlsx' % (time.time()))
e=excel

a = PrCalc('pr', query_sm, uid, og=og.tar, **data_description)
a.create_tar_sr_il_abc()
a.tar_sr_il.head()
a.create_tar_pr_hr()
a.create_pers_infrast()

pd.set_option('display.max_columns', 500)

def calc_time(x):
    y = x.split(':')
    try:
        return float(y[0]) + float(y[1])/60
    except ValueError:
        return 0

# kopiuje wcześniejsze tabele
df = a.tar_pr_hr.copy()
fk = a.fk_szcz.copy()
fk = fk.rename(columns={'kod_nfz':'kod_sw', 'opk_nr':'nr_opk','x-do wyrzucenia powtórka':'x-powt'})
slo_hr = a.slo_hr
# bierze tylko te opki kore asia zaakceptowala i sa w danym roku
#?? delegacja na oddzielną metodę, można liczyć na opk i na kat med kat opk dzieki temu zaleznie co sie w tamtej metodzie podstawi
fk = fk[(fk['rok'].str.strip()==a.kwargs['rok'])&(fk['x-powt']=='1')]
df['czas_jednego_hr_int'] = df['czas_jednego_hr'].apply(calc_time)
df['total_time'] = df['czas_jednego_hr_int'] * df['ilosc_hr']
df_slo = df.merge(slo_hr, left_on=['kod_sw','nr_opk_hr','nazwa_hr'], right_on=['kod_sw','nr_opk_hr','nazwa_hr_sw'], validate='m:1')
df_slo = df_slo.drop(columns=['nazwa_hr_x'])
df_slo = df_slo.rename(columns={'nazwa_hr_y':'nazwa_hr'})
#wyciaga z fk tylko te kolumny ktore sa porzebne. docelowo to powinno byc robione na instancji, zeby mozna bylo eksportować plik fk
# albo na jakims wrapperze isntacji żeby wszystkie Calc'i korzystaly z tej samej fki
fk_pers = fk[['wyn_h_lekarz','wyn_h_pieleg','wyn_h_pozost_med','wyn_h_pozost_nmed', 'kod_sw','nr_opk', 'kat_med','kat_opk','infrast_odt_h_bloku']]
df_slo = df_slo.merge(fk_pers, left_on=['kod_sw','nr_opk_hr'], right_on=['kod_sw','nr_opk'], validate='m:1')
df_slo = df_slo.drop(columns=['nr_opk']) #usuwa kolumne dla porzadku

# zmienia anestezjologow, do innej metody
df_slo['kat_med'].mask(# warunek,wartosc orginalna jezeli falsz, wpisana jeżeli prawda
    ((df_slo['nazwa_hr']=='LEKARZ ANESTEZJOLOG') & (df_slo['kat_med']!='18')),'43')
df_slo['kat_opk'].mask(# warunek,wartosc jezeli falsz
    ((df_slo['nazwa_hr']=='LEKARZ ANESTEZJOLOG') & (df_slo['kat_med']!='18')),'1')
df_slo['kat_med'].mask(# warunek,wartosc jezeli falsz
    ((df_slo['nazwa_hr']=='PIELEGNIARKA ANESTEZJOLOGICZNA') & (df_slo['kat_med']!='18')),'43')
df_slo['kat_opk'].mask(# warunek,wartosc jezeli falsz
    ((df_slo['nazwa_hr']=='PIELEGNIARKA ANESTEZJOLOGICZNA') & (df_slo['kat_med']!='18')),'1')

# pr_hr_pers_wagi
# określa czym jednostkową grupę perosnelu
personel_distinct_groups = a.kwargs['case_group']+a.unit_id +['nazwa_hr',]
pr_hr_pers_wagi = df_slo.groupby( personel_distinct_groups+['nr_opk_hr'] )['kat_opk'].count().reset_index()
pr_hr_pers_wagi = pr_hr_pers_wagi.rename(columns={'kat_opk':'PERSONEL_ZABIEG_LICZBA'})
#pr_hr_pers czas
pr_hr_pers_czas = df_slo.groupby(personel_distinct_groups)['czas_jednego_hr_int'].sum().reset_index()
# pr-hr infras wagi
pr_hr_infras_wagi = a.tar.groupby(a.kwargs['case_group']+a.unit_id +['nr_opk_pr'])['id'].count().reset_index()
pr_hr_infras_wagi = pr_hr_infras_wagi.rename(columns={'id':'LICZBA_OPK_PR'})

#zwraca wyjątek, jeżeli jest kilka nierozroznialnych procedur, albo do error loga
# if not pr_hr_infras_wagi[pr_hr_infras_wagi['LICZBA_OPK_PR']>1].empty:
#     raise Exception('More than one procedure in unit pr')

# pr-hr infras czas
a.tar['czas_pr_int'] = a.tar['czas_pr'].apply(calc_time)
#liczy sredni czas na procedura w jednostce
pr_hr_infras_czas = a.tar.groupby(a.kwargs['case_group']+a.unit_id)['czas_pr_int'].mean().reset_index()
pr_hr_infras_czas = pr_hr_infras_czas.rename(columns={'czas_pr_int':'avg_czas_pr_int'})

pr_hr_pers_wagi_wyn_h  = pr_hr_pers_wagi.merge(fk_pers, left_on=['kod_sw','nr_opk_hr'], right_on=['kod_sw','nr_opk'], validate='m:1')

#oblicza koszt personelu, dzilei na grupy i przypisuje wynagrodzenia potem laczy w pd concat

def calc_avg_wyn_h_mean_weights(df,groups, col, substr):
    df_filtered = df[df['nazwa_hr'].str.upper().str.contains(substr)]
    df1 = df_filtered.groupby(
        groups).apply(
        lambda x: np.average(x[col], weights=x['PERSONEL_ZABIEG_LICZBA'])).reset_index()
    df2 = df1.rename(columns={0: 'wyn_h_mean'})
    return df2.reset_index()

personel = []
for i in (('wyn_h_lekarz', 'LEKAR'),
            ('wyn_h_pieleg', 'PIEL'),
            ('wyn_h_pozost_med', 'POZOST'),
            ('wyn_h_pozost_nmed', 'INNY'),):
    personel.append(calc_avg_wyn_h_mean_weights(pr_hr_pers_wagi_wyn_h,personel_distinct_groups, i[0], i[1]))
personel_wyn_h_all = pd.concat(personel).sort_values(personel_distinct_groups)
#laczy czas z wynagrodzeniem
personel_costs = personel_wyn_h_all.merge(pr_hr_pers_czas, on=personel_distinct_groups, validate='1:1')
personel_costs['koszt_hr'] = personel_costs['czas_jednego_hr_int']*personel_costs['wyn_h_mean']
personel_costs_sum = personel_costs.groupby(a.kwargs['case_group']+a.unit_id)['koszt_hr'].sum().reset_index()

## infrastruktura
pr_hr_infras_wagi = pr_hr_infras_wagi.merge(fk_pers, left_on=['kod_sw','nr_opk_pr'], right_on=['kod_sw','nr_opk'], validate='m:1')

#tutaj nie ma kilku grup jak w personelu, wiec srednia wazona liczona jest wprost
pr_hr_infras_wagi = pr_hr_infras_wagi.groupby(a.kwargs['case_group']+a.unit_id).apply(
    lambda x: np.average(x['infrast_odt_h_bloku'], weights=x['LICZBA_OPK_PR'])).reset_index()
pr_hr_infras_wagi  = pr_hr_infras_wagi.rename(columns = {0:'mean_h_infrast'})

pr_hr_infras_sum = pr_hr_infras_wagi.merge(pr_hr_infras_czas, on=a.kwargs['case_group']+a.unit_id,validate='1:1')
pr_hr_infras_sum['koszt_infrast'] = pr_hr_infras_sum['mean_h_infrast']*pr_hr_infras_sum['avg_czas_pr_int']
pr_hr_infras_sum = pr_hr_infras_sum.drop(columns=[ 'mean_h_infrast', 'avg_czas_pr_int',])
#oblicza koncowy koszt ptr
pr_hr_sum = pr_hr_infras_sum.merge(personel_costs_sum, on=a.kwargs['case_group']+a.unit_id,validate='1:1')
pr_hr_sum['koszt_pr'] = pr_hr_sum['koszt_infrast']+pr_hr_sum['koszt_hr']
pr_hr_sum.columns

################################DOTAD OK

sorted(list(fk.columns))

fk_pers[fk_pers[['kod_sw','nr_opk']].duplicated()]

df_slo['nr_opk_hr'].unique()
#dorobic tu joina ze slownikem FK zeby przypisac jezeli lek/piel jest z opk anest to zeby był jako anest
#przypisac ceny anestezjologow do wierszy lekarz anestezjolog

df_slo[['nazwa_hr','nr_opk_hr']].head()

df.columns

df_g = df.groupby(a.single_pr+['nazwa_hr', 'nr_opk_hr'])
df_g.sum().head()
fk = a.fk_szcz.copy()
fk['rok']
print(list(a.fk_szcz.columns))

x = df['czas_jednego_hr'][3]

slo_hr.columnss

slo_hr

a = pd.asd

p = r'T:\organizacyjne_robocze\012_Taryfikator\slowniki\pytar\dict_output\FK_SZCZEGOLOWY_2018_07_20_14_07.xlsx'
a = pd.read_excel(p)
a['ROK']

p = r'T:\organizacyjne_robocze\012_Taryfikator\slowniki\pytar\dict_output\FK_SZCZEGOLOWY_2018_07_20_14_07.xlsx.pkl'


import numpy as np
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import (
    Dense, Input, Conv2D, Reshape, Add, ReLU, Dropout,
    Flatten, Softmax, BatchNormalization, MaxPooling2D, AveragePooling2D
)

################################ Start of network construction #########################################
################################# conv1  ##################################
resnet50_conv1_input = Input(shape=( 256, 256, 3), name='conv1_input' )

x = Conv2D(
    64, kernel_size=7, strides=2, activation='relu',
    padding='same', kernel_constraint=keras.constraints.max_norm(2.)
)(resnet50_conv1_input)

resnet50_conv1_output = MaxPooling2D(
    pool_size=3, padding='same', strides=2
)(x)

resnet50_conv1 = Model(
    inputs = resnet50_conv1_input,
    outputs = resnet50_conv1_output,
    name = "ResNet-50_conv_1block"
)

################################# conv2  ##################################
# First Block of conv2

resnet50_conv2_first_block_input = Input(shape=(64,64,64), name='conv2_first_block_input' )
x = Conv2D( 64, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv2_first_block_input)
x = BatchNormalization()(x)
x = Conv2D( 64, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 256, kernel_size=1, strides=1, padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

shortcut = Conv2D(
    256, kernel_size=1, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.)
)(resnet50_conv2_first_block_input)
shortcut = BatchNormalization()(shortcut)
x = Add()([x, shortcut])

resnet50_conv2_first_block_output = ReLU()(x)

resnet50_conv2_first_block = Model(
    inputs = resnet50_conv2_first_block_input,
    outputs = resnet50_conv2_first_block_output,
    name = 'resnet50_conv2_first_block'
)

# Identity Block of conv2
resnet50_conv2_identity_block_input = Input(shape=(64,64,256), name='conv2_identity_block_input' )
x = Conv2D( 64, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv2_identity_block_input)
x = BatchNormalization()(x)
x = Conv2D( 64, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 256, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

x = Add()([x, resnet50_conv2_identity_block_input ])
resnet50_conv2_identity_block_output = ReLU()(x)

resnet50_conv2_identity_block = Model(
    inputs = resnet50_conv2_identity_block_input,
    outputs= resnet50_conv2_identity_block_output,
    name = 'resnet50_conv2_identity_block'
)

# Combining the 2 types of blocks
resnet50_conv2_input = Input(shape=(64,64,64), name='resnet50_conv2_input')

x = resnet50_conv2_first_block(resnet50_conv2_input)
# x = resnet50_conv2_identity_block(resnet50_conv2_input)
x = resnet50_conv2_identity_block(x)
resnet50_conv2_output = resnet50_conv2_identity_block(x)

resnet50_conv2 = Model(
    inputs = resnet50_conv2_input,
    outputs = resnet50_conv2_output,
    name = "ResNet-50_conv2_block"
)

################################# conv3  ##################################
# First Block of conv3

resnet50_conv3_first_block_input = Input(shape=(64,64,256), name='conv3_first_block_input' )
x = Conv2D( 128, kernel_size=1, strides=2, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv3_first_block_input)
x = BatchNormalization()(x)
x = Conv2D( 128, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 512, kernel_size=1, strides=1, padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

shortcut = Conv2D(512, kernel_size=1, strides=2, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv3_first_block_input)
shortcut = BatchNormalization()(shortcut)
x = Add()([ x, shortcut])
resnet50_conv3_first_block_output = ReLU()(x)

resnet50_conv3_first_block = Model(
    inputs  = resnet50_conv3_first_block_input,
    outputs = resnet50_conv3_first_block_output,
    name = 'resnet50_conv3_first_block'
)

# Identity Block of conv3
resnet50_conv3_identity_block_input = Input(shape=(32,32,512), name='conv3_identity_block_input' )
x = Conv2D( 128, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv3_identity_block_input)
x = BatchNormalization()(x)
x = Conv2D( 128, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 512, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

x = Add()([x, resnet50_conv3_identity_block_input ])
resnet50_conv3_identity_block_output = ReLU()(x)

resnet50_conv3_identity_block = Model(
    inputs = resnet50_conv3_identity_block_input,
    outputs= resnet50_conv3_identity_block_output,
    name = 'resnet50_conv3_identity_block'
)

# Combining the 2 types of blocks
resnet50_conv3_input = Input(shape=(64,64,256), name='resnet50_conv3_input' )

x = resnet50_conv3_first_block(resnet50_conv3_input)
x = resnet50_conv3_identity_block(x)
x = resnet50_conv3_identity_block(x)
resnet50_conv3_output = resnet50_conv3_identity_block(x)

resnet50_conv3 = Model(
    inputs = resnet50_conv3_input,
    outputs = resnet50_conv3_output,
    name = "ResNet-50_conv3_block"
)

################################# conv4  ##################################
# First Block of conv4

resnet50_conv4_first_block_input = Input(shape=(32,32,512), name='conv4_first_block_input' )
x = Conv2D( 256, kernel_size=1, strides=2, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv4_first_block_input)
x = BatchNormalization()(x)
x = Conv2D( 256, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 1024, kernel_size=1, strides=1, padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

shortcut = Conv2D(1024, kernel_size=1, strides=2, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv4_first_block_input)
shortcut = BatchNormalization()(shortcut)
x = Add()([ x, shortcut])
resnet50_conv4_first_block_output = ReLU()(x)

resnet50_conv4_first_block = Model(
    inputs  = resnet50_conv4_first_block_input,
    outputs = resnet50_conv4_first_block_output,
    name = 'resnet50_conv4_first_block'
)

# Identity Block of conv4
resnet50_conv4_identity_block_input = Input(shape=(16,16,1024), name='conv4_identity_block_input' )
x = Conv2D( 256, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv4_identity_block_input)
x = BatchNormalization()(x)
x = Conv2D( 256, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 1024, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

x = Add()([x, resnet50_conv4_identity_block_input ])
resnet50_conv4_identity_block_output = ReLU()(x)

resnet50_conv4_identity_block = Model(
    inputs = resnet50_conv4_identity_block_input,
    outputs= resnet50_conv4_identity_block_output,
    name = 'resnet50_conv4_identity_block'
)

# Combining the 2 types of blocks
resnet50_conv4_input = Input(shape=(32,32,512), name='resnet50_conv4_input' )

x = resnet50_conv4_first_block(resnet50_conv4_input)
x = resnet50_conv4_identity_block(x)
x = resnet50_conv4_identity_block(x)
x = resnet50_conv4_identity_block(x)
x = resnet50_conv4_identity_block(x)
resnet50_conv4_output = resnet50_conv4_identity_block(x)

resnet50_conv4 = Model(
    inputs = resnet50_conv4_input,
    outputs = resnet50_conv4_output,
    name = "ResNet-50_conv4_block"
)

################################# conv5  ##################################
# First Block of conv5
resnet50_conv5_first_block_input = Input(shape=(16,16,1024), name='conv5_first_block_input' )
x = Conv2D( 512, kernel_size=1, strides=2, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv5_first_block_input)
x = BatchNormalization()(x)
x = Conv2D( 512, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 2048, kernel_size=1, strides=1, padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

shortcut = Conv2D(2048, kernel_size=1, strides=2, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv5_first_block_input)
shortcut = BatchNormalization()(shortcut)
x = Add()([ x, shortcut])
resnet50_conv5_first_block_output = ReLU()(x)

resnet50_conv5_first_block = Model(
    inputs  = resnet50_conv5_first_block_input,
    outputs = resnet50_conv5_first_block_output,
    name = 'resnet50_conv5_first_block'
)

# Identity Block of conv5
resnet50_conv5_identity_block_input = Input(shape=(8,8,2048), name='conv5_identity_block_input' )
x = Conv2D( 512, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(resnet50_conv5_identity_block_input)
x = BatchNormalization()(x)
x = Conv2D( 512, kernel_size=3, strides=1, activation='relu', padding='same', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)
x = Conv2D( 2048, kernel_size=1, strides=1, activation='relu', padding='valid', kernel_constraint=keras.constraints.max_norm(2.))(x)
x = BatchNormalization()(x)

x = Add()([x, resnet50_conv5_identity_block_input ])
resnet50_conv5_identity_block_output = ReLU()(x)

resnet50_conv5_identity_block = Model(
    inputs = resnet50_conv5_identity_block_input,
    outputs= resnet50_conv5_identity_block_output,
    name = 'resnet50_conv5_identity_block'
)

# Combining the 2 types of blocks
resnet50_conv5_input = Input(shape=(16,16,1024), name='resnet50_conv5_input' )

x = resnet50_conv5_first_block(resnet50_conv5_input)
x = resnet50_conv5_identity_block(x)
resnet50_conv5_output = resnet50_conv5_identity_block(x)

resnet50_conv5 = Model(
    inputs = resnet50_conv5_input,
    outputs = resnet50_conv5_output,
    name = "ResNet-50_conv5_block"
)

# tf.keras.utils.plot_model(resnet50_conv5, show_shapes=True, show_dtype=True)

################################# classifier  ##################################
# The classifier will tell us whether this event is
# electron CC / muon CC / tauon CC / Neutral (4 types)

resnet50_classifier_input = Input(shape=(8,8,2048), name='classification')
x = AveragePooling2D(pool_size=2, padding='same')(resnet50_classifier_input)
x = Dropout(0.2)(x)
x = Flatten()(x)

# I think it's 4, but if we want to classify more types of events
# Need to change 4 to something else...
number_of_categories = 4

resnet50_classifier_output = Dense(
    number_of_categories, activation='softmax', kernel_constraint=keras.constraints.max_norm(2.)
)(x)

resnet50_classifier = Model(
    inputs = resnet50_classifier_input,
    outputs= resnet50_classifier_output,
    name = "ResNet-50_Classifier"
)

####################################################################################
def build_resnet50():
    resnet50_input = Input(shape=( 256, 256, 3))

    # image Augumentation ??
    x = resnet50_input

    x = resnet50_conv1(x)  # do conv in this block
    x = resnet50_conv2(x)
    x = resnet50_conv3(x)
    x = resnet50_conv4(x)
    x = resnet50_conv5(x)

    resnet50_output = resnet50_classifier(x)

    resnet50_model = Model(
        inputs  = resnet50_input,
        outputs = resnet50_output,
        name = 'ResNet-50_Whole_Network'
    )

    print( resnet50_model.summary() )

    resnet50_model.compile(
        optimizer=keras.optimizers.Adam(learning_rate=0.0005),
        loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
        metrics=['accuracy']
    )

    return resnet50_model

################################ End of network construction #########################################

resnet50_network = build_resnet50()

# tf.keras.utils.plot_model(resnet_obj, show_shapes=True, show_dtype=True)

random_inputs = np.random.rand(500, 256, 256, 3)   # Some random data
random_labels = np.random.rand(500, 1, 1, 1)       # Some random data

history = resnet50_network.fit(
    random_inputs, random_labels, epochs=10

)


# NAME : Concatenation of Consecutive Binary Numbers
# LINK : https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3618/
# DATE : 28/01/2021

class Solution:
    def concatenatedBinary(self, n: int) -> int:
        result = 0
        i = 1
        while i <= n:
            result = ((result << (i.bit_length() % 1000000007)) + i) % 1000000007
            i += 1
        return result

# It's my first binary shift :D
# Thanks to https://youtu.be/ttlNQ6YrdGs


input_file = open('input.txt','r')
input_lines = input_file.read().splitlines()
print(input_lines)
# print(len(input_lines))

A = []
B = []
C = []
sum_list=[]
loop_count=0
for i in input_lines:
    loop_count+=1
    print("\nLoop Count",loop_count)
    print(i)

    A.append(int(i))
    print("adding",i,"to A")
    if loop_count>1:
        B.append(int(i))
        print("adding",i,"to B")
    if loop_count>2:
        C.append(int(i))
        print("adding",i,"to C")

    if len(A)==3:
        sum_list.append(sum(A))
        A=[]
        print("A added to sum and blanked")
    if len(B)==3:
        sum_list.append(sum(B))
        B=[]
        print("B added to sum and blanked")
    if len(C)==3:
        sum_list.append(sum(C))
        C=[]
        print("C added to sum and blanked")

print(sum_list)

prev = sum(sum_list)
count=0
for i in sum_list:
    if i > prev:
        count += 1
    prev = i

print(count)


# 1791. 找出星型图的中心节点
# 有一个无向的 星型 图，由 n 个编号从 1 到 n 的节点组成。星型图有一个 中心 节点，并且恰有 n - 1 条边将中心节点与其他每个节点连接起来。

# 给你一个二维整数数组 edges ，其中 edges[i] = [ui, vi] 表示在节点 ui 和 vi 之间存在一条边。请你找出并返回 edges 所表示星型图的中心节点。

# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/find-center-of-star-graph
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

import collections
from typing import List

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        vdict = collections.defaultdict(int)
        for u1,v1 in edges[:3]:
            vdict[u1]+=1
            vdict[v1]+=1
        u1,v1 =edges[0][0],edges[0][1]
        if vdict[u1]==3:
            return u1
        return v1

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:
            return edges[0][0]
        return edges[0][1]

sol = Solution()
edges = [[1,2],[2,3],[4,2]]
print(sol.findCenter(edges))


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 23:25:58 2020

@author: Administrator
"""

from PIL import Image,ImageDraw,ImageFont

def add_font(text,i):

    font=ImageFont.truetype('simhei.ttf', 80)
    img=Image.open('a.jpg')
    draw=ImageDraw.Draw(img)
    draw.text((110,110),text,(0,0,0),font=font)
    #img.show()
    img.save('pic/{}.png'.format(i))

if __name__=='__main__':
    text=['2020Flag','发CCFSCI','平安喜乐','坚持锻炼','发量不变','更爱肥肥']
    for i in range(len(text)):
        add_font(text[i],i)


# Module is create to take a 3 row matrix, and return a parametric curve for the shot
# Row 0 should be x-positions, row 2 should be y-positions, row 3 should be approximate z-positions
# The z-positions are expected to not be perfectly parabolic, but the x and y coords should be on some y=mx + b line

import numpy as np
import math

import matplotlib.pyplot as plt

test_matrix = np.array([[1, 2, 3, 4, 5],
                           [2, 4, 6, 8, 10],
                           [1, 1, 1, 1, 1]], dtype=float)

# Reduces 3-D shot to equivalent 2-D coords
def flatten_shot(shot_matrix):
    squished = np.array([shot_matrix[0], shot_matrix[2]])

    for i in range(len(shot_matrix[0])):

        squished[0, i] = math.sqrt(shot_matrix[0, i]**2 + shot_matrix[1, i]**2)

    return squished

# Performs the polynomial fitting
def fit_parabola(r_arr, z_arr):
    return np.polyfit(r_arr, z_arr, 2)

# Given the 3 coefficients of a 2D parabola, proceeds to parameterize it
# Takes coefficients in decreasing order of degrees
def parameterize_2d_parabola(a, b, c):
    r = np.polynomial.polynomial.Polynomial([0, 1])
    z = np.polynomial.polynomial.Polynomial([c, b, a])

    return np.array([r, z])

def parameterize_2d_line(x_arr, y_arr):
    directing_vector = [(x_arr[1] - x_arr[0]), (y_arr[1] - y_arr[0])]

    x = np.polynomial.polynomial.Polynomial([x_arr[0], directing_vector[0]])
    y = np.polynomial.polynomial.Polynomial([y_arr[0], directing_vector[1]])

    return np.array([x, y])

def distance_between_points(p1, p2):
    x_diff = p1[0] - p2[0]
    y_diff = p1[1] - p2[1]

    dist = math.sqrt(x_diff**2 + y_diff**2)
    return dist

# This implementation is absolutely fucked, since the x polynomial and y polynomial have a different variable
# than the z polynomial. This class is meant to be a black box so that the user doesn't need to worry about fixing it
# Note that t = sqrt(v^2 +(mv + b)^2)
# raw matrix contains x-positions, y-positions, ball size rows
# There should be a pdf/onenote somewhere explaining the math

class ParametricParabola:
    def __init__(self, aligned_matrix):

        flat_shot = flatten_shot(aligned_matrix)

        parabola_coefficients = fit_parabola(flat_shot[0], flat_shot[1])
        parabola_coefficients = list(map(lambda x : round(x, 5), parabola_coefficients))

        parametric_parabola_2d = parameterize_2d_parabola(parabola_coefficients[0], parabola_coefficients[1], parabola_coefficients[2])

        parametric_line_xy = parameterize_2d_line(aligned_matrix[0], aligned_matrix[1])

        self.x_poly_base_t = parametric_line_xy[0]
        self.y_poly_base_t = parametric_line_xy[1]
        self.z_poly_base_r = parametric_parabola_2d[1]
        self.__zeroes_distance = None
        self.__xy_zeroes = None
        self.__parameter_range = None

    def evaluate_at(self, t):
        x = self.x_poly_base_t(t)
        y = self.y_poly_base_t(t)

        r = math.sqrt(x**2 + y**2)
        z = self.z_poly_base_r(r)

        return np.array([round(x, 3), round(y, 3), round(z, 3)])

    def __get_all_potential_xy_zeroes(self):
        zeroes = self.z_poly_base_r.roots()
        self.__zeroes_distance = max(zeroes) - min(zeroes)

        potential_xy_zeroes = []

        for zero in zeroes:
            temp_poly = self.x_poly_base_t**2 + self.y_poly_base_t**2 - zero**2
            t_s = temp_poly.roots()

            for t in t_s:
                x = self.x_poly_base_t(t)
                y = self.y_poly_base_t(t)
                potential_xy_zeroes.append((x, y))

        return potential_xy_zeroes

    # Can throw an exception
    def __narrow_down_by_direction(self):
        potential_zeroes = self.__get_all_potential_xy_zeroes()

        assert len(potential_zeroes) <= 4

        if len(potential_zeroes) == 2:
            return potential_zeroes

        if len(potential_zeroes) < 2:
            raise Exception("The polynomial had less than 2 roots, i.e. it doesn't follow projectile motion")

        # We now have the zeroes ordered from furthest away to closest away
        # List can be 3 or four elements long, depending on the parabola
        potential_zeroes.sort(key=lambda p: p[0]**2 + p[1]**2, reverse=True)

        candidate_vector_1 = (potential_zeroes[0][0] - potential_zeroes[-1][0], potential_zeroes[0][1] - potential_zeroes[-1][1])

        xy_line_directing_vector = (self.x_poly_base_t.coef[1], self.y_poly_base_t.coef[1])

        # We need to check if these 2 vectors ar in the same direction. We check if dot product is positive
        dot_product = candidate_vector_1[0]*xy_line_directing_vector[0] + candidate_vector_1[1]*xy_line_directing_vector[1]

        if dot_product > 0:
            potential_zeroes.pop(1)
        else:
            potential_zeroes.pop(0)

        return potential_zeroes

    # Can throw an exception
    def __narrow_down_by_dist(self):
        # Ordered from furthest to nearest from origin
        ordered_narrowed_down_zeroes = self.__narrow_down_by_direction()

        if len(ordered_narrowed_down_zeroes) == 2:
            return ordered_narrowed_down_zeroes

        # If we make it here, there should be three potential zeroes
        dist1 = distance_between_points(ordered_narrowed_down_zeroes[0], ordered_narrowed_down_zeroes[1])
        dist2 = distance_between_points(ordered_narrowed_down_zeroes[0], ordered_narrowed_down_zeroes[2])

        if abs(dist1 - self.__zeroes_distance) < abs(dist2 - self.__zeroes_distance):
            ordered_narrowed_down_zeroes.pop(2)
        else:
            ordered_narrowed_down_zeroes.pop(1)

        return ordered_narrowed_down_zeroes

    # Can throw an exception
    # TODO: currently propagates the exception forward. Convenient for testing, but needs to be fixed eventually
    def get_xy_zeroes(self):
        if self.__xy_zeroes is None:
            self.__xy_zeroes = self.__narrow_down_by_dist()

        return self.__xy_zeroes

    # Currently throws an exception, which is not suitable. Will fix itself when get_xy_zeroes handles exception
    # TODO: handle the case where there are no zeroes (i.e. non-parabolic path)
    def get_parameter_range(self):
        if self.__parameter_range is None:
            xy_zeroes = self.get_xy_zeroes()

            parameter_bound_1 = (self.x_poly_base_t - xy_zeroes[0][0]).roots()[0]
            parameter_bound_2 = (self.x_poly_base_t - xy_zeroes[1][0]).roots()[0]

            self.__parameter_range = sorted([parameter_bound_1, parameter_bound_2])

        return self.__parameter_range

    def get_3d_points_arr(self, amount=100):
        parameter_range = self.get_parameter_range()
        t_values = np.linspace(parameter_range[0], parameter_range[1], num=amount)

        shot_points_arr = np.empty([3, amount])

        for i in range(amount):
            shot_points_arr[:,i] = self.evaluate_at(t_values[i])

        return shot_points_arr

r = math.sqrt(2)

test3 = np.array([[r/2, r, 3*r/2, 2*r, 5*r/2],
                 [r/2, r, 3*r/2, 2*r, 5*r/2],
                 [0, 3, 4, 3, 0]])

test_parabola = ParametricParabola(test3)
position_matrix = test_parabola.get_3d_points_arr()

fig = plt.figure()
ax = plt.axes(projection="3d")
ax.scatter(position_matrix[0], position_matrix[1], position_matrix[2], 'red')
plt.show()


'''

'''

#code
import sys

def num_ways(N):
    if N == 0:
        return 1
    if N == 1:
        return 1
    return (num_ways(N-1) + num_ways(N-2))

t = int(input())
for i in range(t):
    L, R, N = map(int,input().split())
#     print(L, R, N)
    c = 0
    for j in range(L, R+1):
        x = num_ways(j)
        c += 1
        if c == N:
            break
    if c == N:
        print(j, end = " ")
        if j == 0:
            print(".")
        else:
            for i in range(j):
                if i % 2 == 0:
                    print(".", end = "")
                else:
                    print("#", end = "")
    else:
        print(-1)


import warnings
from datetime import datetime

import numpy as np
from numpy import cov
from scipy import linalg

def time_format():
    return f"{datetime.now()}|> "

def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
    """Numpy implementation of the Frechet Distance.
    The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
    and X_2 ~ N(mu_2, C_2) is
            d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).

    Stable version by Dougal J. Sutherland.
    Params:
    -- mu1 : Numpy array containing the activations of the pool_3 layer of the
             inception net ( like returned by the function 'get_predictions')
             for generated samples.
    -- mu2   : The sample mean over activations of the pool_3 layer, precalcualted
               on an representive data set.
    -- sigma1: The covariance matrix over activations of the pool_3 layer for
               generated samples.
    -- sigma2: The covariance matrix over activations of the pool_3 layer,
               precalcualted on an representive data set.
    Returns:
    --   : The Frechet Distance.
    """

    mu1 = np.atleast_1d(mu1)
    mu2 = np.atleast_1d(mu2)

    sigma1 = np.atleast_2d(sigma1)
    sigma2 = np.atleast_2d(sigma2)

    assert (
        mu1.shape == mu2.shape
    ), "Training and test mean vectors have different lengths"
    assert (
        sigma1.shape == sigma2.shape
    ), "Training and test covariances have different dimensions"

    diff = mu1 - mu2

    # product might be almost singular
    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
    if not np.isfinite(covmean).all():
        msg = (
            "fid calculation produces singular product; adding %s to diagonal of cov estimates"
            % eps
        )
        warnings.warn(msg)
        offset = np.eye(sigma1.shape[0]) * eps
        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))

    # numerical error might give slight imaginary component
    if np.iscomplexobj(covmean):
        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
            m = np.max(np.abs(covmean.imag))
            raise ValueError("Imaginary component {}".format(m))
        covmean = covmean.real

    tr_covmean = np.trace(covmean)

    return (
        diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
    )

def calculate_fid(act1, act2):

    mu1, sigma1 = act1.mean(axis=0), cov(act1, rowvar=False)
    mu2, sigma2 = act2.mean(axis=0), cov(act2, rowvar=False)
    fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2)
    return fid


""" Задача 22: Даны два неупорядоченных набора целых чисел (может быть, с повторениями).
Выдать без повторений в порядке возрастания все те числа, которые встречаются в обоих наборах.
Пользователь вводит 2 числа. n — кол-во элементов первого множества. m — кол-во элементов
второго множества. Затем пользователь вводит сами элементы множеств. """

""" import random

n = int(input("Please, insert the quantity of first array's elements: "))
list_first = [random.randint(1, 10) for i in range (n)]
list_first.sort()
print(list_first)
m = int(input("Please, insert the quantity of second array's elements: "))
list_second = [random.randint(1, 10) for i in range (m)]
list_second.sort()
print(list_second)
set_first = set(list_first)
set_second = set(list_second)
set_new = set_first.union(set_second)
print(set_new) """

""" Задача 24: В фермерском хозяйстве в Карелии выращивают чернику. Она растёт на круглой грядке,
причём кусты высажены только по окружности. Таким образом, у каждого куста есть ровно два соседних.
Всего на грядке растёт N кустов. Эти кусты обладают разной урожайностью, поэтому ко времени сбора
на них выросло различное число ягод — на i-ом кусте выросло ai ягод. В этом фермерском хозяйстве
внедрена система автоматического сбора черники. Эта система состоит из управляющего модуля и
нескольких собирающих модулей. Собирающий модуль за один заход, находясь непосредственно перед
некоторым кустом, собирает ягоды с этого куста и с двух соседних с ним. Напишите программу для
нахождения максимального числа ягод, которое может собрать за один заход собирающий модуль,
находясь перед некоторым кустом заданной во входном файле грядки."""

import random
n = int(input("Please, insert the quantity of blueberry bushes: "))
bush = [random.randint(80, 100) for i in range(n)]
print(bush)
sum = list()
for i in range(len(bush)-1):
    sum.append(bush[i-1] + bush[i] + bush[i + 1])
sum.append(bush[-2] + bush[-1] + bush[0])
print(max(sum))

""" Задача №33. Хакер Василий получил доступ к классному журналу и хочет заменить все свои минимальные оценки на
максимальные. Напишите программу, которая заменяет оценки Василия, но наоборот: все максимальные – на минимальные.
Input: 5 -> 1 3 3 3 4
Output: 1 3 3 3 1 """

""" import random

number_list = int(input("Введите количтсво оценок: "))
some_list = [random.randint(1, 5) for i in range (number_list)]

min = max = some_list[0]

for i in some_list:
    if min > i:
          min = i
    elif max < i:
          max = i

print(*some_list)

for i in range (len(some_list)):
    if some_list[i] == max:
        some_list[i] = min

print(*some_list)
 """

""" Дан список интов, повторяющихся элементов в списке нет. Нужно преобразовать это множество
в строку, сворачивая соседние по числовому ряду числа в диапазоны.
Примеры:
[1,4,5,2,3,9,8,11,0] => "0-5,8-9,11"
[1,4,3,2] => "1-4"
[1,4] => "1,4" """

""" some_list = [1, 4, 3, 9, 8, 11, 0, 13, 5, 12]
some_list.sort()
result_list = []
temp_list = []
print(some_list)
for i in range(0, len(some_list)-1):
    if some_list[i + 1] - some_list[i] == 1:
        temp_list.append(some_list[i])
    else:
        temp_list.append(some_list[i])
        result_list.append(temp_list)
        temp_list = []
if temp_list:
    result_list.append(temp_list)

if some_list[-1] - some_list[-2] == 1:
    result_list[-1].append(some_list[-1])
else:
    result_list.append([some_list[-1]])

print(result_list) """


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

# In[ ]:

'''Module: Domestic (Inherits Fan Properties)
Attributes:
    hasSeasonTickets
Functions:
    Initialize Domestic Fan
updateTicketStatus
Module: International (Inherits Fan Properties)
Attributes:
Home Country
Functions:
Initialize Domestic Fan
'''

from club.fan.fan import fan
from club.fan.fantypeExceptions import ViewsException, TicketException

viewMethod = ["Online", "TV", "online", "tv", "ONLINE", "Tv"]

class domestic(fan):
    def __init__(self, name, favouritePlayer, purchasedMerchandise, currentCity, hasSeasonTickets, yearsSinceFan):
        fan.__init__(self, name, favouritePlayer, purchasedMerchandise, currentCity)
        self.hasSeasonTickets = hasSeasonTickets
        self.yearsSinceFan = yearsSinceFan

    def updateTicketStatus(self, newTicketStatus):
        try:
            if isinstance(newTicketStatus, str) == True:
                raise(TicketException(newTicketStatus))
            if isinstance(newTicketStatus, int) == True:
                raise(ValueError)
        except TicketException as texc:
            print("Message: ", texc)
        except ValueError:
            print("Incorrect Value Type")

        else:
            self.hasSeasonTickets = newTicketStatus

    def asList(self):
        return([self.name, self.getFavouritePlayer(), self.getPurchasedMerchandise(), self.getCurrentCity(),
                self.hasSeasonTickets, self.yearsSinceFan])

    def display(self):
        fan.display(self)
        print("   Has Season Tickets: {}\n      Years Since Fan: {}".format(self.hasSeasonTickets, self.yearsSinceFan))

class international(fan):
    def __init__(self, name, favouritePlayer, purchasedMerchandise, currentCity, country, viewMatches):
        fan.__init__(self, name, favouritePlayer, purchasedMerchandise, currentCity)
        self.country = country
        self.viewMatches = viewMatches

    def updateViewMatches(self, newViewMatches):
        try:
            if newViewMatches not in viewMethod:
                raise(ViewsException(newViewMatches))
            if isinstance(newViewMatches, str) != True:
                raise(ValueError)
        except ViewsException as vexc:
            print("Message: ", vexc)
        except ValueError:
            print("Error! Wrong input type!")
        else:
            self.viewMatches = newViewMatches

    def display(self):
        fan.display(self)
        print("              Country: {}\n        Views Matches: {}".format(self.country, self.viewMatches))

    def asList(self):
        return([self.name, self.getFavouritePlayer(), self.getPurchasedMerchandise(), self.getCurrentCity(),
                self.country, self.viewMatches])


import os
import zipfile
import urllib
import numpy as np
import tiktoken

WIKITEXT_DATA_PATH = os.path.join(os.path.dirname(__file__), "datasets/wikitext/")

def get_wikitext_data():
    """ Inspired from https://github.com/tysam-code/hlb-gpt """
    if not os.path.exists(WIKITEXT_DATA_PATH):
        os.makedirs(WIKITEXT_DATA_PATH, exist_ok=True)
        print("downloading data and tokenizing (1-2 min)")
        raw_data_source = 'https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip'
        urllib.request.urlretrieve(raw_data_source, os.path.join(WIKITEXT_DATA_PATH,'data.zip'))

        with zipfile.ZipFile(os.path.join(WIKITEXT_DATA_PATH, "data.zip"), 'r') as zip_ref:
            zip_ref.extractall(WIKITEXT_DATA_PATH)

        with open(os.path.join(WIKITEXT_DATA_PATH, "wikitext-103-raw/wiki.train.raw"), 'r') as data_file:
            raw_train_data = data_file.read()

        with open(os.path.join(WIKITEXT_DATA_PATH, "wikitext-103-raw/wiki.valid.raw"), 'r') as data_file:
            raw_eval_data = data_file.read()

        tokenizer = tiktoken.get_encoding("gpt2")
        raw_tokenized_train = tokenizer.encode_ordinary(raw_train_data)
        raw_tokenized_eval = tokenizer.encode_ordinary(raw_eval_data)

        train_tokenized = np.array(raw_tokenized_train, dtype=np.uint16)
        eval_tokenized = np.array(raw_tokenized_eval, dtype=np.uint16)

        train_tokenized.tofile(os.path.join(WIKITEXT_DATA_PATH, 'train.bin'))
        eval_tokenized.tofile(os.path.join(WIKITEXT_DATA_PATH, 'val.bin'))
        print("completed the tokenization process!")

    train_data = np.memmap(os.path.join(WIKITEXT_DATA_PATH, 'train.bin'), dtype=np.uint16, mode='r')
    val_data = np.memmap(os.path.join(WIKITEXT_DATA_PATH, 'val.bin'), dtype=np.uint16, mode='r')

    return {'train': train_data, 'val': val_data}


# -*- coding: utf-8 -*-
#REFACTORME: Отрефакторить до няшнокавайного состояния
import os

import re
import string
import urlparse

from django.utils.safestring import SafeData, mark_safe
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy
from django.utils.http import urlquote

from django.utils.html import punctuation_re, word_split_re

def is_img_url(url):
    ext = os.path.splitext(url)[1]
    return ext[1:].lower() in ['jpg','jpeg','png','gif', 'bmp']

youtube_re = re.compile(r'^http://www.youtube.com/watch')
def is_youtube_url(url):
    match = youtube_re.match(url)
    if match:
        key =  urlparse.parse_qs(urlparse.urlparse(url).query)['v']
        if key:
            return key[0]
    return None

vimeo_re = re.compile(r'http://vimeo.com/([\d]+)')
def is_vimeo_url(url):
    match = vimeo_re.match(url)
    return match and match.groups()[0]

def imgurlize(text, trim_url_limit=None, nofollow=False, autoescape=False, imgclass=''):
    """
    Converts any URLs in text into clickable links.

    Works on http://, https://, www. links and links ending in .org, .net or
    .com. Links can have trailing punctuation (periods, commas, close-parens)
    and leading punctuation (opening parens) and it'll still do the right
    thing.

    If trim_url_limit is not None, the URLs in link text longer than this limit
    will truncated to trim_url_limit-3 characters and appended with an elipsis.

    If nofollow is True, the URLs in link text will get a rel="nofollow"
    attribute.

    If autoescape is True, the link text and URLs will get autoescaped.
    """
    trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
    safe_input = isinstance(text, SafeData)
    words = word_split_re.split(force_unicode(text))
    nofollow_attr = nofollow and ' rel="nofollow"' or ''
    for i, word in enumerate(words):
        match = None
        if '.' in word or '@' in word or ':' in word:
            match = punctuation_re.match(word)
        if match:
            lead, middle, trail = match.groups()
            # Make URL we want to point to.
            url = None
            if middle.startswith('http://') or middle.startswith('https://'):
                url = urlquote(middle, safe='/&=:;#?+*')
            elif middle.startswith('www.') or ('@' not in middle and \
                    middle and middle[0] in string.ascii_letters + string.digits and \
                    (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
                url = urlquote('http://%s' % middle, safe='/&=:;#?+*')

            is_youtube = is_img = is_vimeo = None
            if url:
                is_youtube = is_youtube_url(url)
                is_img = is_img_url(url)
                is_vimeo = is_vimeo_url(url)
            if url and (is_img or is_youtube or is_vimeo):
                trimmed = trim_url(middle)
                if autoescape and not safe_input:
                    lead, trail = escape(lead), escape(trail)
                    url, trimmed = escape(url), escape(trimmed)

                if is_img:
                    middle = '' % (url, imgclass, url)
                elif is_youtube:
                    template = '''
                    <object width="480" height="385">
                    <param name="movie" value="http://www.youtube.com/v/%(key)s?fs=1&hl=ru_RU"></param>
                    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%(key)s?fs=1&hl=ru_RU" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>
                    %(url)s
                    '''

                    url = '%s' % (url, nofollow_attr, trimmed)
                    middle = template%{'url':url, 'key':is_youtube}
                elif is_vimeo:
                    template = '''
                    <object width="480" height="385">
                    <param name="allowfullscreen" value="true" />
                    <param name="allowscriptaccess" value="always" />
                    <param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=%(key)s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=1&color=00ADEF&fullscreen=1&autoplay=0&loop=0" />
                    <embed src="http://vimeo.com/moogaloop.swf?clip_id=%(key)s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=1&color=00ADEF&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="480" height="385"></embed></object>
                    %(url)s
                    '''
                    url = '%s' % (url, nofollow_attr, trimmed)
                    middle = template%{'url': url, 'key':is_vimeo}

                words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
            else:
                if safe_input:
                    words[i] = mark_safe(word)
                elif autoescape:
                    words[i] = escape(word)
        elif safe_input:
            words[i] = mark_safe(word)
        elif autoescape:
            words[i] = escape(word)
    return u''.join(words)

imgurlize = allow_lazy(imgurlize, unicode)

def nya_parser(string):
    '''
    @todo  запилить нормальный парсинг.
    '''
    from django.utils.html import escape, urlize
    import re
    body = string

    body = escape(body)
    body = imgurlize(body, imgclass="parsed_img")
    body = urlize(body, 42)
    body = re.sub(r'(?:^|\s)@([\w]+)\b', r' <a href="/u/\g<1>">@\g<1> ', body)
    body = re.sub(r'(?:^|\s)/([\d]+)\b', r' <a href="#\g<1>">/\g<1> ', body)
    body = re.sub(r'(?:^|\s)#([\d]+)/([\d])\b', r' <a href="/\g<1>#\g<2>">#\g<1>/\g<2> ', body)
    body = re.sub(r'(?:^|\s)#([\d]+)\b', r' <a href="/\g<1>">#\g<1> ', body)
    return body