#!/usr/bin/python python3
# -*- coding: utf-8 -*-
"""This is Test Code."""

import yaml
import logging
import tweepy
from flask import Flask, session, redirect, render_template, request

# ログレベル設定
logging.basicConfig(level=logging.INFO)

# パスワード系ファイル読み込み
secret = yaml.load(open('secret.yaml').read())

# Consumer Key
CONSUMER_KEY = secret['CONSUMER_KEY']
# Consumer Secret
CONSUMER_SECRET = secret['CONSUMER_SECRET']
# Callback URL (認証後リダイレクトされるURL)
# CALLBACK_URL = 'https://flask-tweepy.herokuapp.com/'  # Heroku上
CALLBACK_URL = 'http://localhost:5000/'  # ローカル環境

logging.warn('app start!')

# Flask の起動
app = Flask(__name__)
# flask の session を使うにはkeyを設定する必要がある．
app.secret_key = secret['SECRET_KEY']

@app.route('/')
def index():
    """ root ページの表示 """
    # 連携アプリ認証済みなら user の timeline を取得
    timeline = user_timeline()

    # templates/index.html を使ってレンダリング．
    return render_template('index.html', timeline=timeline)

@app.route('/twitter_auth', methods=['GET'])
def twitter_auth():
    """ 連携アプリ認証用URLにリダイレクト """
    # tweepy でアプリのOAuth認証を行う
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)

    try:
        # 連携アプリ認証用の URL を取得
        redirect_url = auth.get_authorization_url()
        # 認証後に必要な request_token を session に保存
        session['request_token'] = auth.request_token
    except tweepy.TweepError as e:
        logging.error(str(e))

    # リダイレクト
    return redirect(redirect_url)

def user_timeline():
    """ user の timeline のリストを取得 """
    # request_token と oauth_verifier のチェック
    token = session.pop('request_token', None)
    verifier = request.args.get('oauth_verifier')
    if token is None or verifier is None:
        return False  # 未認証ならFalseを返す

    # tweepy でアプリのOAuth認証を行う
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)

    # Access token, Access token secret を取得．
    auth.request_token = token
    try:
        auth.get_access_token(verifier)
    except tweepy.TweepError as e:
        logging.error(str(e))
        return {}

    # デバッグのためアクセストークンを出力
    token_str = '\t'.join((
         'access_token:' + auth.access_token,
         'access_tokne_secret:' + auth.access_token_secret
    ))
    logging.info(token_str)

    # tweepy で Twitter API にアクセス
    api = tweepy.API(auth)

    # user の timeline 内のツイートのリストを最大100件取得して返す
    return api.user_timeline(count=100)

if __name__ == '__main__':
    port = 5000
    app.run(port=port)


import seaborn as sns
import matplotlib.pyplot as plt
from wordcloud import WordCloud

from collections import Counter
from nltk.corpus import stopwords

import pandas as pd
import numpy as np

from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

import yaml

with open('config.yaml', 'r') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)

QUERIES_COL = config['queries_col']

def most_common_words(df, queries_col=QUERIES_COL, n_commons=25, remove_stopwords=True, by='word'):
    """
    checks for the most important [queries | individual words] in the search corpus.

    :param df: Pandas DataFrame of which one column in test search queries
    :param queries_col: the search queries column
    :param n_commons: number of top most common
    :param remove_stopwords: use NLTK to remove english stopwords
    :param by: 'word' returns most common *words*, 'query' returns most common *complete queries*.
    :return: Pandas DataFrame with most common words
    """
    if by == 'word':
        entries = df[queries_col].str.cat(sep=' ')
        entries = entries.split(' ')
    elif by == 'query':
        entries = df[queries_col]
    else:
        raise Exception ('The keyword argument "separate" should either be set to "word" or "query"')

    c = Counter(entries)
    commons = c.most_common(n_commons)
    commons = pd.DataFrame(commons)

    if remove_stopwords:
        sw_ind = commons[0].apply(lambda word: word in stopwords.words('english'))
        ind_to_drop = commons[sw_ind].index
        commons.drop(index=ind_to_drop, inplace=True)

    commons.rename(columns={0: "word", 1: "count"}, inplace=True)

    return commons

def plot_stats(df, queries_col=QUERIES_COL, **mcw_kwargs):
    """
    plots graphic information about individual words in the search query corpus.

    :param df: Pandas DataFrame
    :param queries_col: the column that holds the queries in df
    :param top_n: top n words to show
    :param separate: if True, returns most common *words*. Otherwise returns most common *complete queries*.
    :return: None
    """
    commons_df = most_common_words(df, queries_col, **mcw_kwargs)
    top_n = mcw_kwargs['n_commons']

    total = commons_df['count'].sum(axis=0)
    commons_df['freq'] = commons_df['count'].apply(lambda x: x / total)
    if len(commons_df) > top_n:
        commons_df = commons_df[:top_n]

    fig, axes = plt.subplots(1, 2, figsize=(18, 4))

    # plotting the word cloud
    wordcloud = WordCloud()
    commons_dict = dict(zip(commons_df['word'], commons_df['freq']))
    wordcloud.generate_from_frequencies(frequencies=commons_dict)
    axes[0].imshow(wordcloud, interpolation="bilinear")
    axes[0].axis("off")

    # plotting the bar count
    words = commons_df['word']
    counts = commons_df['count']
    sns.barplot(x=words, y=counts, ax=axes[1])
    axes[1].tick_params(axis='x', labelrotation=90)

    plt.suptitle(f'Most Common {top_n} {"Words" if mcw_kwargs["by"] == "word" else "Queries"}')

    plt.show()

    return None

def tsnescatterplot(model, word, list_names):
    """ Plot in seaborn the results from the t-SNE dimensionality reduction algorithm of the vectors of a query word,
    its list of most similar words, and a list of words.
    """
    arrays = np.empty((0, 50), dtype='f')
    word_labels = [word]
    color_list = ['red']

    # adds the vector of the query word
    arrays = np.append(arrays, model.wv.__getitem__([word]), axis=0)

    # gets list of most similar words
    close_words = model.wv.most_similar([word])

    # adds the vector for each of the closest words to the array
    for wrd_score in close_words:
        wrd_vector = model.wv.__getitem__([wrd_score[0]])
        word_labels.append(wrd_score[0])
        color_list.append('blue')
        arrays = np.append(arrays, wrd_vector, axis=0)

    # adds the vector for each of the words from list_names to the array
    for wrd in list_names:
        wrd_vector = model.wv.__getitem__([wrd])
        word_labels.append(wrd)
        color_list.append('green')
        arrays = np.append(arrays, wrd_vector, axis=0)

    # Reduces the dimensionality from 300 to 50 dimensions with PCA
    reduc = PCA(n_components=19).fit_transform(arrays)

    # Finds t-SNE coordinates for 2 dimensions
    np.set_printoptions(suppress=True)

    Y = TSNE(n_components=2, random_state=0, perplexity=15).fit_transform(reduc)

    # Sets everything up to plot
    df = pd.DataFrame({'x': [x for x in Y[:, 0]],
                       'y': [y for y in Y[:, 1]],
                       'words': word_labels,
                       'color': color_list})

    fig, _ = plt.subplots()
    fig.set_size_inches(9, 9)

    # Basic plot
    p1 = sns.regplot(data=df,
                     x="x",
                     y="y",
                     fit_reg=False,
                     marker="o",
                     scatter_kws={'s': 40,
                                  'facecolors': df['color']
                                  }
                     )

    # Adds annotations one by one with a loop
    for line in range(0, df.shape[0]):
        p1.text(df["x"][line],
                df['y'][line],
                '  ' + df["words"][line].title(),
                horizontalalignment='left',
                verticalalignment='bottom', size='medium',
                color=df['color'][line],
                weight='normal'
                ).set_size(15)

    plt.xlim(Y[:, 0].min() - 50, Y[:, 0].max() + 50)
    plt.ylim(Y[:, 1].min() - 50, Y[:, 1].max() + 50)

    plt.title('t-SNE visualization for {}'.format(word.title()))


######################
# Updating GTM tags  #
######################

import argparse
import httplib2
from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from pprint import pprint

CLIENT_SECRETS = 'client_secrets.json'
SCOPE = ['https://www.googleapis.com/auth/tagmanager.readonly',
         'https://www.googleapis.com/auth/tagmanager.edit.containers',
         'https://www.googleapis.com/auth/tagmanager.edit.containerversions',
         "https://www.googleapis.com/auth/tagmanager.publish"]
# SCOPE = ['https://www.googleapis.com/auth/tagmanager.edit.containers']

# Parse command-line arguments
parser = argparse.ArgumentParser(parents = [tools.argparser])
flags = parser.parse_args()

# Set up a Flow object to be used if we need to authenticate
flow = client.flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope = SCOPE,
    message = tools.message_if_missing(CLIENT_SECRETS))
# Prepare credentials, and authorize the HTTP object with them.
# If the credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful, the good
# credentials will be written back to a file.
storage = file.Storage('tagmanager.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http = httplib2.Http())

# Build the service object
service = build('tagmanager', 'v1', http = http)

# # Input version
# account_id = raw_input('Please enter account ID: ')
# container_id = raw_input('Please enter container ID: ')

account_id = '126511049'
container_id = '1571633'

# Get the list of all tags
tags = service.accounts().containers().tags().list(
    accountId = account_id,
    containerId = container_id
).execute()

# Make a local list of tags you want to update
tags_to_update = []
for tag in tags.get('tags', []):
    # Specify conditions on tag you want to update here
    if '_import_1' in tag['name'] and tag['type'] == 'ua':
        tags_to_update.append(tag)

# Make local changes to tags you want to update here
for tag in tags_to_update:
    # Here we changed tags' names:
    # tag['name'] = 'IF ' + tag['name']
    # Here we change UA tracking ID:
    next((x for x in tag['parameter'] if x['key'] == 'trackingId'), None)['value'] = '{{00 UA ID Interflora.pl}}'

# Push the changes to GTM by passing the list with changed tags
for tag in tags_to_update:
    del tag['accountId']
    del tag['containerId']
    tag_ID = tag.get('tagId')
    del tag['tagId']

    tags_update = service.accounts().containers().tags().update(
        accountId = account_id,
        containerId = container_id,
        tagId = tag_ID,
        body = tag
    ).execute()

quit()


from PIL import Image
import time
import numpy as np
import argparse
import random
from progressbar import ProgressBar
import cv2

import utils
import interval_tools as tools

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

p = argparse.ArgumentParser(description="pixel mangle an image")
p.add_argument("-ins", "--inputs",	help="input]", required=True)

__args = p.parse_args()

image_input_paths = __args.inputs

print ("Input: " + str(__args.inputs))

##########################################
#random thresholds

thresholds_dict = {1 : [[0.1 , 0.3 ], [0.7 , 0.9 ]],
			  2 : [[0.2 , 0.6 ], [0.4 , 0.8 ]],
			  3 : [[0.05, 0.42], [0.75, 0.9 ]],
			  4 : [[0.25, 0.38], [0.55, 0.95]],
			  5 : [[0.4 , 0.6 ], [0.05, 0.8 ]],
			  6 : [[0.5 , 0.7 ], [0.3 , 0.9 ]]}

def rndvar(value):

	value += random.uniform(0.1, -0.1)
	if value < 0:
		return 0
	elif value > 1:
		return 1
	else:
		return value

def rand_thresholds():

	thr = thresholds_dict[random.randint(1, 6)]

	t1 = rndvar(thr[0][0])
	t2 = rndvar(thr[1][0])
	t3 = 0
	u1 = rndvar(thr[0][1])
	u2 = rndvar(thr[1][1])
	u3 = 1

	thresholds = [t1, u1, t2, u2, t3, u3]

	return thresholds

##########################################
# random interval functions

functions = {1 : "v",
			       2 : "h",
			       3 : "s",
			       4 : "l",
			       5 : "y",
			       6 : "i",
			       7 : "q",
			       8 : "max_rgb",
			       9 : "min_rgb",
			       10 : "max_hsv",
			       11 : "min_hsv",
			       12 : "max_yiq",
			       13 : "min_yiq",
			       14 : "r",
			       15 : "g",
			       16 : "b"}

def rand_intfunc():
	i1 = utils.read_pixel_function(functions[random.randint(1, 16)])
	i2 = utils.read_pixel_function(functions[random.randint(1, 16)])
	i3 = utils.read_pixel_function(functions[random.randint(1, 16)])

	int_funcs = [i1, i2, i3]

	return int_funcs

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

def get_cmd(param_string):
	p_string = param_string.split('__')
	thrshs = p_string[0].split('-')
	funcs = p_string[1].split('-')

	head = 'python gcp_newsort.py -ins '
	inp = 'sparamtest.png'

	threshold_string = f' -t {thrshs[0]} -tt {thrshs[2]} -ttt {thrshs[4]} -u {thrshs[1]} -uu {thrshs[3]} -uuu {thrshs[5]} '
	w_int_f = f' -i {funcs[0]} -ii {funcs[1]} -iii {funcs[2]} '

	cmd = f'%s%s%s%s\n' % (head, inp, w_int_f, threshold_string)
	print(cmd)

	return cmd

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

def evaluate(count_dict):

	triple = (count_dict[1],count_dict[2],count_dict[3])
	diff12 = max(triple[0],triple[1])-min(triple[0],triple[1])
	diff23 = max(triple[1],triple[2])-min(triple[1],triple[2])
	diff31 = max(triple[2],triple[0])-min(triple[2],triple[0])

	d_value = diff12 + diff23 + diff31
	print(d_value)

	return d_value

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

def main(image_input_paths):

	input_img = Image.open(image_input_paths)
	img_x = input_img.size[1]
	img_y = input_img.size[0]
	input_img = input_img.convert('RGB')

	bands = input_img.getbands()
	bl = len(bands)

	pixels = np.array(input_img.getdata(), np.uint8).reshape(input_img.size[1], input_img.size[0], bl)

	sdim = int(min(input_img.size)/(max(input_img.size)/100))
	ldim = 100

	if input_img.size[0] > input_img.size[0]:
		new_dim = tuple([ldim, sdim])
	else:
		new_dim = tuple([sdim, ldim])

	pixels = cv2.resize(pixels, new_dim)

	siz = input_img.size

	param_sets = []
	param_eval = []

	for n in range(300):   # # # # # # # # # # # # # # # # # # # # # # # # # # # #   Poolgröße
		thresholds = rand_thresholds()
		int_funcs = rand_intfunc()

		interval_array = tools.find_intervals(pixels, thresholds, int_funcs)

		unique, counts = np.unique(interval_array, return_counts=True)
		count_dict = dict(zip(unique, counts))

		print(unique)

		if len(unique) < 3:
			pass

		else:
			value = evaluate(count_dict)

			param_sets.append("%s-%s-%s-%s-0-1__%s-%s-%s" % (thresholds[0],thresholds[1],thresholds[2],thresholds[3],int_funcs[0],int_funcs[1],int_funcs[2]))
			param_eval.append(value)

		count_dict.clear()

	param_pairs = list(zip(param_sets, param_eval))
	param_pairs.sort(key=lambda pair: pair[1], reverse=True)

	return param_pairs

	#for l in range(0, 4):
	#	print(get_cmd(param_pairs[l][0]), '+\n')
	#
	#for l in range(-1, -5):
	#	print(get_cmd(param_pairs[l][0]), '/\n')
    #
	#for l in range(round(len(param_pairs)/2-2), round(len(param_pairs)/2+3)):
	#	print(get_cmd(param_pairs[l][0]), '-\n')

if __name__ == "__main__":
	paths = image_input_paths
	erg = main(paths)

	with open('erg.txt', 'w') as f:
		for i in erg:
			f.write(get_cmd(str(i[0])) + '\n')


import unittest,os,sys,json

path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))))))
sys.path.append(path)
from config.config_test import Conf
from common.http_requests import HttpRequests
from common import logging_test
from common.mysql_data import Mysql_connet
from common.retry import Retry
from common.doc_value import doc_parameter
uri = '/device/getDeviceAlarms'
@Retry
class Test_Add_Task(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.url = Conf.TEST_APP_URL.value
        cls.http = HttpRequests(cls.url)
        cls.mysql = Mysql_connet('device')
    @doc_parameter(Conf.TEST_URL.value,uri)
    def test_add_task_success(self):
        '''获取设备某种报警类型下的报警信息用例：{}{}'''
        payload = {
          "alarmType": 0,
          "alarmTypes": [
            0
          ],
          "status": 0,
          "terminalNo": self.mysql.terminal_no
        }
        payload = json.dumps(payload)

        response = Test_Add_Task.http.post(
            uri, data=payload)
        self.assertEqual(200, response.status_code, '返回非200')
        self.assertEqual(str(0), str(response.json()['code']), '获取设备某种报警类型下的报警信息失败')
        logging_test.log_test()
        logging_test.logging.info(Conf.TEST_URL.value + uri + '-接口返回:' + response.text)

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


"""
test_vtluugwiki.py - tests for the VTLUUG wiki module
author: mutantmonkey <mutantmonkey@mutantmonkey.in>
"""
import re
import unittest
from mock import MagicMock
from modules import vtluugwiki
from web import catch_timeout

class TestVtluugwiki(unittest.TestCase):

    def setUp(self):
        self.phenny = MagicMock()
        self.input = MagicMock()

    @catch_timeout
    def test_vtluug(self):
        self.input.groups.return_value = ['', "VT-Wireless"]
        vtluugwiki.vtluug(self.phenny, self.input)
        out = self.phenny.say.call_args[0][0]
        m = re.search(r'https://vtluug[.]org/wiki/VT-Wireless',
                out, flags=re.UNICODE)
        self.assertTrue(m)

    @catch_timeout
    def test_vtluug_invalid(self):
        term = "EAP-TLS#netcfg"
        self.input.groups.return_value = ['', term]
        vtluugwiki.vtluug(self.phenny, self.input)
        self.phenny.say.assert_called_once_with( "Can't find anything in "\
                "the VTLUUG Wiki for \"{0}\".".format(term))

    @catch_timeout
    def test_vtluug_none(self):
        term = "Ajgoajh"
        self.input.groups.return_value = ['', term]
        vtluugwiki.vtluug(self.phenny, self.input)
        self.phenny.say.assert_called_once_with( "Can't find anything in "\
                "the VTLUUG Wiki for \"{0}\".".format(term))


#coding=utf-8
#lizhenwei		2017-08-04		create

import os,sys

from PyQt5.QtCore import (Qt,pyqtSignal,pyqtSlot,QModelIndex)
from PyQt5.QtGui import (QBrush,QStandardItemModel,QStandardItem,QMouseEvent)
from PyQt5.QtWidgets import (QApplication,QTableView,QItemDelegate,QAbstractItemView)

class stateDelegate(QItemDelegate):
	'状态item托管'
	sgReverseState = pyqtSignal(QModelIndex)

	def __init__(self,colno=2,enClick=False):
		super(stateDelegate,self).__init__()

		self.colno = colno
		self.enClick = enClick

	def paint(self, painter, option, index):
		if index.column() == self.colno:
			val = index.data()
			d = min(option.rect.width(),option.rect.height())
			painter.save()
			if 0 == val:
				# 0为绿色
				painter.setBrush(QBrush(Qt.green))
			elif 1 == val:
				painter.setBrush(QBrush(Qt.red))
			painter.setPen(Qt.NoPen);
			painter.drawEllipse(option.rect.center(),d>>1,d>>1);
			painter.restore();

		else:
			super(stateDelegate,self).paint(painter,option,index)

	def editorEvent(self,event, model, option, index):
		msEvent = QMouseEvent(event)
		if (msEvent.type() == msEvent.MouseButtonRelease) and option.rect.contains(msEvent.x(),msEvent.y()):
			if self.enClick:
				self.sgReverseState.emit(index)

		return super(stateDelegate,self).editorEvent(event,model,option,index);

class ioTableView(QTableView):

	# 设置bit状态, addr,state
	sgSetBitState = pyqtSignal(int,int)

	def __init__(self,mode):
		'mode: 0输入，1输出'
		super(ioTableView,self).__init__()
		self.mode = mode
		self.initUI()

	def initUI(self):
		self.itemModel = QStandardItemModel()

		headers = ("地址","名称","状态")
		self.itemModel.setHorizontalHeaderLabels(headers)

		self.stateDelegate = stateDelegate(2, self.mode==1)

		self.setModel(self.itemModel)
		self.setItemDelegateForColumn(2,self.stateDelegate)

		stateSize = 36
		self.verticalHeader().setDefaultSectionSize(stateSize*1.2)
		self.verticalHeader().hide()
		self.setColumnWidth(2,stateSize)
		self.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.setSelectionMode(QAbstractItemView.NoSelection)

		self.stateDelegate.sgReverseState.connect(self.onReverseState)

		# self.setSortingEnabled(True)
		# self.sortByColumn(0,Qt.AscendingOrder)

	def loadIOCfgDict(self,iodict):
		'加载io列表'
		for idname,cfg in iodict.items():
			addrItem = QStandardItem()
			addrItem.setData(cfg["addr"],Qt.EditRole)
			nameItem = QStandardItem(cfg["name"])
			stateItem = QStandardItem()
			stateItem.setData(cfg["state"],Qt.EditRole)
			self.itemModel.appendRow([addrItem,nameItem,stateItem])
		self.sortByColumn(0,Qt.AscendingOrder)

	@pyqtSlot(QModelIndex)
	def onReverseState(self,idx):
		'翻转电平'
		preVal = idx.data()
		curVal = preVal^1
		self.itemModel.setData(idx,curVal,Qt.EditRole)
		addr = self.itemModel.index(idx.row(),0).data()
		self.sgSetBitState.emit(addr,curVal)

	@pyqtSlot(int,int)
	def onSetBitState(self,addr,state):
		for i in range(self.itemModel.rowCount()):
			taddr = self.itemModel.item(i,0).data(Qt.EditRole)
			if addr == taddr:
				self.itemModel.item(i,2).setData(state,Qt.EditRole)
				break

def test():
	app = QApplication(sys.argv)
	inview = ioTableView(1)
	in0 = {"addr":0,"name":"test0","state":0}
	in1 = {"addr":1,"name":"test1","state":1}
	iodict = {"in0":in0, "in1":in1}
	inview.loadIOCfgDict(iodict)
	inview.show()
	sys.exit(app.exec_())

if __name__ == '__main__':
	test()


# project setup

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from itertools import combinations, permutations
from collections import Counter
import random
import time
from numpy.random import multinomial

def combinations_creator(simulation_type):
    """
    We generate a list of combinations of 14 choose 4. Each item in this list represents a possible combination
    that can be drawn on lottery night. one combination is left unassigned to a team, this combination is
    11-12-13-14.
    :param simulation_type: a user inputted string expressing what type of simulation this is
    :return: a list of ball combinations and one tuple that is the excluded combination

    >>> combos, discarded = combinations_creator('r')
    >>> len(discarded) == 4
    True

    >>> combos, discarded = combinations_creator('r')
    >>> len(combos) == 1001
    True

    >>> combos, discarded = combinations_creator('w')
    >>> len(combos) == 1001
    True

    >>> combos, discarded = combinations_creator('w')
    >>> len(discarded) == 4
    True
    """
    if simulation_type == 'r' or simulation_type == 'w' or simulation_type == 'a':
        ball_combinations = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 4)
        ball_combinations = list(ball_combinations)
        excluded_combination = (11, 12, 13, 14)
        return ball_combinations, excluded_combination

def odds_creator(simulation_type, iteration_counter, playoff_team, wild_card_odds):
    """
    Each team is given their respective odds of obtaining the #1 pick
    based on their position in standings/type of simulation. If it is a regular simulation, the
    regular odds are given, if it is a wild-card simulation, there is
    another team added with a random normal variable that determines their odds, and for a multinomial simulation,
    the odds are represented as an array for each pick for each team.
    :param simulation_type: a user inputted string expressing what type of simulation this is
    :param iteration_counter: represents which iteration of the simulation the program is on
    :param playoff_team: represents the wild-card playoff team
    :param wild_card_odds: represents the odds of the wild-card playoff team
    :return: a dictionary with key/value pairs being each team and their odds, and a playoff team and their odds

    >>> odds, playoff_selected_team, playoff_odds = odds_creator('r', 1, None, None)
    >>> len(odds) == 14
    True

    >>> odds, playoff_selected_team, playoff_odds = odds_creator('m', 1, None, None)
    >>> len(odds['Houston Rockets']) == 14
    True

    >>> odds, playoff_selected_team, playoff_odds = odds_creator('a', 100, None, None)
    >>> len(odds) == 14
    True
    """
    if simulation_type == 'r' or simulation_type == 'w' or simulation_type == 'a':
        rockets_odds = 0.14
        timberwolves_odds = 0.14
        pistons_odds = 0.14
        magic_odds = 0.125
        thunder_odds = 0.105
        cavaliers_odds = 0.09
        kings_odds = 0.075
        raptors_odds = 0.06
        bulls_odds = 0.045
        wizards_odds = 0.03
        pelicans_odds = 0.02
        pacers_odds = 0.015
        warriors_odds = 0.01
        spurs_odds = 0.005

        if simulation_type == 'w':
            if iteration_counter == 1:
                mu, sigma = 0.07, 0.035
                wild_card_odds = np.round(np.random.normal(mu, sigma, 1),
                                          3)  # using a normal dist. to determine odds of wild card team
                while wild_card_odds <= 0 or wild_card_odds >= 0.14:  # we should not have a wild card team with non-positive odds or odds greater than the top possible odds
                    wild_card_odds = np.round(np.random.normal(mu, sigma, 1), 3)
            randomizer = random.randint(1, 5)
            if randomizer == 1:
                rockets_odds -= wild_card_odds
            elif randomizer == 2:
                timberwolves_odds -= wild_card_odds
            elif randomizer == 3:
                pistons_odds -= wild_card_odds
            elif randomizer == 4:
                magic_odds -= wild_card_odds
            else:
                thunder_odds -= wild_card_odds

    elif simulation_type == 'm':
        rockets_odds = [0.14, 0.134, 0.127, 0.12, 0.479, 0, 0, 0, 0, 0, 0, 0, 0,
                        0]  # from left to right, these odds represent each team's chances of obtaining picks 1-14
        timberwolves_odds = [0.14, 0.134, 0.127, 0.120, 0.278, 0.20, 0, 0, 0, 0, 0, 0, 0, 0]
        pistons_odds = [0.14, 0.134, 0.127, 0.120, 0.148, 0.260, 0.07, 0, 0, 0, 0, 0, 0, 0]
        magic_odds = [0.125, 0.122, 0.119, 0.115, 0.072, 0.257, 0.167, 0.022, 0, 0, 0, 0, 0, 0]
        thunder_odds = [0.105, 0.105, 0.106, 0.105, 0.022, 0.196, 0.267, 0.087, 0.006, 0, 0, 0, 0, 0]
        cavaliers_odds = [0.09, 0.092, 0.094, 0.096, 0, 0.086, 0.297, 0.206, 0.037, 0.002, 0, 0, 0, 0]
        kings_odds = [0.075, 0.078, 0.081, 0.085, 0, 0, 0.197, 0.341, 0.129, 0.013, 0, 0, 0, 0]
        raptors_odds = [0.06, 0.063, 0.067, 0.072, 0, 0, 0, 0.345, 0.321, 0.067, 0.004, 0, 0, 0]
        bulls_odds = [0.045, 0.048, 0.052, 0.057, 0, 0, 0, 0, 0.507, 0.259, 0.03, 0.001, 0, 0]
        wizards_odds = [0.03, 0.033, 0.036, 0.04, 0, 0, 0, 0, 0, 0.659, 0.190, 0.012, 0, 0]
        pelicans_odds = [0.02, 0.022, 0.024, 0.028, 0, 0, 0, 0, 0, 0, 0.776, 0.126, 0.004, 0]
        pacers_odds = [0.015, 0.017, 0.019, 0.021, 0, 0, 0, 0, 0, 0, 0, 0.861, 0.067, 0.001]
        warriors_odds = [0.01, 0.011, 0.012, 0.014, 0, 0, 0, 0, 0, 0, 0, 0, 0.929, 0.023]
        spurs_odds = [0.005, 0.006, 0.006, 0.007, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.976]

    odds_dictionary = {'Houston Rockets': rockets_odds, 'Minnesota Timberwolves': timberwolves_odds,
                       'Detroit Pistons': pistons_odds,
                       'Orlando Magic': magic_odds, 'Oklahoma City Thunder': thunder_odds,
                       'Cleveland Cavaliers': cavaliers_odds,
                       'Sacramento Kings': kings_odds, 'Toronto Raptors': raptors_odds, 'Chicago Bulls': bulls_odds,
                       'Washington Wizards': wizards_odds,
                       'New Orleans Pelicans': pelicans_odds, 'Indiana Pacers': pacers_odds,
                       'Golden State Warriors': warriors_odds, 'San Antonio Spurs': spurs_odds}

    if simulation_type == 'w':
        if iteration_counter == 1:
            playoff_teams = ['Charlotte Hornets', 'Boston Celtics', 'Miami Heat', 'Atlanta Hawks', 'New York Knicks',
                             'Milwaukee Bucks', 'Brooklyn Nets', 'Philadelphia 76ers',
                             'Utah Jazz', 'Pheonix Suns', 'Los Angeles Clippers', 'Denver Nuggets', 'Dallas Mavericks',
                             'Portland Trail Blazers', 'Los Angeles Lakers',
                             'Memphis Grizzlies']
            playoff_team_selector = random.randint(0, len(playoff_teams) - 1)
            playoff_team = playoff_teams[playoff_team_selector]
            print('The Wild Card Playoff Team selected to participate in the NBA Draft Lottery is the:', playoff_team)
            print('The', playoff_team, 'will enter the NBA Draft Lottery with:', str(wild_card_odds),
                  'odds of obtaining the #1 pick')

        odds_dictionary[playoff_team] = wild_card_odds

    return odds_dictionary, playoff_team, wild_card_odds

def odds_assigner(ping_pong_combinations, discarded_combination, odds_dict):
    """
    This function assigns a certain number of combinations of ping pong balls to each team based on their odds.
    We temporarily remove the unassigned ping pong ball from the list of ping pong ball combinations and
    re-assign it back after. Then, we generate 1000 random numbers from 0 through 1000. Finally, we assign each
    team their odds from this number
    :param ping_pong_combinations: an array containing all the combinations of 14 choose 4 ping pong balls
    :param discarded_combination: the one combination that is not assigned to a team
    :param odds_dict: A dictionary that maps each their to their respective odds
    :return: a resulting dictionary that maps each team to their combinations
    """
    ping_pong_combinations.remove(discarded_combination)
    random_indices = random.sample(range(len(ping_pong_combinations)), 1000)
    random_indices_length = len(random_indices)
    combinations_dictionary = {}
    for i in odds_dict.keys():
        sample = int(odds_dict[i] * random_indices_length)
        draw = random.sample(random_indices, sample)
        for j in draw:
            if draw[0] == j:
                combinations_dictionary[i] = [ping_pong_combinations[j]]
            else:
                combinations_dictionary[i].append(ping_pong_combinations[j])
            random_indices.remove(j)
    ping_pong_combinations.append(discarded_combination)
    return combinations_dictionary

def ball_combination_picker():
    """
    This function simulates the selection of combinations of balls as done in the NBA Draft Lottery.
    First, a list of numbers from 1-15 is created. Then, the balls are mixed for 1/100000 of the time they
    are mixed in the actual NBA Draft Lottery. during this time, the list is shuffled and a random number is
    chosen from the list. This represents the first ball drawn. This process is repeated until 4 balls are drawn.
    :return: a list representing the 4 number combination that was drawn
    """
    ping_pong_balls = list(range(1, 15))
    number_of_balls_picked = 0
    ball_combination = []

    while number_of_balls_picked < 4:
        number_of_balls_picked += 1
        start = time.time()
        time.time()
        elapsed = 0

        if number_of_balls_picked == 1:
            mixing_seconds = 0.0002
        else:
            mixing_seconds = 0.0001

        while elapsed < mixing_seconds:
            random.shuffle(ping_pong_balls)
            elapsed = time.time() - start
            print("Shuffling ping pong balls; ", elapsed, "seconds elapsed...")
            time.sleep(.0001)
        chosen_ball = random.choice(ping_pong_balls)
        print("The chosen ball is: ", chosen_ball)
        ball_combination.append(chosen_ball)
        ping_pong_balls.remove(chosen_ball)

    return ball_combination

def team_selector(four_ball_combination, displaced_combination, teams_combinations):
    """
    Once the combination of balls is drawn, we must check which team has actually been assigned this combination.
    In order to do this, we look at all the permuatations of the ball combination and compare it to the combination
    assigned to each team and the unassigned combination to see which one the combination belongs to.
    :param four_ball_combination: an array representing the four number combination that was chosen
    :param displaced_combination: an array representing the combination that has not been assigned to a team
    :param teams_combinations: a dictionary that maps each team to a set of combinations they've been assigned to
    :return: the team that has been assigned the combination

    >>> team = team_selector([1,2,3,4], [11,12,13,14], {'Houston Rockets': [(1,2,3,4)]})
    >>> team == 'Houston Rockets'
    True

    >>> team = team_selector([1,2,3,4], [11,12,13,14], {'Minnesota Timberwolves': [(1,2,4,3)]})
    >>> team == 'Minnesota Timberwolves'
    True

    >>> team = team_selector([1,2,5,4], [11,12,13,14], {'Minnesota Timberwolves': [(1,2,4,3)]})
    >>> team != 'Minnesota Timberwolves'
    True
    """
    ball_combinations = list(permutations(four_ball_combination, 4))
    unassigned_four_ball_combinations = list(permutations(displaced_combination, 4))
    for i in ball_combinations:
        if i in unassigned_four_ball_combinations:
            return ValueError

        for j in teams_combinations:
            if i in teams_combinations[j]:
                return j

def lottery_results(dictionary_combinations, combination_unassigned, input_user):
    """
    This function calls on the ball_combination_picker() and team_selector() methods to run a full simulation of
    one NBA Draft Lottery. For the regular simulation, based on the first four teams that are assigned picks,
    the simulator goes in order based on a list of the teams in order of odds that are remaining and assigns
    them the picks 5-12. There are modifications for the other simulations involved, such as changing the number
    of teams that are picked using ping pong balls.
    :param dictionary_combinations: dictionary that maps each team to their assigned ball combinations
    :param combination_unassigned: an array representing the unassigned ball combination
    :param input_user: a user inputted string expressing what type of simulation this is
    :return: a dictionary that maps each team to the pick that they've been given in the lottery
    """
    team_aggregate_stats = {}
    team_order = 1
    lottery_order = list(dictionary_combinations.keys())
    pick_limit = 0

    if input_user == 'r' or input_user == 'R' or input_user == 'w' or input_user == 'W':
        pick_limit = 4
        pick_number = 5

    elif input_user == 'a' or input_user == 'A':
        pick_limit = 14

    while team_order <= pick_limit:
        ball_combination = ball_combination_picker()
        team = team_selector(ball_combination, combination_unassigned, dictionary_combinations)
        print()

        if team in lottery_order:
            print("The number #", team_order, " pick in the 2021 NBA Draft goes to: ", team)
            if team not in team_aggregate_stats:
                team_aggregate_stats[team] = [team_order]
            else:
                team_aggregate_stats[team].append(team_order)
            print()
            lottery_order.remove(team)
            team_order += 1

    if input_user != 'a' and input_user != 'A':
        if input_user == 'r' or input_user == 'R':
            total_pick_limit = 14

        elif input_user == 'w' or input_user == 'W':
            total_pick_limit = 15

        print()
        print("Picks 5 -", total_pick_limit, "are in this order: ")
        for j in lottery_order:
            if pick_number != total_pick_limit:
                print(j + ", ")
            else:
                print(j)

            if j not in team_aggregate_stats:
                team_aggregate_stats[j] = [pick_number]
            else:
                team_aggregate_stats[j].append(pick_number)
            pick_number += 1

    print('___________________')
    return team_aggregate_stats

def team_stats_calculator(team_stats):
    """
    This function uses the Counter function to count the number of times each team got each pick all the iterations
    of the simulation are complete.
    :param team_stats: A dictionary that maps each team to every pick that they received during the simulation
    :return: a Counter object that maps each team to the counts of each pick that they received during the simulation

    >>> cleaned_team_stats = team_stats_calculator({'Houston Rockets': [1, 2, 4, 6, 7]})
    >>> cleaned_team_stats
    {'Houston Rockets': Counter({1: 1, 2: 1, 4: 1, 6: 1, 7: 1})}

    >>> cleaned_team_stats = team_stats_calculator({'Houston Rockets': [1, 2, 4, 6, 7], 'Minnesota Timberwolves': [1, 3, 3, 3, 3]})
    >>> len(cleaned_team_stats['Minnesota Timberwolves']) == 2
    True

    >>> cleaned_team_stats = team_stats_calculator({'Houston Rockets': [1, 2, 4, 6, 7], 'Minnesota Timberwolves': [1, 3, 3, 3, 3]})
    >>> len(cleaned_team_stats) == 4
    False
    """
    formatted_team_stats = {}
    for i in team_stats:
        formatted_team_stats[i] = Counter(team_stats[i])
    return formatted_team_stats

def team_data_plotter(team_aggregate_data):
    """
    This function creates two lists, one that contains each team's names, and one that contains their associated
    picks from the simulation...these are used to generate a plot that provides a visual understanding of the
    simulation
    :param team_aggregate_data: a dictionary that maps each team to the counts of the picks they received
                                during the simulation
    """
    new_key = "Kings"
    old_key = "Sacramento Kings"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Pistons"
    old_key = "Detroit Pistons"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Cavs"
    old_key = "Cleveland Cavaliers"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Rockets"
    old_key = "Houston Rockets"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Wolves"
    old_key = "Minnesota Timberwolves"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Magic"
    old_key = "Orlando Magic"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Thunder"
    old_key = "Oklahoma City Thunder"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Raptors"
    old_key = "Toronto Raptors"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Bulls"
    old_key = "Chicago Bulls"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Wizards"
    old_key = "Washington Wizards"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Pelicans"
    old_key = "New Orleans Pelicans"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Pacers"
    old_key = "Indiana Pacers"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Warriors"
    old_key = "Golden State Warriors"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    new_key = "Spurs"
    old_key = "San Antonio Spurs"
    if old_key in team_aggregate_data:
        team_aggregate_data[new_key] = team_aggregate_data.pop(old_key)

    team_list = []
    pick_list = []
    for i in team_aggregate_data:
        for j in team_aggregate_data[i].items():
            k = 0
            while k < int(j[1]):
                team_list.append(i)
                pick_list.append(j[0])
                k += 1

    fig_dims = (20, 10)
    fig, ax = plt.subplots(figsize=fig_dims)
    x = team_list
    y = pick_list
    print('___________________')
    print()
    print("The following plot summarizes our simulations of the NBA Draft Lottery: ")
    print()
    sns.stripplot(x=x, y=y, alpha=0.5, s=10, linewidth=1.0, jitter=True)
    plt.show()

def team_sim_data(team_info, sim_count, input_from_user):
    """
    This function takes our Counter dictionary and uses its values to obtain some summary statistics
    for each team from our simulation. These statistics include: mean pick, standard deviation of pick,
    highest pick and lowest pick. This function also tests our hypotheses laid out in the readme as well.
    :param team_info: a dictionary that maps each team to the counts of the number of times they obtained each pick
    :param sim_count: the number of times the simulation iterated
    :param input_from_user: a user inputted string expressing what type of simulation this is
    """
    print()
    print('The following statistics summarize our simulations of the NBA Draft Lottery: ')
    print()
    hypothesis_1_count = 0
    hypothesis_1_indices = []
    hypothesis_2_count = 0
    hypothesis_2_indices = []
    hypothesis_3_count = 0

    for i in team_info:
        picks = []
        for j in team_info[i].items():
            k = 0
            while k < int(j[1]):
                picks.append(j[0])
                k += 1

        print(i, "simulation statistics: ")
        print()
        print("Average Pick: " + str(np.mean(picks)))
        print("Standard Deviation of Picks: " + str(np.std(picks)))
        print("Lowest Pick: #" + str(np.max(picks)))
        print("Highest Pick: #" + str(np.min(picks)))
        print()

        if input_from_user == 'r':
            if (
                    i == 'Oklahoma City Thunder' or i == 'Cleveland Cavaliers' or i == 'Sacramento Kings' or i == 'Toronto Raptors'):
                for r, k in enumerate(picks):
                    if k <= 4 and r not in hypothesis_1_indices:
                        hypothesis_1_count += 1
                        hypothesis_1_indices.append(i)

        if input_from_user == 'a':
            if i == 'Houston Rockets' or i == 'Minnesota Timberwolves' or i == 'Detroit Pistons':
                for r, k in enumerate(picks):
                    if k >= 7 and r not in hypothesis_2_indices:
                        hypothesis_2_count += 1
                        hypothesis_2_indices.append(i)

        if input_from_user == 'o':
            if i == 'New York Knicks':
                for r in picks:
                    if r == 1:
                        hypothesis_3_count += 1

    if input_from_user == 'r' or input_from_user == 'a' or input_from_user == 'o':
        print('___________________')
        print()
        if input_from_user == 'r':
            if hypothesis_1_count / (sim_count - 1) >= 0.25:
                print("Hypothesis 1 is: True")
            else:
                print("Hypothesis 1 is: False")

        elif input_from_user == 'a':
            if hypothesis_2_count / (sim_count - 1) >= 0.40:
                print("Hypothesis 2 is: True")
            else:
                print("Hypothesis 2 is: False")

        elif input_from_user == 'o':
            if hypothesis_3_count / (sim_count - 1) >= 0.40:
                print("Hypothesis 3 is: True")
            else:
                print("Hypothesis 3 is: False")

def multinomial_simulator(odds, counter):
    """
    This function iterates through the odds list for each team in the lottery. It then creates a multinomial
    distribution and simulates the number of times each pick is awarded to each team out of a given number
    of simulations.
    :param odds: A list representing a team's chances of obtaining picks 1-14
    :param counter: An integer representing how many times the simulation should iterate
    """
    print()
    for i in odds:
        simulations = multinomial(counter, odds[i])
        for j in range(len(simulations)):
            print(i + ' Pick %d: %d ' % (j + 1, simulations[j]))
        print()

def bernoulli_random_trial():
    """
    This function simply uses the numpy package for a random bernoulli trial with 0.7 success rate and
    runs this one time. Then, it returns the results: either a 1 for success or a 0 for failure. This is used to determine
    whether or not the NBA's attempt to rig the 1985 Lottery in favor of the Knicks is successful or not.
    :return: a variable that represents a 0 for a failed attempt or a 1 for a successful attempt

    >>> result = bernoulli_random_trial()
    >>> result == 0 or result == 1
    array([ True])
    """
    x = 1
    success_rate = 0.7
    Y = np.random.binomial(1, success_rate, x)
    return Y

def nba_rigging_odds(bernoulli_result):
    """
    This function determines the odds of each team winning the lottery. If the bernoulli trial was a success, a
    normal random variable that results in odds that are larger than the original odds for the Knicks is used to
    replace their original odds, then a randomly selected team loses the difference between these odds,
    illustrating that the lottery was rigged. If the bernoulli trial was a failure, the Knicks' odds are brought
    down to 0.001 and a randomly selected team gets the rest of their odds added.
    :param bernoulli_result: a variable that represents a 0 for a failed attempt or a 1 for a successful attempt
    :return: a list of the odds for each team to win the lottery
    """
    pacers_odds = 0.1429
    clippers_odds = 0.1429
    supersonics_odds = 0.1429
    hawks_odds = 0.1429
    kings_odds = 0.1429
    warriors_odds = 0.1429

    if bernoulli_result == 1:
        print('The NBA was not caught attempting to rig the 1985 NBA Draft Lottery')
        mu, sigma = 0.25, 0.1
        knicks_odds = np.round(np.random.normal(mu, sigma, 1),
                               3)  # using a normal dist. to determine odds of rigged knicks pick
        while knicks_odds <= 0 or knicks_odds >= 0.2858 or knicks_odds <= 0.1429:  # knicks should not have non-positive odds or odds that will reduce other teams' odds to negative values
            knicks_odds = np.round(np.random.normal(mu, sigma, 1), 3)
        randomizer = random.randint(1, 6)
        if randomizer == 1:
            pacers_odds -= (knicks_odds - 0.1429)
        elif randomizer == 2:
            clippers_odds -= (knicks_odds - 0.1429)
        elif randomizer == 3:
            supersonics_odds -= (knicks_odds - 0.1429)
        elif randomizer == 4:
            hawks_odds -= (knicks_odds - 0.1429)
        elif randomizer == 5:
            kings_odds -= (knicks_odds - 0.1429)
        else:
            warriors_odds -= (knicks_odds - 0.1429)
        print('The New York Knicks rigged odds are now:', knicks_odds)
        print()

    else:
        print('The NBA was caught attempting to rig the 1985 NBA Draft Lottery')
        knicks_odds = 0.01
        randomizer = random.randint(1, 6)
        if randomizer == 1:
            pacers_odds += (0.1429 - knicks_odds)
        elif randomizer == 2:
            clippers_odds += (0.1429 - knicks_odds)
        elif randomizer == 3:
            supersonics_odds += (0.1429 - knicks_odds)
        elif randomizer == 4:
            hawks_odds += (0.1429 - knicks_odds)
        elif randomizer == 5:
            kings_odds += (0.1429 - knicks_odds)
        else:
            warriors_odds += (0.1429 - knicks_odds)
        print('The New York Knicks odds after punishment are now:', knicks_odds)
        print()

    return [knicks_odds, pacers_odds, clippers_odds, supersonics_odds, hawks_odds, kings_odds, warriors_odds]

def nba_1985_draft_lottery_simulator(team_odds):
    """
    Given the odds for each team, a multinomial distribution is used to determine the 1st pick, then the 2nd pick,
    and so on, all the way to the fifth pick. Then, the final two picks in the lottery are filled in manually.
    The resulting pick for each team is then added to a dictionary, in which the key is the team name and the value
    is the pick, and this dictionary is returned.
    :param team_odds: a list representing the odds for all the teams in the lottery of getting the number #1 pick
    :return: a dictionary that maps each team to their pick
    """
    team_list = ['New York Knicks', 'Indiana Pacers', 'Los Angeles Clippers', 'Seattle SuperSonics', 'Atlanta Hawks',
                 'Sacramento Kings', 'Golden State Warriors']
    pick_list = []
    pick_number = 1
    while pick_number <= 5:
        simulations = multinomial(1, team_odds)
        pick_list.append(team_list[np.argmax(simulations)])
        team_odds.pop(np.argmax(simulations))
        team_list.pop(np.argmax(simulations))
        pick_number += 1

    for i in team_list:
        if i not in pick_list:
            pick_list.append(i)

    pick_dictionary = {}
    for i, value in enumerate(pick_list):
        pick_dictionary[value] = [i + 1]
        print("The number #", i + 1, "pick in the 1985 NBA Draft goes to:", value)

    print()
    return pick_dictionary


"""Client library for Akt Direkt service."""

import threading
import urllib.parse
from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredError, OAuth2Error
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session

__copyright__ = """

    Copyright 2018 Lantmäteriet

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

"""

class AktDirectClient:
    """Client library for Akt Direkt service."""

    def __init__(self, service_url, consumer_key, consumer_secret, token_url):
        """Initialize client with configuration given by Lantmäteriet."""
        self.service_url = service_url
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.token_url = token_url
        self._update_token_recursion_limiter = threading.Semaphore(
            1
        )  # Used to stop recursion in error handling
        self._init_lock = threading.RLock()
        self._initialize()

    def _initialize(self):
        """Initialize/reinitialize client libraries."""
        with self._init_lock:
            self.auth = HTTPBasicAuth(self.consumer_key, self.consumer_secret)
            self.client = BackendApplicationClient(client_id=self.consumer_key)
            self.oauth = OAuth2Session(client=self.client)
            self.update_token()

    def update_token(self):
        """Fetch new token from server.

        Get a access token using your consumer key and secret,
        the token will be used to access the service.
        Note that a token has a limited life.
        """
        with self._init_lock:
            try:
                token = self.oauth.fetch_token(token_url=self.token_url, auth=self.auth)
                print(f"fetched new token: {token}")
                self.oauth.token = token
            except OAuth2Error as err:
                # We have seen a case where update_token on expiration fails but reinitializaton
                # works, so if update fails we try to reinitialize.
                # But initilize calls update_token so if it's a "real" error we needs to stop the error
                # handling from going into a recursion.
                with self._update_token_recursion_limiter as recursion_ok:
                    if not recursion_ok:
                        raise

                    print(
                        "Got OAuth2Error when trying to update token, will reinitialize. error was: ",
                        err,
                    )
                    self._initialize()

    def _call_service(self, rel_path, params=None, stream=False):
        """Call the service and handle token expiration.

        This method is used by the get_ and test_ methods in this class.

        returns a requests response object
        """
        # without the / the last element in service_url may be replaced
        url = urllib.parse.urljoin(self.service_url + "/", rel_path)
        try:
            res = self.oauth.get(url, stream=stream, params=params)
        except TokenExpiredError:
            # If the token has expired get a new one and retry
            self.update_token()
            res = self.oauth.get(url, stream=stream, params=params)
        except OAuth2Error as err:
            # This is not a case we have seen but to be on the safe side we try to reinitialize
            # if it happens.
            print(
                "Got OAuth2Error other than TokenExpiredError, will reinitialize. error was: ",
                err,
            )
            self._initialize()
            res = self.oauth.get(url, stream=stream, params=params)
        if not res.ok:
            # If update_token() fails the next call will result in a 401
            # We can choose to reinitialize on all errors instead of only 401 because
            # the Akt-Direkt API do not use HTTP error codes as part of the API.
            print(
                "Got an HTTP response >= 400, will reinitialize and try again, error was: ",
                res.status_code,
                res.text,
            )
            self._initialize()
            res = self.oauth.get(url, stream=stream, params=params)

        print(f"Called {res.request.url}", params)
        if not res.ok:
            print("Call failed, status-code:", res.status_code)
            print(res.text)
        return res

    def get_djvu(self, archive, id_):
        """Get the dossier as a DjVU.

        returns a requests response object
        """
        rel_path = "document/bundle.djvu"
        params = {"archive": archive, "id": id_}
        res = self._call_service(rel_path, stream=True, params=params)
        return res

    def get_djvu_djvu_on_error(self, archive, id_):
        """Get the dossier as a DjVU.

        returns a requests response object
        """
        rel_path = "document/djvu_on_error/bundle.djvu"
        params = {"archive": archive, "id": id_}
        res = self._call_service(rel_path, stream=True, params=params)
        return res

    def get_ping(self):
        """Make a communication test with Akt Direkt.

        This call test your configuration, communications, authentication and authorization.

        returns a requests response object
        """
        rel_path = "ping"
        res = self._call_service(rel_path)

        return res

    def test_connection(self):
        """Make a communication test with Akt Direkt.

        This call test your configuration, communications, authentication and authorization.

        returns a boolean, True if everything is OK or False if not.
        """
        res = self.get_ping()
        return res.ok


from typing import Dict

import pandas as pd
import pytest
from biome.text import TrainerConfiguration, VocabularyConfiguration
from biome.text import Pipeline
from biome.text.data import DataSource

@pytest.fixture
def training_data_source(tmp_path) -> DataSource:
    data_file = tmp_path / "relations.json"
    df = pd.DataFrame(
        [
            {
                "text": "The most common audits were about waste and recycling.",
                "entities": [
                    {"start": 34, "end": 39, "label": "PN", "text": "waste"},
                    {"start": 16, "end": 22, "label": "QTY", "text": "audits"},
                ],
                "label": "Message-Topic(e1,e2)",
            },
            {
                "text": "The company fabricates plastic chairs.",
                "entities": [
                    {"start": 4, "end": 11, "label": "OBJECT", "text": "company"},
                    {"start": 31, "end": 37, "label": "SUBJECT", "text": "chairs"},
                ],
                "label": "Product-Producer(e2,e1)",
            },
        ]
    )
    df.to_json(data_file, lines=True, orient="records")

    return DataSource(
        source=str(data_file), flatten=False, lines=True, orient="records"
    )

@pytest.fixture
def pipeline_dict() -> Dict:
    pipeline_dict = {
        "name": "biome-rele",
        "features": {
            "word": {"embedding_dim": 2},
            "char": {
                "embedding_dim": 2,
                "dropout": 0.1,
                "encoder": {
                    "type": "gru",
                    "hidden_size": 2,
                },
            },
        },
        "head": {
            "type": "RelationClassification",
            "labels": ["Message-Topic(e1,e2)", "Product-Producer(e2,e1)"],
            "entities_embedder": {"num_embeddings": 12, "embedding_dim": 50},
            "feedforward": {
                "num_layers": 1,
                "hidden_dims": [4],
                "activations": ["relu"],
                "dropout": [0.1],
            },
        },
    }

    return pipeline_dict

@pytest.fixture
def trainer_dict() -> Dict:
    trainer_dict = {
        "num_epochs": 1,
        "optimizer": {"type": "adamw", "lr": 0.002},
    }

    return trainer_dict

def test_train(pipeline_dict, training_data_source, trainer_dict, tmp_path):
    pipeline = Pipeline.from_config(pipeline_dict)
    pipeline.predict(
        text="The most common audits were about waste and recycling",
        entities=[
            {"start": 34, "end": 39, "label": "OBJECT", "text": "waste"},
            {"start": 16, "end": 22, "label": "SUBJECT", "text": "audits"},
        ],
    )
    pipeline.create_vocabulary(VocabularyConfiguration(sources=[training_data_source]))

    pipeline.train(
        output=str(tmp_path / "relation_classifier"),
        trainer=TrainerConfiguration(**trainer_dict),
        training=training_data_source,
        validation=training_data_source,
    )

    pl_trained = Pipeline.from_pretrained(str(tmp_path / "relation_classifier"))
    pl_trained.predict(
        text="The most common audits were about waste and recycling",
        entities=[
            {"start": 34, "end": 39, "label": "OBJECT", "text": "waste"},
            {"start": 16, "end": 22, "label": "SUBJECT", "text": "audits"},
        ],
    )


import os

import cv2 as cv
import torch
import tqdm
from torch.multiprocessing import Pool
from tqdm import tqdm

def detect_face(data):
    from utils import get_central_face_attributes, align_face
    src_path = data['src_path']
    dst_path = data['dst_path']
    with torch.no_grad():
        has_face, bboxes, landmarks = get_central_face_attributes(src_path)
        if has_face:
            img = align_face(src_path, landmarks)
            cv.imwrite(dst_path, img)

    return True

def megaface_align(src, dst):
    image_paths = []
    for dirName, subdirList, fileList in tqdm(os.walk(src)):
        for fname in fileList:
            if fname.lower().endswith('.jpg'):
                src_path = os.path.join(dirName, fname)
                dst_path = os.path.join(dirName.replace(src, dst), fname)
                image_paths.append({'src_path': src_path, 'dst_path': dst_path})

    # print(image_paths[:20])
    num_images = len(image_paths)
    print('num_images: ' + str(num_images))

    with Pool(1) as p:
        r = list(tqdm(p.imap(detect_face, image_paths), total=num_images))

    # for image_path in tqdm(image_paths):
    #     detect_face(image_path)

    print('Completed!')

if __name__ == '__main__':
    megaface_align('megaface/MegaFace', 'megaface/MegaFace_aligned')
    megaface_align('megaface/FaceScrub', 'megaface/FaceScrub_aligned')


# -*- coding: utf-8 -*-
"""
Created on Mon Aug 28 20:46:08 2017

@author: Victor
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import linear_model
from sklearn import metrics
from sklearn import pipeline

def plot_learning_curve(estimator, X, y):
    plt.figure()
    plt.title('Learning curve')
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = model_selection .learning_curve(estimator, X, y, train_sizes=np.linspace(.1, 1.0, 5))
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")

    plt.legend(loc="best")
    return plt

if __name__ == '__main__':
    # Read the training dataset
    trainDataSet = pd.read_table('train.csv', encoding='utf-8', sep=',', index_col=0, header=0)

    # Fills in missing values with average value
    trainDataSet['Embarked'].fillna('Unknwon', inplace = True)
    trainDataSet['Age'].fillna(30, inplace = True)

    # Generate dummy features from categorical features
    X = pd.get_dummies(trainDataSet[['Age','SibSp','Parch','Pclass','Sex','Embarked']], columns = ['Pclass','Sex','Embarked'])
    y = trainDataSet.Survived

    # Split the training set in training and test set
    X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3)

    #Generate a pipeline that scales and applies logistic regression
    pipe = pipeline.Pipeline(steps=[('scaler', preprocessing.StandardScaler()), ('logistic', linear_model.LogisticRegression())])

    # Find the best value for parameter C
    estimator = model_selection.GridSearchCV(pipe, dict(logistic__C=np.logspace(-4, 4, 9)))
    estimator.fit(X_train, y_train)
    print(estimator.best_params_)

    # Plot the learning curve
    plot_learning_curve(estimator.best_estimator_, X_train, y_train)

    # Estimate the prediction on the test dataset
    y_test_est = estimator.best_estimator_.predict(X_test)
    print(metrics.f1_score(y_test, y_test_est))
    print(metrics.accuracy_score(y_test, y_test_est))

    # Read the dataset to predict
    predictDataSet = pd.read_table('test.csv', encoding='utf-8', sep=',', index_col=0, header=0)
    predictDataSet['Embarked'].fillna('Unknwon', inplace = True)
    predictDataSet['Age'].fillna(30, inplace = True)

    # Generate features and predict output
    X_pred = pd.get_dummies(predictDataSet[['Age','SibSp','Parch','Pclass','Sex','Embarked']], columns = ['Pclass','Sex','Embarked'])
    X_pred = X_pred.reindex(columns = X.columns, fill_value=0)
    y_pred = estimator.best_estimator_.predict(X_pred)

    # Save output to format for kaggle submission
    np.savetxt('prediction.csv', np.column_stack((X_pred.index.values, y_pred)), delimiter=',', header = 'PassengerId,Survived', fmt = '%i', comments='')


from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import CustomerForm,WomanForm,SkillForm
from .models import Woman,Skill,Notification,Customer

# Create your views here.
@login_required(login_url='/accounts/login/')
def home(request):

    return render(request, 'home.html')

@login_required(login_url='/accounts/login/')
def womanprofile(request):
    current_user=request.user
    if request.method == 'POST':
        form=WomanForm(request.POST,request.FILES)
        if form.is_valid():
            womanprofile=form.save(commit=False)
            womanprofile.user_id = current_user
            womanprofile.save()

    else:
        form=WomanForm()

    return render(request,'womanprofile.html',{"forms":form})

@login_required(login_url='/accounts/login/')
def customerprofile(request):
    current_user=request.user
    if request.method == 'POST':
        form=CustomerForm(request.POST,request.FILES)
        if form.is_valid():
            customerprofile=form.save(commit=False)
            customerprofile.user_id = current_user
            customerprofile.save()

    else:
        form=CustomerForm()

    return render(request,'customerprofile.html',{"forms":form})

@login_required(login_url='/accounts/login/')
def skill(request):
    current_user=request.user
    print (current_user.id)
    lady=Woman.objects.get(user_id=current_user.id)
    if request.method == 'POST':
        print('-'*30)
        print(lady)

        form=SkillForm(request.POST,request.FILES)
        if form.is_valid():
            skill=form.save(commit=False)
            skill.woman_id = lady
            skill.save()

    else:
        form=SkillForm()

    return render(request,'skill.html',{"forms":form})

def salon(request):
    salon_skills=Skill.objects.filter(skill_service=5)

    return render(request,'salon.html',{'salon_skills':salon_skills})

def laundry(request):
    laundry_skills=Skill.objects.filter(skill_service=6)

    return render(request,'laundry.html',{'laundry_skills':laundry_skills})

def babysitting(request):
    babysitting_skills=Skill.objects.filter(skill_service=7)

    return render(request,'babysitting.html',{'babysitting_skills':babysitting_skills})

def grocery(request):
    grocery_skills=Skill.objects.filter(skill_service=8)

    return render(request,'grocery.html',{'grocery_skills':grocery_skills})

def notification(request, service, id):
    current_user=request.user
    try:

        customer = Customer.objects.get(user_id=current_user.id)
    except:
        return redirect(customerprofile)
    new_notification = Notification(service=service,location=customer.location,phone=customer.phone,woman_id=id, customer_id=current_user.id)
    new_notification.save_notification()

    return redirect(service.lower())

def profile_notification(request):
    current_user=request.user
    print('Hello',current_user.id)
    try:
        woman=Woman.objects.get(user_id=current_user.id)
        woman_account=Notification.objects.filter(customer_id=current_user.id)
        print('-'* 30)
        print(woman_account)
    except:
        return redirect(womanprofile)
    return render(request,'notification.html',{'woman_account':woman_account})


"""
Routines for preprocessing image stacks.

All functions in this module are designed to take an image stack and additional arguments as input.
"""
import numpy as np
from scipy.fft import fft2
from skimage.registration import phase_cross_correlation
from skimage.transform import AffineTransform, warp
from .image_functions import detect_changes_division, detect_changes_subtraction

def _stack_operation(stack, function, *args, **kwargs):
    """
    Perform an operation for all images of an image stack.

    This is just a wrapper for a function which can perform a procedure for one image to
    perform it for all images of a stack instead.

    Parameters
    ----------
    stack: ImageStack
        The image stack the function should be performed on
    function: function
        A function which takes ONE image as input and returns ONE image
    args:
        args are forwarded to the function.
    kwargs:
        kwargs are forwarded to the function.
    """
    for ind, img in enumerate(stack):
        stack[ind] = function(img, *args, **kwargs)
    return stack

def _rolling_stack_operation(stack, function, keep_first=False, *args, **kwargs):
    """
    Perform an rolling operation for all images of an image stack.

    :math:`I_{new} = func(I_{n-1}, I_n)`

    This is just a wrapper for a function which can perform a procedure for two subsequent images
    for a whole stack.

    Parameters
    ----------
    stack: ImageStack
        The image stack the function should be performed on
    function: function
        A function which takes TWO subsequent images as input and returns ONE image
    keep_first: bool
        If True, keep the first image of the stack.
        The function will not be performed on the first image alone!
    args:
        args are forwarded to the function.
    kwargs:
        kwargs are forwarded to the function.
    """
    img_minus1 = stack[0]
    for ind, img in enumerate(stack[1:]):
        stack[ind+1] = function(img_minus1, img, *args, **kwargs)
        img_minus1 = img
    if not keep_first:
        del stack[0]
    return stack

def region_of_interest(images, x0=0, x1=None, y0=0, y1=None):
    """
    Crop all images in a stack to the desired shape.

    This function changes the images in the stack.
    If the input images should be preserved copy the input to a separate object before!

    The coordinate system is the following: x0->x1 = width, y0->y1 = height from the top left corner of the image

    Parameters
    ----------
    images: list, ImageStack
    x0: int
    x1: int
    y0: int
    y1: int

    Returns
    -------
    out: list, ImageStack
        ImageStack or list with the cropped images
    """
    for ind, img in enumerate(images):
        images[ind] = img[y0:y1, x0:x1]
    return images

def image_shift(images):
    """
    Compute the shift of all images in a stack.

    The shift of the n+1st image relative to the n-th is computed. The commutative sum of these shifts
    is the shift relative to the 0th image in the stack.

    All input images must have the same width and height!
    Parameters
    ----------
    images: ImageStack, list

    Returns
    -------
    out: list
        [(0,0), (y1, x1), ...(yn, xn)] The shift in x and y direction relative to the first image in the stack.
    """
    n_minus_1 = fft2(images[0])
    shift = [(0, 0)]

    for img in images[1:]:
        fft_n = fft2(img)
        shift.append(phase_cross_correlation(n_minus_1, fft_n, space='fourier', upsample_factor=5)[0])
        n_minus_1 = fft_n

    return np.cumsum(shift, axis=0)

def biggest_common_sector(images):
    """
    Biggest common sector of the image stack

    This function computes the relative translation between the images with the first image in the stack as
    the reference image. Then the biggest common sector is cropped from the images. The cropping window
    moves with the relative translation of the images so that the translation is corrected.

    Warping of the images which could be a result of strain is not accounted for. If the warp cant be neglected
    do not use this method!!

    Parameters
    ----------
    images: list or ImageStack

    Returns
    -------
    out: list, ImageStack
        list or ImageStack with the corrected images.
    """
    # if all images are the same shape, no need to crop them
    shapes = np.array([img.shape for img in images])
    height, width = shapes.min(axis=0)
    if not (np.all(shapes[:, 0] == height) and np.all(shapes[:, 1] == width)):
        images = region_of_interest(images, 0, width, 0, height)

    # compute shift relative to the 0th image
    total_shift = (np.round(image_shift(images)) * -1).astype(int)

    # minimal and maximal boarders to cut after shift
    h_min, w_min = np.abs(np.min(total_shift, axis=0)).astype(int)
    h_max, w_max = np.abs(np.max(total_shift, axis=0)).astype(int)

    # cutting out the image
    for ind, (n, (t_h, t_w)) in enumerate(zip(images, total_shift)):
        images[ind] = n[t_h + h_min:height + t_h - h_max, t_w + w_min: width + t_w - w_max]

    return images

def shift_correction(images):
    """
    Shift correction of all images in a stack. This function is more precise than :func:`biggest_common_sector`
    but more time consuming. The memory footprint is the same.

    This function computes the relative translation between the images with the first image in the stack as
    the reference image. The images are translated into the coordinate system of the 0th image form the stack.

    Warping of the images which could be a result of strain is not accounted for. If the warp cant be neglected
    do not use this function!

    Parameters
    ----------
    images: list, ImageStack

    Returns
    -------
    out: list, ImageStack
        list or ImageStack with the corrected images.
    """

    shapes = np.array([img.shape for img in images])
    height, width = shapes.min(axis=0)
    if not (np.all(shapes[:, 0] == height) and np.all(shapes[:, 1] == width)):
        images = region_of_interest(images, 0, width, 0, height)

    # compute shift relative to the 0th image
    total_shift = np.round(image_shift(images)) * -1

    h_min, w_min = np.abs(np.min(total_shift, axis=0).astype(int))
    h_max, w_max = np.abs(np.max(total_shift, axis=0).astype(int))

    for ind, (img, t) in enumerate(zip(images, total_shift)):
        if not (t[0] == 0 and t[1] == 0):
            shift = AffineTransform(translation=t[::-1])
            temp = warp(img, shift, mode='constant', cval=0.5,
                        preserve_range=True)[h_min: height - h_max, w_min: width - w_max].astype(img.dtype.type)
        else:
            temp = img[h_min: height - h_max, w_min: width - w_max]
        images[ind] = temp
    return images

def change_detection_division(images, output_range=None):
    """
    Change detection for all images in an image stack.

    Change detection with image rationing is applied to an image stack.
    The new images are the result of the change between the n-th and the n-1st image.

    The first image will be deleted from the stack.

    Parameters
    ----------
    images: ImageStack, list
    output_range: tuple, optional
        The resulting images will be rescaled to the given range. E.g. (0,1).

    Returns
    -------
    out: ImageStack, list
    """
    return _rolling_stack_operation(images, detect_changes_division, output_range=output_range)

def change_detection_subtraction(images, output_range=None):
    """
    Change detection for all images in an image stack.

    Change detection with image differencing is applied to an image stack.
    The new images are the result of the change between the n-th and the n-1st image.

    The first image will be deleted from the stack.

    Parameters
    ----------
    images: ImageStack, list
    output_range: tuple, optional
        The resulting images will be rescaled to the given range. E.g. (0,1).

    Returns
    -------
    out: ImageStack, list
    """
    return _rolling_stack_operation(images, detect_changes_subtraction, output_range=output_range)

def overload_images(images):
    """
    Combines the nth image with the n-1st with logical_or.

    :math:`I_n^{new} = I_n | I_{n-1}`

    Parameters
    ----------
    images: ImageStack
        Image stack with image-dtype bool

    Returns
    -------
    out: ImageStack
    """
    if images._dtype != bool:
        raise TypeError('The stack must contain only bool images!')

    def fun(img1, img2):
        return np.logical_or(img1, img2)
    return _rolling_stack_operation(images, fun, True)


import numpy as np
import cv2
from keras.models import load_model

label = ['circle', 'mark', 'erase', 'X']
filename = './../image_classification(CNN)/my_model.h5'
model = load_model(filename)

# load the two input images
img1 = cv2.imread("./survey1.jpg")
img2 = cv2.imread("./survey1_checked.jpg")

if img1.shape != img2.shape:
    print('Two images shape differ')
    width = img1.shape[0]
    height = img1.shape[1]
    # The position of width and height where exactly?
    img2 = cv2.resize(img2, (height, width), interpolation=cv2.INTER_AREA)

#convert the images to gray scale
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

kernel = np.ones((3, 3), np.uint8)

diff = cv2.subtract(gray1, gray2)
diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)

# diff = cv2.morphologyEx(diff, cv2.MORPH_CLOSE, kernel)
dilation = cv2.dilate(diff, kernel, iterations=3)

diff = cv2.medianBlur(dilation, 5)
_, mask = cv2.threshold(diff, 100, 255, cv2.THRESH_BINARY)  # Binary threshold
_, region = cv2.threshold(dilation, 200, 255, cv2.THRESH_BINARY_INV)

image, contours, hierachy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image = cv2.drawContours(img1, contours, -1, (0, 0, 255), -1)

for idx, cnt in enumerate(contours):
    x, y, w, h = cv2.boundingRect(cnt)
    roi = region[y:y+h, x:x+w]
    roi = cv2.copyMakeBorder(roi, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[255, 255, 255])
    extend = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
    cv2.imshow('test', extend)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    X = np.array([extend])
    X = X.reshape(1, 28, 28, 1)
    Y = model.predict(X)
    lab = np.unravel_index(np.argmax(Y), Y.shape)[1]
    print(label[lab])
    if label[lab] == "mark":
        color = (0, 255, 0)
    elif label[lab] == "circle":
        color = (0, 255, 0)
    elif label[lab] == "X":
        color = (0, 0, 255)
    else:
        color = (0, 0, 255)

    print('cnt: {} len: {}, coordinate: ({}, {}), ({}, {})'.format(idx, len(cnt), x, y, x + w, y + h))
    img3 = cv2.rectangle(img2, (x, y), (x + w, y + h), color, 2)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image', 600, 600)

cv2.imshow('image', img3)

cv2.waitKey(0)
cv2.destroyAllWindows()


from uuid import UUID

from pulsar.api import BadRequest, Http401

from lux.models import Schema, fields

def ensure_service_user(request, errorCls=None):
    # user must be anonymous
    if not request.cache.user.is_anonymous():
        raise (errorCls or BadRequest)
    return
    # the service user must be authenticated
    if not request.cache.user.is_authenticated():
        raise Http401('Token')

def id_or_field(field, id=None, **kwargs):
    if id:
        try:
            UUID(id)
        except ValueError:
            kwargs[field] = id
        else:
            kwargs['id'] = id
    return kwargs

class IdSchema(Schema):
    id = fields.UUID(required=True, description='unique id')


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

from __future__ import (division, absolute_import, print_function,
                        unicode_literals, annotations)

from urllib.parse import urlencode, quote_plus
import requests

def main():
    base_url = 'https://images-api.nasa.gov/search'

    search_term = 'apollo 11'
    desc = 'moon landing'
    media = 'image'
    query = {'q': search_term, 'description': desc, 'media_type': media}
    full_url = base_url + '?' + urlencode(query, quote_via=quote_plus)

    r = requests.get(full_url)
    data = r.json()
    item = data['collection']['items'][0]

    nasa_id = item['data'][0]['nasa_id']
    asset_url = 'https://images-api.nasa.gov/asset/' + nasa_id
    image_request = requests.get(asset_url)
    image_json = image_request.json()
    image_urls = [url['href'] for url in image_json['collection']['items']]
    print(image_urls)

if __name__ == '__main__':
    main()


# import the necessary packages
from __future__ import print_function
from bin.shapedetector import ShapeDetector
from PIL import Image
from PIL import ImageTk
import numpy as np
import tkinter as tki
import threading
import imutils
import cv2
import sqlite3 as sq

class PhotoBoothApp:

    def __init__(self, vs, outputPath):
        # store the video stream object and output path, then initialize
        # the most recently read frame, thread for reading frames, and
        # the thread stop event
        self.vs = vs
        self.outputPath = outputPath
        self.frame = None
        self.thread = None
        self.stopEvent = None
        self.shape = None

        # initialize the root window and image panel
        self.root = tki.Tk()
        self.panel = None

        # start a thread that constantly pools the video sensor for
        # the most recently read frame
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

        # Select from which ever compound lift is selected
        self.frame2 = tki.LabelFrame(self.root)
        self.current_row = 0

        #create a label for databases entry
        self.jb_label = tki.Label(self.frame2, text="Jenis Buku: ", font=18)
        self.jb_label.grid(row=self.current_row, column=0)
        self.jb_text = tki.StringVar()
        self.jb_entry = tki.Entry(self.frame2, textvariable=self.jb_text, font=18)
        self.jb_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.k_label = tki.Label(self.frame2, text="Kode: ", font=18)
        self.k_label.grid(row=self.current_row, column=0)
        self.k_text = tki.StringVar()
        self.k_entry = tki.Entry(self.frame2, textvariable=self.k_text, font=18)
        self.k_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.n_label = tki.Label(self.frame2, text="Nama Pengarang: ", font=18)
        self.n_label.grid(row=self.current_row, column=0)
        self.n_text = tki.StringVar()
        self.n_entry = tki.Entry(self.frame2, textvariable=self.n_text, font=18)
        self.n_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.p_label = tki.Label(self.frame2, text="Penerbit: ", font=18)
        self.p_label.grid(row=self.current_row, column=0)
        self.p_text = tki.StringVar()
        self.p_entry = tki.Entry(self.frame2, textvariable=self.p_text, font=18)
        self.p_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.ko_label = tki.Label(self.frame2, text="Kota: ", font=18)
        self.ko_label.grid(row=self.current_row, column=0)
        self.ko_text = tki.StringVar()
        self.ko_entry = tki.Entry(self.frame2, textvariable=self.ko_text, font=18)
        self.ko_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.t_label = tki.Label(self.frame2, text="Tahun: ", font=18)
        self.t_label.grid(row=self.current_row, column=0)
        self.t_text = tki.StringVar()
        self.t_entry = tki.Entry(self.frame2, textvariable=self.t_text, font=18)
        self.t_entry.grid(row=self.current_row, column=1)
        self.current_row += 1

        self.kol_text = tki.StringVar()
        self.gab_label = tki.Message(self.frame2, textvariable=self.kol_text, font=18, width=500)
        self.gab_label.grid(row=self.current_row)
        self.current_row += 1
        self.current_row += 1

        # create code input
        self.kin_label = tki.Label(self.frame2, text="Input kode: ", font=18)
        self.kin_label.grid(row=self.current_row, column=0)
        self.current_row += 1
        self.kin_text = tki.StringVar()
        self.kin_entry = tki.Entry(self.frame2, textvariable=self.kin_text, font=18)
        self.kin_entry.grid(row=self.current_row, column=0)
        self.inkode = tki.Button(self.frame2, text="input",
                               command=self.inputkode)
        self.inkode.grid(row=self.current_row, column=1)
        self.current_row += 1

        # create the button
        self.btn1 = tki.Button(self.frame2, text="Tambah Koleksi",
                               command=self.pluskoleksi)
        self.btn1.grid(row=self.current_row, column=0)
        self.btn2 = tki.Button(self.frame2, text="New Capture",
                               command=self.resume)
        self.current_row += 1
        self.btn2.grid(row=self.current_row, column=1)
        self.btn1 = tki.Button(self.frame2, text="Kurang Koleksi",
                               command=self.minkoleksi)
        self.btn1.grid(row=self.current_row, column=0)
        self.frame2.pack(side="right", fill='y')

        # set a callback to handle when the window is closed
        self.root.wm_title("Book Code")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose)

    def videoLoop(self):
        # DISCLAIMER:
        # I'm not a GUI developer, nor do I even pretend to be. This
        # try/except statement is a pretty ugly hack to get around
        # a RunTime error that Tkinter throws due to threading

        # threshold up and low din hsv
        lower = {'blue': (110, 100, 100), 'red': (-10, 100, 100), 'green': (40, 70, 70),
                 'yellow': (20, 100, 117)}  # assign new item lower['blue'] = (93, 10, 0)
        upper = {'blue': (130, 255, 255), 'red': (10, 255, 255), 'green': (70, 255, 255),  'yellow': (40, 255, 255)}

        # database session
        con = sq.connect('data_buku.db')  # dB browser for sqlite needed
        con.text_factory = str
        self.c = con.cursor()  # SQLite command, to connect to db so 'execute' method can be called

        try:
            # keep looping over frames until we are instructed to stop
            while not self.stopEvent.is_set():
                # grab the frame from the video stream and resize it to
                # have a maximum width of 300 pixels
                self.frame = self.vs.read()
                self.frame = imutils.resize(self.frame, width=300)

                # OpenCV represents images in BGR order; however PIL
                # represents images in RGB order, so we need to swap
                # the channels, then convert to PIL and ImageTk format
                blurred = cv2.GaussianBlur(self.frame, (11, 11), 0)
                image = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

                #make a call for ShapeDetector class
                sd = ShapeDetector()

                # for each color in dictionary check object in frame
                for self.key, value in upper.items():
                    # construct a mask for the color from dictionary`1, then perform
                    # a series of dilations and erosions to remove any small
                    # blobs left in the mask
                    kernel = np.ones((9, 9), np.uint8)
                    mask = cv2.inRange(image, lower[self.key], upper[self.key])
                    mask = cv2.erode(mask, None, iterations=2)
                    mask = cv2.dilate(mask, None, iterations=2)

                    # find contours in the mask and initialize the current
                    # (x, y, w, h) center of the rectangle
                    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                            cv2.CHAIN_APPROX_SIMPLE)[-2]
                    # cnts = cnts[0] if imutils.is_cv2() else cnts[1]
                    center = None

                    # only proceed if at least one contour was found
                    if len(cnts) > 0:
                        # find the largest contour in the mask, then use
                        # it to compute the minimum enclosing circle and
                        # centroid
                        c = max(cnts, key=cv2.contourArea)
                        (x, y, w, h) = cv2.boundingRect(c)
                        M = cv2.moments(c)
                        if (M["m00"] == 0):
                            M["m00"] = 1
                        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

                        if (x+y+w+h) >400:
                            #Do when reach the minimum contours length
                            self.shape = sd.detect(c)
                            cv2.putText(image, self.key, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
                            # c = c.astype("float")
                            c = c.astype("int")
                            cv2.drawContours(image, [c], -1, (0, 0, 0), 2)
                            cv2.putText(image, self.shape, (x + 15, y + 15), cv2.FONT_HERSHEY_SIMPLEX,
                                    0.5, (0, 0, 0), 2)
                            self.txt = self.key + " " + self.shape

                            #Gets data from database
                            plus = 'FROM buku INNER JOIN kode_buku ON buku.id = kode_buku.id WHERE kode_buku.kode = "' + self.txt + '"'
                            self.c.execute('SELECT jenis_buku ' + plus)

                            data = self.c.fetchall()  # Gets the data from the table

                            # Inserts record row by row in label
                            for row in data:
                                self.jb_text.set(row)

                            self.c.execute(
                                'SELECT buku.kode ' + plus)

                            data2 = self.c.fetchall()

                            for row in data2:
                                self.k_text.set(row)

                            self.c.execute(
                                'SELECT nama_pengarang ' + plus)

                            data3 = self.c.fetchall()

                            for row in data3:
                                self.n_text.set(row)

                            self.c.execute(
                                'SELECT penerbit ' + plus)

                            data4 = self.c.fetchall()

                            for row in data4:
                                self.p_text.set(row)

                            self.c.execute(
                                'SELECT kota ' + plus)

                            data5 = self.c.fetchall()

                            for row in data5:
                                self.ko_text.set(row)

                            self.c.execute(
                                'SELECT tahun ' + plus)

                            data6 = self.c.fetchall()

                            for row in data6:
                                self.t_text.set(row)

                            self.c.execute("SELECT 'Tersedia ' || koleksi || ' koleksi dari total ' || total || ' koleksi' " + plus)
                            data7 = self.c.fetchall()

                            for row in data7:
                                self.kol_text.set(row)

                            con.commit()
                            self.stopEvent.set()

                #Show image in GUI
                image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                image = Image.fromarray(image)
                image = ImageTk.PhotoImage(image)

                # if the panel is not None, we need to initialize it
                if self.panel is None:
                    self.panel = tki.Label(image=image)
                    self.panel.image = image
                    self.panel.pack(side="left", padx=10, pady=10)

                # otherwise, simply update the panel
                else:
                    self.panel.configure(image=image)
                    self.panel.image = image

        except RuntimeError:
            print("[INFO] caught a RuntimeError")

    def takeSnapshot(self):
        #Stop the Thread
        self.stopEvent.set()

    def resume(self):
        #Resume the Thread
        self.stopEvent = threading.Event()
        self.thread = threading.Thread(target=self.videoLoop, args=())
        self.thread.start()

    def onClose(self):
        # set the stop event, cleanup the camera, and allow the rest of
        # the quit process to continue
        print("[INFO] closing...")
        self.stopEvent.set()
        self.vs.stop()
        self.root.quit()

    def pluskoleksi(self):
        # database session
        con = sq.connect('data_buku.db')  # dB browser for sqlite needed
        con.text_factory = int
        c = con.cursor()  # SQLite command, to connect to db so 'execute' method can be called
        b = con.cursor()
        d = con.cursor()

        kode = self.k_text.get()
        kode = kode.translate({ord(i): None for i in "('),"})

        plus = 'FROM buku WHERE kode = "' + kode + '"'
        c.execute('SELECT buku.id ' + plus)

        b.execute('SELECT koleksi ' + plus)

        d.execute('SELECT total ' + plus)

        data1 = c.fetchall()
        data1 = data1[0][0]

        data2 = b.fetchall()
        data2 = data2[0][0]

        data2 = int(data2)
        data3 = d.fetchall()
        data3 = data3[0][0]

        data3 = int(data3)
        if data2 < data3:
            w = 1 + data2
            c.execute(
                    'UPDATE buku SET koleksi = ' + str(w) + ' WHERE buku.id = ' + str(data1))
            print("done")
        else:
            print("Maaf, koleksi buku sudah lengkap")

        con.commit()

    def inputkode(self):
        con = sq.connect('data_buku.db')  # dB browser for sqlite needed
        c = con.cursor()  # SQLite command, to connect to db so 'execute' method can be called

        self.kodetext = self.kin_text.get()

        plus1 = 'FROM buku WHERE kode = "' + self.kodetext + '"'
        c.execute('SELECT jenis_buku ' + plus1)

        data = c.fetchall()  # Gets the data from the table

        # Inserts record row by row in label
        for row in data:
            self.jb_text.set(row)

        c.execute(
            'SELECT buku.kode ' + plus1)

        data2 = c.fetchall()

        for row in data2:
            self.k_text.set(row)

        c.execute(
            'SELECT nama_pengarang ' + plus1)

        data3 = c.fetchall()

        for row in data3:
            self.n_text.set(row)

        c.execute(
            'SELECT penerbit ' + plus1)

        data4 = c.fetchall()

        for row in data4:
            self.p_text.set(row)

        c.execute(
            'SELECT kota ' + plus1)

        data5 = c.fetchall()

        for row in data5:
            self.ko_text.set(row)

        c.execute(
            'SELECT tahun ' + plus1)

        data6 = c.fetchall()

        for row in data6:
            self.t_text.set(row)

        c.execute(
            "SELECT 'Tersedia ' || koleksi || ' koleksi dari total ' || total || ' koleksi' " + plus1)
        data7 = c.fetchall()

        for row in data7:
            self.kol_text.set(row)

        con.commit()
        self.stopEvent.set()

    def minkoleksi(self):
        # database session
        con = sq.connect('data_buku.db')  # dB browser for sqlite needed
        con.text_factory = int
        c = con.cursor()  # SQLite command, to connect to db so 'execute' method can be called
        b = con.cursor()
        d = con.cursor()

        kode = self.k_text.get()
        kode = kode.translate({ord(i): None for i in "('),"})

        plus = 'FROM buku WHERE kode = "' + kode + '"'
        c.execute('SELECT buku.id ' + plus)

        b.execute('SELECT koleksi ' + plus)

        d.execute('SELECT total ' + plus)

        data1 = c.fetchall()
        data1 = data1[0][0]

        data2 = b.fetchall()
        data2 = data2[0][0]

        data3 = d.fetchall()
        data3 = data3[0][0]

        data3 = int(data3)
        data2 = int(data2)
        if data2 > 0:
            w = data2 - 1
            c.execute(
                    'UPDATE buku SET koleksi = ' + str(w) + ' WHERE buku.id = ' + str(data1))
            print("done")
            con.commit()
        else:
            print("Maaf, koleksi telah kosong")


import datetime
from twilio.rest import TwilioRestClient
from data import *
import sqlite3

account_sid = "" # Your Account SID from www.twilio.com/console
auth_token  = ""  # Your Auth Token from www.twilio.com/console

client = TwilioRestClient(account_sid, auth_token)

def sendMessage(body , to) :
    message = client.messages.create(body=body,
        to= to, # Replace with your phone number
        from_="+14133845487") # Replace with your Twilio number
    print(message.sid)

def sendBaby(chat_id):
    conn = sqlite3.connect('example.db')
    c = conn.cursor()

    c.execute("SELECT * FROM subs WHERE chatid = ?" , [chat_id])
    temp  = c.fetchall()[0]
    babyweek = temp[5]
    mobile_no  = temp[1]
    for i in babydata :
        if i >= babyweek :
            write_baby( i, babyweek , mobile_no)
    sendMessage("You have registered for New Born Baby Vaccination Schedule." , '+91' + str(mobile_no))

def write_baby(week , babyweek , mobile_no):
    d = datetime.date.today()
    diff = week - babyweek
    t =datetime.timedelta(days=7*diff)
    a = t+d
    result_date = str(a.day) + '/' + str(a.month) + '/' + str(a.year)
    file = open('messages.csv' , 'a')
    file.write(result_date + ',' + str(mobile_no) + ',' + babydata[week] + '\n')
    file.close()

def sendPreg(chat_id):
    conn = sqlite3.connect('example.db')
    c = conn.cursor()

    c.execute("SELECT * FROM subs WHERE chatid = ?" , [chat_id])
    temp  = c.fetchall()[0]
    pregweek = temp[3]
    mobile_no  = temp[1]
    for i in pregdata :
        if i >= pregweek :
            write_preg( i, pregweek , mobile_no)
    sendMessage("You have registered for Pregnancy Checkup Schedule." , '+91' + str(mobile_no))

def write_preg(week , pregweek , mobile_no):
    d = datetime.date.today()
    diff = week - pregweek
    t =datetime.timedelta(days=7*diff)
    a = t+d
    result_date = str(a.day) + '/' + str(a.month) + '/' + str(a.year)
    file = open('messages.csv' , 'a')
    file.write(result_date + ',' + str(mobile_no) + ',' + pregdata[week] + '\n')
    file.close()

def write_monthly(chat_id) :
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    c.execute("SELECT * FROM subs WHERE chatid = ?" , [chat_id])
    temp  = c.fetchall()[0]
    mobile_no  = temp[1]
    d = datetime.date.today()
    for i in range(1,13):
        t = datetime.timedelta(days=30*i)
        a = t+d
        result_date = str(a.day) + '/' + str(a.month) + '/' + str(a.year)
        file = open('messages.csv' , 'a')
        file.write(result_date + ',' + str(mobile_no) + ',' + "Reminder For Due Monthly Checkup By MEDIBOT" + '\n')
        file.close()
    sendMessage("You have registered for Monthly Regular Checkup Schedule." , '+91' + str(mobile_no))


# -*- coding: utf-8 -*-
# index_page.models

from google.appengine.ext import db

class FeedBack(db.Model):
    question = db.TextProperty(u'Ваш вопрос, отзыв или пожелание')
    email = db.EmailProperty(u'Ваш email')
    telephone = db.StringProperty(
        u'или Ваш телефон (не забудьте указать код города)')


#!/usr/bin/python3.6
from flask import Flask, request, render_template, render_template_string
import requests

app = Flask(__name__)

def lfi_search(ip,port,param):
	file = open('lfi.txt','r')
	res = []
	for x in file:
		payload = str('http://'+ip+':'+port+'?'+param+'='+x).strip('\n')
		r = requests.get(payload)
		res.append(r.text)
	return(res)

@app.route("/")
def index():
	return render_template_string('Hello World!')

@app.route("/gun", methods=['GET', 'POST'])
def lfi():
	if request.method == 'POST':
		ip = str(request.form['ip'])
		port = str(request.form['port'])
		param = str(request.form['param'])
		result = lfi_search(ip,port,param)
		return render_template('gun.html', ip=ip,port=port, param=param,result=result)
	else:
		return render_template('gun.html')

@app.route("/hehehe")
def hehehe():
	return render_template_string('lalka')

if __name__ == '__main__':
	app.run(host='0.0.0.0', port=8123,debug=True)