import os
from django.conf import settings
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.shortcuts import redirect
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import Hospede, Acesso, CustomUser

def index(request):
    return render(request, 'index.html', {})

def encoding(request, filename):
    try:
        encoding_path = os.path.join(settings.MEDIA_ROOT, 'encoding', f'{filename}.pkl')

        if os.path.exists(encoding_path):
            with open(encoding_path, 'rb') as file:
                response = HttpResponse(file.read(), content_type='application/octet-stream')
                response['Content-Disposition'] = f'attachment; filename="{filename}.pkl"'
                return response
        else:
            messages.error(request, 'O arquivo de encoding não existe.')
            return redirect('index')
    except Exception:
        messages.error(request, 'Ocorreu um erro durante o download do arquivo.')
        return redirect('index')

def guest_json(request, phone):
    guest = get_object_or_404(Hospede, phone=phone)
    if guest:
        guest_data = {
            'name': guest.name,
            'phone': guest.phone,
            'nickname': guest.nickname,
            'relationship': guest.relationship,
            'owner': guest.owner.email
        }
        access = Acesso(guest=guest)
        access.save()
        return JsonResponse(guest_data)
    else:
        return HttpResponse('Hospede não encontrado.')

@csrf_exempt
def owner_json(request, email):
    owner = get_object_or_404(CustomUser, email=email)
    if owner:
        if request.method == 'POST':
            chat_id = request.POST.get('chat_id')
            if owner.first_access:
                owner.chat_id = chat_id
                owner.first_access = False
                owner.save()
                return HttpResponse('Chat ID salvo com sucesso')
            else:
                if owner.chat_id == chat_id:
                    return HttpResponse('Chat ID salvo com sucesso')
                else:
                    return HttpResponse('Chat ID ja cadastrado')

        owner_data = {
            'name': owner.get_full_name(),
            'email': owner.email,
            'first_access': owner.first_access,
            'chat_id': owner.chat_id
        }
        return JsonResponse(owner_data)
    else:
        return HttpResponse('Proprietário(a) não encontrado.')

def telegram(request):
    return render(request, 'telegram.html', {})


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 14:35:10 2019

@author: Shalin
"""

#inputs are "maps" which are just a list of lists. Please ignore the poor naming convention.
#Each index in the list represents an event or detection interval.
#map[i][0] is the start index of the ith event/detection.
#Similarly map[i][1] is the end index of the ith event/detection
import os
import numpy as np
def get_metric_values(gt_map,pred_map):
    gt_idx = 0
    pred_idx = 0
    while gt_idx < len(gt_map) and pred_idx < len(pred_map):
        if gt_map[gt_idx][0] <= pred_map[pred_idx][0]:
            if gt_map[gt_idx][1] < pred_map[pred_idx][0]:
                FN += 1
                gt_idx += 1
            elif gt_map[gt_idx][1] >= pred_map[pred_idx][1]:
                TP += 1
                gt_idx, pred_idx = increment_idcs_exit_event(gt_map, pred_map, gt_idx, pred_idx)
            elif get_overlap(gt_map[gt_idx],pred_map[pred_idx]) < 0.5:
                FN += 1
                gt_idx += 1
            else:
                TP += 1
                gt_idx += 1
                pred_idx += 1
        else:
            if gt_map[gt_idx][0] > pred_map[pred_idx][1]:
                FP += 1
                pred_idx += 1
            elif get_overlap(gt_map[gt_idx],pred_map[pred_idx]) < 0.5:
                FP += 1
                pred_idx += 1
            else:
                TP += 1
                gt_idx, pred_idx = increment_idcs_exit_event(gt_map, pred_map, gt_idx, pred_idx)
    FN += (len(gt_map) - gt_idx)
    FP += (len(pred_map) - pred_idx)
    return FP, FN, TP

def increment_idcs_exit_event(gt_map, pred_map, gt_idx, pred_idx):
    while gt_map[gt_idx][1] > pred_map[pred_idx][0]:
        if get_overlap(gt_map[gt_idx],pred_map[pred_idx]) < 0.5:
            gt_idx += 1
            return gt_idx, pred_idx
        pred_idx += 1
        if gt_idx >= len(gt_map) or pred_idx >= len(pred_map):
            return gt_idx, pred_idx
    gt_idx += 1
    return gt_idx, pred_idx

def get_overlap(gt_tup, pred_tup):
    if pred_tup[1] > gt_tup[1]:
        num = (gt_tup[1] - pred_tup[0])+1
    else:
        num = (pred_tup[1] - gt_tup[0])+1
    return num / ((pred_tup[1] - pred_tup[0])+1)

def get_maps(detections):
    _map = []
    for l in detections:
        counts = [0, 0, None] if int(l) == 1 else [None, None, None]
        for i, v in l:
            val = int(v)
            if val == 0:
                if all([counts[0], counts[1]]):
                    counts[2] = i
                    _map.append(counts)
                    counts = [None, None, None]
                    continue
            if counts[1] == (i - 1):
                counts[1] += 1
            else:
                counts = [i + 1, i, None]
        if all([counts[0], counts[1]]):
            counts[2] = len(l) - 1
            _map.append(counts)
    return list(map(lambda x: [x[0], x[2]], _map))

if __name__ == '__main__':
    label_path = 'D:\\NCSU\\sem2\\ECE 542 Neural Networks\\project\\3b\\ECE542-Proj3b\\Training Data B'
    predict_file_name = 'prediction.txt'
#    detection = [[0]*10 + [1]*5 + [0]*10 ]
#    print(detection)
#    print(get_maps(detection))

#    eval_obj = Eval()
    FP, FN, TP={},{},{}
    session_list = [13,16]
    for session_id in session_list:
        cur_label_path = os.path.join(label_path, 'Session{:02d}'.format(session_id), 'detection.txt')
        cur_predict_path = os.path.join(label_path, 'Session{:02d}'.format(session_id), predict_file_name)
        label_file = np.loadtxt(cur_label_path)
        predict_file = np.loadtxt(cur_predict_path)
        FP[session_id], FN[session_id], TP[session_id] = get_metric_values(get_maps(label_file),get_maps(predict_file))

#    eval_obj.print_eval()


#https://book.douban.com/top250?start=0/25/50/....
import requests
from lxml import etree
import time
import random
from fake_useragent import UserAgent

class TUSHU:
    def __init__(self):
        self.url='https://book.douban.com/top250?start={}'

    def get_html(self,url):
        """使用随机的User-Agent"""
        headers={
            'User-Agent':UserAgent().random
        }
        html=requests.get(url=url,headers=headers).content.decode('utf8','ignore')
        self.lxml_html(html)

    def lxml_html(self,html):
        """lxml+xpath进行数据解析"""
        #解析函数
        #1.解析对象
        l_html=etree.HTML(html)
        #2.生成节点对象--基准xpath
        l_list=l_html.xpath('//div[@class="indent"]/table')
        #3.提取节点对象数据
        for l in l_list:
            item={}
            #判断是否为空
            if l.xpath('.//div[@class="pl2"]/a/text()'):
                item['name']=l.xpath('.//div[@class="pl2"]/a/text()')[0].strip()
            else:
                item['name']=None
            if l.xpath('.//p[@class="pl"]/text()'):
                item['info']=l.xpath('.//p[@class="pl"]/text()')[0].strip()
            else:
                item['info']=None
            if l.xpath('.//span[@class="rating_nums"]/text()'):
                item['score']=l.xpath('.//span[@class="rating_nums"]/text()')[0].strip()
            else:
                item['info']=None
            if l.xpath('.//span[@class="pl"]/text()'):
                item['nums']=l.xpath('.//span[@class="pl"]/text()')[0].split('\n')[1].strip()
            else:
                item['info']=None
            if l.xpath('.//span[@class="inq"]/text()'):
                item['inq']=l.xpath('.//span[@class="inq"]/text()')[0].strip()
            else:
                item['info']=None

            print(item)

    def run(self):
        for i in range(10):
            page_url=self.url.format(i*25)
            self.get_html(url=page_url)
            time.sleep(random.randint(2,3))

if __name__ == "__main__":
    TUSHU().run()


"""
Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method.
The file contains a list of words separated by commas. Your program should output the words and their frequencies
(the number of times each word appears in the file) without any duplicates.

Ex: If the input is:

input1.csv

and the contents of input1.csv are:

hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy

the output is:

hello 1
cat 2
man 2
hey 2
dog 2
boy 2
Hello 1
woman 1
Cat 1

"""

import csv
filename = input()
#filename = 'input1.csv'

word_list = []
with open(filename, 'r') as csvfile:
    file = csv.reader(csvfile, delimiter=',')

    for line in file:
        for word in line:
            word_list.append(word)

    unique_words = sorted(set(word_list), key=word_list.index)

    for x in unique_words:
        print(x, word_list.count(x))

Python Practice Tests/Practice Test 1/33.20_Word frequencies (lists).py


"""
This file contains the code for the bunny jumping game,
where the user plays as a bunny trying to jump over as many
snakes as possible. Inspiration for this game from
https://github.com/codewmax/chrome-dinosaur.
"""
import pygame
import os
import random
import sys
from buttons import menuButton
import menu as mainMenu
import RPi.GPIO as GPIO

pygame.init()

# initializing the window size to fit the LCD tablet
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1024
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.HWSURFACE | pygame.DOUBLEBUF)

GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
GPIO.setup(20, GPIO.IN)    # set GPIO 20 as input

# initializing assets for game animations and sound
RUNNING = [pygame.image.load("bunnyjump_assets/bunny/Bunny.png"),
           pygame.image.load("bunnyjump_assets/bunny/BunnyRun1.png"),
           pygame.image.load("bunnyjump_assets/bunny/BunnyRun2.png")]

JUMPING = pygame.image.load("bunnyjump_assets/bunny/BunnyRun2.png")

SNAKE = pygame.image.load("bunnyjump_assets/snake/Snake.png")

CLOUD = pygame.image.load(os.path.join("bunnyjump_assets/background", "Cloud.png"))

BG = [pygame.image.load(os.path.join("bunnyjump_assets/background", "Grass.png")),
      pygame.image.load(os.path.join("bunnyjump_assets/background", "Ground.png")),
      pygame.image.load(os.path.join("bunnyjump_assets/background", "Sky.png"))]

JUMP_SOUND = pygame.mixer.Sound("bunnyjump_assets/jump.wav")

# Class for the cloud object in the background
class Cloud:
    # initializing where the first cloud should be generated
    def __init__(self):
        self.x = SCREEN_WIDTH + random.randint(1000, 1200)
        self.y = random.randint(50, 100)
        self.image = CLOUD
        self.width = self.image.get_width()

    # updating the position of the cloud as the bunny moves across the screen
    def update(self):
        self.x -= game_speed # moving the cloud at the same speed as the game
        if self.x < -self.width: # if the cloud has moved past the end of the screen, reset its position
            self.x = SCREEN_WIDTH + random.randint(1500, 2000)
            self.y = random.randint(50, 100)

    # drawing the cloud on the game screen
    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

# Class for the snake object that the user will try to jump over
class Snake:
    # initializing where the first snake should be generated
    def __init__(self):
        self.image = SNAKE
        self.rect = self.image.get_rect()
        self.rect.x = SCREEN_WIDTH
        self.rect.y = 318

    # updating the position of the snake as the bunny moves across the screen
    def update(self):
        self.rect.x -= game_speed # moving the snake at the same speed as the game
        if self.rect.x < -self.rect.width: # if the snake has moved past the end of the screen, remove it from the list of snakes
            snakes.pop()

    # drawing the snake on the game screen
    def draw(self, screen):
        screen.blit(self.image, self.rect)

# Class for the bunny object that the user will play as
class Bunny:
    X_POS = 30
    Y_POS = 316
    JUMP_VEL = 8.5

    # initializing where the bunny will start from and its instance variables
    def __init__(self):
        self.run_img = RUNNING # the images for when the bunny is running
        self.jump_img = JUMPING # the image for when the bunny is jumping

        self.bunny_run = True
        self.bunny_jump = False

        self.step_index = 0
        self.jump_vel = self.JUMP_VEL # determines how high the bunny will jump into the air
        self.image = self.run_img[0]
        self.bunny_rect  = self.image.get_rect()
        self.bunny_rect.x = self.X_POS
        self.bunny_rect.y = self.Y_POS

    # updating the state of the bunny based on user actions
    def update(self, userInput, fabric):
        if self.bunny_run:
            self.run()
        if self.bunny_jump:
            self.jump()

        # check for cycling through the bunny running animations
        if self.step_index >= 15:
            self.step_index = 0

        # if the screen is touched or fabric is touched and the bunny is not already jumping
        if (fabric or userInput[0]) and not self.bunny_jump:
            pygame.mixer.Sound.play(JUMP_SOUND) # play the jumping sound
            pygame.mixer.music.stop()
            self.bunny_run = False
            self.bunny_jump = True
        # if the bunny is not jumping or the screen is not touched or the fabric is not touched, keep running
        elif not (self.bunny_jump or userInput[0] or fabric):
            self.bunny_run = True
            self.bunny_jump = False

    # displaying the bunny while it is running
    def run(self):
      self.image = self.run_img[self.step_index // 5] # changing the image for the running animation
      self.bunny_rect = self.image.get_rect()
      self.bunny_rect.x = self.X_POS
      self.bunny_rect.y = self.Y_POS
      self.step_index += 1

    # defining the jumping action of the bunny
    def jump(self):
        self.image = self.jump_img
        if self.bunny_jump:
            self.bunny_rect.y -= self.jump_vel * 3 # move the bunny into the air
            self.jump_vel -= 0.849 # decrease the rate at which the bunny is moving into the air
        if self.jump_vel < -self.JUMP_VEL:
            self.bunny_jump = False # making the bunny fall back down from jumping
            self.jump_vel = self.JUMP_VEL # resetting the jump velocity

    # drawing the bunny on the game screen
    def draw(self, screen):
      screen.blit(self.image, (self.bunny_rect.x, self.bunny_rect.y))

def main():
    global game_speed, x_pos_bg, y_pos_bg, points, snakes
    run = True
    clock = pygame.time.Clock()
    player = Bunny() # instance of the bunny the player will play as
    cloud = Cloud() # instance of the cloud moving across the background
    game_speed = 10
    x_pos_bg = 0
    y_pos_bg = 348
    points = 0
    font = pygame.font.Font('freesansbold.ttf', 20)
    snakes = []
    death_count = 0

    # create menu button object
    menuButtonObj = menuButton("test_hamburg_menu.png")

    def score():
        global points, game_speed
        points += 1
        # increase the speed of the game every 500 points
        if points % 500 == 0:
            game_speed += 1

        # displaying the points scored so far in the top right of the game screen
        text = font.render("Points: " + str(points), True, (0, 0, 0))
        textRect = text.get_rect()
        textRect.center = (900, 40)
        SCREEN.blit(text, textRect)

    def background():
        # creating the ground that the bunny will be running on
        global x_pos_bg, y_pos_bg
        image_width = BG[0].get_width()
        for i in range(0, 60):
            SCREEN.blit(BG[0], (image_width*i + x_pos_bg, y_pos_bg))
            for j in range(1, 14):
                SCREEN.blit(BG[1], (image_width*i + x_pos_bg, image_width*j + y_pos_bg))
        if x_pos_bg <= -image_width:
            x_pos_bg = 0
        x_pos_bg -= game_speed # moving the ground across the screen

    while run:
        for event in pygame.event.get():
            # exiting the game
            if event.type == pygame.QUIT:
                run = False
                sys.exit()
            # if the menu button is pressed, go to the main menu
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos  # gets mouse position
                if menuButtonObj.button.collidepoint(mouse_pos):
					# jump back to main menu
                    mainMenu.main()

        SCREEN.fill((135, 206, 235))
        userInput = pygame.mouse.get_pressed() # get whether or not the screen was touched
        fabric = False
        if GPIO.input(20): # check whether the conductive fabric was touched
            fabric = True
        player.draw(SCREEN)
        player.update(userInput, fabric)

        # if there are no more snakes, create a new one and add it to the list of snakes
        if len(snakes) == 0:
            snakes.append(Snake())

        for obstacle in snakes:
            obstacle.draw(SCREEN)
            obstacle.update()
            # if the bunny collides with the snake, the game ends
            if player.bunny_rect.colliderect(obstacle.rect):
                pygame.time.delay(1000)
                death_count += 1
                menu(death_count)

        background()
        cloud.draw(SCREEN)
        cloud.update()
        score()

        clock.tick(30)
        SCREEN.blit(menuButtonObj.img, menuButtonObj.img.get_rect(center = menuButtonObj.button.center))
        pygame.display.update()

def menu(death_count):
    global points
    run = True
    # create menu button object
    menuButtonObj = menuButton("test_hamburg_menu.png")

    while run:
        SCREEN.fill((135, 206, 235))
        font = pygame.font.Font('freesansbold.ttf', 30)

        if death_count == 0:
            # rendering the UI for the very beginning
            text = font.render("Press screen to Start", True, (0, 0, 0))
        else:
            # rendering the UI and displaying the score for when the player collides with a snake
            text = font.render("Press screen to Restart", True, (0, 0, 0))
            score = font.render("Your Score: " + str(points), True, (0, 0, 0))

            # positioning the score in the corner
            scoreRect = score.get_rect()
            scoreRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 100)
            SCREEN.blit(score, scoreRect)

        # displaying the instructions on the screen
        instruction = font.render("Touch the screen to jump over the snake", True, (0, 0, 0))
        instructionRect = instruction.get_rect()
        instructionRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)
        SCREEN.blit(instruction, instructionRect)
        textRect = text.get_rect()
        textRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        SCREEN.blit(text, textRect)
        SCREEN.blit(RUNNING[0], (SCREEN_WIDTH // 2 - 20, SCREEN_HEIGHT // 2 - 140))
        SCREEN.blit(menuButtonObj.img, menuButtonObj.img.get_rect(center = menuButtonObj.button.center))

        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos
                if menuButtonObj.button.collidepoint(mouse_pos):
                    # jump back to main menu
                    mainMenu.main()
                else:
                    main()

# menu(death_count=0)


# to print Python kun line no. ma xa

content = True
i = 1 # i is line counter
with open("log.txt") as f:
    while content:
        content = f.readline()

        if "python" in content.lower(): # avoids case sensitive; Python vaye pani python vayepani ; baal hunna
            print(content)
            print(f"Yes python is present in line number {i}")

        i += 1


import turtle
import random
tim = turtle.Turtle()
screen=turtle.Screen()

colors=["red","DeepSkyBlue","yellow","blue","pink","violet","green","violet","orange"]
for num_of_sides in range(3,11,1):
    for _ in range(num_of_sides):
        tim.color(random.choice(colors))
        angle = 360/num_of_sides
        tim.forward(100)
        tim.right(angle)

screen.exitonclick()


from bottle import BaseRequest, request, run, post, route
from PIL import Image
from StringIO import StringIO
import read_single_image
import time

# aumentar peso maximo de archivo a recibir, en bytes
BaseRequest.MEMFILE_MAX = 1024 * 1024 * 10 # 10 MB max

@post('/inference')
def inference():
    t0 = time.time()
    data = request.files.image

    raw = data.file.read()
    im = Image.open(StringIO(raw))

    response = {
        'lectura': read_single_image.main(im),
        'tiempo_inferencia': time.time() - t0
    }

    return response

@route('/test')
def test():
    return("Hello world!")

run(host='0.0.0.0', port=8080, debug=True)


# -*- coding = utf-8 -*-
import torch
import torch.nn as nn
import torchvision

class BCNN_all(nn.Module):
    def __init__(self):
        super(BCNN_all, self).__init__()
        #VGG16的卷积层与池化层
        self.features = torchvision.models.vgg16(pretrained=False).features
        self.features = torch.nn.Sequential(*list(self.features.children())[:-1]) #去除最后的pool层
        #全连接层
        self.fc = torch.nn.Linear(512*512, 200)

    def forward(self,x):
        N=x.size()[0]
        assert x.size() == (N, 3, 448, 448)
        x=self.features(x)
        assert x.size() == (N, 512, 28, 28)
        x = x.view(N, 512, 28*28)
        x = torch.bmm(x, torch.transpose(x, 1, 2))/(28*28) #双线性
        assert x.size() == (N, 512, 512)
        x = x.view(N, 512*512)
        x = torch.sqrt(x + 1e-5)
        x = torch.nn.functional.normalize(x)
        x=self.fc(x)
        assert x.size() == (N, 200)
        return x


"""
Demo of word embedding (Glove) representations of words.

Setup:
- pip3 install torchvision tqdm
- glove.6B.50d.txt must be in this directory
"""

import code

import torch
from tqdm import tqdm

emb = torch.zeros(400000, 50)
idx2word = []
word2idx = {}

with open("glove.6B.50d.txt", "r") as f:
    for i, line in tqdm(enumerate(f.readlines()), total=400000):
        # break apart the line
        pieces = line.strip().split(" ")
        word = pieces[0]
        nums = pieces[1:]

        # build the word vector, save to matrix
        emb[i] = torch.FloatTensor([float(num) for num in nums])

        # add it to our vocab bookkeeping
        idx2word.append(word)
        assert idx2word[i] == word
        word2idx[word] = i

print("Play with `emb` and `word2idx`")
code.interact(local=dict(globals(), **locals()))

# ideas
# ---
#
# hotel, motel
# hotel, aquarium
#
# tuesday, wednesday
# tuesday, zebra
# tuesday, tuesday
#
# happy, delighted
# happy, zebra
# happy, sad

def sim(word1, word2):
    vec1 = emb[word2idx[word1]]
    norm1 = vec1 / vec1.dot(vec1).sqrt()

    vec2 = emb[word2idx[word2]]
    norm2 = vec2 / vec2.dot(vec2).sqrt()

    return norm1.dot(norm2)

print("Play with `sim(word1, word2)`")
code.interact(local=dict(globals(), **locals()))


#!/usr/bin/python3
""" doc """
import sys
if len(sys.argv) != 2:
    print("Usage: nqueens N")
    exit(1)
try:
    N = eval(sys.argv[1])
except Exception:
    print("N must be a number")
    exit(1)
if (N < 4):
    print('N must be at least 4')
    exit(1)
Grid = [[0]*N for _ in range(N)]
Nq = [N]
solution = []

def attack(i, j):
    """ doc """
    for k in range(N):
        if Grid[i][k] == 1 or Grid[k][j] == 1:
            return True
    for k in range(N):
        for z in range(N):
            if (k + z == i + j) or (k - z == i - j):
                if Grid[k][z] == 1:
                    return True
    return False

def Nqueens(n, x):
    """ doc """
    for i in range(x, N):
        for j in range(N):
            if (not(attack(i, j))) and (Grid[i][j] != 1):
                Grid[i][j] = 1
                Nq[0] = Nq[0] - 1
                Nqueens(n - 1, i + 1)
                if Nq[0] == 0:
                    position()
                Grid[i][j] = 0
                Nq[0] = Nq[0] + 1
    return False

def reset(N):
    """ doc """
    for k in range(N):
        for z in range(N):
            Grid[k][z] = 0

def validate(N):
    """ doc """
    suma = 0
    store = []
    for k, i in enumerate(Grid):
        if 1 in i:
            store.append([k, i.index(1)])
            suma += 1
    if suma == N:
        return store
    else:
        return []

def position():
    """ doc """
    x = validate(N)
    if len(x) == N and x not in solution:
        print(x)
        solution.append(x)

Nqueens(N, 0)


'''
Thomas Koutsidis
June 24th, 2022

Question 3

The main() calls the three functions listed below and prints the sum of rows of the input matrix.
The three functions are:
- in_matrix(): prompts the user for dimensions m and n of a matrix and gets the integers from the user, which are elements of the matrix.
It then builts and returns a nested list mx with m elements, each element is a list of n integers.
List mx represenets an (m x n) matric with integer elements. The program crashes if the user inputs a non-integer.
- print_matrix(mx): prints the elements of matrix mx row by row.
- sum_rows(mx): returns a list with elements that are the sums of numbers in mx rows.

'''

def in_matrix():
    print("Program to sum the rows of an input matrix.")
    m = int(input("Enter the number of rows: "))
    n = int(input("Enter the number of columns: "))
    mx = []
    for i in range(m):
        row = []
        for j in range(n):
            print("Enter next element of row", i, end = ": ")
            num = int(input())
            row.append(num)
        mx.append(row)
    return mx

def print_matrix(mx):
    print("Input matrix: ")
    for i in range(len(mx)):
        for j in range(len(mx[0])):
            print(mx[i][j], end = "\t")
        print()

def sum_rows(mx):
    sums = []
    for i in range(len(mx)):
        sum = 0
        for j in range(len(mx[0])):
            sum = sum + mx[i][j]
        sums.append(sum)
        print("Sum of numbers in row", i, "is", sum)

def main():
    mx = in_matrix()
    print_matrix(mx)
    sum_rows(mx)

main()


import sys, time
sys.path.append('lib')

import HWiNFO
from influxdb import InfluxDBClient
import schedule

# Wait for HWiNFO to be launched.
time.sleep(20)

homestats = InfluxDBClient(host='raspberrypi4bserver.local',database='homestats')
hwinfo = HWiNFO.HwInfoRemote('127.0.0.1')

def job():
  data = hwinfo.get_data()

  # Memory
  for v in data.groups[0].items:
    if v.name == 'Physical Memory Load':
      memory_load = v.value

  # CPU Load
  for v in data.groups[1].items:
    if v.name == 'Total CPU Usage':
      cpu_load = v.value

  # CPU Temp
  for v in data.groups[4].items:
    if v.name == 'CPU Die (average)':
      cpu_temperature = v.value

  # GPU
  for v in data.groups[11].items:
    if v.name == 'GPU Utilization':
      gpu_load = v.value
    if v.name == 'GPU Temperature':
      gpu_temperature = v.value

  points = [
    {
      'measurement': 'desktop',
      'fields': {
        'memory_load': memory_load,
        'cpu_load': cpu_load,
        'cpu_temperature': cpu_temperature,
        'gpu_load': gpu_load,
        'gpu_temperature': gpu_temperature,
      }
    }
  ]
  homestats.write_points(points)

schedule.every(20).seconds.do(job)

while True:
  schedule.run_pending()
  time.sleep(1)


import tkinter as tk

class Application(tk.Tk):
     def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('Your first App')

        first_label = tk.Label(self, text = "I'm a cool App!!", font=10)
        first_label.pack(padx = 3, pady = 3)
        first_button = tk.Button(self, text ="Hello World", command = hello)
        first_button.pack(padx= 5, pady = 5)
        Application.first_entry = tk.Entry(self, width = 30)
        Application.first_entry.pack(padx = 7, pady = 7)

def hello():
    x = Application.first_entry.get()
    print(x)
app = Application()
app.mainloop()


"Postgresql backend"
from datetime import timedelta
from typing import Optional
from uuid import uuid4

import psycopg

from stormlock.backend import Backend, Lease, LockExpiredException, LockHeldException

class Postgresql(Backend):
    "Stormlock backend that uses postgresql as a data store."

    def __init__(self, connection: str, table: str = "stormlock"):
        super().__init__()
        self._conn = psycopg.connect(connection)
        self._conn.autocommit = True
        self._table = table

    def lock(self, resource: str, principal: str, ttl: timedelta):
        lease_id = str(uuid4())
        with self._conn.cursor() as cur:
            cur.execute(
                f"""
                INSERT INTO {self._table} as t
                (resource, lease, principal, expires) VALUES
                (%(resource)s, %(lease)s, %(principal)s,
                    current_timestamp+%(ttl)s)
                ON CONFLICT (resource) DO UPDATE
                SET (lease, principal, created, expires) =
                (excluded.lease, excluded.principal,
                    DEFAULT, current_timestamp+%(ttl)s)
                WHERE t.expires < excluded.created
                """,
                {
                    "resource": resource,
                    "lease": lease_id,
                    "principal": principal,
                    "ttl": ttl,
                },
            )
            if cur.rowcount == 1:
                return str(lease_id)
            raise LockHeldException(resource, self.current(resource))

    def unlock(self, resource: str, lease_id: str):
        with self._conn.cursor() as cur:
            cur.execute(
                f"""
                DELETE FROM {self._table} WHERE resource = %s AND lease = %s
                """,
                (resource, lease_id),
            )

    def renew(self, resource: str, lease_id: str, ttl: timedelta):
        with self._conn.cursor() as cur:
            cur.execute(
                f"""
                UPDATE {self._table} SET expires = current_timestamp + %s
                WHERE resource=%s AND lease=%s
                    AND expires > current_timestamp
                """,
                (ttl, resource, lease_id),
            )
            if cur.rowcount < 1:
                raise LockExpiredException(resource)

    def current(self, resource: str) -> Optional[Lease]:
        with self._conn.cursor() as cur:
            cur.execute(
                f"""
                SELECT principal, created, lease FROM {self._table}
                WHERE resource = %s AND expires > current_timestamp""",
                (resource,),
            )
            row = cur.fetchone()
            if row:
                principal, created, _id = row
                return Lease(principal, created, str(_id))
            return None

    def is_current(self, resource: str, lease_id: str) -> bool:
        with self._conn.cursor() as cur:
            cur.execute(
                f"""
                SELECT count(lease) FROM {self._table}
                WHERE resource = %s AND expires > current_timestamp
                AND lease = %s""",
                (resource, lease_id),
            )
            row = cur.fetchone()
            if row:
                return row[0] > 0
            return False

    def close(self):
        self._conn.close()


import os.path

def check_secret(secret):
    if not secret.isdigit():
        raise IOError("Error, the secret must be a number")

def check_amount_people(amount_people):
    if amount_people < 0:
        raise IOError("Error, the amount of people must be positive.")
    if amount_people < 2:
        raise IOError("Error, there must be at least 2 people.")

def check_file(file):
    if not os.path.isfile(file):
        raise IOError(f"Error, the file '{file}' do not exist.")
    if not file.endswith(".txt"):
        raise IOError(f"Error, the file '{file}' must be a txt.")

def check_mail(mail):
    if not mail.endswith("gmail.com"):
        raise IOError("Error, the mail given must be a gmail.")

def check_minimum_people(amount_people, minimum_people):
    if minimum_people < 0:
        raise IOError(f"Error, the number of number of the minimum number of  people to retrieve the secret must be "
                      f"positive.")
    if amount_people < 2:
        raise IOError("Error, there must be at least 2 people.")
    if minimum_people > amount_people:
        raise IOError(f"Error, the number of the minimum number of people"
                      f" to retrieve the secret ({minimum_people}) can not be greater than the amount of people ({amount_people}).")

def check_key(key):
    if 'k' not in key:
        raise IOError(f"Error, the key entered is incorrect must contain a 'k'.")
    portions = key.split('k')
    if len(portions[0]) < 1 or len(portions[1]) < 1 or not portions[1].isdigit() or not portions[0].isdigit():
        raise IOError(f"Error, the key entered is incorrect.")


import sys, os
import pandas as pd

#import ilc modules

def calc_cls(nl_dic, bl_dic, ell, band_centers, cwd):

    os.chdir(cwd + '/ilc_modules')
    import ilc, flatsky, misc, foregrounds as fg
    os.chdir(cwd)

    ############
    which_spec_arr = ['TT','EE']
    final_comp = 'cmb'
    freqcalib_fac = None
    ############

    #params
    paramfile = 'params.ini'
    # read and store param dict
    os.chdir(cwd + '/ilc_modules')
    param_dict = misc.fn_get_param_dict(paramfile)

    #get the CMB, noise, and foreground covariance
    try:
        ignore_fg = param_dict['ignore_fg']
    except:
        ignore_fg = []

    ignore_fg.append(final_comp.lower()) #the required component need not go into the covariance matrix.
    print('Ignoring ' + str(ignore_fg))

    #freqarr = [145]
    #param_dict['which_gal_mask'] = 0

    #Generate Cl spectrum
    cl_dic = {}
    include_gal = param_dict['include_gal']
    for which_spec in which_spec_arr:
        if which_spec == 'TT':
            el, cl_dic[which_spec] = ilc.get_analytic_covariance(param_dict, band_centers, \
                    nl_dic = nl_dic['T'], ignore_fg = ignore_fg, include_gal = include_gal, bl_dic = bl_dic)
        else:
            el, cl_dic[which_spec] = ilc.get_analytic_covariance\
                        (param_dict, band_centers, nl_dic = nl_dic['P'], ignore_fg = ignore_fg, which_spec = which_spec, \
                        pol_frac_per_cent_dust = param_dict['pol_frac_per_cent_dust'], \
                        pol_frac_per_cent_radio = param_dict['pol_frac_per_cent_radio'], \
                        pol_frac_per_cent_tsz = param_dict['pol_frac_per_cent_tsz'], \
                        pol_frac_per_cent_ksz = param_dict['pol_frac_per_cent_ksz'], \
                        include_gal = include_gal, bl_dic = bl_dic)

    #ilc weights
    lmin = el[0]
    weights_dic = {}
    for which_spec in which_spec_arr:
        weights_dic[which_spec] = ilc.get_multipole_weightsarr(final_comp, band_centers, el, cl_dic[which_spec], lmin,
                                                               freqcalib_fac)#, ignore_fg)

    #calculate residuals and separate
    #get the residual power now
    cl_residual = {}
    for which_spec in which_spec_arr:
        cl_residual[which_spec] = ilc.residual_power(param_dict, band_centers, el, cl_dic[which_spec],
                                                                              final_comp = final_comp,
                                                                              freqcalib_fac = freqcalib_fac,
                                                                              return_weights = 0)

    return el, cl_dic, weights_dic, cl_residual

def convert_params_excel(exp_dir, cwd):

    params_file = 'params.ini'

    os.chdir(cwd + '/ilc_modules')
    params = pd.read_csv('params.ini',comment='#',sep='=',names=['Parameter','Value'])

    os.chdir(exp_dir)
    params.to_excel('comp_sep_params.xlsx')

    return

def convert_fisher_params_excel(exp_dir,cwd,params_file='params_planck_r_0.0_2015_cosmo_lensed_LSS_JM.txt'):

    #params_file = 'params.ini'

    os.chdir(cwd + '/ilc_modules')
    params = pd.read_csv(params_file,comment='#',sep='=',names=['Parameter','Value'])

    os.chdir(exp_dir)
    params.to_excel('fisher_params.xlsx')

    return

def append_params(exp_dir, cwd):

    os.chdir(exp_dir)
    append_params = pd.read_excel('comp_sep_params.xlsx')

    os.chdir(cwd + '/ilc_modules')
    append_params.to_csv('params.ini',sep='=',columns=['Parameter','Value'],index=False)

    print('Done!')

    return

def append_fisher_params(exp_dir,cwd,params_file='params_planck_r_0.0_2015_cosmo_lensed_LSS_JM.txt'):

    os.chdir(exp_dir)
    append_params = pd.read_excel('fisher_params.xlsx')

    os.chdir(cwd + '/ilc_modules')
    append_params.to_csv(params_file,sep='=',columns=['Parameter','Value'],index=False)

    print('Done!')

    return


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 22:33:46 2018
fetch and feed
@author: lopo
"""
import tensorflow as tf
#fetch 即可以执行多个op
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

add = tf.add(input2, input3)
mul = tf.multiply(input1, add)

with tf.Session() as sess:
    result = sess.run([mul,add])
    print(result)

#feed
#创建占位符
input4 = tf.placeholder(tf.float32)
input5 = tf.placeholder(tf.float32)
output = tf.multiply(input4, input5)

with tf.Session() as sess:
    #feed的数据以字典的形式传入
    print(sess.run(output, feed_dict={input4:[8.],input5:[2.]}))


# python program to create a small paint application

# import everything from tkinter
from tkinter import *

# create a GUI window
window = Tk()

# function to draw oval shaped points
def callback(event):
    c.create_oval(event.x - 5, event.y - 5,
                  event.x + 5, event.y + 5, fill="#558832")

# function to drag and draw anything
def draw(event):
    c.create_oval(event.x - 5, event.y - 5,
                  event.x + 5, event.y + 5, fill="#000000")

# function to draw a rectangle
def drawRectangle(event):
    global draw, x1, y1
    if draw:
        c.create_rectangle(x1, y1, event.x, event.y, fill="Red")
        draw = False
    else:
        x1 = event.x
        y1 = event.y
        draw = True

# create a canvas where we can draw and specify its width and height
c = Canvas(window, width=400, height=400)
# show the canvas
c.pack()
# when we left click the mouse, callback function is called
c.bind("<Button-1>", callback)
# when be drag after left clicking the mouse, draw function is called
c.bind("<B1-Motion>", draw)
# when we right click the mouse, drawRectangle function is called
# initially x and y co-ordinates of starting point is 0
# once we right click initial co-ordinates changes
# after drawing each rectangle draw is set to false
c.bind("<Button-3>", drawRectangle)
draw = False
x1 = 0
y1 = 0
# display the window
window.mainloop()


import csv
from logging import getLogger
from typing import Iterator, Union

from scrapy import Spider, Request
from scrapy.http import HtmlResponse

from ecom_parser.models.product import ProductData
from ecom_parser.settings import ZENROW_PROXY
from ecom_parser.spiders.apteka.serializers import ProductResponseData

logger = getLogger(__name__)

TARGET_CATEGORIES_FILENAME = 'categories.csv'
PRODUCTS_LIST_CSS = 'div[itemtype$=Product]'
IS_LAST_PRODUCTS_PAGE_CSS = 'li[class$=item_next] a[class$=link_disabled]'
NEXT_PAGE_URL_CSS = 'li[class$=item_next] a::attr(href)'
PRODUCT_SECTIONS_LIST_CSS = 'li[itemprop=itemListElement] a span span::text'

class AptekaSpider(Spider):
    name = 'apteka'

    default_cookies = {'city': '92'}  # Дефолтное значение для региона - Томск
    default_meta = {'proxy': ZENROW_PROXY}

    root_url = 'https://apteka-ot-sklada.ru'

    def start_requests(self) -> Iterator[Request]:
        with open(TARGET_CATEGORIES_FILENAME) as file:
            for (category_url,) in csv.reader(file):
                yield self.request_category(category_url)

    def request_category(self, url: str) -> Request:
        return Request(url=url,
                       callback=self.parse_category,
                       cookies=self.default_cookies,
                       meta=self.default_meta)

    def parse_category(self, response: HtmlResponse) -> Iterator[Union[ProductData, Request]]:
        sections = [section.strip()
                    for section in response.css(PRODUCT_SECTIONS_LIST_CSS).getall()]
        response_products_data = [ProductResponseData.from_html(div, sections)
                                  for div in response.css(PRODUCTS_LIST_CSS)]
        for product_data in response_products_data:
            yield ProductData.create(product_data)

        if not self.is_last_products_page_received(response):
            next_page_url = f'{self.root_url}/{response.css(NEXT_PAGE_URL_CSS).get()}'
            assert next_page_url is not None
            yield self.request_category(next_page_url)

    @staticmethod
    def is_last_products_page_received(response: HtmlResponse) -> bool:
        return bool(response.css(IS_LAST_PRODUCTS_PAGE_CSS).get())


# 这题和I不同，要考虑如下两种情况11101、10111以及1201111
class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        le, ri = 0, len(nums) - 1
        while le <= ri:
            mid = le + ri >> 1
            if nums[mid] == target: return True
            while le < mid and nums[le] == nums[mid]:
                le += 1
            if nums[le] <= nums[mid]: # le~mid是升序；注意仅仅是le~mid升序！
                if nums[le] <= target < nums[mid]:
                    ri = mid - 1
                else: # 左侧取值范围是[nums[le], nums[mid]]，不在这个范围内必然是在右侧！
                    le = mid + 1
            else: # 右侧是升序
                if nums[mid] < target <= nums[ri]: # 因为右侧必然是升序，因此检查target是否在[nums[mid], nums[ri]]范围内
                    le = mid + 1
                else:
                    ri = mid - 1
        return False


import asyncio
from asyncio import Lock

import time

from .cdn_error import PageEnd
from ..models.json_model_async import JSONModel_async
from ..spider.api_spider import ApiSpider, DataError, BackOffError
from ..cache.redis_cache import Cache
import logging

logger = logging.getLogger(__name__)

class CDN(object):
    model = JSONModel_async
    api = ApiSpider
    cache = Cache

    @classmethod
    def get_cache(cls, key):
        return cls.cache.get(key)

    @classmethod
    def set_cache(cls, key, value, **kwargs):
        return cls.cache.set(key, value, **kwargs)

    @classmethod
    def count(cls, unit=10000, **kwargs):
        spider = cls.api(**kwargs)
        page_size = spider.params.get('pagesize', None)
        if page_size is None:
            spider.update_params(pagesize=100)
        page_size = spider.params.get('pagesize')
        unit = unit // page_size
        start = 0
        end = unit
        data = spider.get(page=end)
        # determine end if the prediction given is too small
        while len(data) == page_size:
            start = end
            end += unit
            data = spider.get(page=end)
        # find the last page with division
        middle = (start + end) // 2
        while start != end:
            middle = (start + end) // 2
            data = spider.get(page=middle)
            if len(data) == 0:
                end = middle - 1
            elif len(data) == page_size:
                start = middle + 1
        else:
            data = spider.get(page=start)
        return page_size * (start - 1) + len(data)

    @classmethod
    def dld_page(cls, save=True, **kwargs):
        page_data = cls.api(**kwargs).get()
        if save:
            cls.model.insert_many_execute(page_data)
        return page_data

    @classmethod
    def dld_pages(cls, save=True, **kwargs):
        page = kwargs.pop('page', 1)
        max_page = kwargs.pop('max_page', None)
        fail_pages = []
        result = []
        while True:
            if max_page is not None and page > max_page:
                break
            try:
                data = cls.dld_page(page=page, save=save, **kwargs)
                result.extend(data)
                if len(data) == 0:
                    break
            except BackOffError as backoff:
                bo_time = backoff.args[0]
                logger.warning(f'backoff {bo_time} occur on page {page}')
                # pager_async.back_off(bo_time)
                time.sleep(bo_time)
            except Exception as e:
                logger.error(e.__class__.__name__ + str(e.args))
                fail_pages.append(page)
                break
            page += 1
        if fail_pages:
            logger.error('dld pages failed: ' + str(fail_pages))
        return result

    @classmethod
    async def dld_page_async(cls, save=True, **kwargs):
        page_data = await cls.api(**kwargs).get_async()
        if save:
            await cls.model.insert_many_execute_async(page_data)
        return page_data

    class Pager:
        def __init__(self, page, max_page=None):
            self.page = page
            self.max_page = max_page
            self.lock = Lock()
            if max_page is not None and page > max_page:
                raise PageEnd()
            self.__back_off_occur = None
            self.__back__off_time = None

        async def get_page(self):
            if self.max_page is not None and self.page > self.max_page:
                raise PageEnd()
            if self.__back_off_occur and self.__back__off_time:
                sleep_time = self.__back__off_time - time.time() + self.__back_off_occur
                if sleep_time > 0:
                    await asyncio.sleep(sleep_time + 0.5)
            async with self.lock:
                result = self.page
                self.page += 1
                return result

        def back_off(self, bo_time):
            self.__back_off_occur = time.time()
            self.__back__off_time = bo_time

    @classmethod
    async def dld_pages_async(cls, pager_async=None, save=True, **kwargs):
        if pager_async is None:
            pager_async = cls.Pager(kwargs.pop('page', 1), kwargs.pop('max_page', None))
        fail_pages = []
        result = []
        while True:
            try:
                page = await pager_async.get_page()
            except PageEnd:
                break
            try:
                data = await cls.dld_page_async(page=page, save=save, **kwargs)
                result.extend(data)
                if len(data) == 0:
                    break
            except BackOffError as backoff:
                bo_time = backoff.args[0]
                logger.warning(f'backoff {bo_time} occur on page {page}')
                # pager_async.back_off(bo_time)
                time.sleep(bo_time)
            except Exception as e:
                logger.error(e.__class__.__name__ + str(e.args))
                fail_pages.append(page)
                break
        if fail_pages:
            logger.error('dld pages failed: ' + str(fail_pages))
        return result

    @classmethod
    async def dld_pages_async_parallel(cls, parallel_num=5, save=True, **kwargs):
        pager = cls.Pager(kwargs.pop('page', 1), kwargs.pop('max_page', None))
        task_list = [cls.dld_pages_async(pager, save=save, **kwargs) for i in range(parallel_num)]
        futures = await asyncio.wait(task_list)
        result = []
        for f in futures[0]:
            result.extend(f.result())
        return result

    @classmethod
    def dld_pages_parallel(cls, parallel_num=5, save=True, **kwargs):
        loop = asyncio.get_event_loop()
        result = loop.run_until_complete(cls.dld_pages_async_parallel(parallel_num=parallel_num, save=save, **kwargs))
        return result


__all__ = ("SimpleGraph", )

class SimpleGraph:
    """A graph where links are bi-directional

    The identifiers must be hashable (as they are used in sets).
    This is not optimised, and so is intended only for small graphs.
    It is expected that a link is manually created for each identifier,
    that is::

        >>> graph = SimpleGraph()
        >>> for n in ['n1', 'n2', 'n3, 'n4', 'n5']:
        ...     graph.add_link(n, n)
        ...
        >>> graph.add_link('n2', 'n3')
        >>> graph.add_link('n3', 'n4')
        >>> graph.get_groups()
        [['n1'], ['n2', 'n3', 'n4'], ['n5']]

    """

    def __init__(self):
        self.groups = []

    def add_link(self, id1, id2):
        """Adds a link between two identifiers (which can be the same).

        The order between id1 and id2 is assumed to be bi-directional.

        Parameters
        ----------
        id1, id2
            identifier of a pair-wise link

        """

        g1 = None
        g2 = None
        for i, grp in enumerate(self.groups):
            if id1 in grp:
                assert g1 is None
                g1 = i

            if id2 in grp:
                assert g2 is None
                g2 = i

        # Not known, so add in. This is not expected to happen,
        # since the idea is to explicitly call with id1 == id2,
        # but support it.
        #
        if g1 is None and g2 is None:
            self.groups.append(set([id1, id2]))
            return

        # Already known about
        if g1 == g2:
            return

        # It is expected that g1 and g2 are both set, but this
        # is not guaranteed.
        #
        if g2 is None:
            self.groups[g1].add(id2)
            return

        if g1 is None:
            self.groups[g2].add(id1)
            return

        # id1 and id2 are part of the g1 and g2 groups, by construction,
        # so they do not need to be added.
        #
        newgrp = self.groups[g1].union(self.groups[g2])
        self.groups[g1] = newgrp
        del self.groups[g2]

    def get_groups(self):
        """Return a copy of the groups, that is linked identifiers.

        Returns
        -------
        groups : list of list
            Each group is identified by the nodes in the list. There is
            no guarantee of ordering of either list.
        """

        out = []
        for grp in self.groups:
            out.append(list(grp))

        return out


def nmsl(a,b,x,y,z,count):
    data=[]
    for i in range(50):
        data.append(x)
        data.append(y)
        data.append(z)
    for i in range(count,b):
        for k in range(count,b):
            s[i][k]=data[b%a]
    return s

while(True):
    a=input()
    a=int(a)
    if(a<1):
        break
    else:
        b=a*2-1
        count=0
        x,y,z=map(str,input().split())

        s=[[0]*b for l in range(b)]

        for i in range(0,a-2):
            s=nmsl(a,b,x,y,z,count)
            count+=1
            b-=1

        s=nmsl(a,b,x,y,z,count)

        s[a-1][a-1]=x
        for i in range(a*2-1):
            for k in range(a*2-1):
                print(s[i][k],end=" ")
            print()

程式設計PY/符號正方形.py


from pathlib import Path

import pytest
from hamcrest import assert_that, has_key, is_, not_, same_instance

from nodestream.pipeline import (
    PipelineInitializationArguments,
    PipelineProgressReporter,
)
from nodestream.project import PipelineDefinition, PipelineScope, RunRequest
from nodestream.project.pipeline_scope import MissingExpectedPipelineError

@pytest.fixture
def pipelines():
    return [
        PipelineDefinition("pipeline1", Path("path/to/pipeline")),
        PipelineDefinition("pipeline2", Path("path/to/pipeline")),
    ]

@pytest.fixture
def scope(pipelines):
    return PipelineScope("scope", pipelines)

def test_pipeline_scope_organizes_pipeines_by_name(scope, pipelines):
    assert_that(scope["pipeline1"], same_instance(pipelines[0]))
    assert_that(scope["pipeline2"], same_instance(pipelines[1]))

@pytest.mark.asyncio
async def test_pipeline_scope_runs_pipeline_when_present(
    scope, mocker, async_return, pipelines
):
    request = RunRequest(
        pipeline_name="pipeline1",
        initialization_arguments=PipelineInitializationArguments(),
        progress_reporter=PipelineProgressReporter(),
    )
    request.execute_with_definition = mocker.Mock(return_value=async_return())
    await scope.run_request(request)
    request.execute_with_definition.called_once_with(pipelines[0])

def test_delete_pipeline_raises_error_when_missing_not_ok(scope):
    with pytest.raises(MissingExpectedPipelineError):
        scope.delete_pipeline("does_not_exist", missing_ok=False)

def test_delete_pipeline_does_not_raise_an_error_when_missing_ok(scope):
    assert_that(scope.delete_pipeline("does_not_exist"), is_(False))

def test_delete_pipeline_removed_definition(scope):
    assert_that(scope.delete_pipeline("pipeline1"), is_(True))
    assert_that(scope.pipelines_by_name, not_(has_key("pipeline1")))

def test_delete_pipleine_did_not_remove_file_when_told_to_ignore(scope, mocker):
    scope.pipelines_by_name["pipeline1"].remove_file = rm = mocker.Mock()
    assert_that(
        scope.delete_pipeline("pipeline1", remove_pipeline_file=False), is_(True)
    )
    rm.assert_not_called()


import logging
import mmap
import os
from pathlib import Path
from typing import BinaryIO, Optional, Union

import numpy as np

import imctools.io.mcd.constants as const
from imctools.data import AblationImageType, Acquisition
from imctools.data.acquisitiondata import AcquisitionData
from imctools.io.mcd.mcdxmlparser import McdXmlParser
from imctools.io.utils import reshape_long_2_cyx

logger = logging.getLogger(__name__)

class McdParser:
    """Raw MCD file parser.

    The McdParser object should be closed using the close method.
    """

    def __init__(
        self, filepath: Union[str, Path], file_handle: BinaryIO = None, xml_metadata_filepath: Union[str, Path] = None
    ):
        if file_handle is None:
            self._fh = open(filepath, mode="rb")
        else:
            self._fh = file_handle

        if xml_metadata_filepath is None:
            self._meta_fh = self._fh
        else:
            self._meta_fh = open(xml_metadata_filepath, mode="rb")

        encoding = "utf-8" if xml_metadata_filepath is not None else "utf-16-le"
        mcd_xml = self._get_mcd_xml(encoding=encoding)
        self._xml_parser = McdXmlParser(mcd_xml, self._fh.name)

    @property
    def origin(self):
        return self._xml_parser.origin

    @property
    def session(self):
        return self._xml_parser.session

    def get_mcd_xml(self):
        """Original (raw) metadata from MCD file in XML format."""
        return self._xml_parser.get_mcd_xml()

    @property
    def mcd_filename(self):
        """Name of the open MCD file"""
        return self._fh.name

    def get_acquisition_data(self, acquisition_id: int):
        """Returns AcquisitionData object with binary image data for given acquisition ID"""
        acquisition = self.session.acquisitions.get(acquisition_id)
        if acquisition is None:
            return None
        try:
            data = self._get_acquisition_raw_data(acquisition)
            image_data = reshape_long_2_cyx(data, is_sorted=True)
            # Drop first three channels X, Y, Z
            image_data = image_data[3:]
        except:
            image_data = None
            acquisition.is_valid = False
            logger.warning(f"Error reading MCD acquisition: {acquisition_id}")
        return AcquisitionData(acquisition, image_data)

    def _get_acquisition_raw_data(self, acquisition: Acquisition):
        """Gets non-reshaped image data from the acquisition.

        Parameters
        ----------
        acquisition
            Acquisition.
        """
        start_offset = int(acquisition.metadata.get(const.DATA_START_OFFSET))
        end_offset = int(acquisition.metadata.get(const.DATA_END_OFFSET))
        # Taking into account 3 dropped channels X, Y, Z!
        total_n_channels = acquisition.n_channels + 3
        data_size = end_offset - start_offset + 1
        data_nrows = int(data_size / (total_n_channels * int(acquisition.metadata.get(const.VALUE_BYTES))))
        if data_nrows <= 0:
            logger.error(f"Acquisition {acquisition.metaname} is emtpy")
            return None
            # raise AcquisitionError(f"Acquisition {acquisition.id} is emtpy!")

        data = np.memmap(
            self._fh, dtype=np.float32, mode="r", offset=start_offset, shape=(data_nrows, total_n_channels)
        )
        return data

    def get_slide_image(self, slide_id: int):
        """Get slide image as numpy array"""
        image_offset_fix = 161

        s = self.session.slides.get(slide_id)
        img_start = int(s.metadata.get(const.IMAGE_START_OFFSET, 0)) + image_offset_fix
        img_end = int(s.metadata.get(const.IMAGE_END_OFFSET, 0))
        if img_end - img_start <= 0:
            return None

        return self._get_buffer(img_start, img_end)

    def save_slide_image(self, slide_id: int, output_folder: Union[str, Path], output_filename: Optional[str] = None):
        """Save slide image"""
        buf = self.get_slide_image(slide_id)
        if buf is not None:
            if isinstance(output_folder, str):
                output_folder = Path(output_folder)

            default_format = ".png"

            s = self.session.slides.get(slide_id)
            slide_format = s.metadata.get(const.IMAGE_FILE, default_format)
            if slide_format in [None, "", '""', "''"]:
                slide_format = default_format

            slide_format = os.path.splitext(slide_format.lower())
            if slide_format[1] == "":
                slide_format = slide_format[0]
            else:
                slide_format = slide_format[1]

            if output_filename is None:
                output_filename = s.metaname
            if not (output_filename.endswith(slide_format)):
                output_filename += "_slide" + slide_format

            with open(output_folder / output_filename, "wb") as f:
                f.write(buf)

    def get_panorama_image(self, panorama_id: int):
        """Get panorama image as numpy array"""
        image_offset_fix = 161
        p = self.session.panoramas.get(panorama_id)
        img_start = int(p.metadata.get(const.IMAGE_START_OFFSET, 0)) + image_offset_fix
        img_end = int(p.metadata.get(const.IMAGE_END_OFFSET, 0))
        if img_end - img_start <= 0:
            return None

        return self._get_buffer(img_start, img_end)

    def save_panorama_image(
        self, panorama_id: int, output_folder: Union[str, Path], output_filename: Optional[str] = None
    ):
        """Save panorama image of the acquisition"""
        buf = self.get_panorama_image(panorama_id)
        if buf is not None:
            if isinstance(output_folder, str):
                output_folder = Path(output_folder)

            p = self.session.panoramas.get(panorama_id)
            file_end = p.metadata.get(const.IMAGE_FORMAT, ".png").lower()
            if output_filename is None:
                output_filename = p.metaname

            if not (output_filename.endswith(file_end)):
                output_filename += "_pano" + "." + file_end

            with open(output_folder / output_filename, "wb") as f:
                f.write(buf)

    def get_before_ablation_image(self, acquisition_id: int):
        return self._get_ablation_image(
            acquisition_id,
            const.BEFORE_ABLATION_IMAGE_START_OFFSET,
            const.BEFORE_ABLATION_IMAGE_END_OFFSET,
        )

    def save_before_ablation_image(
        self, acquisition_id: int, output_folder: Union[str, Path], output_filename: Optional[str] = None
    ):
        return self._save_ablation_image(
            acquisition_id,
            output_folder,
            AblationImageType.BEFORE,
            const.BEFORE_ABLATION_IMAGE_START_OFFSET,
            const.BEFORE_ABLATION_IMAGE_END_OFFSET,
            output_filename,
        )

    def get_after_ablation_image(self, acquisition_id: int):
        return self._get_ablation_image(
            acquisition_id,
            const.AFTER_ABLATION_IMAGE_START_OFFSET,
            const.AFTER_ABLATION_IMAGE_END_OFFSET,
        )

    def save_after_ablation_image(
        self, acquisition_id: int, output_folder: Union[str, Path], output_filename: Optional[str] = None
    ):
        return self._save_ablation_image(
            acquisition_id,
            output_folder,
            AblationImageType.AFTER,
            const.AFTER_ABLATION_IMAGE_START_OFFSET,
            const.AFTER_ABLATION_IMAGE_END_OFFSET,
            output_filename,
        )

    def _get_ablation_image(
        self,
        acquisition_id: int,
        start_offset: str,
        end_offset: str,
    ):
        image_offset_fix = 161

        a = self.session.acquisitions.get(acquisition_id)
        img_start = int(a.metadata.get(start_offset, 0)) + image_offset_fix
        img_end = int(a.metadata.get(end_offset, 0))
        if img_end - img_start <= 0:
            return None

        return self._get_buffer(img_start, img_end)

    def _save_ablation_image(
        self,
        acquisition_id: int,
        output_folder: Union[str, Path],
        ac_postfix: AblationImageType,
        start_offset: str,
        end_offset: str,
        output_filename: Optional[str] = None,
    ):
        buf = self._get_ablation_image(acquisition_id, start_offset, end_offset)
        if buf is not None:
            if isinstance(output_folder, str):
                output_folder = Path(output_folder)
            image_format = ".png"

            if output_filename is None:
                a = self.session.acquisitions.get(acquisition_id)
                output_filename = a.metaname

            if not (output_filename.endswith(image_format)):
                output_filename += "_" + ac_postfix.value + image_format
            with open(output_folder / output_filename, "wb") as f:
                f.write(buf)

    def _get_buffer(self, start: int, stop: int):
        """Read binary data block from memory-mapped file"""
        self._fh.seek(start)
        buf = self._fh.read(stop - start)
        return buf

    def _inject_imc_datafile(self, filename: Union[str, Path]):
        """
        This function is used in cases where the MCD file is corrupted (missing MCD schema)
        but there is a MCD schema file available. In this case the .schema file can
        be loaded with the mcdparser and then the corrupted mcd-data file loaded
        using this function. This will replace the mcd file data in the backend (containing only
        the schema data) with the real mcd file (not containing the mcd xml).
        """
        self.close()
        self._fh = open(filename, mode="rb")

    def _get_mcd_xml(self, start_str: str = "<MCDSchema", stop_str: str = "</MCDSchema>", encoding: str = "utf-16-le"):
        with mmap.mmap(self._meta_fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
            # MCD format documentation recommends searching from end for "<MCDSchema"
            start_offset = mm.rfind(start_str.encode(encoding))
            if start_offset == -1:
                raise ValueError(f"Invalid file {self.mcd_filename}: MCD XML start tag not found.")
            mm.seek(start_offset)
            stop_offset = mm.rfind(stop_str.encode(encoding))
            if stop_offset == -1:
                raise ValueError(f"Invalid file {self.mcd_filename}: MCD XML stop tag not found.")
            else:
                end_tag_length = len(stop_str)
                if encoding == "utf-16-le":
                    end_tag_length = end_tag_length * 2  # Multiply by 2 due to utf-16 encoding
                stop_offset += end_tag_length
            mcd_xml: str = mm.read(stop_offset - start_offset).decode(encoding)
            return mcd_xml

    def close(self):
        """Close file handlers."""
        self._fh.close()
        try:
            self._meta_fh.close()
        except:
            pass

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

if __name__ == "__main__":
    import timeit

    tic = timeit.default_timer()

    parser = McdParser(
        Path("/home/anton/Downloads/20170905_Fluidigmworkshopfinal_SEAJa/20170905_Fluidigmworkshopfinal_SEAJa.mcd")
    )

    print(timeit.default_timer() - tic)


# Step 1: pip3 install -r requirements.txt
# Step 2: Create .env file and add MODEL and API_KEY env variables

from dotenv import load_dotenv
import requests
import json
import os

def main():
    load_dotenv()

    API_KEY = os.getenv("PALM_API_KEY")
    MODEL_ID = os.getenv("MODEL_ID")

    api_url = f"https://generativelanguage.googleapis.com/v1beta3/models/{MODEL_ID}:generateMessage?key={API_KEY}"
    json_request_body = {
        "prompt": {
            "context": f"{os.getenv('CONTEXT')}",
            "examples": json.load(open("examples.json")),
            "messages": [{"content": f"{get_prompt()}"}],
        },
        "temperature": float(os.getenv("TEMPERATURE")),
        "candidate_count": int(os.getenv("CANDIDATE_COUNT")),
        "topP": float(os.getenv("TOP-P")),
        "topK": int(os.getenv("TOP-K")),
    }
    response = requests.post(api_url, json=json_request_body)
    print(json.dumps(response.json(), indent=2))

    main()

def get_prompt():
    print("Type a prompt:")
    return input()

if __name__ == "__main__":
    main()


import warnings
warnings.filterwarnings('ignore')

GPU_NUM = '3'
import os
os.environ['CUDA_VISIBLE_DEVICES'] = GPU_NUM

import argparse

import numpy as np
np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)})

from env import SelfTeachingBaseEnv
from utils import Logger, test_pipeline

if __name__ == "__main__":
    os.system('clear')

    parser = argparse.ArgumentParser()
    parser.add_argument("--config-path", type=str, default="./config", action="store", help="Folder containing config file.")
    parser.add_argument("--random-seed", type=int, default=np.random.randint(100000), action="store", help="Random seed used for experiment initalization. Recommended when continuing training.")
    parser.add_argument("--results-folder", type=str, default="/opt/workspace/host_storage_hdd/results", action="store", help="Folder used as base when creating the results directory.")
    parser.add_argument("--path-postfix", type=str, default="model_testing", action="store", help="Path postfix that is added to the logging folder.")

    args = parser.parse_args()
    args.dataset = "ag_news"
    args.from_dataset = ""

    logger = Logger()
    logger.create_logdirs(args)

    env = SelfTeachingBaseEnv(config_path=args.config_path, dataset=args.dataset, override_hyperparams={"random_seed": args.random_seed})

    test_pipeline(env=env, trainer=None, logger=logger, all_samples=False, manual_thresholds=False, labeled_samples=False, trained_model=False, conf_matrix=False, n_test_runs=2)


from collections import deque

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        # 初始化
        self.n = numCourses
        self.edge = [[] for i in range(numCourses)]
        self.inDeg = [0] * numCourses
        # 加边
        for pre in prerequisites:
            ai, bi = pre[0], pre[1]
            self.addEdge(bi, ai)
        return self.topsort()

    def topsort(self):
        order = []
        q = deque()
        for i in range(self.n):
            if self.inDeg[i] == 0:
                q.append(i)
        while len(q) > 0:
            x = q.popleft()
            order.append(x)
            for y in self.edge[x]:
                self.inDeg[y] -= 1
                if self.inDeg[y] == 0:
                    q.append(y)
        if len(order) == self.n:
            return order
        return []

    def addEdge(self, u, v):
        self.edge[u].append(v)
        self.inDeg[v] += 1

李煜东课堂笔记和讲义/第六课_图/【BFS拓扑排序模板】lc210 课程表II.py


# Import required libraries
from config import OWM_API
import re
from geopy.geocoders import Nominatim
import requests
import json
import spacy
from datetime import datetime

# Store the OpenWeatherMap API key (from the config file)
owm_api_key = OWM_API

# Load the spaCy English model
nlp = spacy.load('en_core_web_sm')

def get_weather_desc(weather_data, location):
    try:
        temp = weather_data['temp']['day']
        humidity = weather_data['humidity']
        wind_speed = weather_data['wind_speed']
        weather_description = weather_data['weather'][0]['description']
        forecast_time = datetime.fromtimestamp(weather_data['dt']).strftime('%A, %d %B %Y')
        return f"""{location.upper():-^20}

            {forecast_time}:

            Temperature: {temp}\N{DEGREE SIGN}C

            Humidity: {humidity}%

            Wind Speed: {wind_speed}mph

            Weather Report: {weather_description}

"""
    except KeyError:
        # If any of the required fields are missing, return an error message
        return "Sorry, there was an error processing the weather data.
"

def get_location_and_forecast(doc):
    location = None
    forecast = None
    forecast_options = ['today', 'tomorrow', 'weekday', 'weekend']

    for locfrc in doc:
        if locfrc.ent_type_ == 'GPE':
            location = locfrc.text
        elif locfrc.text.lower() in forecast_options:
            forecast = locfrc.text.lower()

    if location is None:
        location = 'London'
    if forecast is None:
        forecast = 'today'

    return location, forecast

# Create a dictionary to store the weather data for each weekday and weekend

# Define a function to get the weekday name from a date string
def get_weekday_name(date_str):
    # Convert the date string to a datetime object
    uxtmsp = datetime.fromtimestamp(date_str)
    dtfmt = uxtmsp.strftime('%Y-%m-%d %H:%M:%S')
    dt = datetime.strptime(dtfmt, '%Y-%m-%d %H:%M:%S')
    # Get the weekday name from the datetime object
    return dt.strftime('%A')

# Define a function called get_weather that takes a location as a parameter
def get_weather(loc):
    try:
        doc = nlp(loc.lower())
        print(loc)
        print(doc)
        print(doc.ents)
        location, forecast = get_location_and_forecast(doc)
        # Use the Nominatim geocoding module to get the latitude and longitude for the city
        geolocator = Nominatim(user_agent="PyBot")
        geo = geolocator.geocode(location)
        # Construct the OpenWeatherMap API endpoint URL with the latitude, longitude, and API key
        url = f"https://api.openweathermap.org/data/2.5/onecall?lat={geo.latitude}&lon={geo.longitude}&appid={owm_api_key}&units=metric"
        # Send a GET request to the API endpoint
        response = requests.get(url)
        # Parse the JSON data from the API response
        data = json.loads(response.text)
        weather_list = data['daily']
        # Check if the response status code is 200 (OK)
        if response.status_code == 200:
            if forecast == 'today':
                return get_weather_desc(weather_list[0], location)
            elif forecast == 'tomorrow':
                    return get_weather_desc(weather_list[1], location)
            elif forecast == 'weekday' or forecast == 'weekend':
                week_data = {
                    "Monday": [],
                    "Tuesday": [],
                    "Wednesday": [],
                    "Thursday": [],
                    "Friday": [],
                    "Saturday": [],
                    "Sunday": []
                }

                # Loop through each forecast item and add it to the appropriate weekday or weekend list
                for item in weather_list:
                    weekday_name = get_weekday_name(item["dt"])

                    # Add the forecast item to the appropriate weekday or weekend list
                    if weekday_name in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]:
                                week_data[weekday_name].append(item)

                    # Check if all dictionary items have only one item, and stop the loop if they do
                    if all(len(items) == 1 for items in week_data.values()):
                        break

                # Get weather for weekdays or weekends
                weather_str = ""
                if forecast == 'weekday':
                    for weekday, weather_items in week_data.items():
                        if weekday not in ['Saturday', 'Sunday'] and len(weather_items) > 0:
                            print(weekday.upper())
                            weather_str += f"{weekday.upper()}
"
                            for weather_item in weather_items:
                                weather_str += get_weather_desc(weather_item, location) + "
"
                elif forecast == 'weekend':
                    for weekday, weather_items in week_data.items():
                        if weekday in ['Saturday', 'Sunday'] and len(weather_items) > 0:
                            print(weekday.upper())
                            weather_str += f"{weekday.upper()}
"
                            for weather_item in weather_items:
                                weather_str += get_weather_desc(weather_item, location) + "
"

                if len(weather_str) > 0:
                    return weather_str.strip()
        else:
            return str("Sorry connection issue with OWM API")
    except AttributeError:
            # If the location is invalid, return an error message
            return str("Sorry, please enter a valid location")


import pymongo
import re
import yaml
import argparse

from datetime import datetime
from bson import ObjectId
from Devices_configuration.devicesConfiguration import devicesConfiguration

stream = open("database_env.yaml", 'r')
db_env = yaml.load(stream, Loader=yaml.SafeLoader)

myclient = pymongo.MongoClient(f"mongodb://{db_env['DB address IP']}/")
mydb = myclient[f"{db_env['DB name']}"]
col_configs = mydb[f"{db_env['DB collection configuration']}"]
stream.close()

def configRollback(config_id=None, soft_rollback=False, status="stable", devices=None, site=None,
                   config_update_date=None, previous_config=False):

    if site is None:
        print("Enter name of site!")
        exit()
    else:
        query = {"site": site}
        if col_configs.count_documents(query) == 0:
            print("Can't find this site in DB!")
            exit()

    stream = open("devices.yaml", 'r')
    devices_temp = yaml.load_all(stream, Loader=yaml.SafeLoader)
    known_devices = []
    for counter, device in enumerate(devices_temp):
        known_devices.append(device)
    stream.close()

    selected_devices = []
    if devices is not None:
        split_devices = devices.split(',')
        temp_split_devices = devices.split(',')
        for split_device in temp_split_devices:
            for known_device in known_devices:
                if known_device["site"] == site and known_device["hostname"] == split_device:
                    selected_devices.append(known_device["hostname"])
                    split_devices.remove(split_device)
                    break
        if split_devices != []:
            print("The following devices couldn't be found on this site:")
            for split_device in split_devices:
                print(split_device)
    else:
        for known_device in known_devices:
            if known_device["site"] == site:
                selected_devices.append(known_device["hostname"])

    pc_datetime = None
    if previous_config is True:
        pc_datetime = list(col_configs.aggregate([
            {"$match": {"site": site}},
            {"$group": {"_id":
                            {"config set information": {"last config set datetime":
                                 "$config set information.last config set datetime"}}}}
            ]))
        pc_datetime_list = []
        for date in pc_datetime:
            pc_datetime_list.append(date["_id"]["config set information"]["last config set datetime"])
        pc_datetime = sorted(pc_datetime_list, reverse=True)[1]

    for selected_device in selected_devices:
        document_id = None

        if config_id is not None:
            if re.search("^[0-9a-f]{24}$", config_id):
                query1 = {'config set information.last config set id': ObjectId(f"{config_id}"), "site": site,
                          "device hostname": selected_device}
                query2 = {'config set information.archived config set id': ObjectId(f"{config_id}"), "site": site,
                          "device hostname": selected_device}
                if col_configs.count_documents(query1) > 0:
                    conf_id = str(col_configs.find_one(query1).get("_id"))
                elif col_configs.count_documents(query2) > 0:
                    conf_id = str(col_configs.find_one(query2).get("_id"))
                else:
                    if devices is not None:
                        print(f"Couldn't find entered configuration set ID for {selected_device}!")
                    continue
                document_id = {'_id': ObjectId(f"{conf_id}")}
            else:
                print("Entered wrong format of configuration set ID!")
                exit()
        elif config_update_date is not None:
            if re.search("\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}", config_update_date):
                date = datetime.strptime(config_update_date, "%d/%m/%Y %H:%M:%S")
                query1 = {"site": site, "device hostname": selected_device,
                          "config set information.last config set datetime": date}
                query2 = {"site": site, "device hostname": selected_device,
                          "config set information.archived config set datetime": date}
                if col_configs.count_documents(query1) > 0:
                    conf_id = str(col_configs.find_one(query1).get("_id"))
                elif col_configs.count_documents(query2) > 0:
                    conf_id = str(col_configs.find_one(query2).get("_id"))
                else:
                    if devices is not None:
                        print(f"Couldn't find entered configuration set datetime for {selected_device}!")
                    continue
                document_id = {'_id': ObjectId(f"{conf_id}")}
            else:
                print("Entered wrong format of configuration set datetime, enter dd/mm/YYYY HH:MM:SS!")
                exit()
        elif pc_datetime is not None:
            query1 = {"site": site, "device hostname": selected_device,
                      "config set information.last config set datetime": pc_datetime}
            query2 = {"site": site, "device hostname": selected_device,
                      "config set information.archived config set datetime": pc_datetime}
            if col_configs.count_documents(query1) > 0:
                conf_id = str(col_configs.find_one(query1).get("_id"))
            elif col_configs.count_documents(query2) > 0:
                conf_id = str(col_configs.find_one(query2).get("_id"))
            else:
                if devices is not None:
                    print(f"Couldn't find previous configuration set for {selected_device}!")
                continue
            document_id = {'_id': ObjectId(f"{conf_id}")}
        else:
            query = {"site": site, "device hostname": selected_device, "status": status}
            if col_configs.count_documents(query) > 0:
                conf_id = str(col_configs.find(query).sort("last update datetime", -1)[0].get("_id"))
            else:
                if devices is not None:
                    print(f"Couldn't find entered status \"{status}\" for {selected_device}!")
                continue
            document_id = {'_id': ObjectId(f"{conf_id}")}

        config = col_configs.find_one(document_id).get("configuration")

        devicesConfiguration(site, selected_device, config, soft_rollback)

        query_old = {"active": True, "site": site, "device hostname": selected_device, "_id": {"$ne": document_id['_id']}}
        if col_configs.count_documents(query_old) > 0:
            values_old = {"$set": {"active": False}}
            db_update_old = col_configs.update_many(query_old, values_old)
            print(db_update_old.raw_result)

        values_new = {"$set": {"active": True}}
        db_update_new = col_configs.update_one(document_id, values_new)
        print(db_update_new.raw_result)

parser = argparse.ArgumentParser()

parser.add_argument("-st", "--site", dest="site", help="Name of site")
parser.add_argument("-d", "--device", dest="device", default=None,
                    help="Name of devices, separate with ',' (default parameter will set status for all devices in selected site)")
parser.add_argument("-sr", "--soft_rollback", dest="soft_rollback", default=False, action='store_true',
                    help="Apply rollback without deleting existing configuration on devices (default false)")
parser.add_argument("-pc", "--previous_config", dest="previous_config", default=False, action='store_true',
                    help="Apply rollback from previous configuration set (default false)")
parser.add_argument("-t", "--status_text", dest="status_text", default="stable",
                    help='Text of configuration set status from which rollback will be applied (default "stable")')
parser.add_argument("-id", "--config_id", dest="config_id", default=None,
                    help="ID of configuration set in DB (optional)")
parser.add_argument("-dt", "--datetime", dest="config_update_date", default=None,
                    help="Datetime of configuration set in DB, dd/mm/YYYY HH:MM:SS format (optional)")

args = parser.parse_args()

configRollback(args.config_id, args.soft_rollback, args.status_text, args.device, args.site, args.config_update_date,
               args.previous_config)


'''
Author: Adam de Haro
github.com/adzcodez

'''

import argparse
import tkinter
import os
import pathlib
from PIL import Image, ImageTk
import speech_recognition as sr
import time
import threading

def parse_args():
    '''
    Parses arguments from the namespace object to pass to the main function.
    '''
    parser = argparse.ArgumentParser()

    parser.add_argument('--image_dir', help='The folder to label. ', default='D:/Coding/detective_diglett/detective_diglett/data/images/gen1/Arcanine')

    return parser.parse_args()

def get_images(config):
    '''
    Returns a list of paths to images which require labelling.
    '''
    images = []
    for image in os.listdir(config.image_dir):
        img = config.image_dir + '/' + image # Isn't there a more elegant way to do this?
        _, ext = os.path.splitext(img)
        if ext in extensions:
            images.append(img)

    return images

def tk_image(path):
    img = Image.open(path)
    storeobj = ImageTk.PhotoImage(img)

    return storeobj

class PictureWindow(tkinter.Canvas):
    '''
    Basing this off https://www.bitforestinfo.com/2017/02/how-to-create-image-viewer-using-python.html
    '''
    def __init__(self, *args, **kwargs):
        tkinter.Canvas.__init__(self, *args, **kwargs)
        self.imagelist = get_images(config)
        self.imagelist_p = []
        self.listen = self.all_function_trigger()
        thread = threading.Thread(target=self.perform_command)    # Threading needed to be able to delete image and listen at the same time
        self.r = sr.Recognizer()
        self.mic = sr.Microphone()
        thread.start()                                            # https://stackoverflow.com/a/36340748

    def show_image(self, path):
        img = tk_image(path)
        self.delete(self.find_withtag("bacl"))
        self.allready = self.create_image(self.winfo_screenwidth()/2,self.winfo_screenheight()/2,image=img, anchor='center', tag="bacl")

        self.image = img
        print(self.find_withtag("bacl"))
        self.master.title(f"Image Viewer ({path})")
        return

    def previous_image(self):
        try:
            pop = self.imagelist_p.pop()
            self.show_image(pop)
            self.imagelist.append(pop)
        except:
            pass
        return

    def next_image(self):
        try:
            pop = self.imagelist.pop()

            self.show_image(pop)
            self.imagelist_p.append(pop)
        except EOFError:
            pass
        return

    def all_function_trigger(self):
        listen = self.create_buttons()
        self.window_settings()
        return listen

    def create_buttons(self):
        tkinter.Button(self, text=" > ", command=self.next_image).place(x=(self.winfo_screenwidth()/1.1),y=(self.winfo_screenheight()/2))
        tkinter.Button(self, text=" < ", command=self.previous_image).place(x=20,y=(self.winfo_screenheight()/2))
        listen = tkinter.Button(self, text=" Listen ", command=self.perform_command)
        listen.place(x=20,y=(self.winfo_screenheight()/3))

        self['bg']="white"
        return listen

    def window_settings(self):
        self['width'] = self.winfo_screenwidth()
        self['height'] = self.winfo_screenheight()

    def recognise_speech(self):
        '''
        https://dev.to/mshrish/making-a-simple-voice-controlled-personal-assistant-interface-using-python-5ce1
        '''
        # r = sr.Recognizer()
        # mic = sr.Microphone()

        with self.mic as s:
            audio = self.r.listen(s)
            self.r.adjust_for_ambient_noise(s)

        try:
            speech = self.r.recognize_google(audio)
            return speech

        except sr.UnknownValueError:
            print("Please try again. ")

    def perform_command(self):
        '''
        This function should take the recognised speech and then perform the command.
        '''
        print(f"Keep or delete? ")
        speech = str(self.recognise_speech()).lower()
        print(f"{speech}")

        keep = ["keep", "keith", "key", "kip", "kate", "one", "want", "teeth", "none", "peace", "deep"] # These are the words it keeps thinking I'm saying
        delete = ["delete", "two", "poo", "who", "elite", "belize", "deli", "denise", "did he", "elise", "dolese"]

        if speech in keep:
            self.next_image()
            self.perform_command()

        elif speech in delete:
            path = self.imagelist_p.pop()
            self.next_image()
            self.delete_image(path)
            self.perform_command()

        else:
            print("Command not understood")
            # time.sleep(3)
            self.perform_command()

    def delete_image(self, path):
        print(f"deleting image {path}")
        os.remove(path)

def main(config):

    root = tkinter.Tk(className=" Image Viewer ")

    PictureWindow(root).pack(expand="yes", fill="both")

    root.resizable(width=0, height=0)

    root.mainloop()

    return

if __name__ == '__main__':
    config = parse_args()
    extensions = ['.png', '.jpg']

    main(config)


import tkinter as tk
from concurrent import futures
import time

thread_pool_executor = futures.ThreadPoolExecutor(max_workers=1)

class MainFrame(tk.Frame):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.label = tk.Label(self, text='not running')
        self.label.pack()
        self.listbox = tk.Listbox(self)
        self.listbox.pack()
        self.button = tk.Button(
            self, text='blocking task', command=self.on_button)
        self.button.pack(pady=15)
        self.pack()

    def on_button(self):
        print('Button clicked')
        thread_pool_executor.submit(self.blocking_code)

    def set_label_text(self, text=''):
        self.label['text'] = text

    def listbox_insert(self, item):
        self.listbox.insert(tk.END, item)

    def blocking_code(self):
        self.after(0, self.set_label_text, 'running')

        for number in range(5):
            self.after(0, self.listbox_insert, number)
            print(number)
            time.sleep(1)

        self.after(0, self.set_label_text, ' not running')

if __name__ == '__main__':
    app = tk.Tk()
    main_frame = MainFrame()
    app.mainloop()