import random
import time

SLOT_SYMBOLS = ["🍒", "🍇", "🍊", "💖", "💰", "🍎", "🍉", "🔔", "🍋", "7"]
bank = 200

class Slot():
    def __init__(self):
        self.slot_value = None

    def spin(self):
        # animate symbols
        for i in range(50):
            print(f"\r{SLOT_SYMBOLS[random.randrange(0, len(SLOT_SYMBOLS))]} {SLOT_SYMBOLS[random.randrange(0, len(SLOT_SYMBOLS))]} {SLOT_SYMBOLS[random.randrange(0, len(SLOT_SYMBOLS))]}", end='')
            time.sleep(0.015)

        self.slot_value = SLOT_SYMBOLS[random.randrange(0, len(SLOT_SYMBOLS))]
        return self.slot_value

slot_1, slot_2, slot_3 = Slot(), Slot(), Slot()

def check_win(slot1Value, slot2Value, slot3Value):
    winnings = 0
    isWin = False

    if slot1Value == "🍒" and slot2Value != "🍒" and slot3Value != "🍒":
        print("You Win with 1 Cherry!")
        isWin = True
        winnings = 20
    elif slot1Value == slot2Value and slot1Value == slot3Value:
        if slot1Value == "🍇":
            winnings = 100
            isWin = True
        elif slot1Value == "💖":
            winnings = 200
            isWin = True
        elif slot1Value == "🍋":
            winnings = 300
            isWin = True
        elif slot1Value == "🔔":
            winnings = 400
            isWin = True
        elif slot1Value == "7":
            winnings = 1000
            isWin = True
    else:
        print("Sorry, you lose!")
        winnings = -20
        isWin = False

    return isWin, winnings

def run():
    global bank
    while True:
        print(f"You currently have ${bank}!")
        choice = input("Press ENTER to spin or type 'q' to quit>")
        if choice.lower() == 'q':
            break
        else:
            print(f"\r{slot_1.spin()} {slot_2.spin()} {slot_3.spin()}", end=' ')
            bank += check_win(slot_1.slot_value, slot_2.slot_value, slot_3.slot_value)[1]
            if bank <= 0:
                print("Game over!")
                choice = input("[P]lay again? [Q]uit? >").lower()
                if choice == 'p':
                    bank = 200
                    continue
                else:
                    print("Thank you for playing.")
                    break
            else:
                print(f"You have ${bank}!")
                choice = input("[S]pin again? [Q]uit? >").lower()
                if choice == 's':
                    continue
                else:
                    print(f"You won a total of ${bank}! Good job!")
                    print("Thank you for playing.")
                    break

if __name__ == '__main__':
    run()


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import xml.etree.cElementTree as ET
import re

class Task1Pipeline:
    def open_spider(self, spider):
        self.root = ET.Element("data")
        self.regex = re.compile(r'^[ \t\r\n]*$')
        self.links = []

    def close_spider(self, spider):
        for link in self.links:
            ET.SubElement(self.root, "link").text = link
        tree = ET.ElementTree(self.root)
        tree.write("task1.xml", encoding='utf-8')

    def process_item(self, item, spider):
        items = ItemAdapter(item).asdict()
        page = ET.SubElement(self.root, "page", url=items["page"])
        filtered = [i for i in items["text"] if not self.regex.match(i)]
        ET.SubElement(page, "fragment", type="text").text = ''.join(filtered)
        filtered = [i for i in items["images"] if not self.regex.match(i)]
        ET.SubElement(page, "fragment", type="image").text = ' '.join(filtered)
        self.links += items["links"]
        return item

class Task2Pipeline:
    text = []
    images = []
    prices = []

    def open_spider(self, spider):
        self.root = ET.Element("data")

    def close_spider(self, spider):
        tree = ET.ElementTree(self.root)
        tree.write("task2.xml", encoding='utf-8')

    def process_item(self, item, spider):
        items = ItemAdapter(item).asdict()
        self.text += items['text']
        self.images += items['images']
        self.prices += items['prices']
        if len(self.images) >= 20 :
            for i in range(20):
                elem = ET.SubElement(self.root, "item")
                ET.SubElement(elem, "description").text = self.text[i]
                ET.SubElement(elem, "price").text = self.prices[i]
                ET.SubElement(elem, "image").text = self.images[i]
        return item


import asyncio
import discord
import time
import Discordbotfunctions as functions

client = discord.Client()

# What the bot does on startup
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" The Roots"))

# events that occur when messages are sent
@client.event
async def on_message(message):

    # ignores own messages sent by bot
    if message.author == client.user:
        return

    # help menu
    if message.content.startswith('$help'):
        await message.channel.send("""Yo, what up? I\'m here to make using this server easier. My Commands include:
        -**$help**:
            lists all available commands
        -**$games**:
            lists all available games
        -**$ltrflwi**:
            Gives Information about the Letter Flow game
        -**tprapi:
            Gives information about the Topic Rap Game
        """)

    # Games menu
    if message.content.startswith('$games'):
        await message.channel.send("""I specialize in Hip-Hop games. If your down to play select a game: $ltrflw,
        $tprap, $story""")

    # Games are here
    if message.content.startswith('$ltrflwi'):
        await message.channel.send("In this game each person has got 5 seconds of time to rap about letters"
                                   "in the alphabet. If you stumble or mess up, pick up the flow with the next person."
                                   "The goal is to reach the letter Z without messing up. If you want to play type: "
                                   "$ltry")

        await asyncio.sleep(5)

        if message.content.startswith('$ltry'):
            await message.channel.send("Yo yo yo, the game is about to start! stop type $stop")
            letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

            for letter in letters:

                await message.channel.send("The next letter is: "+str(letter))
                await asyncio.sleep(2)
                await message.channel.send("3"),
                await asyncio.sleep(1)
                await message.channel.send("2"),
                await asyncio.sleep(1)
                await message.channel.send("1"),
                await asyncio.sleep(1)

                if letter == 'Z':
                    await message.channel.send("Aaaand the game has finished!")
                    break

client.run(functions.get_key("D:\Programming\python\Miscellaneous stuff\Discordbotkeys.txt", "2pac"))


def preberi (ime_datoteke):
    dat = open(ime_datoteke).read().split("\n")
    d = {}
    i = 1
    for vrstica in dat:
        if vrstica == "":
            break
        d[i]=[]
        i+=1

    j = 1
    for vrstica in dat:
        if vrstica == " ":
            break
        cifra = vrstica.split(" ")
        for c in cifra:
            if c == '':
                break
            d[j].append(int(c))
        j+=1
    for indeks in d:
       d[indeks]=sortiraj(d[indeks])
    return d

def sortiraj(seznam):
    if len(seznam)==1:
        return seznam
    i = 0
    min = seznam[0]
    while i<len(seznam):
        if min > seznam[i]:
            min = seznam[i]
        i+=1

    zbrisano = []
    j = 0
    while True:
        if seznam[j] == min:
            break
        zbrisano.append(seznam[j])
        seznam.pop(j)
    seznam.extend(zbrisano)
    return seznam

def mozna_pot(pot, zemljevid):
    mozni_izhodi_vhodi = preveri_vhod_izhod(zemljevid)
    if pot[0] not in mozni_izhodi_vhodi or pot[-1] not in mozni_izhodi_vhodi:
        return False
    i = 0
    j = 1

    while j < len(pot):
        if pot[i] not in zemljevid[pot[j]] or (pot[i] in mozni_izhodi_vhodi and i>0) or pot[i]==pot[j]:
            return False
        i += 1
        j += 1

    return True

def preveri_vhod_izhod(zemljevid):
    seznam=[]
    for indeks in zemljevid:
        if len(zemljevid[indeks])==1:
            seznam.append(indeks)
    return seznam

def hamiltonova(pot,zemljevid):
    stKrozisc = 0
    if mozna_pot(pot,zemljevid):

        dolzinaUnikat = unikati(pot)

        if len(pot) == len(dolzinaUnikat):

            for st, krozisce in zemljevid.items():
                if len(krozisce) > 1:
                    stKrozisc = stKrozisc + 1

            if len(pot) - 2 == stKrozisc:
                return True
            else:
                return False
        else:
            return False
    else:
        return False

def unikati(s):
    seznam=[]
    for i in s:
        if i not in seznam:
            seznam.append(i)
    return seznam

def navodila(pot, zemljevid):
    gps = []
    j = 0
    premik = 0

    while j < len(pot)-2:
        prejsnji = pot[j]
        trenutni = pot[j+1]
        naslednji = pot[j+2]
        izvozi = zemljevid[trenutni]
        izhodisce = izvozi.index(prejsnji)
        izvozi.extend(izvozi)
        while True:
            if izvozi[izhodisce] == naslednji:
                break
            izhodisce += 1
            premik += 1
        gps.append(premik)
        premik = 0
        j+=1

    return gps

def prevozi(zacetek, navodila, zemljevid):
    prevozeno = []
    prevozeno.append(zacetek)
    krozisce = zemljevid[zacetek][0]
    prevozeno.append(krozisce)
    izhodisce = zacetek
    indeks = 0

    for cifra in navodila:
        krozisca = zemljevid[krozisce]
        i = 0
        while i<len(krozisca):
            if krozisca[i] == izhodisce:
                indeks = i
                break
            i+=1
        indeks += cifra
        krozisca.extend(krozisca)
        izhodisce = krozisce
        krozisce = krozisca[indeks]
        prevozeno.append(krozisce)

    return prevozeno


from random import random, randrange

class TestSensors:
    def __init__(self):
        pass

    def GetData(self):
        self.power1 = round(random() * 100, 1)
        self.power2 = round(random() * 100, 1)

        self.voltage1 = randrange(1163, 1289) / 100
        self.voltage2 = 12
        self.current1 = round(self.power1 / self.voltage1, 2)
        self.current2 = round(self.power2 / self.voltage2, 2)

        self.usage = abs(self.power1 - self.power2)

        return {
            "BatteryVoltage": self.voltage1,
            "SolarVoltage": self.voltage2,
            "BatteryCurrent": self.current1,
            "SolarCurrent": self.current2,
            "BatteryPower": self.power1,
            "SolarPower": self.power2,
            "Usage": self.usage,
        }


import sys
input = sys.stdin.readline

s = input().rstrip()
q = int(input())

count = [[0] * 26 for _ in range(len(s))]  # 구간 별로 각 알파벳 개수 셀 배열
count[0][ord(s[0]) - 97] = 1
for i in range(1, len(s)):
    count[i][ord(s[i]) - 97] = 1  # 문자열 (i, i번째 알파벳) 위치 1로 초기화
    for j in range(26):
        count[i][j] += count[i-1][j]  # 직전까지의 알파벳 개수 반영해주기

for _ in range(q):
    a, l, r = input().split()
    l, r = map(int, [l, r])
    if l > 0:
        print(count[r][ord(a) - 97] - count[l-1][ord(a) - 97])
    else:
        print(count[r][ord(a) - 97])

백준/Silver/16139. 인간－컴퓨터 상호작용/인간－컴퓨터 상호작용.py

인간－컴퓨터 상호작용.py


import enum
import os
from typing import List, Tuple, Union, Optional

import PIL.Image
import numpy as np

from .. import transforms as trafos
from ..base import BaseDataset

class FASSEGParts(tuple, enum.Enum):
    """Mapping of part names to colors in FASSEG dataset."""
    EYES = (0, 0, 255)
    NOSE = (0, 255, 255)
    SKIN = (255, 255, 0)
    HAIR = (127, 0, 0)  # incl. brows: "background",
    BACKGROUND = (255, 0, 0)
    MOUTH = (0, 255, 0)

class FASSEGHandle(BaseDataset):
    """Handle for FASSEG-like datasets.

    .. note::
        The original FASSEG dataset is not required for this handle.
        Any dataset with a format following that of the FASSEG dataset is
        supported (folder structure, file types, color codes).

    The FASSEG dataset can be found here::
    https://github.com/massimomauro/FASSEG-repository

    The required structure for supported datasets is very simple

    - under :py:attr:`~hybrid_learning.datasets.base.BaseDataset.dataset_root`
      all input images
    - under :py:attr:`annotations_root`
      all annotation files with the same file name as the corresponding input
      image

    Once a handle is instantiated, its ``__getitem__`` yields tuples
    of input image and binary part segmentation mask (possibly transformed
    by :py:attr:`hybrid_learning.datasets.base.BaseDataset.transforms`).
    For details see :py:meth:`getitem`.
    """

    @property
    def part_name(self) -> Optional[str]:
        """The string name of the part that is extracted from the masks."""
        return getattr(self.part, 'name', self._part_name)

    def __init__(self, dataset_root: str, annotations_root: str = None,
                 part: Union[FASSEGParts, Tuple[int, int, int]] = None,
                 part_name: str = None,
                 **kwargs):
        """Init.

        :param dataset_root: the directory under which to find the images;
        :param annotations_root: the directory under which to find the
            segmentation masks; assumes as default that

            - ``dataset_root`` is :file:`{path}/{split}_RGB` and
            - ``annotations_root`` is :file:`{path}/{split}_Labels`

        :param part: the :py:class:`FASSEGParts` instance to use the color of
            or the color tuple
        :param part_name: the string name of the ``part`` that is extracted;
            overridden by ``part.name`` if ``part`` features such an attribute
        :param kwargs: parameters for
            :py:class:`~hybrid_learning.datasets.base.BaseDataset`
        """
        # Value checks and default values
        if part is None and part_name is None:
            raise ValueError("Part specification or part_name needed!")
        part = part if part is not None else FASSEGParts[part_name]
        # Dataset root exists?
        if not os.path.isdir(dataset_root):
            raise NotADirectoryError("Given dataset_root {} does not exist"
                                     .format(dataset_root))
        # Annotations root (given or default) exists?
        if annotations_root is not None and not os.path.isdir(annotations_root):
            raise NotADirectoryError("Given annotations_root {} does not exist"
                                     .format(annotations_root))
        if annotations_root is None:
            annotations_root: str = "{}Labels" \
                .format(dataset_root.rsplit("RGB", 1)[0])
            if not os.path.isdir(annotations_root):
                raise ValueError(("annotations_root not given and default {} "
                                  "does not exist").format(annotations_root))

        super().__init__(dataset_root=dataset_root, **kwargs)

        self.part = part
        """Part of the face and its color to select mask of."""
        self._part_name = part_name
        """Default for string name of the part if :py:attr:`part` has no
        attribute ``name``."""
        self.annotations_root: str = annotations_root
        """Path to the annotations root folder under which to find the
        annotation files."""
        self.img_fns: List[str] = \
            [fn for fn in os.listdir(self.dataset_root)
             if os.path.isfile(os.path.join(self.dataset_root, fn))]
        """List of file names of images (and their annotations) handled by
        this instance.
        Images can be found in the
        :py:attr:`~hybrid_learning.datasets.base.BaseDataset.dataset_root` and
        annotations in :py:attr:`annotations_root`.
        These are used for :py:meth:`getitem`."""

        # Are there labels for all files?
        for i in range(len(self.img_fns)):
            if not os.path.isfile(self.mask_filepath(i)):
                raise FileNotFoundError(
                    "For input image {} no mask file {} exists".format(
                        os.path.isfile(os.path.join(self.dataset_root,
                                                    self.img_fns[i])),
                        os.path.isfile(os.path.join(self.annotations_root,
                                                    self.img_fns[i]))))

    def __len__(self):
        return len(self.img_fns)

    # noinspection PyTypeChecker
    def getitem(self, i: int) -> Tuple[PIL.Image.Image, PIL.Image.Image]:
        """Load image and its mask at index ``i`` and select binary part mask.

        Used for
        :py:meth:`~hybrid_learning.datasets.base.BaseDataset.__getitem__`.
        The value of the return tuple ``(input_img, part_mask)`` are
        :py:class:`torch.Tensor` representations of
        :py:class:`PIL.Image.Image` image instances.
        """
        img: PIL.Image.Image = PIL.Image.open(self.image_filepath(i))
        mask: PIL.Image.Image = PIL.Image.open(self.mask_filepath(i))

        # obtain binary mask for specific part:
        rgb_color: np.ndarray = np.array(self.part)
        part_mask: PIL.Image.Image = PIL.Image.fromarray(
            np.all(np.array(mask) == rgb_color, axis=-1))

        return img, part_mask

    def descriptor(self, i: int) -> str:
        """Return the image file name for index ``i``.
        This is unique throughout a FASSEG like dataset and can be used for
        e.g. image IDs for caching."""
        return self.img_fns[i]

    def image_filepath(self, i):
        """Provide the path to the image at index ``i``."""
        return os.path.join(self.dataset_root, self.descriptor(i))

    def mask_filepath(self, i):
        """Provide the path to the mask at index ``i``."""
        return os.path.join(self.annotations_root, self.descriptor(i))

    _default_transforms: trafos.TupleTransforms = \
        trafos.OnBothSides(trafos.ToTensor())
    """Default transformation function transforming images to
    :py:class:`torch.Tensor`."""


import random
import warnings
from torch.utils.data import Subset
import collections.abc as abc
from datasets.CPSCDataset import CPSCDataset2D

random.seed(9834275)

def load_2d_dataset(data_path, ref_path) -> CPSCDataset2D:
    return CPSCDataset2D(data_path, ref_path)

def load_datasets(data_path, ref_path):
    return load_2d_dataset(data_path, ref_path)

def split(dataset, ratio: tuple) -> tuple:  # ratio e.g. (0.8, 0.1, 0.1)
    size = len(dataset)
    indices = list(range(size))
    random.shuffle(indices)
    split_sizes = (int(size * ratio[0]), int(size * ratio[1]), int(size * ratio[2]))

    train_indices = indices[0:split_sizes[0]]
    eval_indices = indices[split_sizes[0]:split_sizes[0] + split_sizes[1]]
    test_indices = indices[split_sizes[0] + split_sizes[1]:]

    train_set = Subset(dataset, indices=list(train_indices))
    eval_set = Subset(dataset, indices=list(eval_indices))
    test_set = Subset(dataset, indices=list(test_indices))

    return train_set, eval_set, test_set

def split_dataset(dataset: CPSCDataset2D, k_split: tuple[int, abc.Sequence]) -> tuple[tuple]:
    k = k_split[0]
    if k < 0:
        message = f"k {k} < 0, rounding to 1"
        warnings.warn(message)
        k = 1

    ratio = tuple(k_split[1])  # sequence
    #ratio = [round(x / sum(ratio), 2) for x in ratio]
    if ratio[0] < ratio[1] or ratio[0] < ratio[2]:
        message = f"splits may not be correct: (train, eval, test) = {ratio}"
        warnings.warn(message)

    return tuple(split(dataset, ratio) for _ in range(k_split[0]))


# Import flask
from flask import Flask, render_template, url_for, request, jsonify, redirect
# Import bike_data.py
import bike_data as bd
# Convert month int to month string
import calendar as cal

# Create flask app
app = Flask(__name__)

# Web page
@app.route("/")
def main():
    # Renders home page with data-summary answers
    return render_template('index.html',
        max_start_month=bd.max_start_month,
        max_start_dow=bd.max_start_dow,
        max_start_hod=bd.max_start_hod,
        total_trip_duration=bd.total_trip_duration,
        avg_trip_duration=bd.avg_trip_duration,
        max_start_station=bd.max_start_station,
        max_end_station=bd.max_end_station,
        max_start_end_station=bd.max_start_end_station,
        customers=bd.customers,
        subscribers=bd.subscribers,
        males=bd.males,
        females=bd.females,
        by_oldest=bd.by_oldest,
        by_youngest=bd.by_youngest,
        by_popular=bd.by_popular
    )

# Helper function
def city_to_name(month_abbrev):
    if month_abbrev == 'chi':
        month = 'Chicago'
    elif month_abbrev == 'ny':
        month = 'New York City'
    elif month_abbrev == 'dc':
        month = 'Washington DC'
    return month

# Web page
@app.route("/data", methods=['GET', 'POST'])
def data():
    # POST requests
    if request.method == 'POST':
        city = request.form.get('city')
        month = request.form.get('month')
        dow = request.form.get('dow')
        data = bd.data_inquiry(city=city, month=month, dow=dow)
        return render_template('data.html',
            data=data
        )

# Check if this file is the main program
if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    # flash will use to create sessions for users.
    app.secret_key = 'super_secret_key'
    # Server reloads itself each time a load change,
    # and gives helpful debugger.
    app.debug = True
    # Run function used to run local server with application.
    # By default, server only accessible on host machine
    # But because using Vagrant, must change port to 0.0.0.0 to state that
    # web server should listen on all public IP Addresses
    # and make server publicly available
    app.run(host='0.0.0.0', port=5000)


import os

class FileLock:
    def __init__(self, filename):
        self.filename = filename
        self.fd = None
        self.pid = os.getpid()

    def acquire(self):
        try:
            self.fd = os.open(self.filename, os.O_CREAT|os.O_EXCL|os.O_RDWR)
            # Only needed to let readers know who's locked the file
            os.write(self.fd, "%d" % self.pid)
            return 1    # return ints so this can be used in older Pythons
        except OSError:
            self.fd = None
            return 0

    def release(self):
        if not self.fd:
            return 0
        try:
            os.close(self.fd)
            os.remove(self.filename)
            return 1
        except OSError:
            return 0

    def __del__(self):
        self.release()

def main():
    lock = FileLock("lock.file")
    while 1:
        if lock.acquire():
            raw_input("acquired lock. Press ENTER to release:")
            lock.release()
            raw_input("released lock. Press ENTER to retry:")
        else:
            raw_input("Unable to acquire lock. Press ENTER to retry:")

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  5 11:25:41 2018

@author: ElAwbery
"""

# Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that
# 0 < pwr < 6, and root**pwr is equal to the integer entered by the user. If no such pair of integers exists,
# it should print a message to that effect

# my first attempt:

userInt = int(input("Enter an integer: "))

absUserInt = abs(userInt)
pwr = 2
root = 0
notFound = True

while pwr < 6:

    while root <= absUserInt and notFound:
        if root**pwr == absUserInt:
            notFound = False
            if userInt < 0 and root%2 == 0:
                print ("No perfect root")
                break
            elif userInt < 0:
                root = -root
            print (userInt, "=", root, "^", pwr)
        else:
            root = root + 1

    pwr = pwr + 1
    root = 0

if notFound:
    print ("There are no integers such that", userInt, "has an integer root to the power of another integer less than or equal to 6.")

# A later attempt with better code:

userInt = int(input("Enter an integer: "))

pwr = 2
root = 0
notFound = True

while pwr < 6 and notFound:

    while root <= userInt and notFound:
        if root**pwr == userInt:
            print(userInt, "=", root, "^", pwr)
            notFound = False
        else:
            root = root + 1
    pwr = pwr + 1
    root = 0

if notFound:
    print (userInt, "has no natural roots with 1 < power < 6")


class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """用字典保存 value:index
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """

        d = {}

        for i, num in enumerate(nums):
            if num in d and abs(d[num]-i) <= k:
                return True
            else:
                d[num] = i

        return False


from fastapi import FastAPI, Depends, status, HTTPException, Form, UploadFile, File
from sqlalchemy.orm import Session
from devmodule.repository.oauth2 import get_current_user
from devmodule.core import schemas, database, models
from sqlalchemy import event
import os
import re
from devmodule.drive import driveDB

# Get all the developers profiles
def view_all_profiles(db):
    '''
    This function is implemented to get all the profiles in db that exist.
    '''
    all_profiles = db.query(models.Profile).all()
    active_profiles = all_active_profiles(all_profiles)
    return active_profiles

# To get the all active users only
def all_active_profiles(all_profiles):
    active_profiles = []
    for profile in all_profiles:
        if profile.is_active:
            active_profiles.append(profile)

    return active_profiles

# Search the users for profiles
def search_profiles(query:str, db:Session =Depends(database.get_db)):
    all_profiles = db.query(models.Profile).filter(
        models.Profile.first_name.contains(query) |
        models.Profile.last_name.contains(query) |
        models.Profile.short_intro.contains(query)
     ).all()

    if all_profiles:
        return all_active_profiles(all_profiles)
    else:
        skill_filter = db.query(models.Skill).filter(
        models.Skill.name.contains(query)).all()
        for skill in skill_filter:
            all_profiles.append(skill.owner)
        all_profiles = all_active_profiles(all_profiles)
    return all_profiles

# To get the single profile using the id parameter
def view_single_profile(id:int, db:Session =Depends(database.get_db)):
    user_profile = db.query(models.Profile).filter(models.Profile.id == id).first()
    if not user_profile:
              raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='No such profile exist')
    return user_profile

#To create basic info of profile
def create_profile(username,first_name,last_name, db:Session =Depends(database.get_db)):
    user = db.query(models.User).filter(models.User.email == username).first()
    create_profile = models.Profile(
        first_name = first_name,
        last_name = last_name,
        username = username,
        is_active=True,
        user_id= user.id
    )
    db.add(create_profile)
    db.commit()
    db.refresh(create_profile)
    return True

#Update profile for user
def update_profile(
    first_name,
    last_name,
    profile_image,
    location,
    short_intro,
    bio,
    social_github,
    social_twitter,
    social_linkedin,
    social_youtube,
    social_website,
    db:Session =Depends(database.get_db),
    current_user: models.User = Depends(get_current_user)):
    user_profile = db.query(models.Profile).filter(models.Profile.id == current_user.id)
    try:
        # user = db.query(models.User).filter(models.User.id == user_profile.first().user_id)
        if not user_profile.first():
                raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail='No such profile exist')
        f = open(os.path.realpath(os.curdir)+'/temp/profile_images/'+profile_image.filename, 'wb')
        f.write(profile_image.file.read())
        f.close()
        page = 'profile'
        profile_img_id = driveDB.upload_file(profile_image.filename,os.path.realpath(os.curdir)+'/temp/profile_images/'+profile_image.filename, page)
        weburl = driveDB.get_file_with_id(profile_img_id).get('webContentLink')
        profileObj = db.query(models.Profile).filter(models.Profile.id == current_user.id).first()
        if profileObj.profile_image:
            prev_image_id = re.search('=(.*?)&', profileObj.profile_image).group(1)
            delete_image(prev_image_id)
        user_profile.update({
            'first_name':first_name,
            'last_name':last_name,
            'profile_image':weburl,
            'location':location,
            'short_intro':short_intro,
            'bio':bio,
            'social_github':social_github,
            'social_twitter':social_twitter,
            'social_linkedin':social_linkedin,
            'social_youtube':social_youtube,
            'social_website':social_website,
        })
        db.commit()
        os.remove(os.path.realpath(os.curdir) + '/temp/profile_images/' + profile_image.filename)
        response = "Profile updated"
        return response
    except:
        response = "Something went wrong"
        return response

# Specific function to delete the image
def delete_image(id:str):
    return driveDB.delete_file(id)

# To Deactivate the user profile
def deactivate_user(db:Session = Depends(database.get_db), current_user: models.User = Depends(get_current_user)):
    is_active1 = {
        'is_active': False
    }
    user_profile = db.query(models.Profile).filter(models.Profile.user_id ==  current_user.id)
    if not user_profile.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='No such user exist')
    user_profile.update(is_active1)
    db.commit()
    return 'User Deleted'


from c11.electric_vehicle import ElectricVehicle

if __name__ == '__main__':
    # v = Vehicle("mazda", "3", "white", 1999)
    # print(v.get_manufacturer())
    # print(v._model)
    # print(v.__dict__)
    # print(v._Vehicle__manufacturer)
    ev = ElectricVehicle('tesla', 'model 3', 'white', 2022, 103, 4)
    ev.drive(100)
    print("bye")


import os
import numpy as np
import torch as tc
from learning import *
from uncertainty import *
from uncertainty.pac_ps import PredSetConstructorFederated
from .util import *

def compute_k(n, e, d):
    r = 0.0
    s = 0.0

    for h in range(n + 1):
        if h == 0:
            r = n * np.log(1.0 - e)
        else:
            r += np.log(n - h + 1) - np.log(h) + np.log(e) - np.log(1.0 - e)
        s += np.exp(r)

        if s > d:
            if h == 0:
                raise Exception("Compute k: s > d when h is 0")
            else:
                return h - 1
    return n

class PredSetConstructor_Federated(PredSetConstructorFederated):
    def __init__(self, model, params=None, name_postfix=None, save_logits=False):
        super().__init__(model=model, params=params, name_postfix=name_postfix)
        self.model_inf = model
        self.save_logits = save_logits

    def train(self, ld, params=None):
        if params is None:
            params = self.params

        # Count number of validation examples
        self.n = 0
        for participant_ld in ld:
            for _, y in participant_ld:
                self.n += len(y)

        self.eps = params.eps
        self.delta = params.delta
        if self.name_postfix is None:
            self.name_postfix = ''
        self.name_postfix = self.name_postfix + f'_n_{self.n}_eps_{self.eps:e}_delta_{self.delta:e}'

        # Solve for k*
        print("Computing k")
        k = compute_k(self.n, self.eps, self.delta)

        print("Precomputing predicted logits...")
        nlls = tc.Tensor([]).to(self.device)
        logits = tc.Tensor([]).to(self.device)
        labels = tc.Tensor([]).to(self.device)
        for participant_ld in ld:
            participant_logits = tc.Tensor([]).to(self.device)
            participant_nlls = tc.Tensor([]).to(self.device)
            participant_labels = tc.Tensor([]).to(self.device)
            for x, y in participant_ld:
                x = x.to(self.device)
                y = y.to(self.device)
                with tc.no_grad():
                    x_logits = self.model_inf.forward(x)['ph']
                    x_nll = - x_logits.log()
                participant_logits = tc.cat((participant_logits, x_logits), dim=0)
                participant_nlls = tc.cat((participant_nlls, x_nll), dim=0)
                participant_labels = tc.cat((participant_labels, y), dim=0)

            logits = tc.cat((logits, participant_logits), dim=0)
            nlls = tc.cat((nlls, participant_nlls), dim=0)
            labels = tc.cat((labels, participant_labels), dim=0).type(tc.int64)
        # print(f" NLLs shape = {nlls.shape}")
        # print(f" labels shape = {labels.shape}")
        # neg_log_likelihoods = (num_val, 62)
        # labels = (num_val,)

        # Debugging - save logits of labels
        if self.save_logits:
            logits_y = np.array([])
            for i in range(len(labels)):
                val = logits[i][labels[i]].item()
                logits_y = np.append(logits_y, val)
            print(logits_y.shape)
            path_npy = os.path.join("/home/aheyler/snapshots/latest_femnist_ps_v4_nov1", "logits_val_arr.npy")
            print(path_npy)
            np.save(path_npy, logits_y)

        else:
            print(f"\n## Training dataset results for n={len(labels)}, eps={self.eps}, delta={self.delta}, K={k}:")

            # Binary search on T between 0 to 1
            window_size = 1
            high = 1
            low = 0
            while window_size > 1e-5:
                # prob_thresh_T \in [0, 1]
                if low == 0 and high == 1:
                    prob_thresh_T = 0.5
                else:
                    prob_thresh_T = (low + high) / 2

                # compute corresponding T where the prob_thresh_T = e**(-T)
                T = - math.log(prob_thresh_T)

                # Count errors
                set = nlls <= T
                membership = set.gather(1, labels.view(-1, 1)).squeeze(1)
                errs = sum(membership == False)

                # Evaluate sizes
                sizes = set.sum(1).float()

                min = tc.min(sizes).item()
                q1 = tc.quantile(sizes, 0.25, interpolation='nearest').item()
                med = tc.median(sizes).item()
                q3 = tc.quantile(sizes, 0.75, interpolation='nearest').item()
                max = tc.max(sizes).item()
                mean = tc.mean(sizes).item()
                # else:
                #     # print(f"membership type = {type(membership)}")
                #     # print(f"sizes = {sizes}")
                #     # print(f"sizes type = {type(sizes)}")
                #     sizes = sizes.detach().cpu().numpy()
                #     membership = membership.detach().cpu().numpy()
                #     print(f"membership = {membership}")
                #     correct_sizes = sizes[membership]
                #     np.save("correct_sizes.npy", correct_sizes)

                #     correct_sizes = tc.tensor(correct_sizes)
                #     not_membership = 1 - membership
                #     incorrect_sizes = sizes[not_membership]
                #     np.save("incorrect_sizes.npy", incorrect_sizes)
                #     incorrect_sizes = tc.tensor(incorrect_sizes)

                #     print(f"correct len = {len(correct_sizes)}")
                #     print(f"incorrect len = {len(incorrect_sizes)}")

                #     correct_min = tc.min(correct_sizes).item()
                #     correct_q1 = tc.quantile(correct_sizes, 0.25, interpolation='nearest').item()
                #     correct_med = tc.median(correct_sizes).item()
                #     correct_q3 = tc.quantile(correct_sizes, 0.75, interpolation='nearest').item()
                #     correct_max = tc.max(correct_sizes).item()
                #     correct_mean = tc.mean(correct_sizes).item()

                #     incorrect_min = tc.min(incorrect_sizes).item()
                #     incorrect_q1 = tc.quantile(incorrect_sizes, 0.25, interpolation='nearest').item()
                #     incorrect_med = tc.median(incorrect_sizes).item()
                #     incorrect_q3 = tc.quantile(incorrect_sizes, 0.75, interpolation='nearest').item()
                #     incorrect_max = tc.max(incorrect_sizes).item()
                #     incorrect_mean = tc.mean(incorrect_sizes).item()

                # Update window - flipped
                if errs == k: # Exact threshold found --> keep this T
                    window_size = 0
                elif errs > k: # Too many errors --> search below prob_thresh_T
                    high = prob_thresh_T
                    window_size = high - low
                else: # Too few errors --> search above prob_thresh_T
                    low = prob_thresh_T
                    window_size = high - low
                print(f"Probability threshold={prob_thresh_T:.4f}, T={T:.4f}, Error rate = {errs/len(labels):.4f}, Errors = {errs}, Size = {[min, q1, med, q3, max]}, Mean size = {mean:.4f}")
                # else:
                #     print(f"Probability threshold={prob_thresh_T:.4f}, T={T:.4f}, Error rate = {errs/len(labels):.4f}, Errors = {errs}," +
                #           f"Correct Size = {[correct_min, correct_q1, correct_med, correct_q3, correct_max]}, Mean correct size = {correct_mean:.4f}," +
                #           f"Inorrect Size = {[incorrect_min, incorrect_q1, incorrect_med, incorrect_q3, incorrect_max]}, Mean incorrect size = {incorrect_mean:.4f}")

            self.T_opt = T
            self.prob_thresh_opt = prob_thresh_T

        return True

    def test(self, ld, params=None):
        logits = tc.Tensor([]).to(self.device)
        labels = tc.Tensor([]).to(self.device)
        for participant_ld in ld:
            participant_logits = tc.Tensor([]).to(self.device)
            participant_labels = tc.Tensor([]).to(self.device)
            for x, y in participant_ld:
                x = x.to(self.device)
                y = y.to(self.device)
                with tc.no_grad():
                    x_logits = self.model_inf.forward(x)['ph']
                participant_logits = tc.cat((participant_logits, x_logits), dim=0)
                participant_labels = tc.cat((participant_labels, y), dim=0)

            logits = tc.cat((logits, participant_logits), dim=0)
            labels = tc.cat((labels, participant_labels), dim=0).type(tc.int64)
        # print(f" logits shape = {logits.shape}")
        # print(f" labels shape = {labels.shape}")

        if self.save_logits:
            logits_y = np.array([])
            for i in range(len(labels)):
                val = logits[i][labels[i]].item()
                logits_y = np.append(logits_y, val)
            print(logits_y.shape)
            path_npy = os.path.join("/home/aheyler/snapshots/latest_femnist_ps_v4_nov1", "logits_test_arr.npy")
            print(path_npy)
            np.save(path_npy, logits_y)

        else:
            set = logits > self.prob_thresh_opt
            membership = set.gather(1, labels.view(-1, 1)).squeeze(1)
            errs = sum(membership == False)

            # Evaluate sizes
            sizes = set.sum(1).float()
            min = tc.min(sizes).item()
            q1 = tc.quantile(sizes, 0.25, interpolation='nearest').item()
            med = tc.median(sizes).item()
            q3 = tc.quantile(sizes, 0.75, interpolation='nearest').item()
            max = tc.max(sizes).item()
            mean = tc.mean(sizes).item()

            membership_arr = membership.detach().cpu().numpy()
            np.save("membership.npy", membership_arr)
            sizes_arr = sizes.detach().cpu().numpy()
            np.save("sizes.npy", sizes_arr)
            set_arr = set.detach().cpu().numpy()
            np.save("set.npy", set_arr)
            labels_arr = labels.detach().cpu().numpy()
            np.save("labels.npy", labels_arr)

            print(f"\n## Test dataset results for n={len(labels)}, eps={self.eps}, delta={self.delta}:")
            print(f"Probability threshold={self.prob_thresh_opt:.4f}, T={self.T_opt:.4f}, Error rate = {errs/len(labels):.4f}, Errors = {errs}, Size = {[min, q1, med, q3, max]}, Mean size = {mean:.4f}")

        return True

# non-log space k computation
# k = 0
# binom = math.factorial(num_val) / (math.factorial(num_val - k) * math.factorial(k))
# lhs = binom * (eps)**k * (1-eps)**(num_val - k)
# while lhs < delta:
#     k += 1
#     binom = math.factorial(num_val) / (math.factorial(num_val - k) * math.factorial(k))
#     lhs += binom * (eps)**k * (1-eps)**(num_val - k)
# k = max(0, k-1) # get last k before exceeding delta


import os
from fabric.api import run, sudo, env, task, put, cd

import fabtools.python
import fabtools.rpm
import fabtools.files

env.forward_agent = True
env.user = 'admin'

TMP_VENV_DIR = '/tmp/copyIndex'
SRC_DIR = os.path.join(TMP_VENV_DIR, 'src')
REMOTE_PY = os.path.join(TMP_VENV_DIR, 'bin', 'python')

HERE = os.path.dirname(__file__)

@task
def copyIndex(from_es, from_idx, to_idx, to_es='', force_copy='0'):
    """Copy an elasticsearch index

    Allows to copy an index into a new index or other existing index.
    The copy can be inside an instance or between different instances.

    If a remote host is specified the copy code is executed on the remote
    machine.

    Arguments:
        from_es: origin elasticsearch host name
        from_idx: origin index name
        to_idx: target index name
        to_es: target elasticsearch host name
        force_copy: copy to target even if the target index exists
    """
    if env.host is not None:
        # run the code on the remote machine
        RemoteIndexCopy(from_es, from_idx, to_idx, to_es, force_copy)()
    else:
        LocalIndexCopy(from_es, from_idx, to_idx, to_es, force_copy)()

class IndexCopyBase(object):

    def __init__(self, from_es, from_idx, to_idx, to_es, force_copy):
        self.from_es = from_es
        self.from_idx = from_idx
        self.to_idx = to_idx
        self.to_es = to_es
        self.force_copy = force_copy

    def __call__(self):
        raise NotImplementedError

class LocalIndexCopy(IndexCopyBase):

    def __call__(self):
        from .helpers import es_copyindex
        es_copyindex.copyIndex(self.from_es,
                               self.from_idx,
                               self.to_idx,
                               self.to_es,
                               self.force_copy,
                              )

class RemoteIndexCopy(IndexCopyBase):

    REMOTE_TMP = 'tmp/iris'

    def __call__(self):
        self.setupRemote()
        cmd = ['sudo',
               'docker',
               'run',
               '-ti',
               '--rm',
               'iris-migration',
               'python',
               'es_copyindex.py',
               self.from_es,
               self.from_idx,
               self.to_idx,
               self.to_es,
               self.force_copy
              ]
        cmd = ' '.join(['"%s"' % c for c in cmd])
        run(cmd)
        self.shutdownRemote()

    def setupRemote(self):
        run('mkdir -p ' + self.REMOTE_TMP)
        put('fabfile/helpers/es_copyindex.py', self.REMOTE_TMP)
        put('fabfile/Dockerfile', self.REMOTE_TMP)
        with cd(os.path.join(self.REMOTE_TMP)):
            run('sudo docker build -t iris-migration .')

    def shutdownRemote(self):
        run('rm -rf ' + self.REMOTE_TMP)


import numpy as np
import pickle
import sys
import os
import json
from rouge import Rouge
from pythonrouge.pythonrouge import Pythonrouge
import matplotlib.pyplot as plt

from all_feat import _length_indicator

topic ='War Crimes and Criminals'
input_path = "/home/ml/jliu164/code/contentHMM_input/"
_model_path = "/home/ml/jliu164/code/contentHMM_tagger/contents/"
save_path = "../filter_results/topic2files(content).pkl"
data_path = "../data/model_input/"
fail_path = '../contentHMM_input/fail/'
cand_rec_path = data_path+"FFNN/cand_record/"

EOD = "*EOD*" # predict the end
START_SENT = "**START_SENT**"
SOD = "**START_DOC**"
END_SENT = "**END_SENT**"

N_CAND = 10

if sys.version_info[0] <3:
	from corenlpy import AnnotatedText as A
	ds=2

	files_ = pickle.load(open(save_path))[topic]
	with open(fail_path+topic+"_Failed.txt") as f:
		paths = f.readlines()
		failed_l = [p.split("/")[-1].split(".")[0] for p in paths]
		failed = set(failed_l)
	files = [fs for fs in files_[:-1] if fs.split('/')[-1].split(".")[0] not in failed]
	files = files[int(np.around(0.1*len(files))):-int(np.around(0.1*len(files)))] if ds==1 else files[int(-np.around(0.1*len(files))):]
	p_selected = data_path+"FFNN/selected_sentences"+str(ds)+".json"

	with open(p_selected,'r') as f:
		selected_tot = json.load(f)

	# print(files[-6])
	# print(selected_tot[-6])

###############
# separate case #
###############

def acc_(yp,Y,cand_len):
	n_correct = 0
	idx = 0
	for i in range(len(cand_len)):
		yp_ = yp[idx:idx+cand_len[i]]
		Y_ = Y[idx:idx+cand_len[i]]

		if np.argmax(Y_)==np.argmax(yp_):
			n_correct += 1

		idx += cand_len[i]
	return float(n_correct)/len(cand_len)

def accuracy_at_k(yp,Y,cand_len,k):
	### calculate acc@k. For exact match, k=1. Caveat: k <= min(cand_len)
	assert np.sum(cand_len)==len(yp)==len(Y), (len(yp),len(Y),np.sum(cand_len))
	n_correct = 0
	idx = 0
	for i in range(len(cand_len)):
		yp_ = yp[idx:idx+cand_len[i]].ravel()
		Y_ = Y[idx:idx+cand_len[i]].ravel()

		indicies = yp_.argsort()[-k:]

		if np.argmax(Y_) in indicies:
			n_correct += 1
		# print(yp_,Y_)
		# print((indicies),np.argmax(Y_))
		yp_[:] = 0
		yp_[indicies] = 1
		idx += cand_len[i]
	return float(n_correct)/len(cand_len), yp

def accuracy(yp,Y):
	### calculate exact match for 0/1 downsample
	assert len(yp) == len(Y)
	return float(np.sum(yp==Y))/len(Y)

def breakdown(yp,y,cand_len):
	### print a breakdown of performance for predicted scores. compare ability to predict <FOS> and <EOS>
	print("************ Performance breakdown on predicting <First> and <EOS> ***************")
	# eos_scores_first = []
	# eos_scores_true = []
	# first_scores_last = []
	# first_scores_true = []
	eos_correct = 0
	n_eos=0
	fos_correct = 1 if np.argmax(yp[:cand_len[0]])==np.argmax(y[:cand_len[0]]) else 0
	n_fos=1

	idx = 0
	next_fos = False
	for i in range(len(cand_len)):

		yp_ = yp[idx:idx+cand_len[i]].ravel()
		y_ = y[idx:idx+cand_len[i]].ravel()

		## accuracy for EOS
		if np.argmax(y_)==cand_len[i]-1:
			n_eos+=1
			if np.argmax(yp_)==cand_len[i]-1:
				eos_correct +=1
			next_fos = True
			idx += cand_len[i]
			continue

		## accuracy for First
		if next_fos:
			# print("FOS")
			n_fos+=1

			if np.argmax(y_)==np.argmax(yp_):
				fos_correct +=1
			next_fos = False

		idx += cand_len[i]

	print("Accuracy on getting EOS right: %s, accuracy on getting first sentence: %s" %(float(eos_correct)/n_eos,float(fos_correct)/n_fos))
	print(n_eos, n_fos)
	print(eos_correct, fos_correct)

#########################
# EOS evaluation detail #
#########################
def eos_confusion(yp,y,cand_len):
	## build confusion matrix for EOS prediction
	from sklearn.metrics import confusion_matrix

	yp = yp.ravel()
	eos_idx = []
	eos_idx_pred = []
	cand_len_incr =  np.hstack((np.zeros(1), np.add.accumulate(cand_len)))
	idx = 0
	for i in range(len(cand_len)):
		yp_ = yp[idx:idx+cand_len[i]]
		y_ = y[idx:idx+cand_len[i]]
		## index for when should be predicting EOS
		if np.argmax(y_)==cand_len[i]-1:
			eos_idx.append(cand_len_incr[i]+np.argmax(y_))
		## index for when model IS predicting EOS
		if np.argmax(yp_)==cand_len[i]-1:
			eos_idx_pred.append(cand_len_incr[i]+np.argmax(yp_))
		idx += cand_len[i]
	eos_idx = np.array(eos_idx).astype(int)
	eos_idx_pred = np.array(eos_idx_pred).astype(int)

	y_true = np.zeros(y.shape).astype(int)
	y_true[eos_idx] = 1 # only consider EOS
	ypred = np.zeros(yp.shape).astype(int)
	ypred[eos_idx_pred] = 1

	print(confusion_matrix(y_true, ypred,labels=[0,1]))

###############
# Evaluation  extrinsically #
###############
def rouge_score(generated, truth):
	## y_true,yp: a list of sentences, each a list of word tokens. <EOS> excluded
	hyps = []
	for doc in generated:
		hyp = []
		# print("\n")
		for sent in doc:
			# print(sent)
			if sent[0] == SOD:
				hyp.append((" ").join(sent[2:-1]))
			else:
				hyp.append((" ").join(sent[1:-1]))
		hyps.append((" ").join(hyp))
	refs = []
	for doc in truth:
		hyp = []
		for sent in doc:
			if sent[0] == SOD:
				hyp.append((" ").join(sent[2:-1]))
			else:
				hyp.append((" ").join(sent[1:-1]))
		refs.append((" ").join(hyp))
	# rouge = Rouge()
	# scores = rouge.get_scores(hyps,refs,avg=True)

	## Perl version
	ROUGE_path ="/home/ml/jliu164/.local/lib/python3.6/site-packages/pythonrouge/RELEASE-1.5.5/ROUGE-1.5.5.pl"
	data_path = "/home/ml/jliu164/.local/lib/python3.6/site-packages/pythonrouge/RELEASE-1.5.5/data"
	rouge = Pythonrouge(n_gram=2, ROUGE_SU4=True, ROUGE_L=True, stemming=True, stopwords=True, word_level=True, length_limit=True, length=50, use_cf=False, cf=95, scoring_formula="average", resampling=True, samples=1000, favor=True, p=0.5)
	rouge_1 = []
	rouge_2 = []
	rouge_l = []
	rouge_su4 = []
	for hyp,ref in zip(hyps,refs):
		# print(hyp)
		# print(ref)
		setting_file = rouge.setting(files=False, summary=[[hyp]], reference= [[[ref]]])
		result = rouge.eval_rouge(setting_file, recall_only=True, ROUGE_path=ROUGE_path, data_path=data_path)
		# print(result) # {'ROUGE-1': 0.31429, 'ROUGE-2': 0.08824, 'ROUGE-L': 0.22857, 'ROUGE-SU4': 0.12887}
		rouge_1.append(result["ROUGE-1"])
		rouge_2.append(result["ROUGE-2"])
		rouge_l.append(result["ROUGE-L"])
		rouge_su4.append(result["ROUGE-SU4"])
	rouge_1 = np.array(rouge_1)
	rouge_2 = np.array(rouge_2)
	rouge_l = np.array(rouge_l)
	rouge_su4 = np.array(rouge_su4)
	scores = {"rouge_1":np.mean(rouge_1),"rouge_2":np.mean(rouge_2),"rouge_L":np.mean(rouge_l),"rouge_su4":np.mean(rouge_su4)}
	return scores # {"rouge-1": {"f": _, "p": _, "r": _}, "rouge-2" : { ..     }, "rouge-3": { ... }}

def oracle_chance(n_range = np.arange(15), ds_range = range(2,3)):
	### if every time take next 10 candidates, what's the chance of next summary sentence in candidate?
	data_path = "/home/ml/jliu164/code/data/model_input/"
	n_in = 0
	n_all = 0
	for ds in ds_range:
		p_selected = data_path+"FFNN/selected_sentences"+str(ds)+".json"
		with open(p_selected,'r') as f:
			selected_tot = json.load(f) # indices of article sentences selected as summary
		for selected in selected_tot:
			n_all += len(selected) #selected:[0,4,5,13]
			if selected[0] in n_range:
				n_in += 1 # first sentence
			for i in range(len(selected)-1):
				if selected[i+1]-selected[i] in n_range:
					n_in += 1
	print("candidate range = %s, computed over ds range %s, chances of having the correct sentence in candidate set is %s"%(n_range,ds_range,float(n_in)/n_all))
	print("n_all",n_all,"n_in",n_in)

#########################
#  Generate summary intrinsic   #
#########################
def generate_summary_fake(yp, index):
	### yp: predicted y. index: which article to generate summary. ds: 1 if dev set, 2 if test set
	### not truly generating summary: already assuming gold standard summary
	print("file path:", files[index])
	print("selected sentences", selected_tot[index])

	print("yp.shape", yp.shape)
	cand_len = np.load("../data/model_input/FFNN/candidate_length_rdn"+str(ds)+".npy")
	cand_rec = pickle.load(open(cand_rec_path+"rdn_sample"+str(ds)+".pkl","rb"))
	xml = open("/home/rldata/jingyun/nyt_corpus/content_annotated/"+files[index]).read()
	text = A(xml)

	n_cand_set = len(cand_rec[index])
	n_cand = sum([len(s) for s in cand_rec[index]])+len(cand_rec[index])
	print("n_cand_set",n_cand_set, "n_cand",n_cand)
	offset_cand_len = sum([len(s) for s in selected_tot[:index]])+index
	cand_len_ = cand_len[offset_cand_len:offset_cand_len+n_cand_set]
	# print(cand_len_)
	offset_y = sum([len(i) for s in cand_rec[:index] for i in s]) + sum([len(cand_rec[i]) for i in range(index)])
	# print("offset_y",offset_y)
	cand_y = yp[offset_y:offset_y+n_cand]

	print("****** original text:\n")
	print([_pretty_sentence(s) for s in text.sentences])
	print("\n******selecting summary:")
	targets = _generate(cand_y, text.sentences, cand_len_, cand_rec[index])
	print("\n******* Actual summary:")
	print([_pretty_sentence(text.sentences[i]) for i in np.array(selected_tot[index]).astype(int)])
	print("Selected sentences: %s, actual sentences: %s"%(targets,selected_tot[index]))

def _generate(y, source, cand_len, cand_rec):
	### given a source article (list of sentence), predicted y, candidate length each time, sample record, generate a summary with EOS
	idx=0
	# print("cand_len", cand_len)
	# print("cand_rec", cand_rec)
	# print(y)
	targets = []
	for i in range(len(cand_len)):
		c = cand_len[i]
		y_ = y[idx:idx+c]
		target = np.argmax(y_)

		if target == c-1:
			print("<EOS>")
			break
		else:
			yp = source[cand_rec[i][target]]
			targets.append(cand_rec[i][target])
			# print("i",i,"target",target,"index in source",cand_rec[i][target])
			print(_pretty_sentence(yp))

		idx += c
	return targets

def _pretty_sentence(sent):
	## return a readable sentence from AnnotatedText sentence. sent: one sentence
	ll = [i['word'] for i in sent['tokens']]
	return (" ").join(ll)

if __name__ == '__main__':

	# oracle_chance() # 0.64
	# exit(0)

	dp = "(1030, 727)"
	yp = np.load("pred/yp_ffnn_2step/"+dp+".npy")
	# generate_summary_fake(yp,14)

	Y = np.load("../data/model_input/FFNN/Y_rdn1.npy")
	cl = np.load("../data/model_input/FFNN/candidate_length_rdn1.npy")
	sep = int(0.1*len(cl))
	cl_dev = cl[:sep]
	Y = Y[:np.sum(cl_dev)]
	print(dp)
	# breakdown(yp,Y,cl_dev)
	eos_confusion(yp,Y,cl_dev)


from django.conf.urls import url
from . import views
app_name = 'users'

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^signin$', views.sign_in, name='sign_in'),
    url(r'^register$', views.register, name='register'),
    url(r'^registerTest$', views.register_test, name='register_test'),
    url(r'^signIn_test$', views.signIn_test, name='signIn_test'),
]


#!/opt/anaconda3/bin/python

import math
import argparse

from Butterfly import ButterflyNet

def check_args(args):
    '''
    Check if the input args from cmd line is legal
    '''
    # check n_stage & type_list & pfx_list
    assert args.n_stage == len(args.type_list), "Number of stages does not match the length of switch nodes type list"
    if args.pfx_list is not None:
        assert args.n_stage == len(args.pfx_list), "Number of stages does not match the length of switch nodes prefix name list"

    # check switch nodes type_list
    for _ in args.type_list:
        assert _ == 2 or _ == 4, "Invalid value found in switch nodes type list, allowed values are 2 or 4"

    # check type_list & n_port
    product = math.prod(args.type_list)
    assert args.n_port == product, "Number of i/o ports derived from type_list does not match input argument n_port"
    assert args.n_port <= 256, "Invalid argument: n_port, supported number of ports should be no greater than 256"

    # check monitor definition
    assert args.monitor_def[0] >= 1280 and args.monitor_def[0] <= 3840, "Invalid monitor width, allowed range is 1280 to 3840"
    assert args.monitor_def[1] >= 720 and args.monitor_def[1] <= 2160, "Invalid monitor height, allowed range is 720 to 2160"

    return

def main():
    parser = argparse.ArgumentParser(description='Automatically Generating Network Topology for Hi-GP')
    parser.add_argument('-ns', '--n_stage', type=int, required=True, help='number of stages/ranks in the interconnection network')
    parser.add_argument('-np', '--n_port', type=int, required=True, help='number of i/o ports of the interconnection network, power of two')
    parser.add_argument('-tl', '--type_list', nargs='+', type=int, required=True, help='type list of switch nodes in stage ascending order')
    parser.add_argument('-df', '--monitor_def', nargs=2, type=int, required=True, help='definition (Width Height in pixels) of used monitor which will determine the canvas size etc, e.g. 1920 1080')

    parser.add_argument('--pfx_list', nargs='+', type=str, help='prefix name of the switch nodes in stage ascending order')
    parser.add_argument('--tcl_fn', type=str, help='output tcl command file name for automatic connection')

    args = parser.parse_args()
    check_args(args)

    bfNet = ButterflyNet(
        n_stage=args.n_stage,
        n_port=args.n_port,
        type_list=args.type_list,
        monitor_def=args.monitor_def,
        pfx_list=args.pfx_list,
        tcl_fn=args.tcl_fn
        )

    # bfNet.save_network_image()
    bfNet.gen_connect_tcl_as_file()

if __name__ == '__main__':
    main()


import cv2

#leemos imagen
img = cv2.imread('..\\banco_img\\messi.jpg', cv2.IMREAD_COLOR)
resize_img = cv2.resize(img, (300,300))
resize_img2 = cv2.resize(img, (0,0), fx=0.2, fy=0.2)    #30% en 'X' y 30% en 'Y'

#mostramos imagen real
cv2.imshow("Messi 1: ", img)
cv2.waitKey(0)
#mostramos imagen alterada 1
cv2.imshow("Messi 2: ", resize_img)
cv2.waitKey(0)
#mostramos imagen alterada 2
cv2.imshow("Messi 3: ", resize_img2)
cv2.waitKey(0)

#cortamos un "area de interes"
cropped_img = img[50:500, 100:450]     #los pixeles de la imagen funcionan como lista
cv2.imshow("Messi 4: ", cropped_img)
cv2.waitKey(0)

#rotamos la imagen 90 grados en sentido horario y antihorario
cropped_img1 = cv2.rotate(cropped_img, cv2.ROTATE_90_CLOCKWISE)
cropped_img2 = cv2.rotate(cropped_img, cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imshow("Messi 5: ", cropped_img1)
cv2.imshow("Messi 6: ", cropped_img2)
cv2.waitKey(0)


from datetime import datetime, timezone
import sys

from JenkinsChangeLogs import JenkinsChangeLogs

if __name__ == '__main__':
    jclo = JenkinsChangeLogs()
    for arg in sys.argv[1:-1]:
        jclo.append(arg)
    print(F'Changesets Loaded: {len(jclo)}')

    print(F'Stats:')

    for ename, x in jclo.get_summary(order = True).items():
        print('  ', ename, x)

    for ename, x in jclo.get_summary('author', order = True).items():
        print('  ', ename, x)

    htmldoc = jclo.gen_html()
    open(sys.argv[-1], 'w').write(htmldoc)


try:
    from util import Record, identity, comp, partial
    from util_tf import tf, scope, variable, placeholder, Linear, Affine, Normalize, spread_image
except ImportError:
    from src.util import Record, identity, comp, partial
    from src.util_tf import tf, scope, variable, placeholder, Linear, Affine, Normalize, spread_image
import math

def NLLNormal(pred, target, scale=1e-6):
    tmp = tf.square(pred - target) * -(1.0 / (2.0 * 1)) \
        - 0.5 * tf.log(2 * tf.constant(math.pi))
    return tmp * scale

class Enc(Record):

    def __init__(self, dim_x, dim_d, dim_btlnk, name= 'encoder'):
        self.name = name
        with scope(name):
            self.lin = Linear(dim_d, dim_x, name= 'lin')
            self.nrm = Normalize(    dim_d, name= 'nrm')
            self.l_mu = Linear(dim_btlnk, dim_d, name= 'mu')
            self.l_lv = Linear(dim_btlnk, dim_d, name= 'lv')
    def __call__(self, x, name= None):
        with scope(name or self.name):
            hl = self.nrm(tf.nn.elu(self.lin(x)))
            mu = self.l_mu(hl)
            lv = self.l_lv(hl)
            z = mu + tf.exp(0.5 * lv) * tf.random_normal(shape=tf.shape(lv))
            return z, mu, lv, hl

class Gen(Record):
    def __init__(self, dim_x, dim_btlnk, name="generator"):
        self.name = name
        with scope(name):
            self.lex = Linear(dim_x, dim_btlnk, name="lex")

    def __call__(self, x, name=None):
        with scope(name or self.name):
            #return tf.clip_by_value(self.lex(x), 0.0, 1.0)
            return tf.nn.sigmoid(self.lex(x))

class Dis(Record):

    def __init__(self, dim_x, dim_d, name= 'discriminator'):
        self.name = name
        with scope(name):
            dim_d *=2
            self.lin = Linear(dim_d, dim_x, name= 'lin')
            self.nrm = Normalize(    dim_d, name= 'nrm')
            self.lin2 = Linear(dim_d, dim_d, name= 'lin2')
            self.nrm2 = Normalize(    dim_d, name= 'nrm2')
            self.lex = Linear(1, dim_d, name= 'lex')

    def __call__(self, x, name= None):
        with scope(name or self.name):
            x = self.nrm(tf.nn.leaky_relu(self.lin(x)))
            #x = self.nrm2(tf.nn.leaky_relu(self.lin2(x)))
            #return tf.clip_by_value(self.lex(x), 0.0, 1.0), x
            return self.lex(x), x

class VAEGAN(Record):

    @staticmethod
    def new(dim_x, dim_btlnk, dim_d, dim_noise, accelerate):
        return VAEGAN(dim_x= dim_x
                      , dim_btlnk=dim_btlnk
                      , dim_noise=dim_noise
                      , enc = Enc(dim_x, dim_d, dim_btlnk)
                      , gen= Gen(dim_x, dim_btlnk)
                      , dis= Dis(dim_x, dim_d)
                      , accelerate=accelerate)

    def build(self, x, y, z, loss_type):
        d_scale_factor = tf.constant(0.)#tf.constant(0.25)
        g_scale_factor = tf.constant(0.)#tf.constant(1 - 0.75/2)
        with scope("x"):
            x = placeholder(tf.float32, [None, self.dim_x], x, "x")
        with scope("y"):
            y = placeholder(tf.float32, [None], y, "y")
        with scope("z"):
            z = placeholder(tf.float32, [None, self.dim_noise], z, "z")

        zx, mu, lv, hl_e = self.enc(x)

        gzx = self.gen(zx)
        #gz = self.gen(z)

        dx, hl_dx = self.dis(x)
        dgzx, hl_dgzx = self.dis(gzx)
        #dgz, hl_dgz = self.dis(gz)

        with tf.variable_scope("step"):
            step = tf.train.get_or_create_global_step()
            rate = self.accelerate * tf.to_float(step)
            rate_anneal = tf.tanh(rate)

        with scope("loss"):
            dx_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(dx)-d_scale_factor, logits=dx))
            dgzx_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(dgzx), logits=dgzx))
            #dgz_loss =  tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(dgz), logits=dgz))
            d_loss = dx_loss + dgzx_loss #+ dgz_loss

            kl_loss = tf.reduce_mean(0.5 * (tf.square(mu) + tf.exp(lv) - lv - 1.0))

            gzx_loss = tf.reduce_mean(
                tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(dgzx) - g_scale_factor, logits=dgzx))

            if loss_type=="xtrpy":
                epsilon = 1e-10
                ftr_loss = tf.reduce_mean(-tf.reduce_sum(x * tf.log(epsilon+gzx) +
                                                         (1-x) * tf.log(epsilon+1-gzx),  axis=1))
                g_loss = gzx_loss/10 + ftr_loss/5 + kl_loss*rate_anneal

            else:
                ftr_loss = tf.reduce_mean(tf.abs(x-gzx))
                g_loss = gzx_loss/2 + ftr_loss*10 + kl_loss*rate_anneal

        with scope("AUC"):
            _, auc_gzx = tf.metrics.auc(y, tf.reduce_mean((x-gzx)**2, axis=1))
            _, auc_dx = tf.metrics.auc(y, tf.nn.sigmoid(dx))
            _, auc_dgzx = tf.metrics.auc(y, tf.nn.sigmoid(dgzx))

        g_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="generator")
        g_vars.append(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="encoder"))
        print(g_vars)
        d_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="discriminator")
        print(d_vars)

        with scope('train_step'):
            #optimizer = tf.train.RMSPropOptimizer()
            optimizer = tf.train.AdamOptimizer()
            d_step = optimizer.minimize(d_loss, step, var_list=d_vars)
            g_step = optimizer.minimize(g_loss, step, var_list=g_vars)

        return VAEGAN(self
                      , step=step
                      , x=x
                      , y=y
                      , z=z
                      , zx=zx
                      , mu=mu
                      , lv=lv
                      , m=tf.reduce_mean(mu)
                      , l=tf.reduce_mean(lv)
                      #, gz=gz
                      , gzx=gzx
                      , auc_gzx=auc_gzx
                      , auc_dx=auc_dx
                      , auc_dgzx=auc_dgzx
                      , g_step=g_step
                      , d_step=d_step
                      , g_loss=g_loss
                      , d_loss=d_loss
                      #,gz_loss=gz_loss
                      ,gzx_loss=gzx_loss
                      , ftr_loss=ftr_loss
                      ,kl_loss=kl_loss
                      , dx_loss=dx_loss
                      #, dgz_loss=dgz_loss
                      , dgzx_loss=dgzx_loss)


"""
Person class.
"""
import filters
from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise
import numpy as np

class Person:

    def __init__(self, det_num, x_min, y_min, x_max, y_max, score, det_type):
        self.track_num = -1
        self.id = -1
        self.det_num = det_num
        self.det_type = det_type
        self.ped_det_count = 0
        self.mtb_det_count = 0
        self.x_min = x_min
        self.y_min = y_min
        self.x_max = x_max
        self.y_max = y_max

        self.p_detect = []
        self.p_detect.append([x_min + (x_max - x_min) / 2, y_min + (y_max - y_min) / 2])

        self.km = KalmanFilter(dim_x=4, dim_z=2)
        # self.km.x = np.array([self.p_detect[-1][0]], [self.p_detect[-1][1]], [0.], [0.])  # initial state (location and velocity)

        self.km.x = np.array(
            [self.p_detect[-1][0], self.p_detect[-1][1], 0., 0.])  # initial state (location and velocity)

        self.km.F = np.array(
            [[1., 0., 1., 0.], [0., 1., 0., 1.], [0., 0., 1., 0.], [0., 0., 0., 1.], ])  # state transition matrix
        # self.km.F = np.array([[1., 0.], [0., 1.]])  # state transition matrix

        # self.km.H = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])  # Measurement function
        self.km.H = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.]])  # Measurement function

        self.km.P *= 1000.  # covariance matrix
        self.km.R = 5  # state uncertainty
        dt = 0.01
        # self.km.Q = Q_discrete_white_noise(2, dt, .1)  # process uncertainty

        self.p_predict = []
        #print "nu1"
        #self.km_predict()
        #self.km_get_prediction()
        self.p_predict.append(self.p_detect[-1])

        self.score = []
        self.score.append(score)

        self.track_id = -1
        self.skipped_frames = 0
        self.remove_track = False
        self.first_frame = -1

    # Correct coordiante outside of frame
    #def correct_point(coor):

    def km_predict(self):
        self.km.predict()

    def km_get_prediction(self):
        vector = [self.km.x[0], self.km.x[1]]
        self.p_predict.append(vector)
        #print self.p_predict
        #print len(self.p_predict)

    def km_update(self, center):
        #vector = []
        #vector.append(center[0])
        #vector.append(center[1])
        #vector.append(0.2)
        #vector.append(0.1)
        vector = [center[0], center[1]]
        #self.km.update(np.array(vector))
        self.km.update(np.transpose(vector))


def main():
    import csv
    import matplotlib.pyplot as plt
    f1=open('seoul.csv','r',encoding='ANSI')
    data=csv.reader(f1,delimiter=',')
    header=next(data)
    X=[]
    seoul=[]
    for row in data:
        #print(row)
        if row[2]!='':
            seoul.append(float(row[2]))
            X.append(row[0])
    f1.close()

    f2=open('all.csv','r',encoding='ANSI')
    data2=csv.reader(f2,delimiter=',')
    header2=next(data2)
    all=[]
    for row2 in data2:
        #print(row2)
        if row2[2]!='':
            all.append(float(row2[2]))
    f2.close()

    f3=open('daejeon.csv','r',encoding='ANSI')
    data3=csv.reader(f3,delimiter=',')
    header3=next(data3)
    daejeon=[]

    for row3 in data3:
        #print(row3)
        if row3[2]!='':
            daejeon.append(float(row3[2]))
    f3.close()

    f4=open('busan.csv','r',encoding='ANSI')
    data4=csv.reader(f4,delimiter=',')
    header4=next(data4)
    busan=[]
    for row4 in data4:
        #print(row4)
        if row4[2]!='':
            busan.append(float(row4[2]))
    f4.close()

    f5=open('jeju.csv','r',encoding='ANSI')
    data5=csv.reader(f5,delimiter=',')
    header5=next(data5)
    jeju=[]
    for row5 in data5:
        #print(row5)
        if row3[2]!='':
            jeju.append(float(row5[2]))
    f5.close()

    plt.title('Monthly Average Temperature In Seoul,Busan,Daejeon,Jeju,Nation in 2022')
    plt.plot(X,seoul,label='seoul',marker='s')
    plt.plot(X,all,label='all',marker='s')
    plt.plot(X,daejeon,label='daejeon',marker='s')
    plt.plot(X,busan,label='busan',marker='s')
    plt.plot(X,jeju,label='jeju',marker='s')
    plt.xlabel('Months in 2022')
    plt.ylabel('Monthly Average Temperature')
    plt.legend()
    plt.show()

if __name__ == '__main__':
    main()


from sys import argv
import math as m

import numpy as np

# -----------------------------------------------------------------------------
def arg_parse():
    if len(argv) == 3:
        script, params_file, points_file = argv
        R, T, f, d, ic, jc = read_params(params_file)
        points_vector = read_points(points_file)
    else:
        print("Invalid Argument(s).")
        print("USAGE: {0} <params-file> <points-file>".format(argv[0]))
        exit()

    return points_vector, R, T, f, d, ic, jc

# -----------------------------------------------------------------------------
def read_params(filename):
    file = open(filename, "r")
    if file.mode == "r":
        lines = file.readlines()
        R = lines[0].split()
        T = lines[1].split()
        f, d, ic, jc = lines[2].split()
    else:
        print("open() failed")
        exit()

    # convert to flaots and convert rotations to radians
    R = np.array([float(i)*m.pi/180. for i in R])
    T = np.array([[float(i) for i in T]])

    return R, T, float(f), float(d), float(ic), float(jc)

# -----------------------------------------------------------------------------
def read_points(filename):
    points = np.loadtxt(filename)
    return points

# -----------------------------------------------------------------------------
def get_camera_matrix(R, T, f, d, ic, jc):

    # rotations in each direction
    Rx = np.array([[1.,           0.,            0.],
                   [0.,  m.cos(R[0]),  -m.sin(R[0])],
                   [0.,  m.sin(R[0]),   m.cos(R[0])]])

    Ry = np.array([[ m.cos(R[1]),  0.,  m.sin(R[1])],
                   [          0.,  1.,           0.],
                   [-m.sin(R[1]),  0.,  m.cos(R[1])]])

    Rz = np.array([[m.cos(R[2]),  -m.sin(R[2]),  0.],
                   [m.sin(R[2]),   m.cos(R[2]),  0.],
                   [         0.,            0.,  1.]])

    # rotation matrix
    Rot = Rx @ Ry @ Rz

    # pixels are square of size 'd' microns - convert to millimeters
    sx = f/(d * 1e-3)
    sy = f/(d * 1e-3)
    K = np.array([[sx,  0.,  ic],
                  [0.,  sy,  jc],
                  [0.,  0.,  1.]])

    # concatenate rotation and translation
    Rt = np.hstack((Rot.T, -Rot.T @ T.T))

    # multiply to form camera matrix
    M = K @ Rt

    return M

# -----------------------------------------------------------------------------
def project_points(points, M, ic, jc):
    visible = []
    hidden = []

    print("Projections:")
    for i,pt in enumerate(points):
        print("{0}: {1:.1f} {2:.1f} {3:.1f} ".format(i, pt[0], pt[1], pt[2]), end='')

        # convert to homogenous
        pt = np.append(pt, 1.0)

        # project with camera matrix and convert back to affine
        warp = M @ pt
        row = warp[1]/warp[2]
        col = warp[0]/warp[2]

        # convert back to affine
        print("=> {0:.1f} {1:.1f} ".format(row, col), end='')

        # check if inside the image (4000 x 6000 image)
        if row >= 0 and row < 4000 and col >= 0 and col < 6000:
            print("inside")
        else:
            print("outside")

        # check if point in front of or behind the camera (z positive or negative)
        if warp[2] < 0:
            hidden.append(i)
        else:
            visible.append(i)

    print("visible:", end='')
    for pt in visible:
        print(" {0}".format(pt), end='')

    print("\nhidden:", end='')
    for pt in hidden:
        print(" {0}".format(pt), end='')
    print()

# -----------------------------------------------------------------------------
def print_matrix(M):
    for row in M:
        for element in row[:len(row)-1]:
            print("{0:.2f}, ".format(element), end='')
        print("{0:.2f}".format(row[-1]))

# =============================================================================
if __name__ == "__main__":
    points, R, T, f, d, ic, jc = arg_parse()
    M = get_camera_matrix(R, T, f, d, ic, jc)
    print("Matrix M:")
    print_matrix(M)

    project_points(points, M, ic, jc)


import sys
from itertools import combinations

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline

def solve():
    N = int(rl())
    X, Y = [0] * N, [0] * N
    for i in range(N):
        X[i], Y[i] = map(int, rl().split())

    ans = 0
    for i, j in combinations(range(N), 2):
        xi, yi, xj, yj = X[i], Y[i], X[j], Y[j]
        dy = yj - yi
        dx = xj - xi
        if dy == 0:
            ans = max(ans, Y.count(yi))
            continue
        if dx == 0:
            ans = max(ans, X.count(xi))
            continue
        a = dy / dx
        cnt = 2
        for k in range(i + 1, N):
            if j == k:
                continue
            dx = X[k] - xj
            if dx == 0:
                continue
            b = (Y[k] - yj) / dx
            cnt += (a == b)
        ans = max(ans, cnt)
    print(ans)

if __name__ == '__main__':
    solve()


'''
t검정 : t 분포에 대한 가설검정
t 검정 유형
  1. 한 집단 평균 검정: 모평균 검정
  2. 두 집단 평균 검정:
  3. 대응 두 집단
'''

from scipy import stats # test
import numpy as np # sampling
import pandas as pd # csv file read

# 1. 한 집단 평균 검정 : 남자 평균 키(모평균) : 175.5cm -> 29명 표본추출
#귀무가설: 모평균 175 cm와 차이가 없다.
#대립가설: 모평균 175 cm와 차이가 있다.
sample_data = np.random.uniform(172,179, size=29) #172~179 인 29 명
print(sample_data)
print(len(sample_data),'명')

# 기술통계
print('평균 키 =', sample_data.mean()) # np.mean

# 단일집단 평균차이 검정
one_group_test = stats.ttest_1samp(sample_data, 175) #(sample,모평균(mu))
print('t검정 통계량 = %.3f, pvalue = %.5f'%(one_group_test))
# t검정 통계량 = -0.006(-1.96~1.96), pvalue = 0.99498

# 2. 두 집단 평균 검정 : 남여 평균 점수 차이 검정
female_score = np.random.uniform(50, 100, size=30) # 여성
male_score = np.random.uniform(45, 95, size=30) # 남성

two_sample = stats.ttest_ind(female_score, male_score)
#(statistic=0.9260080405465926, pvalue=0.358278964123807)
print(two_sample)
print('두 집단 평균 차이 검정 = %.3f, pvalue = %.3f'%(two_sample))
#[해설] 두집단 간 평균 차이 없다

# file 자료 이용
sample = pd.read_csv('C:/ITWILL/4_python-ll/data/two_sample.csv')
print(sample.info())

two_df = sample[['method', 'score']]
print(two_df)

# 교육방법 기준 subset
method1 = two_df[two_df.method==1] #방법1
method2 = two_df[two_df.method==2] #방법2

# score 칼럼 추출
score1 = method1.score #방법1 ->점수
score2 = method2.score #방법2 ->점수

# 두 집단 평균차이 검정
two_sample = stats.ttest_ind(score1, score2)
print(two_sample)
#Ttest_indResult(statistic=nan, pvalue=nan) -> 결측치 score1 or score2 안에 결측치가 있다.

#결측치 처리:nan-> 평균 대체
score1=score1.fillna(score1.mean())
score2=score2.fillna(score2.mean())

# 두 집단 평균차이 검정
two_sample = stats.ttest_ind(score1, score2)
print(two_sample)
# Ttest_indResult(statistic=-0.9468624993102985, pvalue=0.34466920341921115)
#[해설] 두집단 간 평균 차이 없다

# 3. 대응 두 집단 : 복용전 65 -> 복용후 60 몸무게 변환
before = np.random.randint(60, 65, size=30)
after = np.random.randint(59, 64,  size=30)

paired_sample = stats.ttest_rel(before, after)
print(paired_sample)
print('t검정 통계량 = %.5f, pvalue = %.5f'%paired_sample)
#t검정 통계량 = 2.89230, pvalue = 0.00718
#[해설] 두집단 간 평균 차이 없다.

before.mean()#61.96666666666667
after.mean()#60.96666666666667

#[헤설] 복용전과 복용후 몸무게 변화는 없다.


from acts import asserts
from acts_contrib.test_utils.wifi import wifi_test_utils as wutils
from acts_contrib.test_utils.wifi.rtt import rtt_const as rconsts
from acts_contrib.test_utils.wifi.rtt import rtt_test_utils as rutils
from acts_contrib.test_utils.wifi.rtt.RttBaseTest import RttBaseTest

class RangeApMiscTest(RttBaseTest):
    """Test class for RTT ranging to Access Points - miscellaneous tests which
  do not fit into the strict IEEE 802.11mc supporting or non-supporting test
  beds - e.g. a mixed test."""

    # Number of RTT iterations
    NUM_ITER = 10

    # Time gap (in seconds) between iterations
    TIME_BETWEEN_ITERATIONS = 0

    #############################################################################

    def test_rtt_mixed_80211mc_supporting_aps_wo_privilege(self):
        """Scan for APs and perform RTT on one supporting and one non-supporting
    IEEE 802.11mc APs with the device not having privilege access (expect
    failures)."""
        dut = self.android_devices[0]
        rutils.config_privilege_override(dut, True)
        rtt_aps = rutils.scan_with_rtt_support_constraint(dut, True)
        non_rtt_aps = rutils.scan_with_rtt_support_constraint(dut, False)
        mix_list = [rtt_aps[0], non_rtt_aps[0]]
        dut.log.debug("Visible non-IEEE 802.11mc APs=%s", mix_list)
        events = rutils.run_ranging(dut, mix_list, self.NUM_ITER,
                                    self.TIME_BETWEEN_ITERATIONS)
        stats = rutils.analyze_results(events, self.rtt_reference_distance_mm,
                                       self.rtt_reference_distance_margin_mm,
                                       self.rtt_min_expected_rssi_dbm,
                                       self.lci_reference, self.lcr_reference)
        dut.log.debug("Stats=%s", stats)

        for bssid, stat in stats.items():
            asserts.assert_true(
                stat['num_no_results'] == 0,
                "Missing (timed-out) results",
                extras=stats)
            if bssid == rtt_aps[0][wutils.WifiEnums.BSSID_KEY]:
                asserts.assert_false(
                    stat['any_lci_mismatch'], "LCI mismatch", extras=stats)
                asserts.assert_false(
                    stat['any_lcr_mismatch'], "LCR mismatch", extras=stats)
                asserts.assert_equal(
                    stat['num_invalid_rssi'], 0, "Invalid RSSI", extras=stats)
                asserts.assert_true(
                    stat['num_failures'] <=
                    self.rtt_max_failure_rate_two_sided_rtt_percentage *
                    stat['num_results'] / 100,
                    "Failure rate is too high",
                    extras=stats)
                asserts.assert_true(
                    stat['num_range_out_of_margin'] <=
                    self.rtt_max_margin_exceeded_rate_two_sided_rtt_percentage
                    * stat['num_success_results'] / 100,
                    "Results exceeding error margin rate is too high",
                    extras=stats)
            else:
                asserts.assert_true(
                    stat['num_failures'] == self.NUM_ITER,
                    "All one-sided RTT requests must fail when executed without privilege",
                    extras=stats)
                for code in stat['status_codes']:
                    asserts.assert_true(
                        code == rconsts.
                        EVENT_CB_RANGING_STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC,
                        "Expected non-support error code",
                        extras=stats)
        asserts.explicit_pass("RTT test done", extras=stats)


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

urlpatterns = [
    path('',views.loginPage),
    #path('login_admin2/',views.login_admin2),
    #path('login_admin2_validation',views.login_admin2_validation),
    path('loginValidation/',views.loginValidation),
    path('register/', views.register),
    path('registrationValidation',views.register),
    path('logout/',views.logout)

]


import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import facebook

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishme():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<=12:
        speak("Good Morning sir. You look fabulous. Let us start from where you left last time.")

    elif hour>=12 and hour<=17:
        speak("Good Afternoon sir. Shouldn't you take a rest, just kidding. Let us start from where you left last time.")

    else:
        speak("Good evening sir. Nice to see you again")

    speak("How can I help you?")

def takeCommand():
    #it takes microphone input and returns a string output
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening sir..")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing")
        query = r.recognize_google(audio, language='en-in')
        print(f"You said: {query}\n")

    except Exception:
        #print(e)
        print("I'm sorry. Will you please say that again...")
        return "None"
    return query

if __name__=="__main__":
    wishme()
    while True:
        query = takeCommand().lower()
        #logics to do different tasks
        if 'wikipedia' in query:
            speak('Searching wikipedia..')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak('According to wikipedia')
            speak(results)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")
            speak('Play a video sir.')

        elif 'open chrome' in query:
            webbrowser.open("google.com")
            speak('That\'s a lot of tabs.')

        elif 'play music' in query:
            music_dir = 'D:\\Entertainment\\Songs\\english songs'
            songs = os.listdir(music_dir)
            os.startfile(os.path.join(music_dir, songs[1]))

        elif 'who are you' in query:
            speak('I am JARVIS, abbreviated version of Just A Rather Very Intelligent System')

        elif 'what are you' in query:
            speak('To be honest sir. I don\'t know. But according to you, I am an AI project that you want to take it to next level. And since you have been kicked out of yoour dream project, you want to make me a far lot more better and efficient than everything else. And finally to use my capabillities to prove we do not need a god, but science')

        elif 'quit' in query:
            exit(0)


import requests
from bs4 import BeautifulSoup
import time
import sys

def get_regi_list(last_time, budget, cities):
    url = get_url(cities)
    response = requests.get(url)
    msg = ""

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        regi_list = soup.find('div', class_='regi-list')
        if regi_list:
            items = regi_list.find_all('div', class_='regi-item d-flex flex-wrap')
            for item in items:
                regi_info = item.find('ul', class_='regi-info')
                places = regi_info.find_all('span')
                place_str = ''
                for place in places:
                    place_str += place.text
                    place_str += ' '
                price = item.find('div', class_='price regularbold')
                new_price = float(price.text.replace('€', '').replace(',', ''))
                if new_price <= budget:
                    print(new_price)
                    msg += f"Found a room that is {new_price} euros in "
                    msg += place_str
                    room_url = item.get('data-url')
                    msg += f"{room_url}\n"
        else:
            print("No 'regi-list' div found.")
    else:
        print(f"Request failed with status code: {response.status_code}")
        msg += f"Request failed with status code: {response.status_code}\n"

    if msg != "":
        current_time = time.time()
        if current_time - last_time > 120: # change this to your desired time, meaning if the last message was sent more than 2 minutes ago, send a new message
            send_message(msg)
            last_time = current_time

    return last_time

def get_url(cities):
    maps = {
        'Amsterdam': '24',
        'Arnhem': '320',
        'Capelle aan den IJssel': '619',
        'Delft': '26',
        'Den Bosch' : '28',
        'Den Haag': '90',
        'Den Bosch': '110',
        'Dordrecht': '620',
        'Eindhoven': '29',
        'Groningen': '545',
        'Haarlem': '616',
        'Helmond': '6099',
        'Maastricht': '6090',
        'Nijmegen': '6217',
        'Rotterdam': '25',
        'Rijswijk': '6224',
        'Sittard': '6211',
        'Tilburg': '6093',
        'Utrecht': '27',
        'Nieuwegein': '6051',
        'Zeist': '6145',
        'Zoetermeer': '6088'
    }
    if len(cities) == 1:
        city_para = f"{maps[cities[0]]}"
    else:
        city_para = f"{maps[cities[0]]}"
        for city in cities[1:]:
            city_para += f"%2C{maps[city]}"
    url = f"https://holland2stay.com/residences.html?available_to_book=179&city={city_para}&product_list_limit=30&product_list_order=price"
    return url

def send_message(msg):
    TOKEN = "your_token"
    chat_id = "your_chat_id"
    url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&text={msg}"
    print(requests.get(url).json())

if __name__ == "__main__":
    budget = 2000
    cities = ['Amsterdam', 'Eindhoven']
    last_time = time.time() - 130
    while True:
        try:
            last_time = get_regi_list(last_time, budget, cities)
            time.sleep(12)
        except Exception as e:
            time.sleep(12)


import sys
from collections import deque
sys.stdin = open('백준4179. 불!.txt', 'r')

d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
R, C = map(int, input().split())
maps = [list(''.join(sys.stdin.readline().rstrip())) for _ in range(R)]
answer = 0
def fire():
    for _ in range(len(fire_queue)):
        r, c = fire_queue.popleft()
        for idx in range(4):
            nr = r + d[idx][0]
            nc = c + d[idx][1]
            if 0 <= nr < R and 0 <= nc < C and not visited[nr][nc]:
                if maps[nr][nc] != '#':
                    maps[nr][nc] = 'F'
                    visited[nr][nc] = 1
                    fire_queue.append((nr, nc))

def man():
    global answer, flag
    for _ in range(len(man_queue)):
        r, c, s = man_queue.popleft()
        for idx in range(4):
            nr = r + d[idx][0]
            nc = c + d[idx][1]
            if 0 <= nr < R and 0 <= nc < C:
                if maps[nr][nc] == '.':
                    maps[nr][nc] = 'J'
                    visited[nr][nc] = 1
                    man_queue.append((nr, nc, s+1))
            else:
                answer = s+1

flag = True
man_queue = deque([])
fire_queue = deque([])
visited = [[0] * C for _ in range(R)]
for r in range(R):
    for c in range(C):
        if maps[r][c] == 'F':
            fire_queue.append((r, c))
            visited[r][c] = 1
        elif maps[r][c] == 'J':
            man_queue.append((r, c, 0))
            visited[r][c] = 1

while man_queue:
    fire()
    man()
    if answer > 0: break
print(answer if answer else "IMPOSSIBLE")


class Atm:
    def __init__(self,cardnumber,pin) :
        self.cardnumber=cardnumber
        self.pin=pin

    def checkbalance(self):
        print("your balance is 50000")

    def withdrawl(self,amount):
        newamount=50000-amount

        print("your withdrawl amount is "+str(amount)+" your remaining balance is "+str(newamount))

def main() :
    cardno=input("enter your card number ")
    pinno=input("enter your pin number ")

    newuser= Atm(cardno,pinno)
    print("choose your activity 1. balance enquiry 2. withdrawl")
    activity=int(input("enter activity number "))
    if(activity==1):
        newuser.checkbalance()

    elif(activity==2):
        amount=int(input("enter the amount "))
        newuser.withdrawl(amount)
    else:
        print("enter a valid number")
main()


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

from PIL import Image
from pylab import *

# 配列に画像を読み込む
im = array(Image.open('empire.jpg'))

# 画像を表示する
imshow(im)

# 点の座標
x = [100,100,400,400]
y = [200,500,200,500]

# 赤い星マークで点を描画する
plot(x,y,'r*')

# 最初の2点間に線を描画する
plot(x[:2],y[:2])

# タイトルを追加し、描画結果を表示する
title('Plotting: "empire.jpg"')
axis('off')
show()


# !/usr/bin/env python
# -*- coding:utf-8 -*-
import urlparse
import json
from cgi import parse_qs,escape
def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    params = parse_qs(environ['QUERY_STRING'])
    name = params.get('name',[''])[0]
    website = params.get('website',[''])[0]
    user = params.get('user',[''])[0]
    dic = [{'name':name,'website':website,"user":user}]
    data = {'data':dic}
    return json.dumps(data)


#!/usr/bin/env python3
# -*-encoding: utf-8-*-

# created: 02.12.18
# by David Zashkolny
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
import functools

def cache(func):
    """ Decorator for save answers of any function
    """
    results = {}

    @functools.wraps(func)
    def __cache(*args):         # changed function
        nonlocal results               # if this function call with parameters that already used
        if args in results.keys():     # then answer gets from dictionary
            # print("{} - got from cache".format(args))
            rez = results[args]
        else:
            rez = func(*args)
            results[args] = rez
        return rez

    return __cache

@cache
def recursive(a: tuple, i: int, j: int):
    """ Recursive solution of the longest monotone subsequence
    :param a: sequence (must be the tuple or any other hashable sequence for cache)
    :param i: right bound
    :param j: left bound
    :return: length of the longest subsequence, subsequence
    """
    if i == j:                 # if right bound == left bound then sequence is one element
        return 1, (a[i], )

    _pre_count, _pre_seq = recursive(a, i-1, j)   # check if a[i] is continuation of previous max sequence
    if a[i] >= _pre_seq[-1]:
        return _pre_count + 1, _pre_seq + (a[i], )
    else:
        max_count = 1
        max_seq = (a[i],)
        for k in range(j, i):          # if it's false - check all sequences between i and j
            tmp_count, tmp_seq = recursive(a, i-1, k)      # from k to i-1
            if tmp_count+1 > max_count and a[i] >= tmp_seq[-1]:   # find maximum
                max_count = tmp_count + 1
                max_seq = tmp_seq + (a[i], )

        for k in range(i):
            tmp_count, tmp_seq = recursive(a, k, 0)   # and between 0 and i
            if tmp_count+1 > max_count and a[i] >= tmp_seq[-1]:    # from 0 to k
                max_count = tmp_count + 1
                max_seq = tmp_seq + (a[i], )

        return (max_count, max_seq) if max_count > _pre_count else (_pre_count, _pre_seq)

def dynamic(a, b):
    """ Dynamic solution for the longest common sequence of
    consecutive numbers

    :param a: sequence of numbers
    :param b: sequence of numbers
    :return: sequenve of numbers
    """
    m = len(a)
    n = len(b)
    d = [[0 for i in range(n)] for j in range(m)]    # d[i][j] is length of common sequence of consecutive
    prev = [-1 for j in range(n)]                    # numbers that ends with a[i] == b[j]
    global_max = 0
    global_pos = -1
    for i in range(0, m):
        for j in range(0, n):        # iterate through all the elements by dual circle
            if a[i] == b[j]:         # if pair is equal then check if there is sequence that ends with a[i]-1
                max_len = 0   # find longest sequence ends with a[i]-1
                max_prev = -1
                for k in range(i+1):
                    for l in range(j+1):
                        if k == i and l == j:
                            continue
                        if d[k][l] > max_len and a[k] == b[l] == a[i] - 1:
                            max_len = d[k][l]
                            max_prev = l
                d[i][j] = max_len + 1
                if d[i][j] > global_max:
                    global_max = d[i][j]
                    global_pos = j
                prev[j] = max_prev

    res = []                   # rebuild the answer
    while global_pos != -1:
        res.append(b[global_pos])
        global_pos = prev[global_pos]

    return res[::-1]

if __name__ == '__main__':
    test_a = [5, 2, 7, 3, 8, 34, 9, 4, 2, 7, 0, 1, 6, 3, 67, 5, 6]
    test_b = [1, 2, 7, 2, 6, 3, 7, 9, 32, 7, 2, 4, 7, 5, 45, 36, 100, 213, 6]
    test_m = len(test_a)
    test_n = len(test_b)

    print(dynamic(test_a, test_b))
    print(dynamic(test_a, test_b))


class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [False] * (len(s)+1) # one extra element for base case
        dp[len(s)] = True

        for i in range(len(s)-1, -1, -1): # reverse for loop from last element
            for word in wordDict:
                if i+len(word) <= len(s) and s[i: i+len(word)] == word:
                    dp[i] = dp[i+len(word)]
                    # True only if there is a word starting at index => i+len(word) => i.e new word starts where this one ends
                if dp[i] == True:
                    break

        return dp[0] # dp stores if a word is starting at index i and it has others words following it