# simple circlespell - works with keyboard input
# up arrow = select   ::  down arrow = rotate
#
# last edit: 4/26
################CHANGES############
# addition of global variables
# canvas text more legible
# cleaned up code a bit
# made txtBox the window focus
# blinking cursor
##########TODO##############
# tcp/ip socket
# simple language model based on letter frequency
# need to determine max_r2
# window resizable?
# window on top?
# undo if wrong circle is selected
# addition of phrases: menu of topics, add to first circle, how to layout phrases?
# diving bell and butterfly
# change window name
######################BUGS#######################
#
##############CURRENTLY WORKING ON##########
# window focus: see line 309
# trying to position root window in center of screen

from Tkinter import *
from math import *
from socket import *
from tkFont import *
import time

def draw_circle(x, y, r, width, tag):
	global canvas
	canvas.create_oval(x-r, y-r, x+r, y+r, width=width, tags=tag)

def draw_interface(x, y, r1, max_r2):
	#print "in draw interface()"

	global canvas, highlighted, circle_list, txtBox

	num_circles = len(circle_list)
	#print "num_circles in draw_interface =",num_circles
	angle       = ((2 * pi) / num_circles)

	if num_circles > 1:
		r2          = min(r1 * sin(angle/2), max_r2)
	else:
		r2			= r1

	#print "in draw_interface circle_list:",circle_list

	# draw each circle
	for i, circle in enumerate(circle_list):
		#print "in for loop"
		#print "circle%i" %i, " contains:",circle

		#name each circle
		tag = "circ%s" %i

		if i == highlighted:
			width    = 3
		else:
			width    = 1

		if num_circles > 1:
			x_offset =  r1 * sin( angle * i)
			y_offset = -r1 * cos( angle * i)
		else:
			x_offset = 0
			y_offset = 0

		draw_circle(x+x_offset, y+y_offset, r2, width, tag)

		#print "1st interface drawn:", tag, "width=",canvas.itemcget(tag,"width")
		#print "circle:",circle," width:",width

		num_letters = len(circle)

		#print "num_letters:",num_letters

		small_angle = ((2 * pi) / num_letters)

		#draw stuff in circle
		for j, letter in enumerate(circle):
			if num_letters > 1:		#space objects around circle
				letter_x_offset = 0.75 *  r2 * sin( small_angle * j)
				letter_y_offset = 0.75 * -r2 * cos( small_angle * j)
			else:	#center object
				letter_x_offset = 0
				letter_y_offset = 0

			canvas.create_text(x+x_offset+letter_x_offset, y+y_offset+letter_y_offset, text=letter, font="Courier 16 bold")

	canvas.update()		#process all events in event queue

def update(decision):
			#print "in update()"
			update_circs(decision,x,y,r1,max_r2)
			#print "after update_circs call: highlighted=",highlighted
			return

def update_circs(decision,x,y,r1,max_r2):
				#print "in update_circs()"
				global canvas, highlighted, circle_list, txtBox

				select = 1
				rotate = 0

				#print "decision =",decision
				#print "begin update_circs: highlighted:",highlighted

				if decision == select:
					#print "decision == select"
					circle_list = circle_list[highlighted]
					num_circles = len(circle_list)

					#clear screen
					canvas.delete('all')

					if num_circles == 1:   #single option left, must be user's choice
						#print "num_circles == 1"
						output(circle_list)
						circle_list = []
						canvas.delete('all') #clear canvas

					#print "circle_list before layout():", circle_list
					#print "in update() circle_list b4 get_layou() call:",circle_list

					get_layout()	#arrange items in circles and determine next default highlighing

					#print "in update() circle_list after layout():", circle_list

					draw_interface(x,y,r1,max_r2)

				else:	#decision = rotate
					#print "decision = rotate"
					item = "circ%s" %highlighted
					canvas.itemconfigure(item,width=1)

					#print item,": width=",canvas.itemcget(item,"width")

					highlighted = (highlighted + 1) % len(circle_list)
					item = "circ%s" %highlighted
					canvas.itemconfigure(item,width=3)

					#print item,": width=",canvas.itemcget(item,"width")

				canvas.update()		#process all events in event queue

def output(item):
	global canvas, txtBox

	#print "in output():"

	if item[0] == "SPC":
		txtBox.insert(INSERT," ")
	elif item[0] == "DEL":
		txtBox.delete("%s-1c" % INSERT,INSERT)
	else:
		txtBox.insert(INSERT,item[0])

	#print "2rd cursor pos:", txtBox.index(INSERT)

def get_layout():
			#print "in get_layout()"

			global highlighted, circle_list

			#use huffman to determine
			#highlighted = huffman()
			highlighted = 0
			num_circles = 5

			#default screen
			num_items = len(circle_list)		#number objects to be distributed among circles
			if num_items == 0:
				#circle_list = ['DEL','SPC']
				circle_list = map(chr,range(97,123))
				circle_list.insert(0,'DEL')
				circle_list.insert(0,'SPC')
				num_items = len(circle_list)

				#print "circle_list in get_layout", circle_list

			if num_items < num_circles:
				num_circles = num_items

			max_circle_len = int(ceil(num_items / num_circles))			#max number items in each new  circle

			#print "max_circle_len in get_layout", max_circle_len
			#print "num_items after if in get_layout",num_items
			#print "circle_list in get_layout after if", circle_list

			new_circles = []
			index = 0

			#distribute objects in circles
			while len(new_circles) < num_circles:
				if len(new_circles) == (num_circles - 1):	#we're in last circle
					new_circles.append(circle_list[index:num_items])
				else:
					new_circles.append(circle_list[index:index+max_circle_len])
					index = index + max_circle_len

				#print "circle_list[index:index+max_circle_len]",circle_list[index:index+max_circle_len]
				#print "new_circles before if",new_circles
				#print "index =",index
				#print "index+max_circle_len",index+max_circle_len
				#print "j =",j

			circle_list = new_circles

def test_interface():
	time.sleep(2)	#just to see initial interface
	#print "in test_interface()"
	numtries = 10
	for i in range(1,numtries):
		#print "user input #",i
		#print "in test_interface: highlighted=",highlighted
		update(1)
		time.sleep(2)

def getKeyIn():
	#print "in getKeyIn()"
	#print event.keysym
	#decision = highlighted

	global canvas

	#print "in getKeyIn, highlighted=",highlighted

	def keyCtrl(event):
		#print "in keyCtrl()"
		#return "break"

		global circle_list, highlighted, txtBox

		decision = 2

		#print "key pressed:",event.keysym

		if event.keysym == 'Up':
			#print "key up"
			decision = 1	#select
		if event.keysym == 'Down':
			#print "key down"
			decision = 0	#rotate

		#print "before update call"

		if decision < 2:
			update(decision)

		#print "after upddte call"
		#print "in keyCtrl highlighted=", highlighted

		return "break"

	#print "before bind call"

	canvas.bind_all('<Key>',keyCtrl)

	#canv.bind_all('<Key-u>',keyCtrl)

	#print "end of getKeyIn"

root = Tk()
s = 50
x = 200
y = 200
r1 = 110 #radius of center circle
max_r2 = 80

canvas = Canvas(root,height=400,width=400,bg='yellow')
canvas.grid(row=2,column=1)
#canvas.focus_set()

txtBox = Text(root,width=50,height=1,padx=5,pady=5,insertofftime=250,takefocus=1)
txtBox.grid(row=1,column=1)
txtBox.focus()
#txtBox.insert(INSERT,"hello")

highlighted = 0		#default highlited circle
circle_list = []
get_layout()
draw_interface(x,y,r1,max_r2)

#testing
#test_interface(highlighted,circle_list,txtBox)

#grab keyboard input
getKeyIn()

root.mainloop()


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

# In[52]:

import matplotlib.pyplot as plt
import sklearn.datasets as skdata
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.decomposition import PCA
from sklearn.metrics import f1_score

# In[72]:

numeros = skdata.load_digits()

imagenes = numeros['images']

target = numeros['target']
n_imagenes = len(target)
target[target!=1]=0

# para poder correr PCA debemos "aplanar las imagenes"
data = imagenes.reshape((n_imagenes, -1)) # para volver a tener los datos como imagen basta hacer data.reshape((n_imagenes, 8, 8))
print(np.shape(data))

# Vamos a hacer un split training test
scaler = StandardScaler()
x_train, x_test, y_train, y_test = train_test_split(data, target, train_size=0.5)

x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)

#numero = 1
#dd = y_train==numero
#nn = y_train!=numero

cov = np.cov(x_train.T)
valores, vectores = np.linalg.eig(cov)
valores = np.real(valores)
vectores = np.real(vectores)
ii = np.argsort(-valores)
valores = valores[ii]
vectores = vectores[:,ii]

clf = LinearDiscriminantAnalysis()

y_prediccion = []
f_1_score = []

y_prediccion_test = []
f_1_score_test = []
number_components = []

y_pred = 0
f_1 = 0

for i in range(3,40):

    clf.fit(x_train[:,:i], y_train)

    y_pred = clf.predict(x_train[:,:i])
    y_pred_test = clf.predict(x_test[:,:i])

    f_1 = f1_score(y_train, y_pred)

    f_1_test = f1_score(y_test, y_pred_test)

    y_prediccion.append(y_pred)
    f_1_score.append(f_1)

    y_prediccion_test.append(y_pred_test)
    f_1_score_test.append(f_1_test)

    number_components.append(i)

y_prediccion_o = []
f_1_score_o = []

y_prediccion_test_o = []
f_1_score_test_o = []
number_components_o = []

for i in range(3,40):

    clf.fit(x_train[:,:i], y_train)

    y_pred = clf.predict(x_train[:,:i])
    y_pred_test = clf.predict(x_test[:,:i])

    f_1 = f1_score(y_train, y_pred, pos_label = 0)

    f_1_test = f1_score(y_test, y_pred_test, pos_label = 0)

    y_prediccion_o.append(y_pred)
    f_1_score_o.append(f_1)

    y_prediccion_test_o.append(y_pred_test)
    f_1_score_test_o.append(f_1_test)

    number_components_o.append(i)

plt.figure()
plt.subplot(1,2,1)
plt.scatter(number_components,f_1_score)
plt.scatter(number_components,f_1_score_test)
plt.ylabel("f_1")
plt.xlabel("number")

plt.subplot(1,2,2)
plt.scatter(number_components_o,f_1_score_o)
plt.scatter(number_components_o,f_1_score_test_o)
plt.ylabel("f_1")
plt.xlabel("number")

plt.tight_layout()

plt.savefig("F1_score_LinearDiscriminantAnalysis.png")


import win32api, time

print("die screensaver!")
dif = 1
exc = False

while True:
    try:
        pos = win32api.GetCursorPos()
        time.sleep(30)
        curPos = win32api.GetCursorPos()
        if pos == curPos:
            newPos = (curPos[0], curPos[1] + dif)
            print("Let's move to %s from %s" % (newPos, pos))
            dif *= -1
            win32api.SetCursorPos(newPos)
    except():
        if not exc:
            print("Something bad happened.. But never mind")
            exc = True


from sklearn.base import TransformerMixin, BaseEstimator

class GenreOHE(BaseEstimator, TransformerMixin):

    def __init__(self, column_name='genre'):
        self.column_name=column_name
        self.list_unique_genre = None

    def fit(self, X, y=None):
        # separate all genres into one list, considering comma + space as separators
        genre = X[self.column_name].str.split(', ').tolist()

        # flatten the list
        flat_genre = [item for sublist in genre for item in sublist]

        # convert to a set to make unique
        set_genre = set(flat_genre)

        # back to list
        self.list_unique_genre = list(set_genre)

        return self

    def transform(self, X):
        # create columns by each unique genre
        data = X.reindex(X.columns.tolist() + self.list_unique_genre,
                         axis=1,
                         fill_value=0)

        # for each value inside column, update the dummy
        for index, row in data.iterrows():
            for val in row[self.column_name].split(', '):
                if val != 'NA':
                    data.loc[index, val] = 1

        data = data.drop(self.column_name, axis=1)
        return data


import pandas as pd # importing pandas
import plotly.express as px # importing plotly.express for visualizing the dataset
import streamlit as st # importing streamlit which is used for web apps

# Streamlit supports a wide range of characters including emojis
st.set_page_config(page_title = "Titanic Dashboard", page_icon = "ðŸš¢", layout = "wide")

# Streamlit cache decorator so that we do not have to read the csv file again and again
@st.cache
def read_data():
    df = pd.read_csv("train.csv")

    df['Sex'].replace({
        "male" : "Male",
        "female" : "Female"
    }, inplace = True)

    df['Embarked'].replace({
        "S" : "Southampton",
        "C" : "Cherbourg",
        "Q" : "Queenstown"
    }, inplace = True)

    return df

df = read_data()

# A sidebar to for all the filters.
st.sidebar.header("Apply Filters ")

embarked = st.sidebar.multiselect(
    "Embarked ",
    options = df["Embarked"].unique(),
    default = df["Embarked"].unique(),
)

pclass = st.sidebar.multiselect(
    "Passenger Class ",
    options = df["Pclass"].unique(),
    default = df["Pclass"].unique(),
)

sex = st.sidebar.multiselect(
    "Sex:  ",
    options = df["Sex"].unique(),
    default = df["Sex"].unique(),
)

# Using the query method with all the three filters that we have in our dataset.
df_selection = df.query(
    "Embarked == @embarked & Pclass == @pclass & Sex == @sex"
)

st.title("ðŸš¢ Titanic Dashboard") # Title of our web app

st.markdown("##") # Used to separate paragraphs

# df_selection is used because it queries only from those attributes that are checked in the filters
total_deaths = df_selection['Survived'].sum()
median_age = df_selection['Age'].median() # 50 percent of people above/below this age abroad
total_survival = len(df_selection['Survived']) - total_deaths

# Plotting three graphs horizontally.
left_column, middle_column, right_column = st.columns(3)

with left_column:
    st.subheader("Total Deaths ðŸ’€")
    st.subheader(f" {total_deaths}")
with middle_column:
    st.subheader("Median Age Aboard ðŸ‘¦")
    st.subheader(f" {median_age}")
with right_column:
    st.subheader("Total Survivals ðŸ‘«")
    st.subheader(f" {total_survival}")

st.markdown("---") # Used to separate paragraphs

box_plot = px.box(df_selection,
    y = "Age",
    x = "Pclass",
    title = "Age and Passengers' Class"
)

# Using update_layout method to give the manual xlabels and ylabels
box_plot.update_layout(
    xaxis_title_text = "Class",
    yaxis_title_text = "Age",
)

# use_container_width is made True so that it does not occupy the whole space
left_column.plotly_chart(box_plot, use_container_width = True)

pie_chart = px.pie(names = df_selection["Embarked"].unique(),
    values = df_selection.groupby("Embarked")["Embarked"].count(),
    hole = 0.5,
    title="Embarked"
)

middle_column.plotly_chart(pie_chart, use_container_width = True)

group_plot = px.histogram(df_selection,
    x = "Survived",
    color = "Sex",
    barmode = 'group',
    title="Survival by Sex"
)

# Using update_layout method to give the manual xlabels and ylabels
group_plot.update_layout(
    xaxis_title_text = "Survived",
    yaxis_title_text = "Frequency"
)

right_column.plotly_chart(group_plot,use_container_width = True)

# df_selection is used because it queries only from those attributes that are checked in the filters
age_by_survival = (
    df_selection.groupby(by=["Age"]).sum()[["Survived"]].sort_values(by="Survived")
)

fig_age_survival = px.bar(
    age_by_survival,
    x = "Survived",
    y = age_by_survival.index,
    orientation = "h",
    title="Survival by Age",
    color_discrete_sequence = ["#0083B8"] * len(age_by_survival),
    template = "plotly_white",
)

# Using update_layout method to give the manual xlabels and ylabels
fig_age_survival.update_layout(
    plot_bgcolor = "rgb(0, 0, 26)",
    xaxis = (dict(showgrid=False))
)

# use_container_width is made True so that it does not occupy the whole space
left_column.plotly_chart(fig_age_survival, use_container_width = True)

pie_chart = px.pie(names = ["Survived", "Dead"],
    values = df.groupby("Survived")["Survived"].count(),
    hole = 0.5,
    title="Dead and Survived",
    labels = ["Survived", "Dead"],
)

middle_column.plotly_chart(pie_chart, use_container_width = True)

plot = px.histogram(df_selection,
    x = "Pclass",
    color = "Sex",
    barmode = 'group',
    title = "Siblings Aboard",
)

plot.update_layout(
    xaxis_title_text = "Passenger Class",
    yaxis_title_text = "Frequency",
)

right_column.plotly_chart(plot, use_container_width = True);

line_plot = px.line(df_selection,
    x = "Fare",
    y = ["Fare_Tax", "Food Charges", "Luggage Charges"], # Plotting multiple lines for one x
    title = "Different Fares",
)

# Using update_layout method to give the manual xlabels and ylabels
line_plot.update_layout(
    yaxis_title_text = "Amount",
)

st.plotly_chart(line_plot, use_container_width = True)


from maltego_trx.maltego import MaltegoMsg, MaltegoTransform, UIM_INFORM
from maltego_trx.transform import DiscoverableTransform
from modules.IOCparser.extensions import iocparser_registry as registry
from modules.IOCparser.extensions import iocparser_set as IoCparser

from ..utils import iocapi

@registry.register_transform(display_name="To Domains on Website [IoC-Parser]", input_entity="maltego.URL",
                             description='Retrieves domain IOCs from Website',
                             output_entities=["maltego.domain"],
                             transform_set=IoCparser)
class WebsiteToIoCsDomain(DiscoverableTransform):
    @classmethod
    def create_entities(cls,request: MaltegoMsg, response: MaltegoTransform):
        website = request.Value
        iocs = iocapi.getIOC(website)
        if iocs:
            for key in iocs['data']:
                    for domain in iocs['data']['DOMAIN']:
                        response.addEntity("maltego.Domain", domain)
        else:
            response.addUIMessage("No indicator found on Website", UIM_INFORM)


from pyspark.sql import SparkSession
from pyspark.sql import functions as F

class DataFrameProcessor:
    def __init__(self):
        self.spark = SparkSession.builder.appName("Data Frame Processor").getOrCreate()
        self.dataFrame = self.spark.read.csv('./SampleCSV.csv', inferSchema=True, header=True)

    def rowFilter(self, columnName, value):
        filteredRows = self.dataFrame.filter(self.dataFrame[columnName] == value)

        return filteredRows

    def columnFilter(self, columnName):
        filteredColumn = self.dataFrame.select(columnName)

        return filteredColumn

    def columnMean(self, columnName):
        columnMean = self.dataFrame.agg(F.mean(columnName)).collect()[0][0]
        return columnMean

processor = DataFrameProcessor()
filteredRow = processor.rowFilter('Name', 'John Doe')
filteredRow.show()
filteredColumn = processor.columnFilter('Department')
filteredColumn.show()
averageSalary = processor.columnMean('Salary')
print(averageSalary)


"""
纯手动暴力搜索的方式
"""
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 1. 加载数据
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=0)

# 手动暴力
best_score = 0
for gamma in [0.01, 0.1, 1]:
    for c in [0.1, 1, 10, 100]:
        svm = SVC(C=c, gamma=gamma)
        svm.fit(X_train, y_train)
        score = svm.score(X_test, y_test)

        if score > best_score:
            best_score = score
            best_parameters = {"C":c, "gamma":gamma}

print(f"best parameters = {best_parameters}")
print(f"best score = {best_score}")


"""
Google Code Jam
2016 Round 1B

Problem C.
    :author: yamaton
    :date: 2016-04-30
"""

import itertools as it
import functools
import operator
import collections
import math
import sys

def duplicates(words):
    res = collections.defaultdict(set)
    for i, w in enumerate(words):
        res[w].add(i)
    return [group for group in res.values() if len(group) > 1]

def solve(xss):
    people = list(range(len(xss)))
    list_groups = [duplicates(ys) for ys in zip(*xss)]
    pp(list_groups)

    candidates = [p for p in people if all(any(p in g for g in gs) for gs in list_groups)]
    pp('candidates', candidates)

    if len(candidates) <= 1:
        return len(candidates)

    pss = [{p: next(i for (i, g) in enumerate(gs) if p in g) for p in candidates}
           for gs in list_groups]

    pp('pss', pss)

    n = min(map(len, pss))
    while n > 1:
        for subset in it.combinations(candidates, n):
            pos = [[d[p] for p in subset] for d in pss]
            if all(len(set(s)) == len(s) for s in pos):
                pp('ppl', subset)
                return n
        n -= 1
    return n

def pp(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def main():
    for _tc in range(1, int(input())+1):
        pp('\n--------- case #%d -------' % _tc)
        print("Case #%d: " % _tc, end='')
        n = int(input())
        xss = [input().strip().split() for _ in range(n)]
        result = solve(xss)
        pp()
        pp('input =', xss)
        pp('result =', result)
        print(result)

if __name__ == '__main__':
    main()


from django.db import models

class Category(models.Model):
    name = models.CharField('название категории', max_length=50)
    icon = models\
        .ImageField("иконка",upload_to='media/categories')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "категория"
        verbose_name_plural = "категории"

class Level(models.Model):
    name = models.CharField('название уровня', max_length=50)
    code = models.CharField('код уровня', max_length=2)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "уровень"
        verbose_name_plural = "уровни"

class Theme(models.Model):
    name = models.CharField('название темы', max_length=50)
    photo = models.ImageField('фото',upload_to='media/themes')
    category = models\
        .ForeignKey(Category, on_delete=models.CASCADE,
                    verbose_name='категория')
    level = models.ForeignKey(Level, on_delete=models.CASCADE,
                              verbose_name='уровень')
    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "тема"
        verbose_name_plural = "темы"

class Word(models.Model):
    name = models.CharField('слово', max_length=50)
    translation = models.CharField('перевод', max_length=50)
    transcription = models.CharField('транскрипция', max_length=50)
    example = models.TextField('пример', max_length=200)
    theme = models.ForeignKey(Theme, on_delete=models.CASCADE,
                              verbose_name='тема')
    sound = models.FileField('звук', upload_to='media/sounds')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "слово"
        verbose_name_plural = "слова"


# EXERCISE - WATCH COCO
# Ask user's name and age
# If user's name start with ('a' or 'A') and age is above 10 then
# Print 'you can watch coco movei'
# Else print 'sorry, you cannot watch coco'

user_name = input("enter your name: ")
user_age = int(input("enter your age: "))
# if user_age >= 10 and (user_name[0] == 'a' or user_name[0] == 'A'):
if user_name[0].lower() == 'a' and user_age >= 10:
    print("you can watch coco movei")
else:
    print("sorry, you cannot watch coco")


#!/bin/env python3

import sys
import argparse
import logging
import pprint
from collections import OrderedDict
from tplib.library import Library
from tplib.expressions import compile_bool, compile_str

# ordered dict

def cli_parser():
    parser = argparse.ArgumentParser(
        description='Query and print information about testcases and/or requirements in the testcase library.',
        epilog="""
Examples:

 * Show content of all testcases in specified directory

  * ``./query.py -t tests/scenarios/removed_testcase/new/``

 * Show content of testcases with priority greater than 8

  * ``./query.py -t tests/scenarios/removed_testcase/old/ 'tc.priority>8'``

 * Print names and filenames of all testcases

  * ``./query.py -t tests/scenarios/removed_testcase/old/ True 'tc.name, tc.filename'``

 * Get names of installer testcases which verify requirement X and are not disabled, manual and have specified priority

  * ``./query.py -tb ~/git/testplans/ '"installer" in tc.tags and "disabled" not in tc.tags and tc.priority < 9 and tc.execution.type != "manual" and "requirement X name" in tc.verifiesRequirement|map(attribute="name")' 'tc.name'``
""",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument(
        'directory',
        help="Directory where requirements and testcases are located.",
    )
    parser.add_argument(
        'query',
        nargs='?',
        default="True",
        help="Jinja expression used for filterling. Use 'i' variable for the item reference. Also 'tc' in case of testcase and 'req' in case of requirement are available.",
    )
    parser.add_argument(
        'print_query',
        nargs='?',
        help="Result of Jinja query to be printed for the queried items."
    )
    selector = parser.add_mutually_exclusive_group()
    selector.add_argument(
        '-r', '--requirements-only',
        action="store_true",
        help="Show requirements only.",
    )
    selector.add_argument(
        '-t', '--testcases-only',
        action="store_true",
        help="Show testcases only.",
    )
    selector.add_argument(
        '-p', '--testplans_only',
        action="store_true",
        help="Show testplans only.",
    )
    parser.add_argument(
        '-b', '--brief',
        action="store_true",
        help="Show only list of items without details.",
    )
    verbosity = parser.add_mutually_exclusive_group()
    verbosity.add_argument(
        '-d', '--debug',
        action="store_true",
        help="Turn on debugging in tplib.",
    )
    verbosity.add_argument(
        '-q', '--quiet',
        action="store_true",
        help="Run logging in quiet mode: show tplib errors and failures only.",
    )
    return parser

def main():
    in_args=sys.argv[1:]
    args = cli_parser().parse_args(in_args)
    loglevel = logging.INFO
    logformat = "%(levelname)-8s: %(message)s"
    if args.debug:
        loglevel = logging.DEBUG
        logformat = "%(name)s(%(levelname)s): %(message)s"
    elif args.quiet:
        loglevel = logging.ERROR
    logging.basicConfig(
        level=loglevel,
        format=logformat,
    )
    library = Library(args.directory)
    eval_bool_query = compile_bool(args.query)
    if args.print_query is not None:
        eval_str_format = compile_str(args.print_query)
        def print_func(**kwargs):
            print(eval_str_format(**kwargs))
    elif args.brief:
        def print_func(i, **kwargs):
            print(repr(i))
    else:
        def print_func(i, **kwargs):
            print(i.dump())

    if not args.testcases_only and not args.testplans_only:
        for _, requirement in sorted(library.requirements.items()):
            if eval_bool_query(i=requirement, req=requirement):
                print_func(i=requirement, req=requirement)
    if not args.requirements_only and not args.testplans_only:
        for _, testcase in sorted(library.testcases.items()):
            if eval_bool_query(i=testcase, tc=testcase):
                print_func(i=testcase, tc=testcase)
    if not args.requirements_only and not args.testcases_only:
        for _, testplan in sorted(library.testplans.items()):
            if eval_bool_query(i=testplan, tp=testplan):
                print_func(i=testplan, tp=testplan)


from collections import defaultdict

#read in text file and separate by spaces
#data will be an array
with open('message_01.txt',"r") as myfile:
    data = myfile.read().split(" ")

#initialize defaultdict and count the number of times each word appears
d = defaultdict(int)
for i in data:
    d[i] += 1

#print the words and their counts
for k,v in d.items():
    print(f'{k}{v}',end='')


from django.shortcuts import render,  redirect
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from django.conf import settings
from django.contrib import messages
from .forms import UserRegisterForm

def register(request):
	if request.method == 'POST':
		form = UserRegisterForm(request.POST)
		if form.is_valid():
			user = form.save()
			group = Group.objects.get(pk=settings.PUBLIC_GROUP_ID)
			user.groups.add(group)
			username = form.cleaned_data.get('username')
			messages.success(request, f'Welcome {username} Your account has been created! Please login Now')

			return redirect('login')
	else:
		form = UserRegisterForm()
	return render(request, 'users/register.html', {'form': form})

def login_success(request):
	usergroup = None
	if request.user.is_authenticated:
		usergroup = request.user.groups.values_list('id', flat=True).last()
	if usergroup == settings.MINISTRY_GROUP_ID:
		return redirect('strack-home')
	elif usergroup == settings.DEO_GROUP_ID:
		return redirect('deo-page')
	elif usergroup == settings.TEACHER_GROUP_ID:
		return redirect('teacher-page')
	elif usergroup == settings.SCHOOL_GROUP_ID:
		return redirect('school-page')
	else:
		return redirect('website-home')


import random
flag = True
while flag:
    num = input('Enter number for an upper bound:')
    if num.isdigit():
        print('Let play')
        num=int(num)
        flag = False
    else:
        print('Try again type a number')
randnum = random.randint(1,num)
guess = None
count = 1
while guess != randnum:
    guess = (input('Enter number between 1 and '+ str(num)+': '))
    if guess.isdigit():
        guess = int(guess)
    count += 1
print('Succeed')
print('You guess count is ',count)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import gzip
import os
import sys
import time

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
import sklearn
import input_data
from matplotlib import pyplot as plt

# TODO
# These are some useful constants that you can use in your code.
# Feel free to ignore them or change them.
# TODO
IMAGE_SIZE = 32
NUM_LABELS = 10
SEED = 66478  # Set to None for random seed.
BATCH_SIZE = 64
NUM_EPOCHS = 10
EVAL_BATCH_SIZE = 1024
EVAL_FREQUENCY = 100  # Number of steps between evaluations.
# This is where the data gets stored
#TRAIN_DIR = 'data'
# HINT:
# if you are working on the computers in the pool and do not want
# to download all the data you can use the pre-loaded data like this:
TRAIN_DIR = '/home/mllect/data/rgbd'

def data_type():
  """Return the type of the activations, weights, and placeholder variables."""
  return tf.float32

def error_rate(predictions, labels):
  """Return the error rate based on dense predictions and sparse labels."""
  return 100.0 - (100.0 * numpy.sum(numpy.argmax(predictions, 1) == labels) / predictions.shape[0])

def fake_data(num_images, channels):
  """Generate a fake dataset that matches the dimensions of rgbd_10 dataset."""
  data = numpy.ndarray(
      shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, channels),
      dtype=numpy.float32)
  labels = numpy.zeros(shape=(num_images,), dtype=numpy.int64)
  for image in xrange(num_images):
    label = image % 2
    data[image, :, :, 0] = label - 0.5
    labels[image] = label
  return data, labels

#classic way, stride of 1 and padding makes it preserve the size of the image
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1,seed = SEED)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def main(argv=None):  # pylint: disable=unused-argument
  if FLAGS.self_test:
    print('Running self-test.')
    NUM_CHANNELS = 1
    train_data, train_labels = fake_data(256, NUM_CHANNELS)
    validation_data, validation_labels = fake_data(EVAL_BATCH_SIZE, NUM_CHANNELS)
    test_data, test_labels = fake_data(EVAL_BATCH_SIZE, NUM_CHANNELS)
    num_epochs = 1
  else:
    if (FLAGS.use_rgbd):
      NUM_CHANNELS = 4
      print('****** RGBD_10 dataset ******')
      print('* Input: RGB-D              *')
      print('* Channels: 4               *')
      print('*****************************')
    else:
      NUM_CHANNELS = 3
      print('****** RGBD_10 dataset ******')
      print('* Input: RGB                *')
      print('* Channels: 3               *')
      print('*****************************')
    # Load input data
    data_sets = input_data.read_data_sets(TRAIN_DIR, FLAGS.use_rgbd)
    num_epochs = NUM_EPOCHS

    train_data = data_sets.train.images  # (27999, 32, 32, 3)
    train_labels= data_sets.train.labels

    test_data = data_sets.test.images #(6321, 32, 32, 3)
    test_labels = data_sets.test.labels

    validation_data = data_sets.validation.images #(5413, 32, 32, 3)
    validation_labels = data_sets.validation.labels

  train_size = train_labels.shape[0]

  train_data_node = tf.placeholder(data_type(), shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))
  train_labels_node = tf.placeholder(tf.int64, shape=(BATCH_SIZE,))
  eval_data = tf.placeholder(data_type(), shape=(EVAL_BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))
  keep_prob = tf.placeholder(tf.float32)

  #Get the predictions of data
  def eval_in_batches(data, sess):
    """Get all predictions for a dataset by running it in small batches."""
    size = data.shape[0]
    if size < EVAL_BATCH_SIZE:
      raise ValueError("batch size for evals larger than dataset: %d" % size)
    predictions = numpy.ndarray(shape=(size, NUM_LABELS), dtype=numpy.float32)
    for begin in xrange(0, size, EVAL_BATCH_SIZE):
      end = begin + EVAL_BATCH_SIZE
      if end <= size:
        predictions[begin:end, :] = sess.run(eval_prediction,feed_dict={eval_data: data[begin:end, ...],keep_prob:1})
      else:
        batch_predictions = sess.run(eval_prediction,feed_dict={eval_data: data[-EVAL_BATCH_SIZE:, ...],keep_prob:1})
        predictions[begin:, :] = batch_predictions[begin - size:, :]
    return predictions

  #Define the weights

  W_conv11 = weight_variable([3, 3, NUM_CHANNELS, 32])
  b_conv11 = bias_variable([32])
  W_conv12 = weight_variable([3, 3, 32, 32])
  b_conv12 = bias_variable([32])

  W_conv21 = weight_variable([3, 3, 32, 64])
  b_conv21 = bias_variable([64])
  W_conv22 = weight_variable([3, 3, 64, 64])
  b_conv22 = bias_variable([64])

  W_conv31 = weight_variable([3, 3, 64, 128])
  b_conv31 = bias_variable([128])
  W_conv32 = weight_variable([3, 3, 128, 128])
  b_conv32 = bias_variable([128])

  W_fc = weight_variable([4 * 4 * 128, 256])
  b_fc = bias_variable([256])

  W_out = weight_variable([256, NUM_LABELS])
  b_out = bias_variable([NUM_LABELS])

  #Define the architecture
  def conv_nn(x,keep_prob):
    ######First layer ########
    h_conv11 = conv2d(x, W_conv11) + b_conv11
    h_relu11 = tf.nn.relu(h_conv11)
    h_conv12 = conv2d(h_relu11, W_conv12) + b_conv12
    h_relu12 = tf.nn.relu(h_conv12)
    h_pool11 = max_pool_2x2(h_relu12)

    ##### Second layer #######
    h_conv21 = conv2d(h_pool11, W_conv21) + b_conv21
    h_relu21 = tf.nn.relu(h_conv21)
    h_conv22 = conv2d(h_relu21, W_conv22) + b_conv22
    h_relu22 = tf.nn.relu(h_conv22)
    h_pool21 = max_pool_2x2(h_relu22)

    ##### Third layer #######
    h_conv31 = conv2d(h_pool21, W_conv31) + b_conv31
    h_relu31 = tf.nn.relu(h_conv31)
    h_conv32 = conv2d(h_relu31, W_conv32) + b_conv32
    h_relu32 = tf.nn.relu(h_conv32)
    h_pool31 = max_pool_2x2(h_relu32)

    ###### Fully connected layer ####
    h_pool31_flat = tf.reshape(h_pool31, [-1, 4*4*128])
    h_fc = tf.nn.relu(tf.matmul(h_pool31_flat, W_fc) + b_fc)

    #dropout keep_prob = 0.5 in case of training and 1 otherwise
    h_fc = tf.nn.dropout(h_fc, keep_prob)

    ###### Output layer #########
    logits = tf.matmul(h_fc, W_out) + b_out
    return logits

  #Feed the inputs to the cnn
  logits = conv_nn(train_data_node,keep_prob)
  eval_logits = conv_nn(eval_data,keep_prob)

  #Get the predictions
  train_pred = tf.nn.softmax(logits)
  eval_prediction = tf.nn.softmax(eval_logits)

  # Compute the loss of the model
  loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits,train_labels_node))

  #Regularization
  regularize = tf.nn.l2_loss(W_fc) + tf.nn.l2_loss(b_fc) + tf.nn.l2_loss(W_out) + tf.nn.l2_loss(b_out)
  loss+= 0.01*regularize

  #define an optimizer
  optimizer = tf.train.AdamOptimizer(1e-4).minimize(loss)

  #Train
  with tf.Session() as sess:
      sess.run(tf.initialize_all_variables())
      val_list = []
      train_list = []
      for epoch in range(NUM_EPOCHS):
          epoch_loss = 0
          epoch_train_error = 0
          for b in range(int(train_size/BATCH_SIZE)):  # There will be some data left out at the end !! fix it
              #getting the right batch for training
              batch_begin = b*BATCH_SIZE
              batch_end = batch_begin + BATCH_SIZE
              x_train_batch = train_data[batch_begin:batch_end]
              y_train_batch = train_labels[batch_begin:batch_end]

              #get the loss and optimize
              _,l =sess.run([optimizer,loss],feed_dict={train_data_node:x_train_batch, train_labels_node:y_train_batch,keep_prob:0.5})
              pred = sess.run(train_pred,feed_dict={train_data_node:x_train_batch, keep_prob:1})
              epoch_loss+=l
              train_error = error_rate(pred, y_train_batch)
              epoch_train_error+= train_error
              if((b%EVAL_FREQUENCY) == 0):
                  #Validatiion error should be on the whole validation data
                  val_pred = eval_in_batches(validation_data,sess)
                  val_error = error_rate(val_pred, validation_labels)
                  val_list.append(val_error)
                  train_list.append(train_error)
                  print('Epoch: %d, step: %d, loss: %.2f, train error: %.2f %%, validation error: %.2f %%' %
                        (epoch+1,b,l,train_error,val_error))
          epoch_train_error = epoch_train_error/(b+1)
          print('Epoch %d completed out of %d, epoch_loss: %.2f, epoch_train_error: %.2f %%' %
                (epoch+1,NUM_EPOCHS,epoch_loss,epoch_train_error))

      test_pred = eval_in_batches(test_data,sess)
      test_error = error_rate(test_pred,test_labels)
      print('Test error: %.2f %%' % test_error)
      print('Confusion matrix:')
    #  NOTE: the following will require scikit-learn
      print(confusion_matrix(test_labels, numpy.argmax(eval_in_batches(test_data, sess), 1)))
      plt.axis([0, 60, 0, 100])
      plt.xlabel("steps")
      plt.ylabel("Error(%)")
      plt.plot(val_list,label = 'Validation error')
      plt.plot(train_list, label = 'Training error')
      plt.title("Training vs Validation error")
      plt.legend()
      plt.show()

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--use_rgbd',
      default=False,
      help='Use rgb-d input data (4 channels).',
      action='store_true'
  )
  parser.add_argument(
      '--self_test',
      default=False,
      action='store_true',
      help='True if running a self test.'
  )
  FLAGS = parser.parse_args()

  tf.app.run()


class Config:
    def __init__(self):
        self.lr = 2e-4
        self.device = 'cuda:0'
        self.checkpoint_dir = 'checkpoints/mnist_v3'
        self.log_freq = 50
        self.save_freq = 1000
        # self.load_path = 'checkpoints/mnist_v3/weights/latest.pth'
        self.load_path = ''
        self.batch_size = 128
        self.filters = 128
        self.n_epoch = 500
        self.diffusion_steps = 1000

    def __str__(self):
        stringa = ''
        for k, v in self.__dict__.items():
            stringa += f'{k}={v}' + '\n'
        return stringa

opt = Config()


from ..myutils import numUtils
import numpy as np

primes = numUtils.primesLessThanM[3:]

lastIdx = 1
maxPrime = 0
sum = np.sum(primes[0:lastIdx])
while sum < 10**6:
    sum += primes[lastIdx]
    if sum in primes:
        maxPrime = sum
        print(maxPrime, primes[lastIdx], lastIdx)
    lastIdx += 1


node = int(input())
temp = list(map(int, input().split()))

# 시작과 끝 노드
start = temp[0]
end = temp[1]

num = int(input())

graph = []
visit = []

for i in range(node+1):
    graph.append([])
    visit.append(0)

# 그래프에 노드 삽입
for i in range(num):
    temp = list(map(int, input().split()))
    graph[temp[0]].append(temp[1])
    graph[temp[1]].append(temp[0])

# 정렬
for i in range(node):
    graph[i].sort()

# bfs
def bfs(graph, visit, start):
    queue = list()
    queue.append(start)
    while queue:
        tmp = queue.pop(0)
        # pop한것이 tmp가 0일 경우
        for i in graph[tmp]:
            if(visit[i] == 0):
                visit[i] = visit[tmp]+1
                queue.append(i)

bfs(graph, visit, start)

if visit[end] != 0:
    print(visit[end])
else:
    print("-1")


import os
import math
import json
import logging
import torch
import torch.optim as optim
from utils.util import ensure_dir

class BaseTrainer:
    """
    Base class for all trainers
    """
    def __init__(self, model, loss, metrics, finetune, resume, config, train_logger=None):
        self.config = config
        self.logger = logging.getLogger(self.__class__.__name__)
        self.model = model
        self.loss = loss
        self.metrics = metrics
        self.name = config['name']
        self.epochs = config['trainer']['epochs']
        self.save_freq = config['trainer']['save_freq']
        self.verbosity = config['trainer']['verbosity']

        # 设置设备
        if torch.cuda.is_available():
            if config['cuda']:
                self.with_cuda = True
                self.gpus = {i: item for i, item in enumerate(self.config['gpus'])}
                device = 'cuda'
                if torch.cuda.device_count() > 1 and len(self.gpus) > 1:
                    self.model = torch.nn.DataParallel(self.model)
                torch.cuda.empty_cache()
            else:
                self.with_cuda = False
                device = 'cpu'
        else:
            self.logger.warning('Warning: There\'s no CUDA support on this machine, '
                                'training is performed on CPU.')
            self.with_cuda = False
            device = 'cpu'

        self.device = torch.device(device)
        self.model.to(self.device).half()

        self.logger.debug('Model is initialized.')
        self._log_memory_usage() # 将当前显存占用加入到log中

        self.train_logger = train_logger

        # 由config中的字符来指定使用nn.optim中的哪个优化器
        self.optimizer = getattr(optim, config['optimizer_type'])(model.parameters(), **config['optimizer'])

        # 由config中的字符来指定使用nn.optim.lr_scheduler中的哪个学习率管理器
        self.lr_scheduler = getattr(optim.lr_scheduler, config['lr_scheduler_type'], None)
        if self.lr_scheduler:
            self.lr_scheduler = self.lr_scheduler(self.optimizer, **config['lr_scheduler'])
            self.lr_scheduler_freq = config['lr_scheduler_freq']

        self.monitor = config['trainer']['monitor']
        self.monitor_mode = config['trainer']['monitor_mode']
        assert self.monitor_mode == 'min' or self.monitor_mode == 'max'
        self.monitor_best = math.inf if self.monitor_mode == 'min' else -math.inf
        self.start_epoch = 1
        self.checkpoint_dir = os.path.join(config['trainer']['save_dir'], self.name)
        ensure_dir(self.checkpoint_dir)
        json.dump(config, open(os.path.join(self.checkpoint_dir, 'config.json'), 'w'),
                  indent=4, sort_keys=False)

        if resume: # resume就载入整个ckpt，继续训练
            self._resume_checkpoint(resume)

        if finetune and not resume: # finetune就不载入ckpt中的模型参数外的数据
            self._restore_checkpoint(finetune)

    def train(self):
        """
        Full training logic
        """
        for epoch in range(self.start_epoch, self.epochs + 1):
            try:
                result = self._train_epoch(epoch) # 训练一个epoch，返回log
            except torch.cuda.CudaError:
                self._log_memory_usage()

            log = {'epoch': epoch}
            for key, value in result.items():
                if key == 'metrics':
                    for i, metric in enumerate(self.metrics): # precision, recall, hmean
                        log[metric.__name__] = result['metrics'][i]
                elif key == 'val_metrics':
                    for i, metric in enumerate(self.metrics): # val_precision, val_recall, val_hmean
                        log['val_' + metric.__name__] = result['val_metrics'][i]
                else:
                    log[key] = value # loss...
            if self.train_logger is not None:
                self.train_logger.add_entry(log)
                if self.verbosity >= 1:
                    for key, value in log.items():
                        self.logger.info('    {:15s}: {}'.format(str(key), value))
            if (self.monitor_mode == 'min' and log[self.monitor] < self.monitor_best)\
                    or (self.monitor_mode == 'max' and log[self.monitor] > self.monitor_best):
                self.monitor_best = log[self.monitor]
                self._save_checkpoint(epoch, log, save_best=True) # 如果当前epoch得到最好结果，则保存为model_best.pth.tar
            if epoch % self.save_freq == 0: # 每间隔一定epoch保存一次模型参数
                self._save_checkpoint(epoch, log)
            if self.lr_scheduler and epoch % self.lr_scheduler_freq == 0: # 每间隔一定epoch更新一次lr_scheduler状态
                self.lr_scheduler.step(epoch) # 学习率管理器将学习率调整到epoch处的学习率
                lr = self.lr_scheduler.get_lr()[0]
                self.logger.info('New Learning Rate: {:.8f}'.format(lr)) # 显示当前学习率

    def _log_memory_usage(self):
        '''
        Record the cuda memory usage to log
        '''
        if not self.with_cuda:
            return

        template = """Memory Usage: \n{}"""
        usage = []
        for deviceID, device in self.gpus.items():
            deviceID = int(deviceID)
            allocated = torch.cuda.memory_allocated(deviceID) / (1024 * 1024)
            cached = torch.cuda.memory_cached(deviceID) / (1024 * 1024)

            usage.append('    CUDA: {}  Allocated: {} MB Cached: {} MB \n'.format(device, allocated, cached))

        content = ''.join(usage)
        content = template.format(content)

        self.logger.debug(content)

    def _train_epoch(self, epoch):
        """
        Training logic for an epoch

        :param epoch: Current epoch number
        """
        raise NotImplementedError

    def _save_checkpoint(self, epoch, log, save_best=False):
        """
        Saving checkpoints

        :param epoch: current epoch number
        :param log: logging information of the epoch
        :param save_best: if True, rename the saved checkpoint to 'model_best.pth.tar'
        """
        arch = type(self.model).__name__
        state = {
            'arch': arch,
            'epoch': epoch,
            'logger': self.train_logger,
            'state_dict': self.model.state_dict(),
            'optimizer': self.optimizer.state_dict(),
            'monitor_best': self.monitor_best,
            'config': self.config
        }
        filename = os.path.join(self.checkpoint_dir, 'checkpoint-epoch{:03d}-loss-{:.4f}.pth.tar'
                                .format(epoch, log['loss']))
        torch.save(state, filename)
        if save_best:
            os.rename(filename, os.path.join(self.checkpoint_dir, 'model_best.pth.tar'))
            self.logger.info("Saving current best: {} ...".format('model_best.pth.tar'))
        else:
            self.logger.info("Saving checkpoint: {} ...".format(filename))

    def _resume_checkpoint(self, resume_path):
        """
        Resume from saved checkpoints

        :param resume_path: Checkpoint path to be resumed
        """
        self.logger.info("Loading checkpoint: {} ...".format(resume_path))
        checkpoint = torch.load(resume_path)
        self.start_epoch = checkpoint['epoch'] + 1
        self.monitor_best = checkpoint['monitor_best']
        self.model.load_state_dict(checkpoint['state_dict'])
        self.optimizer.load_state_dict(checkpoint['optimizer'])
        # 将参数全部放入GPU
        if self.with_cuda:
            for state in self.optimizer.state.values():
                for k, v in state.items():
                    if isinstance(v, torch.Tensor):
                        state[k] = v.cuda(self.device)
        self.train_logger = checkpoint['logger']
        self.config = checkpoint['config']
        self.logger.info("Checkpoint '{}' (epoch {}) loaded".format(resume_path, self.start_epoch))

    def _restore_checkpoint(self, checkpoint_path):
        """
        just load parameter of pretrained model

        :param checkpoint_path: Checkpoint path to be resumed
        """
        self.logger.info("Loading checkpoint: {} ...".format(checkpoint_path))
        checkpoint = torch.load(checkpoint_path)
        pretrained_dict = checkpoint['state_dict'] # 预训练模型的state_dict
        model_dict = self.model.state_dict() # 当前用来训练的模型的state_dict

        if pretrained_dict.keys() != model_dict.keys(): # 需要进行参数的适配
            print('Parameters are inconsistant, adapting model parameters ...')
            # 在合并前(update),需要去除pretrained_dict一些不需要的参数
            # 只含有识别分支的预训练模型参数字典中键'0', '1'对应全模型参数字典中键'2', '3'
            pretrained_dict['2'] = transfer_state_dict(pretrained_dict['0'], model_dict['2'])
            pretrained_dict['3'] = transfer_state_dict(pretrained_dict['1'], model_dict['3'])
            del pretrained_dict['0'] # 把原本预训练模型中的键值对删掉，以免错误地更新当前模型中的键值对
            del pretrained_dict['1']
            model_dict.update(pretrained_dict)  # 更新(合并)模型的参数
            self.model.load_state_dict(model_dict)
        else:
            print('Parameters are consistant, load state dict directly ...')
            self.model.load_state_dict(checkpoint['state_dict'])
            # self.optimizer.load_state_dict(checkpoint['optimizer'])
            # if self.with_cuda:
            #     for state in self.optimizer.state.values():
            #         for k, v in state.items():
            #             if isinstance(v, torch.Tensor):
            #                 state[k] = v.cuda(self.device)

def transfer_state_dict(pretrained_dict, model_dict):
    '''
    根据model_dict,去除pretrained_dict一些不需要的参数,以便迁移到新的网络
    url: https://blog.csdn.net/qq_34914551/article/details/87871134
    :param pretrained_dict: 预训练模型的state_dict
    :param model_dict: 当前模型的state_dict
    :return: 预训练模型中包含的当前模型的state_dict
    '''
    # state_dict2 = {k: v for k, v in save_model.items() if k in model_dict.keys()}
    state_dict = {}
    for k, v in pretrained_dict.items():
        if k in model_dict.keys():
            # state_dict.setdefault(k, v)
            state_dict[k] = v
        else: # 预训练模型多出来的，但是本模型没有
            print("Missing key(s) in state_dict :{}".format(k))
    return state_dict


from playwright.sync_api import sync_playwright
from utils.custom_utils import comuni_catania, typology_map, swap_dict
import numpy as np
from bs4 import BeautifulSoup
import logging
import pandas as pd
from tqdm import tqdm
import re
from urllib.parse import urlparse
from scrapers.bots.Scraper import House
from scrapers.bots.Subito import SubitoHouses
from math import ceil

def test(page):
    page.goto("https://www.subito.it/ville-singole-e-a-schiera/b-b-cod-a3-514-catania-372307732.htm")
    if page.is_visible("span:has-text('€')"):
        price = page.locator("span:has-text('€')").first.inner_text()
        print(price)

def open_context(browser, trace):
    context = browser.new_context(ignore_https_errors=True)
    if trace:
        context.tracing.start(screenshots=True, snapshots=True)
    context.set_default_timeout(60*1000)
    return context

def main(typology: str, municipality: list, trace: bool, headless: bool):
    logger = logging.getLogger("main_logger")

    if municipality==[]:
        municipality = comuni_catania
    municipality = [c.replace('\'', '-').replace(' ', '-').lower() for c in municipality]

    with sync_playwright() as spw:
        browser = spw.chromium.launch(headless=headless)
        context = open_context(browser, trace)

        page = context.new_page()

        house_links = {}
        for m in municipality:
            for t in typology:
                house_links[m] = {swap_dict(typology_map['subito'])[t]: []}
                try:
                    page.goto(f"https://www.subito.it/annunci-sicilia/vendita/{t}/catania/{m}")
                    navs_txt = ' '.join(page.locator("nav").all_inner_texts())
                    max_page = max([int(n) for n in re.findall(r"(\d+)", navs_txt)])
                except:
                    max_page = 1

                for page_n in range(1, max_page+1):
                    page.goto(f"https://www.subito.it/annunci-sicilia/vendita/{t}/catania/{m}/?o={page_n}",
                                wait_until='domcontentloaded', timeout=30*1000)
                    houses_html = page.locator('.items').first.inner_html()
                    soup = BeautifulSoup(houses_html, 'html.parser')
                    house_links[m][swap_dict(typology_map['subito'])[t]].extend([l['href'] for l in soup.find_all('a', href=True)
                                        if urlparse(l['href']).path.startswith('/'+t)])
            print(house_links.keys())
        page.close()
        context.close()

        houses = []
        for m in house_links.keys():
            for t in house_links[m].keys():
                hl_stacks = np.array_split(house_links[m][t], ceil(len(house_links[m][t])/250))
                for hl_stack in hl_stacks:
                    context = open_context(browser, trace)
                    for link in tqdm(hl_stack, total=len(hl_stack)):
                        page = context.new_page()
                        page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())

                        page.goto(link, wait_until='domcontentloaded')
                        title = page.locator('h1').first.inner_text()
                        surface = page.locator("text=/\d+ mq/").first.inner_text()
                        description = page.locator('p:below(:text("Descrizione"))').first.inner_text()
                        index = int(re.findall(r"(\d+)", page.url)[-1])
                        house = House(index, 'subito', link, t, m, title, surface, description)

                        if page.is_visible("span:has-text('€')"):
                            price = page.locator("span:has-text('€')").first.inner_text()
                            house.price = price
                        else:
                            house.price = ''

                        if page.is_visible('span:right-of(:text("Piano"))'):
                            ait = ' '.join(page.locator('span:right-of(:text("Piano"))').all_inner_texts())
                            house.floor = re.findall(r"\d{1}", ait)[0]
                        else:
                            house.floor = ''

                        if page.is_visible('span:right-of(:text("Locali"))'):
                            ait = ' '.join(page.locator('span:right-of(:text("Locali"))').all_inner_texts())
                            house.rooms = re.findall(r"\d{1,2}", ait)[0]
                        else:
                            house.rooms = ''
                        houses.append(house)
                        page.close()
                    context.close()

        df = pd.DataFrame(houses)
        df.to_csv("house.csv", index=False)
        print(df)
        houses = SubitoHouses(df)
        houses.preprocess()
        houses.dump(pd.Timestamp.now().strftime("%Y-%m-%d"))


def numIslands(grid):
    num_col = len(grid[0])
    num_row = len(grid)
    count = 0
    visited = []
    for i in range(num_row):
        visited.append([False] * num_col)

    for col in range(num_col):
        for row in range(num_row):
            if not visited[row][col] and grid[row][col] == '1':
                BFS((row, col), grid, visited)
                count = count + 1
    return count

def BFS(vertex, grid, visited):
    queue = [vertex]

    while queue:
        row, col = queue.pop(0)
        if row - 1 >= 0 and grid[row - 1][col] == '1' and not visited[row - 1][col]:
            queue.append((row - 1, col))
            visited[row - 1][col] = True
        if row + 1 <= len(grid) - 1 and grid[row + 1][col] == '1' and (not visited[row + 1][col]):
            queue.append((row + 1, col))
            visited[row + 1][col] = True
        if col - 1 >= 0 and grid[row][col - 1] == '1' and not visited[row][col - 1]:
            queue.append((row, col - 1))
            visited[row][col - 1] = True
        if col + 1 <= len(grid[0]) - 1 and grid[row][col + 1] == '1' and not visited[row][col + 1]:
            queue.append((row, col + 1))
            visited[row][col + 1] = True

if __name__ == '__main__':
    grid = [["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"]]
    print('Reult', numIslands(grid))


import sys

sys.stdin = open("input.txt", "r")

T = int(input())

for t in range(1, T + 1):
    N, M = map(int, input().split())
    Ai = list(map(int, input().split()))
    Bj = list(map(int, input().split()))
    sum_num = 0
    max_num = 0

    if len(Ai) > len(Bj):
        for i in range(len(Ai)-len(Bj)+1):
            sum_num = 0
            for j in range(len(Bj)):
                sum_num += Ai[i + j] * Bj[j]
            if sum_num > max_num:
                max_num = sum_num

    if len(Ai) < len(Bj):
        for i in range(len(Bj)-len(Ai)+1):
            sum_num = 0
            for j in range(len(Ai)):
                sum_num += Ai[j] * Bj[i + j]
            if sum_num > max_num:
                max_num = sum_num

    print('#%d' %t, max_num)


class Shop(list):
    name = ''
    date = ''

    def __init__(self, clothes):
        self.name = clothes[0]
        self.date = clothes[1]
        self.extend(clothes[2:])

    def cheapest3(self):
        unique_clothes = set(self)

        sorted_unique_clothes = sorted(unique_clothes)
        return sorted_unique_clothes[0:3]

    def add_price(self, the_price):
        self.append(the_price)

with open('clothes.txt',  encoding="utf-8") as clothes:
    data = clothes.readline()
    clothes = data.strip().split(',')
    shop = Shop(clothes)
    print(shop.cheapest3())

    shop.add_price('12')
    print(shop.cheapest3())


# -*- coding: utf-8 -*-
""" This script is used to optimize the parameters which are inferred from
non-dividing traces under the EM algorithm.
Update : Script deprecated since no parameter except the coupling is optimized
using EM. """
""""""""""""""""""""" MODULE IMPORT """""""""""""""""""""
### Import external modules
import pickle
import numpy as np
import sys
import copy
import matplotlib
import os
matplotlib.use('Agg') #to run the script on a distant server
import matplotlib.pyplot as plt

sys.path.insert(0, os.path.realpath('..'))
sys.path.insert(0, os.path.realpath('../Classes'))
sys.path.insert(0, os.path.realpath('../Functions'))

### Import internal modules
from Classes.LoadData import LoadData
from Classes.HMM_SemiCoupled import HMM_SemiCoupled
from Classes.PlotResults import PlotResults
import Classes.EM as EM

###Import internal functions
from Functions.signal_model import signal_model
from Functions.create_hidden_variables import create_hidden_variables
from Functions.display_parameters import display_parameters_from_file
from Functions.clean_waveform import clean_waveform

#access main directory
os.chdir('..')
""""""""""""""""""""" LOAD SHELL ARGUMENTS """""""""""""""""
try:
    nb_iter = int(sys.argv[1])
    nb_traces = int(sys.argv[2])
    size_block = int(sys.argv[3])
    cell = sys.argv[4]
    if sys.argv[5]=="None":
        temperature = None
    else:
        temperature = int(sys.argv[5])
except:
    print("No shell input given, default arguments used")
    nb_iter = 15
    nb_traces = 1000
    size_block = 100
    cell = 'NIH3T3'
    temperature = None

""""""""""""""""""""" LOAD INIT GUESS PARAMETERS """""""""""""""""
path = 'Parameters/Real/init_parameters_nodiv_'+str(temperature)+"_"+cell+".p"
with open(path, 'rb') as f:
    l_parameters = [dt, sigma_em_circadian, W, pi,
    N_theta, std_theta, period_theta, l_boundaries_theta, w_theta,
    N_phi, std_phi, period_phi, l_boundaries_phi, w_phi,
    N_amplitude_theta, mu_amplitude_theta, std_amplitude_theta,
    gamma_amplitude_theta, l_boundaries_amplitude_theta,
    N_background_theta, mu_background_theta, std_background_theta,
    gamma_background_theta, l_boundaries_background_theta,
    F] = pickle.load(f)

""""""""""""""""""""" DISPLAY PARAMETERS """""""""""""""""
display_parameters_from_file(path, show = False)

""""""""""""""""""""" CREATE HIDDEN VARIABLES """""""""""""""""
theta_var_coupled, amplitude_var, background_var \
                        = create_hidden_variables(l_parameters = l_parameters )
""""""""""""""""""""" LOAD DATA """""""""""""""""
if cell == 'NIH3T3':
    path =  "Data/NIH3T3.ALL.2017-04-04/ALL_TRACES_INFORMATION.p"
    dataClass=LoadData(path, nb_traces, temperature = temperature,
                        division = False)
else:
    path = "Data/U2OS-2017-03-20/ALL_TRACES_INFORMATION_march_2017.p"
    dataClass=LoadData(path, nb_traces, temperature = temperature,
                        division = True) #all thz U2OS divide

(ll_area_tot_flat, ll_signal_tot_flat, ll_nan_circadian_factor_tot_flat,
    ll_obs_phi_tot_flat, T_theta, T_phi) = dataClass.load()
print(len(ll_signal_tot_flat), " traces kept")

""""""""""""""""""""" CREATE BLOCK OF TRACES """""""""""""""""
ll_area_tot = []
ll_signal_tot = []
first= True
#print(ll_area_tot_flat)
#print(ll_signal_tot_flat)

for index, (l_area, l_signal) in enumerate(zip(ll_area_tot_flat,
                                                ll_signal_tot_flat)):
    if index%size_block==0:
        if not first:
            ll_area_tot.append(ll_area)
            ll_signal_tot.append(ll_signal)

        else:
            first = False
        ll_area = [l_area]
        ll_signal = [l_signal]
    else:
        ll_area.append(l_area)
        ll_signal.append(l_signal)
#get remaining trace
ll_area_tot.append(ll_area)
ll_signal_tot.append(ll_signal)

""""""""""""""""""""" OPTIMIZATION """""""""""""""""
lP=0
l_lP=[]
l_idx_to_remove = []
for it in range(nb_iter):
    print("Iteration :", it)
    l_jP_phase = []
    l_jP_amplitude = []
    l_jP_background = []
    l_gamma = []
    l_gamma_0 = []
    l_logP = []
    ll_signal_hmm = []

    """ CLEAN TRACES AFTER FIRST ITERATION """
    if it==1:
        ll_signal_tot_flat = ll_signal_hmm_clean
        print("nb traces apres 1ere iteration : ", len(ll_signal_tot_flat))
        ll_signal_tot = []
        first= True
        for index, l_signal in enumerate( ll_signal_tot_flat):
            if index%size_block==0:
                if not first:
                    ll_signal_tot.append(ll_signal)
                else:
                    first = False
                ll_signal = [l_signal]
            else:
                ll_signal.append(l_signal)
        #get remaining trace
        ll_signal_tot.append(ll_signal)

    for ll_signal in ll_signal_tot:

        """ INITIALIZE AND RUN HMM """
        l_var = [theta_var_coupled, amplitude_var, background_var]
        hmm=HMM_SemiCoupled(l_var, ll_signal, sigma_em_circadian,
                            ll_val_phi = [], waveform = W ,  pi = pi,
                            crop = False )
        (l_gamma_0_temp, l_gamma_temp ,l_logP_temp,  ll_alpha,  ll_beta, l_E,
            ll_cnorm, ll_idx_phi_hmm_temp, ll_signal_hmm_temp,
            ll_nan_circadian_factor_temp) = hmm.run_em()

        #create ll_mat_TR
        ll_mat_TR = [np.array([theta_var_coupled.TR_no_coupling \
                        for i in gamma_temp]) for gamma_temp in l_gamma_temp ]

        """ PLOT TRACE EXAMPLE """
        zp = zip(enumerate(ll_signal_hmm_temp),l_gamma_temp, l_logP_temp)
        for (idx, signal), gamma, logP in zp:
            plt_result = PlotResults(gamma, l_var, signal_model, signal,
                                    waveform = W, logP = None,
                                    temperature = temperature, cell = cell)
            plt_result.plotEverythingEsperance(False, idx)
            if idx==0:
                break

        l_jP_phase_temp, l_jP_amplitude_temp,l_jP_background_temp \
            = EM.compute_jP_by_block(ll_alpha, l_E, ll_beta, ll_mat_TR,
                                    amplitude_var.TR, background_var.TR,
                                    N_theta, N_amplitude_theta,
                                    N_background_theta)
        l_jP_phase.extend(l_jP_phase_temp)
        l_jP_amplitude.extend(l_jP_amplitude_temp)
        l_jP_background.extend(l_jP_background_temp)
        l_gamma.extend(l_gamma_temp)
        l_logP.extend(l_logP_temp)
        l_gamma_0.extend(l_gamma_0_temp)
        ll_signal_hmm.extend(ll_signal_hmm_temp)

    t_l_jP = (l_jP_phase, l_jP_amplitude,l_jP_background)

    """ REMOVE BAD TRACES IF FIRST ITERATION"""
    if it==0:
        Plim = np.percentile(l_logP, 10)
        #Plim = -10000
        for idx_trace, P in enumerate(l_logP):
            if P<=Plim:
                l_idx_to_remove.append(idx_trace)
        for index in sorted(l_idx_to_remove, reverse=True):
            del t_l_jP[0][index]
            del t_l_jP[1][index]
            del t_l_jP[2][index]
            del l_gamma[index]
            del l_logP[index]
            del l_gamma_0[index]
            del ll_signal_hmm[index]
        ll_signal_hmm_clean = copy.deepcopy(ll_signal_hmm)

    """ PARAMETERS UPDATE """
    ll_idx_obs_phi = None
    [F_up, pi_up, std_theta_up, sigma_em_circadian_up, ll_coef,
    std_amplitude_theta_up, std_background_theta_up, mu_amplitude_theta_up,
    mu_background_theta_up, W_up] = EM.run_EM(l_gamma_0, l_gamma, t_l_jP,
                                              theta_var_coupled, ll_idx_obs_phi,
                                              F, ll_signal_hmm,  amplitude_var,
                                              background_var, W,
                                              ll_idx_coef = None )

    if np.mean(l_logP)-lP<10**-9:
        print("diff:", np.mean(l_logP)-lP)
        print(print("average lopP:", np.mean(l_logP)))
        break
    else:
        lP = np.mean(l_logP)
        print("average lopP:", lP)
        l_lP.append(lP)

    """ PLOT WAVEFORM """
    plt.plot(theta_var_coupled.domain, W_up)
    plt.xlabel('Circadian phase')
    plt.ylabel(r'$W(\theta)$')
    plt.ylim([-0.1,1.5])
    plt.show()
    plt.close()

    """ CHOOSE NEW PARAMETERS """

    cond_F = False
    cond_pi = False
    cond_std_theta = False
    cond_sigma_em_circadian = False
    cond_std_amplitude_theta = False
    cond_std_background_theta = False
    cond_mu_amplitude_theta = False
    cond_mu_background_theta = False
    cond_W = False

    """ PUT ITERATION CONDITIONS ON THE UPDATE """
    [cond_it_F, cond_it_pi, cond_it_std_theta, cond_it_sigma_em_circadian,
    cond_it_std_amplitude_theta, cond_it_std_background_theta,
    cond_it_mu_amplitude_theta, cond_it_mu_background_theta, cond_it_W] \
                    = [False,False,False,False,False,False,False,False,False]

    '''
    if it>=0:   cond_it_F = True
    if it>=18:   cond_it_pi = True
    if it>=25:   cond_it_std_theta = True
    if it>=18:   cond_it_sigma_em_circadian = True
    if it>=10:   cond_it_std_amplitude_theta = True
    if it>=14:   cond_it_std_background_theta = True
    if it>=10:   cond_it_mu_amplitude_theta = True
    if it>=14:   cond_it_mu_background_theta = True
    if it>=0:   cond_it_W = True
    '''

    if it>=0:   cond_it_F = True
    if it>=0:   cond_it_pi = True
    if it>=0:   cond_it_std_theta = True
    if it>=0:   cond_it_sigma_em_circadian = True
    if it>=0:   cond_it_std_amplitude_theta = True
    if it>=0:   cond_it_std_background_theta = True
    if it>=0:   cond_it_mu_amplitude_theta = True
    if it>=0:   cond_it_mu_background_theta = True
    if it>=0:   cond_it_W = True

    """ REINPUT NEW PARAMETERS """
    if cond_F and cond_it_F:
        F = F_up
    if cond_pi and cond_it_pi:
        pi = pi_up
    #block simga_theta to 0.2 to keep good inference
    if cond_std_theta and cond_it_std_theta and std_theta_up<0.2:
        std_theta = std_theta_up
    #block sigma_e to 0.1 to prevent divergence
    if cond_sigma_em_circadian and cond_it_sigma_em_circadian \
                                                and sigma_em_circadian_up>0.:
        sigma_em_circadian = sigma_em_circadian_up
    if cond_std_amplitude_theta and cond_it_std_amplitude_theta:
        std_amplitude_theta = std_amplitude_theta_up
    if cond_std_background_theta and cond_it_std_background_theta:
        std_background_theta = std_background_theta_up
    if cond_mu_amplitude_theta and cond_it_mu_amplitude_theta:
        mu_amplitude_theta = mu_amplitude_theta_up
    if cond_mu_background_theta and cond_it_mu_background_theta:
        mu_background_theta = mu_background_theta_up
    if cond_W and cond_it_W:
        W = W_up

    #redefine boundaries OU process if first iterations
    if it<10:
        l_boundaries_amplitude_theta = (mu_amplitude_theta-5*std_amplitude_theta,
                                    mu_amplitude_theta+5*std_amplitude_theta)
    if it<14:
        l_boundaries_background_theta = (mu_background_theta\
                                    -5*std_background_theta,
                                    mu_background_theta+5*std_background_theta)

    l_parameters = [dt, sigma_em_circadian, W, pi,
    N_theta, std_theta, period_theta, l_boundaries_theta, w_theta,
    N_phi, std_phi, period_phi, l_boundaries_phi, w_phi,
    N_amplitude_theta, mu_amplitude_theta, std_amplitude_theta,
    gamma_amplitude_theta, l_boundaries_amplitude_theta,
    N_background_theta, mu_background_theta, std_background_theta,
     gamma_background_theta, l_boundaries_background_theta,
    F]

    theta_var_coupled, amplitude_var, background_var \
                        = create_hidden_variables(l_parameters = l_parameters)

plt.plot(l_lP)
plt.savefig("Parameters/Real/opt_parameters_nodiv_"+str(temperature)+"_"\
                                                                +cell+'.pdf')
#plt.show()
plt.close()

""""""""""""""""""""" RENORMALIZE WAVEFORM AND UPDATE PARAMETERS """""""""""""""
W = clean_waveform(W)

l_parameters = [dt, sigma_em_circadian, W, pi,
N_theta, std_theta, period_theta, l_boundaries_theta, w_theta,
N_phi, std_phi, period_phi, l_boundaries_phi, w_phi,
N_amplitude_theta, mu_amplitude_theta, std_amplitude_theta,
gamma_amplitude_theta, l_boundaries_amplitude_theta,
N_background_theta, mu_background_theta, std_background_theta,
gamma_background_theta, l_boundaries_background_theta,
F]

""""""""""""""""""""" WRAP PARAMETERS """""""""""""""""
path = "Parameters/Real/opt_parameters_nodiv_"+str(temperature)+"_"+cell+".p"
pickle.dump( l_parameters, open( path, "wb" ) )
""""""""""""""""""""" DISPLAY PARAMETERS """""""""""""""""
display_parameters_from_file(path, show = True)


import argparse
import contextlib
import os
import sys
import pkg_resources

from iiblib import iib_client, iib_authentication

def setup_iib_client(parsed_args):
    iib_auth = iib_authentication.IIBKrbAuth(
        parsed_args.iib_krb_principal,
        parsed_args.iib_server,
        ktfile=parsed_args.iib_krb_ktfile,
    )
    kwargs = {
        "auth": iib_auth,
    }
    if parsed_args.iib_insecure:
        kwargs["ssl_verify"] = False
    iibc = iib_client.IIBClient(parsed_args.iib_server, **kwargs)
    return iibc

def setup_arg_parser(args):
    parser = argparse.ArgumentParser()
    arg_groups = {}
    for aliases, arg_data in args.items():
        holder = parser
        if arg_data["group"]:
            arg_groups.setdefault(
                arg_data["group"], parser.add_argument_group(arg_data["group"])
            )
            holder = arg_groups[arg_data["group"]]
        action = arg_data.get("action")
        if not action and arg_data["type"] == bool:
            action = "store_true"
        kwargs = {
            "help": arg_data.get("help"),
            "required": arg_data.get("required", False),
            "default": arg_data.get("default"),
        }
        if action:
            kwargs["action"] = action
        else:
            kwargs["type"] = arg_data.get("type", "str")
            kwargs["nargs"] = arg_data.get("count")

        holder.add_argument(*aliases, **kwargs)

    return parser

@contextlib.contextmanager
def setup_entry_point_cli(entry_tuple, name, args, environ_vars):
    orig_argv = sys.argv[:]
    orig_environ = os.environ.copy()

    try:
        # First argv element is always the entry point name.
        # For a console_scripts entry point, this will be the same value
        # as if the script was invoked directly. For any other kind of entry point,
        # this value is probably meaningless.
        sys.argv = [name]
        sys.argv.extend(args)
        for key in environ_vars:
            os.environ[key] = environ_vars[key]
        entry_point_func = pkg_resources.load_entry_point(*entry_tuple)
        yield entry_point_func
    finally:
        sys.argv = orig_argv[:]
        os.environ.update(orig_environ)

        to_delete = [key for key in os.environ if key not in orig_environ]
        for key in to_delete:
            del os.environ[key]


answer1 = widget_inputs["radio1"]
answer2 = widget_inputs["radio2"]
answer3 = widget_inputs["radio3"]
answer4 = widget_inputs["radio4"]

is_correct = False

comments = []
def commentizer(new):
    if new not in comments:
        comments.append(new)

if answer1 == True:
    is_correct = True
else:
    is_correct = is_correct and False
    commentizer("Check the first one. Remember, vector images scale nicely and this logo seems simple enough to be vector.")

if answer4 == True:
    is_correct = is_correct and True
else:
    is_correct = is_correct and False
    commentizer("Check the second one. Will the image be reused? If so, an external file probably makes more sense.")

if is_correct:
    commentizer("Great job! You're getting better at thinking through your image options in different situations.")

grade_result["comment"] = "\n\n".join(comments)
grade_result["correct"] = is_correct


#source code: https://gist.github.com/keithweaver/61fd7cec7b161a4f500ac05d257c7b72
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)

MotorTopL = 16
MotorTopR = 17
MotorMidL = 18
MotorMidR = 19
MotorBotL = 20
MotorBotR = 21

GPIO.setup(MotorTopL,GPIO.OUT)
GPIO.setup(MotorTopR,GPIO.OUT)
GPIO.setup(MotorMidL,GPIO.OUT)
GPIO.setup(MotorMidR,GPIO.OUT)
GPIO.setup(MotorBotL,GPIO.OUT)
GPIO.setup(MotorBotR,GPIO.OUT)

i = 0
refresh = False
arr = [[0,1],[1,1],[0,0]]

while (i < 1000):
    if refresh == False:
        reset()
    else:
        emboss(arr)
        sleep(5)

    i += 1

#raise dots according to input arr
def emboss(arr):
    if arr[0][0] == 1:
        GPIO.output(MotorTopL,GPIO.HIGH)
    elif arr[0][1] == 1:
        GPIO.output(MotorTopR,GPIO.HIGH)
    elif arr[1][0] == 1:
        GPIO.output(MotorMidL,GPIO.HIGH)
    elif arr[1][1] == 1:
        GPIO.output(MotorMidR,GPIO.HIGH)
    elif arr[2][1] == 1:
        GPIO.output(MotorBotL,GPIO.HIGH)
    elif arr[2][2] == 1:
        GPIO.output(MotorBotR,GPIO.HIGH)

sleep(5)

#reset all dots
def reset():
    GPIO.output(MotorTopL,GPIO.LOW)
    GPIO.output(MotorTopR,GPIO.LOW)
    GPIO.output(MotorMidL,GPIO.LOW)
    GPIO.output(MotorMidR,GPIO.LOW)
    GPIO.output(MotorBotL,GPIO.LOW)
    GPIO.output(MotorBotR,GPIO.LOW)

GPIO.cleanup()


def reverse(x):
    MAX = 2**31 - 1
    MIN = -(2**31)

    if x > 0:
        sign = 1
    else:
        sign = -1
        x = -x

    output = 0
    while x > 0:
        last_digit = x % 10
        x = x // 10 # storing the remaining digit
        if output == (MAX //10) and last_digit >= MAX % 10:
            return 0
        if output > (MAX // 10):
            return 0
        output = output * 10 + last_digit
    return output * sign


import pgzrun

HEIGHT = 400
WIDTH = 600

item = Rect((300,200),(25,25))
ivy = 3

item2 = Rect((250,250),(25,25))
i2vy = 2

item3 = Rect((250,150),(25,25))
i3vy = 4

platform = Rect((10, 60), (25, 250))
platform1 = Rect((460, 60), (25, 250))

def item_motion_control(obj,plt,speed,plt1): #define new function
    obj.x += speed
    if obj.x > WIDTH:
        obj.x = 0
    if obj.x < 0:
        obj.x = 0

        speed = - speed

    if obj.colliderect(plt):
        speed = -speed

    if obj.colliderect(plt1):
        speed = -speed # apply reverse

    return speed

def platform_control():
    if keyboard.up:
        platform.y += 3
    if keyboard.up:
        platform1.y -= 3
    if keyboard.down:
        platform.y -= 3
    if keyboard.down:
        platform1.y += 3

def draw():
    screen.fill('white')
    screen.draw.filled_rect(item, 'green')
    screen.draw.filled_rect(item2, 'red')
    screen.draw.filled_rect(item3, 'yellow')
    screen.draw.filled_rect(platform, 'brown')
    screen.draw.filled_rect(platform1, 'brown')

def update():

    global ivy
    global i2vy
    global i3vy
    ivy = item_motion_control(item, platform, ivy, platform1)
    i2vy = item_motion_control(item2, platform, i2vy, platform1)
    i3vy = item_motion_control(item3, platform, i3vy, platform1)

    platform_control()

    print(item.x, item.y, ivy)


import logging

from django.utils.translation import gettext_lazy as _
from djmoney.contrib.django_rest_framework import MoneyField
from moneyed import CURRENCIES
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from expenses.api.fields import UserSpecificSlugRelatedField
from expenses.models import Category, Retailer, Transaction

logger = logging.getLogger(__name__)

class CategorySerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    name = serializers.CharField(max_length=255)
    product_type = serializers.ChoiceField(choices=Category.PRODUCT_TYPES)
    slug = serializers.CharField(max_length=255)
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())

    class Meta:
        model = Category
        fields = ["id", "name", "product_type", "user", "slug"]
        validators = [
            UniqueTogetherValidator(
                queryset=Category.objects.all(),
                fields=["name", "user"],
                message=_("There is already a Category with this name for the current user"),
            ),
            UniqueTogetherValidator(
                queryset=Category.objects.all(),
                fields=["slug", "user"],
                message=_("There is already a Category with this slug for the current user"),
            ),
        ]

class RetailerSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    name = serializers.CharField(max_length=255)
    online = serializers.BooleanField()
    slug = serializers.CharField(max_length=255)
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())

    class Meta:
        model = Retailer
        fields = ["id", "name", "online", "user", "slug"]
        validators = [
            UniqueTogetherValidator(
                queryset=Retailer.objects.all(),
                fields=["name", "user"],
                message=_("There is already a Retailer with this name for the current user"),
            ),
            UniqueTogetherValidator(
                queryset=Retailer.objects.all(),
                fields=["slug", "user"],
                message=_("There is already a Retailer with this slug for the current user"),
            ),
        ]

class TransactionSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    name = serializers.CharField(max_length=255)
    amount = MoneyField(max_digits=14, decimal_places=2)
    amount_currency = serializers.ChoiceField(choices=CURRENCIES)
    retailer = UserSpecificSlugRelatedField(many=False, read_only=False, slug_field="slug", queryset=Retailer.objects)
    category = serializers.StringRelatedField(
        read_only=True,
    )
    category = UserSpecificSlugRelatedField(many=False, read_only=False, slug_field="slug", queryset=Category.objects)
    date = serializers.DateField()
    transaction_type = serializers.ChoiceField(choices=Transaction.TRANSACTION_TYPES)
    recurring = serializers.BooleanField()
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())

    class Meta:
        model = Transaction
        fields = [
            "id",
            "name",
            "amount",
            "amount_currency",
            "retailer",
            "category",
            "date",
            "transaction_type",
            "recurring",
            "user",
        ]
        validators = [
            UniqueTogetherValidator(
                queryset=Transaction.objects.all(),
                fields=[
                    "name",
                    "amount",
                    "amount_currency",
                    "retailer",
                    "category",
                    "date",
                    "transaction_type",
                    "recurring",
                    "user",
                ],
                message=_("The transaction is a duplicate"),
            )
        ]


import HashSet as hset
import BstMap as bst
import os

# Program starts

def read_file(file_path):
    with open(file_path, "r", encoding='utf8') as file:
        words = []
        for word in file:
            words.append(word[:-1])
    return words

# Initialize word set
words_100 = hset.HashSet()   # Create new empty HashSet
words_100.init()             # Initialize with eight empty buckets

holy_words = hset.HashSet()   # Create new empty HashSet
holy_words.init()

map_100 = bst.BstMap()
holy_map = bst.BstMap()

# get my paths to the documents
home = os.getcwd()
home = os.chdir(home + "/src/large_texts.txt")
home = os.getcwd()

path_100 = home + '/words_100k.txt'
holy_path = home + '/words_holygrail.txt'
rows_100 = read_file(path_100)
holy_rows = read_file(holy_path)

for word in rows_100:
    words_100.add(word)
    if len(word) >= 4:
        value = map_100.get(word)
        if value is None:
            map_100.put(word, 1)
        else:
            value += 1
            map_100.put(word, value)

for word in holy_rows:
    holy_words.add(word)
    if len(word) >= 4:
        value = holy_map.get(word)
        if value is None:
            holy_map.put(word, 1)
        else:
            value += 1
            holy_map.put(word, value)

top_100 = sorted(map_100.as_list(), key=lambda x: x[1], reverse=True)[:10]
holy_top = sorted(holy_map.as_list(), key=lambda x: x[1], reverse=True)[:10]

print('The 100K setences file has ', words_100.size, ' unique words.')
print('The top 10 occurrences are ', top_100)
print('Max bucket size for all the words: ', words_100.max_bucket_size())
print('Max depth in the BST for all the words: ', map_100.max_depth())

print('\nThe holy Grail script has ', holy_words.size, ' unique words.')
print('The top 10 occurrences are ', holy_top)
print('Max bucket size for all the words is: ', holy_words.max_bucket_size())
print('Max depth in the BST for all the words is: ', holy_map.max_depth())


import sys
from random import randint
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QSlider, QLabel, QMainWindow, QPushButton
from PyQt5.QtCore import Qt

from dedosManoDerecha import DedosDerecha
from dedosManoIzquierda import DedosIzquierda
from brazoDerecho import BrazoDerecho
from brazoIzquierdo import BrazoIzquierdo
from cabeza import Cabeza
from cadera import Cadera
from boca import Boca
from anilloLeds import AnilloLeds

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(790, 445)
        self.setWindowTitle('Robot Rob')
        self.ventanaDedosDerecha = DedosDerecha()
        self.ventanaDedosIzquierda = DedosIzquierda()
        self.ventanaBrazoDerecho = BrazoDerecho()
        self.ventanaBrazoIzquierdo = BrazoIzquierdo()
        self.ventanaCabeza = Cabeza()
        self.ventanaCadera = Cadera()
        self.ventanaBoca = Boca()
        self.ventanaAnilloLeds = AnilloLeds()

        l = QHBoxLayout()

        buttonDedosDerecha = QPushButton("Dedos mano derecha")
        buttonDedosDerecha.clicked.connect(self.toggle_ventanaDedosDerecha)
        l.addWidget(buttonDedosDerecha)

        buttonDedosIzquierda = QPushButton("Dedos mano izquierda")
        buttonDedosIzquierda.clicked.connect(self.toggle_ventanaDedosIzquierda)
        l.addWidget(buttonDedosIzquierda)

        buttonBrazoDerecho = QPushButton("Brazo Derecho")
        buttonBrazoDerecho.clicked.connect(self.toggle_ventanaBrazoDerecho)
        l.addWidget(buttonBrazoDerecho)

        buttonBrazoIzquierdo = QPushButton("Brazo Izquierdo")
        buttonBrazoIzquierdo.clicked.connect(self.toggle_ventanaBrazoIzquierdo)
        l.addWidget(buttonBrazoIzquierdo)

        buttonCabeza = QPushButton("Cabeza")
        buttonCabeza.clicked.connect(self.toggle_ventanaCabeza)
        l.addWidget(buttonCabeza)

        buttonCadera = QPushButton("Cadera")
        buttonCadera.clicked.connect(self.toggle_ventanaCadera)
        l.addWidget(buttonCadera)

        buttonBoca = QPushButton("Boca")
        buttonBoca.clicked.connect(self.toggle_ventanaBoca)
        l.addWidget(buttonBoca)

        buttonAnilloLeds = QPushButton("Anillo Leds")
        buttonAnilloLeds.clicked.connect(self.toggle_ventanaAnilloLeds)
        l.addWidget(buttonAnilloLeds)

        w = QWidget()
        w.setLayout(l)
        self.setCentralWidget(w)

    def toggle_ventanaDedosDerecha(self, checked):
        if self.ventanaDedosDerecha.isVisible():
            self.ventanaDedosDerecha.hide()
        else:
            self.ventanaDedosDerecha.show()

    def toggle_ventanaDedosIzquierda(self, checked):
        if self.ventanaDedosIzquierda.isVisible():
            self.ventanaDedosIzquierda.hide()
        else:
            self.ventanaDedosIzquierda.show()

    def toggle_ventanaBrazoDerecho(self, checked):
        if self.ventanaBrazoDerecho.isVisible():
            self.ventanaBrazoDerecho.hide()
        else:
            self.ventanaBrazoDerecho.show()

    def toggle_ventanaBrazoIzquierdo(self, checked):
        if self.ventanaBrazoIzquierdo.isVisible():
            self.ventanaBrazoIzquierdo.hide()
        else:
            self.ventanaBrazoIzquierdo.show()

    def toggle_ventanaCabeza(self, checked):
        if self.ventanaCabeza.isVisible():
            self.ventanaCabeza.hide()
        else:
            self.ventanaCabeza.show()

    def toggle_ventanaCadera(self, checked):
        if self.ventanaCadera.isVisible():
            self.ventanaCadera.hide()
        else:
            self.ventanaCadera.show()

    def toggle_ventanaBoca(self, checked):
        if self.ventanaBoca.isVisible():
            self.ventanaBoca.hide()
        else:
            self.ventanaBoca.show()

    def toggle_ventanaAnilloLeds(self, checked):
        if self.ventanaAnilloLeds.isVisible():
            self.ventanaAnilloLeds.hide()
        else:
            self.ventanaAnilloLeds.show()

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec()


import requests

from core.http_config import HTTPConfig, HTTP_POST, HTTP_GET, HTTP_PUT, HTTP_DELETE

class HTTPConnection:
    http_config = None

    def __init__(self, config: HTTPConfig = None):
        if not HTTPConfig:
            raise ValueError("Config required")

        self.http_config = config

    def execute(self, *, data: None) -> requests.Response:
        """

        :param data: JSON encoded payload
        :return:
        """
        params = {"url": self.http_config.url, "headers": self.http_config.headers}

        if data:
            params["data"] = data

        if self.http_config.method == HTTP_POST:
            response = requests.post(**params)

        elif self.http_config.method == HTTP_GET:
            response = requests.get(**params)
        elif self.http_config.method == HTTP_PUT:
            response = requests.put(**params)
        elif self.http_config.method == HTTP_DELETE:
            response = requests.delete(**params)

        else:
            raise ValueError("Method not implemented!")

        return response


import pygame.font

class Scoreboard:
    """Show the game info"""
    def __init__(self, ai_settings, screen, stats):
        """Initialize score attributes"""
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.ai_settings = ai_settings
        self.stats = stats

        # Font settings for scoring information
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont(None,  48)

        # Prepare the initial image
        self.prep_score()

    def prep_score(self):
        """Turn the score into a rendered image"""
        score_str = str(self.stats.score)
        self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color)

        # Show the score at right top of the screen
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = 20

    def show_score(self):
        """Draw score to the screen"""
        self.screen.blit(self.score_image, self.score_image)


"""
Handles Fits -> Pandas transformations for tables with multidimensional "columns"
"""

import numpy as np
import pandas as pd
import sys

def to_pandas(recarr):
    """
    Converts potentially nested record array (such as a FITS Table) into Pandas DataFrame

    FITS tables sometimes have multidimensional columns, which are not supported for DataFrames
    Pandas DataFrames however provide many nice features, such as SQL speed database matchings.

    The approach is to flatten out multidimensional column [[COL]] into [COL_1, COL_2, ..., COL_N]

    Examples
    --------

    Just pass the loaded FITS table::

        import fitsio as fio
        import xpipe.io.catalogs as catalogs

        raw_data = fio.read("data.fits")
        data = catalogs.to_pandas(raw_data)

    Parameters
    ----------
    recarr : numpy.array
        array to be converted to DataFrame

    Returns
    -------
    pandas.DataFrame
        array as DataFrame

    """

    newarr = flat_copy(recarr)
    res = pd.DataFrame.from_records(newarr.byteswap().newbyteorder(), columns=newarr.dtype.names)
    return res

def flat_type(recarr):
    """
    Assigns the dtypes to the flattened array

    Parameters
    ----------
    recarr : numpy.array
        array to be converted to DataFrame

    Returns
    -------
    list
        dtypes of flattened array

    """

    newtype = []
    for dt in recarr.dtype.descr:
        if len(dt) == 3:
            for i in np.arange(dt[2][0]):
                newtype.append((dt[0] + '_' + str(i), dt[1]))
        else:
            newtype.append(dt)
    return newtype

def flat_copy(recarr):
    """
    Copies the record array into a new recarray which has only 1-D columns

    Parameters
    ----------
    recarr : numpy.array
        array to be converted to DataFrame

    Returns
    -------
    numpy.array
        array with 1-D columns
    """

    newtype = flat_type(recarr)
    newarr = np.zeros(len(recarr), dtype=newtype)

    oldnames = recarr.dtype.names
    j = 0
    for i, dt in enumerate(recarr.dtype.descr):
        if len(dt) == 3:
            for c in np.arange(dt[2][0]):
                #                 print newtype[j]
                newarr[newtype[j][0]] = recarr[oldnames[i]][:, c]
                j += 1

        else:
            #             print newtype[j]
            newarr[newtype[j][0]] = recarr[oldnames[i]]
            j += 1
    return newarr

def match_endian(arr):
    """Tries to auto convert the Endian ordering of an array to match to native ordering"""
    valid_endians = ["<", ">"]
    endians = {
        "little": "<",
        "big": ">"
    }
    native_byteorder = endians[sys.byteorder]
    array_byteorder = arr.dtype.byteorder

    if len(arr.shape) != 1:
        raise TypeError("only 1D arrays are applicable for this method")

    if (array_byteorder in valid_endians) and native_byteorder != array_byteorder:
        result = arr.newbyteorder().byteswap()
    else:
        result = arr
    return result


"""
TestMetricValue
"""
from unittest import TestCase

from nbdb.common.metric_key import MetricKey
from nbdb.common.metric_value import MetricValue
from nbdb.string_table.in_memory_string_table import InMemoryStringTable

class TestMetricValue(TestCase):
    """
    Tests the MetricValue object related methods
    """

    def setUp(self) -> None:
        """
        Setup the string table and create metric keys for validation
        :return:
        """
        self.string_table = InMemoryStringTable()
        self.key = MetricKey('f', {})
        self.tokenized_key = self.key.generate_tokenized_metric_key(
            self.string_table)

    def test_valid_metric_values(self):
        """
        Test the valid cases for a metric value and make sure they
        are stored appropriately
        :return:
        """
        metric_value = MetricValue(self.tokenized_key, 100, 10.0)

        self.assertEqual(metric_value.value, 10.0)
        self.assertEqual(metric_value.epoch, 100)
        self.assertEqual(self.tokenized_key.generate_series_id(),
                         metric_value.key.generate_series_id())

    def test_invalid_metric_values(self):
        """
        Test the incorrect usage
        :return:
        """
        # Invalid MetricValue with string value
        self.assertRaises(AssertionError, MetricValue,
                          self.tokenized_key, 100, '10')
        # Invalid MetricValue with untokenized key
        self.assertRaises(AssertionError, MetricValue, self.key, 100, 10)

        # Invalid MetricValue with invalid epoch
        self.assertRaises(AssertionError, MetricValue,
                          self.tokenized_key, 0, 10)