'''
# mit_course_number_6.0001_problem_set3_solutions

MIT Course 6.0001: Introduction to Computer Science and Programming in Python

Author: Eshgin Guluzade

Specialty: Mechanical Engineer

Country: Azerbaijan

My LinkedIn: https://www.linkedin.com/in/eshginguluzade/

My Quora: https://www.quora.com/profile/Eshgin-Guluzade

My Youtube Channel: https://www.youtube.com/channel/UCr6yufueEVaXBHgM8x1YlTw
'''

def substitute_hand(hand, letter):
    """
    Allow the user to replace all copies of one letter in the hand (chosen by user)
    with a new letter chosen from the VOWELS and CONSONANTS at random. The new letter
    should be different from user's choice, and should not be any of the letters
    already in the hand.

    If user provide a letter not in the hand, the hand should be the same.

    Has no side effects: does not mutate hand.

    For example:
        substitute_hand({'h':1, 'e':1, 'l':2, 'o':1}, 'l')
    might return:
        {'h':1, 'e':1, 'o':1, 'x':2} -> if the new letter is 'x'
    The new letter should not be 'h', 'e', 'l', or 'o' since those letters were
    already in the hand.

    hand: dictionary (string -> int)
    letter: string
    returns: dictionary (string -> int)
    """
    herfler = 'aeioubcdfghjklmnpqrstvwxyz'
    if letter in hand:
        for i in hand.keys():
           herfler = herfler.replace(i, '')
        new_letter = random.choice(herfler)
        hand[new_letter] = hand[letter]
        del(hand[letter])
        new_hand = hand
        return new_hand
    else:
        return hand

def play_game(word_list):

        numberOfSubs = 0
        numberOfReply = 0

        new_score = 0
        old_score = 0

    #for hands in range (numberOfHands):
        hand = deal_hand(HAND_SIZE)
        old_hand = hand.copy()
        (display_hand(hand))

        if numberOfSubs == 0:
            subs_yes_no = input('Would you like to substitute a letter? ')
            if subs_yes_no == 'yes':
                letter = input('Which letter would you like to replace: ')
                hand = substitute_hand(hand, letter)
                old_hand = hand.copy()
                numberOfSubs = 1
            else:
                print(' ')
                numberOfSubs = 1
        #else:
        #    continue

        old_score = play_hand(hand, word_list)
        print('Total score for this hand: ', old_score)
        print('------------------------------------')
        if numberOfReply == 0:
            replay  = input('Would you like to replay the hand? ')
            if replay == 'yes':
                new_score = play_hand(old_hand, word_list)
                print('Total score for this hand: ', new_score)
                print('------------------------------------')
                numberOfReply = 1
            else:
                numberOfReply = 1

        #else:
        #    continue

        global overall_score
        overall_score += max(old_score, new_score)

        #hands += 1

Problem 6 Playing a game____substitute_hand(hand, letter)__and__play_game(word_list).py


'''
Created on 04/09/2017

@author: chernomirdinmacuvele
'''
from PyQt5.Qt import Qt, QSqlRelationalTableModel
from PyQt5 import QtSql
import QT_msg

class viewModel():
    def __init__(self, dbcon= None, TblName= None, dictModel=None, filtro=None):
        self.TblName = TblName
        self.dictModel = dictModel
        self.filtro = filtro
        self.msg = QT_msg
        self.txt_306 = "Erro nº:309 \nPorfavor tente de novo."
        self.txt_100 = "Erro nº: 100 \nPorfavor tente de novo."

        self.setViewModel()

    def setViewModel(self):
        self.Model = QSqlRelationalTableModel()
        self.Model.setTable(self.TblName)
        self.Model.setFilter(self.filtro)
        for idx, val in enumerate (self.dictModel['val2Rel']):
            if val is not None:
                self.Model.setRelation(idx, QtSql.QSqlRelation(self.dictModel["relTblName"][idx], val[0], val[1]))
        self.Model.setSort(0, Qt.AscendingOrder)
        for idx, val in enumerate (self.dictModel['newNames']):
            self.Model.setHeaderData(idx, Qt.Horizontal, val)
        bOK = self.Model.select()
        if not bOK:
            self.msg.error(txt="Erro na configuracao do Modelo", verbTxt=str(self.Model.lastError().text()))


# -*- coding: utf-8 -*-
from openerp import api, fields, models

class GrilleSalaire(models.Model):

    _inherit = ['mail.thread']
    _name = 'corpe_paie.grille_salaire'
    _description = 'Grille salariale'
    _rec_name = "code"
    _order = "num_ordre asc"

    name = fields.Char(string="Description", required=True)

    types_contrat = fields.Many2many(
        string='Type de contrat de cette grille',
        required=True,
        help="type de contrat prenant en charge cette grille",
        comodel_name='hr.contract.type',
        relation='model_grille_to_typecontrat')

    code = fields.Char(string="Code", required=True)

    montant = fields.Float(
        string="Salaire",
        required=True,
        digits=(16, 2))

    num_ordre = fields.Integer(
        string="Numero d'ordre",
        required=True)

    categ_id = fields.Many2one(
        comodel_name='corpe_paie.categorie_salariale',
        string="Categorie salariale")

    ech_id = fields.Many2one(
        comodel_name='corpe_paie.echelon_salariale',
        string="Echellon")

    contracts = fields.One2many(
        string='contracts',
        required=False,
        readonly=True,
        index=False,
        default=None,
        help="contrats dans cette grille",
        comodel_name='hr.contract',
        inverse_name='grille_salaire')

    masse = fields.Float(
        string='Masse de la grille',
        readonly=True)

    @api.onchange('categ_id', 'ech_id')
    def onchange_num_ordre(self):
        if self.categ_id and self.ech_id:
            self.code = str(self.categ_id.code + self.ech_id.code).upper()
            self.num_ordre = self.categ_id.num_ordre * 20
            self.num_ordre += self.ech_id.num_ordre

    @api.constrains("montant")
    def update_salaries_employee(self):
        contract_obj = self.env["hr.contract"]
        for record in self:
            contracts = contract_obj.search([('grille_salaire', '!=', False)])
            contracts.update_salary()

    @api.constrains('montant', "contracts")
    def check_masse(self):
        self.update_masse()

    @api.multi
    def update_masse(self):
        for record in self:
            record.masse = sum(record.contracts.mapped('wage'))


'''
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/
Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

Example 1:
Input: data = [1,0,1,0,1]
Output: 1
Explanation:
There are 3 ways to group all 1's together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.
'''
'''
Time:O(n)
Space:O(1)
'''
class Solution:
    def minSwaps(self, data: List[int]) -> int:
        s = sum(data)
        cursum = sum(data[:s])
        res = s - cursum
        for i in range(1, len(data) - s + 1):
            cursum = cursum - data[i-1] + data[i+s-1]
            res = min(res, s - cursum)
        return res

1151. Minimum Swaps to Group All 1's Together.py


import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QTextEdit, QLabel
from PyQt5.QtCore import Qt
from collections import defaultdict
import heapq
# Importações: collections e heapq são módulos usados para trabalhar com coleções e filas de prioridade (heap), respectivamente.

class NoHuffman:
    def __init__(self, caractere, frequencia):
        self.caractere = caractere
        self.frequencia = frequencia
        self.esquerda = None
        self.direita = None

    def __lt__(self, outro):
        return self.frequencia < outro.frequencia

# Classe NoHuffman: Define uma classe para representar um nó na árvore de Huffman. Cada nó possui um caractere, uma frequência,
# uma referência para o nó filho esquerdo e uma referência para o nó filho direito. A função __lt__ é usada para comparar nós com
# base em suas frequências.

def construir_arvore_huffman(texto):
    frequencias = defaultdict(int)

    # Cria um dicionário padrão onde as chaves são caracteres e os valores são inicializados com zero.

    for char in texto:
        frequencias[char] += 1

    # Conta a frequência de cada caractere no texto, incrementando os valores no dicionário.

    fila_prioridade = [NoHuffman(caractere, frequencia) for caractere, frequencia in frequencias.items()]

    # Cria uma lista de nós NoHuffman com base nas frequências de caracteres no dicionário.

    heapq.heapify(fila_prioridade)

    # Transforma a lista de nós em uma fila de prioridade (heap) usando a função heapify.

    while len(fila_prioridade) > 1:
        no_esquerda = heapq.heappop(fila_prioridade)
        no_direita = heapq.heappop(fila_prioridade)
        no_pai = NoHuffman(None, no_esquerda.frequencia + no_direita.frequencia)
        no_pai.esquerda = no_esquerda
        no_pai.direita = no_direita
        heapq.heappush(fila_prioridade, no_pai)

    # Combina os nós de menor frequência em um novo nó pai, repetindo o processo até que reste apenas um nó na fila.

    return fila_prioridade[0]

    # Retorna o nó raiz da árvore de Huffman construída.

def codificar_texto(arvore_huffman, texto):
    codigos = {}

    # Cria um dicionário para armazenar os códigos de Huffman de cada caractere.

    def gerar_codigos(no, codigo_atual=""):
        if no is not None:
            if no.caractere is not None:
                codigos[no.caractere] = codigo_atual
            gerar_codigos(no.esquerda, codigo_atual + "0")
            gerar_codigos(no.direita, codigo_atual + "1")

    # Função recursiva para gerar os códigos de Huffman a partir da árvore.

    gerar_codigos(arvore_huffman)

    # Gera os códigos de Huffman para cada caractere na árvore.

    codigo_final = ""
    for char in texto:
        codigo_final += codigos[char]

    # Codifica o texto substituindo cada caractere pelo seu código de Huffman.

    return codigo_final

    # Retorna o texto codificado.

class HuffmanGUI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Codificação de Huffman")
        self.setFixedSize(600, 400)  # Define o tamanho fixo da janela
        self.setWindowFlag(Qt.WindowMaximizeButtonHint, False)  # Remove o botão de maximizar

        # Janela principal
        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)

        layout = QVBoxLayout()

        # Título e campo de entrada de texto
        input_label = QLabel("Texto a ser codificado:")
        layout.addWidget(input_label)

        self.text_edit = QTextEdit()
        self.text_edit.setStyleSheet("background-color: #1E90FF; color: white; border-radius: 8px;")
        layout.addWidget(self.text_edit)

        # Botão para codificar o texto
        encode_button = QPushButton("Codificar")
        encode_button.clicked.connect(self.codificar)
        layout.addWidget(encode_button)

        # Título e área de exibição do texto codificado com cor ligeiramente mais escura
        result_label = QLabel("Texto resultante:")
        layout.addWidget(result_label)

        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setStyleSheet("background-color: #1E90FF; color: white; border-radius: 8px;")
        layout.addWidget(self.result_text)

        main_widget.setLayout(layout)

        # Aplicar estilo CSS à janela principal
        self.setStyleSheet("""
            QWidget {
                background-color: #9dcfff;
                border-radius: 70px;
            }
            QPushButton {
                background-color: #1E90FF;
                border: none;
                color: white;
                text-align: center;
                font-size: 16px;
                padding: 10px 20px;
                margin: 4px 2px;
                border-radius: 8px;
            }
            QPushButton:hover {
                background-color: #1C86EE;
            }
        """)

    def codificar(self):
        texto_original = self.text_edit.toPlainText()
        arvore_huffman = construir_arvore_huffman(texto_original)
        codigo_comprimido = codificar_texto(arvore_huffman, texto_original)
        self.result_text.setPlainText(codigo_comprimido)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = HuffmanGUI()
    window.show()
    sys.exit(app.exec_())


from emmaApp.utils.authentication_manager import androidmanagement, cloud_project_id

CALLBACK_URL = 'https://storage.googleapis.com/android-management-quick-start/enterprise_signup_callback.html'

# Generate a signup URL where the enterprise admin can signup with a Gmail account.
signup_url = androidmanagement.signupUrls().create(
    projectId=cloud_project_id,
    callbackUrl=CALLBACK_URL
).execute()

print('Please visit this URL to create an enterprise:', signup_url['url'])

enterprise_token = input('Enter the code: ')

# Complete the creation of the enterprise and retrieve the enterprise name.
enterprise = androidmanagement.enterprises().create(
    projectId=cloud_project_id,
    signupUrlName=signup_url['name'],
    enterpriseToken=enterprise_token,
    body={}
).execute()

enterprise_name = enterprise['name']

# EAJmqckxDX-PV1eJGZUS5SYmrHcB1O-stL5DbRbcwYl3PyTV_YHPDSPjScQKNav2i747XJSZSGAf5ukOM4vfUtTadFXigwBMIlvee4YkpVGzw_UBwcBtwisw
print('\nYour enterprise name is', enterprise_name)

# Paste the enterprise name here.
# enterprise_name = 'enterprises/LC03hr5qbt'


# 必须要加的头文件

import decimal
import json
from django.http import JsonResponse
from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，进行文字匹配
import urllib.request, urllib.error  # 制定URL，获取网页数据

# 得到指定一个URL的网页内容
def askURL(url):
    head = {
        "User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122  Safari / 537.36"
    }

    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # html = response.read().decode("gbk")
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html

def get_plate():
    url = "https://flash-api.xuangubao.cn/api/plate/rank?field=core_avg_pcp&type=0"
    html = askURL(url)  # 保存获取到的网页源码
    html = json.loads(html)

    # context = decimal.getcontext()  # 获取decimal现在的上下文
    # context.rounding = decimal.ROUND_HALF_UP  # 修改rounding策略

    # 提取前5排名的版块
    res = {}
    data = html['data']
    res['plate_up'] = [data[0], data[1], data[2], data[3], data[4],
                       data[5]]

    data.reverse()

    # print(type(data))
    res['plate_down'] = [data[0], data[1], data[2], data[3], data[4],
                         data[5]]

    return res

def get_plate_data():
    # 先获取版块的排行榜，用代码表示
    plate_code = get_plate()
    base_url = "https://flash-api.xuangubao.cn/api/plate/data?fields=plate_id,plate_name,fund_flow,rise_count,fall_count,stay_count,limit_up_count,core_avg_pcp,core_avg_pcp_rank,core_avg_pcp_rank_change,top_n_stocks,bottom_n_stocks&plates="

    context = decimal.getcontext()  # 获取decimal现在的上下文
    context.rounding = decimal.ROUND_HALF_UP  # 修改rounding策略

    res={'plate_up':[],'plate_down':[]}

    # 用代码拼接URL，获取每个热门版块的代表公司
    j = 1
    for i in plate_code['plate_up']:
        plate=[]
        i = str(i)
        url = base_url + i
        html = askURL(url)  # 保存获取到的网页源码
        html = json.loads(html)

        id = str(j)

        plate_name = html['data'][i]['plate_name']

        plate_change_percent = html['data'][i]['core_avg_pcp']
        plate_change_percent = decimal.Decimal(plate_change_percent * 100).quantize(decimal.Decimal("0.01"))
        plate_change_percent = str(plate_change_percent)
        plate_change_percent += "%"

        company_id = html['data'][i]['top_n_stocks']['items'][0]['symbol']
        company_id = company_id[:-3]

        company_change_percent = html['data'][i]['top_n_stocks']['items'][0]['change_percent']
        company_change_percent = decimal.Decimal(company_change_percent * 100).quantize(decimal.Decimal("0.01"))
        company_change_percent = str(company_change_percent)
        company_change_percent += "%"

        simple_name = html['data'][i]['top_n_stocks']['items'][0]['stock_chi_name']

        plate.append(id)
        plate.append(plate_name)
        plate.append(company_id)
        plate.append(simple_name)
        plate.append(plate_change_percent)
        plate.append(company_change_percent)

        res['plate_up'].append(plate)
        j += 1

    j = 1
    for i in plate_code['plate_down']:
        plate = []
        i = str(i)
        url = base_url + i
        html = askURL(url)  # 保存获取到的网页源码
        html = json.loads(html)

        id = str(j)

        plate_name = html['data'][i]['plate_name']

        plate_change_percent = html['data'][i]['core_avg_pcp']
        plate_change_percent = decimal.Decimal(plate_change_percent * 100).quantize(decimal.Decimal("0.01"))
        plate_change_percent = str(plate_change_percent)
        plate_change_percent += "%"

        company_id = html['data'][i]['bottom_n_stocks']['items'][0]['symbol']
        company_id = company_id[:-3]

        company_change_percent = html['data'][i]['bottom_n_stocks']['items'][0]['change_percent']
        company_change_percent = decimal.Decimal(company_change_percent * 100).quantize(decimal.Decimal("0.01"))
        company_change_percent = str(company_change_percent)
        company_change_percent += "%"

        simple_name = html['data'][i]['bottom_n_stocks']['items'][0]['stock_chi_name']

        plate.append(id)
        plate.append(plate_name)
        plate.append(company_id)
        plate.append(simple_name)
        plate.append(plate_change_percent)
        plate.append(company_change_percent)

        res['plate_down'].append(plate)

        j += 1

    # res.encode(encoding='utf-8')
    print()
    # print(res)
    print()
    return res

def plate_data(request):
    res = get_plate_data()
    return JsonResponse({
        'result': "success",
        'data': res,
    })


#%%

import matplotlib.pyplot as plt

from sklearn import datasets
import time
import numpy as np
import pandas as pd
import seaborn as sn
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
#%%

from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
import pickle as pickle

class ROLF():
    def __init__(self,p=1.5,lr_center = 0.1, lr_sigma = 0.1,initSigma = 2,strategy = ''):
        self.p = p
        self.lr_center = lr_center
        self.lr_sigma = lr_sigma
        self.initSigma = initSigma
        self.lables = None
        self.assignmensts = None
        self.center = None
        self.sigma = None
        self.strategy = strategy

    def _setSigma_Standard(self):
        return self.initSigma
    def _setSigma_Minimum(self):
        return np.min(self.sigma)
    def _setSigma_Maximum(self):
        return np.max(self.sigma)
    def _setSigma_Mean(self):
        return np.mean(self.sigma)

    def _set_setSigma_Strategy(self,strategy):
        """set the choosen strategy to init new neurons sigma"""
        if strategy == "min":
            return self._setSigma_Minimum
        elif strategy == "max":
            return self._setSigma_Maximum
        elif strategy == "mean":
            return self._setSigma_Mean
        else:
            return self._setSigma_Standard

    def _find_neurons(self,X,strategy):
        """Find the neurons in out training data
            k is the number of neurons found so far. We use this, so we are able to slice the center
            array, such that we do not have to perform the distance calculation for the zero (non center) elements.
            the first neuron gets initilized on the first pattern right away
        """
        X = np.asarray(X)
        funct_setSigma = self._set_setSigma_Strategy(self.strategy)
        self.center = np.zeros(X.shape)
        self.sigma = np.ones(len(X))*self.initSigma
        self.center[0] = X[0]
        k = 1
        for x in X:
            distance = np.linalg.norm(self.center[:k] - x,axis=1)
            acceptors = np.where(distance <= self.sigma[:k]*self.p)[0]
            if len(acceptors) > 0:
                winner = acceptors[np.argmin(distance[acceptors])]
                self.center[winner] += self.lr_center * (x-self.center[winner])
                self.sigma[winner] += self.lr_sigma * (distance[winner]-self.sigma[winner])
            else:
                self.center[k] = x
                self.sigma[k] = funct_setSigma()
                k += 1
        self.center = self.center[:k]
        self.sigma = self.sigma[:k]

    def _find_neighbourhood(self):
        """calculate the neighbourhood graph and assign cluster labels"""
        cluster_id = 0
        notIterated = list(np.arange(0,len(self.center)))
        self.lables = np.zeros(len(self.center),dtype=int)
        while len(notIterated) > 0:
            stack = [notIterated[0]]
            notIterated.remove(notIterated[0])
            while len(stack) > 0:
                NeuronNeuronDist = np.linalg.norm(self.center[stack[-1]] - self.center[notIterated],axis = 1)
                inPercField = NeuronNeuronDist - ((self.sigma[notIterated] + self.sigma[stack[-1]]) * self.p)
                connected = np.where(inPercField <= 0)
                self.lables[stack[-1]] = cluster_id
                stack.pop()
                for k in np.flip(connected[0]):
                    stack.append(notIterated[k])
                    notIterated.remove(notIterated[k])
            cluster_id += 1

    def fit(self,X,strategy = ""):
        """run the fitting process"""
        self._find_neurons(X,strategy)
        self._find_neighbourhood()

    def predict(self,x):
        """predict the label of a new pattern"""
        distance = np.linalg.norm(self.center - x,axis=1)
        acceptors = np.where(distance <= self.sigma*self.p)[0]
        if len(acceptors) > 0:
            return self.lables[acceptors[0]]
        else:
            return -1
    def savemodel(self):
        np.savetxt('ROLFcenter.csv', self.center, delimiter=',')
        np.savetxt('ROLFlables.csv', self.lables, delimiter=',')

        '''
        df = pd.DataFrame()
        df['labels'] = self.lables
        df['centers0'] = self.center[0]
        df['p'] = self.p
        df['lr_center'] = self.lr_center
        df['lr_sigma'] = self.lr_sigma
        df['initSigma'] = self.initSigma
        print(df.head(5))
        '''
#%%

# Run the examples on your own, replace make_circles with make_moons to change the example
# If you get to much cluster or to less, play around with the initSigma
'''
X = pd.read_csv('hammerhead_reduced.csv', delimiter = ',')
X = X.fillna(0)
del X['epoch']
#Z,y = datasets.make_moons(n_samples=100000, noise=0.05)
rolf = ROLF(p=2,lr_center = 0.01, lr_sigma = 0.01,initSigma = 20, strategy = 'max')
start_time = time.time()
rolf.fit(X)
with open('rolf.pickle', 'wb') as handle:
    pickle.dump(rolf, handle)
    handle.close()
print('')
print("fitting ROLF took %s seconds" % (time.time() - start_time))
print(len(rolf.center), 'neurons approximating', len(X), 'datapoints')
print(len(np.unique(rolf.lables)), 'clusters where found')
print(silhouette_score(rolf.center, rolf.lables))
'''
##### Vizualizing learned Network ###############################################
'''
fig, (ax1, ax2) = plt.subplots(1, 2)

for c in range(0, len(rolf.center)):
    radius = rolf.sigma[c]*rolf.p
    circle = plt.Circle((rolf.center[c][0], rolf.center[c][1]),radius, alpha=0.15,)
    ax1.add_patch(circle)
    circle = plt.Circle((rolf.center[c][0], rolf.center[c][1]),rolf.sigma[c], alpha=0.25,)
    ax1.add_patch(circle)

    for k in range(0, len(rolf.center)):
        distance = np.linalg.norm(rolf.center[c] - rolf.center[k])
        perc = (rolf.sigma[c] + rolf.sigma[k])*rolf.p
        if distance <= perc:
            ax1.plot([rolf.center[c][0], rolf.center[k][0]], [
                    rolf.center[c][1], rolf.center[k][1]], linewidth=1, color='black')
ax1.scatter(X[:, 0], X[:, 1], marker='.', color="black", alpha=0.02)
ax1.set_title("network vizualization")

##### Vizualize input space clustering #############################################

labels = []
points = []
for x in np.arange(-50,50,1):
    for y in np.arange(-20,20,1):
        points.append([x,y])
        labels.append(rolf.predict([x,y]))
points = np.asarray(points)
labels = np.asarray(labels)

for i in np.unique(labels):
    cluster = points[labels==i]
    if i == -1:
        ax2.scatter(cluster[:,0],cluster[:,1],label='class: unknown')
    else:
        ax2.scatter(cluster[:,0],cluster[:,1],label='class: ' + str(i))

ax2.set_title("predicted clusters for the input space")
plt.show()
'''
'''
#3D Plots

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
labels = []
points = []
for x in np.arange(-50,50,0.1):
    for y in np.arange(-20,20,0.1):
        for z in np.arange(-20, 20, 0.1):
            print(type(x))
            print(type(y))
            print(type([x,y,z]))
            points.append([x,y,z])
            labels.append(rolf.predict([x,y,z]))
points = np.asarray(points)
print(points)
labels = np.asarray(labels)
print(labels)
for i in np.unique(labels):
    cluster = points[labels==i]
    if i == -1:
        plt.scatter(cluster[:,0],cluster[:,1],cluster[:,2],label='class: unknown')
    else:
        plt.scatter(cluster[:,0],cluster[:,1],cluster[:,2],label='class: ' + str(i))

plt.title("predicted clusters for the input space")
plt.show()

#plotting
'''
#Plotting PCA reduced Clusters
'''
rolf_PCA = PCA(n_components=2).fit_transform(rolf.center)
plt.scatter(rolf_PCA.T[0], rolf_PCA.T[1], c=rolf.lables)
plt.title('PCA reduced Clusters')
plt.ylabel('PCA_comp1')
plt.xlabel('PCA_comp0')
plt.show()
'''
'''
#decision tree on classification task
clf = DecisionTreeClassifier(random_state=1234)
model = clf.fit(rolf_PCA, rolf.lables)
text_representation = tree.export_text(clf)
print(text_representation)

fig = plt.figure(figsize=(50,25))
_ = tree.plot_tree(clf,
                   feature_names=['PCA_comp0','PCA_comp1'],
                   class_names=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29'],
                   filled=True)

#clf DecisionTreeClassifier
import graphviz
# DOT data
dot_data = tree.export_graphviz(clf, out_file=None,
                                feature_names=['PCA_comp0','PCA_comp1'],
                                filled=True)

# Draw graph
graph = graphviz.Source(dot_data, format="png")
graph
#nochmal für gesamten Featureraum
'''
'''
def gentargetfile():
    with open('rolf.pickle', 'rb') as handle:
        ROLF = pickle.load(handle)
    X = pd.read_csv('hammerhead_reduced.csv', delimiter=',')
    X = X.fillna(0)
    del X['epoch']
    X = X.to_numpy()
    results = []
    for i in range(len(X)):
        results.append(ROLF.predict(X[i]))
    y = np.array(results)
    return y

clf = DecisionTreeClassifier(random_state=1234)
model = clf.fit(X, gentargetfile())
text_representation = tree.export_text(clf)
print(text_representation)

fig = plt.figure(figsize=(150,75),dpi = 200)
_ = tree.plot_tree(clf,filled=True)
fig.savefig("decistion_tree.png")
'''


import math
import policies.total
import random
# import total

stripe_fail_cases_correlated_dict = {}
def stripe_fail_cases_correlated(n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks):
    key = (n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks)
    # print(key)
    if key in stripe_fail_cases_correlated_dict:
        return stripe_fail_cases_correlated_dict[key]
    if num_failed_disks < num_affected_racks:
        stripe_fail_cases_correlated_dict[key] = 0
        return 0
    if num_failed_disks > num_affected_racks * drives_per_rack:
        stripe_fail_cases_correlated_dict[key] = 0
        return 0
    if num_racks < n_net or num_racks < num_affected_racks:
        stripe_fail_cases_correlated_dict[key] = 0
        return 0
    if num_failed_chunks > n_net:
        stripe_fail_cases_correlated_dict[key] = 0
        return 0

    count = 0
    if num_racks == 1:
        if n_net == 0:
            count =  math.comb(drives_per_rack, num_failed_disks)
        else:  # n_net = 1
            if num_failed_chunks == 1:
                count = num_failed_disks * math.comb(drives_per_rack, num_failed_disks)
            else:
                count = drives_per_rack * math.comb(drives_per_rack, num_failed_disks)
        stripe_fail_cases_correlated_dict[key] = count
        # print(count)
        return count

    max_failures_curr_rack = min(num_failed_disks-num_affected_racks+1, drives_per_rack, num_failed_disks)
    count = 0

    for curr_rack_failure in range(0, max_failures_curr_rack+1):
        curr_rack_affected = 0 if curr_rack_failure == 0 else 1
        count += math.comb(drives_per_rack, curr_rack_failure) * stripe_fail_cases_correlated(n_net, num_failed_chunks, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected)
        if n_net > 0:
            count += math.comb(drives_per_rack, curr_rack_failure) * (
                        curr_rack_failure * stripe_fail_cases_correlated(n_net-1, num_failed_chunks-1, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected) +
                        (drives_per_rack - curr_rack_failure) * stripe_fail_cases_correlated(n_net-1, num_failed_chunks, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected)
                        )
    stripe_fail_cases_correlated_dict[key] = count
    # print(count)
    return count

stripe_fixed_fail_chunk_cases_correlated_dict = {}
def stripe_fixed_fail_chunk_cases_correlated(n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks):
    key = (n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks)

    if key in stripe_fixed_fail_chunk_cases_correlated_dict:
        return stripe_fixed_fail_chunk_cases_correlated_dict[key]
    if num_failed_disks < num_affected_racks:
        stripe_fixed_fail_chunk_cases_correlated_dict[key] = 0
        return 0
    if num_failed_disks > num_affected_racks * drives_per_rack:
        stripe_fixed_fail_chunk_cases_correlated_dict[key] = 0
        return 0
    if num_racks < n_net or num_racks < num_affected_racks:
        stripe_fixed_fail_chunk_cases_correlated_dict[key] = 0
        return 0
    if num_failed_chunks > n_net or num_failed_chunks < 0:
        stripe_fixed_fail_chunk_cases_correlated_dict[key] = 0
        return 0

    count = 0
    if num_racks == 1:
        if n_net == 0:
            count =  math.comb(drives_per_rack, num_failed_disks)
        else:  # n_net = 1
            if num_failed_chunks == 1:
                count = num_failed_disks * math.comb(drives_per_rack, num_failed_disks)
            else:
                # print(key)
                # print("drives_per_rack {} . num_failed_disks {}".format(drives_per_rack, num_failed_disks))
                count = (drives_per_rack - num_failed_disks) * math.comb(drives_per_rack, num_failed_disks)
        stripe_fixed_fail_chunk_cases_correlated_dict[key] = count
        # print(key)
        # print(count)
        return count

    max_failures_curr_rack = min(num_failed_disks-num_affected_racks+1, drives_per_rack, num_failed_disks)
    count = 0

    for curr_rack_failure in range(0, max_failures_curr_rack+1):
        curr_rack_affected = 0 if curr_rack_failure == 0 else 1
        count += math.comb(drives_per_rack, curr_rack_failure) * stripe_fixed_fail_chunk_cases_correlated(n_net, num_failed_chunks, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected)
        if n_net > 0:
            count += math.comb(drives_per_rack, curr_rack_failure) * (
                        curr_rack_failure * stripe_fixed_fail_chunk_cases_correlated(n_net-1, num_failed_chunks-1, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected) +
                        (drives_per_rack - curr_rack_failure) * stripe_fixed_fail_chunk_cases_correlated(n_net-1, num_failed_chunks, num_racks-1,
                            drives_per_rack, num_failed_disks-curr_rack_failure, num_affected_racks-curr_rack_affected)
                        )
    stripe_fixed_fail_chunk_cases_correlated_dict[key] = count
    # print(key)
    # print("\t{}".format(count))
    return count

recoverability_dict = {}
#function to calculate recoverability
def calculate_recoverability(k, l, r, R):
    key = (k, l, r, R)
    if key in recoverability_dict:
        return recoverability_dict[key]

    n = k + l + r

    #create k data blocks
    data_blocks = []
    for i in range(k):
        data_blocks.append('k'+str(i))

    #create l local parity blocks
    local_parities = []
    for i in range(l):
        local_parities.append('l'+str(i))

    #create r global parity blocks
    global_parities = []
    for i in range(r):
        global_parities.append('r'+str(i))

    #here is the whole set of data and parity blocks
    data_and_parity = data_blocks + local_parities + global_parities

    print(data_and_parity)

    #variables required to group data blocks into l local groups
    num_local_groups = l
    local_groups = []
    local_group_ids = []

    #group data blocks into l groups
    start = 0
    end = k
    step = int(k/l)
    for i in range(start, end, step):
        x = i
        local_groups.append(data_blocks[x:x+step])

    #setting initial recoverable patterns to 0
    recoverable = 0

    iters=100000
    #start the recoverability calculation
    for i in range(iters):
        k_terms = 0
        l_terms = l
        r_terms = r
        random_comb = random.sample(data_and_parity, R)
        comb_list = list(random_comb)

        #find number of data blocks in a failure combo/pattern
        for j in range(len(random_comb)):
            if 'k' in comb_list[j]:
                k_terms = k_terms + 1

        #check if failed data block can be swapped with its local group parity
        #calculate the number of failed data blocks and available global parity blocks
        for j in range(len(random_comb)):
            if 'k' in random_comb[j]:
                for m in range(len(local_groups)):
                    if random_comb[j] in local_groups[m]:
                        local_group_id = m
                        break
                if local_parities[local_group_id] not in comb_list:
                    k_terms = k_terms - 1
                    comb_list.append(local_parities[local_group_id])
            if 'r' in random_comb[j]:
                r_terms = r_terms - 1
        if k_terms <= r_terms:
            recoverable = recoverable + 1

    res = recoverable/iters
    recoverability_dict[key] = res
    return res

def stripe_total_cases(k_net, p_net, total_drives, drives_per_rack):
    num_racks = total_drives // drives_per_rack
    n_net = k_net + p_net
    count =  math.comb(num_racks, n_net)
    count *= (drives_per_rack ** n_net)
    return count

if __name__ == "__main__":
    n_net = 10
    total_drives = 1100
    total_cases = stripe_total_cases(8, 2, total_drives, 100)
    # failure_cases = stripe_fail_cases(10, 3, 100, [2,1,1,0,0,0,0,0,0,0], 0)
    num_failed_chunks = 4
    num_racks = 11
    drives_per_rack = 100
    num_failed_disks = 5
    num_affected_racks = 5
    failure_cases_fixed_chunks = stripe_fixed_fail_chunk_cases_correlated(n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks)
    failure_cases_1 = stripe_fail_cases_correlated(n_net, num_failed_chunks, num_racks, drives_per_rack, num_failed_disks, num_affected_racks)
    failure_cases_2 = stripe_fail_cases_correlated(n_net, num_failed_chunks+1, num_racks, drives_per_rack, num_failed_disks, num_affected_racks)
    print("total cases: \t\t\t{}\nfailure_cases_fixed_chunks: \t{}".format(total_cases, failure_cases_fixed_chunks))
    print("failure_cases_1: \t\t{}\nfailure_cases_2: \t\t{}\ndiff: \t\t\t\t{}".format(failure_cases_1, failure_cases_2, failure_cases_1 - failure_cases_2))
    stripe_failure_prob = failure_cases / total_cases
    print("stripe fail prob: \t{}".format(stripe_failure_prob))

    chunks_per_drive = 100
    num_stripes = chunks_per_drive * total_drives // n_net
    no_failure_prob = (1-stripe_failure_prob) ** num_stripes
    print("system fail prob: {}".format(1-no_failure_prob))


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

"""
A module for working with suffix arrays.

Author: venantius
https://github.com/venantius/takehome/blob/master/readyforzero/search/suffixarray.py
License: Eclipse license
"""

import difflib

class SuffixArray(object):
    """
    Suffix Array class. Ideal for fast fuzzy string matching
    """
    def __init__(self):
        self.array = []
        self.hashmap = {}

    def insert(self, string):
        """
        Add a new string to the suffix array
        """
        for i in range(len(string)):
            self.array.append(string[i:])
            try:
                self.hashmap[string[i:]].append(string)
            except KeyError:
                self.hashmap[string[i:]] = [string]
        self.array = sorted(self.array)

    def get_fuzzy_search_results(self, string):
        """
        Uses _fuzzy_search and matches results to the hashmap's keys
        """
        results = []
        for result in self._fuzzy_search(string):
            results.extend(self.hashmap[result])
        return set(results)

    def _fuzzy_search(self, string, position=0, array=None):
        """
        Approximate text search
        """
        if not array:
            array = self.array

        if len(array) == 0:
            return array
        elif len(array) == 1:
            if difflib.SequenceMatcher(a=string,
                    b=array[0][:len(string)]).ratio() < 0.70:
                return []
            else:
                return array
        else:
            start_point = array[0]
            end_point = array[-1]
            if len(start_point) > position and len(end_point) > position and \
                    start_point[position] == end_point[position]:
                return self._fuzzy_search(string, position + 1, array)
            else:
                length = len(array) / 2
                left = self._fuzzy_search(string, position, array[:length])
                right = self._fuzzy_search(string, position, array[length:])
                return left + right


#!/usr/bin/python3
""" prints the State object with the name passed as argument from the database
"""
import sys
from model_state import Base, State
from sqlalchemy import (create_engine)
from sqlalchemy.orm import sessionmaker

if __name__ == "__main__":
    engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'
                           .format(sys.argv[1], sys.argv[2], sys.argv[3]))
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    found = False
    for state in session.query(State):
        if state.name == sys.argv[4]:
            print("{}".format(state.id))
            found = True
            break
    if found is False:
        print("Not found")


"""
Module for k-Lines extraction and k-Label manipulation

Recall that bands contains NO information of the k-points.
So we must provide that ourselves, and reading the dftb_pin.hsd (the parsed
input) seems the best way to do so. We also need to figure out what to do
with equivalent points, or points where a new path starts.
Finally, points internal to the Brilloin Zone are labeled with Greek letters,
which should be rendered properly.
"""
import sys
from os.path import normpath, expanduser, isdir
from os.path import join as joinpath
import logging
import numpy as np
from collections import defaultdict
from skpar.dftbutils.lattice import getSymPtLabel

logger = logging.getLogger(__name__)

def get_klines(lattice, hsdfile="dftb_pin.hsd", workdir=None, *args, **kwargs):
    """
    This routine analyses the KPointsAndWeights stanza in the input file of DFTB+
    (given as an input argument *hsdfile*), and returns the k-path, based on
    the lattice object (given as an input argument *lattice*).
    If the file name is not provided, the routine looks in the default
    dftb_pin.hsd, i.e. in the parsed file!

    The routine returns a list of tuples (kLines) and a dictionary (kLinesDict)
    with the symmetry points and indexes of the corresponding k-point in the
    output band-structure.

    kLines is ordered, as per the appearence of symmetry points in the hsd input, e.g.:

        * [('L', 0), ('Γ', 50), ('X', 110), ('U', 130), ('K', 131), ('Γ', 181)]

    therefore it may contain repetitions (e.g. for 'Γ', in this case).

    kLinesDict returns a dictionary of lists, so that there's a single entry for
    non-repetitive k-points, and more than one entries in the list of repetitive
    symmetry k-points, e.g. (see for 'Γ' above):

        * {'X': [110], 'K': [131], 'U': [130], 'L': [0], 'Γ': [50, 181]}
    """
    kLines_dftb = list()

    if workdir is not None:
        fhsd = normpath(expanduser(joinpath(workdir, hsdfile)))
    else:
        fhsd = hsdfile
    with open(fhsd, "r") as fh:
        for line in fh:
            if "KPointsAndWeights = Klines {".lower() in " ".join(line.lower().split()):
                extraline = next(fh)
                while not extraline.strip().startswith("}"):
                    # skip over commented line, in case of non-parsed .hsd file
                    while extraline.strip().startswith("#"):
                        extraline = next(fh)
                    words = extraline.split()[:4]
                    nk, k = int(words[0]), [float(w) for w in words[1:]]
                    kLabel = getSymPtLabel(k, lattice)
                    if kLabel:
                        kLines_dftb.append((kLabel, nk))
                    if len(words) > 4 and words[4] == "}":
                        extraline = "}"
                    else:
                        extraline = next(fh)

    # logger.debug('Parsed {} and obtained:'.format(hsdfile))
    # At this stage, kLines_dftb contains distances between k points
    # logger.debug('\tkLines_dftb: {}'.format(kLines_dftb))
    # Next, we convert it to index, from 0 to nk-1
    kLines = [
        (lbl, sum([_dist for (_lbl, _dist) in kLines_dftb[: i + 1]]) - 1)
        for (i, (lbl, dist)) in enumerate(kLines_dftb)
    ]
    # logger.debug('\tkLines      : {}'.format(kLines))
    klbls = set([lbl for (lbl, nn) in kLines])
    kLinesDict = dict.fromkeys(klbls)
    for lbl, nn in kLines:
        if kLinesDict[lbl] is not None:
            kLinesDict[lbl].append(nn)
        else:
            kLinesDict[lbl] = [
                nn,
            ]
    # logger.debug('\tkLinesDict  : {}'.format(kLinesDict))
    output = kLines, kLinesDict
    return output

def greekLabels(kLines):
    """
    Check if Γ is within the kLines and set the label to its latex formulation.
    Note that the routine will accept either list of tupples ('label',int_index) or
    a list of strings, i.e. either kLines or only the kLinesLabels.
    Could do check for other k-points with greek lables, byond Γ
    (i.e. points that are inside the BZ, not at the faces) but in the future.
    """
    try:
        lbls, ixs = list(zip(*kLines))
    except ValueError:
        lbls, ixs = kLines, None
    lbls = list(lbls)

    for i, lbl in enumerate(lbls):
        if lbl == "Gamma":
            # lbls[i] = r'$\Gamma$'
            lbls[i] = "Γ"
    if ixs is not None:
        result = list(zip(lbls, ixs))
    else:
        result = lbls
    return result

def get_kvec_abscissa(lat, kLines):
    """Return abscissa values for the reciprocal lengths corresponding
    to the k-vectors derived from kLines.
    """
    xx = []
    xt = []
    xl = []
    skipticklabel = False
    logger.debug("Constructing k-vector abscissa for BS plotting:")
    logger.debug("kLines:\n{}".format(kLines))
    pos = 0
    xx.append(np.atleast_1d(pos))
    for item1, item2 in zip(kLines[:-1], kLines[1:]):
        l1, i1 = item1
        kp1 = lat.get_kcomp(l1)
        l2, i2 = item2
        kp2 = lat.get_kcomp(l2)
        nseg = i2 - i1
        if l1 == "Gamma":
            l1 = "Γ"
        if l2 == "Gamma":
            l2 = "Γ"
        if nseg > 1:
            seglen = np.linalg.norm(lat.get_kvec(kp2 - kp1))
            xsegm, delta = np.linspace(0, seglen, nseg + 1, retstep=True)
            if not skipticklabel:
                xt.append(pos)
                xl.append(l1)
            else:
                skipticklabel = False
        else:
            seglen = 0
            delta = 0
            xsegm = np.zeros(2)
            xt.append(pos)
            if l1 == l2:
                xl.append(l1)
            else:
                xl.append("{}|{}".format(l1, l2))
            skipticklabel = True
        logger.debug(
            "{:>2s} -- {:2s}: {:8.3f} -- {:8.3f} : {:8.3f}/{:<3d}={:8.3f}".format(
                l1, l2, pos + xsegm[0], pos + xsegm[-1], seglen, len(xsegm), delta
            )
        )
        xx.append(pos + xsegm[1:])
        pos += seglen
    # append the tick and label for the last point
    xt.append(pos)
    xl.append(l2)
    #
    for item in xx:
        item = np.array(item)
    xx = np.concatenate(xx)
    assert xx.shape == (kLines[-1][-1] + 1,), (xx.shape, kLines)
    logger.debug(
        "Tick labels: {}".format(
            ", ".join(["{}:{:.3f}".format(l, t) for l, t in zip(xl, xt)])
        )
    )
    return xx, xt, xl


import sqlite3
from bottle import request, route, run
from bottle import post, get, put, delete

@get('/items')
def get_all_items():
    conn = sqlite3.connect('items.db')
    c = conn.cursor()
    c.execute("SELECT * FROM items order by id")
    result = c.fetchall()
    items = []
    for item in result:
        items.append({'id': item[0], 'item': item[1], 'price': item[2]})
    return {'items': items}

@get('/items/<id:int>')
def get_item(id):
    conn = sqlite3.connect('items.db')
    c = conn.cursor()
    c.execute("SELECT * FROM items where id=?", (id,))
    result = c.fetchall()
    return {'id': result[0][0], 'item': result[0][1], 'price': result[0][2]}

@post('/items')
def new_item():
    data = request.json
    conn = sqlite3.connect('items.db')
    c = conn.cursor()
    c.execute("INSERT INTO items (item,price) VALUES (?,?)", (data['item'],data['price']))
    conn.commit()
    c.close()
    return data

@put('/items/<id:int>')
def update_item(id):
    data = request.json
    conn = sqlite3.connect('items.db')
    c = conn.cursor()
    c.execute("UPDATE items SET item=?,price=? WHERE id=?", (data['item'],data['price'], id))
    conn.commit()
    c.close()
    return data

@delete('/items/delete/<id:int>')
def delete_item(id):
    conn = sqlite3.connect('items.db')
    c = conn.cursor()
    c.execute("DELETE FROM items WHERE id=?", (id,))
    conn.commit()
    c.close()

    return {}

if __name__ == '__main__':
    run(reloader=True, debug=True)


#!/usr/bin/env python

"""Short docstring

Long Docstring

"""

from MetapopulationNetwork import MetapopulationNetwork
from Patch import Patch
from Edge import Edge

__author__ = "Michael Pitcher"
__copyright__ = "Copyright 2017"
__credits__ = ["Michael Pitcher"]
__license__ = ""
__version__ = ""
__email__ = "mjp22@st-andrews.ac.uk"
__status__ = "Development"

class MultiPatchMetapopulationNetwork(MetapopulationNetwork):
    """
    A network of identical patches (no spatial attributes) with defined connections
    """
    def __init__(self, compartments, number_patches, connections):
        """
        Create a new multi-patch network
        :param compartments: Compartments of subpopulations of nodes
        :param number_patches: Number of nodes in network
        :param connections: Edge definitions - consists of (n1, n2) pairs integers, where 0 <= n1, n2 < number_patches
        """
        # Create the nodes
        nodes = [Patch(n, compartments) for n in range(number_patches)]
        edges = []
        # Create the edges
        for (n1, n2) in connections:
            edges.append(Edge(nodes[n1], nodes[n2]))
        MetapopulationNetwork.__init__(self, nodes, edges)


import numpy as np
import numpy.random as nr
import matplotlib.pyplot as plt

#statistical variance
delta1sq=1; delta2sq=5;
#delta3 is the harmonic value of delta1 and delta2
delta3sq=(delta1sq*delta2sq)/(delta1sq+delta2sq);
SNRdB=np.arange(0,21); SNR=10**(SNRdB/10);
#path co-efficengt for u1 and u2
a1=0.9; a2=1-a1;

#blocklength for coding
blklen=1000000;
#traget data rate /user quality data rate.
#in praftical it depend son the what kind of data rate and whta is the user need.
tildeR_1=1; tildeR_2=1;
#Thershold snr
R1=2**tildeR_1-1;
R2=2**tildeR_2-1;
#phi is used in the theoritacal calculation
phi=max(R2/a2,R1/(a1-a2*R1));

#we are the initalizing Probaliltly of outage over tghe length of SNR
Pout1 = np.zeros(len(SNRdB));
Pout2 = np.zeros(len(SNRdB));

Pout1_theory = np.zeros(len(SNRdB));
Pout2_theory = np.zeros(len(SNRdB));

for ix in range(len(SNRdB)):
    print(ix);

    rhos=SNR[ix];
    #these are the complex channels complex gassuina. mean=0
    h1=np.sqrt(delta1sq/2)*(nr.normal(0,1,blklen)+1j*nr.normal(0,1,blklen))
    h2=np.sqrt(delta2sq/2)*(nr.normal(0,1,blklen)+1j*nr.normal(0,1,blklen))

    #we are taking the minimum value and maximum value for u1 and u2
    #This is the diffrenec btw fixed NOMA and ordred NOMA line no(41-42)
    beta_1=np.minimum(np.absolute(h1)**2,np.absolute(h2)**2)
    beta_2=np.maximum(np.absolute(h1)**2,np.absolute(h2)**2)

    #The desired signal power for u1,u2,u3 SINR value
    gamma1_u1=(a1*rhos*beta_1)/(a2*rhos*beta_1+1)
    gamma1_u2=(a1*rhos*beta_2)/(a2*rhos*beta_2+1)
    #after doing the SIC
    gamma2_u2=a2*rhos*beta_2

    #we are simulating the outage probability for u1 and u2
    Pout1[ix]=np.sum(np.log2(1+gamma1_u1)<tildeR_1)/blklen
    Pout2[ix]=np.sum(np.logical_or(np.log2(1+gamma1_u2)<tildeR_1,np.log2(1+gamma2_u2)<tildeR_2))/blklen

    Pout1_theory[ix]=1-np.exp(-R1/(delta3sq*rhos*(a1-a2*R1)));
    Pout2_theory[ix]=1-np.exp(-phi/(rhos*delta1sq))-np.exp(-phi/(rhos*delta2sq))+ np.exp(-phi/(rhos*delta3sq));

#ploting the graph section.
plt.yscale('log')
plt.plot(SNRdB, Pout1,'r-');
plt.plot(SNRdB, Pout1_theory,'rs');
plt.plot(SNRdB, Pout2,'g-.');
plt.plot(SNRdB, Pout2_theory,'go');
plt.grid(1,which='both')
plt.legend(["Outage 1 (Sim)", "Outage 1 (Theory)","Outage 2 (Sim)", "Outage 2 (Theory)"], loc ="lower left");
plt.suptitle('Pout vs SNR for Ordered NOMA')
plt.ylabel('Probability of Outage')
plt.xlabel('SNR (dB)')

#why is there intersection in the graph for sim and theoritical
'''at low snr if decoding of u1 at u2 then error is going to propagate
Then the outage will increse at low snr'''
#this is called SIC failure...


#
# https://leetcode.com/problems/contains-duplicate/
#
# Given an integer array nums, return true if any value appears at least twice
# in the array, and return false if every element is distinct.
#
# Example 1:
#       Input: nums = [1,2,3,1]
#       Output: true
#
# Example 2:
#       Input: nums = [1,2,3,4]
#       Output: false
#
# Example 3:
#       Input: nums = [1,1,1,3,3,4,3,2,4,2]
#       Output: true
#

from typing import List
import sys
import pdb
br = pdb.set_trace

solution_json = {
    "date": "2022/10/10",
    "design": 0,
    "coding": 0,
    "runtime": "463 ms",
    "fasterThan": "96%",
    "memory": "26 MB"
}

class Solution:
    def __init__(self):
        self.module = sys.modules[__name__]

    def containsDuplicate(self, nums: List[int]) -> bool:
        num_set = set()
        for v in nums:
            if v in num_set:
                return True
            num_set.add(v)

        return False


import datetime
name,pts,time,hit=[],[],[],[]
num =int(input('พิมพ์จำนวนผู้ซ้อมยิงปืน: '))
for i in range(num):
    print(i+1,'ข้อมูล')
    regname =input('ชื่อ : ')
    regpts =int(input('คะแนน : '))
    regtime =float(input('เวลาที่ใช้ : '))
    name.insert(i,regname),pts.insert(i,regpts),time.insert(i,regtime),hit.insert(i,regpts/regtime)
for i in range(num):
    j = i
    for j in range(num):
        if pts[i] > pts[j]:
            a,b,c,d = hit[i],name[i],pts[i],time[i]
            hit[i],name[i],pts[i],time[i]=hit[j],name[j],pts[j],time[j]
            hit[j],name[j],pts[j],time[j]=a,b,c,d
date = datetime.datetime.now()
datenew = date.strftime('%G-%m-%d %H:%M:%S')
print('\nShotgun',date.strftime('%A'),'Training',date.strftime('%Y'))
print(datenew)
print('-'*110+'\n{0:-<15}{1:-<15}{2:-<15}{3:-<20}{4:-<15}{5:-<15}{6:-<15}'.format('No.','PTS','TIME','COMPETITOR','HIT FACTOR','STATE POINTS','STATE PERCENT\n'+'-'*110))
for i in range(num):
    print('{0: <15}{1: <15}{2: <15}{3: <20}{4: <15}{5: <15}{6: <1}'.format(i+1,pts[i],time[i],name[i],'%.4f'%hit[i],'%.4f'%float(hit[i]/hit[0]*50),'%.4f'%float((hit[i]/hit[0]*50)/(hit[0]/hit[0]*50)*100)))


import csv
import itertools
import re
import tailer as tl
import scipy
import pandas as pd
import numpy as np
import os
import io
from os import path
from scipy import stats
from scipy import ndimage
from pathlib import Path
from datetime import datetime
from tools import *

def to_seconds(col, format):
    if format == '%H:%M:%S':
        base_time = pd.to_datetime('00:00:00', format=format)
    elif format == '%M:%S':
        base_time = pd.to_datetime('00:00', format=format)
    else:
        raise NotImplementedError

    col = pd.to_datetime(col, format=format) - base_time
    return col.dt.total_seconds()
    pass

class GarminParser:

    def __init__(self, sourcedir, destfile):
        self.sourcedir = sourcedir
        self.destfile = destfile
        self.required_cols = ['Average pace (min/km)', 'Average heart rate (bpm)', 'Average cadence (rpm)']

        self.columns_to_delete = ['Sample rate', 'Stride length (m)', 'Power (W)', 'Speed (km/h)', 'Running index',
                                  'HR max', 'HR sit', 'VO2max', 'Notes', ]
        pass

    def get_columns(self, dt, columns_name, f=None, drop_nan=True, *args):

        col = f(dt[columns_name].copy(), *args) if f != None else dt[columns_name]
        if drop_nan:
            col = col.replace('', np.nan)
            col = col.dropna()

        success = False if col.isnull().values.any() or col.shape[0] == 0 else True
        if not success:
            stop = 1

        return col, success

    def process_distances_and_cadence(self, dt_bigger):
        empty = pd.DataFrame()
        summary = pd.DataFrame()

        paces, success = self.get_columns(dt_bigger, 'Pace (min/km)', to_seconds_time, False, )
        if not success: return empty
        distances, success = self.get_columns(dt_bigger, 'Distances (m)')
        if not success: return empty

        lap = 1000
        delta = 1000
        last_index = distances.shape[0]
        i = 0
        lap_paces = []
        prev = i
        while i != last_index:
            prev = i
            i = distances.searchsorted(lap)
            lap += delta

            ##jeżeli ostatnie okrążenie trwało zbyt krótko istnieje duża szansa
            ##że ostatnie okrążenie będzie nienaturalnie szybkie
            if i - prev < 30:
                break
            lap_paces.append(np.average(paces[prev:i]))

        lap_paces = np.array(lap_paces)
        summary['Pace std'] = [np.std(lap_paces)]
        summary['Lap pace median'] = [np.median(lap_paces)]
        summary['Avg Pace(s/km)'] = [np.average(lap_paces)]
        summary['Best Lap'] = [np.max(lap_paces)]

        return summary

    def get_primary_sumarry_order(self, dt: pd.DataFrame, dt_bigger: pd.DataFrame = None):
        empty = pd.DataFrame()
        summary = pd.DataFrame()
        # def get_columns(self, dt, columns_name, f=None, accept_nan=False, drop_nan=True, *args):
        time, success = self.get_columns(dt, 'Duration', to_seconds, False, '%H:%M:%S')
        if not success:
            return empty
        summary['Time'] = time

        distance, success = self.get_columns(dt, 'Total distance (km)')
        if not success:
            return empty
        summary['Distance'] = distance

        avg_hr, success = self.get_columns(dt, 'Average heart rate (bpm)')
        if not success:
            return empty
        summary['Avg HR'] = avg_hr
        ##max HR
        hrs, success = self.get_columns(dt_bigger, 'HR (bpm)')
        if not success: return empty
        summary['Max HR'] = np.max(np.array(hrs))

        elevs, success = self.get_columns(dt, ['Ascent (m)', 'Descent (m)'])
        summary['Elev Gain'] = elevs['Ascent (m)'] if success else 0
        summary['Elev Loss'] = elevs['Descent (m)'] if success else 0

        cadence, success = self.get_columns(dt, ['Average cadence (rpm)', ])
        if not success: return empty
        summary['Avg Run Cadence'] = cadence

        calories, success = self.get_columns(dt, 'Calories')
        if not success: return empty
        summary['Calories'] = calories

        temp, success = self.get_columns(dt_bigger, 'Temperatures (C)')
        if not success: return empty
        summary['Avg Temperature'] = np.median(np.array(temp))

        cadence, success = self.get_columns(dt_bigger, 'Cadence')
        if not success: return empty
        summary['Max Run Cadence'] = np.max(np.array(cadence))

        hrs, success = self.get_columns(dt_bigger, 'HR (bpm)')
        if not success: return empty
        summary['HR median'] = np.median(np.array(hrs))
        summary['HR std'] = np.std(np.array(hrs))

        paces_summary = self.process_distances_and_cadence(dt_bigger)
        summary = summary.join(paces_summary)

        return summary

    def process_file(self, file):
        df = self.get_primary_sumarry_order(pd.read_csv(file, nrows=1), pd.read_csv(file, skiprows=2))

        if not df.empty:
            file_name = os.path.basename(file)
            splited = str.split(os.path.basename(file_name),"_")
            start_date = (splited[2])
            start_time = splited[3].split('.')[0]
            df['File name'] = [file_name]
            df['Date'] = [datetime.strptime(start_date, '%Y-%m-%d').date()]
            df['Start time'] = [start_time]
            df['Type'] = -1

        return df

    def process_dir(self):

        dir = self.sourcedir
        df_initialized = False
        files = [path.join(dir, f) for f in os.listdir(dir) if path.isfile(path.join(dir, f))]
        for file in files:
            if file.lower().endswith('rr.csv'):
                continue
            new_row = self.process_file(file)
            if not new_row.empty:
                if not df_initialized:
                    df = pd.DataFrame(new_row)
                    df_initialized = True
                else:
                    df = df.append(new_row)
            else:
                stop =1
        df.to_csv(self.destfile)

if __name__ == '__main__':
    file = '/home/zywko/PycharmProjects/BA_Code/resources/polar_data/activity_example.CSV'
    sourcedir = '/home/zywko/PycharmProjects/BA_Code/resources/polar_data/csvs'
    dest_file = '/home/zywko/PycharmProjects/BA_Code/resources/polar_data/summary_polar_to_label.csv'

    parser = GarminParser(sourcedir, dest_file)
    parser.process_dir()
    pass


from utils.logger import get_logger

from plugins.base_plugin import BasePlugin
from plugins.echp.heat_pump_control_group import HeatPumpControllGroup

# (Request from mail: Eml6429)

#region File Attributes

__author__ = "Orlin Dimitrov"
"""Author of the file."""

__copyright__ = "Copyright 2020, POLYGON Team Ltd."
"""Copyrighter
@see http://polygonteam.com/"""

__credits__ = ["Angel Boyarov"]
"""Credits"""

__license__ = "GPLv3"
"""License
@see http://www.gnu.org/licenses/"""

__version__ = "1.0.0"
"""Version of the file."""

__maintainer__ = "Orlin Dimitrov"
"""Name of the maintainer."""

__email__ = "or.dimitrov@polygonteam.com"
"""E-mail of the author.
@see or.dimitrov@polygonteam.com"""

__status__ = "Debug"
"""File status."""

__class_name__ = "EnergyCenterHeatpump"
"""Plugin class name."""

#endregion

class EnergyCenterHeatpump(BasePlugin):
    """Energy center heat pump controll plugin."""

#region Attributes

    __logger = None
    """Logger
    """

    __heat_pump_control_group = None
    """Heat pump controll group.
    """

#endregion

#region Constructor / Destructor

    def __del__(self):
        """Destructor
        """

        # Heat pump
        if self.__heat_pump_control_group is not None:
            del self.__heat_pump_control_group

        super().__del__()

        if self.__logger is not None:
            del self.__logger

#endregion

#region Public Methods

    def _init(self):
        """Initialize the plugin.
        """

        # Create logger.
        self.__logger = get_logger(__name__)
        self.__logger.info("Starting up the: {}".format(self.name))

        self.__heat_pump_control_group = HeatPumpControllGroup(
            name="Heat Pump Controll Group",
            key="{}.hpcg".format(self.key),
            controller=self._controller,
            registers=self._registers)

        if self.__heat_pump_control_group is not None:
            self.__heat_pump_control_group.init()

    def _update(self):
        """Update the plugin.
        """

        self.__heat_pump_control_group.update()

    def _shutdown(self):
        """Shutting down the plugin.
        """

        self.__logger.info("Shutting down the {}".format(self.name))

        # Shutdown in order the heatpump.
        self.__heat_pump_control_group.shutdown()

#endregion


import os
import time

import pymysql
import requests

import config

sess = config.sess

def grab(url, filename):
    print(url, filename)
    path = os.path.join(config.res, filename)
    if os.path.exists(path):
        print(path, 'already had')
        return
    with open(path, 'wb') as f:
        resp = sess.get(url)
        f.write(resp.content)
    time.sleep(0.2)

def scrawl():
    conn = pymysql.connect(**config.database)
    cur = conn.cursor(pymysql.cursors.DictCursor)
    rows = cur.execute("select * from files")
    for i in range(rows):
        it = cur.fetchone()
        grab(it['url'], it['path'])
    cur.close()
    conn.close()

scrawl()

爬取审批系统/全部/4-下载二进制.py


import win32gui  # Import the module for interacting with the Windows GUI
import win32clipboard  # Import the module for accessing the clipboard

def log_keystrokes(file_path, key):
    # Write the pressed key to the keystroke log file
    with open(f"{file_path}/f_keystroke.txt", "a") as f:
        f.write(f"{key}\n")

    # Get the title of the active window
    window = win32gui.GetWindowText(win32gui.GetForegroundWindow()).lower()

    # Define a set of browser names
    browsers = {
        "chrome", "firefox", "safari", "edge", "opera", "internet explorer", "brave", "chromium", "vivaldi",
        "yandex browser", "maxthon", "tor browser", "uc browser", "pale moon", "seamonkey", "avant browser",
        "midori", "epic browser", "comodo dragon", "waterfox", "slimjet", "basilisk", "falkon", "konqueror",
        "blisk", "torch browser", "puffin browser", "sleipnir", "otter browser", "lunascape"
    }

    # Check if the active window belongs to a browser
    for browser in browsers:
        if browser in window:
            try:
                # Access the clipboard to retrieve the URL
                win32clipboard.OpenClipboard()
                url = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
                win32clipboard.CloseClipboard()
                if url:
                    url = url.decode("utf-8")
                    # Write the URL to the website log file
                    with open(f"{file_path}/f_website.log", "a") as f:
                        f.write(f"{url}\n")
            except Exception as e:
                print(f"Error accessing clipboard: {e}")
            break


import fileinput
import re
from functools import reduce

def sum_all_invalid_and_remove(fields, tickets):
    s = 0
    valid = []
    for i, ticket in enumerate(tickets):
        all_good = True
        for v in ticket:
            for _, l1, r1, l2, r2 in fields:
                if (l1 <= v <= r1) or (l2 <= v <= r2):
                    break
            else:
                all_good = False
                s += v
        if all_good:
            valid.append(ticket)
    return (s, valid)

def find_all_possible(fields, tickets):
    possible = []
    for i in range(len(fields)):
        possible.append([])
        for name, l1, r1, l2, r2 in fields:
            for j in range(len(tickets)):
                if not ((l1 <= tickets[j][i] <= r1) or (l2 <= tickets[j][i] <= r2)):
                    break
            else:
                possible[i].append(name)
    return possible

lines = list(map(lambda x: x.rstrip(), fileinput.input()))
fields = map(lambda l: re.match(
    "(.+): (\d+)-(\d+) or (\d+)-(\d+)", l), lines[:20])
fields = list(map(lambda m: (m.group(1), int(m.group(2)),
                             int(m.group(3)), int(m.group(4)), int(m.group(5))), fields))
my_ticket = list(map(int, lines[22].split(",")))
nearby_tickets = list(map(lambda l: list(map(int, l.split(","))), lines[25:]))

# part 1
s, valid_tickets = sum_all_invalid_and_remove(fields, nearby_tickets)
print(s)

# part 2
possible = find_all_possible(fields, valid_tickets)
possible = list(enumerate(possible))
possible.sort(key=lambda p: len(p[1]))
prev = set()
mult = 1
for i, p in possible:
    if list((set(p) - prev))[0].startswith("departure"):
        mult *= my_ticket[i]
    prev = set(p)
print(mult)


#import ray.rllib.agents.dqn as dqn
import numpy as np
import argparse
import torch

from search_space import get_hparams

def convert_to_vec(args, config):
    df_hparams = get_hparams(args)
    using = []

    if args.experiment == "data_aug":
        for i in range(len(df_hparams)):
            row = df_hparams.iloc[i]
            using.append(config[row.Name])
    else:
        raise Exception("only implemented the data_aug experiment")

    return (using)

# converts a hparam df to a config
def convert_to_config(args, df_hparams):

    if args.search == 'cocabo':
        config = get_base_config(args)
        if args.experiment == "exploration":

            for i in range(len(df_hparams)):
                row = df_hparams.iloc[i]
                type_vec = row.Type
                if row.Name == "exploration_type":
                    if args.env.split('_')[0] == 'Atari':
                        if type_vec == 'continuous':
                            config['exploration_config'] = exp_atari[row.Use]
                        else:
                            config['exploration_config'] = exp_atari[row.Range[int(row.Use)]]
                    else:
                        if type_vec == 'continuous':
                            config['exploration_config'] = exp_basic[row.Use]
                        else:
                            config['exploration_config'] = exp_basic[row.Range[int(row.Use)]]
                else:
                    if type_vec == 'continuous':
                        config[row.Name] = row.Use
                    else:

                        config[row.Name] = row.Range[row.Use]

        elif args.experiment == 'data_aug':
            for i in range(len(df_hparams)):
                row = df_hparams.iloc[i]
                type_vec = row.Type
                if type_vec == 'continuous':
                    config[row.Name] = row.Use
                else:
                    config[row.Name] = row.Range[int(row.Use)]
        else:
            raise Exception("only implemented exploration and data_aug so far")

        return (config)

    else:
        config = get_base_config(args)
        if args.experiment == "exploration":

            for i in range(len(df_hparams)):
                row = df_hparams.iloc[i]
                if row.Name =="exploration_type":
                    if args.env.split('_')[0] == 'Atari':
                        config['exploration_config'] = exp_atari[row.Use]
                    else:
                        config['exploration_config'] = exp_basic[row.Use]
                else:
                    config[row.Name] = row.Use

        elif args.experiment == 'data_aug':
            for i in range(len(df_hparams)):
                row = df_hparams.iloc[i]
                config[row.Name] = row.Use
        else:
            raise Exception("only implemented exploration and data_aug so far")

        return(config)

# samples from each hparam range, generates a config with it
def get_random_config(args):

    df_hparams = get_hparams(args)

    to_use = []
    for i in range(len(df_hparams)):
        row = df_hparams.iloc[i]
        if row.Type == 'continuous':
            to_use.append(np.random.uniform(row.Range[0], row.Range[1]))
        elif row.Type == 'categorical':
            if args.cat_exp == 'fixed':
                if args.search == 'cocabo':
                    to_use.append(0)
                else:
                    to_use.append(args.fixed_cat_val)
            else:
                if args.search == 'cocabo':
                    to_use.append(round(np.random.uniform()*(len(row.Range)-1)))
                else:
                    to_use.append(row.Range[round(np.random.uniform()*(len(row.Range)-1))])
        else:
            raise Exception('Must be either continuous or categorical')
    df_hparams['Use'] = to_use
    config = convert_to_config(args, df_hparams)
    return(config)

def get_base_config(args):

    if args.experiment == "exploration":

        if args.algo == 'dqn':
            config = dqn.DEFAULT_CONFIG.copy()

        config["num_gpus"] = args.gpu_per_trial
        config["num_workers"] = args.cpu_per_trial

        if args.env == 'frozenlake':
            config["env"] = "FrozenLake-v0"
            config["env_config"] = {
                        "desc": [
                            "SFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFF",
                            "FFFFFFFFFFFFFFFG",
                        ],
                        "is_slippery": False
            }
            # Limit horizon to make it really hard for non-curious agent to reach
            # the goal state.
            config["horizon"] = 40

        elif args.env.split('_')[0] == 'Atari':

            config["env"] = '{}NoFrameskip-v4'.format(args.env.split('_')[1])
            config['hiddens'] = [512]
            config['double_q'] = False
            config['dueling'] = False
            config['prioritized_replay'] = False
            config['num_atoms'] = 1
            config['target_network_update_freq'] = 8000
            config['lr'] = 0.0000625
            config['adam_epsilon'] = 0.00015
            config['buffer_size'] = 1000000
            config['rollout_fragment_length'] = 4
            config['train_batch_size'] = 32
            config['timesteps_per_iteration'] = 10000
            config['learning_starts'] = 20000
            config['prioritized_replay_alpha']: 0.5
            config['final_prioritized_replay_beta']: 1.0
            config['prioritized_replay_beta_annealing_timesteps'] = 2000000
            config['n_step'] = 1
            #config['model']['grayscale'] = True

    elif args.experiment == 'data_aug':

        if len(args.env.split('-')) >1:
            ## DMC

            # PPO Arguments.
            config = {}
            config['lr'] = 7e-4
            config['eps'] = 1e-5 # RMSprop epsilon
            config['alpha'] = 0.99 # RMSProp alpha
            config['gamma']=0.99 # discount factor for rewards
            config['gae_lambda'] = 0.95 # gae lambda parameter
            config['entropy_coef'] = 0.01 # entropy term coefficient
            config['value_loss_coef'] = 0.5 #value loss coefficient (default: 0.5)
            config['max_grad_norm'] = 0.5 #max norm of gradients
            config['seed']=1
            config['num_processes'] = 4 # how many training CPU processes to use
            config['num_steps'] = 500 # number of forward steps in A2C
            config['ppo_epoch'] = 3 # number of ppo epochs
            #config['num_mini_batch']=32 # number of batches for ppo
            config['clip_param'] = 0.2 # ppo clip parameter
            config['log_interval'] = 1 # log interval, one log per n updates
            config['save_interval'] = 1 # save interval, one save per n update
            config['num_env_steps'] = 10e6 # number of environment steps to train
            config['hidden_size'] = 512 # state embedding dimension
            config['train_resource_files'] = 'auto-drac-dmc/distractors/images/*mp4'
            config['frame_stack'] = 3
            config['total_frames'] = 1000
            # DrAC Arguments.
            config['use_sacae_network']=False
            config['aug_type']='crop' # augmentation type
            config['aug_coef'] = 0.1 # coefficient on the augmented loss
            config['aug_extra_shape'] = 0 # increase image size by
            config['image_pad'] = 12 # increase image size by
            config['preempt'] = False # safe preemption: load the latest checkpoint with same args and continue training)
            config['cuda'] = True if args.gpu_per_trial >0 else False
        else:
            ## ProcGen

            # PPO Arguments.
            config = {}
            config['lr'] = 5e-4
            config['eps'] = 1e-5 # RMSprop epsilon
            config['alpha'] = 0.99 # RMSProp alpha
            config['gamma']=0.999 # discount factor for rewards
            config['gae_lambda'] = 0.95 # gae lambda parameter
            config['entropy_coef'] = 0.01 # entropy term coefficient
            config['value_loss_coef'] = 0.5 #value loss coefficient (default: 0.5)
            config['max_grad_norm'] = 0.5 #max norm of gradients
            config['seed']=1
            config['num_processes'] = 64 # how many training CPU processes to use
            config['num_steps'] = 256 # number of forward steps in A2C
            config['ppo_epoch'] = 3 # number of ppo epochs
            config['num_mini_batch']=8 # number of batches for ppo
            config['clip_param'] = 0.2 # ppo clip parameter
            config['log_interval'] = 1 # log interval, one log per n updates
            config['save_interval'] = 1 # save interval, one save per n update
            config['num_env_steps'] = 25e6 # number of environment steps to train
            config['hidden_size'] = 256 # state embedding dimension
            # Procgen Arguments.
            config['distribution_mode']='easy' # distribution of envs for procgen
            config['num_levels'] = 200 # number of Procgen levels to use for training
            config['start_level'] = 0 # start level id for sampling Procgen levels
            # DrAC Arguments.
            config['aug_type']='crop' # augmentation type
            config['aug_coef'] = 0.1 # coefficient on the augmented loss
            config['aug_extra_shape'] = 0 # increase image size by
            config['image_pad'] = 12 # increase image size by
            config['preempt'] = False # safe preemption: load the latest checkpoint with same args and continue training)
            config['cuda'] = True if args.gpu_per_trial >0 else False

    else:
        raise Exception("Only works for exploration and data_aug")

    return(config)


from collections import Counter

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not s or not words:
            return []

        one_word = len(words[0])
        word_num = len(words)
        n = len(s)
        res = []

        counter_w = Counter(words)

        # 由于每次步长为 one_word，因此起点的设置有 one_word 种
        # 例如，单词长度为 3 时，起点可以为 0,1,2 且不重复
        for i in range(one_word):
            left = right = i
            counter_s = Counter()
            word_count = 0

            while right + one_word <= n:
                w = s[right: right + one_word]
                right += one_word
                counter_s[w] += 1
                word_count += 1

                while counter_s[w] > counter_w[w]:
                    lw = s[left: left + one_word]
                    left += one_word
                    counter_s[lw] -= 1
                    word_count -= 1

                # 当 counter_s 中所有单词计数不超过 counter_w 且总单词数等于 words 中单词数时
                # 证明找到了串联的子串
                if word_count == word_num:
                    res.append(left)

        return res

30. 串联所有单词的子串.py

30. 串联所有单词的子串.py


import json

from django import forms
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext as _

from core.forms.mixins import SyncedDataMixin
from dcim.models import DeviceRole, DeviceType, Location, Platform, Region, Site, SiteGroup
from extras.choices import *
from extras.models import *
from extras.utils import FeatureQuery
from netbox.forms import NetBoxModelForm
from tenancy.models import Tenant, TenantGroup
from utilities.forms import BootstrapMixin, add_blank_choice
from utilities.forms.fields import (
    CommentField, ContentTypeChoiceField, ContentTypeMultipleChoiceField, DynamicModelMultipleChoiceField, JSONField,
    SlugField,
)
from virtualization.models import Cluster, ClusterGroup, ClusterType

__all__ = (
    'ConfigContextForm',
    'ConfigTemplateForm',
    'CustomFieldForm',
    'CustomLinkForm',
    'ExportTemplateForm',
    'ImageAttachmentForm',
    'JournalEntryForm',
    'SavedFilterForm',
    'TagForm',
    'WebhookForm',
)

class CustomFieldForm(BootstrapMixin, forms.ModelForm):
    content_types = ContentTypeMultipleChoiceField(
        queryset=ContentType.objects.all(),
        limit_choices_to=FeatureQuery('custom_fields'),
    )
    object_type = ContentTypeChoiceField(
        queryset=ContentType.objects.all(),
        # TODO: Come up with a canonical way to register suitable models
        limit_choices_to=FeatureQuery('webhooks').get_query() | Q(app_label='auth', model__in=['user', 'group']),
        required=False,
        help_text=_("Type of the related object (for object/multi-object fields only)")
    )

    fieldsets = (
        ('Custom Field', (
            'content_types', 'name', 'label', 'group_name', 'type', 'object_type', 'required', 'description',
        )),
        ('Behavior', ('search_weight', 'filter_logic', 'ui_visibility', 'weight', 'is_cloneable')),
        ('Values', ('default', 'choices')),
        ('Validation', ('validation_minimum', 'validation_maximum', 'validation_regex')),
    )

    class Meta:
        model = CustomField
        fields = '__all__'
        help_texts = {
            'type': _(
                "The type of data stored in this field. For object/multi-object fields, select the related object "
                "type below."
            )
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Disable changing the type of a CustomField as it almost universally causes errors if custom field data is already present.
        if self.instance.pk:
            self.fields['type'].disabled = True

class CustomLinkForm(BootstrapMixin, forms.ModelForm):
    content_types = ContentTypeMultipleChoiceField(
        queryset=ContentType.objects.all(),
        limit_choices_to=FeatureQuery('custom_links')
    )

    fieldsets = (
        ('Custom Link', ('name', 'content_types', 'weight', 'group_name', 'button_class', 'enabled', 'new_window')),
        ('Templates', ('link_text', 'link_url')),
    )

    class Meta:
        model = CustomLink
        fields = '__all__'
        widgets = {
            'link_text': forms.Textarea(attrs={'class': 'font-monospace'}),
            'link_url': forms.Textarea(attrs={'class': 'font-monospace'}),
        }
        help_texts = {
            'link_text': _(
                "Jinja2 template code for the link text. Reference the object as {{ object }}. Links "
                "which render as empty text will not be displayed."
            ),
            'link_url': _("Jinja2 template code for the link URL. Reference the object as {{ object }}."),
        }

class ExportTemplateForm(BootstrapMixin, SyncedDataMixin, forms.ModelForm):
    content_types = ContentTypeMultipleChoiceField(
        queryset=ContentType.objects.all(),
        limit_choices_to=FeatureQuery('export_templates')
    )
    template_code = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'font-monospace'})
    )

    fieldsets = (
        ('Export Template', ('name', 'content_types', 'description', 'template_code')),
        ('Data Source', ('data_source', 'data_file', 'auto_sync_enabled')),
        ('Rendering', ('mime_type', 'file_extension', 'as_attachment')),
    )

    class Meta:
        model = ExportTemplate
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Disable data field when a DataFile has been set
        if self.instance.data_file:
            self.fields['template_code'].widget.attrs['readonly'] = True
            self.fields['template_code'].help_text = _(
                'Template content is populated from the remote source selected below.'
            )

    def clean(self):
        super().clean()

        if not self.cleaned_data.get('template_code') and not self.cleaned_data.get('data_file'):
            raise forms.ValidationError("Must specify either local content or a data file")

        return self.cleaned_data

class SavedFilterForm(BootstrapMixin, forms.ModelForm):
    slug = SlugField()
    content_types = ContentTypeMultipleChoiceField(
        queryset=ContentType.objects.all()
    )
    parameters = JSONField()

    fieldsets = (
        ('Saved Filter', ('name', 'slug', 'content_types', 'description', 'weight', 'enabled', 'shared')),
        ('Parameters', ('parameters',)),
    )

    class Meta:
        model = SavedFilter
        exclude = ('user',)

    def __init__(self, *args, initial=None, **kwargs):

        # Convert any parameters delivered via initial data to JSON data
        if initial and 'parameters' in initial:
            if type(initial['parameters']) is str:
                initial['parameters'] = json.loads(initial['parameters'])

        super().__init__(*args, initial=initial, **kwargs)

class WebhookForm(BootstrapMixin, forms.ModelForm):
    content_types = ContentTypeMultipleChoiceField(
        queryset=ContentType.objects.all(),
        limit_choices_to=FeatureQuery('webhooks')
    )

    fieldsets = (
        ('Webhook', ('name', 'content_types', 'enabled')),
        ('Events', ('type_create', 'type_update', 'type_delete', 'type_job_start', 'type_job_end')),
        ('HTTP Request', (
            'payload_url', 'http_method', 'http_content_type', 'additional_headers', 'body_template', 'secret',
        )),
        ('Conditions', ('conditions',)),
        ('SSL', ('ssl_verification', 'ca_file_path')),
    )

    class Meta:
        model = Webhook
        fields = '__all__'
        labels = {
            'type_create': 'Creations',
            'type_update': 'Updates',
            'type_delete': 'Deletions',
            'type_job_start': 'Job executions',
            'type_job_end': 'Job terminations',
        }
        widgets = {
            'additional_headers': forms.Textarea(attrs={'class': 'font-monospace'}),
            'body_template': forms.Textarea(attrs={'class': 'font-monospace'}),
            'conditions': forms.Textarea(attrs={'class': 'font-monospace'}),
        }

class TagForm(BootstrapMixin, forms.ModelForm):
    slug = SlugField()

    fieldsets = (
        ('Tag', ('name', 'slug', 'color', 'description')),
    )

    class Meta:
        model = Tag
        fields = [
            'name', 'slug', 'color', 'description'
        ]

class ConfigContextForm(BootstrapMixin, SyncedDataMixin, forms.ModelForm):
    regions = DynamicModelMultipleChoiceField(
        queryset=Region.objects.all(),
        required=False
    )
    site_groups = DynamicModelMultipleChoiceField(
        queryset=SiteGroup.objects.all(),
        required=False
    )
    sites = DynamicModelMultipleChoiceField(
        queryset=Site.objects.all(),
        required=False
    )
    locations = DynamicModelMultipleChoiceField(
        queryset=Location.objects.all(),
        required=False
    )
    device_types = DynamicModelMultipleChoiceField(
        queryset=DeviceType.objects.all(),
        required=False
    )
    roles = DynamicModelMultipleChoiceField(
        queryset=DeviceRole.objects.all(),
        required=False
    )
    platforms = DynamicModelMultipleChoiceField(
        queryset=Platform.objects.all(),
        required=False
    )
    cluster_types = DynamicModelMultipleChoiceField(
        queryset=ClusterType.objects.all(),
        required=False
    )
    cluster_groups = DynamicModelMultipleChoiceField(
        queryset=ClusterGroup.objects.all(),
        required=False
    )
    clusters = DynamicModelMultipleChoiceField(
        queryset=Cluster.objects.all(),
        required=False
    )
    tenant_groups = DynamicModelMultipleChoiceField(
        queryset=TenantGroup.objects.all(),
        required=False
    )
    tenants = DynamicModelMultipleChoiceField(
        queryset=Tenant.objects.all(),
        required=False
    )
    tags = DynamicModelMultipleChoiceField(
        queryset=Tag.objects.all(),
        required=False
    )
    data = JSONField(
        required=False
    )

    fieldsets = (
        ('Config Context', ('name', 'weight', 'description', 'data', 'is_active')),
        ('Data Source', ('data_source', 'data_file', 'auto_sync_enabled')),
        ('Assignment', (
            'regions', 'site_groups', 'sites', 'locations', 'device_types', 'roles', 'platforms', 'cluster_types',
            'cluster_groups', 'clusters', 'tenant_groups', 'tenants', 'tags',
        )),
    )

    class Meta:
        model = ConfigContext
        fields = (
            'name', 'weight', 'description', 'data', 'is_active', 'regions', 'site_groups', 'sites', 'locations',
            'roles', 'device_types', 'platforms', 'cluster_types', 'cluster_groups', 'clusters', 'tenant_groups',
            'tenants', 'tags', 'data_source', 'data_file', 'auto_sync_enabled',
        )

    def __init__(self, *args, initial=None, **kwargs):

        # Convert data delivered via initial data to JSON data
        if initial and 'data' in initial:
            if type(initial['data']) is str:
                initial['data'] = json.loads(initial['data'])

        super().__init__(*args, initial=initial, **kwargs)

        # Disable data field when a DataFile has been set
        if self.instance.data_file:
            self.fields['data'].widget.attrs['readonly'] = True
            self.fields['data'].help_text = _('Data is populated from the remote source selected below.')

    def clean(self):
        super().clean()

        if not self.cleaned_data.get('data') and not self.cleaned_data.get('data_file'):
            raise forms.ValidationError("Must specify either local data or a data file")

        return self.cleaned_data

class ConfigTemplateForm(BootstrapMixin, SyncedDataMixin, forms.ModelForm):
    tags = DynamicModelMultipleChoiceField(
        queryset=Tag.objects.all(),
        required=False
    )
    template_code = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'font-monospace'})
    )

    fieldsets = (
        ('Config Template', ('name', 'description', 'environment_params', 'tags')),
        ('Content', ('template_code',)),
        ('Data Source', ('data_source', 'data_file', 'auto_sync_enabled')),
    )

    class Meta:
        model = ConfigTemplate
        fields = '__all__'
        widgets = {
            'environment_params': forms.Textarea(attrs={'rows': 5})
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Disable content field when a DataFile has been set
        if self.instance.data_file:
            self.fields['template_code'].widget.attrs['readonly'] = True
            self.fields['template_code'].help_text = _(
                'Template content is populated from the remote source selected below.'
            )

    def clean(self):
        super().clean()

        if not self.cleaned_data.get('template_code') and not self.cleaned_data.get('data_file'):
            raise forms.ValidationError("Must specify either local content or a data file")

        return self.cleaned_data

class ImageAttachmentForm(BootstrapMixin, forms.ModelForm):

    class Meta:
        model = ImageAttachment
        fields = [
            'name', 'image',
        ]

class JournalEntryForm(NetBoxModelForm):
    kind = forms.ChoiceField(
        choices=add_blank_choice(JournalEntryKindChoices),
        required=False
    )
    comments = CommentField()

    class Meta:
        model = JournalEntry
        fields = ['assigned_object_type', 'assigned_object_id', 'kind', 'tags', 'comments']
        widgets = {
            'assigned_object_type': forms.HiddenInput,
            'assigned_object_id': forms.HiddenInput,
        }


import sys
input = sys.stdin.readline
nCount = int(input())
nList = [int(input()) for _ in range(nCount)]

def gcd(a,b):
    while b>0:
        a, b = b, a%b
    return a

nList.sort()
newList = [nList[i]-nList[i-1] for i in range(1, nCount)]
if nCount == 2:
    m = newList[0]
else:
    m = gcd(newList[0], newList[1])
    for i in range(2, len(newList)):
        m = gcd(m, newList[i])

result = set()
for i in range(2, int(m**0.5)+1):
    if m % i == 0:
        result.add(i)
        result.add(m//i)
result.add(m)
print(*sorted(list(result)))


from odoo import fields, models

class HrExpense(models.Model):
    _inherit = "hr.expense"

    bill_partner_id = fields.Many2one(
        comodel_name="res.partner",
        string="Vendor",
    )

    def _get_account_move_line_values(self):
        move_line_values_by_expense = super()._get_account_move_line_values()
        # Set tax_exigible, to ensure that, tax inovice is not created for undue vat
        RepartTax = self.env["account.tax.repartition.line"]
        for move_lines in move_line_values_by_expense.values():
            for move_line in filter(
                lambda l: l.get("tax_repartition_line_id"), move_lines
            ):
                tax = RepartTax.browse(move_line["tax_repartition_line_id"]).tax_id
                move_line["tax_exigible"] = tax.tax_exigibility == "on_invoice"
        return move_line_values_by_expense


my = input("")

dic = dict()
dic["alphas"] = 0
dic["digits"] = 0
dic["spaces"] = 0
print(dic)
for i in my:
    if i.isalpha():
        dic["alphas"] +=1
    elif i.isdigit():
        dic["digits"] +=1
    elif i.isspace():
        dic["spaces"] +=1
print(dic)


import serial
import cv2

opencr = serial.Serial(port='/dev/ttyACM0', baudrate=115200)
push_dict = {"f":1,"b":2,"r":3,"l":4,"q":5}
img = cv2.imread("../tanos.jpg")
while True:
    cv2.imshow('img', img)
    key = cv2.waitKey(10)
    if key==27:
        print("프로그램 종료")
        break
    try:
        num = push_dict[chr(key)]
    except Exception as e:
        continue

    opencr.write(bytes(str(num), 'utf-8'))
cv2.destroyAllWindows()


# coding: utf-8

#生成密码序列
#arr:观测序列
#key:连续key个数之和
#arr_len:数组长度

def funtion(arr,key,arr_len):
    index = 0
    last = []
    for i in range(arr_len):#总密码数
        temp = 0
        index = i
        for _ in range(abs(key)):#生成密码累计加多少次
            if key > 0:
                index -= 1
                if index < 0:
                    index = arr_len -1
                temp += arr[index]
            else:
                index += 1
                if index == arr_len:
                    index = 0
                temp += arr[index]
        last.append(temp)
    return last


from pyrecord.exceptions import RecordInstanceError

__all__ = [
    "validate_generalization",
    "validate_initialization",
    "validate_field_access",
    "validate_specialization",
    ]

def validate_initialization(
    record_type,
    values_by_field_order,
    values_by_field_name,
):
    _require_existing_fields_number(record_type, values_by_field_order)
    _require_existing_field_names(record_type, values_by_field_name.keys())
    _require_one_value_per_field(
        record_type,
        values_by_field_order,
        values_by_field_name,
        )

def validate_generalization(record_type, specialized_record):
    _require_type_inheritance(specialized_record.__class__, record_type)

def validate_specialization(record_type, generalized_record, field_values):
    generalized_record_type = generalized_record.__class__
    _require_type_inheritance(record_type, generalized_record_type)
    _require_field_names_missing_in_supertype(
        generalized_record_type,
        field_values,
        )

def validate_field_access(field_name, record_type):
    if field_name not in record_type.field_names:
        raise AttributeError(
            '"{}" has no field "{}"'.format(record_type.__name__, field_name),
            )

def _require_type_inheritance(subtype, supertype):
    if not issubclass(subtype, supertype):
        raise RecordInstanceError(
            "Record type {} is not a subtype of {}".format(
                subtype.__name__,
                supertype.__name__,
                )
            )

def _require_existing_field_names(record_type, field_names):
    for field_name in field_names:
        if field_name not in record_type.field_names:
            raise RecordInstanceError(
                'Unknown field "{}"'.format(field_name),
                )

def _require_existing_fields_number(record_type, values_by_field_order):
    unknown_field_values_count = \
        len(values_by_field_order) - len(record_type.field_names)
    if 0 < unknown_field_values_count:
        raise RecordInstanceError(
            "Too many field values: Cannot map {} values to fields".format(
                unknown_field_values_count,
                )
            )

def _require_one_value_per_field(
    record_type,
    values_by_field_order,
    values_by_field_name,
):
    fields_set_by_position = \
        record_type.field_names[:len(values_by_field_order)]

    # Check there's at most one value per field
    for field_name in values_by_field_name:
        if field_name in fields_set_by_position:
            raise RecordInstanceError(
                'Value of field "{}" is already set'.format(field_name),
                )

    # Check there's at least one value per field
    fields_set_by_name = values_by_field_name.keys()
    fields_with_default_value = \
        record_type._default_values_by_field_name.keys()
    fields_set = \
        fields_set_by_position + \
        tuple(fields_set_by_name) + \
        tuple(fields_with_default_value)
    for field_name in record_type.field_names:
        if field_name not in fields_set:
            raise RecordInstanceError(
                'Field "{}" is undefined'.format(field_name),
                )

def _require_field_names_missing_in_supertype(supertype, subtype_field_names):
    for field_name in supertype.field_names:
        if field_name in subtype_field_names:
            raise RecordInstanceError(
                'Field "{}" is already defined in "{}"'.format(
                    field_name,
                    supertype.__name__,
                    )
                )


import urllib;
import os,sys,re,logging,chromalog;
from chromalog.mark.helpers.simple import success, error, important

chromalog.basicConfig(level=logging.INFO,format="[%(levelname)s] %(message)s");
logger = logging.getLogger(__name__);

isEnd = False;
url = "";
content = "";
pattern = "<a href=\"/photos/(.*?)\"";
sep = os.path.sep;

directory = os.path.realpath(os.getcwd() +sep +"pictures"+sep);

page  = 1;
count = 0;
if not os.path.exists(directory):
    logger.info("Creating directory");
    os.makedirs(directory);

while (not isEnd):
    isEnd = True;
    url = "http://unsplash.com/?page=" + str(page);
    content = urllib.urlopen(url).read();
    for s in re.findall(pattern,content):
        pic = "http://unsplash.com/photos/" + s + "/download";
        filename = directory+ sep + s + ".jpeg";
        logger.info("Loading:\t %s",s)
        if(not os.path.exists(filename)):
            urllib.urlretrieve(pic,filename);

            logger.info("Loaded:\t %s (%d)",success(s),count);

            count+=1;
            isEnd = False;
        else:

            logger.warning(s + " Exists");

    page+=1;
logger.info("%s %d %s",success("Successfully downloaded"),count,success("pictures"));