# -*- coding: utf-8 -*-
"""
Employee Name: Ashish Kalra
Employee ID: 142968
Batch: GENESIS | Feb 2020
Date: 17 Feb 2020

@author: Ashish
"""

import pandas as pd
import numpy as np
from math import radians, cos, sin, asin, sqrt
#import matplotlib.pyplot as plt

FILE = 'AirlinesData.csv'
DF = pd.read_csv(FILE, index_col=0)

print(DF.head(5))
print(DF.describe())
print(DF.columns)

def main():
    """
    This is the main function consisting of all the test cases
    """
    print("findbyID")
    print(findby_ID(5))
    print("findbyCountry")
    print(findby_Country("India"))
    print("findbyCity")
    print(findby_City("Delhi"))
    print("Number of airports available in the country: ")
    print(avail_Airports("India"))
    print("Number of airports available in the city: ")
    print(avail_Airports("Mumbai"))
    print("Maximum number of Airports in:")
    print(max_Airports())
    print("Highest altitude of an Airport in the country (feet): ")
    print(max_Altitude("India"))
    print("Distance between Airports in the city:")
    print(air_Distance("Agra", "New York"))

def findby_ID(ID):
    #ID = int(input("Enter the Airline ID: "))
    attr = DF.loc[DF['Airline ID'] == ID]
    return attr

def findby_Country(destination):
    if destination in DF['Country'].unique():
        return DF[DF['Country'] == destination]
    else:
        return "Not Available"

def findby_City(destination):
    if destination in DF['City'].unique():
        return DF[DF['City'] == destination]
    else:
        return "Not Available"

def avail_Airports(destination):
    source_1 = DF["Country"].unique()
    source_2 = DF['City'].unique()
    if destination in source_1:
        return len(DF.loc[DF["Country"] == destination, "Name"])
    elif destination in source_2:
        return len(DF.loc[DF["City"] == destination, "Name"])
    else:
        return "No Airports available"

def max_Airports():
    L1 = []
    L2 = []
    def number_Airports():
        listCountry = DF['Country'].unique()
        for i in listCountry:
            L1.append(i)
            L2.append(avail_Airports(i))
    number_Airports()
    max_Airports = np.max(np.array(L2))
    top = L1[L2.index(max_Airports)]
    return top

# highest airport in a country
def max_Altitude(destination):
    highest = np.max(DF.loc[DF['Country'] == destination, "Altitude"])
    return highest

def air_Distance(destination1, destination2):
    Lat1 = DF.loc[DF["City"] == destination1, "Latitude"].iloc[0]
    Long1 = DF.loc[DF["City"] == destination1, "Longitude"].iloc[0]
    Lat2 = DF.loc[DF["City"] == destination2, "Latitude"].iloc[0]
    Long2 = DF.loc[DF["City"] == destination2, "Latitude"].iloc[0]
    def distance(lat1, long1, lat2, long2):
        long1 = radians(long1)
        long2 = radians(long2)
        lat1 = radians(lat1)
        lat2 = radians(lat2)
        dlong = long2 - long1
        dlat = lat2 - lat1
        a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlong / 2)**2
        c = 2 * asin(sqrt(a))
        r = 6371
        return c * r
    airDistance = distance(Lat1, Long1, Lat2, Long2)
    return airDistance

if __name__ == '__main__':
    main()


import csv
import argparse

import delete
import secret

parser = argparse.ArgumentParser(
    prog="delete",
    description="Requests deletion of scary data from Amplitude, based on a Cohort CSV file containing an amplitude_id field."
)
parser.add_argument("csvfile", help="A file that contains an amplitude_id column, used to request deletions.")
args = parser.parse_args()

deleter = delete.Delete(secret.API_KEY, secret.SECRET_KEY)

amplitude_ids = []

with open(args.csvfile, 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        amplitude_ids.append(row["amplitude_id"].strip())

expected_deletion_date = deleter.delete_amplitude_ids(amplitude_ids)
data = deleter.get_deletion_jobs(expected_deletion_date)
print(f"Registered deletion jobs for {expected_deletion_date}:", len(data["amplitude_ids"]))
print(f"Amplitude IDs in input CSV file", len(amplitude_ids))


from django.shortcuts import render

# Create your views here.
from index.appviews import AppBaseTemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from django.http.response import JsonResponse

from .models import History

@method_decorator(login_required,name='dispatch')
class HistoryView(AppBaseTemplateView):
    template_name = 'history/history.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        history_list = History.objects.filter(user=self.request.user).order_by('-create_time')[:100]
        context['history_list'] = history_list
        context['badge_content'] = "所有记录"
        context['tittle'] = "所有记录"
        return context
    def get(self, request, context={}, *args, **kwargs):
        return super().get(request, context, *args, **kwargs)

    def post(self, request, context={}, *args, **kwargs):
        operation = request.POST.get('operation',None)
        ids = request.POST.getlist('ids',None)
        if not operation or not ids:
            return super().post(request, context, *args, **kwargs)

        print(ids)
        if operation=="delete":
            for i in ids:
                try:
                    h = History.objects.get(id=i,user=request.user)
                    h.delete()
                except Exception as e:
                    pass

        return super().post(request, context, *args, **kwargs)

@method_decorator(login_required,name='dispatch')
class HistoryAskingView(HistoryView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        history_list = History.objects.filter(user=self.request.user,type='asking').order_by('-create_time')[:100]
        context['history_list'] = history_list
        context['badge_content'] = "我的提问"
        context['tittle'] = "我的提问"
        return context

@method_decorator(login_required,name='dispatch')
class HistoryAnsweringView(HistoryView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        history_list = History.objects.filter(user=self.request.user,type='answering').order_by('-create_time')[:100]
        context['history_list'] = history_list
        context['badge_content'] = "我的回答"
        context['tittle'] = "我的回答"
        return context

@method_decorator(login_required, name='dispatch')
class HistoryLikingView(HistoryView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        history_list = History.objects.filter(user=self.request.user, type='liking').order_by('-create_time')[
                       :100]
        context['history_list'] = history_list
        context['badge_content'] = "我的点赞"
        context['tittle'] = "我的点赞"
        return context

@method_decorator(login_required, name='dispatch')
class HistoryCollectingView(HistoryView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        history_list = History.objects.filter(user=self.request.user, type='collecting').order_by('-create_time')[
                       :100]
        context['history_list'] = history_list
        context['badge_content'] = "我的收藏"
        context['tittle'] = "我的收藏"
        return context

@method_decorator(login_required, name='dispatch')
class HistoryAdvancedView(AppBaseTemplateView):
    template_name = 'history/history_advanced.html'

    def get_context_data(self, **kwargs):
        context =  super().get_context_data(**kwargs)
        return context

    def post(self, request, context={}, *args, **kwargs):
        operation = request.POST.get('operation',None)
        if operation == "clear_all":
            History.objects.filter(user=request.user).delete()
        return super().post(request, context, *args, **kwargs)


def kth_to_last(l, k):
    l_len = l.len()

    if k > l_len:
        return None

    count = 0
    node = l.head
    idx = l_len - k

    while node:
        if count == idx:
            return node

        node = node.next
        count += 1

    return None


fruits = ["apple","pear", "banana"]
# print(fruits[0])

# fruits[0] += "s"
# print(fruits)
# [0,1,2]

for num in range(len(fruits)):
    fruits[num] += "s"

print(fruits)

# print(list(enumerate(fruits)))
# [(0, 'apple'), (1, 'pear'), (2, 'banana')]

for index,value in enumerate(fruits):
    fruits[index] += "s"

print(fruits)

# 1st loop
# index = 0
# value = "apple"
# fruits[index] += "s"
# --> fruits[0] += "s"
# -->

# for value in fruits:
#     print(value)

# print(fruits)

fruits = ["apple", "banana", "pear"]
prices = [1.3, 0.5, 1.6]
colors = ["red", "yellow", "red"]

all = zip(fruits, prices, colors)

print(list(all))

all2 = zip(fruits, prices)
dict1 = dict(all2)
print(dict1)
# {'apple': 1.3, 'banana': 0.5, 'pear': 1.6}

employees = [
    {
        "username" : "Jon",
        "monthly_salary" : 2000
    },
    {
        "username" : "Emma",
        "monthly_salary" : 5000
    },
    {
        "username" : "Paul",
        "monthly_salary" : 1300
    }
]

high_salary_people = [person["username"] for person in employees if person["monthly_salary"] > 1500]
print(high_salary_people)

# Syntax
# [what_to_add for_loop condition]


import numpy as np
import random

class ReplayMemory():
    def __init__(self, size, observation_shape, hist_len):
        self.size = size
        self.count = 0
        self.current = 0
        self.hist_len = hist_len
        self.observation_shape = observation_shape

        self.observations = np.empty((size,) + observation_shape, dtype=np.uint8)
        self.actions = np.empty(size, dtype=np.uint8)
        self.rewards = np.empty(size, dtype=np.float32)
        self.dones = np.empty(size, dtype=np.bool)

    def add(self, obs, action, reward, done):
        self.observations[self.current] = obs
        self.actions[self.current] = action
        self.rewards[self.current] = reward
        self.dones[self.current] = done

        self.current += 1
        self.count = max(self.current, self.count)
        self.current %= self.size

    def sample(self, batch_size):
        assert self.count - self.hist_len > batch_size

        n = 0
        idx = np.empty(batch_size, dtype=np.uint32)
        obs = np.empty((batch_size, self.observation_shape[0], self.observation_shape[1], self.observation_shape[2] * self.hist_len), dtype=np.uint8)
        next_obs = np.empty((batch_size, self.observation_shape[0], self.observation_shape[1], self.observation_shape[2] * self.hist_len), dtype=np.uint8)
        while n < batch_size:
            # reserve hist_len in the beginning of replay memory
            i = random.randint(self.hist_len, self.count - 1)
            # i is the index of _next_ observation
            # skip if episode ended within previous hist_len frames
            # or if current pointer is within those hist_len frames
            if np.any(self.dones[(i - self.hist_len):(i - 1)]) \
                    or (i - self.hist_len) < self.current <= i:
                #print("not good:", i)
                continue
            else:
                #print("good:", i)
                pass
            # take slice of last hist_len observations
            obs[n] = np.swapaxes(self.observations[(i - self.hist_len):i], 0, 3)[0]
            next_obs[n] = np.swapaxes(self.observations[(i - self.hist_len + 1):(i + 1)], 0, 3)[0]
            idx[n] = i - 1
            n += 1

        actions = self.actions[idx]
        rewards = self.rewards[idx]
        dones = self.dones[idx]
        return obs, actions, rewards, dones, next_obs

if __name__ == '__main__':
    mem = ReplayMemory(10, (84, 84, 1), 4)
    assert mem.size == 10
    assert mem.current == 0
    assert mem.count == 0

    assert mem.observations.shape == (10, 84, 84, 1)
    assert mem.actions.shape == (10,)
    assert mem.rewards.shape == (10,)
    assert mem.dones.shape == (10,)

    for i in range(25):
        mem.add(np.ones((84, 84, 1)) * i, i, i, i % 17 == 0)
        assert mem.size == 10
        assert mem.current == (i + 1) % 10
        assert mem.count == (i + 1 if i < 10 else 10)

    print(np.mean(mem.observations, axis=(1, 2, 3)))
    print(mem.actions)
    print(mem.dones)

    obs, actions, rewards, dones, next_obs = mem.sample(4)
    for i in range(len(obs)):
        assert obs.shape == (4, 84, 84, 4)
        assert actions.shape == (4,)
        assert rewards.shape == (4,)
        assert dones.shape == (4,)
        assert next_obs.shape == (4, 84, 84, 4)
        assert np.mean(obs[i, :, :, 3]) == actions[i]
        assert np.mean(obs[i, :, :, 2]) == actions[i] - 1
        assert np.mean(obs[i, :, :, 1]) == actions[i] - 2
        assert np.mean(obs[i, :, :, 0]) == actions[i] - 3
        assert np.mean(next_obs[i, :, :, 3]) == actions[i] + 1, str(np.mean(next_obs[i, :, :, 3])) + ' != ' + str(actions[i] + 1)
        assert np.mean(next_obs[i, :, :, 2]) == actions[i]
        assert np.mean(next_obs[i, :, :, 1]) == actions[i] - 1
        assert np.mean(next_obs[i, :, :, 0]) == actions[i] - 2
        assert rewards[i] == actions[i]
        assert dones[i] == (actions[i] % 17 == 0)


from mrjob.job import MRJob
import os
import re

class MRSentiment(MRJob):
    def mapper_init(self):
        self.weights = {}
        with open('C:/Users/SuperLinguini/Documents/Clubs GT/Big Data/mrjob-tutorial/sentiments.txt', 'r') as f:
            for line in f:
                ls = re.split('\s+', line.strip().lower());
                if len(ls) == 2:
                    word = ls[0]
                    word = re.sub('\W', '', word)
                    self.weights[word] = float(ls[1])

    def mapper(self, _, line):
        ls = line.lower().split()
        count = 0
        for word in ls:
            if word in self.weights:
                count += self.weights[word]
            yield word, count

    def reducer(self, key, values):
        tot, n = 0.0, 0.0
        for value in values:
            n += 1
            tot += value
        yield (key, tot/n)

def windows_fix():
    # Windows can't make symlinks without being an Administrator.
    # Workaround: Pretend we can't make symlinks and mrjob will work without them.
    # https://github.com/Yelp/mrjob/blob/cc64250308ebf887f4dfe24959f3877a1cd31404/mrjob/sim.py#L123
    if os.name == 'nt':
        del os.symlink

if __name__ == '__main__':
    windows_fix()
    MRSentiment.run()


'''
quqacukqauackck
quackquackquackquackquackquackquackquackquackquack
'''
s = input()
lst = s.split('quack')

ans = 0
if len(lst)>1:
    tmp = ''.join(lst)
    if tmp == '':
        ans = 1
    else:
        ans = -1
else:
    tmp_s = list(lst[0])
    dock ='quack'
    cnt = 0
    while 1:
        for d_o in dock:
            for i in range(len(tmp_s)):
                if d_o == tmp_s[i]:
                    tmp_s = '_'
                    break
            else:
                break
        else:
            cnt+=1
    print(cnt)

print(ans)


from typing import List, Optional
from fastapi import Depends, Request
from fastapi import APIRouter
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session
from db.connection import get_session
from models.cascade import CascadeNameAndLevel
from db import crud_cascade

from source.main import main_config

QuestionConfig = main_config.QuestionConfig
SchoolInformationEnum = main_config.SchoolInformationEnum
CascadeLevels = main_config.CascadeLevels

security = HTTPBearer()
cascade_route = APIRouter()

school_information_qid = QuestionConfig.school_information.value
school_information_levels = CascadeLevels.school_information.value

@cascade_route.get(
    "/cascade/school_information",
    response_model=List[CascadeNameAndLevel],
    name="cascade:get_school_information",
    summary="get school information cascade of filter",
    tags=["Cascade"]
)
def get_cascade(
    req: Request,
    level: Optional[SchoolInformationEnum] = None,
    session: Session = Depends(get_session)
):
    level_numb = school_information_levels[level.value]
    cascade = crud_cascade.get_cascade_by_question_id(
        session=session,
        question=school_information_qid,
        level=level_numb,
        distinct=True)
    cascade = [c.to_name_level for c in cascade]
    cascade.sort(key=lambda x: x.get('name'))
    return cascade


import sys
import analyze_annotations
import pandas as pd

model_name = sys.argv[1]
#model_name = 'giga_full_updated'

top_cutoff = 3
concept_cutoff = 3
ann_dict = analyze_annotations.show_annotation_status(model_name, top_cutoff, concept_cutoff)
properties = ann_dict['complete']

#cols = ['property', 'u', 'all', 'prop_specific', 'non-specific'] # 'p', 'n', 'l', 'i', 'r', 'b']
cols = ['property']
e_types = ['all', 'prop_specific', 'non-specific']
#e_types = ['prop_specific']

for et in e_types:
    cols.append(f'{et}-div')
print(cols)

table = []
for prop in list(properties):
    d = dict()
    d['property'] =  prop
    et_counts = analyze_annotations.get_evidence_diversity(model_name, prop, e_types, top_cutoff, concept_cutoff)
    for et, count in et_counts.items():
        d[f'{et}-div'] = count
    #d.update(analyze_annotations.get_evidence_diversity(model_name, prop, top_cutoff, concept_cutoff))
    for c in cols:
        if c not in d:
            d[c] = 0#np.nan
    table.append(d)

#cols = ['property', 'u', 'all', 'prop_specific', 'non-specific'] #, 'p', 'n', 'l', 'i', 'r', 'b']
df = pd.DataFrame(table)[cols]
df = df[cols].sort_values('prop_specific-div', ascending = False) #.round(2) #.round(0)
#print(df.to_latex(index=False))
df.to_csv(f'../analysis/diversity-{model_name}.csv')


#! python3
# -*- coding: utf-8 -*-

from checkdrawn import addbets_contest
from checkdrawn import checkdrawn

from createbets import iter_create_bet
from createbets import viewbets
from createbets import remove as removebets

from createcontest import create as createcontest
from createcontest import viewcontests
from createcontest import get_bets_contests
from createcontest import remove as removecontest

def menu_checkdrawn():
    option=''
    while (option != 'X'):
        print('1 = Checar apostas / 2 = Incluir apostas no concurso / X = Sair')
        option = input()
        if (option == '1'):
            checkdrawn('lotofacil',None)
        elif (option == '2'):
            print('digite o concurso para adicionar apostas:')
            contest_number = input()
            print('lista de apostas')
            print(viewbets())
            print('Digite o id da aposta que será incluida no concurso')
            betid = input()
            addbets_contest(contest_number,'lotofacil',betid)
            print('Aposta adicionada')

def menu_createbets():
    option=''
    while (option != 'X'):
        print('1 = Criar nova aposta / 2 = visualizar aposta / 3 = remover aposta / X = Sair')
        option = input()
        if (option == '1'):
            print('Criar nova aposta')
            iter_create_bet()
        elif (option == '2'):
            print('lista de apostas')
            print(viewbets())
        elif (option == '3'):
            print('Digite o id da aposta para excluir:')
            bet_number = input()
            removebets(str(bet_number))

def menu_createcontest():
    option=''
    while (option != 'X'):
        print('1 = Criar novo concurso \n 2 = visualizar concurso \n 3 = visualizar apostas de um concurso \n 4 = remover concurso / X = Sair')
        option = input()
        if (option == '1'):
            print('Digite o novo concurso:')
            contest_number = input()
            print('Digite a modalidade do concurso')
            modality = input()
            print('concurso ', createcontest(contest_number, modality), ' cadastrado com sucesso')
        elif (option == '2'):
            viewcontests()
        elif (option == '3'):
            print('Digite o concurso:')
            contest_number = input()
            x = get_bets_contests(str(contest_number))
        elif (option == '4'):
            print('Digite o concurso para excluir:')
            contest_number = input()
            removecontest(str(contest_number))

option=''
while (option != 'X'):
    print('1 = Checar concurso \n 2 = Criar Apostas \n 3 = Criar Concursos \n X = Sair')
    option = input()
    if (option == '1'):
        menu_checkdrawn()
    elif (option == '2'):
        menu_createbets()
    elif (option =='3'):
        menu_createcontest()


import pytest
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch

from saleor.account.models import User

def test_staff_with_permission_can_impersonate(
    staff_client, customer_user, staff_user, permission_impersonate_users
):
    staff_user.user_permissions.add(permission_impersonate_users)
    staff_user = User.objects.get(pk=staff_user.pk)
    response = staff_client.get(
        reverse("impersonate-start", args=[customer_user.pk]), follow=True
    )
    assert response.context["user"] == customer_user
    assert response.context["user"].is_impersonate
    assert response.context["request"].impersonator == staff_user

    response = staff_client.get(reverse("impersonate-stop"), follow=True)
    assert response.context["user"] == staff_user
    assert response.context["user"].is_impersonate is False

def test_impersonate_list_search_urls_are_disabled():
    with pytest.raises(NoReverseMatch):
        reverse("impersonate-list")
    with pytest.raises(NoReverseMatch):
        reverse("impersonate-search")

def test_impersonate_start_url_uid_arg_is_number():
    with pytest.raises(NoReverseMatch):
        reverse("impersonate", args=["string"])