import os
import platform
import tempfile
import urllib

from cupy import testing
from cupyx.tools import install_library

import pytest

_libraries = ['cudnn', 'nccl', 'cutensor']

def _get_supported_cuda_versions(lib):
    return sorted(set([
        rec['cuda'] for rec in install_library.library_records[lib]]))

class TestInstallLibrary:

    @pytest.mark.parametrize('cuda', _get_supported_cuda_versions('cudnn'))
    @testing.slow
    def test_install_cudnn(self, cuda):
        self._test_install('cudnn', cuda)

    @pytest.mark.skipif(
        platform.system() == 'Windows',
        reason='NCCL is only available for Linux')
    @pytest.mark.parametrize('cuda', _get_supported_cuda_versions('nccl'))
    @testing.slow
    def test_install_nccl(self, cuda):
        self._test_install('nccl', cuda)

    @pytest.mark.parametrize('cuda', _get_supported_cuda_versions('cutensor'))
    @testing.slow
    def test_install_cutensor(self, cuda):
        self._test_install('cutensor', cuda)

    def _test_install(self, library, cuda):
        system = platform.system()
        for rec in install_library.library_records[library]:
            if rec['cuda'] != cuda:
                continue
            version = rec[library]
            filenames = rec['assets'][system]['filenames']
            with tempfile.TemporaryDirectory() as d:
                install_library.install_lib(cuda, d, library)
                self._check_installed(
                    d, cuda, library, version, filenames)
            break
        else:
            pytest.fail(f'unexpected CUDA version {cuda} for {library}')

    def _check_installed(self, prefix, cuda, lib, version, filenames):
        install_root = os.path.join(prefix, cuda, lib, version)
        assert os.path.isdir(install_root)
        for _x, _y, files in os.walk(install_root):
            for filename in filenames:
                if filename in files:
                    return
        pytest.fail('expected file cound not be found')

    @pytest.mark.parametrize('library', _libraries)
    def test_urls(self, library):
        assets = [r['assets']
                  for r in install_library.library_records[library]]
        for asset in assets:
            for system in asset.keys():
                url = asset[system]['url']
                with urllib.request.urlopen(
                        urllib.request.Request(url, method='HEAD')) as resp:
                    assert resp.getcode() == 200

    @pytest.mark.parametrize('library', _libraries)
    def test_main(self, library):
        install_library.main(
            ['--library', library, '--action', 'dump', '--cuda', 'null'])


import sys
input = lambda: sys.stdin.readline()[:-1]

n, q = [int(x) for x in input().split()]
items = {input() for _ in range(n)}
counter = 0
for _ in range(q):
    done = 1
    for _ in range(int(input())):
        if input() not in items:
            done = 0
    if done:
        counter += 1
print(counter)


def solve(a, b, c, x):
  q = x // (a + c)
  r = x % (a + c)
  return (q * a + min(a, r)) * b

a, b, c, d, e, f, x = map(int, input().split())

takahashi = solve(a, b, c, x)
aoki = solve(d, e, f, x)

if takahashi > aoki:
  print("Takahashi")
elif takahashi < aoki:
  print("Aoki")
else:
  print("Draw")


class Tree():
  def __init__(self, data):
    self.data = data
    self.child = []

m = int(input())
ip = list(map(int, input().split()))
l = []
root = None

for i in ip:
  if(i==-1):
    l.pop()
  else:
    node = Tree(i)
    if(len(l)==0):
      root = node
    else:
      l[-1].child.append(node)
    l.append(node)

def heightoftree(root):
  ht = -1
  for i in root.child:
    p = heightoftree(i)
    ht = max(p, ht)
  ht += 1
  return ht

print(heightoftree(root))


from resources.libraries.python.VatExecutor import VatTerminal, VatExecutor

class NATUtil(object):
    """This class defines the methods to set NAT."""

    def __init__(self):
        pass

    @staticmethod
    def set_nat44_interfaces(node, int_in, int_out):
        """Set inside and outside interfaces for NAT44.

        :param node: DUT node.
        :param int_in: Inside interface.
        :param int_out: Outside interface.
        :type node: dict
        :type int_in: str
        :type int_out: str
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If setting of inside and outside interfaces for
            NAT44 fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat44_set_interfaces.vat',
                    int_in=int_in, int_out=int_out)
                return response
        except:
            raise RuntimeError("Setting of inside and outside interfaces for "
                               "NAT failed!")

    @staticmethod
    def set_nat44_deterministic(node, ip_in, subnet_in, ip_out, subnet_out):
        """Set deterministic behaviour of NAT44.

        :param node: DUT node.
        :param ip_in: Inside IP.
        :param subnet_in: Inside IP subnet.
        :param ip_out: Outside IP.
        :param subnet_out: Outside IP subnet.
        :type node: dict
        :type ip_in: str
        :type subnet_in: str or int
        :type ip_out: str
        :type subnet_out: str or int
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If setting of deterministic behaviour of NAT44
            fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat44_set_deterministic.vat',
                    ip_in=ip_in, subnet_in=subnet_in,
                    ip_out=ip_out, subnet_out=subnet_out)
                return response
        except:
            raise RuntimeError("Setting of deterministic behaviour of NAT "
                               "failed!")

    @staticmethod
    def set_nat_workers(node, lcores):
        """Set NAT workers.

        :param node: DUT node.
        :param lcores: List of cores, format: range e.g. 1-5 or list of ranges
            e.g.: 1-5,18-22.
        :type node: dict
        :type lcores: str
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If setting of NAT workers fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat_set_workers.vat', lcores=lcores)
                return response
        except:
            raise RuntimeError("Setting of NAT workers failed!")

    @staticmethod
    def show_nat(node):
        """Show the NAT settings.

        :param node: DUT node.
        :type node: dict
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If getting of NAT settings fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat_show_nat.vat')
                return response
        except:
            raise RuntimeError("Getting of NAT settings failed!")

    @staticmethod
    def show_nat44_deterministic_forward(node, ip_addr):
        """Show forward IP address and port(s).

        :param node: DUT node.
        :param ip_addr: IP address.
        :type node: dict
        :type ip_addr: str
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If command 'exec snat deterministic forward'
            fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat44_deterministic_forward.vat', ip=ip_addr)
                return response
        except:
            raise RuntimeError("Command 'exec nat44 deterministic forward {ip}'"
                               " failed!".format(ip=ip_addr))

    @staticmethod
    def show_nat44_deterministic_reverse(node, ip_addr, port):
        """Show reverse IP address.

        :param node: DUT node.
        :param ip_addr: IP address.
        :param port: Port.
        :type node: dict
        :type ip_addr: str
        :type port: str or int
        :returns: Response of the command.
        :rtype: str
        :raises RuntimeError: If command 'exec snat deterministic reverse'
            fails.
        """

        try:
            with VatTerminal(node, json_param=False) as vat:
                response = vat.vat_terminal_exec_cmd_from_template(
                    'nat/nat44_deterministic_reverse.vat',
                    ip=ip_addr, port=port)
                return response
        except:
            raise RuntimeError(
                "Command 'exec nat44 deterministic reverse {ip}:{port}'"
                " failed!".format(ip=ip_addr, port=port))

    @staticmethod
    def get_nat_static_mappings(node):
        """Get NAT static mappings from VPP node.

        :param node: VPP node.
        :type node: dict
        :returns: List of static mappings.
        :rtype: list
        :raises RuntimeError: If the output is not as expected.
        """

        vat = VatExecutor()
        # JSON output not supported for this command
        vat.execute_script('nat/snat_mapping_dump.vat', node, json_out=False)

        stdout = vat.get_script_stdout()
        lines = stdout.split("\n")

        data = []
        # lines[0,1] are table and column headers
        for line in lines[2::]:
            # Ignore extra data after NAT table
            if "snat_static_mapping_dump error: Misc" in line or "vat#" in line:
                continue
            items = line.split(" ")
            while "" in items:
                items.remove("")
            if not items:
                continue
            if len(items) == 4:
                # no ports were returned
                data.append({
                    "local_address": items[0],
                    "remote_address": items[1],
                    "vrf": items[2],
                    "protocol": items[3]
                })
            elif len(items) == 6:
                data.append({
                    "local_address": items[0],
                    "local_port": items[1],
                    "remote_address": items[2],
                    "remote_port": items[3],
                    "vrf": items[4],
                    "protocol": items[5]
                })
            else:
                raise RuntimeError("Unexpected output from snat_mapping_dump.")

        return data

    @staticmethod
    def get_nat_interfaces(node):
        """Get list of interfaces configured with NAT from VPP node.

        :param node: VPP node.
        :type node: dict
        :returns: List of interfaces on the node that are configured with NAT.
        :rtype: list
        :raises RuntimeError: If the output is not as expected.
        """

        vat = VatExecutor()
        # JSON output not supported for this command
        vat.execute_script('nat/snat_interface_dump.vat', node,
                           json_out=False)

        stdout = vat.get_script_stdout()
        lines = stdout.split("\n")

        data = []
        for line in lines:
            items = line.split(" ")
            for trash in ("", "vat#"):
                while trash in items:
                    items.remove(trash)
            if not items:
                continue
            if len(items) == 3:
                data.append({
                    # items[0] is the table header - "sw_if_index"
                    "sw_if_index": items[1],
                    "direction": items[2]
                })
            else:
                raise RuntimeError(
                    "Unexpected output from snat_interface_dump.")

        return data


# function2py
#전역변수와 지역변수

x=1
def func(a):
    return a+x

#호출
print(func(1))

def func2(a):
    x = 2
    return a+x

print(func2(1))

def times(a=10, b=20):
    return a*b

print(times())
print(times(5))
print(times(5,6))

def connectURI(server, port):
    strURL = "http://"+ server+ ":" + port
    return strURL

print(connectURI("credu.com", "80"))
print(connectURI(port = "80", server="credu.com"))

def union(*ar):
    result = []
    for item in ar:
        for x in item:
            if x not in result:
                result.append(x)
    return result

print(union("HAM", "EGG"))
print(union("HAM", "EGG", "SPAM"))


import requests
from web.models import ApiKeys

def __search(params):
    api_key = ''
    for keys in ApiKeys.select():
        api_key = keys.key

    s = requests.session()
    s.headers = {
        "Authorization": "Bearer " + api_key
    }
    r = s.get("https://api.yelp.com/v3/businesses/search", params=params)
    ratelimits = ApiKeys.select()
    if ratelimits:
        ratelimits = ApiKeys.select().get()
        ratelimits.ratelimit = r.headers['ratelimit-remaining']
    else:
        ratelimits = ApiKeys(r.headers['ratelimit-remaining'])
    ratelimits.save()
    return r.json()["businesses"]

def search(latitude, longitude, radius, category='[]'):
    results = []

    search_params = ({
        "term": "restaurants",
        "limit": 50,
        "latitude": latitude,
        "longitude": longitude,
        "radius": radius,
        "categories": ",".join(list(map(lambda c: c, eval(category)))),
    })

    while True:
        page = __search(search_params)
        results.extend(page)
        if len(page)<50:
            # print(search_params)
            break
        search_params.update({
            "offset": search_params.get("offset", 0) + 50
        })

    return results

def search_all_circles(circles, start_index=0, category='[]'):
    print('start_index', start_index)
    data = []
    uniq_set = set()
    for i,circle in enumerate(circles[start_index:]):
        try:
            results = search(circle[0][1],circle[0][0],circle[1],category)
        except:
            return False, data, start_index + i

        for j in results:
            if j['id'] not in uniq_set:
                data.append(j)
                uniq_set.add(j['id'])
    return True, data, start_index + i

# if __name__ == "__main__":
#     print(len(search("Los Angeles, CA")))


import rospy

from trac_ik_python.trac_ik import IK

rospy.init_node('test_script')
# Get your URDF from somewhere
with open('/home/mlei/concert_ws/ros_src/modularbot/urdf/ModularBot.urdf', 'r') as file:
    urdf=file.read()

ik_solver = IK("base_link",
               "ee_A", urdf_string=urdf)

lower_bound, upper_bound = ik_solver.get_joint_limits()

print(lower_bound)
print(upper_bound)

seed_state = [0.0] * ik_solver.number_of_joints

solution = ik_solver.get_ik(seed_state,
                0.45, 0.1, 0.3,
                0.0, 0.0, 0.0, 1.0,
                0.0, 0.01, 0.01,  # X, Y, Z bounds
                100, 1000, 100)  # Rotation X, Y, Z bounds

print(solution)


# ROZCVICKA

# spravime si prazdny dict.
slovnik = dict()

def pridaj_slovicko(slovnik: dict) -> dict:
    '''

    '''
    # 1 budeme pridavat klucove slovo
    kluc = input('ZADAJ KLUC')
    # 2hodnotu v podobe string
    if kluc == 'q':
        print('KONIEC')
        quit()
    hodnota = input('ZADAJ STRING')
    # vlozit do slovnika
    slovnik[kluc] = hodnota  # zavolam slovnik a pridam klucove slovo a jeho obsah
    # zavolam slovnik, urcim klucove slovo = hodnota
    print(slovnik)
    # vyprintovat hodnoty -
    return slovnik

# HLAVNY PROGRAM
while True:
    slovnik = pridaj_slovicko(slovnik)

# funkciou ALEBO
# nekonecnym cyklom


import torch
import torch.nn as nn
from prodict import Prodict
import utils

class Reducer(nn.Module):
    def __init__(self, dims: Prodict, device=torch.device("cpu")):
        super(Reducer, self).__init__()
        self.input_dim = dims.INPUT_DIM
        self.output_dim = dims.OUTPUT_DIM
        self.net = nn.Sequential(
            nn.Linear(self.input_dim, self.input_dim),
            nn.SELU(),
            nn.Linear(self.input_dim, self.output_dim),
            nn.SELU(),
        )
        self.device = device
        utils.init_network_weights(self.net, std=0.001)

    def forward(self, data):
        net_out = self.net(data)
        return net_out.permute(1, 0, 2)


from bs4 import BeautifulSoup
import requests
import pymongo
from splinter import Browser
from splinter.exceptions import ElementDoesNotExist
import tweepy
# from config import (consumer_key,
#                     consumer_secret,
#                     access_token,
#                     access_token_secret)
# auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# auth.set_access_token(access_token, access_token_secret)
# api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())
import pandas as pd
#import pymongo
from pprint import pprint
#from flask import Flask, render_template

conn = 'mongodb://localhost:27017'
client = pymongo.MongoClient(conn)
#db = client.

def scrape():

    #!which chromedriver
    executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
    browser = Browser('chrome', **executable_path, headless=True)

    # URL of page to be scraped
    url = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'
    browser.visit(url)
    html = browser.html
    # Retrieve page with the requests module
    #response = requests.get(url)
    # Create BeautifulSoup object; parse with 'lxml'
    soup = BeautifulSoup(html, 'html.parser')
    news_p_list = []
    news_title_list = []

    results = soup.find_all('li', class_ ='slide')

    for result in results:
        newstitle = result.find('div',class_='content_title')
        news_title= newstitle.a.text
        news_p = result.find('div', class_ = 'article_teaser_body').text
        news_p_list.append(news_p)
        news_title_list.append(news_title)

        #print(news_title)
        #print("______")
        #print(news_p)
        #print("______")
    print(news_title_list[0])
    print(news_p_list[0])

    url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
    browser.visit(url)
    html = browser.html

    soup = BeautifulSoup(html, 'html.parser')

    results = soup.find('div',class_='carousel_items').a
    print(soup.find('div',class_='carousel_items').article['style'].split("/",1)[1].rstrip("');"))
    featured_image_url = "https://www.jpl.nasa.gov/" +  soup.find('div',class_='carousel_items').article['style'].split("/",1)[1].rstrip("');")
    #featured_image_url = "https://www.jpl.nasa.gov" + results['data-fancybox-href']
    print(featured_image_url)

    # tweets = api.user_timeline('MarsWxReport',count=1)
    # mars_weather = []
    # for tweet in tweets:
    #     pprint(tweet['text'])
    #     mars_weather.append(tweet['text'])
    # print(mars_weather)

    url = 'https://twitter.com/marswxreport?lang=en'
    browser.visit(url)
    html = browser.html
    soup = BeautifulSoup(html, 'html.parser')
    tweets = soup.find("div",class_="js-tweet-text-container").text
    print(tweets)
    mars_weather =  tweets

    target_url = 'https://space-facts.com/mars/'
    tables = pd.read_html(target_url)
    tables =tables[0]
    tables = tables.rename(columns={0: "Info", 1:"Value"})
    tables.set_index('Info', inplace=True)
    weather_stuff = tables.to_dict()
    weather_stuff

    hemisphere_image_urls = [
        {"title": "Cerberus Hemisphere Enhanced", "img_url": "https://astrogeology.usgs.gov/cache/images/cfa62af2557222a02478f1fcd781d445_cerberus_enhanced.tif_full.jpg"},
        {"title": "Schiaparelli Hemisphere Enhanced", "img_url": "https://astrogeology.usgs.gov/cache/images/3cdd1cbf5e0813bba925c9030d13b62e_schiaparelli_enhanced.tif_full.jpg"},
        {"title": "Syrtis Major Hemisphere Enhanced", "img_url": "https://astrogeology.usgs.gov/cache/images/ae209b4e408bb6c3e67b6af38168cf28_syrtis_major_enhanced.tif_full.jpg"},
        {"title": "Valles Marineris Hemisphere Enhanced", "img_url": "https://astrogeology.usgs.gov/cache/images/7cf2da4bf549ed01c17f206327be4db7_valles_marineris_enhanced.tif_full.jpg"},
    ]
    scraped_dict = {"Mars_news_title":news_title_list[0],"Mars_news_p":news_p_list[0],"Mars_images":featured_image_url,"Mars_tweets":mars_weather,"Mars_stats": weather_stuff,"Mars_hemi": hemisphere_image_urls}
    return scraped_dict


from __future__ import absolute_import, division, print_function

import os
import io
import sys
import glob
import base64
import json
import argparse

from tqdm import tqdm
import numpy as np
from PIL import Image

sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utils.equi_to_cube import e2c

def ndarr2b64utf8(img):
    img_t = Image.fromarray(img)
    with io.BytesIO() as output:
        img_t.save(output, format="PNG")
        content = output.getvalue()
        b64_barr = base64.b64encode(content)
        b_string = b64_barr.decode('utf-8')
        return b_string

def b64utf82ndarr(b_string):
    b64_barr = b_string.encode('utf-8')
    content = base64.b64decode(b64_barr)
    img = Image.open(io.BytesIO(content))
    inp_np = np.asarray(img)
    return inp_np

def create_name_pair(inp_paths):
    pair_dict = dict()
    for inp_path in inp_paths:
        base_name, _ = os.path.splitext(os.path.basename(inp_path))
        pair_dict[base_name] = inp_path
    return pair_dict

def save_image(inp_path, output_dir, mask_path=None, face_w=128):
    pano_img = Image.open(inp_path, "r")
    inp_np = np.asarray(pano_img)

    base_name, _ = os.path.splitext(os.path.basename(inp_path))

    out_dict = dict()
    out_dict['f_name'] = inp_path
    out_dict['mask_flag'] = False

    face_list = ['f', 'r', 'b', 'l', 't', 'd']

    if mask_path is not None:
        img_mask = Image.open(mask_path, "r")
        inp_np_mask = np.asarray(img_mask)

        cm_mask, cl_mask = e2c(inp_np_mask, face_w=face_w)
        out_dict['mask_flag'] = True

    cm, cl = e2c(inp_np, face_w=face_w)

    cube_imgs = dict()

    for idx, face in enumerate(cl):
        b_string = ndarr2b64utf8(face)
        if mask_path is None:
            cube_imgs[face_list[idx]] = [b_string]
        else:
            b_string_mask = ndarr2b64utf8(cl_mask[idx])
            cube_imgs[face_list[idx]] = [b_string]
            cube_imgs[str(face_list[idx])+'_mask']=[b_string_mask]

    out_dict['cube'] = cube_imgs
    with open(os.path.join(output_dir, base_name + ".json"), "w") as f:
        json.dump(out_dict, f)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", required=True, type=str, help="\
        path to panorama image input directory. (<input dir>/*.png)")
    parser.add_argument("-m", default=None, type=str, help="\
        path to panorama mask directory. \
        The file name of mask have to be matched with the input image. \
        (<input dir>/*.png)")
    parser.add_argument("-face_w", default=256)
    parser.add_argument("-o", default="output_dir")
    args = parser.parse_args()

    img_paths = glob.glob(os.path.join(args.i, "*.png"))
    out_dir = args.o
    mask_dir = args.m
    face_w = args.face_w

    is_mask_pair = True if mask_dir is not None else False

    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    if is_mask_pair:
        mask_paths = glob.glob(os.path.join(mask_dir, "*.png"))

        # crate pair
        name_path_pair_pano = create_name_pair(img_paths)
        name_path_pair_cube = create_name_pair(img_paths)
        name_path_pair_mask = create_name_pair(mask_paths)

        pair = dict()
        for k, v in name_path_pair_pano.items():
            if k in name_path_pair_mask:
                pair[k] = {'pano': v, 'cube': name_path_pair_cube[k], 'mask': name_path_pair_mask[k]}

        for k, v in tqdm(pair.items(), desc="cube mask pair"):
            save_image(v['pano'], out_dir, mask_path=v['mask'], face_w=face_w)


from tqdm import tqdm
import torch
import torchvision
import torchvision.transforms as transforms
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader, Subset
from model import dCNN
from dataset import NumpySBDDataset
import torch.optim as optim
import os
import yaml
import argparse

device = "cuda" if torch.cuda.is_available() else "cpu"

def getdatasetstate(args={}):
    return {k: k for k in range(args["train_size"])}

def pre_process_fold(root, fold_name, class_to_label, meta, viz=False):
    path = os.path.join(root, fold_name)
    files = os.listdir(path)
    print("Processing fold:", fold_name)

    fold_data = []
    fold_labels = []

    for file in tqdm(files):
        try:
            if file.split(".")[1] != "wav":
                continue
            class_label = meta[meta["slice_file_name"] == file]["classID"].values[0]
            label_name = class_to_label[class_label]

            data, sr = librosa.load(os.path.join(path, file))

            S = librosa.feature.melspectrogram(data, sr, n_mels=128, fmax=8000)
            S_dB = librosa.power_to_db(S, ref=np.max)
            # pad S_dB with zeros to be (128, 173), pad the 1st dimension

            length = S_dB.shape[
                1
            ]  # the 4 second clip has length of 173 (trim anything with length greater than 173)

            if length > 173:
                # trim the length of the spectrogram to 173
                S_dB = S_dB[:173, :]
            else:
                # print(length)
                padding_to_add = 173 - length
                S_dB = np.pad(S_dB, [(0, 0), (0, padding_to_add)], mode="constant")

            #            print(S_dB.shape)
            if S_dB.shape == (128, 173):
                fold_data.append(S_dB)
                fold_labels.append(class_label)
            else:
                print(f"Size mismatch! {S_dB.shape}")

        except IndexError:
            print("Index error while processing file", file)
    return fold_data, fold_labels

def create_10_fold_data(ROOT="./data/"):
    train_file = "train_x.npy"
    full_path = os.path.join(ROOT, train_file)

    if os.path.isfile(full_path) and os.access(full_path, os.R_OK):
        train_x = np.load(ROOT + "train_x.npy")
        train_y = np.load(ROOT + "train_y.npy")
        test_x = np.load(ROOT + "test_x.npy")
        test_y = np.load(ROOT + "test_y.npy")

        # print(f"{train_x.shape} {train_y.shape} {test_x.shape} {test_y.shape}")

        return train_x, train_y, test_x, test_y

    train_x = []
    train_y = []

    test_x = []
    test_y = []

    print("Generating 10-fold data...")
    for fold in tqdm(folds):
        train = True

        if str(TEST_FOLD) in fold:
            train = False

        fold_data, fold_labels = pre_process_fold(
            "./data/audio/", fold, class_to_label, meta, viz=False
        )

        if train:
            train_x.extend(fold_data)
            train_y.extend(fold_labels)
        else:
            test_x.extend(fold_data)
            test_y.extend(fold_labels)

    ROOT_SAVE = "./data/"
    train_x = np.array(train_x)
    train_y = np.array(train_y)
    test_x = np.array(test_x)
    test_y = np.array(test_y)
    np.save(ROOT_SAVE + "train_x.npy", train_x)
    np.save(ROOT_SAVE + "train_y.npy", train_y)
    np.save(ROOT_SAVE + "test_x.npy", test_x)
    np.save(ROOT_SAVE + "test_y.npy", test_y)
    return train_x, train_y, test_x, test_y

def processData(args, stageFor="train", indices=None):
    class_to_label = {
        0: "air_conditioner",
        1: "car_horn",
        2: "children_playing",
        3: "dog_bark",
        4: "drilling",
        5: "engine_idling",
        6: "gun_shot",
        7: "jackhammer",
        8: "siren",
        9: "street_music",
    }

    meta = pd.read_csv("./data/UrbanSound8K.csv")

    folds = list(map(lambda x: "fold" + str(x), list(range(1, 11))))

    TEST_FOLD = 10  # TODO: make this an arg
    ROOT_DATA_DIR = "./data/audio/"  # TODO: make this an arg

    train_x, train_y, test_x, test_y = create_10_fold_data()

    if stageFor == "train":
        dataset = NumpySBDDataset(train_x, train_y)
        dataset = Subset(dataset, indices)
    elif stageFor == "infer":
        dataset = NumpySBDDataset(train_x, train_y)
        dataset = Subset(dataset, indices)
    else:
        dataset = NumpySBDDataset(train_x, train_y)

    loader = DataLoader(
        dataset, batch_size=64, shuffle=True
    )  # TODO: add arg for batch size

    return loader

def train(args, labeled, resume_from, ckpt_file):
    print("========== In the train step ==========")
    batch_size = args["batch_size"]
    lr = args["learning_rate"]
    momentum = args["momentum"]
    epochs = args["train_epochs"]
    train_split = args["split_train"]

    loader = processData(args, stageFor="train", indices=labeled)

    net = dCNN()
    net = net.to(device=device)

    criterion = torch.nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters())

    if resume_from is not None:
        ckpt = torch.load(os.path.join(args["EXPT_DIR"], resume_from + ".pth"))
        net.load_state_dict(ckpt["model"])
        optimizer.load_state_dict(ckpt["optimizer"])
    else:
        getdatasetstate(args)

    net.train()

    for epoch in tqdm(range(args["train_epochs"]), desc="Training"):

        running_loss = 0

        for i, batch in enumerate(loader, start=0):
            data, labels = batch

            data = data.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()
            output = net(data)
            loss = criterion(output, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            if i % 1000:
                print(
                    "epoch: {} batch: {} running-loss: {}".format(
                        epoch + 1, i + 1, running_loss / 1000
                    ),
                    end="\r",
                )
                running_loss = 0

    print("Finished Training. Saving the model as {}".format(ckpt_file))

    ckpt = {"model": net.state_dict(), "optimizer": optimizer.state_dict()}
    torch.save(ckpt, os.path.join(args["EXPT_DIR"], ckpt_file + ".pth"))

    return

def test(args, ckpt_file):
    print("========== In the test step ==========")
    batch_size = args["batch_size"]
    lr = args["learning_rate"]
    momentum = args["momentum"]
    epochs = args["train_epochs"]
    train_split = args["split_train"]

    loader = processData(args, stageFor="test")

    net = dCNN()
    net = net.to(device=device)

    net.load_state_dict(
        torch.load(os.path.join(args["EXPT_DIR"], ckpt_file + ".pth"))["model"]
    )

    net.eval()
    predix = 0
    predictions = {}
    truelabels = {}

    n_val = args["test_size"]
    with tqdm(total=n_val, desc="Testing round", unit="batch", leave=False) as pbar:
        for step, (batch_x, batch_y) in enumerate(loader):
            with torch.no_grad():
                batch_x = batch_x.to(device)
                batch_y = batch_y.to(device)

                prediction = net(batch_x)

            for logit, label in zip(prediction, batch_y):
                # predictions[predix] = logit.cpu().numpy().tolist()
                truelabels[predix] = label.cpu().numpy().tolist()

                class_probabilities = logit.cpu().numpy().tolist()
                index_max = np.argmax(class_probabilities)
                predictions[predix] = index_max

                predix += 1

            pbar.update()

    # unpack predictions
    predictions = [val for key, val in predictions.items()]
    truelabels = [val for key, val in truelabels.items()]

    return {"predictions": predictions, "labels": truelabels}

def infer(args, unlabeled, ckpt_file):
    print("========== In the inference step ==========")
    batch_size = args["batch_size"]
    lr = args["learning_rate"]
    momentum = args["momentum"]
    epochs = args["train_epochs"]
    train_split = args["split_train"]

    loader = processData(args, stageFor="infer", indices=unlabeled)

    net = dCNN()
    net = net.to(device=device)

    net.load_state_dict(
        torch.load(os.path.join(args["EXPT_DIR"], ckpt_file + ".pth"))["model"]
    )

    net.eval()

    n_val = len(unlabeled)
    predictions = {}
    predix = 0

    with tqdm(total=n_val, desc="Inference round", unit="batch", leave=False) as pbar:
        for step, (batch_x, batch_y) in enumerate(loader):
            with torch.no_grad():
                batch_x = batch_x.to(device)
                batch_y = batch_y.to(device)
                prediction = net(batch_x)

            for logit in prediction:
                predictions[unlabeled[predix]] = {}

                class_probabilities = logit.cpu().numpy().tolist()
                predictions[unlabeled[predix]]["pre_softmax"] = class_probabilities
                index_max = np.argmax(class_probabilities)
                predictions[unlabeled[predix]]["prediction"] = index_max
                predix += 1

            pbar.update()

    return {"outputs": predictions}

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--config",
        default=os.path.join(os.getcwd(), "config.yaml"),
        type=str,
        help="Path to config.yaml",
    )
    args = parser.parse_args()

    with open(args.config, "r") as stream:
        args = yaml.safe_load(stream)

    labeled = list(range(5000))
    resume_from = None
    ckpt_file = "ckpt_0"

    print("Testing getdatasetstate")
    getdatasetstate(args=args)
    train(args=args, labeled=labeled, resume_from=resume_from, ckpt_file=ckpt_file)
    test(args=args, ckpt_file=ckpt_file)
    infer(args=args, unlabeled=[10, 20, 30], ckpt_file=ckpt_file)


# -*- coding: utf-8 -*-
# @Author: Ahmed kammorah
# @Date:   2019-04-14 22:19:20
# @Last Modified by:   Ahmed kammorah
# @Last Modified time: 2019-04-14 23:11:39
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import socket
from threading import Thread
import requests

MOCK_SERVER_PORT = 10001

class AKMockHTTPRequestHandler(BaseHTTPRequestHandler):
    SPARKPOST_SEND_PATTERN = re.compile(r'/')
    def do_GET(self):
        if re.search(SPARKPOST_SEND_PATTERN, self.path):
            self.send_response(requests.codes.ok)
            # Add response headers.
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            # Add response content.
            response_content = json.dumps([])
            self.wfile.write(response_content.encode('utf-8'))
            return

def start_mock_server(server_port):
    server_base = 'localhost'
    mock_server = HTTPServer((server_base, server_port), AKMockHTTPRequestHandler)
    ser_thread = Thread(target=mock_server.serve_forever)
    ser_thread.setDaemon(True)
    ser_thread.start()


import sys
sys.stdin = open('input.txt')

def BFS(row1, col1):
    to_visits = [[row1, col1]]
    global answer
    global flag
    dxs = [1, 0, -1, 0]
    dys = [0, 1, 0, -1]
    while to_visits:
        current = to_visits.pop(0)
        current_row = current[0]
        current_col = current[1]
        visited[current_row][current_col] = 1
        for i in range(4):
            w = current_row + dxs[i]
            h = current_col + dys[i]
            if 0 <= w < row and 0 <= h < col and matrix[w][h] == 'O':
                matrix[w][h] = 'I'
                to_visits += [[w, h]]
            if 0 <= w < row and 0 <= h < col and matrix[w][h] == 'P':
                matrix[w][h] = 'I'
                to_visits += [[w, h]]
                answer += 1
    flag += 1

row, col = map(int, input().split())
matrix = [list(input()) for _ in range(row)]
visited = [[0]*col for _ in range(row)]
answer = 0
flag = 0
for row1 in range(row):
    for col1 in range(col):
        if matrix[row1][col1] == 'I':
            BFS(row1, col1)
            break
    if flag > 0:
        break

if answer == 0:
    print('TT')
else:
    print(answer)


#!/usr/bin/env python
# -*- Python -*-
# -*- coding: utf-8 -*-
# ------------------------------------------------- #
# Python source single (add-dir-to-vim-projects.py) #
# Author: Alexei Panov <me@elemc.name>              #
# ------------------------------------------------- #
# Description:

import os
import os.path

typical_ident = "    "
share_str = ""
home_dir = os.path.expanduser("~")

def insert_string(s):
    print(s)

def ident_count(s):
    return len(s) - len(s.strip())

def self_listdir(d):
    dirs = []
    files = []
    for o in os.listdir(d):
        fullpath = os.path.join(d, o)
        if os.path.isdir(fullpath):
            dirs.append(o)
        elif os.path.isfile(fullpath):
            files.append(o)
    dirs.sort()
    files.sort()
    return dirs + files

def format_path_str(path_str):
    new_path_str = path_str.replace(home_dir, "~")
    return new_path_str

def process_file(f, ident=""):
    insert_string("%s%s" % (ident, os.path.basename(f)))

def process_dir(d, ident=""):
    if not os.path.exists(d):
        return

    dir_name = os.path.basename(d)

    if len(ident) == 0:
        insert_string("%s=%s CD=. {" % (dir_name, format_path_str(d)))
    else:
        insert_string("%s%s=%s/ {" % (ident, dir_name, dir_name))

    new_ident = ident + typical_ident
    for f in self_listdir(d):  # os.listdir( d ):
        if f == ".git":
            continue
        o = os.path.join(d, f)
        if os.path.isdir(o):
            process_dir(o, new_ident)
        elif os.path.isfile(o):
            process_file(o, new_ident)

    print("%s}" % ident)

if __name__ == '__main__':
    current_dir = os.path.abspath(os.path.curdir)
    # print( home_dir )
    process_dir(current_dir)


#!/usr/bin/env python
#encoding=utf8

class Record():
    def __init__(self, record_id, parent_id):
        self.record_id = record_id
        self.parent_id = parent_id

class Node():
    def __init__(self, node_id):
        self.node_id = node_id
        self.children = []

    def check_node_id(self):
        if any(child.node_id < self.node_id for child in self.children):
            raise ValueError("Bad node ID")
        for child in self.children:
            child.check_node_id()
        return self

    def __lt__(self, node):
        return self.node_id < node.node_id

def BuildTree(records):
    if not records:
        return None
    if len([r for r in records if r.parent_id == r.record_id]) != 1:
        raise ValueError("bad records")
    if max(r.record_id for r in records) != len(records) - 1:
        raise ValueError("bad records")
    parents = {record.record_id: record.parent_id for record in records}
    records.sort(key=lambda x: x.record_id, reverse=True)
    records.sort(key=lambda x: x.parent_id, reverse=True)
    root_record = records[-1]
    trunks = {root_record.parent_id: Node(root_record.parent_id)}
    for record in records[:-1]:
        if record.parent_id not in trunks:
            trunks[record.parent_id] = Node(record.parent_id)
        trunks[record.parent_id].children.append(Node(record.record_id))
        trunks[record.parent_id].children.sort()
        if record.record_id in trunks:
            # replace the dummy children in its parent's children record
            p_children = trunks[record.parent_id].children
            same_child = lambda c: c.node_id == record.record_id
            other_child = [c for c in p_children if not same_child(c)]
            children = other_child + [trunks[record.record_id]]
            children.sort()
            trunks[record.parent_id].children = children
            del trunks[record.record_id]
    if len(trunks) != 1:
        raise ValueError("Orphan")

    return trunks[root_record.parent_id].check_node_id()


from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

chrome_options = Options()
chrome_options.add_argument("--headless")
wait = WebDriverWait(Chrome, 5)

driver = webdriver.Chrome('/Users/Lucas/anaconda3/chromedriver')

url = 'https://www.google.com/'
browser = Chrome()
browser.get(url)

#buscando as informações na pagina
browser.find_element_by_name('q').send_keys("Eduzz")
browser.find_element_by_name('q').send_keys(Keys.RETURN)
texto = browser.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div/div/div/div/div[1]/a/h3')

frase = 'Vem crescer com a gente.'
validação = frase in texto.text

if(validação == True):
    print('Possui no texto a frase (Vem crescer com a gente.)')
else:
    print('Não possui no texto a frase (Vem crescer com a gente.)')


import os

def sort_file(source_path, dest_path):
    global_content = []
    for file_ in os.listdir(source_path):
        #read the file for contents
        with open(source_path +file_, "r") as f:
            for line in  f.readlines():
                # print(line)
                line = line.strip()
                if not line: continue
                (t, u) = line.split(" ")
                # collect all the file contents
                global_content.append((int(t), u))
    # sort global content by key
    sorted_content = sorted(global_content, key=lambda x: x[0])
    with open(dest_path +"-".join(os.listdir(source_path)) +"-merged.log", "w+") as f:
        for tup in sorted_content:
            f.write(" ".join([str(i) for i in tup])+ "\n")

if __name__ == "__main__":
   sort_file(os.path.realpath(".")+"/files/", os.path.realpath(".")+"/files_p/")


from torch import nn

class Convolution(nn.Module):
    def __init__(self, in_channels, out_channels, k_size=3, rate=1):
        super().__init__()
        self.convlayer = nn.Sequential(
            nn.Conv2d(in_channels=int(in_channels),
                      out_channels=int(out_channels),
                      kernel_size=(k_size, k_size),
                      dilation=(rate, rate),
                      padding='same'),
            nn.BatchNorm2d(int(out_channels)),
            nn.ReLU(inplace=True))

    def forward(self, x):
        return self.convlayer(x)


import numpy as np
from collections import defaultdict
import rl.env
import rl.player
import rl.display

class Env(rl.env.DiscreteEnv):

    def __init__(self, n = 10, h = 1, p = 2, k = 3) -> None:
        super().__init__()

        self.n = n
        self.h = h
        self.p = p
        self.k = k

        # List of players
        self.players = list()
        self.state_size = 0

    # Return the next state and reward
    def step(self, state : tuple, actions : list[tuple], d = None) -> tuple[list[tuple],list[int]]:
        # Random uniformly distributed demand between 0 and n
        if d is None:
            demand = np.random.randint(0, self.n+1)
        else:
            demand = d

        # Holding cost
        cost = max(0,self.h*(state + actions - demand))

        # Lost sales penalty
        cost += max(0,self.p*(demand - state - actions[0]))

        # Fixed ordering cost
        cost += self.k * (actions[0] > 0)

        next_state = state + actions[0] - min(demand, state + actions[0])

        reward = -cost

        return int(next_state), int(reward)

    # Function that returns the available actions
    def A(self, state):
        return tuple([tuple([i]) for i in range(self.n - state + 1)])

    def goal_test(self, state) -> bool:
        raise NotImplementedError("ContinuousEnv.goal_test() is not implemented")

    def reset(self) -> None:
        return 0

    def init_render(self, grid_scale = 50):
        self.grid_scale = grid_scale

        self.width = (self.n+1)*self.grid_scale + self.grid_scale
        self.height = (self.n+1)*self.grid_scale

        self.display = rl.display.displayHandler(self.width, self.height)

    def render(self, agent):
        gs = self.grid_scale
        min_q = 1e10
        max_q = 0

        color_r = [(i, 0, 0) for i in np.linspace(255, 0, int(self.n/2 + 1))]
        color_g = [(0, i, 0) for i in np.linspace(0, 255, int(self.n/2 + 1))]
        color = color_r[:-1] + color_g

        min_q = min(agent.Q.values())
        max_q = max(agent.Q.values())

        for a in range(self.n+1):
            for s in range(self.n+1):
                if(a <= self.n-s):
                    q = agent.Q[s,(a,)]
                    color_index = int((q-min_q) * len(color)/(max_q - min_q + 1e-05))
                    color_index = min(color_index, self.n)
                    self.display.draw_square((a*gs + gs/2, s*gs + gs/2), (gs, gs), color[color_index])
                    self.display.draw_text(str(round(q, 2)), (a*gs + gs/2, s*gs + gs/2), (255,255,255), align="center")
                else:
                    self.display.draw_square((a*gs + gs/2, s*gs + gs/2), (gs, gs), (0,0,0))

        q_range = np.linspace(min_q, max_q, self.n+1)

        if self.n%2 == 0:
            n_ = self.n + 1
        else: n_ = self.n
        for s in range(n_):
            self.display.draw_square(((self.n+1)*gs + gs/2, s*gs + gs/2), (gs, gs), color[s], width = 10)
            self.display.draw_text(str(round(q_range[s], 2)), ((self.n+1)*gs + gs/2, s*gs + gs/2), (255,255,255), align="center")

        self.display.update()

        return self.display.eventHandler()

    def is_terminal(self, state) -> bool:
        return False

    def get_transistion_probabilities(self, state, action):

        p = defaultdict(lambda : 0)

        num_states = len(self.get_states())
        for d in range(num_states):

            next_state, reward = self.step(state, action, d)

            p[(int(next_state), int(reward))] += 1/num_states

        return p

    def get_states(self) -> list:
        return tuple(np.arange(self.n + 1))

class EnvNonUniform(Env):
    def __init__(self, n = 10, h = 1, p = 2, k = 3, b = 1, m = 0) -> None:
        super().__init__(n, h, p, k)

        self.b = b
        self.m = m

        self.p = p

    def step(self, state : tuple, actions : list[tuple], d = None) -> tuple[list[tuple],list[int]]:
        # Random uniformly distributed demand between 0 and n
        if d is None:
            demand_ratio = np.array([(self.b+1)/(self.n+1) \
                                    if x == self.m or x == self.m + 1 \
                                    else (self.n - 1 - 2*self.b)/(self.n**2 - 1) \
                                    for x in range(self.n+1)])

            demand = int(np.random.choice(np.arange(self.n+1),
                                    size = 1,
                                    p = demand_ratio)[0])
        else:
            demand = d

        # Holding cost
        cost = max(0,(self.h*(state + actions[0] - demand)))

        # Lost sales penalty
        cost += max(0,(self.p*(demand - state - actions[0])))

        # Fixed ordering cost
        if(actions[0] > 0): cost += self.k

        next_state = state + actions[0] - min(demand, state + actions[0])

        reward = cost

        return next_state, reward

    def get_transistion_probabilities(self, state, action):

        p = defaultdict(lambda : 0)

        num_states = len(self.get_states())
        for d in range(num_states):

            demand_ratio = np.array([(self.b+1)/(self.n+1) \
                                    if x == self.m or x == self.m + 1 \
                                    else (self.n - 1 - 2*self.b)/(self.n**2 - 1) \
                                    for x in range(self.n+1)])

            next_state, reward = self.step(state, action, d)

            p[(int(next_state), int(reward))] += demand_ratio[d]

        return p


from utils import *

click.echo("Entering level 2")
click.pause()

coffee_counter.count = 0

screen(office, [
    "It is the day of your thesis submission",
    "You have 3 hours before you need to submit",
    "But there is a problem",
    "You have lost your only copy!"
])

click.pause()

response = None
wt = 2.0
while response not in ["C", "c"]:
    bg = office
    screen(bg, [
        "What are you going to do?",
        "A: Tweet about it",
        "B: Try to rewrite it from scratch",
        "C: Conduct a ninja spy mission"
    ], wait_time=wt)

    response = click.prompt("Select an action")
    if response in ["A", "a"]:
        screen(bomb, [
            "Your constant use of social media has led the world down a dark path",
            "Following the nuclear war, little is left of humanity"
        ])
        click.secho("Please try again", blink=True)
        exit()
    elif response in ["b", "B"]:
        screen(bg, [
            "there isn't enough coffee in the world to get that done"
        ])
    wt = 0.0

click.clear()

wt = 2.0
response = None

while response not in ["A", "a", "b", "B", "c", "C"]:
    bg = office
    screen(bg, [
        "You dress as sterling Archer, drink 3 cocktails and begin Interrogating the entire SBRC."
        "After an intense investigation you feel that it must be between one of three people.",
        "Who is it?",
        "A: Nigel",
        "B: Thomas",
        "C: Sneaky bitch Nicole"
    ], wait_time=wt)

    response = click.prompt("Select an action")

if response in ["A", "a"]:
    screen(office,
           [
               "It was a bold move accusing Nigel.",
               "But he understands that you were stressed",
               "He actually thinks more of you for having the courage.",
               "Just don't do it again"
           ]
    )

elif response in ["B", "b"]:
    screen(office,
           [
               "Thomas laughs in your face and calls you a bloody stupid idiot",
               "He turns away and goes to get a coffee",
               "It is clear you are no longer friends"
           ]
    )

elif response in ["C", "c"]:
    screen(office,
           [
               "Nicole is in tears",
               "You didn't have to call her a sneaky bitch",
               "She promptly gets drunk and goes full Mansfield",
               "She C bombs the shit out of you until you cry"
           ]
    )
click.pause()
screen(office,
    [
        "As it turns, it was none of these people.",
        "You left it on the tram when you went to Clifton",
        "Thomas calls you a bloody idiot",
        "Somehow, you manage to submit on time."
    ]
)

click.secho("Level 2 complete", blink=True)
click.pause()


__author__ = 'diegopinheiro'

from genetic_algorithms.genetic_algorithm import GeneticAlgorithm
from stop_criterions.iteration import IterationStopCriterion
from common.set_reader import SetReader
from selection_strategies.fitness_proportionate import FitnessProportionate
from selection_strategies.tournament_selection import TournamentSelection
from selection_strategies.rank_selection import RankSelection
from crossover_strategies.single_point import SinglePoint
from crossover_strategies.two_point import TwoPoint
from fitness_fuctions.accuracy_set import AccuracySet
from initialization_strategies.random_initialization import RandomInitialization
from initialization_strategies.data_initialization import DataInitialization
from mutation_strategies.one_gene_mutation import OneGeneMutation
import random
from common.writer import  Writer
from common.attribute import Attribute
from common.attribute_converter import AttributeConverter
from common.float_converter_2 import FloatConverter2

import sys

def main(output_path):

    print("\r\n\r\n\r\n")
    print("######## Experiment: testIris ########")

    data_set_name = "iris"
    data_set_reader = SetReader(data_set_name)
    training_set = data_set_reader.read_train_set()
    test_set = data_set_reader.read_test_set()
    data_set_attributes = data_set_reader.attributes

    population_size = 100

    replacement_rate = 0.3

    max_number_iteration = 3000

    use_elitism = True
    use_default = True

    initial_number_rules = 4
    min_number_rules = 4
    max_number_rules = 4

    stop_criterion = IterationStopCriterion(max_number_iteration=max_number_iteration)
    selection_strategy = FitnessProportionate()
    # selection_strategy = TournamentSelection(probability=0.7)
    # selection_strategy = RankSelection()
    # crossover_strategy = TwoPoint()
    crossover_strategy = SinglePoint()
    fitness_function = AccuracySet(min_number_rules=min_number_rules, max_number_rules=max_number_rules, dataset=training_set)
    initialization_strategy = DataInitialization(data_set=training_set)
    mutation_strategy = OneGeneMutation()

    # TODO remove fixed seed
    # random.seed(0)

    for rule in [2,3,4]:
        for mutation_rate in [.01, .05, .1, .2, .5]:
            print("rule:%d mutation:%.2f" % (rule, mutation_rate) )
            for run in range(0,30):
                initial_number_rules = rule

                genetic_algorithm = GeneticAlgorithm(population_size=population_size,
                                                     replacement_rate=replacement_rate,
                                                     mutation_rate=mutation_rate,
                                                     use_elitism=use_elitism,
                                                     use_default=use_default,
                                                     initial_number_rules=initial_number_rules,
                                                     stop_criterion=stop_criterion,
                                                     selection_strategy=selection_strategy,
                                                     crossover_strategy=crossover_strategy,
                                                     fitness_function=fitness_function,
                                                     initialization_strategy=initialization_strategy,
                                                     mutation_strategy=mutation_strategy,
                                                     attributes=data_set_attributes,

                                                     test_set=test_set)

                dimensions = genetic_algorithm.calculate_rule_size() * initial_number_rules
                writer = Writer(output_path+'ga_iris_%d_%d_%d_%s_%s_%.2f_%.2f_%d.with_positions' % (population_size, dimensions, initial_number_rules,
                                                                           str.lower(selection_strategy.__class__.__name__),
                                                                           str.lower(crossover_strategy.__class__.__name__),
                                                                                mutation_rate,
                                                                                replacement_rate,
                                                                                run))

                genetic_algorithm.writer = writer

                genetic_algorithm.training_set = training_set
                genetic_algorithm.learn()
                accuracy_training_set = genetic_algorithm.calculate_accuracy(training_set)
                accuracy_test_set = genetic_algorithm.calculate_accuracy(test_set)

                print(genetic_algorithm.get_best_individual().print_individual())
                print("Accuracy Training Set: " + str(accuracy_training_set))
                print("Accuracy Test Set: " + str(accuracy_test_set))

if __name__ == "__main__":
    output_path = sys.argv[1]

    main(output_path)


#Create a contact book

contact_book = {
    "John": {
        "Full Name": "John Henry",
        "Phone": ["123", "456"],
        "Email": ["john@gmail.com", "john.work@live.com"],
        "Address": "Hanoi",
        "Note": "This is John",
        "Tag": ["friend", 'work']
    },
    "Rossa": {
        "Phone": ["321"],
        "Email": ["rosse@gmail.com", "rossa.work@live.com"],
        "Address": "HCM",
        "Note": "This is Rossa",
        "Tag": ['work']
    }
}
#Show menu
def show_menu():
    print('''Please select program mode:
        1) Show all contacts
        2) Add new contact
        3) Edit existing contact
        4) Delete existing contact
        5) Search contact by name
        6) Search contact by tag
        7) Thoat chuong trinh
          ''')
#Select program mode
def get_choice():
    return input("Please select mode: ")

#define function to show all contacts
def show_all_contact(contact):
    print(contact)
#define function to add new contact
def add_new_contact(contact):
    fields = [
        {
            "name": "Name",
            "loop": False,
            "display_text": "Please input contact name: "
        },
        {
            "name": "Phone",
            "loop": True,
            "display_text": "Please input phone number (multiple number allowed, stop if it's blank): "
        },
        {
            "name": "Email",
            "loop": True,
            "display_text": "Please input email (multiple email allowed, stop if it's blank): "
        },
        {
            "name": "Address",
            "loop": False,
            "display_text": "Please input address: "
        },
        {
            "name": "Note",
            "loop": False,
            "display_text": "Note: "
        },
        {
            "name": "Tag",
            "loop": True,
            "display_text": "Please input tag (multiple email allowed, stop if it's blank): "
        }
    ]
    new_contact = {}
    for field in fields:
        if field["loop"]:
            value_list = []
            print(field["display_text"])
            while True:
                value = input()
                if value == "":
                    break
                value_list.append(value)
            new_contact.update({field["name"]: value_list})
        else:
            value = input(field["display_text"])
            new_contact.update({field["name"]: value})
    name = new_contact["Name"]
    del new_contact["Name"]
    contact.update({name: new_contact})
    return contact

#Remove contact
def remove_contact(contact):
    contact_remove = input("Please input contact name that you want to delete:")
    if contact_remove in contact_book.keys():
        del contact_book[contact_remove]
    return contact

#Edit existing contact:
def edit_contact(contact):
    print("Current contacts in book:")
    print(contact.keys())
    while True:
        contact_edit = input("Please input contact name that you want to edit:")
        if contact_edit in contact.keys():
            print("Which parameter do you want to change?")
            print(contact[contact_edit].keys())
            edit_parameter = input("Please input information that you want to change:")
            if edit_parameter in contact[contact_edit].keys():
                value_change = input("Please input new value:")
                contact[contact_edit][edit_parameter] = value_change
                break
            else:
                continue
        else:
            continue
    return contact

#Search contact by contact name
def search_by_name(contact):
    while True:
        search_name = input("Please enter contact name:")
        if search_name in contact.keys():
            print(search_name, ":", contact.get(search_name))
            break
        else:
            print(search_name, " is not in contact book. Please enter name correctly!")
            continue
#Search contact by tag
def search_by_tag(contact):
    condition = False
    while (condition == False):
        search_tag = input("Please enter tag field:")
        for key in contact_book:
            for tag in contact_book[key]["Tag"]:
                if tag == search_tag:
                    print(key, ":", contact_book.get(key))
                    condition = True

#main
while True:
    show_menu()
    user_choice = get_choice()
    print("You select mode: " + user_choice)

    if user_choice == "7":
        break
    elif user_choice == "1":
        show_all_contact(contact_book)
    elif user_choice == "2":
        contact_book = add_new_contact(contact_book)
    elif user_choice == "3":
        contact_book = edit_contact(contact_book)
    elif user_choice == "4":
        contact_book = remove_contact(contact_book)
    elif user_choice == "5":
        search_by_name(contact_book)
    elif user_choice == "6":
        search_by_tag(contact_book)


DATA = [
    {
        'name': 'Facundo',
        'age': 72,
        'organization': 'Platzi',
        'position': 'Technical Coach',
        'language': 'python',
    },
    {
        'name': 'Luisana',
        'age': 33,
        'organization': 'Globant',
        'position': 'UX Designer',
        'language': 'javascript',
    },
    {
        'name': 'Héctor',
        'age': 19,
        'organization': 'Platzi',
        'position': 'Associate',
        'language': 'ruby',
    },
    {
        'name': 'Gabriel',
        'age': 20,
        'organization': 'Platzi',
        'position': 'Associate',
        'language': 'javascript',
    },
    {
        'name': 'Isabella',
        'age': 30,
        'organization': 'Platzi',
        'position': 'QA Manager',
        'language': 'java',
    },
    {
        'name': 'Karo',
        'age': 23,
        'organization': 'Everis',
        'position': 'Backend Developer',
        'language': 'python',
    },
    {
        'name': 'Ariel',
        'age': 32,
        'organization': 'Rappi',
        'position': 'Support',
        'language': '',
    },
    {
        'name': 'Juan',
        'age': 17,
        'organization': '',
        'position': 'Student',
        'language': 'go',
    },
    {
        'name': 'Pablo',
        'age': 32,
        'organization': 'Master',
        'position': 'Human Resources Manager',
        'language': 'python',
    },
    {
        'name': 'Lorena',
        'age': 56,
        'organization': 'Python Organization',
        'position': 'Language Maker',
        'language': 'python',
    },
]

def run():
    # all_python_devs = [worker["name"] for worker in DATA if worker["language"] == "python"]  # Contendrá solo los nombres x list comprehensions

    all_python_devs = list(filter(lambda worker : worker["language"] == "python", DATA))
    all_python_devs = list(map(lambda worker : worker["name"], all_python_devs))

    for worker in all_python_devs:
        print(worker)

    print()

    #Traer los nombres de todos los que trabajan en platzi

    # all_platzi_devs = [worker["name"] for worker in DATA if worker["organization"]=="Platzi"]

    all_platzi_devs = list(filter(lambda worker : worker["organization"] == "Platzi" , DATA))
    all_platzi_devs = list(map(lambda worker : worker["name"] , all_platzi_devs))

    for worker in all_platzi_devs:
        print(worker)

    print()

    # for worker in all_platzi_devs:
    #     print(worker)    #Explicación: DATA hace referencia a la list de diccionarios de arriba. Worker hace referencia a cada diccionario que lo compone en la recorrida. Lo que está entre corchetes al lado de worker hace referencia a la key del diccionario que quiero traer. Si no pusiera nada, me traeria todo el diccionario que cumple el requisito que está despues del if

    # # print(all_python_devs)

    # adults = list(filter(lambda worker : worker["age"] > 18, DATA))
    # adults = list(map(lambda worker: worker["name"], adults))

    adults = [worker["name"] for worker in DATA if worker["age"] > 18]

    for worker in adults:
        print(worker)

    print()

    #Explicación: En la primera high order function - filter, sobre mi lista de diccionarios inicial, armo una lista de diccionarios donde solo me voy a quedar con aquellos diccionarios donde la edad del trabajador sea mayor a 18 años. Esto me va a traer una nueva lista de diccionarios pero con todas las key y values dentro. No solo el nombre
    #Explicación: En la segunda high order function - map, sobre mi lista "adults" ya conformada y filtrada, yo voy transformarla mediante un maps para que solo quede una unica key y value y la misma sea "name".

    old_people = list(map(lambda worker : {**worker , **{"old": worker["age"] > 70}}, DATA))  # Solo funciona en python 3.9.1 usando el "|". En python 3.8 se hace como lo hice recien

    # for worker in old_people:
    #     print(worker)

    # old_people = [{**worker, **{'old': worker['age'] > 70}} for worker in DATA]

    for worker in old_people:
        print(worker)

    print("fin")

if __name__ == '__main__':
    run()


import os
import pandas as pd
from PIL import Image
import numpy as np

import torch
import torch.nn.functional as F
import torchvision.datasets as datasets
from torch.utils.data import Dataset, DataLoader
import torchvision.models as models
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import cv2
import copy
import sys
import time

device = torch.device("cuda")

# 實作一個繼承 torch.utils.data.Dataset 的 Class 來讀取圖片
class Adverdataset(Dataset):
    def __init__(self, root, label, transforms):
        # 圖片所在的資料夾
        self.root = root
        # 由 main function 傳入的 label
        self.label = torch.from_numpy(label).long()
        # 由 Attacker 傳入的 transforms 將輸入的圖片轉換成符合預訓練模型的形式
        self.transforms = transforms
        # 圖片檔案名稱的 list
        self.fnames = []

        for i in range(200):
            self.fnames.append("{:03d}".format(i))

    def __getitem__(self, idx):
        # 利用路徑讀取圖片
        img = Image.open(os.path.join(self.root, self.fnames[idx] + '.png'))
        # 將輸入的圖片轉換成符合預訓練模型的形式
        img = self.transforms(img)
        # 圖片相對應的 label
        label = self.label[idx]
        return img, label

    def __len__(self):
        # 由於已知這次的資料總共有 200 張圖片 所以回傳 200
        return 200

class Best_Attacker:
    def __init__(self, img_dir, label):
        self.model = models.densenet121(pretrained = True)
        self.model.cuda()
        self.model.eval()
        self.iters = 10
        self.alpha = 2/255
        self.mean = [0.485, 0.456, 0.406]
        self.std = [0.229, 0.224, 0.225]
        # 把圖片 normalize 到 0~1 之間 mean 0 variance 1
        self.normalize = transforms.Normalize(self.mean, self.std, inplace=False)
        transform = transforms.Compose([
                        transforms.Resize((224, 224), interpolation=3),
                        transforms.ToTensor(),
                        self.normalize
                    ])
        # 利用 Adverdataset 這個 class 讀取資料
        self.dataset = Adverdataset(img_dir, label, transform)

        self.loader = torch.utils.data.DataLoader(
                self.dataset,
                batch_size = 1,
                shuffle = False)

    def L_infinity(self, origin, new, epsilon):
        difference = origin - new
        max_diff = torch.max(torch.abs(difference))
        return max_diff

    def attack(self, epsilon):
        # 存下一些成功攻擊後的圖片 以便之後顯示
        adv_examples = []
        wrong, fail, success = 0, 0, 0
        img = []
        count = 1
        for (data, target) in self.loader:
            data, target = data.to(device), target.to(device)
            data_raw = copy.deepcopy(data)
            # 將圖片丟入 model 進行測試 得出相對應的 class
            output = self.model(data)
            init_pred = output.max(1, keepdim=True)[1]

            # 如果 class 錯誤 就不進行攻擊
            if init_pred.item() != target.item():
                wrong += 1
                data_raw = data_raw * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                data_raw = data_raw.squeeze().detach().cpu().numpy()
                img.append(data_raw)
                continue

            # 如果 class 正確 就開始計算 gradient 進行攻擊
            for i in range(self.iters):
                data.requires_grad = True
                output = self.model(data)
                loss = F.nll_loss(output, target)
                data_grad = torch.autograd.grad(loss, data)[0]
                data = data + self.alpha * data_grad.sign()
                eta = torch.clamp(data - data_raw, min=-epsilon, max=epsilon)
                data = (data_raw + eta).detach()
                #data = torch.clamp(data_raw + eta, min=0, max=1).detach()
            perturbed_data = data

            # 再將加入 noise 的圖片丟入 model 進行測試 得出相對應的 class
            output = self.model(perturbed_data)
            final_pred = output.max(1, keepdim=True)[1]
            #print('Finish :',count)
            count += 1
            if final_pred.item() == target.item():
                #print("fail")
                # 辨識結果還是正確 攻擊失敗
                adv_ex = perturbed_data * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                adv_ex = adv_ex.squeeze().detach().cpu().numpy()
                img.append(adv_ex)
                fail += 1
            else:
                # 辨識結果失敗 攻擊成功
                success += 1
                #print('success')
                adv_ex = perturbed_data * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                adv_ex = adv_ex.squeeze().detach().cpu().numpy()
                img.append(adv_ex)

        final_acc = (fail / (wrong + success + fail))
        print("Epsilon: {}\tTest Accuracy = {} / {} = {}\n".format(epsilon, fail, len(self.loader), final_acc))
        return img, final_acc

if __name__ == '__main__':
    t1 = time.time()
    # 讀入圖片相對應的 label
    df = pd.read_csv(sys.argv[1] + "/labels.csv")
    df = df.loc[:, 'TrueLabel'].to_numpy()
    label_name = pd.read_csv(sys.argv[1] + "/categories.csv")
    label_name = label_name.loc[:, 'CategoryName'].to_numpy()
    # new 一個 Attacker class
    attacker = Best_Attacker(sys.argv[1] + "/images", df)
    # 要嘗試的 epsilon
    epsilons = [0.1]

    accuracies, examples = [], []

    # 進行攻擊 並存起正確率和攻擊成功的圖片
    for eps in epsilons:
        #ex, acc = attacker.attack(eps)
        img, acc = attacker.attack(eps)
        accuracies.append(acc)
        #examples.append(ex)

    number = 0
    save_path = sys.argv[2]
    if not os.path.isdir(save_path):
        os.mkdir(save_path)
    save_path = save_path + '/'
    for ex in img:
        ex = 255 * np.array(ex).astype(np.float32)
        ex = np.swapaxes(ex,0,1)
        ex = np.swapaxes(ex,1,2)
        #print(ex.shape)
        ex[:,:,[0,2]] = ex[:,:,[2,0]] # chage the color channel
        if len(str(number)) == 1:
            name = '00' + str(number)
            cv2.imwrite(save_path+str(name)+'.png', ex)
        elif len(str(number)) == 2:
            name = '0' + str(number)
            cv2.imwrite(save_path+str(name)+'.png', ex)
        else:
            cv2.imwrite(save_path+str(number)+'.png', ex)
        number += 1
    t2 = time.time()
    print("Execute time :" + str(t2-t1))


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

options = webdriver.ChromeOptions()
options.add_argument(r"user-data-dir=C:\Github\python-whatsapp-messages\whatsapp-web\data")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get('https://web.whatsapp.com')

time.sleep(20)

driver.find_element(By.XPATH, "//*[@title='Eu']").click()

time.sleep(5)

message_field = driver.find_element(By.XPATH, "//div[@class='to2l77zo gfz4du6o ag5g9lrv bze30y65 kao4egtt']//p[@class='selectable-text copyable-text iq0m558w g0rxnol2']")
message_field.send_keys("Message to be sent!")

time.sleep(5)

message_field.send_keys(Keys.ENTER)

time.sleep(5)


# 문제 출처 : https://www.acmicpc.net/problem/1021

from sys import stdin
from collections import deque

n, p = map(int, stdin.readline().split())
arr = list(map(int, stdin.readline().split()))
deque = deque([i for i in range(1, n+1)])

count = 0

for num in arr:
    if deque[0] == num:
        deque.popleft()
        continue

    left_move = deque.index(num)
    right_move = len(deque) - left_move

    if left_move <= right_move:
        deque.rotate(-left_move)
        deque.popleft()
        count += left_move
    else:
        deque.rotate(right_move)
        deque.popleft()
        count += right_move

print(count)


import sys
sys.path.append('../')
sys.path.append('../../')

from main import app
from unittest import TestCase, main

class TestApp(TestCase):

    def setUp(self):
        self.test_app = app.test_client()

    def test_get_index(self):
        response = self.test_app.get('/')
        self.assertEqual(200, response.status_code)

    def test_db_connection(self):
        response = self.test_app.get('/rank/anything')
        self.assertEqual(200, response.status_code, 'Database not found')

if __name__ == '__main__':
    main()


from django import forms
from myapp1.models import OrderItem

class OrderItemForm(forms.ModelForm):
    class Meta:
        model = OrderItem
        fields = ['item', 'client', 'items_ordered']
        widgets = {
            'client': forms.RadioSelect(choices=[
                ('Client A', 'Client A'),
                ('Client B', 'Client B'),
                ('Client C', 'Client C'),
            ]),
        }
        labels = {
            'items_ordered': 'Quantity',
            'client': 'Client Name',
        }

    class InterestForm(forms.Form):
        interested = forms.TypedChoiceField(
            choices=((1, 'Yes'), (0, 'No')),
            coerce=lambda x: bool(int(x)),
            widget=forms.RadioSelect,
            label='Are you interested?'
        )
        quantity = forms.IntegerField(min_value=1, initial=1, label='Quantity')
        comments = forms.CharField(widget=forms.Textarea, required=False, label='Additional Comments')


import os
import sys
import torch
import numpy as np
import time

cur_path = os.path.abspath(os.path.dirname(__file__))
root_path = os.path.split(cur_path)[0]
sys.path.append(root_path)

from torchvision import transforms
from PIL import Image
from segmentron.utils.visualize import get_color_pallete
from segmentron.models.model_zoo import get_segmentation_model
from segmentron.utils.options import parse_args
from segmentron.utils.default_setup import default_setup
from segmentron.config import cfg

def demo():
    args = parse_args()
    args.test = True

    ##############################################
    # args.config_file = "configs/trans10kv2/trans2seg/trans2seg_medium_all_sber.yaml"
    # args.input_img = "tools/4.jpg"
    ##############################################

    cfg.update_from_file(args.config_file)
    cfg.update_from_list(args.opts)
    cfg.PHASE = 'test'
    cfg.ROOT_PATH = root_path

    ##############################################
    # cfg.TEST.TEST_MODEL_PATH = "./workdirs/trans10kv2/trans2seg_medium/Sber2400_50_All_classes.pth"
    # cfg.DATASET.NAME = "sber_dataset_all"
    ##############################################

    # cfg.TEST.TEST_MODEL_PATH = args.model_path
    cfg.check_and_freeze()
    print(cfg.TEST.TEST_MODEL_PATH)

    default_setup(args)

    # create output folders
    output_dir = os.path.join(cfg.VISUAL.OUTPUT_DIR, 'vis_result_{}_{}_{}_{}'.format(
        cfg.MODEL.MODEL_NAME, cfg.MODEL.BACKBONE, cfg.DATASET.NAME, cfg.TIME_STAMP))
    if not os.path.exists(output_dir):
        os.makedirs(output_dir+"/Flipped")
        os.makedirs(output_dir+"/Orig")
        os.makedirs(output_dir+"/Merged_mask")
        os.makedirs(output_dir+"/Orig_confidence")
        os.makedirs(output_dir+"/Flipped_confidence")

    # pathes for different images
    confidence_flipped_dir=output_dir+"/Flipped_confidence"
    confidence_output_dir=output_dir+"/Orig_confidence"
    flipped_dir=output_dir+"/Flipped"
    merged_dir=output_dir+"/Merged_mask"
    output_dir=output_dir+"/Orig"

    # image transform
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(cfg.DATASET.MEAN, cfg.DATASET.STD),
    ])

    # create the model using the configuration
    model = get_segmentation_model().to(args.device)
    model.eval()

    # softmax layer for confidence
    softmax_layer = torch.nn.Softmax(dim=0)

    if os.path.isdir(args.input_img):
        img_paths = [os.path.join(args.input_img, x) for x in os.listdir(args.input_img) if "." in x]
    else:
        img_paths = [args.input_img]

    # print("Images for inference:")
    # print(img_paths)
    print("\n Output file path: ", output_dir)
    # print("\n CFG: /n", cfg)
    print("Dataset Name: ", cfg.DATASET.NAME)
    for img_path in img_paths:
        image = Image.open(img_path).convert('RGB')

        # getting the flipped image
        flipped_image = Image.open(img_path).convert('RGB')
        size_ = image.size
        flipped_image = flipped_image.transpose(method = Image.FLIP_LEFT_RIGHT)
        flipped_image = flipped_image.resize((cfg.TRAIN.BASE_SIZE, cfg.TRAIN.BASE_SIZE), Image.BILINEAR)
        flipped_image = transform(flipped_image).unsqueeze(0).to(args.device)

        image = image.resize((cfg.TRAIN.BASE_SIZE, cfg.TRAIN.BASE_SIZE), Image.BILINEAR)
        # images = transform(image).unsqueeze(0).to(args.device)
        image = transform(image).unsqueeze(0).to(args.device)

        # merging the two images in one batch
        images = torch.cat((image, flipped_image), 0)
        with torch.no_grad():
            output = model(images)

        # Get the mask
        pred = torch.argmax(output[0], 1)[0].cpu().data.numpy()
        pred_f = torch.argmax(output[0], 1)[1].cpu().data.numpy()
        output_norm = softmax_layer(output[0])
        confidence_all = torch.max(output_norm, 1)[0].cpu().data.numpy()*255

        mask = get_color_pallete(pred, cfg.DATASET.NAME)
        mask_f = get_color_pallete(pred_f, cfg.DATASET.NAME)
        mask = mask.resize(size_)
        mask_f = mask_f.resize(size_)
        mask_f = mask_f.transpose(method = Image.FLIP_LEFT_RIGHT)

        # get the result of cropped images (in this case no cropping just flipping)
        cropping_results = [np.array(mask), np.array(mask_f)]
        cropping_edges = [[0, 0, size_[0], size_[1]], [0, 0, size_[0], size_[1]]]

        outname = os.path.splitext(os.path.split(img_path)[-1])[0] + '.png'
        mask.save(os.path.join(output_dir, outname))
        mask_f.save(os.path.join(flipped_dir, outname))

        # Calc confidence
        confidence = np.array(confidence_all, dtype=np.uint8)[0]
        conf_img = Image.fromarray(confidence)
        conf_img = conf_img.resize(size_, Image.BILINEAR)
        conf_img.save(os.path.join(confidence_output_dir, outname))

        confidence_f = np.array(confidence_all, dtype=np.uint8)[1]
        conf_img_f = Image.fromarray(confidence_f)
        conf_img_f = conf_img_f.resize(size_, Image.BILINEAR)
        conf_img_f = conf_img_f.transpose(method = Image.FLIP_LEFT_RIGHT)
        conf_img_f.save(os.path.join(confidence_flipped_dir, outname))
        cropping_confidence = [conf_img, conf_img_f]
        # mask_f.save(os.path.join(flipped_dir, outname))

        # the result of the merged images
        merged_result = getMergedSemanticFromCrops(cropping_results, cropping_confidence, cropping_edges, "And", [size_[1], size_[0]])
        merged_result.save(os.path.join(merged_dir, outname))

# function merging images
def getMergedSemanticFromCrops(crops_result, crops_confidence, crops_edges, function, full_size):
    '''
    function for merging the results from two or more images
    '''

    palette_mirror = 0
    palette_glass = 1
    palette_OOS = 3
    palette_floor = 4
    palette_FU = 2
    palette_BG = 5

    #################################################################
    ####################### Using And function ######################
    #################################################################

    if function.lower() == "and":
        # rospyLogInfoWrapper("Using And for merging cropped images")
        orig_glass = crops_result[0]==palette_glass
        orig_mirror = crops_result[0]==palette_mirror
        orig_OOS = crops_result[0]==palette_OOS
        orig_floor = crops_result[0]==palette_floor
        orig_FU = crops_result[0]==palette_FU
        # classes = [np.ones(full_size) for _ in range(max_clasess)]
        # merged_classes = []
        for i in range(1, len(crops_result)):
            cropped_glass = crops_result[i]==palette_glass
            cropped_mirror = crops_result[i]==palette_mirror
            cropped_OOS = crops_result[i]==palette_OOS
            cropped_floor = crops_result[i]==palette_floor
            cropped_FU = crops_result[i]==palette_FU
            cropped_all_optical = np.logical_or(cropped_mirror, cropped_glass)
            cropped_all_optical = np.logical_or(cropped_all_optical, cropped_OOS)
            cropped_all_floor = np.logical_or(cropped_FU, cropped_floor)

            cropped_all_optical_extended = np.ones(full_size)
            cropped_all_optical_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_all_optical

            cropped_all_floor_extended = np.ones(full_size)
            cropped_all_floor_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_all_floor

            orig_glass = np.logical_and(cropped_all_optical_extended, orig_glass)
            orig_mirror = np.logical_and(cropped_all_optical_extended, orig_mirror)
            orig_OOS = np.logical_and(cropped_all_optical_extended, orig_OOS)
            orig_floor = np.logical_and(cropped_all_floor_extended, orig_floor)
            orig_FU = np.logical_and(cropped_all_floor_extended, orig_FU)

        background = np.logical_or(orig_glass, orig_mirror)
        background = np.logical_or(background, orig_OOS)
        background = np.logical_or(background, orig_floor)
        background = np.logical_or(background, orig_FU)
        background = np.logical_not(background)
        res = orig_glass * palette_glass
        res += orig_mirror * palette_mirror
        res += orig_OOS * palette_OOS
        res += orig_floor * palette_floor
        res += orig_FU * palette_FU
        res += background * palette_BG

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

    #################################################################
    ####################### Using Or function #######################
    #################################################################

    elif function.lower() == "or":
        # rospyLogInfoWrapper("Using And for merging cropped images")
        orig_glass = crops_result[0]==palette_glass
        orig_mirror = crops_result[0]==palette_mirror
        orig_OOS = crops_result[0]==palette_OOS
        orig_floor = crops_result[0]==palette_floor
        orig_FU = crops_result[0]==palette_FU
        # classes = [np.ones(full_size) for _ in range(max_clasess)]
        # merged_classes = []
        for i in range(1, len(crops_result)):
            cropped_glass = crops_result[i]==palette_glass
            cropped_mirror = crops_result[i]==palette_mirror
            cropped_OOS = crops_result[i]==palette_OOS
            cropped_floor = crops_result[i]==palette_floor
            cropped_FU = crops_result[i]==palette_FU
            # cropped_all_optical = np.logical_or(cropped_mirror, cropped_glass)
            # cropped_all_optical = np.logical_or(cropped_all_optical, cropped_OOS)
            # cropped_all_floor = np.logical_or(cropped_FU, cropped_floor)

            cropped_glass_extended = np.zeros(full_size)
            cropped_glass_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_glass

            cropped_mirror_extended = np.zeros(full_size)
            cropped_mirror_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_mirror

            cropped_OOS_extended = np.zeros(full_size)
            cropped_OOS_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_OOS

            cropped_floor_extended = np.zeros(full_size)
            cropped_floor_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_floor

            cropped_FU_extended = np.ones(full_size)
            cropped_FU_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_FU

            orig_glass = np.logical_or(cropped_glass_extended, orig_glass)
            orig_free = np.logical_not(orig_glass)
            orig_mirror = np.logical_and(np.logical_or(cropped_mirror_extended, orig_mirror), orig_free)
            orig_free = np.logical_and(orig_free, np.logical_not(orig_mirror))
            orig_OOS = np.logical_and(np.logical_or(cropped_OOS_extended, orig_OOS), orig_free)
            orig_free = np.logical_and(orig_free, np.logical_not(orig_OOS))
            orig_floor = np.logical_and(np.logical_or(cropped_floor_extended, orig_floor), orig_free)
            orig_FU = np.logical_and(cropped_FU_extended, orig_FU)

        background = np.logical_or(orig_glass, orig_mirror)
        background = np.logical_or(background, orig_OOS)
        background = np.logical_or(background, orig_floor)
        background = np.logical_or(background, orig_FU)
        background = np.logical_not(background)
        res = orig_glass * palette_glass
        res += orig_mirror * palette_mirror
        res += orig_OOS * palette_OOS
        res += orig_floor * palette_floor
        res += orig_FU * palette_FU
        res += background * palette_BG

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

    #################################################################
    #################### Using confidence values# ###################
    #################################################################

    elif function.lower() == "confidence":

        confidence_extended_all = [crops_confidence[0]]
        results_extended_all = [crops_result[0]]
        for i in range(1, len(crops_confidence)):

            cropped_confidence_extended = np.zeros(full_size)
            cropped_confidence_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = crops_confidence[i]
            confidence_extended_all.append(cropped_confidence_extended)

            cropped_segmentation_extended = np.zeros(full_size)
            cropped_segmentation_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = crops_result[i]
            results_extended_all.append(cropped_segmentation_extended)

        max_confidence_args = np.argsort(confidence_extended_all, axis=0)
        result_sorted_confidence = np.take_along_axis(np.array(results_extended_all), max_confidence_args, axis=0)
        res = result_sorted_confidence[-1]
        # rospyLogInfoWrapper("result_max_confidence shape"+str(result_sorted_confidence.shape))
        # rospyLogInfoWrapper("result_max_confidence[0][1]"+str(max_confidence_args[0][0][0:4]))
        # rospyLogInfoWrapper("result_max_confidence[0][2]"+str(max_confidence_args[2][0][0:4]))

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

if __name__ == '__main__':
    demo()


def selection_enclos(table, num) :
    res = []
    for animaux in table :
        if animaux['enclos'] == num :
            res.append(animaux)
    return res

animaux = [ {'nom':'Medor', 'espece':'chien', 'age':5, 'enclos':2},
{'nom':'Titine', 'espece':'chat', 'age':2, 'enclos':5},
{'nom':'Tom', 'espece':'chat', 'age':7, 'enclos':4},
{'nom':'Belle', 'espece':'chien', 'age':6, 'enclos':3},
{'nom':'Mirza', 'espece':'chat', 'age':6, 'enclos':5}]
print(selection_enclos(animaux, 5))
assert selection_enclos(animaux, 5) == [{'nom':'Titine', 'espece':'chat', 'age':2, 'enclos':5}, {'nom':'Mirza', 'espece':'chat', 'age':6, 'enclos':5}]
assert selection_enclos(animaux, 2) == [{'nom':'Medor', 'espece':'chien', 'age':5, 'enclos':2}]
assert selection_enclos(animaux, 7) == []

def trouver_intrus(tab, g,d):
    '''
    Paramètres :
        - tab un tableau de nombres dont tous les éléments sont présents exactement 3 fois à la suite sauf un élément qui est présent une unique fois.
        - g et d sont des entiers multiples de 3.
    '''
    if g == d :
        return tab[g]
    else :
        nombre_de_triplets = (d-g) // 3
        indice = g + 3 * (nombre_de_triplets // 2)
        if tab[indice]==tab[indice+1] :
            return trouver_intrus(tab,indice+1,d)
        else :
            return trouver_intrus(tab,g,indice)


# coding=utf-8
import webapp2
import logging

from controllers.restore import ExportHandler, ExportHttpWorker, ExportWorker
from controllers.event import SaveEventsHandler, LastEventsHandler, UserEventsHandler, EventsCountHandler

class BlankPageHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('')

app = webapp2.WSGIApplication([(r'/', BlankPageHandler),
                               (r'/api/user/(\w+)', SaveEventsHandler),
                               (r'/count', EventsCountHandler),
                               (r'/get', LastEventsHandler),
                               (r'/get/(\w+)', UserEventsHandler),
                               (r'/export/worker/http', ExportHttpWorker),
                               (r'/export/worker', ExportWorker),
                               (r'/export', ExportHandler)], debug=True)

def handle_404(request, response, exception):
    logging.exception(exception)
    response.write('Oops! I could swear this page was here!')
    response.set_status(404)

def handle_500(request, response, exception):
    logging.exception(exception)
    response.write('success')
    response.set_status(200)

app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500


# python -m pip install -r .\requirements.txt
# python .\merge.py .\annotatedPdfs\ final.pdf

import PyPDF2
import os
import sys

def merge_pdfs(pdf_dir, output_filename):
    pdf_writer = PyPDF2.PdfWriter()

    # Get all PDF files in the given directory
    files = [os.path.join(pdf_dir, file) for file in os.listdir(pdf_dir) if file.endswith('.pdf')]

    for file in files:
        with open(file, 'rb') as pdf_file:
            pdf_reader = PyPDF2.PdfReader(pdf_file)

            for page in range(len(pdf_reader.pages)):
                pdf_writer.add_page(pdf_reader.pages[page])

    with open(output_filename, 'wb') as merged_pdf:
        pdf_writer.write(merged_pdf)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python merge.py <PDF_DIRECTORY> <OUTPUT_FILENAME>")
        sys.exit(1)

    pdf_dir = sys.argv[1]
    output_filename = sys.argv[2]

    # Merge the PDFs into a single file
    merge_pdfs(pdf_dir, output_filename)


import requests
from bs4 import BeautifulSoup

# セッションの生成
session = requests.session()

# ログイン
url = "http://somewhere/?controller=login&action=login"
data = { # from Form Data
    "login.x": "39", # <someValue>
    "login.y": "12", # <someValue>
    "accountName": "<ID>", # <ID>
    "password": "<PW>" # <PW>
}

response = session.post(url, data=data) # post方式
response.raise_for_status()
# print(response.text)

soupHome = BeautifulSoup(response.text, "html.parser")
name = soupHome.select_one("#profile-nav > div.menuBody > div.data > div.item.name > a")
print("name: ", name.string)

# 登録時間を取得
url = "http://somewhere/?controller=blog&action=top"
response = session.get(url)
response.raise_for_status()
# print(response.text)

soup = BeautifulSoup(response.text, "html.parser")
regTime = soup.select_one("div.regTime")
print("regTime: ", regTime.string)

# ログインが可能になれば、アクセスできる情報が増える
# ログインする方法を簡単にまとめると、
#  1. 開発者ツールを用いて、どこでログインの処理が行われているのかを確認する
#  2. その際、どこに（;php）何で（;方式）リクエストをするのかを確認する
#  3. pythonで上記(;1., 2.)を実装する
#    3-1. requestモヂュールでsessionを生成する
#    3-2. sessionにリクエストの方式を選択する
#    3-3. raise_for_status関数でログイン処理を行う


import vqa_gradients

import numpy as np
from scipy.linalg import expm
from scipy.stats import unitary_group
from scipy.misc import derivative
import functools as ft
tp = lambda a,b: np.tensordot(a,b,axes=0)

n_qubits = 3

H = 1/np.sqrt(2) * np.array([[1,1],[1,-1]])
X = np.array([[0,1],[1,0]])

M = ft.reduce(tp, np.repeat(H, n_qubits))
Psi = np.zeros((2**n_qubits,1)); Psi[0] = 1
G = np.diag(np.random.choice([1,2,3,4,5,6,7,8,9,10], 2**n_qubits))
W = vqa_gradients.complete_graph(2**n_qubits)/2**n_qubits
#W = np.diag(np.random.choice([1,2,3,4,5,6,7,8,9,10], 2**n_qubits))
R = vqa_gradients.find_R_from_qualities(np.linalg.eigvals(W))
rnd1 = unitary_group.rvs(2**n_qubits)
rnd2 = unitary_group.rvs(2**n_qubits)

def E(param):
    U = ft.reduce(np.matmul,
              [rnd2,
               expm(-1j*param*W),
               rnd1,
               Psi])
    U_dagger = U.conj().T
    return ft.reduce(np.matmul, [U_dagger,G,U])
E = np.vectorize(E)

x = np.array([(2*np.pi*i)/(2*R+1) for i in range(-R,R+1)])
y = E(x)
s = vqa_gradients.Series(x,y)
s.plot(function=E)

rnd = np.random.random()*6-3
print(s.gradient(rnd))
print(derivative(E,rnd,dx=1e-6)[0,0])


class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        num = 0
        for i, n in enumerate(digits[::-1]):
            num += n * 10 ** i
        num += 1
        result = []
        while num > 0:
            result.append(num % 10)
            num //= 10
        return result[::-1]

solution = Solution()
print(solution.plusOne([5,11,9]))


from ._base import Function
from .special import null
from .exceptions import *

class Slot(Function):

    open = True

    __slots__ = (
        'slots',
        'argslots',
        'kwargslots',
        )

    def __init__(self, name = None):
        self.slots = 1
        if name is None:
            self.argslots = 1
            self.kwargslots = []
        else:
            self.argslots = 0
            self.kwargslots = [name]
        super().__init__(name = name)
        # raise FuncyException("Cannot close a Slot function.")
    def __call__(self, arg):
        return arg
    def evaluate(self):
        try:
            return self.tempVal
        except AttributeError:
            return null
    @property
    def value(self):
        return self.evaluate()
    def register_downstream(self, registrant):
        # self.downstream.add(registrant)
        pass

    # def evaluate(self):
    #     key = self.name
    #     try:
    #         try:
    #             if key is None:
    #                 return GLOBEKWARGS[key].pop()
    #             else:
    #                 return GLOBEKWARGS[key]
    #         except KeyError:
    #             return GLOBEKWARGS.setdefault(key, GLOBEKWARGS[None].pop())
    #     except IndexError:
    #         return null


class Stack:

    def __init__(self, *args):
        self.body = list(args)
        self.permitted_count = 100

    def push(self, new_item):
        if len(self.body) < self.permitted_count:
            self.body = self.body + [new_item]
            return self.body

    def pop(self):
        last_num = self.body[-1]
        self.body = self.body[:-1]
        return last_num

    def size(self):
        return len(self.body)

    def back(self):
        return self.body[-1]

    def clear(self, answer):
        if answer == 'y':
            self.body = []
            return self.body

    def show(self):
        print(self.body)

def exit():
    print("Bye")

command = ""

stack = Stack()

if __name__ == '__main__':

    while command != "exit":

        command = input("Enter the command: ")
        if command == 'push':
            input_number = input("Enter a number: ")
            stack.push(input_number)
            print("Ok")
        elif command == 'pop':
            last_num = stack.pop()
            print(last_num)
        elif command == 'show':
            stack.show()
        elif command == 'size':
            stack_len = stack.size()
            print(stack_len)
        elif command == 'back':
            print(stack.body[-1])
        elif command == 'clear':
            input_answer = input("Clear the list, yes or no [y/n]? ")
            stack.clear(input_answer)
            print("Ok")
        else:
            print("Bye")


"""
- `File`: error_filter.py

- `Author`: Me

- `Email`: 0

- `Github`: 0

- `Description`: Filter comamnd with error contents
"""

from base_filter import BaseFilter

class ErrorFilter(BaseFilter):
    """
    Actual implementation for filtering commands with error contents
    """
    def _filter(self, commands):
        """
        Codes for filtering commands with error contents

        Parameters:

        - `commands`: Array of command objects

        Return:

        - `array of commands`
        """
        ret = []

        for command in commands:
            error = command['error']
            if error == '':
                ret.append(command)

        return ret


class NumArray:
    def __init__(self, nums):
        n = len(nums)
        if n == 0:
            return
        psum = [0] * n
        psum[0] = nums[0]
        for i in range(1, n):
            psum[i] = psum[i-1] + nums[i]
        self.psum = psum
        self.nums = nums

    def sumRange(self, i, j):
        if not self.psum:
            return 0
        else:
            return self.psum[j] - self.psum[i] + self.nums[i]