import requests
import time
from bs4 import BeautifulSoup
import json
import csv
import sqlite3

# GRAB LIST OF GROUP'S PUUIDs
# EVERY 30 MINUTES CHECK FOR EVERYONE

def get_all_puuids():
    # Connect to the SQLite database
    conn = sqlite3.connect('user_data.db')
    cursor = conn.cursor()

    # Retrieve the puuid of all users
    cursor.execute('''SELECT puuid FROM users''')
    puuids = cursor.fetchall()

    cursor.execute('''SELECT username FROM users''')
    usernames = cursor.fetchall()

    puuidsDictionary = {}
    for i in range(len(puuids)):
      puuidsDictionary[usernames[i][0]] = puuids[i][0]
    # Close the connection
    conn.close()

    return puuidsDictionary

#format: killer_name, killer_gun, killer_gun_media, victim_name, victim_gun, victim_gun, time_in_match, time_match_start
most_recent_eco = ('plumyum#BZB','spectre', 'https://media.valorant-api.com/weapons/462080d1-4035-2937-7c09-27aa2a5c27a7/displayicon.png','some shitter','classic', 'https://media.valorant-api.com/weapons/29a0cfab-485b-f5d5-779a-b59f85e204a8/displayicon.png', 0, 0)

#format: eco_checker[killer_gun][victim_gun]
# Load the JSON data from the file
with open('eco_checker.json', 'r') as file:
    eco_checker = json.load(file)

# Function that inserts new player into database
def insertPlayer(username, puuid, ecoKills=0, headshots=0, bodyshots=0, legshots=0, lastGame='0'):
  conn = sqlite3.connect('user_data.db')
  cursor = conn.cursor()

  cursor.execute('''
    INSERT INTO users (username, puuid, ecoKills, headshots, bodyshots, legshots, lastGame)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  ''', (username, puuid, ecoKills, headshots, bodyshots, legshots, lastGame))

  # Commit the changes and close the connection
  conn.commit()
  conn.close()

  print("Data has been inserted into the 'users' table.")

# Function that allows SQL SELECT command to be use
def get_by_puuid(keyVal, puuid):
    # Connect to the SQLite database
    conn = sqlite3.connect('user_data.db')
    cursor = conn.cursor()

    # Execute a SELECT query with a WHERE clause to retrieve the keyVal value
    cursor.execute(f'SELECT {keyVal} FROM users WHERE puuid = ?', (puuid,))

    # Fetch the result

    returnVal = cursor.fetchone()

    # Close the connection
    conn.close()

    if returnVal:
        return returnVal[0]  # Extract the keyVal value from the result
    else:
        return None  # Player with the provided puuid not found

# Function that allows SQL UPDATE command to be use
def update_by_puuid(keyVal, new_keyVal_value, puuid):
    # Connect to the SQLite database
    conn = sqlite3.connect('user_data.db')
    cursor = conn.cursor()

    # Execute an UPDATE query with a WHERE clause to update the keyVal value
    cursor.execute(f'UPDATE users SET {keyVal} = ? WHERE puuid = ?', (new_keyVal_value, puuid))

    # Commit the changes and close the connection
    conn.commit()
    conn.close()

# Function that inserts game data into database
def insert_game_log(player_id, game_date, stats):
    # Connect to the SQLite database
    conn = sqlite3.connect('user_data.db')
    cursor = conn.cursor()

    # Insert a new game log
    cursor.execute('''
        INSERT INTO game_logs (player_id, game_date, stats)
        VALUES (?, ?, ?)
    ''', (player_id, game_date, stats))

    # Delete oldest game logs if there are more than 10 for this player
    cursor.execute('''
        DELETE FROM game_logs
        WHERE id NOT IN (
            SELECT id FROM game_logs WHERE player_id = ? ORDER BY game_date DESC LIMIT 10
        ) AND player_id = ?
    ''', (player_id, player_id))
    print("Game log updated!")

    # Commit the changes and close the connection
    conn.commit()
    conn.close()

# Function that gets the most recent game data of a player
def get_recent_game_stats(player_id, num_games=1):
    # Connect to the SQLite database
    conn = sqlite3.connect('user_data.db')
    cursor = conn.cursor()

    # Retrieve the stats column for the specified player's most recent games
    cursor.execute('''
        SELECT stats
        FROM game_logs
        WHERE player_id = ?
        ORDER BY game_date DESC
        LIMIT ?
    ''', (player_id, num_games))

    game_stats = cursor.fetchall()

    # Close the connection
    conn.close()
    json_player_stats_list = []
    for i in range(num_games):
      json_player_stats = game_stats[i][0].replace("'", "\"")
      json_player_stats = json.loads(json_player_stats)
      json_player_stats_list.append(json_player_stats)
    return json_player_stats_list

#-----------------------------------------------------------------------

#finds data from API
def fetch_data_from_api(puuid):
    global most_recent_eco
    # Example API endpoint
    url = f"https://api.henrikdev.xyz/valorant/v3/by-puuid/matches/na/{puuid}?mode=competitive&size=1"
    response = requests.get(url)
    if response.status_code == 200:
      gameEcoCount = 0
      gameHeadshotsCount = 0
      gameBodyshotsCount = 0
      gameLegshotsCount = 0
      soup = BeautifulSoup(response.text, 'html.parser')
      site_json = json.loads(soup.text)

      if site_json["data"][0]["metadata"]["matchid"] != get_by_puuid("lastGame", puuid):
        player_stats = site_json["data"][0]["rounds"][0]["player_stats"]
        update_by_puuid("lastGame", site_json["data"][0]["metadata"]["matchid"], puuid)

        #grabs index of all the players making later processes faster
        playersIndices = {}
        for pos in range(0, 10):
          playersIndices[player_stats[pos]["player_puuid"]] = pos
          if player_stats[pos]["player_puuid"] == puuid:
            playerPos = pos
            playerName = player_stats[pos]['player_display_name']

        # iterates through rounds
        for roundNum in range(0, len(site_json["data"][0]["rounds"])):
          #adds headshots/bodyshots/legshots to user_data.db via users puuid
          headshots = int(site_json["data"][0]["rounds"][roundNum]["player_stats"][playerPos]["headshots"])

          gameHeadshotsCount += headshots
          bodyshots = int(site_json["data"][0]["rounds"][roundNum]["player_stats"][playerPos]["bodyshots"])

          gameBodyshotsCount += bodyshots
          legshots = int(site_json["data"][0]["rounds"][roundNum]["player_stats"][playerPos]["legshots"])

          gameLegshotsCount += legshots
          try:
            update_by_puuid("headshots", get_by_puuid("headshots", puuid)+headshots, puuid)
            update_by_puuid("bodyshots", get_by_puuid("bodyshots", puuid)+bodyshots, puuid)
            update_by_puuid("legshots", get_by_puuid("legshots", puuid)+legshots, puuid)
          except:
            True
          #checks if player gets a kill that round
          kill_events = site_json["data"][0]["rounds"][roundNum]["player_stats"][playerPos]["kill_events"]
          if (kill_events != False):
            killer_gun = site_json["data"][0]["rounds"][roundNum]["player_stats"][playersIndices[puuid]]["economy"]["weapon"]
            #iterates through all the kills the player gets that round
            for kill in kill_events:
              #gets victim's puuid then grabs their loadout_value
              victim_puuid = kill['victim_puuid']
              victim_gun = site_json["data"][0]["rounds"][roundNum]["player_stats"][playersIndices[victim_puuid]]["economy"]["weapon"]

              #adds an ecoKill to user_data.db via users puuid
              try:
                eco_checker[killer_gun["name"]][victim_gun["name"]]
                gameEcoCount += 1
                update_by_puuid("ecoKills", get_by_puuid("ecoKills", puuid)+1, puuid)
                if kill["kill_time_in_match"] > most_recent_eco[6] and site_json["data"][0]["metadata"]["game_start"] >= most_recent_eco[7]:
                  most_recent_eco = (kill["killer_display_name"], kill["damage_weapon_name"], kill["damage_weapon_assets"]["display_icon"], kill["victim_display_name"], victim_gun["name"], victim_gun["assets"]["display_icon"], kill["kill_time_in_match"], site_json["data"][0]["metadata"]["game_start"])

              except:
                True

        total_game_stats_dict ={"ecoKills":gameEcoCount, "headshots":gameHeadshotsCount, "bodyshots":gameBodyshotsCount, "legshots":gameLegshotsCount}
        total_game_stats = str({"ecoKills":gameEcoCount, "headshots":gameHeadshotsCount, "bodyshots":gameBodyshotsCount, "legshots":gameLegshotsCount})
        return total_game_stats_dict

        # CHECK IF USER IS IN DATA BASE ---------------------------------
        # IF NOT ADD THEM
        if get_by_puuid('id', puuid) is None:
          return [{"name": playerName[:playerName.index('#')], "puuid":puuid, "ecoKills":gameEcoCount, "headshots": gameHeadshotsCount, "bodyshots":gameBodyshotsCount, "legshots":gameLegshotsCount}]
        else:
          insert_game_log(get_by_puuid('id',puuid), site_json["data"][0]["metadata"]["game_start"], total_game_stats)

        # ---------------------------------------------------------------

    else:
      #if api is down then gives us the code; a slightly better try except statement
      print(f"Error Status code: {response.status_code}")

def get_puuid(name, tag):
  url = f"https://api.henrikdev.xyz/valorant/v1/account/{name}/{tag}"
  response = requests.get(url)
  if response.status_code == 200:
    soup = BeautifulSoup(response.text, 'html.parser')
    site_json = json.loads(soup.text)
    return site_json["data"]["puuid"]
  else:
    print(f"Error Status code: {response.status_code}")

#prints the entire database
"""
# Connect to the SQLite database
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()

# Execute a SELECT query to retrieve all data from the 'users' table
cursor.execute('SELECT * FROM users')

# Fetch all rows from the result set
rows = cursor.fetchall()

# Print the retrieved data
for row in rows:
    print("ID:", row[0])
    print("Username:", row[1])
    print("PUUID:", row[2])
    print("Eco Kills:", row[3])
    print("Headshots:", row[4])
    print("Bodyshots:", row[5])
    print("Legshots:", row[6])
    print("Latest Match Id:", row[7])
    print("--------------------")

# Close the connection
conn.close()
"""

puuids = get_all_puuids()
#for username in puuids:
  #fetch_data_from_api(puuids[username])
  #print(f'User {username} has been update')
#INFINITY LOOP ONCE WE DONZO YAYAYAYAYA
#while True:
    #for username in puuids:
      #fetch_data_from_api(puuids[username])
      #print(f'User {username} has been update')
    #time.sleep(1800)  # 30 minutes in seconds

#grabs stats from last game in players logs
for i in range(1,14):
  player_stats = get_recent_game_stats(i,2)
  #json_player_stats = player_stats[0][0].replace("'", "\"")
  #json_player_stats = json.loads(json_player_stats)
  print(f"{i}:{player_stats[0]['ecoKills']}")


#!/usr/bin/env python3

#import sys
#from os import listdir, mkdir
from os.path import isfile, join, isdir
from collections import defaultdict
#import copy
#import spacy
#import scispacy
import sys, getopt

PROG_NAME = "add-term-from-umls.py"

# all columns values are zero-indexed

INPUT_COL_CONCEPT_ID = 0
UMLS_COL_CUI = 0
UMLS_COL_LANG = 1
UMLS_LANG_FILTER_VAL = [ "ENG" ]
UMLS_COL_PREFERED = 6
UMLS_COL_SOURCE = 11
UMLS_MESH_SOURCE_FILTER_VAL = "MSH"
UMLS_COL_MESH_ID = 10
UMLS_COL_TERM = 14

UMLS_STY_COL_CUI = 0
UMLS_STY_COL_TYPE_ID = 1
UMLS_STY_COL_TYPE_TREE_ID = 2
UMLS_STY_COL_TYPE_NAME = 3

SEMGROUPS_COL_COARSE_GROUP_ID = 0
SEMGROUPS_COL_FINE_GROUP_ID = 2

UMLS_SEP = '|'
UMLS_MAIN_FILE = "MRCONSO.RRF"
UMLS_GROUP_FILE = "MRSTY.RRF"

FILTER_LANG = False
ADD_GROUP_COL = False
PTC_INPUT = False
USE_MESH_IDS = False
REMOVE_MESH_PREFIX = False
USE_PTC_AS_GROUP_COL = False

INPUT_CONCEPT_FREQ_SEP=":"
SEPARATOR_CONCEPT_ID_TYPE = "@"
OUTPUT_GROUP_SEP=" "

def usage(out):
    print("Usage: ls <input files> | "+PROG_NAME+" [options] <UMLS dir> <output suffix> ",file=out)
    print("",file=out)
    print("  Reads a list of input tsv files with a concept id column (either a UMLS CUI id or a Mesh id)",file=out)
    print("  and maps the id to a term using the UMLS data. For each input file <f> an output file ",file=out)
    print("  <f><output suffix> is created with an additional term column. ",file=out)
    print("  <UMLS dir> is the UMLS metathesaurus data, it must contain RRF files: <UMLS dir>/META/*.RRF",file=out)
    print("  Notes:",file=out)
    print("    - If no term is found for a concept, the term column contains 'NA'.",file=out)
    print("    - In case -g/-G is used, the group column contains a list of groups separated by '"+OUTPUT_GROUP_SEP+"'",file=out)
    print("      The list can be empty, in which case the group column is empty.",file=out)
    print("",file=out)
    print("  Options:")
    print("    -h: print this help message.",file=out)
    print("    -i <id col>: concept id col; default: "+str(INPUT_COL_CONCEPT_ID+1)+".",file=out)
    print("    -m Mesh ids instead of default UMLS CUI ids (CUI is the default).",  file=out)
    print("    -M Mesh ids instead of default UMLS CUI ids + prefix 'MESH:' in the input files.",  file=out)
    print("    -p PTC input: the concept is represented as <id>@<category>, and a Mesh id has a ",file=out)
    print("       prefix 'MESH:'. Both the category and the prefix are removed. Implies '-M'.",file=out)
    print("    -g <UMLS sem groups file> add 'semantic group' column using UMLS group hierarchy which",file=out)
    print("       can be downloaded at https://lhncbc.nlm.nih.gov/semanticnetwork/download/SemGroups.txt",file=out)
    print("    -G add 'semantic group' column using PTC annotated type (requires PTC input; implies -p and -M)",file=out)
    print("    -l filter only English language terms. This can produce 'NA' terms if a concept does ",file=out)
    print("       not have any English term (this is rare but it happens). By default English is prefered")
    print("       but non-English is used if no English term is found.",file=out)
    print("",file=out)

# main

umlsGroupFile = None
try:
    opts, args = getopt.getopt(sys.argv[1:],"hi:mMpg:Gl")
except getopt.GetoptError:
    usage(sys.stderr)
    sys.exit(2)
for opt, arg in opts:
    if opt == "-h":
        usage(sys.stdout)
        sys.exit()
    elif opt == "-i":
        INPUT_COL_CONCEPT_ID = int(arg) -1
    elif opt == "-m":
        USE_MESH_IDS = True
    elif opt == "-M":
        USE_MESH_IDS = True
        REMOVE_MESH_PREFIX = True
    elif opt == '-p':
        PTC_INPUT = True
        USE_MESH_IDS = True
        REMOVE_MESH_PREFIX = True
    elif opt == '-g':
        ADD_GROUP_COL = True
        umlsGroupFile = arg
    elif opt == '-G':
        ADD_GROUP_COL = True
        PTC_INPUT = True
        USE_MESH_IDS = True
        REMOVE_MESH_PREFIX = True
        USE_PTC_AS_GROUP_COL = True
    elif opt == '-l':
        FILTER_LANG = True

#print("debug args after options: ",args)

if len(args) != 2:
    usage(sys.stderr)
    sys.exit(2)

umlsDir = args[0]
outputSuffix = args[1]

input_files = [ f.rstrip() for f in sys.stdin ]
for filename in input_files:
    if not isfile(filename):
        raise Exception("File '"+filename+"' read from STDIN does not exist.")

print("INFO: Reading UMLS concepts and terms...")
umls_mesh_to_cui = defaultdict(list)

#
# due to the possibility that a concept doesn't have an English term,
# there are two maps: one for English (index 1) one for non-English (index 0)
umls_cui_prefered_term = [ {}, {} ]

f= join(umlsDir, "META", UMLS_MAIN_FILE)
with open(f) as infile:
    for line in infile:
        cols = line.rstrip().split(UMLS_SEP)
        index_lang = 0
        if cols[UMLS_COL_LANG] in UMLS_LANG_FILTER_VAL:
            index_lang = 1
        if not FILTER_LANG or (index_lang == 1):                                     # filter language
            cui = cols[UMLS_COL_CUI]
            if cols[UMLS_COL_PREFERED] == 'Y' and umls_cui_prefered_term[index_lang].get(cui) is None:  # store only if prefered term, and only first found
                umls_cui_prefered_term[index_lang][cui] = cols[UMLS_COL_TERM]
            if USE_MESH_IDS and cols[UMLS_COL_SOURCE] == UMLS_MESH_SOURCE_FILTER_VAL:       # store all the CUIs corresponding to this Mesh
                umls_mesh_to_cui[cols[UMLS_COL_MESH_ID]].append(cui)
#                if cols[UMLS_COL_MESH_ID] == 'D000690':
#                    print("DEBUG: ",cols[UMLS_COL_MESH_ID],":",cui, " - term = ",cols[UMLS_COL_TERM])

umls_group_fine_to_coarse = {}
groups_by_cui = defaultdict(set)
if umlsGroupFile is not None:
    print("INFO: Reading UMLS groups...")
    with open(umlsGroupFile) as infile:
        for line in infile:
            cols = line.rstrip().split(UMLS_SEP)
            umls_group_fine_to_coarse[cols[SEMGROUPS_COL_FINE_GROUP_ID]] = cols[SEMGROUPS_COL_COARSE_GROUP_ID]
    f= join(umlsDir, "META", UMLS_GROUP_FILE)
    with open(f) as infile:
        for line in infile:
            cols = line.rstrip().split(UMLS_SEP)
            cui = cols[UMLS_STY_COL_CUI]
            fine_group = cols[UMLS_STY_COL_TYPE_ID]
            coarse_group = umls_group_fine_to_coarse[fine_group]
            if coarse_group is None:                # sanity check
                raise Exception("Error: cannot find coarse group corresponding to fine group '"+fine_group+"'")
            groups_by_cui[cui].add(coarse_group)

print("INFO: Processing input files...")
for input_file in input_files:
    with open(input_file+outputSuffix,"w") as outfile:
        with open(input_file) as infile:
            for line in infile:
                cols = line.rstrip().split('\t')
                concept_id = cols[INPUT_COL_CONCEPT_ID]
                cui_list = None
                if USE_MESH_IDS:
                    is_mesh = True
                    if REMOVE_MESH_PREFIX:
                        if concept_id[:5] == 'MESH:':
                            concept_id = concept_id[5:]
                        else:
                            is_mesh = False
                if PTC_INPUT:
                    sep_pos = concept_id.rfind(SEPARATOR_CONCEPT_ID_TYPE)
                    if sep_pos != -1:
                        ptc_category = concept_id[sep_pos+1:]
                        concept_id = concept_id[0:sep_pos]
                    else:
                        raise Exception("Bug! the concept id is supposed to contain '"+SEPARATOR_CONCEPT_ID_TYPE+"', this is not supposed to happen.",concept_id)
                cols[INPUT_COL_CONCEPT_ID] = concept_id
                if USE_MESH_IDS:
                    cui = None
                    if is_mesh:
                        cui_list = umls_mesh_to_cui[concept_id]
                        if len(cui_list)>0:
                            # just picking the first matched cui
                            cui = cui_list[0]
#                        else:
#                            print("Warning: no CUI found for MeSH descriptor "+concept_id)
                else:
                    cui = concept_id
                term = umls_cui_prefered_term[1].get(cui)
                if term is None:
                    # second attempt if no match found in English: non-English version
                    term = umls_cui_prefered_term[0].get(cui)
                    if term is None:
                        if not PTC_INPUT or is_mesh:
                            print("Warning: no term found for concept '"+concept_id+"'",file=sys.stderr)
                        term = "NA"
                cols.append(term)
                if ADD_GROUP_COL:
                    groups = []
                    if USE_MESH_IDS:
                        if USE_PTC_AS_GROUP_COL:
                            if ptc_category is not None:
                                groups = [ ptc_category ]
                        else:
                            if cui_list is not None and len(cui_list)>0:
                                groups_set = set()
                                for cui in cui_list:
                                    for g in groups_by_cui[cui]:
                                        groups_set.add(g)
                                groups = list(groups_set)
                    else:
                        groups = groups_by_cui[concept_id]
                    cols.append(OUTPUT_GROUP_SEP.join(groups))
                outfile.write("\t".join(cols)+"\n")


import json
import os
from types import SimpleNamespace
from typing import Callable, Dict, TypeVar

import requests
from cachetools import cached, TTLCache
from requests.auth import HTTPBasicAuth

T = TypeVar("T")

class AZGewinkelClient:
    def __init__(self):
        key = os.environ.get("AZGEWINKEL_KEY")
        secret = os.environ.get("AZGEWINKEL_SECRET")
        self.__auth = HTTPBasicAuth(key, secret)
        self.root = "https://azgewinkel.ddns.net/wp-json/wc/v3"

    @cached(cache=TTLCache(maxsize=100, ttl=60))
    def get(self, path: str):

        response = requests.get(self.root + path, auth=self.__auth)
        if response.status_code != 200:
            raise IOError(response)
        text = response.text
        # pprint(json.loads(text))
        data = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
        if 'next' in response.links:
            next_path = response.links['next']['url']
            next_path = next_path.replace(self.root, "")
            next_data = self.get(next_path)
            data = data + next_data
        return data

    @cached(cache=TTLCache(maxsize=100, ttl=60))
    def load(self, path: str, mapper: Callable[[any], T]) -> Dict[int, T]:
        result = {}
        for item in self.get(path):
            result[item.id] = mapper(item)
        return result


class Node:
    def __init__(self, key):
        self.children = []
        self.value = key
        self.parent = None

    def add_child(self, childNode):
        childNode.parent = self
        self.children.append(childNode)

    def print_child(self):

        space = ' ' * self.get_level() * 2
        print(space + self.value)

        if self.children:
            for child in self.children:
                child.print_child()

    def get_level(self):

        level = 0
        p = self.parent
        while p is not None:
            level += 1
            p = p.parent

        return level

def build_tree():

    data = ['*weather', 'sunny', 'rainy', 'cloudy', '*temperature', 'hot', 'warm', 'cold', '*humidity', 'high', 'normal', '*windy', 'weak', 'strong', '*play', 'yes', 'no']
    root = None

    for index in len(data):
        if data[index][0] == '*' and index == 0:
            root = Node(data[index][1:])
        elif data[index][0] == '*':
            total_child = len(root.children)
            root.children[total_child - 1].add_child(Node(data[index][1:]))
        else:
            child_node = Node(data[index])
            root.add_child(child_node)

def make_tree():
    weather = Node("weather")
    sunny = Node("sunny")
    rainy = Node("rainy")
    cloudy = Node("cloudy")
    high = Node("high")
    low = Node("low")
    humidity = Node("humidity")

    weather.add_child(sunny)
    weather.add_child(rainy)
    weather.add_child(cloudy)

    cloudy.add_child(humidity)

    humidity.add_child(high)
    humidity.add_child(low)

    weather.print_child()

if __name__ == '__main__':
    make_tree()


# -*- coding: utf-8 -*-
"""
Created on Sun Dec  6 10:16:31 2020

@author: Ky
"""

def main():
    file = open("day6_input.txt", "r")
    lineList = file.read().split("\n\n")
    num = 0
    total = 0

    alpha = "abcdefghijklmnopqrstuvwxyz"

    for i in range(len(lineList)):
        lineList[i] = lineList[i].replace('\n','')
        for char in alpha:
            if char in lineList[i]:
                num = num + 1
            total = total + num
            num = 0
    print(lineList)
    print(total)
if __name__ == "__main__":
    main()


import sys
import itertools

traces = []

for trace in sys.stdin.readlines():
    minmaxes = []
    x, y = 0, 0
    for step in trace.strip().split(','):
        dir = step[0]
        dist = int(step[1:])
        xoff, yoff = 0, 0
        if dir == 'U':
            yoff = dist
        elif dir == 'R':
            xoff = dist
        elif dir == 'D':
            yoff = -dist
        elif dir == 'L':
            xoff = -dist
        oldx, oldy = x, y
        x, y = x + xoff, y + yoff
        minmax = ((min(oldx, x), max(oldx, x)), (min(oldy, y), max(oldy, y)), dir)
        minmaxes.append(minmax)
    traces.append(minmaxes)

intersections = []

def cross_intersect(hy, hx1, hx2, vx, vy1, vy2):
    # Greater than max or less than min
    if vx > hx2 or vx < hx1:
        return
    if hy > vy2 or hy < vy1:
        return
    intersections.append((vx, hy))

def line_intersect(l1min, l1max, l2min, l2max, l1oth, l2oth, mk):
    if l1oth != l2oth:
        return
    if l1min > l2max or l1max < l2min:
        return
    start = max(l1min, l2min)
    end = min(l1max, l2max)
    intersections.extend(mk(l1oth, val) for val in range(start, end + 1))

for (l1minx, l1maxx), (l1miny, l1maxy), l1d in traces[0]:
    for (l2minx, l2maxx), (l2miny, l2maxy), l2d in traces[1]:
        if l1d == 'U' or l1d == 'D':
            if l2d == 'L' or l2d == 'R':
                cross_intersect(l2miny, l2minx, l2maxx, l1minx, l1miny, l1maxy)
            else:
                line_intersect(l1miny, l1maxy, l2miny, l2maxy, l1minx, l2minx,
                               lambda x, y: (x, y))
        else:
            if l2d == 'U' or l2d == 'D':
                cross_intersect(l1miny, l1minx, l1maxx, l2minx, l2miny, l2maxy)
            else:
                line_intersect(l1minx, l1maxx, l2minx, l2maxx, l1miny, l2miny,
                               lambda y, x: (x, y))

print(intersections)
print(min(abs(x) + abs(y) for x, y in intersections if x or y))


from libs import Pmf
import sys

def ConditionalProb(Pmf, x):
    # computes probability of an event occurring after some period x
    new_pmf = get_new_pmf(Pmf, x)
    asum = sum([new_pmf.Prob(item[0]) for item in new_pmf.Items()])
    return asum

def get_new_pmf(Pmf, x):
    # Create a new PMF
    # Where only considers values
    # after week x.

    [Pmf.Remove(item[0]) for item in Pmf.Items() if item[0] <= x]
    # Pmf.Normalize()
    return Pmf

if __name__ == '__main__':
    data = [0.1, 0.1, 0.1, 0.2, 1, 2, 2, 2, 3, 3, 3, 3, 4]
    pmf = Pmf.MakePmfFromList(data)
    print(ConditionalProb(pmf, float(sys.argv[1])))


import unittest
from sebs.ec2 import Instance
from unittest.mock import patch, MagicMock, call, PropertyMock

class TestInstance(unittest.TestCase):

    def setUp(self):
        self.default_tag = 'sebs'
        self.device_name = '/dev/xdf'
        self.mock_instance = MagicMock(name='mock_instance', id='in-1111')

    def tearDown(self):
        pass

    @patch('sebs.ec2.Instance.get_instance')
    def test_class_properites(self, mock_method):
        mock_method.return_value = self.mock_instance

        server = Instance(self.default_tag)

        self.assertEqual(server.instance, self.mock_instance,
                         'Should set an instance field.')
        self.assertEqual(server.volume_tag, self.default_tag,
                         'Should set volume_tag field.')
        self.assertEqual(server.backup, [], 'Should have empty backup list.')

        mock_method.assert_called_once()

    @patch('sebs.ec2.StatefulVolume')
    @patch('sebs.ec2.Instance.get_instance')
    def test_add_device(self, mock_method, mock_volume_class):
        mock_method.return_value = self.mock_instance
        mock_volume = MagicMock(name='mock_volume')
        mock_volume_class.return_value = mock_volume

        server = Instance(self.default_tag)

        server.add_stateful_device(self.device_name)

        mock_method.assert_called_once()
        mock_volume_class.assert_called_once()

        # Instead of None it should be a session...
        # but I can't figure out how to make a mock method (get_instance)
        # set a class field self.session as a side effect.
        mock_volume_class.assert_called_once_with(None,
                                                  self.mock_instance.id,
                                                  self.device_name,
                                                  self.default_tag)
        self.assertIn(mock_volume, server.backup,
                      'Should put our device in the backup list.')
        mock_volume.get_status.assert_called_once()

    @patch('sebs.ec2.StatefulVolume')
    @patch('sebs.ec2.Instance.get_instance')
    def test_add_multiple_devices(self, mock_method, mock_volume_class):
        mock_method.return_value = self.mock_instance
        mock_volume = MagicMock(name='mock_volume_1')
        mock_volume_class.return_value = mock_volume

        server = Instance(self.default_tag)

        server.add_stateful_device(self.device_name)
        server.add_stateful_device('/dev/2')

        mock_method.assert_called_once()
        self.assertEqual(mock_volume_class.call_count, 2,
                         'Should create two volumes.')

        # Same as above test, need to replace None with session
        mock_volume_class.assert_has_calls(
            [call(None, self.mock_instance.id, self.device_name, self.default_tag),
             call(None, self.mock_instance.id, '/dev/2', self.default_tag)])

        self.assertEqual(len(server.backup), 2, 'Should have two volumes.')
        self.assertEqual(mock_volume.get_status.call_count, 2,
                         'Should have called get_status twice')

    @patch('sebs.ec2.Instance.get_instance')
    def test_tag_volumes(self, mock_method):
        server = Instance(self.default_tag)
        mock_volume = MagicMock(name='mock_volume_1', status='Not Attached')
        mock_volume2 = MagicMock(name='mock_volume_2', status='Missing')

        server = Instance(self.default_tag)
        server.backup = [mock_volume, mock_volume2]
        server.tag_stateful_volumes()

        # Should tag one volume but not the other.
        mock_volume.tag_volume.assert_called_once()
        mock_volume2.tag_volume.assert_not_called()

    @patch('sebs.ec2.ec2_metadata')
    @patch('sebs.ec2.Instance.get_instance')
    def test_attach_volumes(self, mock_method, mock_metadata):

        p = PropertyMock(return_value='AZ2')
        type(mock_metadata).availability_zone = p

        mock_volume = MagicMock(name='mock_volume_1', status='Not Attached')
        mock_volume2 = MagicMock(name='mock_volume_2', status='Missing')

        server = Instance(self.default_tag)
        server.backup = [mock_volume, mock_volume2]
        server.attach_stateful_volumes()

        # Should Attach one volume but not the other.
        mock_volume.copy.assert_called_once_with('AZ2')
        mock_volume.attach.assert_called_once()

        mock_volume2.copy.assert_not_called()
        mock_volume2.attach.assert_not_called()

if __name__ == '__main__':
    unittest.main()


"""Navigation menu for the netbox_facts plugin."""
from django.utils.translation import gettext_lazy as _
from extras.plugins import PluginMenuButton, PluginMenuItem, get_plugin_config
from extras.plugins.navigation import PluginMenu
from utilities.choices import ButtonColorChoices

macaddress_buttons = [
    PluginMenuButton(
        link="plugins:netbox_facts:macaddress_add",
        title="Add",
        icon_class="mdi mdi-plus-thick",
        color=ButtonColorChoices.GREEN,
    )
]
macvendor_buttons = [
    PluginMenuButton(
        link="plugins:netbox_facts:macvendor_add",
        title="Add",
        icon_class="mdi mdi-plus-thick",
        color=ButtonColorChoices.GREEN,
    )
]

menu_buttons = (
    PluginMenuItem(
        link="plugins:netbox_facts:macaddress_list", link_text=_("MAC Addresses"), buttons=macaddress_buttons
    ),
    PluginMenuItem(link="plugins:netbox_facts:macvendor_list", link_text=_("MAC Vendors"), buttons=macvendor_buttons),
)

if get_plugin_config("netbox_facts", "top_level_menu"):
    # add a top level entry
    menu = PluginMenu(
        label=_("Facts"),
        groups=(("Networking", menu_buttons),),
        icon_class="mdi mdi-checkbox-multiple-marked-outline",
    )
else:
    # display under plugins
    menu_items = menu_buttons


import itertools
import pecan

from oslo_log import log
from pecan import rest

from shadowfiend.api import acl
from shadowfiend.api.controllers.v1 import models
from shadowfiend.common import exception
from shadowfiend.common import policy
from shadowfiend.common import timeutils
from shadowfiend.db import models as db_models
from shadowfiend.services import keystone as ks_client

from wsme import types as wtypes
from wsmeext.pecan import wsexpose

LOG = log.getLogger(__name__)
HOOK = pecan.request

class BillingOwnerController(rest.RestController):

    def __init__(self, project_id):
        self.project_id = project_id

    @wsexpose(None, wtypes.text)
    def put(self, user_id):
        """Change billing_owner of this project."""
        HOOK.conductor_rpcapi.change_billing_owner(
            HOOK.context,
            project_id=self.project_id,
            user_id=user_id)

    @wsexpose(models.UserAccount)
    def get(self):
        LOG.info("get_billing_owner")
        user_account = HOOK.conductor_rpcapi.get_billing_owner(
            HOOK.context,
            self.project_id)
        return db_models.Account(**user_account)

class ExistProjectController(rest.RestController):
    """Manages operations on project."""

    _custom_actions = {
        'estimate': ['GET'],
    }

    def __init__(self, project_id):
        self._id = project_id

    @pecan.expose()
    def _lookup(self, subpath, *remainder):
        if subpath == 'billing_owner':
            return (BillingOwnerController(self._id),
                    remainder)

    def _project(self):
        try:
            project = HOOK.conductor_rpcapi.get_project(
                HOOK.context,
                project_id=self._id)
        except Exception:
            LOG.error('project %s no found' % self._id)
            raise exception.ProjectNotFound(project_id=self._id)
        return project

    @wsexpose(models.Project)
    def get(self):
        """Return this project."""
        return db_models.Project(**self._project())

class ProjectController(rest.RestController):
    """Manages operations on the projects collection."""

    def __init__(self):
        pass

    @pecan.expose()
    def _lookup(self, project_id, *remainder):
        if remainder and not remainder[-1]:
            remainder = remainder[:-1]
        return ExistProjectController(project_id), remainder

    @wsexpose([models.UserProject], wtypes.text, wtypes.text, wtypes.text)
    def get_all(self, user_id=None, type=None, duration=None):
        """Get all projects."""
        user_id = acl.get_limited_to_user(HOOK.headers,
                                          'project:all') or user_id
        result = []

        if not type or type.lower() == 'pay':
            # if admin call this api, limit to admin's user_id
            if not user_id:
                user_id = HOOK.context.user_id

            try:
                relations = HOOK.conductor_rpcapi.get_relation(
                    HOOK.context,
                    user_id=user_id)
            except Exception as e:
                LOG.exception('Fail to get all projects')
                raise exception.DBError(reason=e)

            if not relations:
                LOG.warn('User %s has no payed projects' % user_id)
                return []

            project_ids = [up['project_id'] for up in relations]

            projects = self._list_keystone_projects()

            for u, p in itertools.product(relations, projects):
                if u['project_id'] == p.id:
                    up = models.UserProject(
                        user_id=user_id,
                        project_id=u['project_id'],
                        project_name=p.name,
                        user_consumption=u['user_consumption'],
                        project_consumption=u['project_consumption'],
                        billing_owner=None,
                        project_owner=None,
                        project_creator=None,
                        is_historical=u['is_historical'],
                        created_at=u['created_at'])
                    result.append(up)
        elif type.lower() == 'all':
            # if admin call this api, limit to admin's user_id
            if not user_id:
                user_id = HOOK.context.user_id

            k_projects = ks_client.get_project_list(name=user_id)
            LOG.debug('Projects: %s' % k_projects)
            project_ids = [p.id for p in k_projects]

            if not project_ids:
                LOG.warning('User %s has no projects' % user_id)
                return []

            try:
                sf_projects = (HOOK.conductor_rpcapi.
                               get_projects(HOOK.context, project_ids))
            except Exception as e:
                LOG.exception('Fail to get all projects')
                raise exception.DBError(reason=e)
            for k, sf in itertools.product(k_projects, sf_projects):
                k = k.__dict__
                if k['id'] == sf['project_id']:
                    up = models.UserProject(
                        user_id=user_id,
                        project_id=sf['project_id'],
                        project_name=k['name'],
                        project_consumption=sf['consumption'],
                        billing_owner=None,
                        project_owner=None,
                        project_creator=None,
                        is_historical=False,
                        created_at=(
                            sf['created_at'] if sf['created_at'] else None))
                    result.append(up)

        elif type.lower() == 'simple':
            duration = timeutils.normalize_timedelta(duration)
            if duration:
                active_from = timeutils.utcnow() - duration
            else:
                active_from = None
            sf_projects = list(HOOK.conductor_rpcapi.get_projects(
                HOOK.context,
                user_id=user_id,
                active_from=active_from))
            project_ids = [p.project_id for p in sf_projects]

            if not project_ids:
                LOG.warn('User %s has no payed projects' % user_id)
                return []

            k_projects = self._list_keystone_projects()

            for k, sf in itertools.product(k_projects, sf_projects):
                if k.id == sf['project_id']:
                    up = models.UserProject(
                        project_id=sf['project_id'],
                        project_name=k.name,
                        domain_id=sf['domain_id'],
                        billing_owner=dict(user_id=sf['user_id']))
                    result.append(up)

        return result

    def _list_keystone_projects(self):
        projects = []
        domain_ids = \
            [domain.id for domain in ks_client.get_domain_list()]
        for domain_id in domain_ids:
            projects.extend(ks_client.get_project_list(domain_id))
        return projects

    @wsexpose(None, body=models.Project)
    def post(self, data):
        """Create a new project."""
        policy.check_policy(HOOK.context, "project:post")
        try:
            project = data.as_dict()
            return HOOK.conductor_rpcapi.create_project(HOOK.context, project)
        except Exception:
            LOG.exception('Fail to create project: %s' % project)
            raise exception.ProjectCreateFailed(project_id=data.project_id,
                                                user_id=data.user_id)


from itertools import accumulate
from typing import AbstractSet

from .parse import coalesce, is_word, lower
from .types import Context, ContextualEdit, Edit

def _match(lhs: bool, existing: str, insertion: str) -> str:
    existing, insertion = lower(existing), lower(insertion)
    if lhs:
        for match in reversed(tuple(accumulate(insertion))):
            if match == existing[-len(match) :]:
                return match
        else:
            return ""
    else:
        for match in reversed(tuple(accumulate(reversed(insertion)))):
            if match == existing[: len(match) :]:
                return match
        else:
            return ""

def trans(line_before: str, line_after: str, edit: Edit) -> ContextualEdit:
    l_match = _match(True, existing=line_before, insertion=edit.new_text)
    rest = edit.new_text[len(l_match) :]
    r_match = _match(False, existing=line_after, insertion=rest)
    c_edit = ContextualEdit(
        new_text=edit.new_text,
        new_prefix=edit.new_text,
        old_prefix=line_before[-len(l_match) :] if l_match else "",
        old_suffix=line_after[: len(r_match)],
    )
    return c_edit

def trans_adjusted(
    unifying_chars: AbstractSet[str], ctx: Context, edit: Edit
) -> ContextualEdit:
    c_edit = trans(line_before=ctx.line_before, line_after=ctx.line_after, edit=edit)
    new_syms = len(tuple(coalesce(edit.new_text, unifying_chars=unifying_chars)))
    simple_before = (
        ctx.words_before
        if is_word(c_edit.new_text[:1], unifying_chars=unifying_chars)
        else ctx.syms_before
    )
    simple_after = (
        ctx.words_after
        if is_word(c_edit.new_text[-1:], unifying_chars=unifying_chars)
        else ""
    )

    old_prefix = simple_before if new_syms <= 1 else c_edit.old_prefix or simple_before
    old_suffix = simple_after if new_syms <= 1 else c_edit.old_suffix or simple_after

    adjusted = ContextualEdit(
        new_text=c_edit.new_text,
        new_prefix=c_edit.new_prefix,
        old_prefix=old_prefix,
        old_suffix=old_suffix,
    )
    return adjusted

def expand_tabs(context: Context, text: str) -> str:
    new_text = (
        text.expandtabs(context.tabstop)
        if context.expandtab
        else text.replace(" " * context.tabstop, "\t")
    )
    return new_text


from builtins import zip
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt

import lsst.sims.maf.metrics as metrics

from .plotHandler import BasePlotter

__all__ = ['FOPlot', 'SummaryHistogram']

class FOPlot(BasePlotter):
    """
    Special plotter to generate and label fO plots.
    """
    def __init__(self):
        self.plotType = 'FO'
        self.objectPlotter = False
        self.defaultPlotDict = {'title': None, 'xlabel': 'Number of visits',
                                'ylabel': 'Area (1000s of square degrees)',
                                'scale': None, 'Asky': 18000., 'Nvisits': 825,
                                'xMin': 0, 'xMax': None, 'yMin': 0, 'yMax': None,
                                'linewidth': 2, 'reflinewidth': 2}

    def __call__(self, metricValue, slicer, userPlotDict, fignum=None):
        """
        Parameters
        ----------
        metricValue : numpy.ma.MaskedArray
            The metric values calculated with the 'Count' metric and a healpix slicer.
        slicer : lsst.sims.maf.slicers.HealpixSlicer
        userPlotDict: dict
            Dictionary of plot parameters set by user (overrides default values).
            Note that Asky and Nvisits values set here and in the slicer should be consistent,
            for plot labels and summary statistic values to be consistent.
        fignum : int
            Matplotlib figure number to use (default = None, starts new figure).

        Returns
        -------
        int
           Matplotlib figure number used to create the plot.
        """
        if not hasattr(slicer, 'nside'):
            raise ValueError('FOPlot to be used with healpix or healpix derived slicers.')
        fig = plt.figure(fignum)
        plotDict = {}
        plotDict.update(self.defaultPlotDict)
        plotDict.update(userPlotDict)

        if plotDict['scale'] is None:
            plotDict['scale'] = (hp.nside2pixarea(slicer.nside, degrees=True) / 1000.0)

        # Expect metricValue to be something like number of visits
        cumulativeArea = np.arange(1, metricValue.compressed().size + 1)[::-1] * plotDict['scale']
        plt.plot(np.sort(metricValue.compressed()), cumulativeArea, 'k-',
                 linewidth=plotDict['linewidth'], zorder=0)
        # This is breaking the rules and calculating the summary stats in two places.
        # Could just calculate summary stats and pass in labels.
        rarr = np.array(list(zip(metricValue.compressed())),
                        dtype=[('fO', metricValue.dtype)])
        fOArea = metrics.fOArea(col='fO', Asky=plotDict['Asky'], norm=False,
                                nside=slicer.nside).run(rarr)
        fONv = metrics.fONv(col='fO', Nvisit=plotDict['Nvisits'], norm=False,
                            nside=slicer.nside).run(rarr)

        plt.axvline(x=plotDict['Nvisits'], linewidth=plotDict['reflinewidth'], color='b')
        plt.axhline(y=plotDict['Asky'] / 1000., linewidth=plotDict['reflinewidth'], color='r')
        # Add lines for Nvis_median and fOArea: note if these are -666 (badval),
        # the default xMin/yMin values will just leave them off the edges of the plot.
        Nvis_median = fONv['value'][np.where(fONv['name'] == 'MedianNvis')]
        # Note that Nvis is the number of visits (it's not an area) - so goes on number axis
        plt.axvline(x=Nvis_median, linewidth=plotDict['reflinewidth'], color='b',
                    alpha=.5, linestyle=':', label=r'f$_0$ Median Nvisits=%.0f' % Nvis_median)
        plt.axhline(y=fOArea / 1000., linewidth=plotDict['reflinewidth'], color='r',
                    alpha=.5, linestyle=':', label='f$_0$ Area=%.0f' % fOArea)
        plt.legend(loc='lower left', fontsize='small', numpoints=1)

        plt.xlabel(plotDict['xlabel'])
        plt.ylabel(plotDict['ylabel'])
        plt.title(plotDict['title'])

        xMin = plotDict['xMin']
        xMax = plotDict['xMax']
        yMin = plotDict['yMin']
        yMax = plotDict['yMax']
        if (xMin is not None) or (xMax is not None):
            plt.xlim([xMin, xMax])
        if (yMin is not None) or (yMax is not None):
            plt.ylim([yMin, yMax])
        return fig.number

class SummaryHistogram(BasePlotter):
    """
    Special plotter to summarize metrics which return a set of values at each slicepoint,
    such as if a histogram was calculated at each slicepoint
    (e.g. with the lsst.sims.maf.metrics.TgapsMetric).
    Effectively marginalizes the calculated values over the sky, and plots the a summarized
    version (reduced to a single according to the plotDict['metricReduce'] metric).
    """

    def __init__(self):
        self.plotType = 'SummaryHistogram'
        self.objectPlotter = True
        self.defaultPlotDict = {'title': None, 'xlabel': None, 'ylabel': 'Count', 'label': None,
                                'cumulative': False, 'xMin': None, 'xMax': None, 'yMin': None, 'yMax': None,
                                'color': 'b', 'linestyle': '-', 'histStyle': True, 'grid': True,
                                'metricReduce': metrics.SumMetric(), 'bins': None}

    def __call__(self, metricValue, slicer, userPlotDict, fignum=None):
        """
        Parameters
        ----------
        metricValue : numpy.ma.MaskedArray
            Handles 'object' datatypes for the masked array.
        slicer : lsst.sims.maf.slicers
            Any MAF slicer.
        userPlotDict: dict
            Dictionary of plot parameters set by user (overrides default values).
            'metricReduce' (an lsst.sims.maf.metric) indicates how to marginalize the metric values
            calculated at each point to a single series of values over the sky.
            'histStyle' (True/False) indicates whether to plot the results as a step histogram (True)
            or as a series of values (False)
            'bins' (np.ndarray) sets the x values for the resulting plot and should generally match
            the bins used with the metric.
        fignum : int
            Matplotlib figure number to use (default = None, starts new figure).

        Returns
        -------
        int
           Matplotlib figure number used to create the plot.
        """
        fig = plt.figure(fignum)
        plotDict = {}
        plotDict.update(self.defaultPlotDict)
        plotDict.update(userPlotDict)
        # Combine the metric values across all slicePoints.
        if not isinstance(plotDict['metricReduce'], metrics.BaseMetric):
            raise ValueError('Expected plotDict[metricReduce] to be a MAF metric object.')
        # Get the data type
        dt = metricValue.compressed()[0].dtype
        # Change an array of arrays (dtype=object) to a 2-d array of correct dtype
        mV = np.array(metricValue.compressed().tolist(), dtype=[('metricValue', dt)])
        # Make an array to hold the combined result
        finalHist = np.zeros(mV.shape[1], dtype=float)
        metric = plotDict['metricReduce']
        metric.colname = 'metricValue'
        # Loop over each bin and use the selected metric to combine the results
        for i in np.arange(finalHist.size):
            finalHist[i] = metric.run(mV[:, i])
        bins = plotDict['bins']
        if plotDict['histStyle']:
            leftedge = bins[:-1]
            rightedge = bins[1:]

            x = np.vstack([leftedge, rightedge]).T.flatten()
            y = np.vstack([finalHist, finalHist]).T.flatten()

        else:
            # Could use this to plot things like FFT
            x = bins[:-1]
            y = finalHist
        # Make the plot.
        plt.plot(x, y, linestyle=plotDict['linestyle'],
                 label=plotDict['label'], color=plotDict['color'])
        # Add labels.
        plt.xlabel(plotDict['xlabel'])
        plt.ylabel(plotDict['ylabel'])
        plt.title(plotDict['title'])
        plt.grid(plotDict['grid'], alpha=0.3)
        # Set y and x limits, if provided.
        if plotDict['xMin'] is not None:
            plt.xlim(left=plotDict['xMin'])
        elif bins[0] == 0:
            plt.xlim(left=0)
        if plotDict['xMax'] is not None:
            plt.xlim(right=plotDict['xMax'])
        if plotDict['yMin'] is not None:
            plt.ylim(bottom=plotDict['yMin'])
        elif finalHist.min() == 0:
            plotDict['yMin'] = 0
        if plotDict['yMax'] is not None:
            plt.ylim(top=plotDict['yMax'])

        return fig.number


from typing import Any, Dict, Type, TypeVar

import attr

from ..models.subscr_channel_no_sound_option_type import SubscrChannelNoSoundOptionType
from ..models.subscr_channel_no_sound_option_value import SubscrChannelNoSoundOptionValue

T = TypeVar("T", bound="SubscrChannelNoSoundOption")

@attr.s(auto_attribs=True)
class SubscrChannelNoSoundOption:
    """
    Attributes:
        type (SubscrChannelNoSoundOptionType):
        value (SubscrChannelNoSoundOptionValue):
    """

    type: SubscrChannelNoSoundOptionType
    value: SubscrChannelNoSoundOptionValue

    def to_dict(self) -> Dict[str, Any]:
        type = self.type.value

        value = self.value.value

        field_dict: Dict[str, Any] = {}
        field_dict.update(
            {
                "type": type,
                "value": value,
            }
        )

        return field_dict

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        d = src_dict.copy()
        type = SubscrChannelNoSoundOptionType(d.pop("type"))

        value = SubscrChannelNoSoundOptionValue(d.pop("value"))

        subscr_channel_no_sound_option = cls(
            type=type,
            value=value,
        )

        return subscr_channel_no_sound_option


from distutils.core import setup
from edupals.i18n import poinstaller
import sys
import os

if __name__ == '__main__':

	pinstaller = poinstaller.PoInstaller('translations','bell-scheduler','')
	pinstaller.build()
	polist = pinstaller.setup_install()
	listdir=map(lambda x:os.path.join('bell-scheduler','data-files','banners',x),os.listdir('bell-scheduler/data-files/banners'))

	setup(name='bell-scheduler',
		version='0.1',
		description='Bell Scheduler',
		long_description="""""",
		author='Lliurex Team',
		author_email='juapesai@hotmail.com',
		maintainer='Juan Ramon Pelegrina',
		maintainer_email='juapesai@hotmail.com',
		keywords=['software','scheduler','alarms'],
		url='http://www.lliurex.net',
		license='GPL',
		platforms='UNIX',
		packages = ['bellscheduler'],
		package_dir = {'bellscheduler':'bell-scheduler/python3-bellscheduler'},
		package_data = {'bellscheduler':['rsrc/*']},
		data_files = [('bin',['bell-scheduler/BellSchedulerPlayer']),('sbin',['bell-scheduler/bell-scheduler']),
				  ('sbin',['bell-scheduler/bell-scheduler-gui']),
			      ('share/bell-scheduler/banners',listdir),
			      ] + polist ,
		classifiers=[
			'Development Status :: 4 - Beta',
			'Environment :: Console'
			'Intended Audience :: End Users',
			'License :: OSI Approved :: GNU General Public License v3',
			'Operating System :: POSIX',
			'Programming Language :: Python',
			'Topic :: Software',
			'Topic :: Install apps',
			],
	)
	pinstaller.clean()


import streamlit as st
import requests
from PIL import Image
from transformers import BlipProcessor, BlipForConditionalGeneration
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
import numpy as np

# Function to generate a caption
def generate_caption(image):
    processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
    model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
    inputs = processor(image, return_tensors="pt")
    out = model.generate(**inputs)
    return processor.decode(out[0], skip_special_tokens=True)

# Function to find the most similar emoji
def find_similar_emoji(caption, sentence_model, emoji_df):
    caption_embedding = sentence_model.encode([caption])[0]
    caption_embedding = np.array(caption_embedding).reshape(1, -1)

    emoji_embeddings = {row['emoji']: np.array(sentence_model.encode([row['name']])[0]).reshape(1, -1) for _, row in emoji_df.iterrows()}

    similarities = {emoji: cosine_similarity(caption_embedding, emoji_embedding)[0][0] for emoji, emoji_embedding in emoji_embeddings.items()}
    return max(similarities, key=similarities.get)

# Streamlit app
def main():
    st.title("Image to Emoji Converter")

    # User uploads an image
    uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
    if uploaded_file is not None:
        # Display the image
        image = Image.open(uploaded_file)
        st.image(image, caption='Uploaded Image.', use_column_width=True)

        # Load the sentence transformer model
        sentence_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')

        # Load emoji data
        emoji_df = pd.read_csv("./emoji_df.csv")  # Ensure the file is in the same directory as the app

        # Generate caption
        caption = generate_caption(image)
        st.write("Caption:", caption)

        # Find and display the most similar emoji
        emoji = find_similar_emoji(caption, sentence_model, emoji_df)
        st.write("Most similar emoji: ", emoji)

if __name__ == "__main__":
    main()


import logging

from odoo import fields, models

_logger = logging.getLogger(__name__)

class AddressAssociateToAddressAux(models.TransientModel):
    _description = 'Address Associate to Address (Aux)'
    _name = 'clv.address.associate_to_address_aux'

    def _default_address_ids(self):
        return self._context.get('active_ids')
    address_ids = fields.Many2many(
        comodel_name='clv.address',
        relation='clv_address_associate_to_address_aux_rel',
        string='Addresses',
        default=_default_address_ids
    )

    create_new_address_aux = fields.Boolean(
        string='Create new Address (Aux)',
        default=True,
        readonly=False
    )

    # @api.multi
    def _reopen_form(self):
        self.ensure_one()
        action = {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'view_type': 'form',
            'view_mode': 'form',
            'target': 'new',
        }
        return action

    # @api.multi
    def do_address_associate_to_address_aux(self):
        self.ensure_one()

        address_count = 0
        for address in self.address_ids:

            address_count += 1

            _logger.info(u'%s %s %s', '>>>>>', address_count, address.name)

            AddressAux = self.env['clv.address_aux']
            address_aux = AddressAux.search([
                ('related_address_id', '=', address.id),
            ])
            _logger.info(u'%s %s %s', '>>>>>>>>>>', 'address_aux_id:', address_aux.id)

            if address_aux.id is not False:

                new_address_aux = address_aux

            else:

                if self.create_new_address_aux:

                    values = {}
                    values['street_name'] = address.street_name

                    _logger.info(u'%s %s %s', '>>>>>>>>>>', 'values:', values)
                    new_address_aux = AddressAux.create(values)
                    _logger.info(u'%s %s %s', '>>>>>>>>>>', 'new_address_aux:', new_address_aux)

                    values = {}
                    values['related_address_id'] = address.id
                    _logger.info(u'%s %s %s', '>>>>>>>>>>', 'values:', values)
                    new_address_aux.write(values)

                    new_address_aux.do_address_aux_get_related_address_data()

        if address_count == 1:

            action = {
                'type': 'ir.actions.act_window',
                'name': 'Addresses (Aux)',
                'res_model': 'clv.address_aux',
                'res_id': new_address_aux.id,
                'view_type': 'form',
                'view_mode': 'tree,kanban,form',
                'target': 'current',
                'context': {'search_default_name': new_address_aux.name},
            }

        else:

            action = {
                'type': 'ir.actions.act_window',
                'name': 'Addresses (Aux)',
                'res_model': 'clv.address_aux',
                'view_type': 'form',
                'view_mode': 'tree,kanban,form',
                'target': 'current',
            }

        return action
        # return True


from gensim.models import FastText
import enchant
import nltk

model_fasttext = FastText.load('fasttext.model')

fasttext_min_similarity = 0.6
enchant_kr = enchant.Dict('ko_KR')

def include_spell_mistake(word, similar_word, score):
    edit_distance_threshold = 1 if len(word) <= 4 else 2
    score_1 = score > fasttext_min_similarity
    score_2 = len(similar_word) > 3
    score_3 = not enchant_kr.check(similar_word)
    score_4 = word[0] == similar_word[0]
    score_5 = nltk.edit_distance(word, similar_word) <= edit_distance_threshold
    score = score_1 + score_2 + score_3 + score_4 + score_5
    if score > 3:
        return True
    else:
        return False

def spell_check(word):
    w2m = []
    most_similar = model_fasttext.wv.most_similar(word, topn=50)
    for similar_word, score in most_similar:
        if include_spell_mistake(word, similar_word, score):
            w2m.append(similar_word)
    output = {'prediction' : w2m[:3]}
    return output

print(spell_check('스울'))


# -*- coding: utf-8 -*-
import numpy as np
np.set_printoptions(threshold='nan')
import os
from os import walk
import os.path as osPath
import math
import csv
from PIL import Image, ImageDraw, ImageFont, ImageColor

def generateRandomRule():
    myRule = ""
    for i in range(0,32):
         myRule += str(random.randint(0,1))
    return myRule

def remap(value, minInput, maxInput, minOutput, maxOutput):
    if minInput < maxInput:
        value = maxInput if value > maxInput else value
        value = minInput if value < minInput else value
        inputSpan = maxInput - minInput
        outputSpan = maxOutput - minOutput
        scaledThrust = float(value - minInput) / float(inputSpan)
        return minOutput + (scaledThrust * outputSpan)
    else:
        return minOutput

def getInspArrayRangeZero(inArLenght):
    rulesCount = pow(2, inArLenght)
    returnArray = []
    arRange = range(0, rulesCount)
    for i in arRange:
        returnArray.append(0)
    return returnArray

def getInspArraySeqence(inArLenght):
    rulesCount = pow(2, inArLenght)
    arRange = range(0, rulesCount)
    binSeqDiv = [pow(2, x) for x in range(0,inArLenght)]
    binSeqDiv.reverse()
    myArray = [[math.trunc(x / y) % 2 for x in arRange] for y in binSeqDiv]
    myArray = map(list, zip(*myArray))
    return myArray

def returnOne(inNum):
    if inNum > 1:
        return 1
    else:
        return inNum
def loadLayers(inDirPath):
    myDir = []
    truePixs = [[]]
    returnImages = []
    returnData = []
    lastImgSize = 0
    for i in inDirPath:
        myImgColors = []
        myImgs = []
        if os.path.isdir(i):
            myDir = os.listdir(i)
            myDir.sort()
#        print myDir
        if len(myDir) != 0:
            for j in myDir:
                lastImg = Image.open(i + "/" + j)
                lastImg.convert("1")
                lastImg.tobitmap(lastImg)
                lastImgSize = lastImg.size
                myImgColors.append(lastImg.getcolors())
                myImgs.append(lastImg)
#                print "LAST LOADED IMAGE: " + j
#                print "colors = rs = " + str(lastImg.getcolors())
        else:
            return []
        splitString = i.split("_")
        ruleNum = splitString[len(splitString)-2]
        returnData.append([myImgColors, lastImgSize[0], lastImgSize[1], ruleNum, myImgs])
    return returnData

def loadDirs(inDirPath, inRange):
    myDirs = []
    f =[]
    returnData = []
    liWidth = 0
    liHeight = 0
    if os.path.isdir(inDirPath):
        myDirs = os.listdir(inDirPath)
        myDirs.sort()
    if inRange[0] <= len(myDirs):
        startLayer = inRange[0]
        print ("startLayer: " +str(startLayer) + " total dirs " + str(len(myDirs)))
    else:
        return []
    if inRange[len(inRange)-1] <= len(myDirs):
        endLayer = len(inRange)-1
    elif inRange[len(inRange)-1] > len(myDirs):
        endLayer = len(myDirs) - 1
    else:
        return []
    for (path, dirnames, filenames) in walk(inDirPath):
        f.extend(dirnames)
        break
    for j, s in enumerate(f):
        f[j] = inDirPath + s
#    print myDirs[: inRange[len(inRange)-1]]
#    print f[inRange[0]:inRange[len(inRange)-1]]
    f.sort()
#    print f[inRange[0]:inRange[len(inRange)-1]]
    print("endLayer: " + str(endLayer))
    return f[inRange[0]: (inRange[len(inRange)-1])+1]

def getCross(inRules, inInspArraySequence, inWidth, inLogData):
    print("inRules")
    print(inRules)
    dirPath = r"/storage/emulated/0/CA/_moje pokusy/cross_test.png"
    recSize = inWidth / (len(inRules)*4+1.0)
    crossSize = recSize * 3
    gap = recSize
    fontSize = int(crossSize*0.8)
    crossOffset0Vert = fontSize + int(recSize)
    crossOffset0=0
    crossOffset1=recSize
    crossOffset2=recSize*2
    crossOffset3=crossSize
    text2Offset = crossOffset0Vert + int(crossOffset3) + int(recSize)+30
    imHeight = text2Offset + fontSize + int(recSize)
    fadeValue = 0.18
    returnArray = []
    myHSLcol = "hsl(0,100%,50%)"
    myFirstOcurences = inLogData[0]
    myOcurencesCount = inLogData[1]
    maxOcurenceValue = max(myOcurencesCount)
    scaleCount = 10
    scaleStep = maxOcurenceValue / scaleCount
    if scaleStep > 0:
        scaleRange = range(0,maxOcurenceValue,scaleStep)
    else:
        scaleRange = range(0,10,1)
    font = ImageFont.truetype("raavi.ttf", fontSize)
    im = Image.new('RGB', (inWidth,imHeight), (0, 0, 0))
    imD = ImageDraw.Draw(im)
    for i, s in enumerate(inInspArraySequence):
        fillColor0 = int(s[0]*(255*fadeValue+((1-fadeValue)*int(inRules[i])*255)))
#        frameColor = int(255*fadeValue+((1-fadeValue)*int(inRules[i])*255))
        frameColor = int(255*fadeValue)
        imD.rectangle([((crossSize*i+gap*i)+crossOffset1,crossOffset0Vert), (int((crossSize*i+gap*i)+crossOffset2), int(crossOffset0Vert+crossOffset1))], (fillColor0, fillColor0,fillColor0),(frameColor,frameColor,frameColor))
        returnArray.append(int((crossSize*i+gap*i)+crossOffset1))
        fillColor0 = int(s[1]*(255*fadeValue+((1-fadeValue)*int(inRules[i])*255)))
        imD.rectangle([((crossSize*i+gap*i)+crossOffset0,crossOffset0Vert + crossOffset1), ((crossSize*i+gap*i)+crossOffset1,crossOffset0Vert + crossOffset2)], (fillColor0, fillColor0,fillColor0),(frameColor,frameColor,frameColor))
        fillColor0 = int(s[2]*(255*fadeValue+((1-fadeValue)*int(inRules[i])*255)))
        imD.rectangle([((crossSize*i+gap*i)+crossOffset1,crossOffset0Vert + crossOffset1), ((crossSize*i+gap*i)+crossOffset2, crossOffset0Vert + crossOffset2)], (fillColor0, fillColor0,fillColor0),(frameColor,frameColor,frameColor))
        fillColor0 = int(s[3]*(255*fadeValue+((1-fadeValue)*int(inRules[i])*255)))
        imD.rectangle([((crossSize*i+gap*i)+crossOffset2,crossOffset0Vert + crossOffset1), ((crossSize*i+gap*i)+crossOffset3, crossOffset0Vert + crossOffset2)], (fillColor0, fillColor0,fillColor0),(frameColor,frameColor,frameColor))
        fillColor0 = int(s[4]*(255*fadeValue+((1-fadeValue)*int(inRules[i])*255)))
        imD.rectangle([((crossSize*i+gap*i)+crossOffset1,crossOffset0Vert + crossOffset2), ((crossSize*i+gap*i)+crossOffset2, crossOffset0Vert + crossOffset3)], (fillColor0, fillColor0,fillColor0),(frameColor,frameColor,frameColor))
        imD.text((int((crossSize*i+gap*i)+crossOffset1), text2Offset - fontSize),inRules[i],font=font, fill=(255,255,255,255))
        imD.text((int((crossSize*i+gap*i)+crossOffset1), 0), str(i),font=font, fill=(255,255,255,255))
        myHSLcol = "hsl(" + str(int(remap(myOcurencesCount[i], 0, maxOcurenceValue, 0, 185))) + ",100%, " + str(int(remap(myOcurencesCount[i], 0, maxOcurenceValue, 30, 70))) + "%)"
        imD.text((int((crossSize*i+gap*i)+crossOffset1), text2Offset - fontSize*2), str(myFirstOcurences[i]),font=font, fill=myHSLcol)
        textXpos = 3
        for s in scaleRange:
            myHSLcol = "hsl(" + str(int(remap(s, 0, maxOcurenceValue, 0, 185))) + ",100%, " + str(int(remap(s, 0, maxOcurenceValue, 30, 70))) + "%)"
            imD.text((textXpos, text2Offset), str(s),font=font, fill=myHSLcol)
            myTextSize = imD.textsize(str(s),font=font)
            textXpos += (myTextSize[0] + 15)
#    im.save(dirPath)
    return im

def createColorAnalyze(inColData, inSavePath, logReadDir):
    returnArray = []
    for i, imgs in enumerate(inColData):
        textHeight = 10
        resX = imgs[1]
        resY = imgs[2]
        columns = max(math.trunc(math.sqrt(len(imgs[4]))),20)
        maxValue = resX * resY
        nResX = resX * columns
        nResY = 600
        myValues =[]
        mySavePath = inSavePath + str(int(imgs[3],2)) + "_" + imgs[3] + "_" + str(resX) + "x" + str(resY) +"_analyse.png"
        mySavePathBig = inSavePath + str(int(imgs[3],2)) + "_" + imgs[3] + "_" + str(resX) + "x" + str(resY) +"_analyse_big.png"
        logReadPath = logReadDir +imgs[3] + "_" + str(resX) + "x" + str(resY) + ".csv"
        myLogsData = readCSV_Log(logReadPath)
        crossIm = getCross(imgs[3], getInspArraySeqence(5), nResX, myLogsData)
        pColXStart = 0
        pRowYStart = nResY + textHeight*10 + crossIm.size[1]
        mySAnal = Image.new("RGB",(nResX,nResY))
        myBAnal = Image.new("RGB",(columns * resX,nResY + textHeight*10 + int(len(imgs[4])/columns*resY + crossIm.size[1])),(0,0,0))
        myFont = ImageFont.truetype("raavi.ttf", textHeight)
        myFont2 = ImageFont.truetype("arial.ttf", textHeight)
 #+ textHeight + int(math.ceil(len(imgs[4])/columns))))
        mySAnalDraw = ImageDraw.Draw(mySAnal)
        myBAnalDraw = ImageDraw.Draw(myBAnal)
        myImgs = imgs[4]
        for j, cols in enumerate(imgs[0]):
            blackValue = 0
            whiteValue = 0
            bX = nResX / float(len(imgs[0]))
            pColX = pColXStart + ((j % columns)*resX)
            pRowY =	pRowYStart + math.trunc(j/columns)*resY
            for k, vals in enumerate(cols):
                if vals[1] == 0:
                    blackValue = vals[0]
                elif vals[1] == 255:
                    whiteValue = vals[0]
            myValues.append((pColX, pRowY))
            mySAnalDraw.rectangle([bX*j, 0, (bX*j)+bX, remap(whiteValue, 0, maxValue, 0, nResY)], (255,255,255))
            myBAnal.paste(myImgs[j], (pColX, pRowY))
        returnArray.append(myValues)
        myBAnal.paste(mySAnal, (0,0))
        myBAnal.paste(crossIm, (0,mySAnal.size[1]))
        myBAnalDraw.text((3,nResY+crossIm.size[1]), "RULE BINAR CODE: " + imgs[3],font=myFont2)
        myBAnalDraw.text((3,nResY+crossIm.size[1] + textHeight), "GENERATION COUNT: " + str(len(imgs[0])),font=myFont2)
        if len(myLogsData) != 0:
            myFirstOcurences = myLogsData[0]
            myOcurencesCount = myLogsData[1]
            myBAnalDraw.text((3,nResY+crossIm.size[1] + textHeight*2), "GENERATION OF FIRST OCURENCE: " + str(myFirstOcurences),font=myFont2)
            myBAnalDraw.text((3,nResY+crossIm.size[1] + textHeight*3), "OCURENCE COUNT: " + str(myOcurencesCount),font=myFont2)
        mySAnal.save(mySavePath)
        myBAnal.save(mySavePathBig)
    return returnArray

def readCSV_Log(inPath):
    returnArray = []
    inspArrayRange = getInspArrayRangeZero(5)
    firstOcure = getInspArrayRangeZero(5)
    if osPath.isfile(inPath) == True:
        print("Log File Exists: " + inPath)
        f = open(inPath, "r")
        with f:
            reader = csv.reader(f)
            layNum = 0
#            myRows = []
#            myCounts = []
            for i, row in enumerate(reader):
                if len(row) != 1 and len(row) >= 4:
#                    myRows.append(row)
                    myInspMatrixNum = int(row[3])
#                    myCounts.append(myInspMatrixNum)
                    myCount = inspArrayRange[myInspMatrixNum]
                    if myCount == 0:
                        firstOcure[myInspMatrixNum] = layNum + 1
                    myCount += 1
                    inspArrayRange[myInspMatrixNum] = myCount
                else:
#                    returnArray.append(myCounts)
                    layNum = layNum + 1
#                    myRows = []
#                    myCounts = []
    else:
        print("Log File Doesn't Exist: ")
    return [firstOcure, inspArrayRange]

def run(inDirPath):
    myDirs = loadDirs(inDirPath, range(0, 40))
    for i in myDirs:
        print(i)
    myData = loadLayers(myDirs)
    print("\n")
    print("myData: ")
    print("myDataLen " + str(len(myData)))
    for i, d in enumerate(myData):
        print("DIR_NUMBER: " + str(i))
        print("resX: " + str(d[1]))
        print("resY: " + str(d[2]))
        print("ruleNumber: ")
        print(d[4])
#        print myDirs[i]
        a=0
        for j in d[0]:
            print(str(a))
            print(j)
            a += 1
    myAnalyzeData = createColorAnalyze(myData, savePath, logReadDir)
    for i in myAnalyzeData:
        print(i)

def getInvertedDigit(inRule, inPos):
    returnString = ""
    listString = list(inRule)
    if listString[inPos] == '0':
        listString[inPos] = '1'
    elif listString[inPos] == '1':
        listString[inPos] = '0'
    return ''.join(listString)

dirPath = r"/storage/emulated/0/CA/_moje pokusy/CELULAR_AUTOMAT-2D/zaloha/z/"
savePath = r"/storage/emulated/0/CA/_moje pokusy/CELULAR_AUTOMAT-2D/analyse/interesting2/"
logReadDir = r"/storage/emulated/0/CA/_moje pokusy/CELULAR_AUTOMAT-2D/CSV_log/"

resolutionX = 51
resolutionY = 51
layersCount = 100
run(dirPath)


import json
import pathlib
from typing import Set, List

from progress_report import ProgressReport  # , ProgressReportSubstep
import bpy

from . import gltftypes
from . import glb
from .import_manager import ImportManager
from .texture_io import load_textures
from .material_io import load_materials
from .mesh_io import load_meshes
from .node_io import load_objects
from .node import Node
from . import gltf_buffer

from logging import getLogger  # pylint: disable=C0411
logger = getLogger(__name__)

def _setup_skinning(blender_object: bpy.types.Object,
                    attributes: gltf_buffer.VertexBuffer, bone_names: List[str],
                    armature_object: bpy.types.Object)->None:
    # create vertex groups
    for bone_name in bone_names:
        if bone_name:
            blender_object.vertex_groups.new(
                name=bone_name)

    idx_already_done: Set[int] = set()

    # each face
    for poly in blender_object.data.polygons:
        # face vertex index
        for loop_idx in range(poly.loop_start, poly.loop_start + poly.loop_total):
            loop = blender_object.data.loops[loop_idx]
            vert_idx = loop.vertex_index
            if vert_idx < 0:
                raise Exception()
            if vert_idx >= len(attributes.joints):
                raise Exception()

            if vert_idx in idx_already_done:
                continue
            idx_already_done.add(vert_idx)

            cpt = 0
            for joint_idx in attributes.joints[vert_idx]:
                if cpt > 3:
                    break
                weight_val = attributes.weights[vert_idx][cpt]
                if weight_val != 0.0:
                    # It can be a problem to assign weights of 0
                    # for bone index 0, if there is always 4 indices in joint_ tuple
                    bone_name = bone_names[joint_idx]
                    if bone_name:
                        group = blender_object.vertex_groups[bone_name]
                        group.add([vert_idx], weight_val, 'REPLACE')
                cpt += 1

    # select
    # for obj_sel in bpy.context.scene.objects:
    #    obj_sel.select = False
    #blender_object.select = True
    #bpy.context.scene.objects.active = blender_object

    modifier = blender_object.modifiers.new(name="Armature", type="ARMATURE")
    modifier.object = armature_object

def _remove_empty(node: Node):
    for i in range(len(node.children)-1, -1, -1):
        child = node.children[i]
        _remove_empty(child)

    if node.children:
        print(f'{node} children {len(node.children)}')
        return
    if node.blender_armature:
        print(f'{node} has {node.blender_armature}')
        return
    if node.blender_object.data:
        print(f'{node} has {node.blender_object}')
        return

    # remove empty
    print('remove', node)
    bpy.data.objects.remove(node.blender_object, do_unlink=True)
    if node.parent:
        node.parent.children.remove(node)

def load(context,
         filepath: str,
         yup_to_zup: bool
         )->Set[str]:

    path = pathlib.Path(filepath)
    if not path.exists():
        return {'CANCELLED'}

    with ProgressReport(context.window_manager) as progress:
        progress.enter_substeps(5, "Importing GLTF %r..." % path.name)

        body = b''
        try:
            with path.open('rb') as f:
                ext = path.suffix.lower()
                if ext == '.gltf':
                    gltf = gltftypes.from_json(json.load(f))
                elif ext == '.glb' or ext == '.vrm':
                    gltf, body = glb.parse_glb(f.read())
                else:
                    logger.error("%s is not supported", ext)
                    return {'CANCELLED'}
        except Exception as ex:  # pylint: disable=w0703
            logger.error("%s", ex)
            return {'CANCELLED'}

        manager = ImportManager(path, gltf, body, yup_to_zup)
        manager.textures.extend(load_textures(progress, manager))
        manager.materials.extend(load_materials(progress, manager))
        manager.meshes.extend(load_meshes(progress, manager))
        nodes, root = load_objects(context, progress, manager)

        # skinning
        armature_object = next(
            node for node in root.traverse() if node.blender_armature)

        for node in nodes:
            if node.gltf_node.mesh != -1 and node.gltf_node.skin != -1:
                _, attributes = manager.meshes[node.gltf_node.mesh]

                skin = gltf.skins[node.gltf_node.skin]
                bone_names = [
                    nodes[joint].bone_name for joint in skin.joints]

                #armature_object =nodes[skin.skeleton].blender_armature

                _setup_skinning(node.blender_object, attributes,
                                bone_names,
                                armature_object.blender_armature)

        # remove empties
        _remove_empty(root)

        # done
        context.scene.update()
        progress.leave_substeps("Finished")
        return {'FINISHED'}


def binary_search(list1,n):
    low=0
    high=len(list1)-1
    mid =0

    while low<=high:
    #for getting int result
        mid=(high+low) //2

    #Check if n is present in the mid
    if list1 [mid]<n:
        low=mid+1

    #if n is greater ,compare to the right of the mid
    elif list1 [mid]>n:
        high =mid-1

#if n is smaller,compare to the left of the mid
    else:
        return mid
#element was not present on the list

    return -1
#initialize the list

list1 =[12,45,5,67,3,455]
n=0

#function call
result= binary_search (list1,n)

if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in list1")


from django.core.management.base import BaseCommand

from ideascube.search.utils import create_index_table
from ideascube.search.models import SEARCHABLE

class Command(BaseCommand):
    help = 'Reindex all the searchable objects'

    def handle(self, *args, **kwargs):
        create_index_table()
        for model in SEARCHABLE.values():
            count = 0
            for inst in model.objects.all():
                inst.index()
                count += 1
            if count:
                self.stdout.write('Indexed {} content.'.format(model.__name__))
        self.stdout.write('Done reindexing.')


from django.shortcuts import render, redirect
from django.views.generic import TemplateView, ListView, CreateView
from django.core.files.storage import FileSystemStorage
from django.urls import reverse_lazy

from .forms import StForm
from .models import Storage

class Home(TemplateView):
    template_name = 'storage/home.html'

def upload(request):
    context = {}
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        fs = FileSystemStorage()
        name = fs.save(uploaded_file.name, uploaded_file)
        context['url'] = fs.url(name)
    return render(request, 'storage/upload.html', context)

def st_list(request):
    files = Storage.objects.all()
    return render(request, 'storage/st_list.html', {
        'files': files
    })

def upload_file(request):
    if request.method == 'POST':
        form = StForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('st_list')
    else:
        form = StForm()
    return render(request, 'storage/upload_file.html', {
        'form': form
    })

def delete_file(request, pk):
    if request.method == 'POST':
        file = Storage.objects.get(pk=pk)
        file.delete()
    return redirect('st_list')

# class BookListView(ListView):
#     model = Book
#     template_name = 'storage/class_book_list.html'
#     context_object_name = 'books'
#
#
# class UploadBookView(CreateView):
#     model = Book
#     form_class = BookForm
#     success_url = reverse_lazy('class_book_list')
#     template_name = 'storage/upload_file.html'


def multiple(a, b):
    """Return the smallest number n that is a multiple of both a and b.

    >>> multiple(3, 4)
    12
    >>> multiple(14, 21)
    42
    """
    "*** YOUR CODE HERE ***"
    base = 2
    number = 1
    while True:
        if a==1 and b==1:
            return number
        elif a%base==0:
            number = number*base
            a=a/base
            if b%base==0:
                b=b/base
        elif b%base==0 :
            number = number*base
            b=b/base
        else:
            base=base+1

def unique_digits(n):
    """Return the number of unique digits in positive integer n

    >>> unique_digits(8675309) # All are unique
    7
    >>> unique_digits(1313131) # 1 and 3
    2
    >>> unique_digits(13173131) # 1, 3, and 7
    3
    >>> unique_digits(10000) # 0 and 1
    2
    >>> unique_digits(101) # 0 and 1
    2
    >>> unique_digits(10) # 0 and 1
    2
    """
    "*** YOUR CODE HERE ***"
    m=0
    unique=0

    while n != 0:
        if has_digit(m,n%10) == False:
            unique = unique+1
            m = m*10+ n%10
        n=n/10

    return unique

def has_digit(m,k):
    while m!=0:
        if m%10==k:
            return True
        else:
            m=m/10
    return False


import numpy as np
from random import randint
from keras.utils import to_categorical
np.set_printoptions(threshold=np.nan)

def Create_Features(sample_size, sequence_length, feature_length):
    features = []
    for i in range(sample_size):
        _ = []
        for j in range(sequence_length):
            _.append(randint(0,feature_length))
        features.append(_)

    features = np.array(features)

    features = to_categorical(features)
    features = features.reshape([sample_size,sequence_length,feature_length])
    print("features shape: ", features.shape)
    return features

def Create_Labels(sample_size):
    phenotype = []
    for _ in range(sample_size):
        phenotype.append(randint(0,1))
    phenotype = np.array(phenotype)
    print("phenotype shape: ", phenotype.shape)
    return phenotype

def Sample_Data(sample_size,sequence_length, target):
    features = []
    for i in range(sample_size):
        _ = []
        for j in range(sequence_length):
            if j == target and i + randint(0,1)%2 ==0:
                _.append(1)
            else:
                _.append(randint(0, 3))
        features.append(_)

    phenotype = []
    for x in range(sample_size):
        if features[x][target] == 1:
            phenotype.append(1)
        else:
            phenotype.append(0)

    features = np.array(features)

    features = to_categorical(features)
    features = features.reshape([sample_size,sequence_length,4])
    phenotype = np.array(phenotype)
    return features, phenotype


import random

def countingSort(A,B,n,k):
    C=[0] * (k+1)
    print ("C is: ",C)
    for i in range(0,n):
        C[A[i]]= C[A[i]]+1
    print(C)
    for j in range (1,k+1):
        C[j] = C[j] + C[j-1]
        print("C is: ", C)
    print("b is ",B)
    for x in range (n-1,-1,-1):
        B[C[A[x]]-1] = A[x]
        C[A[x]] = C[A[x]]-1
        print("C is: ", C)
        print("B is: ",B)

    print("end")

def Rand( end, num):
    result = []
    for j in range(num):
        result.append(random.randint(0, end))
    return result

#n=int(input("n elements in lists: "))
#k=int(input("K range: "))
#B=[0] * n

#randArr=Rand(k, n)
#print("rand array: ",randArr)
countingSort([1,8,8,4,6,7,3,3,9,2],[0,0,0,0,0,0,0,0,0,0],10,9)

def countingSortR(A,d,n,k):
    C=[0] * (k+1)
    B=[0] * n
    print("C array: " + C)
    for i in range(0,n):
        value = int(A[i]/10**(d-1))
        print("value: ",value)
        C[value%10 ] +=1
    print(C)
    for j in range (1,k+1):
        C[j] = C[j] + C[j-1]
        print("C is: ",C)
    for x in range (n-1,-1,-1):
        value = int(A[x]/10**(d-1))
        B[C[(value)%10]-1] = A[x]
        C[(value)%10] -= 1
    print("B is: ",B)
    print("end")
    for i in range(0,len(A)):
        A[i]=B[i]

def radix(A,d):
    for i in range(1,d+1):
        print(A)
        k=9
        countingSortR(A,i,n,k)

# d=int(input("enter number of digits "))
# n=int(input("number of integer elements "))
# min = 10**(d-1)
# max = (10**(d)) - 1
# rArray=random.sample(range(min, max), n)
# print(rArray)
#
# radix(rArray,d)


import base64
import hashlib
import hmac
import time
from typing import Any, Dict

from pyfs_base import BaseFeishu

class Bot(BaseFeishu):
    def __init__(self, hook_id: str = None, key_word: str = None, secret: str = None) -> None:
        super(Bot, self).__init__()
        self.hook_id = hook_id
        self.key_word = key_word
        self.secret = secret
        # https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
        # curl -X POST -H "Content-Type: application/json" \
        #     -d '{"msg_type":"text","content":{"text":"request example"}}' \
        #     https://open.feishu.cn/open-apis/bot/v2/hook/****
        self.WEBHOOK_URL = self.OPEN_DOMAIN + '/open-apis/bot/v2/hook/{hook_id}'

    def __gen_sign(self, timestamp: int, secret: str) -> str:
        # 拼接timestamp和secret
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        hmac_code = hmac.new(string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()
        # 对结果进行base64处理
        sign = base64.b64encode(hmac_code).decode('utf-8')
        return sign

    def send_hook_message(self, data: Dict[str, Any], hook_id: str = None, secret: str = None) -> Dict[str, Any]:
        hook_id = hook_id or self.hook_id
        secret = secret or self.secret
        if secret:
            timestamp = int(time.time())
            data['timestamp'] = timestamp
            data['sign'] = self.__gen_sign(timestamp, secret)
        return self.post(self.WEBHOOK_URL.format(hook_id=hook_id), data=data)

    # 发送文本消息
    def send_hook_text_message(self, message: str, hook_id: str = None, key_word: str = None, secret: str = None) -> Dict[str, Any]:
        key_word = key_word or self.key_word
        if key_word:
            message = '【{0}】{1}'.format(key_word, message)
        data = {
            'msg_type': 'text',
            'content': {
                'text': message,
            }
        }
        return self.send_hook_message(data, hook_id=hook_id, secret=secret)

    # 发送富文本消息
    def send_hook_post_message(self, post: Dict[str, Any], hook_id: str = None, key_word: str = None, secret: str = None) -> Dict[str, Any]:
        key_word = key_word or self.key_word
        if key_word:
            for lang in post:
                post[lang]['title'] = '【{0}】{1}'.format(key_word, post[lang]['title'])
        data = {
            'msg_type': 'post',
            'content': {
                'post': post,
            }
        }
        return self.send_hook_message(data, hook_id=hook_id, secret=secret)

    # 发送群名片
    def send_hook_share_chat_message(self, share_chat_id: str, hook_id: str = None, secret: str = None) -> Dict[str, Any]:
        # 群 ID 说明: https://open.feishu.cn/document/server-docs/group/chat/chat-id-description
        data = {
            'msg_type': 'share_chat',
            'content': {
                'share_chat_id': share_chat_id,
            }
        }
        return self.send_hook_message(data, hook_id=hook_id, secret=secret)

    # 发送图片
    def send_hook_image_message(self, image_key: str, hook_id: str = None, secret: str = None) -> Dict[str, Any]:
        # 群 ID 说明: https://open.feishu.cn/document/server-docs/group/chat/chat-id-description
        data = {
            'msg_type': 'image',
            'content': {
                'image_key': image_key,
            }
        }
        return self.send_hook_message(data, hook_id=hook_id, secret=secret)

    # 发送消息卡片
    def send_hook_interactive_message(self, interactive: Dict[str, Any], hook_id: str = None, secret: str = None) -> Dict[str, Any]:
        # 卡片结构介绍: https://open.feishu.cn/document/common-capabilities/message-card/message-cards-content/card-structure/card-content
        # 消息卡片搭建工具: https://open.feishu.cn/document/common-capabilities/message-card/message-card-builder
        data = {
            'msg_type': 'interactive',
            'card': interactive,
        }
        return self.send_hook_message(data, hook_id=hook_id, secret=secret)

bot = Bot()
send_hook_message = bot.send_hook_message
send_hook_text_message = bot.send_hook_text_message
send_hook_post_message = bot.send_hook_post_message
send_hook_share_chat_message = bot.send_hook_share_chat_message
send_hook_image_message = bot.send_hook_image_message
send_hook_interactive_message = bot.send_hook_interactive_message


# coding=utf-8

import logging
import datetime
from dofitariomanager import flaskmongo
import numpy
from flask_restful import Resource
from flask import jsonify
from flask import request
from flask import abort
logger_ = logging.getLogger(__name__)

def make_error(status_code, message):
    response = jsonify({
        'status': status_code,
        'message': message
    })
    response.status_code = status_code
    return response

class GeneralWeek(Resource):

    # def __init__(self, session=None):
    #     if session is None:
    #         session = db.get_session()
    #     self._session = session
    def get(self):
        aux = numpy.asarray([[0] * 16] * 7)
        counter = 0
        cursor = flaskmongo.db.tIndividualWeeklyTimetable.find()
        for line in cursor:
            counter = counter + 1
            aux = aux + numpy.array(line['week'])
        result = numpy.ndarray.tolist(aux)

        if counter == 0:
            return make_error(404, "No results o_O, check DB!!!")
        else:
            return {"week": result}


import os

from django.conf import settings
from django.middleware import cache
from sass import compile

def locate(filename):
    for path, dirs, files in os.walk(os.getcwd(), followlinks=True):
        for f in files:
            if f == filename:
                yield os.path.join(path, filename)

class FetchFromCacheMiddleware(cache.FetchFromCacheMiddleware):
    """Minor change to the original middleware that prevents caching of
    requests that have a `sessionid` cookie. This should be the
    Django default, IMHO.

    """

    def process_request(self, request):
        if "sessionid" not in request.COOKIES:
            return super().process_request(request)

class SassMiddleware:
    """Simple SASS middleware that intercepts requests for .css files and
    tries to compile the corresponding SCSS file.

    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if settings.DEBUG and request.path.endswith(".css"):
            css_file = request.path.rsplit("/", 1)[1]
            sass_file = css_file[:-4]
            sass_paths = locate(sass_file)
            for sass_path in list(sass_paths):
                if os.path.exists(sass_path):
                    css_path = sass_path + ".css"
                    map_path = css_path + ".map"
                    css = compile(filename=sass_path, output_style="nested")
                    css, mapping = compile(
                        filename=sass_path, source_map_filename=map_path
                    )
                    with open(css_path, "w") as f:
                        f.write(css)
                    with open(map_path, "w") as f:
                        f.write(mapping)

        response = self.get_response(request)
        return response


from datetime import datetime

import pytest

from tests.assets import POSTS_DICT

class TestSearchPostInReplies:
    @pytest.mark.parametrize(
        ('body', 'result'),
        (
            (
                {'post_id': 2},
                {'amount': 0, 'result': []},
            ),
            (
                {'post_id': 4},
                {'amount': 1, 'result': [POSTS_DICT[5]]},
            ),
        ),
    )
    def test_clear_search(self, client_with_data, body, result):
        resp = client_with_data.post(url='/replies', json=body)
        assert resp.status_code == 200

        data = resp.json()

        for i in data['result']:
            i['post_created_at'] = datetime.strptime(
                i['post_created_at'], '%Y-%m-%dT%H:%M:%S'
            )
        assert data == result


import fileinput
import sys
import math
import os

invoer = []
for line in fileinput.input():
    invoer.append(line.split())

aantal_var = int(invoer[0][0])
aantal_conj = int(invoer[0][1])
vervulbaar = False

combinaties = []
tijdelijke_invoer = []
for i in range(0, int(math.pow(2, aantal_var))):
    tijdelijke_invoer = invoer
    combinaties.append(bin(i))
    combinaties[i] = combinaties[i].replace("0b", "")
    while(len(combinaties[i]) < aantal_var):
        combinaties[i] = "0" + combinaties[i]

    for j in range(0, aantal_var):
        var = combinaties[i]
        tijdelijke_invoer[j+1].append(var[j])

    variables = []
    for i in range(1, aantal_var + 1):
        for j in range(0,2):
            variables.append(tijdelijke_invoer[i][j])

    conjuctions = []
    for i in range(aantal_var + 1, len(tijdelijke_invoer)):
        conjuctions.append(tijdelijke_invoer[i])

    voldoet = True
    for i in range(len(conjuctions)):
        conj_variables = []
        for j in range(len(conjuctions[i])):
            active_conj = conjuctions[i][j]
            if("~" in active_conj):
                active_conj = active_conj[1:len(active_conj)]
                active_variable = active_conj
                var = variables[variables.index(active_variable) + 1]
                if(int(var) == 0):
                    var = "1"
                else:
                    var = "0"
                conj_variables.append(var)
            else:
                active_variable = active_conj
                conj_variables.append(variables[variables.index(active_variable) + 1])

        if( "1" in conj_variables):
            continue
        else:
            voldoet = False

    if(voldoet == True):
        #Bron: https://stackoverflow.com/questions/45027681/pythonic-way-to-print-2d-list-python
        print('\n'.join(map(' '.join, tijdelijke_invoer)))
        vervulbaar = True
        break

    for j in range(0, aantal_var):
        del(tijdelijke_invoer[j+1][1])

if(vervulbaar == False):
    print("Niet vervulbaar")


from APIOpenBD import APIOpenBD
from ElasticsearchWrapper import ElasticsearchWrapper
from flask import Flask, render_template, request, jsonify
import json
from jinja2 import Template, Environment, FileSystemLoader

import re

from jinja2 import evalcontextfilter, Markup, escape

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')

class CustomFlask(Flask):
    '''
    テンプレートのデリミタがVue.jsと競合するので、Flask側でデリミタを別の文字に変更する
	参照：https://muunyblue.github.io/0b7acbba52fb92b2e9c818f7f56bac99.html
    '''
    jinja_options = Flask.jinja_options.copy()
    jinja_options.update(dict(
		block_start_string='(%',
		block_end_string='%)',
		variable_start_string='((',
		variable_end_string='))',
		comment_start_string='(#',
		comment_end_string='#)',
    ))

    template_filter = Flask.template_filter

app = CustomFlask(__name__)
#app = Flask(__name__)

# @app.template_filter()
# @evalcontextfilter
@app.template_filter('nl2br')
def nl2br(eval_ctx, value):
    result = u'\n\n'.join(u'
%s
' % p.replace('\n', '
\n') \
        for p in _paragraph_re.split(escape(value)))
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

@app.template_filter('linebreaksbr')
def linebreaksbr(arg):
    return arg.replace("\n", "
\n")

# env = Environment(loader=FileSystemLoader('.'), trim_blocks=False)

# env.filters['linebreaksbr'] = linebreaksbr
# template = env.get_template('index.html')

# env.filters.update({
# 	"linebreaksbr": jinja2_custom_filters.linebreaksbr,
# })

app.config['JSON_AS_ASCII'] = False    # jsonifyで日本語が文字化けする場合の対処

@app.route("/")
def index():
	'''
	画面
	'''
	return render_template("index.html")
	# return template.render("index.html")

@app.route("/get")
def get():
	'''
	ISBNに対応する書籍情報の取得
	'''
	# パラメータからISBNコードを取得
	isbn = request.args.get('isbn', default=None)
	# 必要な情報を取得する
	json_data = APIOpenBD().get_json(isbn) if isbn else {}
	# dict型をJSON型のレスポンスに変換
	response = jsonify(json_data)

	return response

@app.route("/regist")
def regist():
	'''
	ISBNに対応する書籍情報を取得して、Elasticsearchに登録
	'''
	# パラメータからISBNコードを取得
	isbn = request.args.get('isbn', default=None).replace('-','')
	# 必要な情報を取得する
	json_data = APIOpenBD().get_json(isbn) if isbn else {}

	if json_data == None:
		json_data = {}

	if len(json_data) > 0:
		# Elasticsearch
		es = ElasticsearchWrapper('openbd', 'openbd-index')
		# 追加
		es.insert_one(json_data)

	# dict型をJSON型のレスポンスに変換
	response = jsonify(json_data)

	return response

@app.route("/search")
def search():
	'''
	検索
	'''
	# パラメータからISBNコードを取得
	isbn = request.args.get('isbn', default=None)
	title = request.args.get('title', default=None)
	author = request.args.get('author', default=None)
	publisher = request.args.get('publisher', default=None)
	publishedDate = request.args.get('publishedDate', default=None)
	description = request.args.get('description', default=None)

	# 検索の項目名、項目値のDictionary
	items = {}
	if isbn != None:
		items['isbn'] = isbn.replace('-','')
	if title != None:
		items['title'] = title
	if author != None:
		items['authors'] = author
	if publisher != None:
		items['publisher'] = publisher
	if publishedDate != None:
		items['publishedDate'] = publishedDate
	if description != None:
		items['description'] = description

	# Elasticsearch
	es = ElasticsearchWrapper('openbd', 'openbd-index')
	# 検索
	json_data = es.search_and(items)

	# dict型をJSON型のレスポンスに変換
	response = jsonify(json_data)

	return response

@app.route("/searchall")
def search_all():
	'''
	一覧
	'''
	# Elasticsearch
	es = ElasticsearchWrapper('openbd', 'openbd-index')
	# 検索
	json_data = es.search_all(1000)

	# dict型をJSON型のレスポンスに変換
	response = jsonify(json_data)

	return response

if __name__ == "__main__":
    app.run(debug=False, host='0.0.0.0', port=8080)