import praw, time, sqlite3, datetime, requests, sys

#TODO conform all sql to follow same syntax for variable substitution

def handle_interrupt( function ):
    def wrapped(*args, **kwargs):
        while True:
            try:
                return ( function(*args, **kwargs) )
            except requests.exceptions.ReadTimeout:
                time.sleep(300)
                print( 'read timeout... trying again in 300s' )
                continue
            except ConnectionResetError:
                time.sleep(300)
                print( 'connection reset...trying again in 300s' )
                continue
            except KeyboardInterrupt:
                print('\nsee you space cowboy...')
                sys.exit()
            break
    return ( wrapped )

@handle_interrupt
def get_newusers (cursor, connection, r, cap=990):
    #Initialize three lists, a list of existing users, a list of banned authors
    # and an empty list to keep track of distinct new users
    sql_cmd="SELECT author FROM bots"
    cursor.execute(sql_cmd)
    botbanlist=[ x[0] for x in cursor.fetchall() ]
    sql_cmd="SELECT * FROM redditauthors"
    cursor.execute(sql_cmd)
    name_exists=[ x[0] for x in cursor.fetchall() ]
    just_added=[]

    subreddit=r.get_subreddit('columbus')
    count=1
    for comment in praw.helpers.comment_stream(r,subreddit, limit = 1000):
        author = str(comment.author)
        count+=1
        if count >= cap:
            break
        elif author in name_exists or author in botbanlist or author in just_added:
            continue
        else:
            just_added.append(author)
            cursor.execute("INSERT INTO redditauthors VALUES(?,?)", [author, 99])
            connection.commit()
            print('\b'*len(author), end='')
            print( 'inserted ', author, flush=True)

@handle_interrupt
def row_insert(cursor,connection,redditor,commentname_dict,user,count=1):
    #Insert row by row faster using incremental logic via max(name)
    upd_ts = datetime.datetime.now()
    for comment in redditor.get_comments(limit=None,
    params={'before':commentname_dict[user]}):
#        print('\b'*len(str( count )), end='')
#        print(count, end='', flush=True)
        encode_body = str(comment.body.encode('utf-8'))

        cursor.execute("INSERT INTO redditusercomments VALUES(?,?,?,?,?,?,?)",
        [str(comment.author), str(comment.link_title), str(encode_body),
        str(comment.subreddit), str(comment.created_utc), str(comment.name),
        str(upd_ts) ])
        connection.commit()

        if count == 100:
            columns=[str(comment.author) ,str(upd_ts) , str(comment.name)]
            sql_cmd="INSERT INTO commentlimit VALUES(?,?,?)"
            cursor.execute(sql_cmd,columns)
            connection.commit()
        count+=1
    print(count)

@handle_interrupt
def chunk_insert(cursor,connection,redditor):
    #Create a list comprehension of up to 1000 comments. Bulk Insert into sqlite3
    #2 second overhead for short inserts
    upd_ts = datetime.datetime.now()
    chunk = [(str(comment.author),str(comment.link_title),
    str(comment.body.encode('utf-8')) , str(comment.subreddit),
    str(comment.created_utc), str(comment.name), str(upd_ts))
    for comment in redditor.get_comments(limit=None)]
    print(len(chunk))
    cursor.executemany( "INSERT INTO redditusercomments VALUES(?,?,?,?,?,?,?)", chunk )
    connection.commit()

def update_post_frequency(cursor,connection):
    now = datetime.datetime.utcnow().timestamp()
    sql_cmd="REPLACE into redditauthors " \
            "SELECT author,count(*)/(({}-min(created_ts))/86400) " \
            "FROM redditusercomments " \
            "WHERE author in (select author from redditauthors)" \
            "GROUP BY author".format(now)
    cursor.execute(sql_cmd)
    connection.commit()

def frequency_scheduler(cursor, connection, r):
    thetime=datetime.datetime.now()
    hour,day = thetime.hour,thetime.day
    #regularly schedule new user inserts as well as frequent posters
    #note that new users do not yet have a unique row in postfrequency
    if hour in (0,12):
        get_newusers(cursor, connection, r)
        sql_cmd="SELECT author FROM redditauthors WHERE postrate > 10 "
    #schedule infrequent posters every 2 or 7 days
    if hour == 1:
        if day%2 == 0:
            sql_cmd="SELECT author from redditauthors where postrate <= 10 and postrate > 1"
    if hour == 2:
        if day%7 == 0:
            sql_cmd="SELECT author from redditauthors where postrate <= 1"

    cursor.execute(sql_cmd)
    users_queue=cursor.fetchall()
    users_queue=[x[0] for x in users_queue]
    return(users_queue)

def fetch_latest_comment(cursor):
    sql_cmd="SELECT author, max(name) FROM redditusercomments group by author"
    cursor.execute(sql_cmd)
    maxcreated=cursor.fetchall()
    commentname_dict = { x[0]:x[1] for x in maxcreated }
    return(commentname_dict)

def remove_user(cursor,connection,user):
    print( 'username will be removed from initial query...')
    sql_cmd="DELETE FROM redditauthors where author='{}'".format(user)
    cursor.execute(sql_cmd)
    connection.commit()

def main():
    #Create user_agent per PRAW standards, establish local db access
    print(  datetime.datetime.now() )
    print( "\nstarting..." )
    user_agent = 'last 1000 comments for users from r/Columbus by /u/undelimited'
    r = praw.Reddit(user_agent=user_agent)
    connection = sqlite3.connect('/home/dan/reddit.db')
    cursor = connection.cursor()
    users_queue=frequency_scheduler(cursor, connection, r)
    commentname_dict = fetch_latest_comment(cursor)

    #Prepare the main while loop
    #Each loop will check if the user exists and either bulk insert if they do not
    #or row by row insert if they do
    usernum=0
    userstotal = len(users_queue)
    while users_queue:
        usernum+=1
        user = str(users_queue.pop())
        redditor = r.get_redditor(user)
        print('user ', usernum,'/', userstotal,' ==>> ', redditor, sep='')

        #Check if user exists in our sqlite3 db
        if commentname_dict.get(user) is None:
            #INSERT LOGIC
            chunk_insert(cursor,connection,redditor)
        #UPDATE LOGIC
        else:
        #useraccounts may have been deactivated. Cannot take action based on username dynamically inside
        #wrapper decorator
            try:
                row_insert(cursor,connection,redditor,commentname_dict,user)
            except praw.errors.NotFound:
                remove_user(cursor, connection, user)
            except:
                print("unexpected error:", sys.exc_info()[0])

    print('finished loading records...\n')
    print('inserting into postfrequency table...\n')
    # Post frequency will be used to bucket activity levels by user and select
    # them at an appropriate interval
    update_post_frequency(cursor, connection)
    cursor.close()
    print( "\nend" )
    print(  datetime.datetime.now() )

if __name__ == '__main__':
    main()


import cv2
import numpy as np
import imutils

def create_window(win_name):
    # Create image window
    cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(win_name, 600, 600)

def filter_contour(contour):
    curve_len = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.05 * curve_len, True)
    if len(approx) >= 2 and len(approx) < 50:
        x, y, w, h = cv2.boundingRect(approx)
        if h > 5 and h < 1900:
            return (x, y)

    return (-1, -1)

win_name = 'frame'
create_window(win_name)

filepath = 'training-data/no_qr_code/img27_648_648.jpg'

frame = cv2.imread(filepath)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)

contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
    x, y = filter_contour(cont)
    if x > -1:
        print(cont)
        cv2.drawContours(frame, [cont], 0, (0, 255, 0), 2)
        print(x, y)
cv2.imshow(win_name, frame)
cv2.waitKey(0)
cv2.destroyAllWindows()


# plot the critical q values against n

from math import factorial
from scipy.special import binom
import numpy as np
from scipy.optimize import bisect
import pandas as pd

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

from my_functions import read_matrix_M, calc_p_peak_random_group, calc_delta_p_leader_driven, q0_root_eqn_leader_driven, q1_root_eqn_leader_driven

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

# user parameters
# ---

res_dir = '../../results/leader_driven/'

# how many increments on the x-axis for plotting
ngrid = 50

nV =   [4, 6, 8, 10, 12, 14, 16, 18]
tauV = [2, 3, 4,  5,  6,  7,  8,  9]

# which default parameter values to use from the file default_params.csv
suffix = '_5'
suffix = '_6'
suffix = '_7'

# fixed parameters
# ---

# all parameter names corresponding to columns in default_params.csv
par_names = ['n', 'tau', 'W', 'X', 'Y', 'Z']

# read in the default parameter values
# ---

df = pd.read_csv('../default_params.csv')
df.set_index('suffix', inplace=True)
parD = { par_name: df[par_name].loc[suffix] for par_name in par_names }

# unpack parameter values
W = parD['W']
X = parD['X']
Y = parD['Y']
Z = parD['Z']

# find how the critical values vary with n
# ---

# places to store results
q0V = list()
q1V = list()
qhV = list()   # store q_star values

for n, tau in zip(nV, tauV):

    print('doing n = ' + str(n) + ', tau = ' + str(tau))

    # update parameter values
    parD['n'] = n
    parD['tau'] = tau

    # get previously saved lm, partns, and M
    # ---

    lm, partns, M_num, M_den = read_matrix_M('../../results/matrix_M/matrix_M' + str(n) + '.csv')
    M = M_num / M_den # the matrix for converting F to theta

    # find q_0, the maximum mistake probability where collectivists can still invade
    # ---

    # first, verify a high and low
    q_lo = 1e-6
    q_hi = 1-1e-6

    if np.sign(q0_root_eqn_leader_driven(parD, lm, partns, M, q_lo)) != np.sign(q0_root_eqn_leader_driven(parD, lm, partns, M, q_hi)):

        q_0 = bisect(lambda q: q0_root_eqn_leader_driven(parD, lm, partns, M, q), q_lo, q_hi)

    else:

        q_0 = np.nan

    # store
    q0V.append(q_0)

    # find q_1, the minimum mistake probability where individualists can invade
    # ---

    # first, verify a high and low
    q_lo = 1e-6
    q_hi = 1-1e-6

    if np.sign(q1_root_eqn_leader_driven(parD, lm, partns, M, q_lo)) != np.sign(q1_root_eqn_leader_driven(parD, lm, partns, M, q_hi)):

        q_1 = bisect(lambda q: q1_root_eqn_leader_driven(parD, lm, partns, M, q), q_lo, q_hi)

    else:

        q_1 = np.nan

    # store
    q1V.append(q_1)

    # find q_hat, if it exists
    # ---

    # find p_peak (provides bound for searching for isoclines)
    p_peak = calc_p_peak_random_group(parD)

    # find the maximum q where there are two isoclines

    # if Delta p at p_peak < 0, then there are zero interior equilibria when q=1;
    # otherwise, there are two
    delta_p_at_q1 = calc_delta_p_leader_driven(parD, lm, partns, M, 1, p_peak)

    if delta_p_at_q1 > 0:

        q_max = 1
        p_sing = p_peak

    else:

        # find where the transition from 2 to 0 equilibria is
        # ---

        q_hi = 1
        q_lo = q_1 if q_1 > q_0 else q_0
        q_mid = (q_lo + q_hi)/2
        p_mid = p_peak

        while abs(q_lo-q_hi) > 1e-4:

            # try to find the upper and lower isoclines at q_mid

            try:
                p_up = bisect(lambda p: calc_delta_p_leader_driven(parD, lm, partns, M, q_mid, p),
                        p_mid, 1-1e-6)
            except:
                p_up = np.nan

            try:
                p_lo = bisect(lambda p: calc_delta_p_leader_driven(parD, lm, partns, M, q_mid, p),
                        1e-6, p_mid)
            except:
                p_lo = np.nan

            if np.isnan(p_lo) or np.isnan(p_lo):
                q_hi = q_mid                # search to the left
                q_mid = (q_lo + q_mid)/2
            else:
                q_lo = q_mid                # search to the right
                q_mid = (q_hi + q_mid)/2
                p_mid = (p_up + p_lo)/2

        q_max = q_lo
        p_sing = p_mid

    # store
    qhV.append(q_max)

# write isocline data to file
# ---

# nV, q0V, q1V, qhV
df_out = pd.DataFrame(list(zip(nV, q0V, q1V, qhV)), columns=['nV', 'q0V', 'q1V', 'qhV'])
fname = res_dir + 'critical_v_n' + suffix + '.csv'
df_out.to_csv(fname, index=False)


'''
Created on 4 Jun 2015

@author: dawright
'''
from selenium                   import webdriver
from data.Constants             import Key
from pages.SignInPage           import WATLogin
from pages.WATHomePage          import WATHomePage
import time

class BaseTestCase(object):

    def setUp(self):
        if Key.sBrowser == "firefox":
            self.driver = webdriver.Firefox()
            self.driver.maximize_window()
        elif Key.sBrowser == "chrome":
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
        elif Key.sBrowser == "ie":
            self.driver = webdriver.Ie()
            self.driver.maximize_window()
        else:
            raise Exception("This browser is not supported")

    def navigate_to_page(self, url):
        self.driver.get(url)

    def login_to_the_WAT(self):
        SigninInPage_obj = WATLogin(self.driver)
        SigninInPage_obj.login_to_wat()
        time.sleep(2)

    def login_and_search_player(self):
        self.navigate_to_page(Key.urlWATBase) #Navigate to WAT Sign In Page

        self.login_to_the_WAT() #Login to the WAT

        WATHomePage_obj = WATHomePage(self.driver)
        WATHomePage_obj.playersearchbyid() #Find player

    def tearDown(self):
        self.driver.quit()


def gen_random_lst(length, min_val=1, max_val=10000):
    """
        Возвращает список случайных чисел.

        Возвращает список случайных чисел от 1 до 10000,
        но позволяет пользователю определять свой диапазон
    """
    import random

    rand_lst = [random.randint(min_val, max_val) for i in range(length+1)]

    return rand_lst

def bubble_sort(lst):
    """
    Функция-заглушка для сортировки методом пузырька

    Как бы сортирует, но на самом деле нет список,
    который был ей передан в качестве входного параметра
    Эта функция должна быть переписана
    """
    sorted_list = [i for i in lst]

    return sorted_list

def default_py_sort(lst):
    """
    Сортировка стандартным методом sorted, встроенным в Python
    """

    return sorted(lst)

lst = gen_random_lst(10000)

# print(bubble_sort(lst))

if __name__ == '__main__':

    import timeit

    print(timeit.timeit("default_py_sort(lst)",
                        setup="from __main__ import default_py_sort, lst", number=10))
    print(timeit.timeit("bubble_sort(lst)",
                        setup="from __main__ import bubble_sort, lst", number=10))


BANNED_WORDS_FILE = 'files/profanity_blocklist'
WHITELIST_FILE = 'files/whitelist'
BLACKLIST_FILE = 'files/blacklist'

SECRET_KEY = 'F6XCIZ6XV3m@oiVC'
WTF_CSRF_SECRET_KEY = 't1^7c*W13dK54^5b'

MITMDUMP_PATH = '/Users/arunswaminathan/.virtualenvs/netsec/bin/mitmdump'
MITMPROXY_MONITOR_PATH = '/Users/arunswaminathan/Workspace/StonyBrook/NetSec/design_project/mitmproxy_monitor.py'

##### FILE PATHS #####

FILE_PID = 'files/pid'
FILE_WEBSITE_VISITED = 'files/websites_visited.json'
FILE_WHITELIST = 'files/whitelist'
FILE_BLACKLIST = 'files/blacklist'
FILE_PROFANITY_BLOCKLIST = 'files/profanity_blocklist'


import re
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
from functools import reduce
import database as db
import file_manager as fm

stop_words = ["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself",
              "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",
              "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these",
              "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do",
              "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
              "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
              "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
              "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
              "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
              "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"]

def get_document(path, filename, doc_id, t):
    db.connect_to_database("IR_database")
    db.save_filename(doc_id, filename+".txt")
    global stop_words
    file = open(path+filename+".txt", t)
    counter = 0
    document = []
    for line in file:
        field = re.findall(r"\w+", line)
        for word in field:
            counter += 1
            word = word.lower()
            if word not in stop_words:
                key_word = (word, doc_id, counter)
                document.append(key_word)
    return document

def normalization(word):
    lemmatizer = WordNetLemmatizer()
    ps = PorterStemmer()

    term = lemmatizer.lemmatize(word)
    term = ps.stem(term)
    return term

def tokenizier():
    path = "Collection/"
    # collection = ["A Dark Brown Dog" , "A Pair of Silk Stockings" , "About Love","An Angel in Disguise",
    # "An Occurrence at Owl Creek Bridge","Araby","Army",
    # "Cousin Tribulation's Story","Desiree's Baby","Ex Oblivione","Hearts And Hands","How the Camel Got His Hump",
    # "Lost Hearts","On The Day of the Crucifixion",
    # "Regret","The Brave Tin Soldier","The Cactus","The Cat","The Gift of the Magi","The Haunted Mind",
    # "The Luck of Roaring Camp","The Monkey's Paw","The Skylight Room","The Story of An Hour",
    # "The Tale of Peter Rabbit"]
    collection = fm.get_collection_names(path)
    collection_key_words = []
    for index, document in enumerate(collection):
        key_words_in_one_document = get_document(path, document, index, "r")
        #  normalized_key_words = []
        for word_info in key_words_in_one_document:
            word = normalization(word_info[0])
            collection_key_words.append((word, word_info[1], word_info[2]))
    return collection_key_words

def pre_processed_query(query):
    post_query = []
    counter = 0
    field = re.findall(r"\w+", query)
    for word in field:
        counter += 1
        word = word.lower()
        global stop_words
        if word not in stop_words:
            word = normalization(word)
            post_query.append((word, counter))
    return post_query

def find_term(word, dictionary):
    for item in dictionary:
        if item[0] == word:
            return item[1]

def get_id(post_query, dictionary):
    term_position_id = []
    for item in post_query:
        _id = find_term(item[0], dictionary)
        if _id is None:
            return -1
        position = item[1]
        term_position_id.append((position, _id))
    return term_position_id

def find_common(all_doc):
    res = list(reduce(lambda i, j: i & j, (set(x) for x in all_doc)))
    return res

def positional_intersect(pl1, pl2, d):
    answer = []
    for x, y in zip(range(len(pl1)), range(len(pl2))):
        #  tuple of first->last doc
        tuple1 = pl1[x]
        tuple2 = pl2[y]
        if tuple1[0] == tuple2[0]:
            intersection_list = []
            positions1 = tuple1[1]
            positions2 = tuple2[1]
            i = 0
            j = 0
            while i < len(positions1) and j < len(positions2):
                if positions2[j] - positions1[i] == d:
                    intersection_list.append(positions2[j])
                    i += 1
                    j += 1
                elif positions1[i] > positions2[j]:
                    j += 1
                else:
                    i += 1
            answer.append((tuple1[0], intersection_list))
    return answer

def merge(query, dictionary):
    query_terms = pre_processed_query(query)
    term_position_id = get_id(query_terms, dictionary)
    if term_position_id == -1:
        return None
    query_postings = []
    for word in term_position_id:
        posting_list = db.load_posting_list(word[1])
        query_postings.append((word[0], posting_list))
    differences = []
    for i in range(len(query_postings) - 1):
        diff = query_postings[i + 1][0] - query_postings[i][0]
        differences.append(diff)
    all_doc = []
    for item in query_postings:
        term_doc = []
        for tup in item[1]:
            term_doc.append(tup[0])
        all_doc.append(term_doc)
    common_docs = find_common(all_doc)
    common_postings = []
    for item in query_postings:
        term = []
        for tup in item[1]:
            if tup[0] in common_docs:
                term.append((tup[0], tup[1]))
        common_postings.append(term)
    result_docs = []
    if len(common_postings) > 1:
        result = positional_intersect(common_postings[0], common_postings[1], differences[0])
        for i, d in zip(range(2, len(common_postings)), range(1, len(differences))):
            result = positional_intersect(result, common_postings[i], differences[d])
        for item in result:
            if len(item[1]) != 0:
                result_docs.append(item[0])
    else:
        for term in common_postings:
            for item in term:
                if len(item[1]) != 0:
                    result_docs.append(item[0])
    return result_docs


import constants

class Shape:
    coords = []
    old = []
    def __init__(self, coordinates):
        Shape.old = []
        for i in coordinates:
            cur = []
            for j in i:
                cur.append(j)
            Shape.coords.append(cur)

    def next(self, key):
        for i in Shape.coords:
            cur = []
            for j in i:
                cur.append(j)
            Shape.old.append(cur)

        if key == "LEFT":
            for i in Shape.coords:
                i[0] -= 33
        elif key == "RIGHT":
            for i in Shape.coords:
                i[0] += 33
        elif key == "UP":
            pass
        else:
            for i in Shape.coords:
                i[1] += 33

        if (Shape.coords[-1][-1] > 657):
            Shape.coords = []
            return False
        Shape.old = []
        return True

'''
to do:
1) Проверка последней строки на полное соответствие
2) команда up для любого шейпа
3) Генерация
4) Проверка на левых и правых границ
'''


# João, Robenildo, Victor, Marcos

# Programa que verifica quem é o cachorro mais velho
class Dog:
  def __init__(self, nome, idade):
    self.nome = nome
    self.idade = idade

  def __str__(self):
    return self.nome+" "+str(self.idade)

def mais_velho(lista):
  '''
    Em caso de empate, retorna o primeiro
  '''
  velho = lista[0]
  for i in lista:
    if velho.idade < i.idade:
      velho = i
  return velho

n = int(input("Entre com o número de cachorros: "))
lista = []

for i in range(n):
  cachorro = Dog(input("Digite o nome do cachorro: "), int(input("Digite a idade do cachorro: ")))
  lista.append(cachorro)

dog_older = mais_velho(lista)
print(f"O cachorro mais velho é: {dog_older.nome} com {dog_older.idade} anos.")


from sys import stdin

N = stdin.readline().rstrip()
ans = 0

N = N[::-1]
N = N + '0'
kuriagari = 0

for i in range(len(N)):
    r = int(N[i])
    if kuriagari == 1:
        r += 1
    if 10 - r < r:
        kuriagari = 1
    else:
        kuriagari = 0
    if r == 5 and int(N[i + 1]) > 4:
        kuriagari = 1
    if r == 10:
        r = 0
    ans += min(r, 10 - r)

print(ans)


'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''

def count_th(word):
    i = 0

    def search_word(word, i):

        if(len(word) < 2):
            return i
        else:
            print(f'as int: {word[0]}')
            if(word[0] == "t" and word[1] == "h"):
                i += 1
                word = word[2:]
                print(word)
                return search_word(word, i)
            else:
                word = word[1:]
                return search_word(word, i)

    return search_word(word, i)

count_th("shithth")


"""
Support for monitoring a Sense energy sensor device.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.sense/
"""
import logging

from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.sense import SENSE_DATA

DEPENDENCIES = ['sense']

_LOGGER = logging.getLogger(__name__)

BIN_SENSOR_CLASS = 'power'
MDI_ICONS = {
    'ac': 'air-conditioner',
    'aquarium': 'fish',
    'car': 'car-electric',
    'computer': 'desktop-classic',
    'cup': 'coffee',
    'dehumidifier': 'water-off',
    'dishes': 'dishwasher',
    'drill': 'toolbox',
    'fan': 'fan',
    'freezer': 'fridge-top',
    'fridge': 'fridge-bottom',
    'game': 'gamepad-variant',
    'garage': 'garage',
    'grill': 'stove',
    'heat': 'fire',
    'heater': 'radiatior',
    'humidifier': 'water',
    'kettle': 'kettle',
    'leafblower': 'leaf',
    'lightbulb': 'lightbulb',
    'media_console': 'set-top-box',
    'modem': 'router-wireless',
    'outlet': 'power-socket-us',
    'papershredder': 'shredder',
    'printer': 'printer',
    'pump': 'water-pump',
    'settings': 'settings',
    'skillet': 'pot',
    'smartcamera': 'webcam',
    'socket': 'power-plug',
    'sound': 'speaker',
    'stove': 'stove',
    'trash': 'trash-can',
    'tv': 'television',
    'vacuum': 'robot-vacuum',
    'washer': 'washing-machine',
}

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Sense binary sensor."""
    if discovery_info is None:
        return

    data = hass.data[SENSE_DATA]

    sense_devices = data.get_discovered_device_data()
    devices = [SenseDevice(data, device) for device in sense_devices
               if device['tags']['DeviceListAllowed'] == 'true']
    add_entities(devices)

def sense_to_mdi(sense_icon):
    """Convert sense icon to mdi icon."""
    return 'mdi:{}'.format(MDI_ICONS.get(sense_icon, 'power-plug'))

class SenseDevice(BinarySensorDevice):
    """Implementation of a Sense energy device binary sensor."""

    def __init__(self, data, device):
        """Initialize the Sense binary sensor."""
        self._name = device['name']
        self._id = device['id']
        self._icon = sense_to_mdi(device['icon'])
        self._data = data
        self._state = False

    @property
    def is_on(self):
        """Return true if the binary sensor is on."""
        return self._state

    @property
    def name(self):
        """Return the name of the binary sensor."""
        return self._name

    @property
    def unique_id(self):
        """Return the id of the binary sensor."""
        return self._id

    @property
    def icon(self):
        """Return the icon of the binary sensor."""
        return self._icon

    @property
    def device_class(self):
        """Return the device class of the binary sensor."""
        return BIN_SENSOR_CLASS

    def update(self):
        """Retrieve latest state."""
        from sense_energy.sense_api import SenseAPITimeoutException
        try:
            self._data.get_realtime()
        except SenseAPITimeoutException:
            _LOGGER.error("Timeout retrieving data")
            return
        self._state = self._name in self._data.active_devices


# coding: utf-8

"""
    ORY Hydra

    Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here.  # noqa: E501

    The version of the OpenAPI document: v1.7.0
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from ory_hydra_client.configuration import Configuration

class UserinfoResponse(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'birthdate': 'str',
        'email': 'str',
        'email_verified': 'bool',
        'family_name': 'str',
        'gender': 'str',
        'given_name': 'str',
        'locale': 'str',
        'middle_name': 'str',
        'name': 'str',
        'nickname': 'str',
        'phone_number': 'str',
        'phone_number_verified': 'bool',
        'picture': 'str',
        'preferred_username': 'str',
        'profile': 'str',
        'sub': 'str',
        'updated_at': 'int',
        'website': 'str',
        'zoneinfo': 'str'
    }

    attribute_map = {
        'birthdate': 'birthdate',
        'email': 'email',
        'email_verified': 'email_verified',
        'family_name': 'family_name',
        'gender': 'gender',
        'given_name': 'given_name',
        'locale': 'locale',
        'middle_name': 'middle_name',
        'name': 'name',
        'nickname': 'nickname',
        'phone_number': 'phone_number',
        'phone_number_verified': 'phone_number_verified',
        'picture': 'picture',
        'preferred_username': 'preferred_username',
        'profile': 'profile',
        'sub': 'sub',
        'updated_at': 'updated_at',
        'website': 'website',
        'zoneinfo': 'zoneinfo'
    }

    def __init__(self, birthdate=None, email=None, email_verified=None, family_name=None, gender=None, given_name=None, locale=None, middle_name=None, name=None, nickname=None, phone_number=None, phone_number_verified=None, picture=None, preferred_username=None, profile=None, sub=None, updated_at=None, website=None, zoneinfo=None, local_vars_configuration=None):  # noqa: E501
        """UserinfoResponse - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._birthdate = None
        self._email = None
        self._email_verified = None
        self._family_name = None
        self._gender = None
        self._given_name = None
        self._locale = None
        self._middle_name = None
        self._name = None
        self._nickname = None
        self._phone_number = None
        self._phone_number_verified = None
        self._picture = None
        self._preferred_username = None
        self._profile = None
        self._sub = None
        self._updated_at = None
        self._website = None
        self._zoneinfo = None
        self.discriminator = None

        if birthdate is not None:
            self.birthdate = birthdate
        if email is not None:
            self.email = email
        if email_verified is not None:
            self.email_verified = email_verified
        if family_name is not None:
            self.family_name = family_name
        if gender is not None:
            self.gender = gender
        if given_name is not None:
            self.given_name = given_name
        if locale is not None:
            self.locale = locale
        if middle_name is not None:
            self.middle_name = middle_name
        if name is not None:
            self.name = name
        if nickname is not None:
            self.nickname = nickname
        if phone_number is not None:
            self.phone_number = phone_number
        if phone_number_verified is not None:
            self.phone_number_verified = phone_number_verified
        if picture is not None:
            self.picture = picture
        if preferred_username is not None:
            self.preferred_username = preferred_username
        if profile is not None:
            self.profile = profile
        if sub is not None:
            self.sub = sub
        if updated_at is not None:
            self.updated_at = updated_at
        if website is not None:
            self.website = website
        if zoneinfo is not None:
            self.zoneinfo = zoneinfo

    @property
    def birthdate(self):
        """Gets the birthdate of this UserinfoResponse.  # noqa: E501

        End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.  # noqa: E501

        :return: The birthdate of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._birthdate

    @birthdate.setter
    def birthdate(self, birthdate):
        """Sets the birthdate of this UserinfoResponse.

        End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.  # noqa: E501

        :param birthdate: The birthdate of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._birthdate = birthdate

    @property
    def email(self):
        """Gets the email of this UserinfoResponse.  # noqa: E501

        End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.  # noqa: E501

        :return: The email of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._email

    @email.setter
    def email(self, email):
        """Sets the email of this UserinfoResponse.

        End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.  # noqa: E501

        :param email: The email of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._email = email

    @property
    def email_verified(self):
        """Gets the email_verified of this UserinfoResponse.  # noqa: E501

        True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.  # noqa: E501

        :return: The email_verified of this UserinfoResponse.  # noqa: E501
        :rtype: bool
        """
        return self._email_verified

    @email_verified.setter
    def email_verified(self, email_verified):
        """Sets the email_verified of this UserinfoResponse.

        True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.  # noqa: E501

        :param email_verified: The email_verified of this UserinfoResponse.  # noqa: E501
        :type: bool
        """

        self._email_verified = email_verified

    @property
    def family_name(self):
        """Gets the family_name of this UserinfoResponse.  # noqa: E501

        Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.  # noqa: E501

        :return: The family_name of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._family_name

    @family_name.setter
    def family_name(self, family_name):
        """Sets the family_name of this UserinfoResponse.

        Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.  # noqa: E501

        :param family_name: The family_name of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._family_name = family_name

    @property
    def gender(self):
        """Gets the gender of this UserinfoResponse.  # noqa: E501

        End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.  # noqa: E501

        :return: The gender of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._gender

    @gender.setter
    def gender(self, gender):
        """Sets the gender of this UserinfoResponse.

        End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.  # noqa: E501

        :param gender: The gender of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._gender = gender

    @property
    def given_name(self):
        """Gets the given_name of this UserinfoResponse.  # noqa: E501

        Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.  # noqa: E501

        :return: The given_name of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._given_name

    @given_name.setter
    def given_name(self, given_name):
        """Sets the given_name of this UserinfoResponse.

        Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.  # noqa: E501

        :param given_name: The given_name of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._given_name = given_name

    @property
    def locale(self):
        """Gets the locale of this UserinfoResponse.  # noqa: E501

        End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.  # noqa: E501

        :return: The locale of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._locale

    @locale.setter
    def locale(self, locale):
        """Sets the locale of this UserinfoResponse.

        End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.  # noqa: E501

        :param locale: The locale of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._locale = locale

    @property
    def middle_name(self):
        """Gets the middle_name of this UserinfoResponse.  # noqa: E501

        Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.  # noqa: E501

        :return: The middle_name of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._middle_name

    @middle_name.setter
    def middle_name(self, middle_name):
        """Sets the middle_name of this UserinfoResponse.

        Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.  # noqa: E501

        :param middle_name: The middle_name of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._middle_name = middle_name

    @property
    def name(self):
        """Gets the name of this UserinfoResponse.  # noqa: E501

        End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.  # noqa: E501

        :return: The name of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """Sets the name of this UserinfoResponse.

        End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.  # noqa: E501

        :param name: The name of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._name = name

    @property
    def nickname(self):
        """Gets the nickname of this UserinfoResponse.  # noqa: E501

        Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.  # noqa: E501

        :return: The nickname of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._nickname

    @nickname.setter
    def nickname(self, nickname):
        """Sets the nickname of this UserinfoResponse.

        Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.  # noqa: E501

        :param nickname: The nickname of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._nickname = nickname

    @property
    def phone_number(self):
        """Gets the phone_number of this UserinfoResponse.  # noqa: E501

        End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.  # noqa: E501

        :return: The phone_number of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._phone_number

    @phone_number.setter
    def phone_number(self, phone_number):
        """Sets the phone_number of this UserinfoResponse.

        End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.  # noqa: E501

        :param phone_number: The phone_number of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._phone_number = phone_number

    @property
    def phone_number_verified(self):
        """Gets the phone_number_verified of this UserinfoResponse.  # noqa: E501

        True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.  # noqa: E501

        :return: The phone_number_verified of this UserinfoResponse.  # noqa: E501
        :rtype: bool
        """
        return self._phone_number_verified

    @phone_number_verified.setter
    def phone_number_verified(self, phone_number_verified):
        """Sets the phone_number_verified of this UserinfoResponse.

        True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.  # noqa: E501

        :param phone_number_verified: The phone_number_verified of this UserinfoResponse.  # noqa: E501
        :type: bool
        """

        self._phone_number_verified = phone_number_verified

    @property
    def picture(self):
        """Gets the picture of this UserinfoResponse.  # noqa: E501

        URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.  # noqa: E501

        :return: The picture of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._picture

    @picture.setter
    def picture(self, picture):
        """Sets the picture of this UserinfoResponse.

        URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.  # noqa: E501

        :param picture: The picture of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._picture = picture

    @property
    def preferred_username(self):
        """Gets the preferred_username of this UserinfoResponse.  # noqa: E501

        Non-unique shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace.  # noqa: E501

        :return: The preferred_username of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._preferred_username

    @preferred_username.setter
    def preferred_username(self, preferred_username):
        """Sets the preferred_username of this UserinfoResponse.

        Non-unique shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace.  # noqa: E501

        :param preferred_username: The preferred_username of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._preferred_username = preferred_username

    @property
    def profile(self):
        """Gets the profile of this UserinfoResponse.  # noqa: E501

        URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.  # noqa: E501

        :return: The profile of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._profile

    @profile.setter
    def profile(self, profile):
        """Sets the profile of this UserinfoResponse.

        URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.  # noqa: E501

        :param profile: The profile of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._profile = profile

    @property
    def sub(self):
        """Gets the sub of this UserinfoResponse.  # noqa: E501

        Subject - Identifier for the End-User at the IssuerURL.  # noqa: E501

        :return: The sub of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._sub

    @sub.setter
    def sub(self, sub):
        """Sets the sub of this UserinfoResponse.

        Subject - Identifier for the End-User at the IssuerURL.  # noqa: E501

        :param sub: The sub of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._sub = sub

    @property
    def updated_at(self):
        """Gets the updated_at of this UserinfoResponse.  # noqa: E501

        Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.  # noqa: E501

        :return: The updated_at of this UserinfoResponse.  # noqa: E501
        :rtype: int
        """
        return self._updated_at

    @updated_at.setter
    def updated_at(self, updated_at):
        """Sets the updated_at of this UserinfoResponse.

        Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.  # noqa: E501

        :param updated_at: The updated_at of this UserinfoResponse.  # noqa: E501
        :type: int
        """

        self._updated_at = updated_at

    @property
    def website(self):
        """Gets the website of this UserinfoResponse.  # noqa: E501

        URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.  # noqa: E501

        :return: The website of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._website

    @website.setter
    def website(self, website):
        """Sets the website of this UserinfoResponse.

        URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.  # noqa: E501

        :param website: The website of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._website = website

    @property
    def zoneinfo(self):
        """Gets the zoneinfo of this UserinfoResponse.  # noqa: E501

        String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.  # noqa: E501

        :return: The zoneinfo of this UserinfoResponse.  # noqa: E501
        :rtype: str
        """
        return self._zoneinfo

    @zoneinfo.setter
    def zoneinfo(self, zoneinfo):
        """Sets the zoneinfo of this UserinfoResponse.

        String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.  # noqa: E501

        :param zoneinfo: The zoneinfo of this UserinfoResponse.  # noqa: E501
        :type: str
        """

        self._zoneinfo = zoneinfo

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, UserinfoResponse):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, UserinfoResponse):
            return True

        return self.to_dict() != other.to_dict()


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def sample(probabilities, mode='bernoulli'):
    ''' Sample a tensor based on the probabilities (A tensor given by get_probabilities)'''
    if mode=='bernoulli':
        return tf.floor(probabilities + tf.random_uniform(tf.shape(probabilities), 0, 1))
    elif mode=='gaussian':
        return tf.add(probabilities, tf.random_normal(tf.shape(probabilities), mean=0.0, stddev=1.)) # Add noise to the original probabilities

# Simple RBM class
class RBM:

    def __init__(self, n_visible, n_hidden, lr, epochs, mode='bernoulli'):
        ''' Initialize a model for an RBM with one layer of hidden units '''
        self.mode = mode # bernoulli or gaussian RBM
        self.n_hidden = n_hidden #  Number of hidden nodes
        self.n_visible = n_visible # Number of visible nodes
        self.lr = lr # Learning rate for the CD algorithm
        self.epochs = epochs # Number of iterations to run the algorithm for

        # Initialize weights and biases
        with tf.name_scope('Weights'):
            self.W = tf.Variable(tf.random_normal([self.n_visible, self.n_hidden], mean=0., stddev=4 * np.sqrt(6. / (self.n_visible + self.n_hidden))), name="weights")
        tf.summary.histogram('weights',self.W)
        self.vb = tf.Variable(tf.zeros([1, self.n_visible]),tf.float32, name="visible_bias")
        self.hb = tf.Variable(tf.zeros([1, self.n_hidden]),tf.float32, name="hidden_bias")

    def get_probabilities(self, layer, val):
        ''' Return a tensor of probabilities associated with the layer specified'''
        if layer == 'hidden':
            with tf.name_scope("Hidden_Probabilities"):
                if self.mode=='bernoulli':
                    return tf.nn.sigmoid(tf.matmul(val, self.W) + self.hb)
                elif self.mode=='gaussian':
                    return tf.matmul(val, self.W) + self.hb

        elif layer == 'visible':
            with tf.name_scope("Visible_Probabilities"):
                return tf.nn.sigmoid(tf.matmul(val, tf.transpose(self.W)) + self.vb)

    def CD(self, v, K=1):
        ''' K-step Contrastive Divergence using Gibbs sampling. Return parameters update. '''
        with tf.name_scope("Contrastive_Divergence"):
            h_prob = self.get_probabilities('hidden', v)
            h_state = sample(h_prob, mode=self.mode)
            pos_divergence = tf.matmul(tf.transpose(v), h_prob) # Positive Divergence + h(v).v^T

            fake_v_prob = self.get_probabilities('visible', h_state)
            fake_v_state = fake_v_prob #sample(fake_v_prob)

            fake_h_prob = self.get_probabilities('hidden', fake_v_state)
            fake_h_state = sample(fake_h_prob, mode=self.mode)

            for i in range(K-1): # Number of steps to run the algorithm

                fake_v_prob = self.get_probabilities('visible', fake_h_state)
                fake_v_state = fake_v_prob #sample(fake_v_prob)

                fake_h_prob = self.get_probabilities('hidden', fake_v_state)
                fake_h_state = sample(fake_h_prob, mode=self.mode)

            neg_divergence = tf.matmul(tf.transpose(fake_v_state), fake_h_prob) # Negative Divergence - h(v').v'^T

            dW = pos_divergence-neg_divergence
            dvb = v-fake_v_state
            dhb = h_prob-fake_h_prob

            # Similarity between reconstructed visible layer and input during training.
            self.rec_error = tf.reduce_mean(tf.squared_difference(v, fake_v_state))
            tf.summary.scalar('reconstruction_error', self.rec_error)

            self.div = tf.reduce_mean(tf.abs(dW))
            tf.summary.scalar('weights_increment', self.div)

            return dW, dvb, dhb

    def update(self, v, K=1):
        batch_size = tf.cast(tf.shape(v)[0], tf.float32) # batch size
        dW, dvb, dhb = self.CD(v, K=K) # contrastive divergence

        delta_w = (self.lr/batch_size)*dW # weight gradient
        delta_vb = (self.lr/batch_size)*(tf.reduce_sum(dvb, 0, keep_dims=True)) # visible bias gradient
        delta_hb = (self.lr/batch_size)*(tf.reduce_sum(dhb, 0, keep_dims=True)) # hidden bias gradient

        train_op = [self.W.assign_add(delta_w), self.vb.assign_add(delta_vb), self.hb.assign_add(delta_hb)]
        return train_op

    def gibbs(self, steps, v):
        ''' Use the Gibbs sampler for a network of hidden and visible units. Return a sampled version of the input'''
        with tf.name_scope("Gibbs_sampling"):
            for i in range(steps): # Number of steps to run the algorithm
                hidden_p = self.get_probabilities('hidden', v) # v: input data
                h = sample(hidden_p, mode=self.mode)

                visible_p = self.get_probabilities('visible', h)
                v = visible_p
                #v = sample(visible_p)
            return visible_p

    def free_energy(self, v):
        ''' Compute the free energy for a visible state'''
        vbias_term = tf.matmul(v, tf.transpose(self.vb))
        x_b = tf.matmul(v, self.W) + self.hb
        hidden_term = tf.reduce_sum(tf.log(1 + tf.exp(x_b)))
        return - hidden_term - vbias_term

    def get_feature_map(self):
        ''' Return hidden features'''
        ft_map = {}
        for k in range(self.n_hidden):
            ft_map[k] = self.get_probabilities('visible', tf.expand_dims(tf.one_hot(k+1, self.n_hidden),0))
        return ft_map


import asyncio
import aiohttp
from uvloop import EventLoopPolicy

async def get(url: str, session: aiohttp.ClientSession) -> None:
    async with session.get(url) as response:
        print(str.format('[~] HTTP GET url: {}', response.url))
        print(str.format('[~] status response: {}', response.status))
        text = await response.text()
        print(str.format('[~] response text (auto-decoded): {}', text))

async def post(url: str, session: aiohttp.ClientSession, data: bytes):
    async with session.post(url, data=data) as response:
        print(str.format(
            '[~] HTTP POST "{}" status code: {}', url, response.status
        ))

async def put(url: str, session: aiohttp.ClientSession, data: bytes):
    async with session.put(url, data=data) as response:
        print(str.format(
            '[~] HTTP PUT "{}" status code: {}', url, response.status
        ))

async def delete(url: str, session: aiohttp.ClientSession):
    async with session.delete(url) as response:
        print(str.format(
            '[~] HTTP DELETE "{}" status code: {}', url, response.status
        ))

async def head(url: str, session: aiohttp.ClientSession):
    async with session.head(url) as response:
        print(str.format(
            '[~] HTTP HEAD "{}" status code: {}', url, response.status
        ))

async def options(url: str, session: aiohttp.ClientSession):
    async with session.options(url) as response:
        print(str.format(
            '[~] HTTP OPTIONS "{}" status code: {}', url, response.status
        ))

async def patch(url: str, session: aiohttp.ClientSession, data: bytes):
    async with session.patch(url, data=data) as response:
        print(str.format(
            '[~] HTTP PATCH "{}" status code: {}', url, response.status
        ))

async def runner():
    async with aiohttp.ClientSession() as session:
        print('-' * 80)
        # await get('https://api.github.com/events', session)
        await get('http://httpbin.org/get', session)

        print('-' * 80)
        await post('http://httpbin.org/post', session, b'data')

        print('-' * 80)
        await put('http://httpbin.org/put', session, b'data')

        print('-' * 80)
        await patch('http://httpbin.org/patch', session, b'data')

        print('-' * 80)
        await delete('http://httpbin.org/delete', session)

        print('-' * 80)
        await head('http://httpbin.org/head', session)

        print('-' * 80)
        await options('http://httpbin.org/options', session)

def main():
    asyncio.set_event_loop_policy(EventLoopPolicy())
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(runner())
    finally:
        loop.close()

if __name__ == '__main__':
    main()


# This program is designed to create a list of landTrendr parameters varations. The parameter varations
# are drawn from lists of parameter values.

# output file path (txt file)
outFile = ""

# list of parameter confingations
Segments = [6,8,10,11]
#Segments = [6,9,11]
spike = [0.75,0.90,1.0]
#spike = [0.75,0.90,1.0]
recovery = [0.25,0.50,0.90,1.0]
#recovery = [0.25,0.65,1.0]
pValue = [0.05,0.10,0.15]

list = []
for seg in Segments:
    for ske in spike:
        for rec in recovery:
            for pv in pValue:
                newlist = [seg,ske,rec,pv]
                list.append(newlist)
                print('newlist', newlist)

# make empty list. this will parameters appended to it
parameterDicList = []

# iterator
for subList in list:

# asign each parameter to template
    ltParamTemplate = "{timeSeries: ee.ImageCollection([]), maxSegments: "+str(subList[0])+" , spikeThreshold: "+str(subList[1])+", vertexCountOvershoot: 3, preventOneYearRecovery: true, recoveryThreshold: "+str(subList[2])+", pvalThreshold: "+str(subList[3])+", bestModelProportion: 0.25, minObservationsNeeded: "+str(subList[0])+" }"

# append completed parameters dicionary to emtpy list
    parameterDicList.append(ltParamTemplate)

# end iterator
print(parameterDicList)

# add list to text file
#export file
with open("./LT_parameter_varations_list_dic_144.txt", "w") as output:
    output.write(str(parameterDicList))


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if head==None:
            return

        slow=head
        fast=head
        flag=False
        while fast!=None and fast.next!=None:
            slow=slow.next
            fast=fast.next.next
            if fast==slow:
                flag=True
                break
        if flag:
            fast=head
            while(slow!=fast):
                slow=slow.next
                fast=fast.next
            return fast
        else:
            return None
Time is O(n)
Space is O(1)


from setuptools import setup

long_description = """\
Anaconda Python cannot be installed via pip or other PyPI-based installers.
Please use the Anaconda Installer to bootstrap Anaconda Python onto your system.
"""

setup(
    name = "anaconda",
    version = "0.0.1.1",
    author = "Kale Franz",
    author_email = "kfranz@anaconda.com",
    description = "Please use the Anaconda installer.",
    long_description=long_description,
)


import argparse
import gym
import os
import torch
from deepassist.util.policies import *
from deepassist.util import make_env_
from dl.modules import QFunction
from dl.util import Checkpointer

def evaluate(policy, episodes, env, device):
    obs = env.reset()

    episode_rewards  = [0.0]
    episode_outcomes = []
    episode_lens     = [0]

    for episode in range(episodes):
        done = False
        while not done:
            obs = torch.from_numpy(obs).to(device)
            ac = policy(obs)

            obs, rew, done, _ = env.step(ac)

            episode_rewards[-1] += rew
            episode_lens[-1] += 1

            if done:
                obs = env.reset()
                episode_outcomes.append(rew)
                episode_rewards.append(0.0)
                episode_lens.append(0)

    mean_ep_reward = round(np.mean(episode_rewards), 1)
    mean_ep_succ   = round(np.mean([1 if x==100 else 0 for x in episode_outcomes]), 2)
    mean_ep_crash  = round(np.mean([1 if x==-100 else 0 for x in episode_outcomes]), 2)
    mean_ep_len    = round(np.mean(episode_lens), 2)

    print("======== {} ========".format(policy.__class__.__name__))
    print("Mean Reward: {}".format(mean_ep_reward))
    print("Success Rate: {}".format(mean_ep_succ))
    print("Crash Rate: {}".format(mean_ep_crash))
    print("Mean Episode Length: {}\n".format(mean_ep_len))

    return

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='Evaluate Pilot.')
    parser.add_argument('logdir', type=str, help='logdir')
    parser.add_argument('-l', '--model_t', default=None, type=int)
    parser.add_argument('-e', '--eval_episodes', default=100, type=int)
    parser.add_argument('-g', '--gpu', action='store_true')
    args = parser.parse_args()

    env = make_env_(using_lander_reward_shaping=True)

    net = QFunction(env.observation_space.shape, env.action_space)
    ckptr = Checkpointer(os.path.join(args.logdir, 'ckpts'), max_ckpts_to_keep = 1, min_ckpt_period = 100000)

    save_dict = ckptr.load(t=args.model_t)

    if args.model_t is not None:
        net.load_state_dict(save_dict['net'])

    device = device = torch.device("cuda:0" if args.gpu and torch.cuda.is_available() else "cpu")
    net.to(device)

    fullpolicy   = FullPilotPolicy(net)
    laggypolicy  = LaggyPilotPolicy(net)
    noisypolicy  = NoisyPilotPolicy(net)
    sensorpolicy = SensorPilotPolicy()
    nooppolicy   = NoopPilotPolicy()

    policies = [
        fullpolicy,
        laggypolicy,
        noisypolicy,
        sensorpolicy,
        nooppolicy
    ]

    print("Evaluating on {} episodes\n".format(args.eval_episodes))
    for policy in policies:
        evaluate(policy, args.eval_episodes, env, device)


import GroupBy

from ..MaxObjects import Wheel
from ..MaxObjects import Box

from Py3dsMax import mxs

def import_wheels(node_positions, wheels, object_holder):
    fix_negative_rigidity_nodes(wheels)
    group_helper = GroupBy.DictHelper()
    group_helper.dont_autocompare = ['node1', 'node2']
    grouped_wheels = GroupBy.group_by_comparison_function(group_helper.perform_camparison, wheels)
    for i, wheel_group in enumerate(grouped_wheels):
        import_wheel(i, node_positions, wheel_group, object_holder)

def import_wheel(counter, node_positions, wheel_group, object_holder):
    node_pairs = []
    for wheel in wheel_group:
        temp = []
        node_pairs.append(temp)
        temp.append(node_positions[wheel['node1']])
        temp.append(node_positions[wheel['node2']])
    wheel = Wheel.Wheel(node_pairs, wheel_group[0])
    wheel.name = "wheel_" + str(counter)
    object_holder.add_object(wheel.max_object)

    first_wheel = wheel_group[0]
    if first_wheel['rigidity_node'] != 9999:
        rigidity_node = Box.Box(node_positions[first_wheel['rigidity_node']],
                                name="rigidity_node_" + wheel.name,
                                wirecolor=mxs.color(55, 76, 83))
        object_holder.add_object(rigidity_node.max_object)

def fix_negative_rigidity_nodes(wheels):
    for wheel in wheels:
        for key, value in wheel.items():
            if key is 'rigidity_node':
                if value < 0:
                    wheel['rigidity_node'] = -value


import requests
from bs4 import BeautifulSoup
import sys

class MultilingualOnlineTranslator:
    def __init__(self):
        self.source_language = sys.argv[1]
        self.destination_language = sys.argv[2]
        self.word = sys.argv[3]
        self.languages_list = ("Arabic", "German", "English", "Spanish", "French", "Hebrew", "Japanese", "Dutch",
                               "Polish", "Portuguese", "Romanian", "Russian", "Turkish")
        self.session = requests.Session()

    def mainFunction(self):
        if (self.source_language.title() not in self.languages_list) or \
                ((self.destination_language.title() not in self.languages_list) and
                 (self.destination_language != "all")):
            print("Sorry, the program doesn't support this lang")
        else:
            if self.destination_language == "all":
                for i in range(0, len(self.languages_list)):
                    if i != self.source_language:
                        self.showData(destination_language=self.languages_list[i].lower())
            else:
                self.showData(destination_language=self.destination_language)

    def showData(self, destination_language):
        request = self.session.get(f"https://context.reverso.net/translation/"
                                   f"{self.source_language}-{destination_language}/{self.word}#",
                                   headers={"User-Agent": "Mozilla/5.0"})
        if request:
            soup = BeautifulSoup(request.content, "html.parser")
            soup.prettify()
            print()
            left = [i.text.strip() for i in soup.findAll("div", attrs={"class": "src ltr"})]

            if left:
                with open(f"{self.word}.txt", "a+", encoding="utf-8") as file:
                    file.write(f"{destination_language.title()} Translations:\n")
                    for i in [i.text.strip() for i in soup.find_all("a", {"class": 'translation'})][1:6]:
                        file.write(f"{i}\n")
                    file.write(f"\n{destination_language.title()} Example:\n")

                    if self.languages_list.index(destination_language.title()) == 0:
                        right = [i.text.strip() for i in soup.find_all("div", attrs={"class": "trg rtl arabic"})]
                    elif self.languages_list.index(destination_language.title()) == 5:
                        right = [i.text.strip() for i in soup.find_all("div", attrs={"class": "trg rtl"})]
                    else:
                        right = [i.text.strip() for i in soup.find_all("div", attrs={"class": "trg ltr"})]
                    for l, j, k in zip(range(5), left, right):
                        file.write(f"{j}\n{k}\n")

                with open(f"{self.word}.txt", "r", encoding="utf-8") as file:
                    for i in file.read().split("\n"):
                        print(i)
            else:
                print(f"Sorry, unable to find {self.word}")
        else:
            print("Something wrong with your internet connection")

if __name__ == '__main__':
    MultilingualOnlineTranslator().mainFunction()


import math
def calcula_pi(n):
    lista1=[]
    contador = 1
    while contador <= n:
        pi =(6/(contador**2))
        lista.append(pi)
        contador+=1
    return math.sqrt(sum(lista))
print(calcula_pi(10000))


"""
{
    "author": "Yucheng Huang",
    "difficulty": "medium",
    "link": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/",
    "beats": 0.4091,
    "category": ["tree"],
    "tags": ["DFS"],
    "questions": []
}
"""

"""
思路
	- DFS返回符合条件的结点个数
"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def DFS(self, node):
        if node is None:
            return 0
        if (node is self.p) or (node is self.q):
            if self.DFS(node.left) or self.DFS(node.right):
                self.ans = node
                return 2
            return 1
        else:
            a = self.DFS(node.left)
            b = self.DFS(node.right)
            if a==1 and b==1:
                self.ans = node
                return 2
            return a+b

    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        self.p = p
        self.q = q
        self.DFS(root)
        return self.ans


"""
这个“nest.py”模块，提供了一个名为print_lol()的函数，
这个函数的作用是打印列表，其中有可能包含嵌套列表。
"""
import sys
# from sys import *
# from sys import stdout

def print_lol(the_list, indent=False, level=0, location=sys.stdout):
    """
    这个函数取一个位置参数，名为“the_list”，
    这可以是任何Python列表。
    列表内每一个数据项会输出到屏幕上，各数据各占一行。
    indent:第一层列表是否缩进
    level:给不同层列表加上缩进，显示更加清晰。
    """
    for each_item in the_list:
        if isinstance(each_item, list):
            print_lol(each_item, indent, level+1, location)
        else:
            if indent == 1:
               for tab_stop in range(level):
                    print("\t", end='', file=location) #每一层缩进显示一个Tab制表符
            print(each_item, file=location)


"""Main."""
import pygame
import sys

import KeyListener
import game_graphics.Display
import game_graphics.UI.UI
import Menu
import World
import objects.mobs.Player
import objects.mobs.Worker_man
import objects.mobs.Goblin
import game_state.GameState
import game_graphics.UI
import sounds.Sound_control
import Menu_world

pygame.init()
pygame.mixer.pre_init(44100, 16, 2, 4096)  # preset the mixer init arguments

window_title = "Driven Into the Last Corner"  # Title on top of the frame.
window_width = 1200  # Width of the canvas.
window_height = 700  # Height of the canvas.
fps_fix = 160

running = True  # while True game will run.

sc = sounds.Sound_control.SoundControl()
player = objects.mobs.Player.Player(30 << 5, 70 << 5)
menu_ghost = objects.mobs.Player.Player(30 << 5, 70 << 5)
world = World.World()
menu_world = Menu_world.MenuWorld()
gamestate = game_state.GameState.GameState()

worker_man = objects.mobs.Worker_man.Worker(37 << 5, 70 << 5, 0, [1456, 2162])   # first wood
worker_man2 = objects.mobs.Worker_man.Worker(37 << 5, 70 << 5, 0, [1456, 2162])   # second wood
worker_man3 = objects.mobs.Worker_man.Worker(27 << 5, 70 << 5, 1, [496, 2194])   # first stone

user_interface = None

def update():
    """Update all."""
    if Menu.inMenu:
        menu_world.update()
    else:
        KeyListener.update()
        world.update()
        gamestate.update()
        user_interface.update()
    cameraPos()  # update camera position.

    if KeyListener.exit_game is True:
        sys.exit()

def render(display_obj):
    """Render all visible stuff."""
    if Menu.inMenu:
        menu_world.render(display_obj)
    else:
        display_obj.canvas.fill(int(0x609CB0))
        world.render(display_obj)
        user_interface.render(display_obj)
        #  print(KeyListener.mouseX + World.World.camera_x, World.World.camera_y + KeyListener.mouseY)

cameraPosDoubleX = (menu_ghost.x - (window_width / 2))
cameraPosDoubleY = (menu_ghost.y - (window_height / 2))

def cameraPos():
    """Update camera position."""
    global cameraPosDoubleX
    global cameraPosDoubleY

    if Menu.inMenu:
        cameraPosDoubleY -= 1  # speed of menu camera up movement
        Menu_world.MenuWorld.camera_x = int(cameraPosDoubleX)
        Menu_world.MenuWorld.camera_y = int(cameraPosDoubleY)
    else:
        cameraPosDoubleX += ((player.x + player.camera_shift_x) - (cameraPosDoubleX + window_width / 2)) / 20
        cameraPosDoubleY += ((player.y + player.camera_shift_y) - (cameraPosDoubleY + window_height / 2)) / 20
        World.World.camera_x = int(cameraPosDoubleX)
        World.World.camera_y = int(cameraPosDoubleY)

def run():
    """Run the game."""
    sounds.Sound_control.SoundControl.play_menu_music(sc)

    game_window = game_graphics.Display.Display(window_width, window_height, fps_fix)  # surface
    mr = Menu.MenuRun(game_window.canvas)
    mr.run(game_window.canvas, surf=game_window)

    world.mobs.append(worker_man)
    world.mobs.append(worker_man3)
    world.mobs.append(player)
    world.mobs.append(objects.mobs.Goblin.Goblin(30 << 5, 40 << 5))
    """
    world.mobs.append(objects.mobs.Goblin.Goblin(31 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(32 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(33 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(34 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(35 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(36 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(29 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(28 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(27 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(26 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(30 << 5, 40 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(31 << 5, 41 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(32 << 5, 42 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(33 << 5, 43 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(34 << 5, 44 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(35 << 5, 45 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(36 << 5, 39 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(29 << 5, 38 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(28 << 5, 37 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(27 << 5, 36 << 5))
    world.mobs.append(objects.mobs.Goblin.Goblin(26 << 5, 35 << 5))
    """

    menu_world.mobs.append(menu_ghost)
    menu_world.player = menu_ghost
    World.player = player
    global user_interface
    user_interface = game_graphics.UI.UI.UI()
    sounds.Sound_control.SoundControl.fadeout_menu_music_to_game_music(sc, 3000)  # fadeout time is in ms

    while running:
        game_window.clock.tick(game_window.fps)
        pygame.display.set_caption(window_title + " | " + "FPS: %i" % game_window.clock.get_fps())
        update()
        render(game_window)
        pygame.display.flip()

if __name__ == "__main__":
    run()


from tkinter import *
import tkinter.messagebox

def safe_data():
    try:
        file = open("deliveries.txt", "a")
        file.write("Depot:\n%s\nDescription:\n%s\nAddress:\n%s\n"
                   % (depot.get(), description.get(), address.get("1.0", END)))
        file.close()
        # Clear entry fields
        depot.set(None)
        description.delete(0, END)
        address.delete("1.0", END)
    except Exception as ex:
        tkinter.messagebox.showerror("Error!", "Can't write to the file\n %s" % ex)

# Read contents of a file and return a list
def read_depots(file):
    depots = []
    depots_f = open(file)
    for each_line in depots_f:
        depots.append(each_line.strip())
    return depots

# Create user interface
app = Tk()
app.title('Head-Ex Deliveries')
Label(app, text="Depot:").pack()
# Control variable to initialise radio buttons to None
depot = StringVar()
depot.set(None)
# Call the function passing in the name of the file to read the data from
options = read_depots("depots.txt")
# This * means "Take the rest of the parameters from this list and insert them here"
# Use the data to build the option menu
OptionMenu(app, depot, *options).pack()
Label(app, text="Description:").pack()
description = Entry(app)
description.pack()
Label(app, text="Address:").pack()
address = Text(app)
address.pack()

Button(app, text="Save", command=safe_data).pack()

app.mainloop()


'''
A 2d grid map of m rows and n columns is initially filled with water.
We may perform an addLand operation which turns the water at position (row, col) into a land.
Given a list of positions to operate, count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
'''

class UnionFind(object):

    def __init__(self, n):
        self.id = {}
        self.count = 0
        self.father = {}
        for i in range(n):
            self.father[i] = i

    def add(self, id):
        self.id[id] = id
        self.count += 1

    def find(self, x):
        parent = x
        while parent != self.father[parent]:
            parent = self.father[parent]

        next = None
        while(x != self.father[x]):
            next = self.father[x]
            self.father[x] = parent
            x = next

        return parent

    def union(self, x, y):
        left_parent = self.find(x)
        right_parent = self.find(y)
        if left_parent != right_parent:
            self.father[left_parent] = right_parent
            self.count -= 1

    def get_island_num(self):
        return self.count

class Solution(object):
    def numIslands2(self, m, n, positions):
        """
        :type m: int
        :type n: int
        :type positions: List[List[int]]
        :rtype: List[int]
        """

        if not m and not n:
            return 0

        result = []
        uf = UnionFind(m * n)

        for point in positions:
            x = point[0]
            y = point[1]
            p_id = x * n + y
            uf.add(p_id)
            for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0):
                nx, ny = x + dx, y + dy
                if 0 <= nx < m and 0 <= ny < n:
                    q_id = nx * n + ny
                    if q_id in uf.id:
                        uf.union(p_id, q_id)
            result.append(uf.get_island_num())

        return result


from jedi.parser_utils import get_flow_branch_keyword, is_scope, get_parent_scope
from jedi.evaluate.recursion import execution_allowed

class Status(object):
    lookup_table = {}

    def __init__(self, value, name):
        self._value = value
        self._name = name
        Status.lookup_table[value] = self

    def invert(self):
        if self is REACHABLE:
            return UNREACHABLE
        elif self is UNREACHABLE:
            return REACHABLE
        else:
            return UNSURE

    def __and__(self, other):
        if UNSURE in (self, other):
            return UNSURE
        else:
            return REACHABLE if self._value and other._value else UNREACHABLE

    def __repr__(self):
        return '<%s: %s>' % (type(self).__name__, self._name)

REACHABLE = Status(True, 'reachable')
UNREACHABLE = Status(False, 'unreachable')
UNSURE = Status(None, 'unsure')

def _get_flow_scopes(node):
    while True:
        node = get_parent_scope(node, include_flows=True)
        if node is None or is_scope(node):
            return
        yield node

def reachability_check(context, context_scope, node, origin_scope=None):
    first_flow_scope = get_parent_scope(node, include_flows=True)
    if origin_scope is not None:
        origin_flow_scopes = list(_get_flow_scopes(origin_scope))
        node_flow_scopes = list(_get_flow_scopes(node))

        branch_matches = True
        for flow_scope in origin_flow_scopes:
            if flow_scope in node_flow_scopes:
                node_keyword = get_flow_branch_keyword(flow_scope, node)
                origin_keyword = get_flow_branch_keyword(flow_scope, origin_scope)
                branch_matches = node_keyword == origin_keyword
                if flow_scope.type == 'if_stmt':
                    if not branch_matches:
                        return UNREACHABLE
                elif flow_scope.type == 'try_stmt':
                    if not branch_matches and origin_keyword == 'else' \
                            and node_keyword == 'except':
                        return UNREACHABLE
                if branch_matches:
                    break

        # Direct parents get resolved, we filter scopes that are separate
        # branches.  This makes sense for autocompletion and static analysis.
        # For actual Python it doesn't matter, because we're talking about
        # potentially unreachable code.
        # e.g. `if 0:` would cause all name lookup within the flow make
        # unaccessible. This is not a "problem" in Python, because the code is
        # never called. In Jedi though, we still want to infer types.
        while origin_scope is not None:
            if first_flow_scope == origin_scope and branch_matches:
                return REACHABLE
            origin_scope = origin_scope.parent

    return _break_check(context, context_scope, first_flow_scope, node)

def _break_check(context, context_scope, flow_scope, node):
    reachable = REACHABLE
    if flow_scope.type == 'if_stmt':
        if flow_scope.is_node_after_else(node):
            for check_node in flow_scope.get_test_nodes():
                reachable = _check_if(context, check_node)
                if reachable in (REACHABLE, UNSURE):
                    break
            reachable = reachable.invert()
        else:
            flow_node = flow_scope.get_corresponding_test_node(node)
            if flow_node is not None:
                reachable = _check_if(context, flow_node)
    elif flow_scope.type in ('try_stmt', 'while_stmt'):
        return UNSURE

    # Only reachable branches need to be examined further.
    if reachable in (UNREACHABLE, UNSURE):
        return reachable

    if context_scope != flow_scope and context_scope != flow_scope.parent:
        flow_scope = get_parent_scope(flow_scope, include_flows=True)
        return reachable & _break_check(context, context_scope, flow_scope, node)
    else:
        return reachable

def _check_if(context, node):
    with execution_allowed(context.evaluator, node) as allowed:
        if not allowed:
            return UNSURE

        types = context.eval_node(node)
        values = set(x.py__bool__() for x in types)
        if len(values) == 1:
            return Status.lookup_table[values.pop()]
        else:
            return UNSURE


"""
with相关概念:
    上下文管理协议(Context Management Protocol): 包含方法__enter__()和__exit__(),支持该协议的对象要实现
    这两个方法.

    上下文管理器(Context Manager): 支持上下文管理协议的对象，这种对象实现了__enter__()和__exit__()方法.
        上下文管理器定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作.通常
        使用with语句调用上下文管理器,也可以通过直接调用其方法来使用.

    运行时上下文(runtime context)：由上下文管理器创建,通过上下文管理器的__enter__()和__exit__()方法实现,
        __enter__()方法在语句体执行之前进入运行时上下文,__exit__()在语句体执行完后从运行时上下文退出.with
        语句支持运行时上下文这一概念.

    上下文表达式(Context Expression)：with语句中跟在关键字with之后的表达式,该表达式要返回一个上下文管理器
        对象.

    语句体(with-body)：with语句包裹起来的代码块,在执行语句体之前会调用上下文管理器的__enter__()方法,执行完
        语句体之后会执行__exit__()方法.

    with context_expression [as target(s)]:
        with-body

with语句执行流程:
    context_manager = context_expression
    exit = type(context_manager).__exit__
    value = type(context_manager).__enter__(context_manager)
    exc = True   # True表示正常执行,即便有异常也忽略; False表示重新抛出异常,需要对异常进行处理
    try:
        try:
            target = value  # 如果使用了as子句
            with-body     # 执行with-body
        except:
            # 执行过程中有异常发生
            exc = exit(context_manager, *sys.exc_info())
            # 如果__exit__返回True，则异常被忽略; 如果返回False,则重新抛出异常
            # 由外层代码对异常进行处理
            if not exec:
                raise
    finally:
        # 正常退出; 或者通过statement-body中的break/continue/return语句退出; 或者忽略异常退出
        if exc:
            exit(context_manager, None, None, None)
        # 缺省返回None, None在布尔上下文中看做是False

    1. 执行context_expression, 生成上下文管理器context_manager

    2. 调用上下文管理器的__enter__()方法; 如果使用了as子句,则将__enter__()方法的返回值赋值给as子句中的
       target(s)

    3. 执行语句体with-body

    4. 不管是否执行过程中是否发生了异常,执行上下文管理器的__exit__()方法,__exit__()方法负责执行"清理"工作,
       如释放资源等.

       如果执行过程中没有出现异常,或者语句体中执行了语句break/continue/return,则以None作为参数调用
       __exit__(None, None, None);

       如果执行过程中出现异常,则使用sys.exc_info得到的异常信息为参数调用__exit__(exc_type, exc_value,
       exc_traceback);

    5. 出现异常时,如果__exit__(type, value, traceback)返回 False,则会重新抛出异常,让with之外的语句逻辑
       来处理异常,这也是通用做法;如果返回 True,则忽略异常,不再对异常进行处理.
"""

"""
自定义上下文管理器:(实现__enter__和__exit__)
    context_manager.__enter__(): 进入上下文管理器的运行时上下文,在语句体执行前调用.with语句将该方法的返回
        值赋值给as子句中的target,如果指定了as子句的话
    context_manager.__exit__(exc_type, exc_value, exc_traceback): 退出与上下文管理器相关的运行时上下文,
        返回一个布尔值表示是否对发生的异常进行处理. 参数表示引起退出操作的异常.
            如果退出时没有发生异常,则3个参数都为None,同时返回True.
            如果发生异常,返回True表示不处理异常,否则会在退出该方法后重新抛出异常以由with语句之外的代码逻辑进行处理.
            如果该方法内部产生异常,则会取代由statement-body中语句产生的异常.(最终抛出的异常是该方法内部抛出的异常)
"""

class ContextProtocol(object):
    def __init__(self, tag):
        self.tag = tag

    def __enter__(self):
        print('__enter__')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('__exit__')
        if exc_tb is None:
            print('normal')
            return True
        else:
            raise Exception('exit inner exception')

try:
    with ContextProtocol('tag') as f:
        print('exec body')
        raise Exception('body exception')
except Exception as e:
    print(e)  # exit inner exception

"""
contextlib 模块:
    contextlib模块提供了3个对象: 装饰器contextmanager, 函数nested和上下文管理器closing. 用这些对象,可以对
    已有的生成器函数或者对象进行包装,加入对上下文管理协议的支持,避免了专门编写上下文管理器来支持with语句

    contextmanager: 用于对生成器函数进行装饰,生成器函数被装饰以后,返回的是一个上下文管理器,其__enter__()和
        __exit__()方法由contextmanager负责提供.被装饰的生成器函数只能产生一个值,否则会导致异常RuntimeError;
        产生的值会赋值给as子句中的target

    closing: 上下文自动关闭块末尾的内容. closing 适用于提供了 close() 实现的对象
        with closing(<module>.open(<arguments>)) as f:
            <block>

        实现:
            def __init__(self, thing):
                self.thing = thing
            def __enter__(self):
                return self.thing
            def __exit__(self, *exc_info): // 亮点
                self.thing.close()

    ContextDecorator: 上下文管理器 + 装饰器 (此类既实现了装饰功能,也实现了上下文管理协议),此类的实例相当于
        contextmanager

    class context(ContextDecorator):
        def __enter__(self):
          return self

       def __exit__(self, *exc):
          return False

    @context()
    def say():
        print('hello')

    say()可以按照上下文管理器的方式运行

    等价于=>  with context():
                print('hello')
"""

from contextlib import contextmanager, ContextDecorator

@contextmanager
def demo():
    print('Code before yield-statement executes in __enter__')
    # 生成器函数的只能产生一个值
    for i in range(0, 1):
        yield '*** contextmanager %d ***' % i
    print('Code after yield-statement executes in __exit__')

with demo() as value:
    print(value)

class BaseContextManger(ContextDecorator):
    def __enter__(self):
        print('enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')
        return True

base_context = BaseContextManger()

@base_context
def f():
    print('hello')

f()


import ast
import re
# variable_regexp = r"\$([\w_]+)"
# def extract_variables(content):
#     return re.findall(variable_regexp, content)
# oo=extract_variables("$u_oken")
# print(oo)
pp='C:/Users/cheng/PycharmProjects/HttpRunner/tests/data/demo_testcase_cli.yml'
from httprunner.api import HttpRunner

def run_path(self, path, dot_env_path=None, mapping=None):
    """ run testcase/testsuite file or folder.

    Args:
        path (str): testcase/testsuite file/foler path.
        dot_env_path (str): specified .env file path.
        mapping (dict): if mapping is specified, it will override variables in config block.

    Returns:
        instance: HttpRunner() instance

    """
    # load tests
    self.exception_stage = "load tests"
    tests_mapping = loader.load_tests(path, dot_env_path)
    tests_mapping["project_mapping"]["test_path"] = path

    if mapping:
        tests_mapping["project_mapping"]["variables"] = mapping

    if self.save_tests:
        utils.dump_tests(tests_mapping, "loaded")

    return self.run_tests(tests_mapping)


import os
import re

from setuptools import find_packages, setup

from discover_tests import DiscoverTest

def str_to_bool(x):
    x = str(x)

    return x.lower() in ('true', 't', 'yes', 'y', '1')

with open(
    os.path.join(os.path.dirname(__file__), 'metREx', '__init__.py')
) as i_file:
    info = i_file.read()

    TITLE = (
        re.compile(r""".*__title__ = ["']([^\n]*)['"]""", re.S).match(info).group(1)
    )

    VERSION = (
        re.compile(r""".*__version__ = ["']([^\n]*)['"]""", re.S).match(info).group(1)
    )

    DESCRIPTION = (
        re.compile(r""".*__description__ = ["']([^\n]*)['"]""", re.S).match(info).group(1)
    )

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as r_file:
    README = r_file.read()

INSTALL_REQUIRES = [
    'cfenv',
    'cryptofy',
    'Flask-APIAlchemy',
    'Flask-APScheduler',
    'flask-restx',
    'Flask-Script',
    'Flask-SQLAlchemy',
    'numpy',
    'prometheus-flask-exporter',
    'python-dotenv',
    'PyYAML',
    'SQLAlchemy'
]

EXTRAS_REQUIRE = {
    'db2': [
        'ibm_db',
        'ibm-db-sa'
    ],
    'mssql': [
        'pymssql'
    ],
    'mysql': [
        'pymysql'
    ],
    'oracle': [
        'cx-Oracle'
    ],
    'postgresql': [
        'pg8000'
    ]
}

TESTS_REQUIRE = [
    'Flask-Testing',
    'pytest',
    'teamcity-messages'
]

install_all_extras = str_to_bool(os.getenv('INSTALL_ALL_EXTRAS', False))

if install_all_extras:
    for packages in EXTRAS_REQUIRE.values():
        for package in packages:
            if package not in INSTALL_REQUIRES:
                INSTALL_REQUIRES.append(package)

setup(name=TITLE,
      version=VERSION,
      description=DESCRIPTION,
      long_description=README,
      long_description_content_type='text/markdown',
      license='Apache 2.0',
      keywords='prometheus exporter prometheus-exporter metrics metrics-exporter query-exporter sql sql-exporter appd appd-exporter appdynamics appdynamics-exporter extrahop extrahop-exporter',
      url='https://github.com/homedepot/metREx',
      author='Mike Phillipson',
      author_email='MICHAEL_PHILLIPSON1@homedepot.com',
      packages=find_packages('metREx'),
      package_dir={
          '': 'metREx'
      },
      data_files=[
          ('static', [
              'favicon.ico'
          ])
      ],
      entry_points={
          'console_scripts': [
              'metrex=manage:run'
          ]
      },
      python_requires='>=3.6',
      install_requires=INSTALL_REQUIRES,
      extras_require=EXTRAS_REQUIRE,
      tests_require=TESTS_REQUIRE,
      cmdclass={
          'test': DiscoverTest
      },
      zip_safe=False)


from django.shortcuts import render
from .summarization import summarize
from .forms import TextSummarization

# Create your views here.
def nlp_text_summarization(response):
    # Check if there is any users loggin in:
    if(response.method == 'POST'):
        form = TextSummarization(response.POST)
        if(form.is_valid()):
            text = form.cleaned_data['text']
            original_charcount = len(text)
            original_wordcount = len(text.split(' '))

            summary = summarize(text)
            summary_wordcount = len(summary.split(' '))
            summary_charcount = len(summary)
            form = TextSummarization() # new form
            return render(response, 'nlp/summarization.html',{'original':text,
             'summary':summary,'original_wordcount':original_wordcount,
             'original_charcount':original_charcount,
             'summary_charcount':summary_charcount,
             'summary_wordcount':summary_wordcount,'form' : form})
    else:
        if(response.session['username'] == None or response.session['fullname'] == None):
            return render(response, 'nlp/error.html',{})
        else:
            form = TextSummarization()
            return render(response, 'nlp/summarization.html', {'form':form})


from PySide2.QtWidgets import QLabel, QWidget, QPushButton, QApplication, QHBoxLayout,QVBoxLayout, QGridLayout, QTextEdit, QProgressBar, QSlider

class IHM(QWidget):

    def __init__(self):

        QWidget.__init__(self)

        self.layout = QHBoxLayout()
        self.setWindowTitle("IHM")

        self.bar = QProgressBar(self)
        self.slider = QSlider(self)
        self.slider.setMinimum(0)
        self.slider.setMaximum(100)
        self.slider.setValue(20)
        self.slider.valueChanged.connect(self.valuechange)

        self.layout.addWidget(self.bar)
        self.layout.addWidget(self.slider)
        self.setLayout(self.layout)

    def valuechange(self):
        size = self.slider.value()
        print(size)

if __name__ == "__main__":
    app = QApplication([])
    win = IHM()
    win.show()
    app.exec_()


"""
The following classes are defined:
    ZeropadLayer
"""

from .validate import *

class ZeropadLayer:
    """
    Construct a new zero-padding layer. The input layer is zero-padded by
    the specified amount to form the output layer.

    Args:
        inputs: An object of type ConnectionLayer. The input layer.
        outputs: An object of type ConnectionLayer. The output layer.
        left: A non-negative integer. The amount to zero-pad on the left. If
            not given, defaults to 0.
        right: A non-negative integer. The amount to zero-pad on the right. If
            not given, defaults to 0.
        top: A non-negative integer. The amount to zero-pad on the top. If not
            given, defaults to 0.
        bottom: A non-negative integer. The amount to zero-pad on the bottom.
            If not given, defaults to 0.
    """
    def __init__(self, inputs, outputs, left=0, right=0, top=0, bottom=0):
        validate_dimensions_layer(inputs)
        validate_dimensions_layer(outputs)
        validate_same_dimensions_zeropad(
            inputs,
            outputs,
            left,
            right,
            top,
            bottom
        )

        self._inputs = inputs
        self._outputs = outputs
        self._left = left
        self._right = right
        self._top = top
        self._bottom = bottom

        for depth_slice in self._inputs:
            for row in depth_slice:
                for input_ in row:
                    input_.bind_to(self._update_inputs)

        self._update_inputs()

    def _update_inputs(self):
        self._outputs.values = [
            [[0 for j in range(len(self._inputs[0][0]) +
                               self._left + self._right)]
                for i in range(self._top)] +
            [[0 for j in range(self._left)] + row.values +
                [0 for j in range(self._right)]
                for row in depth_slice] +
            [[0 for j in range(len(self._inputs[0][0]) +
                               self._left + self._right)]
                for i in range(self._bottom)]
            for depth_slice in self._inputs
        ]