import torch
from torch import nn
from torch.nn import init
from torchvision.datasets import FashionMNIST
import numpy as np
import sys
from torch.utils.data import DataLoader
from torchvision import transforms

'''
1、数据加载
2、权重初始化、数据预处理 分割 裁剪
3、loss函数定义
4、准确度估计

torchvision.datasets: 一些加载数据的函数及常用的数据集接口；

torchvision.models: 包含常用的模型结构(含预训练模型)，例如AlexNet、VGG、ResNet等；

torchvision.transforms: 常用的图片变换，例如裁剪、旋转等；

torchvision.utils: 其他的一些有用的方法

解释方法含义：

1、dataset：提前定义的dataset的实例；
2、batch_size：传入数据的batch大小，常常是32、64、128、256’
3、shuffle：bool类型，表示是否在每次获取数据的时候提前打乱数据；
4、num_workers：加载数据的线程数。
5、drop_last：bool类型，为真，表示最后的数据不足一个batch，就删掉

'''

root_train =r'D:\4_data\1_DataSet\Minist\FashionMNIST\FashionMNIST\raw\train-images-idx3-ubyte.gz'
root_test =r'D:\4_data\1_DataSet\Minist\FashionMNIST\FashionMNIST\raw\t10k-images-idx3-ubyte.gz'

batch_size =256
mnist_train =FashionMNIST(root=r'D:\4_data\1_DataSet\Minist\FashionMNIST',train=True, download=False, transform=transforms.ToTensor())
mnist_test = FashionMNIST(root=r'D:\4_data\1_DataSet\Minist\FashionMNIST',train=False, download=False, transform=transforms.ToTensor())
train_iter =DataLoader(mnist_train,batch_size=256,shuffle=True)
test_iter =DataLoader(mnist_test,batch_size=256,shuffle=False)
# print(train_iter)
# print(test_iter)

#3.6.2 初始化模型参数
num_inputs = 784
num_outputs = 10#10个类

W = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_outputs)), dtype=torch.float)
b = torch.zeros(num_outputs, dtype=torch.float)#相当于没有偏置

#同之前一样，我们需要模型参数梯度。
W.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)

X =torch.tensor([[1,2,3],[4,5,6]])
print(X.sum(dim =0,keepdim=True))#dim=0是列  dim=1是行
print(X.sum(dim =1,keepdim=True))

#开始定义softmax运算
'''
我们先描述一下如何对多维的tensor按维度操作
给定一个tensor矩阵x。

我们可以只对其中同一列（dim=0）或者同一行（dim=1）的元素求和，

并在结果中保留行和列这两个维度（keepdim=True）
'''
def softmax(m):
    '''
    输入一个tensor 对每一行的数据做softmax归一化处理
    :param m:
    :return:
    '''
    X_exp =m.exp()# 这是一个矩阵     输入的每一个值都做指数处理
    partition =X_exp.sum(dim=1,keepdim =True)#对行做softmax
    return X_exp/partition#对每一个值做了归一化处理

# X = torch.rand((2, 5))
# X_prob = softmax(X)
# print(X_prob, X_prob.sum(dim=1))

#定义模型（调用softmax算损失）
def net(X):
    return softmax(torch.mm(X.view(-1,num_inputs),W)+b)

#定义损失函数
'''为了得到标签的预测概率 我们使用gather函数

y_hat是在2个样本 在三个类别的预测概率
y是两个样本的实际标签

在代码中，标签类别的离散值是从0开始逐一递增的。
'''
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y = torch.LongTensor([0, 2])#向量 或者列表
print('\n查看一下功能')
print(y)
y_hat.gather(1, y.view(-1, 1))

#计算分类准确度

'''
给定一个类别的-----预测概率分布y-hat ------我们把预测概率-----------最大的类别-----------作为输出类别
如果预测的值和真实值一致 则说明预测正确 否则预测错误

----
其中y_hat.argmax(dim=1)返回矩阵y_hat每行中最大元素的索引，且返回结果与变量y形状相同。argmax返回最大值index
----
相等条件判断式(y_hat.argmax(dim=1) == y)是一个类型为ByteTensor的Tensor，我们用float()将其转换为值为0（相等为假）或1（相等为真）的浮点型Tensor
'''
def accuracy(y_hat, y):
    return (y_hat.argmax(dim=1) == y).float().mean().item()
print(accuracy(y_hat, y))

# 本函数已保存在d2lzh_pytorch包中方便以后使用。该函数将被逐步改进：它的完整实现将在“图像增广”一节中描述
def evaluate_accuracy(data_iter, net):
    acc_sum, n = 0.0, 0
    for X, y in data_iter:
        acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
        n += y.shape[0]
    return acc_sum / n

print(evaluate_accuracy(test_iter, net))

# num_epochs, lr = 5, 0.1
#
# # 本函数已保存在d2lzh包中方便以后使用
# def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
#               params=None, lr=None, optimizer=None):
#     for epoch in range(num_epochs):
#         train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
#         for X, y in train_iter:
#             y_hat = net(X)
#             l = loss(y_hat, y).sum()
#
#             # 梯度清零
#             if optimizer is not None:
#                 optimizer.zero_grad()
#             elif params is not None and params[0].grad is not None:
#                 for param in params:
#                     param.grad.data.zero_()
#
#             l.backward()
#             if optimizer is None:
#                 d2l.sgd(params, lr, batch_size)
#             else:
#                 optimizer.step()  # “softmax回归的简洁实现”一节将用到
#
#
#             train_l_sum += l.item()
#             train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
#             n += y.shape[0]
#         test_acc = evaluate_accuracy(test_iter, net)
#         print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
#               % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
#
# train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, batch_size, [W, b], lr)


"""
840. Magic Squares In Grid
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, and both diagonals all have the same sum.

Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).

Example1:
Input: grid = [
    [4,3,8,4],
    [9,5,1,9],
    [2,7,6,2]
]
Output: 1

Example2:
Input: grid = [[8]]
Output: 0

Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
"""

"""
Note:
1. Brute Force: O(nm) time | O(1) space
2. Magic Order: O(nm) time | O(1) space
ref: https://leetcode.com/problems/magic-squares-in-grid/discuss/133874/Python-5-and-43816729
(1) The center of magic square must be 5.
(2) The even must be in the corner, and the odd must be on the edge.
(3) it must be in a order like "43816729" （clockwise or anticlockwise)
"""

from typing import List
class Solution:
    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        total = 0
        for row in range(rows-2):
            for col in range(cols-2):
                if self.isMagicSquare(row, col, grid):
                    total += 1
        return total

    def isMagicSquare(self, row, col, grid) -> bool:
        squareSet = set()
        for r in range(row, row+3):
            for c in range(col, col+3):
                squareSet.add(grid[r][c])
        if squareSet != {i for i in range(1, 9+1)}:
            return False

        for i in range(row, row+3):
            if sum(grid[i][col:col+3]) != 15:
                return False

        for j in range(col, col+3):
            colSum = 0
            for i in range(row, row+3):
                colSum += grid[i][j]
            if colSum != 15:
                return False

        if sum([grid[row][col], grid[row+1][col+1], grid[row+2][col+2]]) != 15:
            return False
        if sum([grid[row][col+2], grid[row+1][col+1], grid[row+2][col]]) != 15:
            return False
        return True

    def numMagicSquaresInside2(self, grid: List[List[int]]) -> int:
        def isMagicSquare(row, col):
            s = "".join(str(grid[row+x//3][col+x%3]) for x in [0, 1, 2, 5, 8, 7, 6, 3])
            return grid[row][col] % 2 == 0 and (s in "43816729" * 2 or s in "43816729"[::-1] * 2)

        rows, cols = len(grid), len(grid[0])
        total = 0
        for row in range(rows-2):
            for col in range(cols-2):
                if isMagicSquare(row, col) and grid[row+1][col+1] == 5:
                    total += 1
        return total

# Unit Tests
import unittest
funcs = [Solution().numMagicSquaresInside, Solution().numMagicSquaresInside2]

class TestNumMagicSquaresInside(unittest.TestCase):
    def testNumMagicSquaresInside1(self):
        for func in funcs:
            grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
            self.assertEqual(func(grid=grid), 1)

    def testNumMagicSquaresInside2(self):
        for func in funcs:
            grid = [[8]]
            self.assertEqual(func(grid=grid), 0)

    def testNumMagicSquaresInside3(self):
        for func in funcs:
            grid = [[5,5,5],[5,5,5],[5,5,5]]
            self.assertEqual(func(grid=grid), 0)

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


#!/usr/bin/env python

# TODO: search
# - https://docs.python.org/3/library/json.html
# - https://docs.python.org/3/library/urllib.request.html#module-urllib.request

import json
import os
import sys
import urllib.parse as parse
import urllib.request as req
from urllib.error import HTTPError

from colorama import Fore, Back, Style

url = 'http://www.python.org/'

# with req.urlopen(url) as f:
#    print(f.read(300).decode('utf-8'))

# f = req.urlopen(url= url)
# print(f.read().decode('utf-8'))

# TODO: continuar daqui..
# 1- https://www.google.com/search?q=python+use+config+file&rlz=1C1SQJL_enBR856BR856&oq=python+use+config+file&aqs=chrome..69i57.6758j0j7&sourceid=chrome&ie=UTF-8
# 2- yaml file
# https://martin-thoma.com/configuration-files-in-python/
# 3- configparser
# https://docs.python.org/3.4/library/configparser.html

class Board:

    def __init__(self, idBoard):
        self.idBoard = idBoard

    def get_lists(self):
        if self.lists is None:
            self.lists = get_lists_from_board(self.idBoard)
        return self.lists

class TrelloConfig:
    def __init__(self):

        try:
            self.idBoard = os.environ.get('TRELLO_BOARD')
            self.key = os.environ.get('TRELLO_KEY')
            self.token = os.environ.get('TRELLO_TOKEN')

            assert (self.idBoard is not None), "idBoard environment variable is missing."
            assert (self.key is not None), "key environment variable is missing."
            assert (self.token is not None), "token environment variable is missing."

        except Exception as ex:
            message_red_style(f"Something went wrong when reading environment variables. Error: {ex}")
            sys.exit()

    def __repr__(self):
        return repr((self.idBoard, self.key, self.token))

class ResponseApi:
    def __init__(self, json, status, reason):
        self.json = json
        self.status = status
        self.reason = reason

    def __repr__(self):
        return repr((self.json, self.status, self.reason))

def message_red_style(text):
    print('\n' + Back.RED + Fore.LIGHTWHITE_EX +
          text +
          Style.RESET_ALL)

def message_warning_style(text):
    print('\n' + Back.LIGHTYELLOW_EX + Fore.BLACK +
          text +
          Style.RESET_ALL)

def message_green_style(text):
    print('\n' + Back.LIGHTGREEN_EX + Fore.BLACK +
          text +
          Style.RESET_ALL)

def get_json_from_api(api_url, method):

    try:

        f = req.Request(url=api_url, data=None, method=method)

        with req.urlopen(f) as ff:
            json_data_file = ff.read().decode('utf-8')
            return ResponseApi(json.loads(json_data_file), ff.status, ff.reason)
    except HTTPError as ht:
        print('Error:', ht)
        print('Sorry, something wrong happens.')
        sys.exit()

    return None

def find_pr_in_trello(data_to_search, key, token, idBoard):
    trello_api = f'https://api.trello.com/1/search?query={parse.quote(data_to_search)}&idBoards={idBoard}&modelTypes=all&board_fields=name%2CidOrganization&boards_limit=10&card_fields=all&cards_limit=10&cards_page=0&card_board=true&card_list=false&card_members=false&card_stickers=false&card_attachments=false&organization_fields=name%2CdisplayName&organizations_limit=10&member_fields=avatarHash%2CfullName%2Cinitials%2Cusername%2Cconfirmed&members_limit=10&partial=false&key={key}&token={token}'

    response = get_json_from_api(trello_api, 'GET')

    assert (response is not None), 'Sorry, we could not found your PR number in trello, try again.'
    assert (response.status == 200), message_warning_style(
        'Sorry, there is something wrong with trello api, please try again.')

    if len(response.json['cards']) > 0:
        message_green_style('Good, pr founded in trello board.')

        firstCard = response.json['cards'][0]

        idCard = firstCard['id']
        idList = firstCard['idList']

        listName = get_name_of_list_from_card(idList, idBoard)

        print('> Id\t\t\t:', idCard)
        print('> Name\t\t\t:', firstCard['name'])
        print('> Actual List\t:', listName)

        answer = input('\nIs it your trello\'s card? (Y/N): ')

        if answer.lower() == 'n':
            message_red_style('bye, see you again...')
            sys.exit()
        move_pr_trello(idCard, key, token, idBoard)

def get_valid_numeric_option(max):
    number_template = -1
    while number_template < 0 or number_template > max:
        try:
            number_template = int(input('> '))
        except ValueError as ve:
            print(f'Error: {ve}. Try again...')

    return number_template

def get_lists_from_board(idBoard):
    trello_lists_board_api = f'https://api.trello.com/1/boards/{idBoard}/?fields=name&lists=all&list_fields=all'

    response = get_json_from_api(trello_lists_board_api, 'GET')

    if response is not None and len(response.json['lists']) > 0:
        return response.json['lists']
    return None

def get_name_of_list_from_card(idList, idBoard):
    lists_from_board = get_lists_from_board(idBoard)

    for row in lists_from_board:
        if row['id'] == idList:
            return row['name']
    return None

def move_pr_trello(trello_card_id, key, token, idBoard):
    jsonLists = get_lists_from_board(idBoard)

    total = len(jsonLists)

    print('\nWhich list do you wanna move?')
    for t in range(total):
        print(f"> {t} - {jsonLists[t]['name']} - {jsonLists[t]['id']}")

    choosedNumber = get_valid_numeric_option(total)

    id_list_to_move = jsonLists[choosedNumber]['id']
    name_list_to_move = jsonLists[choosedNumber]['name']

    trello_update_card_api = f'https://api.trello.com/1/cards/{trello_card_id}?idList={id_list_to_move}&key={key}&token={token}'

    response = get_json_from_api(trello_update_card_api, 'PUT')

    assert (response.status == 200), message_red_style('Something wrong happens when moving card...')

    message_warning_style(f'moving card to {name_list_to_move}...')

    new_post = f'AUTOMATICO: Movendo card para {name_list_to_move}'

    trello_add_new_comment = f'https://api.trello.com/1/cards/{trello_card_id}/actions/comments?text={parse.quote(new_post)}&&key={key}&token={token}'
    response = get_json_from_api(trello_add_new_comment, 'POST')

    assert (response.status == 200), message_red_style('Something wrong happens when adding a new comment...')

    message_warning_style('adding new comment...')

def main(use_args):
    pr = 0

    # args
    if use_args:

        total_args = len(sys.argv)
        if total_args == 1:
            print('COMMAND arg1; arg1=pr number;')
            sys.exit()

        pr = sys.argv[1]

    config = TrelloConfig()
    find_pr_in_trello(str(pr), config.key, config.token, config.idBoard)

if __name__ == "__main__":
    try:
        main(use_args=True)
    except Exception as ex:
        print('Error:', ex)
    except:
        pass


import typing
import weakref
from collections import defaultdict

class BaseClass:

    __refs = defaultdict(list)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__refs[self.__class__].append(self)

    @classmethod
    def instances(cls) -> typing.List:
        for instance in cls.__refs.get(cls, []):
            yield instance

class BaseClassWeakRef:

    __refs = defaultdict(list)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__refs[self.__class__].append(weakref.ref(self))

    @classmethod
    def instances(cls) -> typing.List:
        for instance_ref in cls.__refs.get(cls, []):
            instance = instance_ref()
            if instance is not None:
                yield instance


#coding: utf-8

#本程序用于显示数据清理和流重组后的数据

import sys
from window_base import *
from PyQt5.QtWidgets import QAbstractItemView, QHeaderView
from PyQt5.QtGui import QFont

class show_Dataclustering_Window(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(show_Dataclustering_Window, self).__init__()
        super().setupUi(self)

        # 设置垂直布局
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        # 设置水平布局
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        # 表格控件
        self.tableView = QtWidgets.QTableView(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 20, 1001, 421))
        self.tableView.setObjectName("tableView")
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格内容不可更改
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选中的方式
            # 下面代码让表格100填满窗口
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            # 设置表格控件的缩放比
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth())
        #sizePolicy.setHorizontalStretch(4)
        #sizePolicy.setVerticalStretch(3)
        self.tableView.setSizePolicy(sizePolicy)
            # 加入布局
        self.verticalLayout.addWidget(self.tableView)

        # 文本控件1
        self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser.setObjectName("textBrowser")
            # 设置文本控件的缩放比
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHeightForWidth(self.textBrowser.sizePolicy().hasHeightForWidth())
        #sizePolicy.setHorizontalStretch(1)
        #sizePolicy.setVerticalStretch(1)
        self.textBrowser.setSizePolicy(sizePolicy)
        self.textBrowser.setFont(QFont('SansSerif', 15))
            # 加入布局
        self.horizontalLayout.addWidget(self.textBrowser)

        # 文本控件2
        self.textBrowser2 = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser2.setObjectName("textBrowser")
            # 设置文本控件的缩放比
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHeightForWidth(self.textBrowser2.sizePolicy().hasHeightForWidth())
        #sizePolicy.setHorizontalStretch(1)
        #sizePolicy.setVerticalStretch(1)
        self.textBrowser2.setSizePolicy(sizePolicy)
        self.textBrowser2.setFont(QFont('SansSerif', 15))
            # 加入布局
        self.horizontalLayout.addWidget(self.textBrowser2)

        # 水平布局加入垂直布局中
        self.verticalLayout.addLayout(self.horizontalLayout)
        # 布局初始化
        self.setCentralWidget(self.centralwidget)

        # 加载事件
        self.action_event()

        super().createUi(self)

    def tableView_set(self):
        # 添加表头：
        self.model = QtGui.QStandardItemModel(self.tableView)
        # 设置表头
        self.model.setHorizontalHeaderLabels([ '簇标记', '完整性', '源IP', '目的IP', '源端口', '目的端口',  '流长度', '流数据'])

        clustering_num = 0 # 用于记录簇标记
        row = 0            # 用于记录行数
        # color初始化
        color = QtGui.QColor(0, 0, 0)
        num = 0
        # 遍历簇类
        for clusters_data in self.Packet_clustering.items():
            len_cluster = len(clusters_data[1])
            # 遍历同簇流数据
            for i in range(0,len_cluster):   # range取头不取尾
                # 遍历流数据，tableview列数比clusters_data[i]长度多1，
                for j in range(1,8):
                    self.model.setItem(row, 0, QtGui.QStandardItem(str(clustering_num)))
                    # 设置字符颜色
                    self.model.item(row, 0).setForeground(QtGui.QBrush(color))
                    # 设置字符位置
                    self.model.item(row, 0).setTextAlignment(QtCore.Qt.AlignCenter)

                    self.model.setItem(row, j, QtGui.QStandardItem(clusters_data[1][i][j-1]))
                    # 设置字符颜色
                    self.model.item(row, j).setForeground(QtGui.QBrush(color))
                    # 设置字符位置
                    self.model.item(row, j).setTextAlignment(QtCore.Qt.AlignCenter)
                row += 1
            # 不同簇采用不同的颜色区分
            if num == 0:
                # 绿
                color = QtGui.QColor(50, 255, 50)
                num += 1
            elif num == 1:
                # 蓝
                color = QtGui.QColor(50, 50, 255)
                num += 1
            elif num == 2:
                # 红
                color = QtGui.QColor(255, 50, 50)
                num +=1
            else:
                # 黑
                color = QtGui.QColor(0, 0, 0)
                num = 0
            # 簇标记更新
            clustering_num += 1

        # 显示数据
        self.tableView.setModel(self.model)

    def action_event(self):
        # 设置表格点击事件
        self.tableView.clicked['QModelIndex'].connect(self.textBrowser_set)
        pass

    def textBrowser_set(self):
        indexs = self.tableView.currentIndex()
        text = self.model.item(indexs.row(), 7).text()
        self.textBrowser.clear()
        self.textBrowser2.clear()
        self.textBrowser.insertPlainText(text)
        self.textBrowser2.insertPlainText(text.encode(encoding='utf-8', errors='ignore').hex())


import argparse
from pathlib import Path

import numpy as np
from matplotlib import pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix, f1_score

from models.hmm.facial_movement import ordinal_from_csv
from models.hmm.prediction_visualisation import load_predictions
from models.hmm.test_hmm import predict_hmm
from models.hmm.train_hmm import fit_hmms
from models.simple.memory_detector import MemoryBasedShakeDetector
from models.simple.random_detector import RandomShakeDetector
from models.simple.rule_detector import RuleBasedShakeDetector, majority_vote
from utils.draw import set_seaborn_theme
from utils.frames_csv import get_splits, load_df, load_all_labels
from utils.io import mkdir_if_not_exists
from validation.event_based import evaluate_events
from models.hmm.filters import majority_filter

def hmm_filter_search(frames_csv,
                      folds_dir,
                      results_dir,
                      method='event',
                      metric='f1'):
    # sizes = [3, 7, 11, 15, 19, 23, 27, 31, 35, 39]
    # sizes = [11, 21, 31, 41, 51, 61, 71, 81, 91, 101]
    sizes = [11, 51, 101, 151, 201]
    results = []

    for size in sizes:
        results.append(validate_hmm_folds(frames_csv,
                                          folds_dir,
                                          filter_size=size,
                                          window_size=36,
                                          method=method,
                                          metric=metric,
                                          results_dir=results_dir,
                                          load_previous=True))

    set_seaborn_theme()
    plt.title('F1 score for head-shake detector on different filter sizes', fontsize=15)
    plt.locator_params(axis='x', nbins=10)
    plt.plot(sizes, results, 'o-')
    plt.xticks(sizes, sizes)
    plt.xlabel('Filter size (frames)')
    plt.ylabel('F1 score')
    plt.show()

def hmm_window_search(frames_csv,
                      folds_dir,
                      method='frame',
                      metric='f1'):
    sizes = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
    labels = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
    results = []

    for size in sizes:
        results.append(validate_hmm_folds(frames_csv, folds_dir, window_size=size, method=method, metric=metric))

    set_seaborn_theme()
    plt.title('F1 score for head-shake detector on different window sizes', fontsize=15)
    plt.locator_params(axis='x', nbins=10)
    plt.plot(sizes, results, 'o-')
    plt.xticks(sizes, labels)
    plt.xlabel('Window size (seconds)')
    plt.ylabel('F1 score')
    plt.show()

def validate_hmm_folds(frames_csv,
                       folds_dir,
                       window_size=36,
                       results_dir=None,
                       filter_size=None,
                       method='frame',
                       load_previous=False,
                       metric=None):
    print(f'Loading samples from {frames_csv}')
    df_frames = load_df(frames_csv)
    splits = get_splits(df_frames)
    all_predictions = []
    label_index = 0

    if metric == 'f1':
        all_labels = []

    if load_previous:
        all_predictions = load_predictions(results_dir/'predictions.npz')

    matrix = np.zeros((2, 2))

    for fold in splits:
        print(f'Validating {fold}/{len(splits)}')
        df_val = df_frames[df_frames['split'] == fold]

        if load_previous:
            labels = load_all_labels(df_val, shift=1, window=window_size)
            predictions = all_predictions[label_index:label_index+len(df_val)]
            label_index += len(df_val)
        else:
            labels, predictions = predict_hmm(df_val, folds_dir / fold, window_size=window_size)

        if filter_size:
            predictions = [majority_filter(prediction, filter_size) for prediction in predictions]

        if method == 'frame':
            matrix = matrix + confusion_matrix(np.concatenate(labels), np.concatenate(predictions), labels=[0, 1])
        elif method == 'event':
            matrix = matrix + evaluate_events(np.concatenate(labels), np.concatenate(predictions))
        else:
            raise ValueError('Invalid method!')

        if (results_dir and not load_previous) or (metric == 'f1'):
            all_predictions.extend(predictions)
        if metric == 'f1':
            all_labels.extend(labels)

    if results_dir and not load_previous:
        mkdir_if_not_exists(results_dir)
        np.savez(results_dir/'predictions.npz', *all_predictions)

    if metric == 'f1':
        if method == 'frame':
            return f1_score(np.concatenate(all_labels), np.concatenate(all_predictions))
        if method == 'event':
            tn, fp, fn, tp = evaluate_events(np.concatenate(all_labels), np.concatenate(all_predictions)).ravel()
            return tp / (tp + (0.5 * (fp + fn)))

    plot_confusion_matrix(matrix, title='Event-level confusion matrix for head-shake detection')

def fit_hmm_folds(frames_csv, folds_dir):
    df_frames = load_df(frames_csv)
    splits = get_splits(df_frames)

    for fold in splits:
        mkdir_if_not_exists(folds_dir / fold)

        df_val = df_frames[df_frames['split'] == fold]
        df_train = df_frames[df_frames['split'].str.contains('fold')].drop(df_val.index)

        fit_hmms(df_train, folds_dir / fold)

def cross_validate_random_preload(frames_csv, window_size=48, movement_threshold=0.5):
    df_frames = load_df(frames_csv)
    vectors = ordinal_from_csv(df_frames, threshold=movement_threshold)

    matrix = cross_validate(
        frames_csv,
        data=vectors,
        model_class=RandomShakeDetector,
        params={
            'window_size': window_size,
            'movement_threshold': movement_threshold
        }
    )
    plot_confusion_matrix(matrix,
                          title='Confusion matrix for random classifier')

def cross_validate_rule_preload(frames_csv, window_size=48, movement_threshold=0.5):
    df_frames = load_df(frames_csv)
    vectors = ordinal_from_csv(df_frames, threshold=movement_threshold)

    matrix = cross_validate(
        frames_csv,
        data=vectors,
        model_class=RuleBasedShakeDetector,
        params={
            'window_size': window_size,
            'movement_threshold': movement_threshold,
            'rule_func': majority_vote
        }
    )
    plot_confusion_matrix(matrix,
                          title=f'Confusion matrix for rule-based classifier with threshold={movement_threshold}')

def cross_validate_memory_preload(frames_csv, window_size=48, movement_threshold=0.5):
    """Cross validation wrapper specifically designed for the memory based classifier using HMM vectors.

    :param frames_csv: Dataframe with frame annotations, labels and any other information used by your model
    :param window_size: Window size to use during prediction of new sequences
    :param movement_threshold: Movement threshold in pixels to determine when a person is considered to move
    """
    df_frames = load_df(frames_csv)
    vectors = ordinal_from_csv(df_frames, threshold=movement_threshold)

    matrix = cross_validate(
        frames_csv,
        data=vectors,
        model_class=MemoryBasedShakeDetector,
        params={
            'window_size': window_size,
            'movement_threshold': movement_threshold
        }
    )
    plot_confusion_matrix(matrix,
                          title=f'Confusion matrix for memory-based classifier with threshold={movement_threshold}')

def cross_validate(frames_csv, data, model_class, params):
    """Do cross validation with an arbitrary model and number of folds.

    The model will be created using any parameters given in params and should be able to fit using a Pandas dataframe
    and index-able collection of data sequences, which length may be variable.

    The code assumes your folds are defined in the Dataframe under a 'split' column, where every fold has a unique
    identifier for the rows to use during validation. This identifier may be anything, so long as it includes the word
    'fold'. Any rows that don't include this word will be ignored (e.g. testing sets or any other collections of
    datapoints you don't wish to use at this time).

    :param frames_csv: Dataframe with frame annotations, labels and any other information used by your model
    :param data: Collection of datapoints, the indices of these datapoints must correspond to the Dataframe
    :param model_class: Reference to the model class to use
    :param params: Parameters for creating models
    :return: Confusion matrix of the results
    """
    df_frames = load_df(frames_csv)
    splits = get_splits(df_frames)
    matrix = np.zeros((2, 2))

    for fold in splits:
        model = model_class(**params)
        matrix = matrix + validate_fold(frames_csv=df_frames, model=model, fold=fold, data=data)

    return matrix

def validate_fold(frames_csv, model, data, fold, classes=None):
    """Validate a single fold. This function assumes a two-class classification problem is being solved, but this can
    be explicitly adjusted using the 'classes' argument.

    :param frames_csv: Dataframe with frame annotations, labels and any other information used by your model
    :param model: Instance of the model that will be trained
    :param data: Collection of datapoints, the indices of these datapoints must correspond to the Dataframe
    :param fold: Label of the fold used for evaluation.
    :param classes: List of integers representing classes.
    :return: Confusion matrix of the validation results.
    """
    if classes is None:
        classes = [0, 1]

    df_frames = load_df(frames_csv)
    df_val = df_frames[df_frames['split'] == fold]
    df_train = df_frames[df_frames['split'].str.contains('fold')].drop(df_val.index)
    assert len(df_val) > 0

    train_indices = list(df_train.index)
    val_indices = list(df_val.index)
    model.fit(df_train, data=[data[index] for index in train_indices])
    val_sequences = [data[index] for index in val_indices]

    cut_size = int((model.window_size - 1) / 2)
    i = 0
    pred_list = []
    label_list = []

    for _, row in df_val.iterrows():
        pred_list.append(model.predict(val_sequences[i]))
        labels = np.load(row['labels_path'])[row['start_frame']:row['end_frame']]
        labels = labels[cut_size + 1:-cut_size]
        label_list.append(labels)

        i += 1

    preds = np.concatenate(pred_list)
    labels = np.concatenate(label_list)

    return confusion_matrix(labels, preds, labels=classes)

def plot_confusion_matrix(matrix, title=None):
    disp = ConfusionMatrixDisplay(matrix, display_labels=['background', 'head-shake'])

    disp.plot()
    plt.subplots_adjust(left=0.25)
    if title:
        plt.title(title, fontsize=12, y=1.1)
    plt.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('frames_csv', type=Path)
    parser.add_argument('-w', '--window_size', default=36 , type=int)
    parser.add_argument('-t', '--movement_threshold', default=0.5, type=float)
    subparsers = parser.add_subparsers(dest='subparser')

    hmm_parser = subparsers.add_parser('hmm')
    hmm_parser.add_argument('folds_dir', type=Path)
    hmm_parser.add_argument('-s', '--save_dir', type=Path)

    window_parser = subparsers.add_parser('window')
    window_parser.add_argument('folds_dir', type=Path)

    filter_parser = subparsers.add_parser('filter')
    filter_parser.add_argument('folds_dir', type=Path)
    filter_parser.add_argument('-s', '--save_dir', type=Path)

    hmm_fit_parser = subparsers.add_parser('hmm_fit')
    hmm_fit_parser.add_argument('folds_dir', type=Path)

    memory_parser = subparsers.add_parser('memory')
    rule_parser = subparsers.add_parser('rule')
    random_parser = subparsers.add_parser('random')

    args = parser.parse_args()

    if args.subparser == 'hmm':
        validate_hmm_folds(args.frames_csv,
                           args.folds_dir,
                           window_size=args.window_size,
                           results_dir=args.save_dir,
                           filter_size=None,
                           method='event',
                           load_previous=True)
    elif args.subparser == 'window':
        hmm_window_search(args.frames_csv,
                          args.fols_dir,
                          method='frame',
                          metric='f1')
    elif args.subparser == 'filter':
        hmm_filter_search(args.frames_csv,
                          args.folds_dir,
                          results_dir=args.save_dir,
                          method='event',
                          metric='f1')
    elif args.subparser == 'hmm_fit':
        fit_hmm_folds(args.frames_csv,
                      args.folds_dir)
    elif args.subparser == 'memory':
        cross_validate_memory_preload(args.frames_csv,
                                      window_size=args.window_size,
                                      movement_threshold=args.movement_threshold)
    elif args.subparser == 'rule':
        cross_validate_rule_preload(args.frames_csv,
                                    window_size=args.window_size,
                                    movement_threshold=args.movement_threshold)
    elif args.subparser == 'random':
        cross_validate_random_preload(args.frames_csv,
                                      window_size=args.window_size,
                                      movement_threshold=args.movement_threshold)
    else:
        raise RuntimeError('Please choose a subcommand')


#Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:

hours = input("Enter hours: ")
rate = input("Enter Hourly Rate: ")

try:
    pay = float(hours) * float(rate)

    if float(hours) > 40 :
        extraHours = float(hours) - 40
        extraHoursPay = float(extraHours) * (float(rate) * .5)
        pay = pay + extraHoursPay

    print(pay)

except:
    print("Error! Please enter numeric input")


import pandas as pd
import os
import numpy as np
import column_rename

#
def read_mapping():
    mapping_df = pd.read_csv('mapping_je_type.csv')

    return mapping_df

def define_final_amount(row):
    if row['D/C'] == 'H':
        return (row['Loc.curr.amount'] * -1)
    else:
        return row['Loc.curr.amount']

def define_doc_amount(row):
    if row['D/C'] == 'H':
        return (row['Amount'] * -1)
    else:
        return row['Amount']

def define_je_type(row, mapping_df):
    return mapping_df.loc[mapping_df['TCODE'] == row['TCode'], 'JE Type'].item()

def manipulate_data(company_code, input_path, fy):
    print('Adding column')
    working_path = input_path + company_code + '/'
    removed_dupe_path = input_path + 'removed_dupe'
    files = sorted(os.listdir(removed_dupe_path))
    df = [''] * len(files)
    ii = 0
    sum_df = 0
    attempt = 0
    for infiles in files:
        print("Attempting reading temp files " + infiles, end=" ")
        file_path = os.path.join(removed_dupe_path, infiles)
        try:
            df[ii] = pd.read_csv(file_path,
                                 delimiter='|',
                                 low_memory=False,
                                 encoding='ISO-8859-15',
                                 dtype={'DocumentNo': 'string', 'Year': 'string', 'Period': 'string', 'Itm': 'string',
                                        'PK': 'string'})  # ,quoting=csv.QUOTE_NONE

            # print(df[ii].tail(10))
            if (ii == 0):
                sum_df = df[ii]
            else:
                temp_sum_df = sum_df
                sum_df = temp_sum_df.append(df[ii], ignore_index=True)
            # print(df[ii].tail())
            ii = ii + 1
            print("- Done reading")
        except Exception as error_reading:
            print(error_reading)
            print("===================================== ERROR READING ===============================")
            attempt = 1
    # try:
    # test = sum_df.loc[sum_df['DocumentNo'].isnull(),'TCode']
    # print(test)
    if (attempt == 0):
        sum_df_fin = sum_df.dropna(subset=['DocumentNo'])
        sum_df_fin.drop('G/L Acct', axis=1, inplace=True)
        sum_df_fin.drop('Clearing', axis=1, inplace=True)
        sum_df_fin.drop('Clrng doc.', axis=1, inplace=True)
        sum_df_fin['G/L'] = sum_df_fin['G/L'].astype(np.int64)
        sum_df_fin['Amount'] = sum_df_fin['Amount'].str.replace(',', '').astype(float)
        sum_df_fin['Loc.curr.amount'] = sum_df_fin['Loc.curr.amount'].str.replace(',', '').astype(float)
        sum_df_fin['Final_Amount'] = sum_df_fin.apply(lambda row: define_final_amount(row), axis=1)
        sum_df_fin['Doc_Amount'] = sum_df_fin.apply(lambda row: define_doc_amount(row), axis=1)
        mapping_df = read_mapping()
        merged = pd.merge(sum_df_fin, mapping_df, on="TCode", how="left")
        unmapped_tcode = merged.loc[merged['Source'].isnull(), 'TCode']

        val = input("Do you want to change columns name? (Press Y and enter if yes): ")
        if (val == 'Y' or val == 'y'):
            merged = column_rename.rename_funct(merged)

        if (len(unmapped_tcode) != 0):
            print(
                "Following TCode exists within document and has not been mapped. Will cancel exporting process.\nPlease update the mapping csv.")
            distinct_unmapped_tcode = unmapped_tcode.drop_duplicates()
            # print(merged.loc[merged['Source'].isnull(),'TCode'])
            print(distinct_unmapped_tcode)
            return False
        else:
            # sum_df_fin['Source'] = sum_df_fin.apply (lambda row: define_je_type(row,mapping_df), axis=1)
            # print('formatted df')
            # print(merged.tail(5))
            # merged.info()
            output_path = 'output/' + company_code + '/'
            try:
                os.mkdir(output_path)
            except:
                print('Output path already exists')
            print("Start exporting...")
            merged.to_csv(output_path + company_code + '_' + fy + '_cleaned.txt', index=False, sep='|')
            non_dec = merged.loc[merged['Period'] != '12']
            non_dec.to_csv(output_path + company_code + '_Jan_Nov_' + fy + '_cleaned.txt', index=False, sep='|')
            dec = merged.loc[merged['Period'] == '12']
            dec.to_csv(output_path + company_code + '_Dec_' + fy + '_cleaned.txt', index=False, sep='|')
            sum_by_gl = merged.groupby(['G/L'])['Final_Amount'].sum().reset_index()
            sum_by_gl.to_csv(output_path + company_code + '_' + fy + '_sumGL.txt', index=False, sep='|')
            # shutil.rmtree(removed_dupe_path)
            print('File for ' + company_code + ' successfuly cleansed.')
            print('====================================================================================')
            return True
            # merged.to_csv('4output_comma.csv', index=False)
            # test_print()
    else:
        print("Error reading " + company_code)
        return False


import serial
from serial.tools.list_ports import comports
import time
from statistics import mean

class Connect:
    connection_status = False

    def __init__(self):
        self.xData = []
        self.yData = []
        self.ocpData = []
        # Get a list of all connected devices through serial port
        com_devices = comports()

        # Connect to the AWT kit. Index might need to change.
        ser = serial.Serial(com_devices[1][0],timeout=10)
        ## Test connection
        print(ser.name)
        ser.write('*'.encode('utf-8'))
        time.sleep(.1)
        device_response = ser.read(size=1).decode('utf-8')

        # should return a '&'
        if(device_response == '&'):
            print("Connection established.")
            # connection_status = True
            self.ser = ser
        else:
            print("The device says: " + device_response)

    # setup_connection()

    def importParam(self, param_list):
        '''
        mode     = 0      vOffset      = 5
        vInit    = 1      initialDelay = 6
        vFinal   = 2      nRuns        = 7
        scanRate = 3      logIvl       = 8
        cGain    = 4      del2         = 9
        '''
        for p in param_list:
            self.ser.write(p.encode('utf-8'))
            self.ser.write(','.encode('utf-8'))
            time.sleep(.1)

    def readData(self):
        # read headers
        header_line = self.ser.read_until().decode('utf-8')
        print(header_line)

        while(header_line != '$\r\n'):
            header_line = self.ser.read_until().decode('utf-8')
            print(header_line)
        print('-------------------------')

        ## record actual data
        data_list = [""]
        while True:
            data_line = self.ser.read_until().decode('utf-8')
            data_list = data_line.split(",")
            ## check if the run ends
            if(data_list[0] == '99999'):
                break

            ## check if the first output is empty
            if(len(data_list) != 1):
                xRead = float(data_list[0])
                yRead1 = float(data_list[1])/1000
                yRead2 = float(data_list[2])/1000
                yRead = yRead1 - yRead2

                mVmin = float(data_list[3])
                mVmax = float(data_list[4])

                # record data
                self.xData.append(xRead)
                self.yData.append(yRead)

    def readOCP(self):
        # read headers
        header_line = self.ser.read_until().decode('utf-8')
        print(header_line)

        while(header_line != '$\r\n'):
            header_line = self.ser.read_until().decode('utf-8')
            print(header_line)
        print('-------------------------')

        ## record actual data
        data_list = [""]
        while True:
            data_line = self.ser.read_until().decode('utf-8')
            data_list = data_line.split(",")
            ## check if the run ends
            if(data_list[0] == '99999'):
                break

            ocp_read = float(data_list[0])
            self.ocpData.append(ocp_read)
            self.ocp_average = mean(self.ocpData)


#!/usr/bin/python3

from typing import List, Tuple, Dict, Set, Union
from re import split
from operator import mul, add

def compute_equal_precedence(enumerator: enumerate) -> int:
    op = lambda a, b: b
    result = 0
    for i, t in enumerator:
        if t == "*":
            op = mul
        elif t == "+":
            op = add
        elif t == "(":
            result = op(result, compute_equal_precedence(enumerator))
        elif t == ")":
            return result
        else:
            result = op(result, int(t))
    return result

def find_matching_brace(tokens: List[Union[str,int]], idx: int) -> int:
    depth = 0
    for i, t in enumerate(tokens[idx:]):
        if t == '(':
            depth += 1
        elif t == ')':
            depth -= 1
            if depth == 0:
                return i
    return idx

def compute(tokens: List[Union[str,int]]) -> int:
    result = 0
    # print(f'Starting from {tokens}')
    while '(' in tokens:
        a = tokens.index('(')
        b = find_matching_brace(tokens, a) + a
        val = compute(tokens[a+1:b])
        tokens = tokens[:a] + [val] + tokens[b+1:]
    while '+' in tokens:
        m = tokens.index('+')
        v: int = int(tokens[m-1]) + int(tokens[m+1])
        tokens = tokens[:m-1] + [int(v)] + tokens[m+2:]
    while '*' in tokens:
        m = tokens.index('*')
        v = int(tokens[m-1]) * int(tokens[m+1])
        tokens = tokens[:m-1] + [int(v)] + tokens[m+2:]
    return int(tokens[0])

def read_file(day: str) -> List[str]:
    with open(f"input/day_{day}.txt") as file:
        lines = [line.strip() for line in file if line.strip() != ""]
        return lines

def phase_1(input: List[str]):
    xsum: int = 0
    for expression in input:
        # print(expression)
        tokens = [t.strip() for t in split(r"( |\(|\))", expression) if t.strip() != ""]
        res = compute_equal_precedence(enumerate(tokens))
        # print(f' --> {res}')
        xsum += res
    return xsum

def phase_2(input: List[str]):
    xsum: int = 0
    for expression in input:
        # print(expression)
        tokens: List[Union[str, int]] = [t.strip() for t in split(r"( |\(|\))", expression) if t.strip() != ""]
        res = compute(tokens)
        # print(f'  --> {res}')
        xsum += res
    return xsum

def execute(input: List[str]):
    p1 = phase_1(input)
    print(f"Phase 1: {p1}")

    p2 = phase_2(input)
    print(f"Phase 2: {p2}")

if __name__ == "__main__":
    for day_input in ["18_s", "18"]:
        print(f"For {day_input}:")
        input = read_file(day_input)
        execute(input)
        print("..............")

# Answers
# 1: 800602729153
# 2: 92173009047076


#!/usr/env python

import sys
import os
import shutil
import tarfile

zipname = sys.argv[1]
files = sys.argv[2:]
samples = [f.split("/")[-3] for f in files]

print("name,timepoint,biorep,path")

for f, s in zip(files, samples):
    r = None

    tmpdir = os.path.join(os.sep, "tsl", "scratch", "macleand", "tmp")
    dest = os.path.join("kallisto", s, "abundance.tsv")
    tmpfile = os.path.join(tmpdir, dest)

    if not os.path.exists(os.path.split(tmpfile)[0]):
        os.makedirs(str(os.path.split(tmpfile)[0]))
    shutil.copyfile(f,tmpfile)

    #now copy also needed files abundance.h5 and run_info.json
    h5i = f.replace(".tsv", ".h5")
    h5o = os.path.join(tmpdir, "kallisto", s, "abundance.h5")
    shutil.copyfile(h5i, h5o)

    jsi = f.replace("abundance.tsv", "run_info.json")
    jso = os.path.join(tmpdir, "kallisto", s, "run_info.json")
    shutil.copyfile(jsi,jso)

    md = s.split("_")
    r = "{},{},{},{}".format(md[0], md[1], md[2], dest)
    print(r)

if not os.path.exists("results"):
    os.mkdir("results")

src = os.path.join(os.sep, "tsl", "scratch", "macleand", "tmp", "kallisto")
with tarfile.open(zipname, "w:gz") as tar:
    tar.add(src,arcname=os.path.basename(src))
shutil.rmtree(src)


# @author: Gautam Patel
# Problem Description URL: https://www.hackerrank.com/challenges/two-characters/problem
#!/bin/python3

import math
import os
import random
import re
import sys
from itertools import groupby
from collections import Counter

# Complete the alternate function below.
def isStringAlternate(s):
    if len(s) < 2: return False
    e_ch = s[0]
    o_ch = s[1]
    if e_ch == o_ch:
        return False
    for i in range(2,len(s)):
        if i%2 == 0 and e_ch != s[i]:
            return False
        if i%2 == 1 and o_ch != s[i]:
            return False
    return True

def alternate(s):
    matcher = re.compile(r'(.)\1+')
    for m in matcher.finditer(s):
        ch = m.group()[0]
        s = s.replace(ch, '')
    if len(s) == 0 or isStringAlternate(s):
        return len(s)
    c = Counter(s)
    cnt_max = 0
    for k in c.items():
        cnt = alternate(s.replace(k[0], ''))
        if cnt > cnt_max:
            cnt_max = cnt
    return cnt_max

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    l = int(input().strip())

    s = input()

    result = alternate(s)

    fptr.write(str(result) + '\n')

    fptr.close()


from part1 import getStacks, printEachElement

def performInstructionsFor9001(s, instructions):
    for i in instructions:
        numberOfCrates = int(i[0])
        initial = int(i[1])-1
        final = int(i[2])-1
        block = []

        # take off from the top
        for i in range(numberOfCrates):
            if len(s[initial]) == 0:
                continue
            block.append(s[initial].pop())

        # add in reverse order
        for i in range(len(block)-1, -1, -1):
            s[final].append(block[i])

    return s

printEachElement(performInstructionsFor9001(*getStacks()))


# -*- coding: utf-8 -*-

#Created on Thu Apr 27 19:27:43 2023

#15-dars Lug'atlar bilan ishlash
#talaba_0 = {
 #   'ism':'oybek',
  #  'familiya': 'Norboyev',
   # 'yosh': 22,
    #'fakultet ' : 'matematika',
     #'kurs': 2
   #  }

#print(talaba_0.items())

#for kalit, qiymat in talaba_0.items():
 #   print(f"kalit: {kalit}")
  #  print(f"Qiymat: {qiymat} \n")

#telefonlar = {
#    'ali': 'Iphone X',
#    'vali': 'galaxy s9',
#    'olim': 'mi 10 pro',
#    'orif': 'Nokia 3310',
#    'Oybek': 'Redmi 11 pro',
#    'Ergashev.D': 'Iphone X',
#    'Dilshod': 'Nokia 3310'
#   }
#for k, q in telefonlar.items():
 #   print(f"{k.title()}()ning telefoni {q}")

# keys()
#mahsulotlar = {
#    'olma': 10000,
#    'anor': 12000,
#   'uzum':15000,
#   'anjir': 20000,
#   'shaftoli': 15000,
#    }
#print(mahsulotlar.keys())

#print('Dokondagi mavjud mahsulotlar:')
#for mahsulot in mahsulotlar.keys():
#        print(mahsulot.title())

#bozorlik = ['anor', 'limon', 'uzum', ' non', 'baliq ikra']
#for mahsulot in mahsulotlar:
#    if mahsulot in bozorlik:
#        print(f"{mahsulot.title()} { mahsulotlar[mahsulot]} so'm")
#
#for buyum in bozorlik:
#    if buyum not in mahsulotlar:
#        print(buyum)
#        print(f"Iltimos, do'koningizga {buyum} ham olib kleing!")

#print("Do'konimizdagi mahsulotlar:")
#for mahsulot in sorted(mahsulotlar):
#         print(mahsulot.title())

#print(telefonlar.values())

#for tel in telefonlar.values():
#    print(tel)
#
#print("foydalanuvchi quyidagi telefonlardan birini ishlatishadi:")
#for tel in set(telefonlar.values()):
#    print(tel)

#toys = {"ball", "car", "horse", "lamp", "ball", "bear", "horse"}

#28.04.2023 17:43
# 16-dars: Nesting

car0 = {
        'model': 'lacetti',
        'rangi': 'oq',
        'yil': 2018,
        'narh': 13000,
        'km': 50000,
        'korobka': 'avtomat'
        }
car1 = {
        'model': 'nexia-3',
        'rangi': 'qora',
        'yil': 2015,
        'narh': 90000,
        'km': 89000,
        'korobka': 'mexanika'
        }
car2 = {
        'model': 'gentra',
        'rangi': 'qizil',
        'yil': 2019,
        'narh': 15000,
        'km': 20000,
        'korobka': 'mexanika'
        }
#car = car0
#print(f"{car['model'].title()}, "
#      f"{car['rangi']} rangi, "
#      f"{car['yil']}-yil, {car['narh']}$")
#
#ar = car1
#print(f"{car['model'].title()}, "
#      f"{car['rangi']} rangi, "
#      f"{car['yil']}-yil, {car['narh']}$")

#car = car2
#print(f"{car['model'].title()}, "
#      f"{car['rangi']} rangi, "
#      f"{car['yil']}-yil, {car['narh']}$")

#cars = [ car0, car1,car2]
#for car in cars:
#    print(f"{car['model'].title()}, "
#          f"{car['rangi']} rangi,"
#          f"{car['yil']}-yil, {car['narh']}$")

malibus = []
for yangi in range(10):
    new_car = {
        'model': "Malibu",
        'rangi': None,
        'yil': 2023,
        'narh': None,
        'km': 0,
        'korobka': 'avto'
        }
    malibus.append(new_car)

#for malibu in malibus[:3]:
#    malibu['rangi']='qizil'
#    print(malibu)

#for malibu in malibus[3:6]:
#    malibu['rangi']='Qora'
#   print(malibu)

#for malibu in malibus[6:10]:
#    malibu ['rangi']= 'ko\'k'
#    malibu ['korobka']= 'mexanik'
#   print(malibu)
#
#for malibu in malibus:
#    if malibu['korobka']=='avto':
#        malibu['narh']=40000
#   else:
#      malibu['narh']=35000
#for malibu in malibus:
#    print(malibu)

# Lug'at ichida ro'yxat
dasturchilar = {
    'ali':['python', 'c++'],
    'vali':  ['html',  'css', 'js',],
    'hasan':['php', 'sql'],
    'husan': ['python', 'php'],
    'maryam': ['c++', 'c#']
    }

#for ism, tillar in dasturchilar.items():
 #   print(f"\n{ism.title()}  quyidagi dasturlash tillarini biladi:")
  #  for til in tillar:
   #     print(til.upper())

#for ism, tillar in dasturchilar.items():
#    print(f"\n{ism.title()}  quyidagi dasturlash tillarini biladi:")
#   for til in tillar:
#        print(f'{til.upper()} ' , end='')

hamkasblar = {
    'ali': {'familiya': 'valiyev',
            't_yil': 1995,
            'malumoti': 'oliy',
            'tillar': ['python', 'c+++']
            },
    'vali': {'familiya': 'aliyev',
             't_yil': 2001,
             'malumoti': 'o\'rta maxsus',
             'tillar': ['html', 'css', 'js']
             },
    'hasan': {'familiya': 'husanov',
              't_yil': 1999,
              'malumoti': 'maxsus',
              'tillar':['python', 'php']}
        }
for ism, info in hamkasblar.items():
        print(f"\n{ism.title()} {info['familiya'].title()},"
              f"{info['t_yil']}-yilda tu'gilgan."
              f"malumoti : {info['malumoti']}. \n"
              "Quyidagi dasturlash tillarini biladi:")
        for til in info['tillar']:
            print(til.upper())


# coding: utf-8

def gcd(a, b):
    if not a % b:
        return b
    return gcd(b, a%b)

t = int(input())

for _ in range(t):
    numbers = list(map(int, input().split()))
    result = 0
    for i in range(1, numbers[0] + 1):
        for j in range(i+1, numbers[0] + 1):
            result += gcd(numbers[i], numbers[j])
    print(result)


from sklearn import metrics

def CD_map_to_int(x):
    # Returns D:0 C:1
    return 68 - ord(x)

# Itertuples is a list of (index,col1,col2,..) for each row. We sort them by score first
df_vectors = pd.DataFrame()
df_vectors_strings = pd.DataFrame()
df_generation_max = df_generation_max.sort_values('opponent_name')
df_generation_max = df_generation_max.sort_values('best_score')
for tup in df_generation_max.itertuples():
    # index vals mean the indexing starts at 1 so +1 to these:
    #(0, 'generation'), (1, 'score_mean'), (2, 'score_median'), (3, 'score_pop_var'), (4, 'score_range'), (5, 'best_score'), (6, 'best_sequence'), (7, 'opponent_name'), (8, 'seed'), (9, 'analysis_name'), (10, 'base_player'), (11, 'stochastic'), (12, 'memory_depth'), (13, 'makes_use_of'), (14, 'score_bin'), (15, 'start_move'), (16, 'num_blocks'), (17, 'mean_block_len'), (18, 'median_block_len')
    seq_str = tup[7]
    opponent_name = str(tup[8])
    best_score = tup[6]
    bins = tup[15]
    # Mapping to integers 0 &1
    df_vectors[opponent_name] = list(
        map(CD_map_to_int, seq_str)) + [best_score] + [seq_str] + [bins]

    # No Mapping Cs & Ds
    df_vectors_strings[opponent_name] = list(
        seq_str) + [best_score] + [seq_str] + [bins]

move_cols = ['move ' + str(x+1) for x in range(200)]
# Transposing and labeling moves as were forming it in a rotated way.
# (Its easier to just make 2 dfs than map one to the other)
df_vectors = df_vectors.transpose()
df_vectors.columns = move_cols + ["best_score", "best_sequence", "score_bins"]

df_vectors_strings = df_vectors_strings.transpose()
df_vectors_strings.columns = move_cols + \
    ["best_score", "best_sequence", "score_bins"]

# Manhatten Distance == Hamming Distance in this example
# Intresting examples: cosine(??), hamming, jaccard sim
dist_array_ham = metrics.pairwise.pairwise_distances(
    df_vectors[move_cols], metric='hamming')
# add labels
dist_array_ham = pd.DataFrame(
    dist_array_ham, index=df_vectors.index, columns=df_vectors.index)

dist_array_cos = metrics.pairwise.pairwise_distances(
    df_vectors[move_cols], metric='cosine')
dist_array_cos = pd.DataFrame(
    dist_array_cos, index=df_vectors.index, columns=df_vectors.index)

dist_array_jac = metrics.pairwise.pairwise_distances(
    df_vectors[move_cols], metric='jaccard')
dist_array_cos = pd.DataFrame(
    dist_array_cos, index=df_vectors.index, columns=df_vectors.index)

dist_array_other = metrics.pairwise.pairwise_distances(
    df_vectors[move_cols], metric='correlation')
dist_array_cos = pd.DataFrame(
    dist_array_cos, index=df_vectors.index, columns=df_vectors.index)


from tkinter import *
import math, random
import sqlite3
import sys
import django
from time import sleep
django.setup()
# Conductor est un daemon
from threading import Thread
from components.mission import Mission
import signal

polling_interval = 1

def bddCreation():
    """
    CREATE TYPE droneStatus AS ENUM('busy','free','maintenance');

    CREATE TYPE stationStatus AS ENUM('working','empty');

    CREATE TYPE deliveryStatus AS ENUM('not assigned','in progress','cancelled'); """

    conn.commit()

    cursor.execute("""
    CREATE TABLE IF NOT EXISTS drone(
         id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
         status TEXT
    )
    """)

    cursor.execute("""
       CREATE TABLE IF NOT EXISTS station(
            id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
            status TEXT,
            xCoord FLOAT,
            yCoord FLOAT,
            batterieNumber INTEGER ,
            anticipatedBatterieNumber INTEGER
       )
       """)
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS mission(
             id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
             status TEXT
             xStockCoord FLOAT,
             yStockCoord FLOAT,
             xFinalCoord FLOAT,
             yFinalCoord FLOAT,
             creationDate DATETIME
        )
        """)
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS mission_drone(
             drone_id INTEGER,
             mission_id INTEGER,
             FOREIGN KEY(drone_id) REFERENCES drone(id),
             FOREIGN KEY(mission_id) REFERENCES mission(id)
        )
        """)
    conn.commit()

def random2DCoords():
    return [random.uniform(RAYON/2, LARGEUR-RAYON/2), random.uniform(RAYON/2, HAUTEUR-RAYON/2)]

def createDrones(number):
    i = 1
    while i < number:
        cursor.execute("""
        INSERT INTO drone(status) VALUES("free")""" )
        i = i+1
    conn.commit()

def deplacement():
    """ Dplacement de la balle """
    global X, Y, DX, DY, RAYON, LARGEUR, HAUTEUR

    # rebond  droite
    if X + RAYON + DX > LARGEUR:
        X = 2 * (LARGEUR - RAYON) - X
        DX = -DX

    # rebond  gauche
    if X - RAYON + DX < 0:
        X = 2 * RAYON - X
        DX = -DX

    # rebond en bas
    if Y + RAYON + DY > HAUTEUR:
        Y = 2 * (HAUTEUR - RAYON) - Y
        DY = -DY

    # rebond en haut
    if Y - RAYON + DY < 0:
        Y = 2 * RAYON - Y
        DY = -DY

    X = X + DX
    Y = Y + DY

    # affichage
    Canevas.coords(Balle, X - RAYON, Y - RAYON, X + RAYON, Y + RAYON)

    # mise a jour toutes les 50 ms
    Mafenetre.after(50, deplacement)

"""
    # Fenetre
    LARGEUR = 480
    HAUTEUR = 320

    # Drone
    RAYON = 5  # rayon des drones
    NUMBER_DRONE = 10

    # Station
    COTE = 5
    NUMBER_STATION = 5

    # direction initiale alatoire
    vitesse = random.uniform(1.8, 2) * 5
    angle = random.uniform(0, 2 * math.pi)
    DX = vitesse * math.cos(angle)
    DY = vitesse * math.sin(angle)

    conn = sqlite3.connect(':memory:')
    cursor = conn.cursor()
    # Cration de la fentre principale
    Mafenetre = Tk()
    Mafenetre.title("Animation Balle")

    # Cration d'un widget Canvas
    Canevas = Canvas(Mafenetre, height=HAUTEUR, width=LARGEUR, bg='white')
    Canevas.pack(padx=15, pady=15)
    bddCreation()
    createDrones(5)
    # Cration d'un objet graphique
    Balle = Canevas.create_oval(X - RAYON, Y - RAYON, X + RAYON, Y + RAYON, width=1, fill='green')

    deplacement()
    Mafenetre.mainloop()
    conn.close()
"""

# Fonction quand le thread du daemon est lance
def run():
    print("Processing... press q key to exit")
    #traitement ici
    while True:
        if mission_mgr.flag_has_new_mission:
            missions = mission_mgr.get_missions
            print(missions)
        sleep(polling_interval)

mission_mgr = Mission()
processing_th = Thread(target=run)
processing_th.start()
signal.signal(signal.SIGINT, signal_sigint_handler)
processing_th.join()


# -*- coding: utf-8 -*-

from typing import Dict

import os
import pkg_resources

from bag.design import Module

yaml_file = pkg_resources.resource_filename(__name__, os.path.join('netlist_info',
                                                                   'delay_cell_mux.yaml'))

# noinspection PyPep8Naming
class bag_digital_ec__delay_cell_mux(Module):
    """Module for library bag_digital_ec cell delay_cell_mux.

    Fill in high level description here.
    """

    def __init__(self, bag_config, parent=None, prj=None, **kwargs):
        Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs)

    @classmethod
    def get_params_info(cls):
        # type: () -> Dict[str, str]
        return dict(
            buf_params='delay buffer parameters.',
            mux_params='mux parameters.',
        )

    def design(self, buf_params, mux_params):
        self.instances['XBUF'].design(**buf_params)
        self.instances['XMUX'].design(**mux_params)


#!/usr/bin python3

# ----------------------------------------------------------------------------
#  IOTpoll cycles thru the connected pins and returns back to Promethus server
#          the settings,  An API gateway allows grafana pages to switch relays
#          if required
#
#    To Set : View Readme.txt in folder
#
#    V 1.1.0  -  2020 Mar - Tidy up code
#
# ----------------------------------------------------------------------------

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

from http.server import BaseHTTPRequestHandler, HTTPServer
from prometheus_client import start_http_server, Gauge

from urllib import parse
import RPi.GPIO as GPIO
import configparser
import time
import http.client
import json
from ZigBee import ZBsensors

import os
import time
import datetime
import glob
import socket
from array import array
#from systemd import journal
import Adafruit_DHT
import logging
import socketserver
import requests

Ddir='/sys/bus/w1/devices/'
configPOLL = configparser.ConfigParser()
configPINS = configparser.ConfigParser()
KillSwitch = True
POLLlst={"DEF":0}
GaugeINT={"DEF":40}     # Internal Sensors List
Vers='1.1.0'
MID='XX'

# -----------------------------------------------------------------
#    Wire-1 : Wire 1 functions and routines
# -----------------------------------------------------------------

def LISTwire1():
    SIDs={}
    devicelist = glob.glob(Ddir+'28*')
    if devicelist=='':
        return SIDs
    else:
        for device in devicelist:
            TT=device.split("/")
            SID = TT[len(TT)-1]
            SIDs['W1_S'+SID[3:]]=GETwire1(TT[len(TT)-1])
    return SIDs

# Get Sensor Reading
def GETwire1(SID):
    devicefile=Ddir+SID+'/w1_slave'
    try:
        fileobj = open(devicefile,'r')
        lines = fileobj.readlines()
        fileobj.close()
    except:
        return devicefile+" Not Found"

    # get the status from the end of line 1
    status = lines[0][-4:-1]

    # is the status is ok, get the temperature from line 2
    if status=="YES":
        equals_pos = lines[1].find('t=')
        temp_string = lines[1][equals_pos+2:]
        tempvalue=float(temp_string)/1000
        return tempvalue
    else:
        return -999

# -----------------------------------------------------------------
#    Switch Sensors (Doors, Motion, Etc)
# -----------------------------------------------------------------

def LISTswitches(SIDs):

    for pin in configPINS:
        if pin != 'DEFAULT':
            if configPINS[pin]["Type"]=='Motion' or configPINS[pin]["Type"]=='Switch':
                SendMSG(str(pin))
                if GPIO.input(int(pin)):
                    SIDs[int(pin)]=1

    return SIDs

# -----------------------------------------------------------------
#    ZigBee Sensors
# -----------------------------------------------------------------

def ZBpoll():
    global ZBconfig, ZBsensors, ZBsensorC, LockSys
    LockSys = datetime.datetime.today()
    ZBsensorC = ZBsensors(configPOLL["ZIGBEE"]["ip"],configPOLL["ZIGBEE"]["key"])
    return ZBsensorC.GetALL()

    #if 'ZIGBEE' not in configPOLL: return SIDzb
    #params = {"words": 10, "paragraphs": 1, "format": "json"}
    #response = requests.get(f"http://"+configPOLL["ZIGBEE"]["ip"]+"/api/"+configPOLL["ZIGBEE"]["key"]+"/sensors/")
    #if response.status_code != 200:
    #    print("ZigBee Return Error : "+str(response.status_code))
    #    return True
    #ZBc=ZB.ZBsensors(response.json())   #  Store Sensors in ZigBee Class
    #return ZBc.GetALL()

# -----------------------------------------------------------------
#   PIN : Controllers
# -----------------------------------------------------------------

def PINpoll():
    # Read Pins
    SID={}
    for Pin in configPINS:
        if Pin != 'DEFAULT':
            Sname=configPINS[Pin]['name'].replace(' ','_')
            if configPINS[Pin]["type"]=='AM2302' or configPINS[Pin]["type"]=='DHT22':
                humidity,temperature = Adafruit_DHT.read_retry(22, Pin)
                if isinstance(temperature, float):
                    SID['PIN_DHT22_'+Pin+'_'+Sname+'_TEMP']=temperature
                if isinstance(humidity, float):
                    SID['PIN_DHT22_'+Pin+'_'+Sname+'_HUM']=temperature

            elif configPINS[Pin]["type"]=='relay':
                SID['PIN_RELAY_'+Pin+'_'+Sname]=RelayGET(Pin)

            elif configPINS[Pin]["type"]=='switch':
                SID['PIN_SWITCH_'+Pin+'_'+Sname]=RelayGET(Pin)

            elif configPINS[Pin]["type"]=='motion':
                SID['PIN_MOTION_'+Pin+'_'+Sname]=RelayGET(Pin)
    return SID

# Return Pin ON/OFF status
def RelayGET(PIN):
    if GPIO.input(int(PIN)):
        return 0
    else:
        return 1
    sys.stdout.flush()

# Toggle Pin
def RelayTOGGLE(PIN):
    print('Toggle:'+str(RelayGET(int(PIN))))
    if RelayGET(PIN):
       GPIO.output(int(PIN), GPIO.LOW)
       return "0"
    else:
       GPIO.output(int(PIN), GPIO.HIGH)
       return "1"
    sys.stdout.flush()

def SETpins():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    for pin in configPINS:
        if pin != 'DEFAULT':
            if configPINS[pin]["type"]=='relay':
                SendMSG('TYPE:RELAY'+'-'+str(pin)+' '+configPINS[pin]['name']+' Initialised')
                GPIO.setup(int(pin), GPIO.OUT)
                GPIO.output(int(pin), GPIO.HIGH)

            if configPINS[pin]["type"]=='AM2302' or  configPINS[pin]["Type"]=='DHT22':
                SendMSG('TYPE:HUM/TEMP'+'-'+str(pin)+' '+configPINS[pin]['name'])

            if configPINS[pin]["type"]=='switch':
                SendMSG('TYPE:SWITCH'+'-'+str(pin)+' '+configPINS[pin]['name']+' Initialised')
                GPIO.setup(int(pin), GPIO.IN, pull_up_down=GPIO.PUD_UP)

            if configPINS[pin]["type"]=='motion':
                SendMSG('TYPE:Motion'+'-'+str(pin)+' '+configPINS[pin]['name']+' Initialised')
                GPIO.setup(int(pin), GPIO.IN, pull_up_down=GPIO.PUD_UP)

    #sys.stdout.flush()

# ------------------------------------------------------------------------
#   Promethues : Comms to Promethus Server
# ------------------------------------------------------------------------

def DelPromethues(key):
    global GaugeINT
    Mkey = MID + '_' + key
    if Mkey in GaugeINT:
        GaugeW1.pop(key)

def UpdPromethues(key,val):
    global GaugeINT
    Mkey = MID + '_' + key
    if not isSetPromethues(key):
        AddPromethues(key)
    if Mkey in GaugeINT:
        # print('UPD'+Mkey+'-'+str(val))
        GaugeINT[Mkey].set(val)

def AddPromethues(key):
    global GaugeINT
    Mkey = MID + '_' + key
    if  key not in GaugeINT:
        GaugeINT[Mkey]=Gauge(Mkey,key)

def POLLEDgauge(key):
    SendMSG('Polled Gauge '+str(key))

def isSetPromethues(key):
    Mkey = MID + '_' + key
    if Mkey not in GaugeINT:
        return False
    else:
        return True

# ------------------------------------------------------------------------
#   Intial Parm Load and validation
# ------------------------------------------------------------------------

def ValidatePARMS():
    global MID
    global PortNo
    global POLLgap

    configPOLL.read('POLL.ini')
    configPINS.read('PINS.ini')

    if "location" not in configPOLL["POLL"]:
        SendMSG('location missing from Config - Job Terminated')
        return True
    if "name" not in configPOLL["POLL"]:
        SendMSG('name missing from Config - Job Terminated')
        return True

    print("Location     : ",configPOLL["POLL"]["location"])
    print("Name         : ",configPOLL["POLL"]["name"])
    SendMSG(configPOLL["POLL"]["name"]+' / '+configPOLL["POLL"]["name"])
    MID=configPOLL["POLL"]["location"]+'_'+configPOLL["POLL"]["name"]+'_V2'
    SendMSG('Promethues Prefix : '+MID)

    PortNo=8010
    if "port" in configPOLL["POLL"]:
        PortNo=int(configPOLL['POLL']['port'])

    POLLgap=30
    if "Time" in configPOLL["POLL"]:
        POLLgap=int(configPOLL['POLL']['Time'])

    SendMSG('Poll Intervals : '+str(POLLgap)+' Seconds')
    SETpins()
    return False

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

def SendMSG(msg):
    print(msg)
    #journal.send(msg)

# ---------------------------------------------------------------------------
#   API Server : Open API server to Port 18100
# ---------------------------------------------------------------------------

class gpioHTTPServer_RequestHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With")

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()
        Rsn=APIincoming(self.path)
        self.wfile.write(bytes(Rsn, "utf8"))

    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(bytes("OK","utf8"))

# -----------------------------------------------------------------------
#    Incoming API handler
# -----------------------------------------------------------------------

def APIincoming(url):
    qsp=dict(parse.parse_qsl(parse.urlsplit(url).query))
    #print(qsp)
    if 'API' in qsp:
        if qsp['API']!='A4C3D2E5112':
           return 'Security Volation'
        RtnTxt=''
    else:
        return 'Security Key Missing'

    if 'TYP' in qsp:
        if qsp['TYP']=='RLY':
            return apiRELAY(qsp)
        return 'Support Types (RLY,SWT,MON)'
    else:
        return 'Missing Task'

def apiRELAY(qsp):

    # Toggle Relay
    if 'PID' in qsp:
        if qsp['PID'] in configPINS:
            return RelayTOGGLE(qsp['PID'])

    # Return All Relay Status
    RtnTxt=''
    for pin in configPINS:
        if pin != 'DEFAULT':
            if configPINS[pin]["Type"]=='Relay':
                if RelayGET(pin)==0:
                    RlyStat='OFF'
                else:
                    RlyStat='ON'
                RtnTxt=RtnTxt+str(pin)+'('+configPINS[pin]['NAME']+')='+RlyStat+'  '

    return RtnTxt

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

def main():
    SendMSG('Version '+Vers)
    if ValidatePARMS(): return

# Start Promethus Server
    start_http_server(PortNo)
    SendMSG('Prometheus running on '+str(PortNo))

# Start API Server
    server_address = ('', 18100)
    httpd = HTTPServer(server_address, gpioHTTPServer_RequestHandler)
    httpd.socket.settimeout(1)
    httpd.handle_request()
    SendMSG('GPIO API running on 18100')

# Main Loop
    while KillSwitch:
        SIDs={}                      # Activate Sensors
        SIDs=LISTwire1()             # Wire-1 Sensor Controls
        print('SID:',SIDs)

        PNs=PINpoll()                # Pin Poll
        print(PNs)
        SIDs = {**SIDs, **PNs}

        if 'ZIGBEE' in configPOLL:   # ZigBee Poll
            ZBs=ZBpoll()
            print('ZBs:',ZBs)
            SIDs = {**SIDs, **ZBs}

        for ActSid in GaugeINT:      # Remove Dead Sensors
            if ActSid not in SIDs:
                DelPromethues(ActSid)

        for sid in SIDs:             # Add New Sensors
            if not isSetPromethues(sid):
                AddPromethues(sid)

        for sid in SIDs:             # Update Sensors
            UpdPromethues(sid,SIDs[sid])

        GapCnt=0
        while GapCnt <= POLLgap:
            time.sleep(1)
            httpd.handle_request()   # Poll API Getway
            GapCnt+=1

    sys.stdout.flush()

if __name__=="__main__":
    main()


# coding=utf8
from django.conf import settings
from hashlib import md5
from pymogile import Client
from wand.image import Image

class Avatar(object):

    def __init__(self, key):
        self.key = key
        self.__origin_store_key = 'avatar/origin/' + self.__key
        self.__large_store_key = 'avatar/large/' + self.__key
        self.__small_store_key = 'avatar/small/' + self.__key

    def __ensure_datastore_client(self):
        if not hasattr(self, '__entity_obj'):
            self.__datastore = Client(
                domain = settings.MOGILEFS_DOMAIN,
                trackers = settings.MOGILEFS_TRACKERS
            )

    def __crop_square(self, data):
        _img = Image(blob = data)
        _delta = _img.width - _img.height
        if _delta > 0:
            _img.crop(_delta / 2 , 0, width = _img.height, height = _img.height)
        elif _delta < 0:
            _img.crop(0, 0, width = _img.width, height = _img.width)
        return _img.make_blob()

    def __resize(self, data, w, h):
        _img = Image(blob = data)
        _img.resize(w, h)
        return _img.make_blob()

    def get_hash_key(self):
        return self.__key

    @classmethod
    def create(cls, origin_data):
        _key = md5(origin_data).hexdigest()
        _inst = cls(_key)

        _inst.__ensure_datastore_client()
        if len(_inst.__datastore.get_paths(_inst.__origin_store_key)) == 0:
            _inst.write(origin_data)

        return _inst

    def read_large_link(self):
        return settings.IMAGE_SERVER + self.__large_store_key

    def read_small_link(self):
        return settings.IMAGE_SERVER + self.__small_store_key

    def write(self, origin_data):
        self.__ensure_datastore_client()
        _square_data = self.__crop_square(origin_data)

        #_fp = self.__datastore.new_file(self.__origin_store_key)
        #_fp.write(origin_data)
        #_fp.close()

        _large_data = self.__resize(_square_data, 180, 180)
        _fp = self.__datastore.new_file(self.__large_store_key)
        _fp.write(_large_data)
        _fp.close()

        _small_data = self.__resize(_square_data, 50, 50)
        _fp = self.__datastore.new_file(self.__small_store_key)
        _fp.write(_small_data)
        _fp.close()

    @staticmethod
    def read_image_data_by_store_key(store_key):
        _datastore = Client(
            domain = settings.MOGILEFS_DOMAIN,
            trackers = settings.MOGILEFS_TRACKERS
        )
        return _datastore.get_file_data(store_key)


import sys

from csp.tools.build import util
from csp.tools.build import scons
from subprocess import Popen, PIPE

import pickle
import re

from distutils import sysconfig

GetPythonInclude = sysconfig.get_python_inc
GetPythonLibrary = sysconfig.get_python_lib

def CheckSConsVersion(minimum):
    version = scons.GetVersion()
    if util.CompareVersions(version, minimum) < 0:
        print('SCons version %s is too old.  Please install'
              'version %s or newer.' % (version, minimum))
        sys.exit(1)

def CheckPythonVersion(minimum):
    version = '.'.join(map(str, sys.version_info[:3]))
    if util.CompareVersions(version, minimum) < 0:
        print('Python version %s is too old.  Please install'
              'version %s or newer.' % (version, minimum))
        sys.exit(1)

def CheckWXVersion(minimum):
    try:
        import wx
    except ImportError:
        print('Missing wx python module. Please install wxPython')
        sys.exit(1)

    version = wx.version()
    if util.CompareVersions(version, minimum) < 0:
        print('wxPython version (%s) is too old. Please install %s or newer.' % (version, minimum))
        sys.exit(1)

def CheckLXMLVersion():
    try:
        import lxml
    except ImportError:
        print('Missing lxml python module used by the layout2 tool. Please install.')
        sys.exit(1)

    # Don't know how to test which version that is installed.
    # Just check that it is installed for now.

def GetGCCVersion():
    p = Popen('gcc -dumpfullversion', shell=True, stdout=PIPE)
    out, err = p.communicate()
    version = out.strip()
    try:
        return tuple(map(int, version.split('.')))
    except Exception:
        return None

def CheckSwig(context, min_version, not_versions=[]):
    ok = 0
    _checking(context, 'swig', reset_cached=1)
    p = Popen(['%s' % context.env.get('SWIG', 'swig'), '-version'], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    swig_out, swig_err = p.communicate()
    if swig_err is not None:
        output = swig_err.splitlines() + swig_out.splitlines()
        output = " ".join(map(lambda x: x.strip(), output))
        match = re.search(r'SWIG Version (\d+\.\d+.\d+)', output)
        if match is not None:
            swig_version = match.groups()[0]
            if util.CompareVersions(swig_version, min_version) >= 0:
                ok = 1
                for nv in not_versions:
                    if util.CompareVersions(swig_version, nv) == 0:
                        ok = 0
    if ok:
        context.Result("yes (%s)" % swig_version)
        context.env['SWIG_VERSION'] = swig_version
    else:
        context.Result("no")
    return ok

def CheckLibVersion(context, name, source, min_version):
    _checking(context, name, min_version)
    old_LIBS = context.env.get('LIBS', '')
    context.env.Append(LIBS=[name])
    success, output = context.TryRun(source, '.c')
    version = output.strip()
    if success and util.CompareVersions(version, min_version) >= 0:
        context.Result("yes (%s)" % version)
        context.env['%s_VERSION' % name.upper()] = version
    else:
        context.Result("no")
        context.env.Replace(LIBS=old_LIBS)
    return success

def CheckOSGVersion(context, lib, min_version):
    OSG_VERSION_CHECK = '''
    /* Override any gcc2 internal prototype to avoid an error.  */
    #ifdef __cplusplus
    extern "C"
    #endif
    #include <stdio.h>
    #include <stdlib.h>
    const char *%(lib)sGetVersion(); /**/
    int main() {
        printf("%%s", %(lib)sGetVersion());
        exit(0);
        return 0;
    }
    ''' % {'lib': lib}
    return CheckLibVersion(context, lib, OSG_VERSION_CHECK, min_version)

# Lazy check that pkg-config is installed.
HAS_PKG_CONFIG = None

def _CheckPkgConfigWorks(context):
    global HAS_PKG_CONFIG
    if HAS_PKG_CONFIG is None:
        _checking(context, 'pkg-config', reset_cached=1)
        p = Popen('pkg-config --version', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        output, error = p.communicate()
        version = output.strip()
        error = error.strip()
        if not error and re.match(r'\d', version) is not None:
            HAS_PKG_CONFIG = 1
            context.Result("yes (%s)" % version)
        else:
            HAS_PKG_CONFIG = 0
            context.Result("no")
            context.Log(error)
    return HAS_PKG_CONFIG

def CheckPkgConfig(context, lib, version=None, lib_name=None, command='pkg-config', version_flag='--modversion', config_flags='--cflags --libs'):
    has_pkg_config = _CheckPkgConfigWorks(context)
    if lib_name is None:
        lib_name = lib
    _checking(context, lib, version, reset_cached=1)
    if not has_pkg_config:
        context.Result("unknown (need pkg-config)")
        return 0
    p = Popen('%s %s %s' % (command, version_flag, lib), shell=True, stdout=PIPE, stderr=PIPE)
    output, error = p.communicate()
    ok = 0
    if output is not None:
        lib_version = output.strip()
        ok = (version is None) or (util.CompareVersions(lib_version, version) >= 0)
    if ok:
        context.Result("yes (%s)" % lib_version)
        context.env['%s_VERSION' % lib_name.upper()] = lib_version
        context.env.ParseConfig('%s %s %s' % (command, config_flags, lib))
    else:
        context.Result("no")
    return ok

def CheckCommandVersion(context, lib, command, min_version=None, lib_name=None):
    if lib_name is None:
        lib_name = lib
    _checking(context, lib, min_version, reset_cached=1)
    p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    output, error = p.communicate()
    version = output.strip()
    error = error.strip()
    ok = not error and (util.CompareVersions(version, min_version) >= 0)
    if ok:
        context.Result("yes (%s)" % version)
        context.env['%s_VERSION' % lib_name.upper()] = version
    else:
        context.Result("no")
        context.Log(error)
    return ok

def _checking(context, target, min_version=None, reset_cached=0):
    if min_version is None:
        context.Message('Checking for %s... ' % (target))
    else:
        context.Message('Checking for %s (>= %s)... ' % (target, min_version))
    if reset_cached:
        # hack into scons internals to prevent the "(cached)" message from
        # displaying when the subsequent check doesn't use the SConf
        # infrastructure (e.g., a straight popen test).
        context.sconf.cached = 0

def CustomConfigure(env):
    scons.SetReading()
    scons.DisableQuiet()
    conf = env.Configure(log_file="#/.config.log")
    conf.AddTests({'CheckSwig': CheckSwig})
    conf.AddTests({'CheckLibVersion': CheckLibVersion})
    conf.AddTests({'CheckOSGVersion': CheckOSGVersion})
    conf.AddTests({'CheckCommandVersion': CheckCommandVersion})
    conf.AddTests({'CheckPkgConfig': CheckPkgConfig})
    return conf

def SetConfig(env, config):
    if config:
        if ('config' in scons.GetCommandlineTargets()) or ReadConfig(env):
            if not env.GetOption('clean'):
                config(env)
                WriteConfig(env)

def ReadConfig(env):
    config_file = env.GetBuildPath('.config')
    try:
        config = open(config_file, 'rt')
    except IOError:
        return None
    # hack to rerun the config if the SConstruct file is modified; this can
    # probably be done more cleanly using regular scons dependencies.  also
    # shouldn't hardcode the name 'SConstruct' here.
    t0 = scons.FS.getmtime(scons.File('#/SConstruct').abspath)
    t1 = scons.FS.getmtime(scons.File('#/.config').abspath)
    if t0 > t1:
        return None
    return pickle.load(config)

def SaveConfig(env, config):
    config_file = env.GetBuildPath('.config')
    pickle.dump(config, open(config_file, 'wt'))


#!/usr/bin/python
#
# -*- coding: utf-8 -*-
# vim: set ts=2 sw=2 et sts=2 ai:

import copy
import time
try:
  import simplejson
except:
  import json as simplejson
import urllib2
import logging

from cache import CACHE

from helpers import *
from libcloud_gae import ResourceNotFoundError

def parse_time(timestamp_str):
  dt = dateutil.parser.parse(timestamp_str)
  return calendar.timegm(dt.utctimetuple())+1e-6*dt.microsecond

class GCEObject(dict):
  # All attributes are dict entries
  def __setattr__(self, key, value):
    self[key] = value

  def __getattr__(self, key):
    return self[key]

  # For pickle and CACHE
  def __setstate__(self, state):
    self.__dict__ = state

  def __getstate__(self):
    return self.__dict__

  def _cache_key(self):
    return type(self).__name__.lower() + ':' + self.name

  # Functions to get/destroy stuff on gce
  @staticmethod
  def _gce_obj_get(driver, name):
    raise NotImplementedError()

  @staticmethod
  def _gce_obj_destory(driver, gce_obj):
    raise NotImplementedError()

  @staticmethod
  def _gce_obj_status(gce_obj):
    return gce_obj.extra['status']

  def update_from_gce(self, gce_obj):
    assert self.name == gce_obj.name, "%s != %s" % (self.name, gce_obj.name)
    self.name = gce_obj.name
    self.create_time = parse_time(gce_obj.extra['creationTimestamp'])
    self.status = self._gce_obj_status(gce_obj)

  # ---------------------------------
  _sentinal = []

  @classmethod
  def load(cls, name, driver=None, gce_obj=None):
    if driver:
      try:
        return cls.load(name, gce_obj=cls._gce_obj_get(driver, name))
      except ResourceNotFoundError:
        pass

    obj = cls(name, sentinal=cls._sentinal)
    cached = CACHE.get(obj._cache_key())
    if cached:
      obj.update(cached)

    if gce_obj:
      obj.update_from_gce(gce_obj)

    if not cached or gce_obj:
      obj.store()
    return obj

  def store(self):
    CACHE.set(self._cache_key(), self, time=60)

  def __init__(self, name, sentinal=None):
    assert sentinal is self._sentinal
    dict.__init__(self)
    self.name = name
    self.status = "IMAGINARY"
    self.create_time = inf

  def __eq__(self, other):
    return type(self) == type(other) and self.name == other.name

  def exists(self):
    return self.create_time != inf

  def ready(self):
    return self.status == "READY"

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

  def destroy(self, driver):
    assert self.exists()
    try:
      self._gce_obj_destory(driver, self._gce_obj_get(driver, self.name))
    except ResourceNotFoundError:
      pass
    CACHE.delete(self._cache_key())

class Disk(GCEObject):
  # Functions to get/destroy stuff on gce
  @staticmethod
  def _gce_obj_get(driver, name):
    return driver.ex_get_volume(name)

  @staticmethod
  def _gce_obj_destory(driver, gce_obj):
    return driver.destroy_volume(gce_obj)

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

  def create(self, driver, from_snapshot):
    self.update_from_gce(
        driver.create_volume(size=None, name=self.name, snapshot=from_snapshot, ex_disk_type='pd-ssd'))

class Snapshot(GCEObject):
  # Functions to get/destroy stuff on gce
  @staticmethod
  def _gce_obj_get(driver, name):
    return driver.ex_get_snapshot(name)

  @staticmethod
  def _gce_obj_destory(driver, gce_obj):
    return driver.destroy_volume_snapshot(gce_obj)

  @staticmethod
  def _gce_obj_status(gce_obj):
    # For some reason snapshot status is only available via .status rather than
    # .extra['status']!?
    return gce_obj.status

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

  def create(self, driver, from_disk):
    self.update_from_gce(
       driver.create_volume_snapshot(driver.ex_get_volume(from_disk), self.name))

class Instance(GCEObject):
  # Functions to get/destroy stuff on gce
  @staticmethod
  def _gce_obj_get(driver, name):
    return driver.ex_get_node(name)

  @staticmethod
  def _gce_obj_destory(driver, gce_obj):
    return driver.destroy_node(gce_obj)

  def update_from_gce(self, gce_obj):
    GCEObject.update_from_gce(self, gce_obj)
    self.public_ips = gce_obj.public_ips

    metadata = {}
    if 'metadata' in gce_obj.extra and 'items' in gce_obj.extra['metadata']:
      for d in gce_obj.extra['metadata']['items']:
        v = d['value']
        if v.startswith('{') or v.startswith('[') or v.startswith('"'):
          try:
            v = simplejson.loads(v)
          except ImportError:
            pass
        metadata[d['key']] = v
    self.metadata = metadata

    self.disks = []
    for d in gce_obj.extra['disks']:
      if d['kind'] != 'compute#attachedDisk':
        continue

      disk = Disk.load(d['deviceName'])
      self.disks.append(disk)

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

  def __init__(self, name, sentinal=None):
    GCEObject.__init__(self, name, sentinal)
    self.public_ips = []
    self.disks = []
    self.metadata = {}

  def ready(self):
    if self.status != "RUNNING":
      return False

    #if not self.fetch():
    #  return False

    return True

  def attached(self, disk):
    return disk in self.disks

  def fetch(self, name=""):
    if name:
      name = '/%s' % name

    if not self.public_ips:
      return None

    try:
      return urllib2.urlopen(
          "http://%s/tmp%s" % (
              self.public_ips[0], name)).read()
    except (urllib2.HTTPError, urllib2.URLError) as e:
      return None

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

  MACHINE_TYPE = 'n1-standard-2'
  BOOT_IMAGE = 'boot-image-wip-2'
  STARTUP_SCRIPT_URL = 'https://raw.githubusercontent.com/mithro/chrome-buildbot-sprint/master/metadata_watcher.py'
  WINDOWS_STARTUP_SCRIPT = 'windows-startup-script.ps1'
  TAGS = ('http-server',)

  def create(self, driver, machine_type):
    self.update_from_gce(driver.create_node(
      self.name,
      size=machine_type or self.MACHINE_TYPE,
      image=self.BOOT_IMAGE,
      ex_tags=self.TAGS,
      ex_metadata={'startup-script-url': self.STARTUP_SCRIPT_URL,
                   'windows-startup-script-ps1': self.WINDOWS_STARTUP_SCRIPT},
      ))

  def attach(self, driver, disk, mode):
    assert self.exists()
    assert self.ready()
    assert isinstance(disk, Disk)
    assert disk.exists()
    assert disk.ready()

    driver.attach_volume(
      node=self._gce_obj_get(driver, self.name),
      volume=disk._gce_obj_get(driver, disk.name),
      device=disk.name,
      ex_mode=mode)

  def detach(self, driver, disk):
    assert self.exists()
    assert self.ready()
    assert isinstance(disk, Disk)
    assert disk.exists()
    assert disk.ready()
    assert disk in self.disks

    driver.detach_volume(
      volume=disk._gce_obj_get(driver, disk.name),
      ex_node=self._gce_obj_get(driver, self.name))

  def set_metadata(self, driver, data={}, **kw):
    metadata = copy.deepcopy(self.metadata)
    metadata.update(data)
    metadata.update(kw)
    for key in metadata.keys():
      v = metadata[key]
      if isinstance(v, (int, long, float, str, unicode)):
        continue
      elif isinstance(metadata[key], (list, dict)):
        metadata[key] = simplejson.dumps(metadata[key])
      else:
        raise TypeError("Can't set metadata key %s to %r" % (key, v))
    while not driver.ex_set_node_metadata(self._gce_obj_get(driver, self.name), metadata):
      time.sleep(1)

    gce_obj = self._gce_obj_get(driver, self.name)
    self.update_from_gce(gce_obj)
    self.store()


f_label = open("label.txt",'r')
f_translate = open("translate.txt",'r')
f_flag = open("flag.txt",'r')

for line_label, line_trans in zip(f_label,f_translate):
    line_label=line_label.strip().split()
    line_trans=line_trans.strip().split()
    label_length = len(line_label)
    flag_line = []
    for i, word in enumerate(line_trans):
        piece = line_label[max(0,i-2):min(i+2,label_length)]
        if word in piece:
            flag_line.append(1)
        else:
            flag_line.append(-1)
    print(flag_line,file=f_flag)


#!/usr/bin/python
from my_pkg.aver_num import *
from my_pkg.fibo_num import *

while True:
    menu = int(input("Select menu: 1) average 2) fibonacci 3) exit ? "))
    if menu == 3:
        print("exit the program...")
        print()
        exit(0)
    elif menu == 1:
        aver()
    elif menu == 2:
        fibo()
    else:
        print("wrong menu")
    print()


#!/usr/bin/python -t

from distutils.core import setup

version = '0.70'

classifiers = [
    "Topic :: Filesystem",
    "Programming Language :: Python",
]

_name = 'stalk'
fullname = _name + '-' + version

setup(
    name = _name,
    version = version,
    url = 'http://githubs.com/kzw',
    author = 'K Z Win',
    author_email = 'kzw@happyw.info',
    license = 'GPL',
    scripts = [ 'bin/stem', 'bin/mount_stalk' ],
    packages = ['stalk', 'stalk.rw' ],
    data_files = [('/sbin',['bin/mount.fuse.Stalk']),
       ('/usr/share/doc/' + fullname, ['README.md']),
        ('/usr/share/man/man1/', ['docs/stem.1.gz']),
        ('/etc/stalk/examples', ['config/examples/internal_yum',
        'config/examples/ssh-known-hosts.read-only'])],
    long_description = 'fuse + rsync + urllib + plugin',
    classifiers = classifiers,
)


from itertools import chain
import sys

A, B, K = map(int, input().split())
diff = B - A

if diff == 0:
    print(A)
    sys.exit()

if K > diff:
    K = diff

ans = [x for x in chain(range(A, A + K), range(B - K + 1, B + 1))]
ans = sorted(list(set(ans)))

print('\n'.join(map(str, ans)))


#!/usr/bin/python3
import numpy as np
import time

N = 10000000
K = N - 200000
A = list(np.random.randint(low=0,
                           high=0x7fffffff,
                           size=(N)))
def timer(f):
    def wraper(*args):
        t1 = time.perf_counter()
        ans = f(*args)
        t2 = time.perf_counter()
        print(f'func {f.__name__} cost {(t2-t1)*1000} ms')
        return ans
    return wraper

@timer
def topk_vanilla(sequence, k):
    x = sorted(sequence)
    return x[k-1]

def partition(sequence, left, right):
    if right == left:
        return left
    s = left
    privot = sequence[s]
    i, j = left, right
    while i < j:
        while(j > i and sequence[j] > privot):
            j -= 1
        if i >= j:
            break
        sequence[i] = sequence[j]
        while(j > i and sequence[i] < privot):
            i += 1
        sequence[j] = sequence[i]
    sequence[j] = privot
    return j

# @timer
def topk_quick(sequence, k, n):
    # print(f'before partition {sequence}')
    i = partition(sequence, 0, n - 1)
    # print(f'after partition {sequence}')
    if i+1 > k:
        print(f'length is {i}')
        return topk_quick(sequence[:i], k, i)
    elif i+1 < k:
        print(f'length is {n-i-1}')
        return topk_quick(sequence[i+1:], k-i-1, n-i-1)
    else:
        print(f'find the answer is {sequence[i]}')
        exit()
        return sequence[i]
# ans1 = topk_vanilla(A, K)
# print(ans1)
ans2 = topk_quick(A, K, N)
print(ans2)


import re

import logging
_log = logging.getLogger("PingRelay")

class MessageFormatter():
    def __init__(self, message_format, alert_user="@everyone", time_format = "%Y-%m-%d %I:%M:%S %p"):
        self.format = message_format
        self.time_format = time_format
        self.alert_user = alert_user

    def format_message(self, message):
        regex = re.compile(r"%{(\w+)}")
        self.message = message
        result = regex.sub(self.fill_placeholder, self.format)
        _log.debug("Formatted with {0} resulted in {1}".format(self.format, result))
        return result

    def fill_placeholder(self, match):
        placeholder = match.group(1).lower()
        if (placeholder == "server"):
            return self.message.server
        if (placeholder == "channel"):
            return self.message.channel
        if(placeholder == "from"):
            return self.message.sender
        if(placeholder == "message"):
            return self.message.message
        if(placeholder == "alerts"):
            if self.message.has_alert:
                return self.alert_user + ": this message matched alert(s): " + self.message.get_alert_str() + "\n"
            else:
                return ""
        if(placeholder == "time"):
            return self.message.time.strftime(self.time_format)
        return match.group()


import pyodbc
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.utils.dates import days_ago

our_dag = DAG(
    "RefreshAnalysisServer",
    description='Обновление модели Analysis Server - Monopoly',
    start_date=days_ago(0, 0, 0, 0, 0),
    tags=['python'],
)

conn_str = (
    'Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.10.so.2.1;'
    'Server=10.22.5.129;'
    'Database=ReportServer;'
    'Trusted_Connection=yes;'
    )

def refresh_model():
        cnxn = pyodbc.connect(conn_str)
        cursor = cnxn.cursor()
        cursor.execute("SELECT MachineName FROM Keys")
        while 1:
            row = cursor.fetchone()
            if not row:
                break
            print(row.MachineName)
        cnxn.close()

refresh = PythonOperator(
    task_id='refresh_model',
    python_callable=refresh_model,
    dag=our_dag
)

# operation

refresh


# author: Nguyen Duc
from TheStack import Stack
"""
Mô tả cây biểu thức
"""

# Mô tả cây nhị phân
class ExpTree :
    def __init__(self, data, left = None , right = None):
        self.data = data
        self.leftChild = left
        self.rightChild = right
    # Hàm xem node đang xét có phải là lá hay không
    def isLeaf(self,node):
        return node.leftChild is None and node.rightChild is None

# Hàm đưa biểu thức vào trong cây nhị phân
def construct(exp):
    s = Stack()
    for i in exp: # Duyệt từng kí tự trong xâu
        if i in '+-*/' :
            s.push(i)
        elif i not in '()':    # Nếu là toán hạng thì tạo cây con và đưa vào Stack
            tmpTree = ExpTree(i)
            s.push(tmpTree)
        elif i == ')':         # Nếu gặp dấu ")" thì lấy ra khỏi stack 3 giá trị tạo thành 1 cây con
            right = s.pop()
            operator = s.pop()
            left = s.pop()
            tmpTree = ExpTree(operator, left , right)
            s.push(tmpTree)
    right = s.pop()
    operator = s.pop()
    left = s.pop()
    root = ExpTree(operator, left , right)
    return root

# Duyệt cây theo thứ tự giữa
def inOrderTraversal(root):
    if root is not None:
        if not root.isLeaf(root):
            print('(' , end = ' ')
        inOrderTraversal(root.leftChild)
        print(root.data , end = ' ')
        inOrderTraversal(root.rightChild)
        if not root.isLeaf(root) :
            print(')' ,end = ' ')
def compute(operator, leftOperand , rightOperand):
    if operator == '+' :
        return float(leftOperand + rightOperand)
    elif operator == '-':
        return float(leftOperand - rightOperand)
    elif operator == '/' :
        return float(leftOperand/rightOperand)
    else:
        return float(leftOperand* rightOperand)
def calculateExpression(expTree):
    if expTree.isLeaf(expTree):
        return float(expTree.data)
    operator = expTree.data
    if expTree.leftChild.isLeaf(expTree.leftChild):
        leftOperand = float(expTree.leftChild.data)
    else:
        leftOperand = calculateExpression(expTree.leftChild)
    if expTree.rightChild.isLeaf(expTree.rightChild):
        rightOperand = float(expTree.rightChild.data)
    else:
        rightOperand = calculateExpression(expTree.rightChild)
    return compute(operator, leftOperand,rightOperand)

# xâu đầu vào phải có đử dấu ngoặc, kể cả các phép nhân, chia
t = construct('(((2+3)*2)*2)+2')
print(calculateExpression(t))
inOrderTraversal(t)


class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2:
            return 0

        hash = [True] * n
        hash[0] = False
        hash[1] = False
        for i in xrange(2, n):
            if hash[i] == True:
                for j in xrange(2, (n-1)//i+1):
                    hash[i*j] = False
        return sum(hash)