from typing import NamedTuple, Optional, List, Dict, Any, Union
from enum import Enum, auto

import pysam

def _build_filter(rec: pysam.VariantRecord) -> List[Union[str, int]]:
    return [f for f in rec.filter]

def _build_info(rec: pysam.VariantRecord) -> Dict[str, Any]:
    info = dict()
    for key, value in rec.info.items():
        info[key] = value
    return info

def _build_format(rec: pysam.VariantRecord) -> List[str]:
    return [f for f in rec.format]

def _build_samples(rec: pysam.VariantRecord) -> Dict[str, Dict[str, Any]]:
    samples = dict()
    for sample_name in rec.samples:
        sample_dict = dict()
        for key, value in rec.samples[sample_name].items():
            sample_dict[key] = value
        samples[sample_name] = sample_dict
    return samples

class VariantType(Enum):
    """Enumeration with the different types of variations
    """
    SNV = auto()
    DEL = auto()
    INS = auto()
    DUP = auto()
    INV = auto()
    CNV = auto()
    TRA = auto()
    SGL = auto()

class BreakendSVRecord(NamedTuple):
    """NamedTuple with the information of a breakend notated SV record
    """
    prefix: Optional[str]
    """Prefix of the SV record with breakend notation. For example, for :code:`G]17:198982]` the prefix will be :code:`G`"""
    bracket: str
    """Bracket of the SV record with breakend notation. For example, for :code:`G]17:198982]` the bracket will be :code:`]`"""
    contig: str
    """Contig of the SV record with breakend notation. For example, for :code:`G]17:198982]` the contig will be :code:`17`"""
    pos: int
    """Position of the SV record with breakend notation. For example, for :code:`G]17:198982]` the position will be :code:`198982`"""
    suffix: Optional[str]
    """Suffix of the SV record with breakend notation. For example, for :code:`G]17:198982]` the suffix will be :code:`None`"""

class ShorthandSVRecord(NamedTuple):
    """NamedTuple with the information of a shorthand SV record
    """
    type: str
    """One of the following, :code:`'DEL'`, :code:`'INS'`, :code:`'DUP'`, :code:`'INV'` or :code:`'CNV'`"""
    extra: Optional[List[str]]
    """Extra information of the SV. For example, for :code:`<DUP:TANDEM:AA>` the extra will be :code:`['TANDEM', 'AA']`"""

def _str_value(value):
    if isinstance(value, str):
        return value
    elif isinstance(value, float):
        return f'{value:.2f}'
    elif hasattr(value, '__iter__'):
        return ','.join([_str_value(v) for v in value])
    elif value is None:
        return '.'
    else:
        return str(value)

def _convert_info_key_value(key, value):
    if value is None:
        return key
    elif isinstance(value, bool):
        return key if value else None
    else:
        return key+'='+_str_value(value)

def _convert_sample_value(key, value):
    if key == 'GT':
        return '/'.join([_str_value(v) for v in value])
    else:
        return _str_value(value)

class VariantRecord():
    """NamedTuple with the information of a variant record
    """
    contig: str
    """Contig name"""
    pos: int
    """Position of the variant in the contig"""
    end: int
    """End position of the variant in the contig (same as `pos` for TRA and SNV)"""
    length: int
    """Length of the variant"""
    id: Optional[str]
    """Record identifier"""
    ref: str
    """Reference sequence"""
    alt: str
    """Alternative sequence"""
    qual: Optional[float]
    """Quality score for the assertion made in ALT"""
    filter: List[Union[str, int]]
    """Filter status. PASS if this position has passed all filters. Otherwise, it contains the filters that failed"""
    variant_type: VariantType
    """Variant type"""
    alt_sv_breakend: Optional[BreakendSVRecord]
    """Breakend SV info, present only for SVs with breakend notation. For example, :code:`G]17:198982]`"""
    alt_sv_shorthand: Optional[ShorthandSVRecord]
    """Shorthand SV info, present only for SVs with shorthand notation. For example, :code:`<DUP:TANDEM>`"""

    def __init__(self, rec: pysam.VariantRecord, contig: str, pos: int, end: int,
                 length: int, id: Optional[str], ref: str,
                 alt: str, variant_type: VariantType,
                 alt_sv_breakend: Optional[BreakendSVRecord] = None,
                 alt_sv_shorthand: Optional[ShorthandSVRecord] = None):
        self._rec = rec
        self.contig = contig
        self.pos = pos
        self.end = end
        self.length = length
        self.id = id
        self.ref = ref
        self.alt = alt
        self.qual = rec.qual
        self.filter = _build_filter(rec)
        self.variant_type = variant_type
        self.alt_sv_breakend = alt_sv_breakend
        self.alt_sv_shorthand = alt_sv_shorthand

        self._info = None
        self._format = None
        self._samples = None

    @property
    def info(self):
        """Additional information"""
        if self._info is None:
            self._info = _build_info(self._rec)
        return self._info

    @info.setter
    def info(self, value):
        self._info = value

    @property
    def format(self):
        """Specifies data types and order of the genotype information"""
        if self._format is None:
            self._format = _build_format(self._rec)
        return self._format

    @format.setter
    def format(self, value):
        self._format = value

    @property
    def samples(self):
        """Genotype information for each sample"""
        if self._samples is None:
            self._samples = _build_samples(self._rec)
        return self._samples

    @samples.setter
    def samples(self, value):
        self._samples = value

    def _replace(self, **kwargs):
        new_record = VariantRecord(self._rec, self.contig, self.pos, self.end,
                                   self.length, self.id, self.ref, self.alt,
                                   self.variant_type, self.alt_sv_breakend,
                                   self.alt_sv_shorthand)
        for key, value in kwargs.items():
            setattr(new_record, key, value)
        return new_record

    def _info_str(self, rec_str: List[str]) -> str:
        # If info has not been loaded, return the original info string
        if self._info is None and len(rec_str) > 7:
            return rec_str[7]
        info_list = []
        for key, value in self.info.items():
            info_str = _convert_info_key_value(key, value)
            if info_str is None:
                continue
            info_list.append(info_str)
        if self.alt_sv_shorthand:
            info_list.insert(0, 'END='+str(self.end))
        info = ";".join(info_list)
        return info

    def _format_str(self, rec_str: List[str]) -> str:
        # If format has not been loaded, return the original format string
        if self._format is None and len(rec_str) > 8:
            return rec_str[8]
        return ":".join(self.format)

    def _samples_str(self, rec_str: List[str]) -> str:
        # If samples and format have not been loaded, return the original samples string
        if self._samples is None and self._format is None and len(rec_str) > 9:
            return '\t'.join(rec_str[9:])
        samples_list = [":".join([_convert_sample_value(k, self.samples[sample_name][k])
                                 for k in self.format]) for sample_name in self.samples]
        samples = "\t".join(samples_list)
        return samples

    def __str__(self):
        rec_str_split = str(self._rec).split('\t')
        contig = self.contig
        pos = self.pos
        id_ = self.id if self.id else '.'
        ref = self.ref
        alt = self.alt
        qual = _str_value(self.qual)
        filter_ = ";".join(map(str, self.filter)) if self.filter else '.'
        info = self._info_str(rec_str_split)
        format_ = self._format_str(rec_str_split)
        samples = self._samples_str(rec_str_split)
        return f'{contig}\t{pos}\t{id_}\t{ref}\t{alt}\t{qual}\t{filter_}\t{info}\t{format_}\t{samples}'.strip()


from zipfile import ZipFile

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
import seaborn as sns

bikes = pd.read_csv('bsd/hour.csv', index_col='dteday', parse_dates=True)

bikes['hour'] = bikes.index.hour

bikes.head()
bikes.tail()

# - **hour** ranges from 0 (midnight) through 23 (11pm)
# - **workingday** is either 0 (weekend or holiday) or 1 (non-holiday weekday)

# ## Task 1
#
# Run these two `groupby` statements and figure out what they tell you about the data.

# mean rentals for each value of "workingday"
# sns.set(style='whitegrid', context='notebook')
# cols = ['hr', 'temp', 'atemp', 'hum', 'windspeed', 'cnt']
# sns.pairplot(bikes[cols], size=2.5)
# plt.show()

#WARNING: dont run code below(mem overflow)
# cm = np.corrcoef(bikes[cols])
#
# hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size':15}, yticklabels=cols, xticklabels=cols)
# plt.show()

# bikes.groupby('workingday').cnt.mean()

# mean rentals for each value of "hour"
# bikes.groupby('hour').cnt.mean()

# bikes.groupby(['holiday', 'season']).cnt.mean().unstack().plot()

feature_cols = ['casual']

X = bikes[feature_cols].values
y = bikes.cnt.values

# X = StandardScaler().fit(X.reshape(-1, 1)).transform(X.reshape(-1, 1))
# y_scaler = StandardScaler().fit(y.reshape(-1, 1))
# y = y_scaler.transform(y.reshape(-1, 1))

X_len = len(X)
test_value = round(X_len * 0.05)

X_train, X_test = X[:-test_value], X[-test_value:]
y_train, y_test = y[:-test_value], y[-test_value:]

linreg = linear_model.LinearRegression()
linreg.fit(X_train.reshape(-1,1), y_train.reshape(-1,1))
y_pred = linreg.predict(X_test.reshape(test_value, 1))

plt.scatter(X_test.reshape(-1,1), y_test, color='b')
plt.plot(X_test.reshape(-1,1), y_pred, color='red',linewidth=1)
plt.show()

# pred = linreg.predict(X_test)
#
# # scores = cross_val_score(linreg, X, y, cv=10, scoring='mean_squared_error')
#
# # The coefficients
print('Coefficients: \n', linreg.coef_)
# # The mean squared error
print("Mean squared error: %.2f"
      % mean_squared_error(y_test, y_pred))
# # Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(y_test, y_pred))
#
# pass


from __future__ import division
class EstadisticaIII:
    def __init__(self,X,Y=[]):
        self.X = X
        self.Y = Y
        self.n = len(X)
    def Fn(self,y):
        return len([x for x in self.X if x<=y])/self.n
    def KS(self,F):
        Xi = sorted(self.X)
        Dn = []
        for i in range(self.n):
            Dn.append(max((i+1)/self.n-F(Xi[i]),F(Xi[i])-i/self.n))
        D = max(Dn)
        K = np.argmax(Dn)
        Femp = [self.Fn(x) for x in np.arange(min(self.X),max(self.X)+0.02,0.01)]
        F0 = [F(x) for x in np.arange(min(self.X),max(self.X)+0.02,0.01)]
        plt.plot(np.arange(min(self.X),max(self.X)+0.02,0.01),Femp)
        plt.plot(np.arange(min(self.X),max(self.X)+0.02,0.01),F0)
        plt.plot(Xi[K],F(Xi[K]),'g^')
        return D


import pickle

import pandas as pd

import mixmod
from mixmod import gm  # gm contains global constants (enum items etc.)

def persist_strategy():
    # --------------------------------------
    # Strategy example :
    # - nbTry = 5
    # - algo 1 : SEM (nb_iteration = 80)
    # - algo 2 : EM (epsilon=0.0001)
    # Note : default algorithm is EM.
    # ------------------------------------
    algo1 = mixmod.algo(name=gm.SEM, nb_iteration=80)
    algo2 = mixmod.algo(name=gm.EM, epsilon=0.0001)
    strategy_ = mixmod.strategy(nb_try=5, algo=[algo1, algo2])
    with open("/tmp/pymixmod_persist_strategy.pkl", "wb") as fd:
        pickle.dump(strategy_, fd)

def clustering_with_persisted_strategy():
    folder_data = "data/"
    data = pd.read_csv(folder_data + "iris.train")
    data = data.iloc[:, :4]  # exclude labels on 5th column

    # nb_cluster contains the numbers of clusters to be tested.
    # Here we assume that there are 2, 3 or 4 clusters.

    with open("/tmp/pymixmod_persist_strategy.pkl", "rb") as fd:
        strategy_ = pickle.load(fd)
    return mixmod.cluster(data, nb_cluster=[2, 3, 4], strategy=strategy_)

if __name__ == "__main__":
    print(
        "-----------------------------------------------------------------------\n"
        "Clustering example : \n"
        "  - iris data (quantitative data)\n"
        "  - strategy :\n"
        "    - nbTry = 5 \n"
        "    - 2 chained algorithms\n"
        "      - SEM (80 iterations)\n"
        "      - EM (epsilon=0.0001)\n"
        "-----------------------------------------------------------------------\n"
    )
    persist_strategy()
    print(clustering_with_persisted_strategy().summary())


import sys
input = sys.stdin.readline
result = 0

def merge_sort(s, e):# 병합정렬
    global result
    if e-s < 1: return
    m = int(s+(e-s) / 2)
    merge_sort(s, m)
    merge_sort(m+1, e)
    for i in range(s, e+1):
        tmp[i] = A[i]

    k = s #A배열에서 어느 위치에 index가 들어가는지
    index1 = s
    index2 = m+1
    while index1 <= m and index2 <= e:
        if tmp[index1] > tmp[index2]:
            A[k] = tmp[index2] # 뒤에 있는 데이터 선택
            result = result + index2 - k #index2 - k: 현재 남아있는 앞에 있는 개수(# swap 값 카운트)
            k += 1
            index2 += 1
        else:
            A[k] = tmp[index1] # 앞에 있는 데이터 선택
            k += 1
            index1 += 1
    while index1 <= m:
        A[k] = tmp[index1]
        k += 1
        index1 += 1
    while index2 <= e:
        A[k] = tmp[index2]
        k += 1
        index2 += 1

N = int(input())
A = list(map(int, input().split()))
A.insert(0,0)
tmp = [0] * int(N+1)
merge_sort(1, N)
print(result)


from collections import OrderedDict
from Models.Utils.FRRN_utils import *

class FRRNet(nn.Module):
    """
    implementation table A of Full-Resolution Residual Networks
    """

    def __init__(self, in_channels=3, out_channels=21, layer_blocks=(3, 4, 2, 2)):
        super(FRRNet, self).__init__()

        # 5×5
        self.first = nn.Sequential(
            OrderedDict([
                ('conv', nn.Conv2d(in_channels=in_channels, out_channels=48, kernel_size=5, padding=2)),
                ('bn', nn.BatchNorm2d(48)),
                ('relu', nn.ReLU()),
            ]))
        self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.up = nn.UpsamplingBilinear2d(scale_factor=2)
        self.relu = nn.ReLU()

        # 3×48 Residual Unit
        self.reslayers_in = nn.Sequential(*[BasicBlock(48, 48, efficient=False) for _ in range(3)])

        # divide
        self.divide = nn.Conv2d(in_channels=48, out_channels=32, kernel_size=1)

        # frrlayer 1
        self.frrnlayer1 = FRRLayer(48, 96, factor=2, num_blocks=layer_blocks[0])

        # frrlayer2
        self.frrnlayer2 = FRRLayer(96, 192, factor=4, num_blocks=layer_blocks[1])

        # frrnlayer3
        self.frrnlayer3 = FRRLayer(192, 384, factor=8, num_blocks=layer_blocks[2])

        # frrnlayer4
        self.frrnlayer4 = FRRLayer(384, 384, factor=16, num_blocks=layer_blocks[3])

        # defrrnlayer1
        self.defrrnlayer1 = FRRLayer(384, 192, factor=8, num_blocks=2)

        # defrrnlayer2
        self.defrrnlayer2 = FRRLayer(192, 192, factor=4, num_blocks=2)

        # defrrnlayer3
        self.defrrnlayer3 = FRRLayer(192, 96, factor=2, num_blocks=2)

        # join
        self.compress = nn.Conv2d(96 + 32, 48, kernel_size=1)

        # 3×48 reslayer

        self.reslayers_out = nn.Sequential(*[BasicBlock(48, 48, efficient=True) for _ in range(3)])

        self.out_conv = nn.Conv2d(48, out_channels, 1)

    def forward(self, x):
        x = self.first(x)
        y = self.reslayers_in(x)

        z = self.divide(y)
        y = self.pool(y)

        y, z = self.frrnlayer1(y, z)

        y = self.pool(y)
        y, z = self.frrnlayer2(y, z)

        y = self.pool(y)
        y, z = self.frrnlayer3(y, z)

        y = self.pool(y)
        y, z = self.frrnlayer4(y, z)

        y = self.up(y)
        y, z = self.defrrnlayer1(y, z)

        y = self.up(y)
        y, z = self.defrrnlayer2(y, z)

        y = self.up(y)
        y, z = self.defrrnlayer3(y, z)

        y = self.up(y)
        refine = self.compress(torch.cat((y, z), 1))

        out = self.reslayers_out(refine)
        out = self.out_conv(out)
        return out


import os
import re

clear = lambda: os.system('clear')

data = "AAAX---aaax---111"
exp = "\w+(?=X), \w+, \w+(?=\w)"
txt='''\
\w+ : 문자(\w),1이상(+)
(?=X) : 뒤에 따라오는(?=) X라는 것을 문자열 검색에 쓰지만 매치는 되지 않음
\w+(?=X) : AAAX에서 문자들이 매치되지만 AAA만 매치됨 X는 제외 시킴
X는 X 앞의 단어 AAA를 찾는데는 기여했지만 자신은 매치되지 않음
\w+ : (?=X)없이 하게되면 AAAX,aaax,111과 매치됨
\w+(?=\w) : AAA,aaa,11과 매치됨
(?=\w) : 조건에 문자를 만족시키면 자신은 찾는데만 기여하고 매치는 안됨
'''
print(data)
print(txt)
while True:
	output = input('{} >>> '.format(exp))
	regex = re.compile(output)
	a = regex.search(data)
	b = regex.findall(data)
	print('search  :',a)
	print('findall :',b)
	if output == '':
		clear()
		break


#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
    new_list = []
    for n in range(list_length):
        try:
            a = my_list_1[n] / my_list_2[n]
        except(ZeroDivisionError):
            print("division by 0")
            a = 0
        except(TypeError, ValueError):
            print("wrong type")
            a = 0
        except(IndexError):
            print("out of range")
            a = 0
        finally:
            new_list.append(a)
    return new_list


from page.E_confirm_order_page import ConfirmOrderPage

class MyOrderPage(ConfirmOrderPage):
    """我的订单页面"""

    order_sn_loc = ('id', 'com.tpshop.malls:id/order_sn_tv')  # 订单编号
    to_be_received_loc = ('id','com.tpshop.malls:id/status_receive_tv') # 待收货
    back_loc = ('id','com.tpshop.malls:id/title_back_img') # 返回图标
    confirm_received_loc = ('id','com.tpshop.malls:id/id_index_gallery_item_button') # 确认收货
    positive_button_loc = ('id','com.tpshop.malls:id/positiveButton') # "确定"按钮
    cart_loc = ('id','com.tpshop.malls:id/bottom_cart_img') # 购物车

    def get_order_sn(self):
        """获取订单编号"""
        return self.get_ele_text(self.order_sn_loc)

    def click_to_be_received(self):
        """点击<待收货>"""
        self.click(self.to_be_received_loc)

    def click_confirm_received(self):
        """点击<确认收货>"""
        self.click(self.confirm_received_loc)

    def click_positive_Button(self):
        """点击<确定>"""
        self.click(self.positive_button_loc)

    def click_back(self):
        """点击返回图标"""
        self.click(self.back_loc)

    def click_cart(self):
        """点击购物车"""
        self.click(self.cart_loc)

if __name__ == '__main__':
    from common.base_app import open_app
    from time import sleep

    driver = open_app()  # 打开TPShop,进入登录页面
    confirm = ConfirmOrderPage(driver)
    confirm.input_account_num('13730626896')  # 输入账号
    confirm.input_password('123456')  # 输入密码
    confirm.click_confirm_login()  # 点击登录
    confirm.wait_page()  # 等待页面加载
    confirm.click_search()  # 点击搜索框
    confirm.input_search_content('容声冰箱')  # 搜索容声冰箱
    confirm.click_search_button()  # 点击搜索按钮
    confirm.wait_page()  # 等待页面加载
    sleep(2)
    confirm.click_RSfridge()  # 点击容声冰箱
    confirm.wait_page()  # 等待页面加载
    sleep(3)
    confirm.click_buy()  # 点击立即购买
    confirm.click_confrim_buy()  # 点击确认购买
    confirm.click_address_RS()  # 点击选择收货地址
    confirm.choose_consignee_RS()  # 选择收货人
    confirm.click_order_balance_RS()  # 点击使用余额
    confirm.wait_page()  # 等待页面加载
    confirm.click_sub_order_RS()  # 点击提交订单
    confirm.input_pay_pwd_RS('123456')  # 输入支付密码
    confirm.click_confirm_pay_pwd_RS()  # 确认支付密码
    order = MyOrderPage(driver)
    sn = order.get_order_sn()  # 获取订单编号
    print(sn)
    sleep(3)
    confirm.quit()


# Definition for a Node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []

class Solution:

    def cloneGraph(self, node: 'Node') -> 'Node':
        if not node:
            return node

        stack = [node]
        visited = {node: Node(node.val, [])}
        while stack:
            n = stack.pop()
            for neighbor in n.neighbors:
                if neighbor not in visited:
                    visited[neighbor] = Node(neighbor.val, [])
                    stack.append(neighbor)
                visited[n].neighbors.append(visited[neighbor])
        return visited[node]


import pandas as pd

dataPath = 'data/'

# maps for converting BPS points
scoringBpsMap = {'FWD': {'GKP': -12, 'DEF': -12, 'MID': -6, 'FWD': 0},
                 'MID': {'GKP': -6, 'DEF': -6, 'MID': 0, 'FWD': 6},
                 'DEF': {'GKP': 0, 'DEF': 0, 'MID': 6, 'FWD': 12},
                 'GKP': {'GKP':0, 'DEF': 0, 'MID': 6, 'FWD': 12}}
cleanSheetBpsMap = {'FWD': {'GKP': 12, 'DEF': 12, 'MID': 0, 'FWD': 0},
                    'MID': {'GKP': 12, 'DEF': 12, 'MID': 0, 'FWD': 0},
                    'DEF': {'GKP': 0, 'DEF': 0, 'MID': -12, 'FWD': -12},
                    'GKP': {'GKP': 0, 'DEF': 0, 'MID': -12, 'FWD': -12}}

# maps for converting absolute points
scoringMap = {'FWD': {'GKP': 2, 'DEF': 2, 'MID': 1, 'FWD': 0},
              'MID': {'GKP': 1, 'DEF': 1, 'MID': 0,  'FWD': -1},
              'DEF': {'GKP': 0, 'DEF': 0, 'MID': -1, 'FWD': -2},
              'GKP': {'GKP': 0, 'DEF': 0, 'MID': -1, 'FWD': -2}}
cleanSheetMap = {'FWD': {'GKP': 4, 'DEF': 4, 'MID': 1, 'FWD': 0},
                 'MID': {'GKP': 3, 'DEF': 3, 'MID': 0, 'FWD': -1},
                 'DEF': {'GKP': 0, 'DEF': 0, 'MID': -3, 'FWD': -4},
                 'GKP': {'GKP': 0, 'DEF': 0, 'MID': -3, 'FWD': -4}}
goalsConcededMap = {'FWD': {'GKP': -1, 'DEF': -1, 'MID': 0, 'FWD': 0},
                    'MID': {'GKP': -1, 'DEF': -1, 'MID': 0, 'FWD': 0},
                    'DEF': {'GKP': 0, 'DEF': 0, 'MID': 1, 'FWD': 1},
                    'GKP': {'GKP': 0, 'DEF': 0, 'MID': 1, 'FWD': 1}}

def getGw(seasonString, gwInt):
    return pd.read_csv(f'{dataPath}{seasonString}/gws/gw{gwInt}.csv')

def getGwFixtures(playerID, df):
    return df[df['element'] == playerID]['fixture'].tolist()

def getGwFixtureInfo(df, fixture):
    df = df[df['fixture'] == fixture]
    df = df.set_index('element')
    return df

def recalculateFixtureBonus(df, playerID, newPos):
    oldPos = df.loc[playerID].position
    BPS = df.loc[playerID].bps
    if oldPos == newPos:
        return 0
    BPS += df.loc[playerID].clean_sheets * cleanSheetBpsMap[oldPos][newPos]
    BPS += df.loc[playerID].goals_scored * scoringBpsMap[oldPos][newPos]
    df.loc[playerID, 'bps'] = BPS
    try:
        newBonus = df.nlargest(3, 'bps', keep='all')['bps'].rank(method='max').loc[playerID]
        return int(newBonus - df.loc[playerID].bonus)
    except KeyError:
        return 0

def recalculateFixturePoints(df, playerID, newPos):
    oldPos = df.loc[playerID].position
    points = df.loc[playerID].total_points
    if oldPos == newPos:
        return 0
    points += (df.loc[playerID].clean_sheets * cleanSheetMap[oldPos][newPos])
    points += (df.loc[playerID].goals_scored * scoringMap[oldPos][newPos])
    points += ((df.loc[playerID].goals_conceded // 2) * goalsConcededMap[oldPos][newPos])
    points += recalculateFixtureBonus(df, playerID, newPos)
    return points

def recalculateTotalPoints(seasonString, playerID, newPos):
    newPoints = 0
    oldPoints = 0
    for i in range(1, 39):
        gw = getGw(seasonString, i)
        fixtureList = getGwFixtures(playerID, gw)
        for fixture in fixtureList:
            fx = getGwFixtureInfo(gw, fixture)
            newPoints += recalculateFixturePoints(fx, playerID, newPos)
            oldPoints += fx.loc[playerID].total_points
    return {'old': oldPoints, 'new': newPoints, }

if __name__ == "__main__":
    print(f"Salah (MID to FWD): {recalculateTotalPoints(seasonString='2021-22', playerID=233, newPos='FWD')}")
    print(f"Jota (MID to FWD): {recalculateTotalPoints(seasonString='2021-22', playerID=240, newPos='FWD')}")
    print(f"Havertz (MID to FWD): {recalculateTotalPoints(seasonString='2021-22', playerID=141, newPos='FWD')}")
    print(f"Dallas (MID to DEF): {recalculateTotalPoints(seasonString='2021-22', playerID=188, newPos='DEF')}")
    print(f"Joelinton (FWD to MID): {recalculateTotalPoints(seasonString='2021-22', playerID=310, newPos='MID')}")
    print(f"Saint-Maximan (FWD to MID): {recalculateTotalPoints(seasonString='2021-22', playerID=307, newPos='MID')}")
    print(f"Kouyate (DEF to MID): {recalculateTotalPoints(seasonString='2021-22', playerID=150, newPos='MID')}")


import pprint

def log(file_name="default.log", msg="Default text"):
    """
    Logs the specified message to specified file.
    Overwrites the whole file each time
    """
    f = open(file_name, "w+")
    pretty = pprint.pformat(msg)
    f.write(pretty)
    f.close()

def perm_log(file_name="default.log", title="Default title", msg="Default text"):
    """
    Logs the specified message to specified file.
    Appends to the file each time
    """
    f = open(file_name, "a")
    f.write(3*"\n"+str(title)+"\n"+80*"-"+"\n")
    f.write(msg)
    f.close()


"""
Created on Thu Mar 17 16:34:46 2022

@author: svein
"""
import speech_recognition as sr
import sounddevice as sd
from scipy.io.wavfile import write
import os
import ffmpeg
from scipy.io import wavfile
import numpy as np

def Speech_to_text():
    myfile="output.wav"

    ## If file exists, delete it ##
    if os.path.isfile(myfile):
        os.remove(myfile)
    else:    ## Show an error ##
        print("Error: %s file not found" % myfile)
 ##
    print("recording start")
    fs = 44100  # Sample rate
    seconds = 4  # Duration of recording

    sd.default.dtype='int32', 'int32'

    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    sd.wait()  # Wait until recording is finished
    print("recording ended")
    wavfile.write("output.wav", fs, myrecording)  # Save as WAV file

    def SpeechToText():
        r = sr.Recognizer()   #Speech recognition
        audio = sr.AudioFile("output.wav")
        with audio as source:
            print("Wait. Program Starting")
            audio = r.record(source)
            message = r.recognize_google(audio)
            print("Check: "+message)
        return message
    Ord=SpeechToText()
    return Ord

if __name__ == "__main__":
    print(Speech_to_text())


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

# In[1]:

import json, urllib
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# In[2]:

asi_measures = pd.read_csv('final-data.csv')
asi_measures.head()

# In[4]:

all_nodes = asi_measures.Category.values.tolist() + asi_measures.ASI.values.tolist()
source_indices = [all_nodes.index(Category) for Category in asi_measures.Category]
target_indices = [all_nodes.index(ASI) for ASI in asi_measures.ASI]

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 20,
      thickness = 20,
      line = dict(color = "black", width = 1.0),
      label =  all_nodes,
    ),

    link = dict(
      source =  source_indices,
      target =  target_indices,
      value =  asi_measures.Count,
))])

fig.update_layout(title_text="Transport mitigation actions in the context of Avoid, Shift and Improve",
                  font_size=10)
fig.show()


import csv

''' def leer_parque(nombre_archivo, parque):
    f = open(nombre_archivo)
    filas = csv.reader(f)
    data = []
    encabezado = next(filas)
    for fila in filas:
        registro = dict(zip(encabezado, fila))
        if registro['espacio_ve'] == parque:
            data.append(registro)
    return data

print(len(leer_parque('arbolado-en-espacios-verdes.csv', 'GENERAL PAZ'))) '''

def leer_parque(nombre_archivo, parque):
    f = open(nombre_archivo)
    filas = csv.reader(f)
    data = []
    encabezado = next(filas)
    for fila in filas:
        registro = dict(zip(encabezado, fila))
        if registro['espacio_ve'] == parque:
            registro['altura_tot'] = float(registro['altura_tot'])
            data.append(registro)

    return data
#print(leer_parque('arbolado-en-espacios-verdes.csv', 'GENERAL PAZ'))

def obtener_alturas(lista_arboles, especie):
    lista_de_alturas = []
    for arbol in lista_arboles:
        if arbol['nombre_com'] == especie:
            altura = arbol['altura_tot']
            lista_de_alturas.append(altura)
    return lista_de_alturas

gral_paz = [leer_parque('arbolado-en-espacios-verdes.csv', 'GENERAL PAZ'), 'General Paz']
los_andes = [leer_parque('arbolado-en-espacios-verdes.csv', 'EJERCITO DE LOS ANDES'),'Los Andes']
centenario = [leer_parque('arbolado-en-espacios-verdes.csv', 'CENTENARIO'),'Centenario']
parques = [gral_paz, los_andes, centenario]
max_arbol = []
proms = []
nombres = []
for parque in parques:
    data = obtener_alturas(parque[0], 'Jacarandá')

    max_arbol.append(max(data))
    proms.append(sum(data)/len(data))
    nombres.append(parque[1])

# print('Medida', nombres)
# print("max", max_arbol)
# print("prom", proms)


#-*- coding: utf-8 -*-
'''
1. 添加系：adddepartment
2. 添加班级：addclass
3. 删除系：deldepartment
4. 删除班级：delclass
5. 编辑系：editdepartment
6. 编辑班级：editclass
'''

from django.shortcuts import render_to_response
from django.template import RequestContext, Template, Context
from classes.models import Class, Department
from teachers.models import Teacher
from students.models import Student
from django.http import HttpResponse, Http404, HttpResponseRedirect
import datetime
import json
import logging
logger = logging.getLogger('mysite.log')
def adddepartment(request):
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        deptls = Department.objects.order_by('id')
        classls = Class.objects.order_by('id')
        judgeadd=0
        errors = []
        if request.method == 'POST':
                if not request.POST.get('deptname',''):
                        errors.append('deptname')
                for dept in deptls:
                        if(dept.deptname==request.POST['deptname']):
                                judgeadd=1
                                break;
                if(judgeadd==0):
                        dept = Department(deptname=request.POST['deptname'],teacherid_id= request.session['userid'],createtime=datetime.datetime.now(),edittime=datetime.datetime.now())
                        dept.save()
        deptls = Department.objects.order_by('id')
        departments = Department.objects.order_by('id')
        return HttpResponseRedirect('/students/')

def addclass(request):
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        deptls = Department.objects.order_by('id')
        classls = Class.objects.order_by('id')
        judgeadd=0
        errors = []
        if request.method == 'POST':
                if not request.POST.get('claname',''):
                        errors.append('claname')
                for clas in classls:
                        if(clas.claname == request.POST['claname']):
                                if(clas.grade == int(request.POST['grade'])):
                                        if(clas.departmentid_id ==int(request.POST['deptid'])):
                                                judgeadd=1
                                                break;
                if(judgeadd==0):
                        cla = Class(claname=request.POST['claname'],departmentid_id=int(request.POST['deptid']),grade=int(request.POST['grade']),teacherid_id= request.session['userid'],createtime=datetime.datetime.now(),edittime=datetime.datetime.now())
                        cla.save()
        deptls = Department.objects.order_by('id')
        classes = Class.objects.order_by('id')
        return HttpResponseRedirect('/students/')

def delclass(request, did):
        global logger
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        error = ''
        try:
                did = int(did)
                cla = Class.objects.get(id=did)
        except ValueError:
                logger.error("classes")
                raise Http404()

        cla.delete()
        return HttpResponseRedirect('/students/')

def deldepartment(request, did):
        global logger
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        error = ''
        try:
                did = int(did)
                dept = Department.objects.get(id=did)
        except ValueError:
                logger.error("classes")
                raise Http404()

        dept.delete()
        return HttpResponseRedirect('/students/')

def editdepartment(request, did):
        global logger
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        errors = []
        deptls = Department.objects.order_by('id')
        classls = Class.objects.order_by('id')
        judgeadd=0
        try:
                did = int(did)
                dept= Department.objects.get(id=did)
        except ValueError:
                logger.error("classes")
                raise Http404()

        if request.method == 'POST':
                if not request.POST.get('deptname',''):
                        errors.append('deptname')
                for deptl in deptls:
                        if(deptl.deptname==request.POST['deptname']):
                                if(dept.deptname!=request.POST['deptname']):
                                        judgeadd=1
                                        break;
                if(judgeadd==0):
                        dept.deptname = request.POST['deptname']
                        dept.edittime=datetime.datetime.now()
                        dept.save()
        deptls = Department.objects.order_by('id')
        departments = Department.objects.order_by('id')
        return HttpResponseRedirect('/students/')

def editclass(request, did):
        global logger
        if not 'username' in request.session:
                return HttpResponseRedirect('/Login/')
        errors = []
        deptls = Department.objects.order_by('id')
        classls = Class.objects.order_by('id')
        judgeadd=0
        try:
                did = int(did)
                clas=Class.objects.get(id=did)
        except ValueError:
                logger.error("classes")
                raise Http404()

        if request.method == 'POST':
                if not request.POST.get('claname',''):
                        errors.append('claname')
                for clasl in classls:
                        if(clasl.claname == request.POST['claname']):
                                if(clasl.grade == int(request.POST['grade'])):
                                        if(clasl.departmentid_id ==int(request.POST['deptid'])):
                                                judgeadd=1
                                                break;
                if(judgeadd==0):
                        clas.claname = request.POST['claname']
                        clas.grade = request.POST['grade']
                        clas.departmentid_id = request.POST['deptid']
                        clas.edittime=datetime.datetime.now()
                        clas.save()
        deptls = Department.objects.order_by('id')
        classes = Class.objects.order_by('id')
        return HttpResponseRedirect('/students/')

def deptnamecheck(request):
        departments = Department.objects.order_by('-id')
        judgedeptname= 0
        if request.method == 'POST':
                deptdeptname=request.POST['deptname']
               # print deptdeptname
                for dept in departments:
                        if (dept.deptname == deptdeptname):
                                judgedeptname=1
                                break
        data={}
        data["judgedeptname"]=judgedeptname
        return HttpResponse(json.dumps(data))

def clanamecheck(request):
        classes = Class.objects.order_by('-id')
        judgeclaname= 0
        if request.method == 'POST':
                cladeptid= int(request.POST['deptid'])
                clagrade = int(request.POST['grade'])
                claclaname = request.POST['claname']
                for cla in classes:
                        if (cla.claname==claclaname):
                                if(cla.grade==clagrade):
                                        #print cla.departmentid_id
                                        #print cladeptid
                                        if(cla.departmentid_id==cladeptid):
                                                judgeclaname=1
                                                break
        data={}
        data["judgeclaname"]=judgeclaname
        return HttpResponse(json.dumps(data))


import sys
import heapq
input = sys.stdin.readline

N = int(input())
arr = []

#입력
for _ in range(N):
    arr.append(list(map(int, input().split())))

#회의시간 기준 정렬
arr.sort(key=lambda x: x[0])

rooms = [0]
answer = 1

for s, e in arr:
    # 가장 빠른 회의 종료 시간보다 array의 회의 시작 시간이 늦거나 같다면
    if s >= rooms[0]:
        # 그 회의 시간을 pop해준 다음 새로운 종료 시간 삽입
        heapq.heappop(rooms)

    else:
        # 가장 빠른 회의 종료 시간보다 빠르다면 회의실 추가 후 종료 시간 삽입
        answer+=1

    # 삽입부 : 이렇게 하면 여러 개를 관리할 수 있음
    heapq.heappush(rooms, e)

print(answer)


import itertools
from itertools import izip, cycle
import os
import string
import glob
from moduleBaseClass import ModuleBaseClass

class XorStuff:

    def __init__(self, filepath=None):
        """Constructor : set xored file (optional)

        """
        self.file_type = None
        self.list_types = self.load_files_types('modules/')
        if filepath is not None:
            self.file_content = self.set_file_content(filepath)

    def load_files_types(self, path):
        """Load all modules from modules/ and make them available

        """
        list_types = {}
        files = glob.glob(path + "*")
        for file in files:
            file_name, file_extension = os.path.splitext(file)
            if not file_name.endswith("__init__") and file_extension == ".py":
                module_name = file_name.replace("/", ".")
                mod = __import__(module_name)
                modules = module_name.split('.')
                for module in modules[1:]:
                    mod = getattr(mod, module)
                    if issubclass(mod.Module, ModuleBaseClass):
                        instance = mod.Module()
                        list_types[instance.name] = instance
        return list_types

    def xor(self, data, key, file_type=None):
        """Perform a simple xor with data and key
           file_type is an instance of modules and provide file checking

        """
        result = []
        for data, char_key in izip(data, cycle(key)):
            byte = chr(ord(data) ^ ord(char_key))
            if file_type is not None:
                if not file_type.live_check(byte):
                    return None
            result.append(byte)
        return ''.join(result)

    def set_file_content(self, filepath, length=None):
        """Open xored file and store content
           Optional : can store n bytes only
        """
        bin_file = ''
        with open(filepath, "rb") as f:
            byte = f.read(1)
            index = 0
            while byte != "":
                bin_file = bin_file + byte
                byte = f.read(1)
                if length is not None:
                    if index == length:
                        break
                    index = index + 1
        self.file_content = bin_file

    def get_pass(self, key_length, grep=None):
        """Try to recover key(s) for a given length and yield them
           Optional : can grep bytes in result
        """
        # Padding of header with %s if key length > header length
        if int(key_length) > len(self.file_type.header):
            header_no_formatters = self.file_type.header.replace('%s', '?')
            formatters = '%s' * (int(key_length) - len(header_no_formatters))
            self.file_type.header = "%s%s" % (self.file_type.header,
                                              formatters)

        bf_length = self.file_type.header.count('%s')
        header_length = len(self.file_type.header.replace('%s', '?'))
        bin_header = self.file_content[:header_length]

        charset = ''.join([chr(i) for i in range(128)])
        key_charset = string.ascii_letters + string.digits + string.punctuation

        # generate keys
        for char in itertools.product(charset, repeat=bf_length):
            generated_header = self.file_type.header % char
            output = self.xor(bin_header, generated_header)
            key = output[0: key_length]
            if not [c for c in key if c not in key_charset]:
                raw = self.xor(self.file_content, key, self.file_type)
                if raw is not None:
                    if self.file_type.final_check(raw):
                        if grep is not None:
                            if grep in raw:
                                yield key
                        else:
                            yield key

    def set_file_type(self, file_type):
        """Load correct file type module according to file extension name

        """
        self.file_type = self.list_types[file_type]


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 21 16:38:00 2016

@author: Neo

Oct 25, 2016: updated by Niu.
"""

import numpy as np
import matplotlib.pyplot as plt

res_dir = '../results/'
dat_fil = ['OVrot.dat', 'GRrot.dat']

#glide for the three special catalog
w3 = np.loadtxt(res_dir + 'SpecialSets.rot', usecols=(1,3,5,7))

Num = np.loadtxt(res_dir + dat_fil[0], usecols=(0,), dtype=int)
W, W_E, WX, WX_E, WY, WY_E, WZ, WZ_E = \
        np.loadtxt(res_dir + dat_fil[0], usecols=list(range(1,9)), unpack=True)
Wg, W_Eg, WXg, WX_Eg, WYg, WY_Eg, WZg, WZ_Eg = \
        np.loadtxt(res_dir + dat_fil[1], usecols=list(range(1,9)), unpack=True)

i = Num
y = np.ones(Num.size)

#############################################################################
#plot, writted a year ago.

#i = range(100,len(Sou)+1)
#y = np.ones(len(i))
#
#fig, ax = plt.subplots(2, 2)
#((ax1, ax2), (ax3, ax4)) = ax
#
#ax1.plot(i, WX, 'b')
##ax1.plot(i, WXg, 'r')
#ax1.set_ylabel('$\omega_x$',fontsize = 25)
#ax1.plot(i, w3[0][1]*y, ':', label = '212 ICRF' )
#ax1.plot(i, w3[1][1]*y, '-.', label = '295 ICRF' )
#ax1.plot(i, w3[2][1]*y, '--', label = '247 MFV' )
#
#ax2.plot(i, WY, 'b')
##ax2.plot(i, WYg, 'r')
#ax2.set_ylabel('$\omega_y$',fontsize = 25)
#ax2.plot(i, w3[0][2]*y, ':', label = '212 ICRF'  )
#ax2.plot(i, w3[1][2]*y, '-.', label = '295 ICRF' )
#ax2.plot(i, w3[2][2]*y, '--', label = '247 MFV' )
#
#ax3.plot(i, WZ, 'b')
##ax3.plot(i, WZg, 'r')
#ax3.set_ylabel('$\omega_z$',fontsize = 25)
#ax3.plot(i, w3[0][3]*y, ':', label = '212 ICRF'  )
#ax3.plot(i, w3[1][3]*y, '-.', label = '295 ICRF' )
#ax3.plot(i, w3[2][3]*y, '--', label = '247 MFV' )
#
#ax4.plot(i, W, 'b')
##ax4.plot(i, Wg, 'r')
#ax4.set_ylabel('$\omega$',fontsize = 25)
#ax4.plot(i, w3[0][0]*y, ':' , label = '212 ICRF' )
#ax4.plot(i, w3[1][0]*y, '-.', label = '295 ICRF' )
#ax4.plot(i, w3[2][0]*y, '--', label = '247 MFV' )
#
#ax1.legend()
#ax2.legend()
#ax3.legend()
#ax4.legend()
#
#ax1.set_xlabel('No. Sources',fontsize = 15)
#ax2.set_xlabel('No. Sources',fontsize = 15)
#ax3.set_xlabel('No. Sources',fontsize = 15)
#ax4.set_xlabel('No. Sources',fontsize = 15)
#
#plt.show()
##plt.savefig('../plot/OARank_rot.eps')
#plt.savefig('../plot/GRank_rot.eps')

##############################################################################
plt.figure()

#set the size of subplots
left,width = 0.10,0.85
bottom,height = 0.1, 0.17
bottom_3 = bottom + height*2 + 0.01
bottom_2 = bottom_3 + height + 0.01
bottom_1 = bottom_2 + height + 0.01

scale4 = [left, bottom,   width, height*2]
scale3 = [left, bottom_3, width, height]
scale2 = [left, bottom_2, width, height]
scale1 = [left, bottom_1, width, height]

ax1 = plt.axes(scale1)
ax2 = plt.axes(scale2, sharex = ax1)
ax3 = plt.axes(scale3, sharex = ax1)
ax4 = plt.axes(scale4)

ax1.plot(i, np.abs(WX) , 'b', linewidth=3)
ax1.plot(i, np.abs(WXg), 'r', linewidth=3)
ax1.set_ylabel('$r_1$',fontsize = 25)
ax1.set_xlim([100, max(i)])
ax1.set_xticks([100,150,200,250,300,350,400,450,500,550])
ax1.set_xticklabels(['','','','','','','','','',''])
ax1.set_ylim([0,15])
ax1.set_yticks(np.arange(0, 15, 5))
ax1.set_yticklabels(['0','5','10'],fontsize = 12)
ax1.plot(i, np.abs(w3[0][1])*y, 'b--', label = '212 ICRF' )
ax1.plot(i, np.abs(w3[1][1])*y, 'g--', label = '295 ICRF')
ax1.plot(i, np.abs(w3[2][1])*y, 'y--', label = '247 MFV' )
ax1.plot(i, np.abs(w3[3][1])*y, 'k--', label = '260 AMS' )

ax2.plot(i, np.abs(WY) , 'b', linewidth=3)
ax2.plot(i, np.abs(WYg), 'r', linewidth=3)
ax2.set_ylabel('$r_2$',fontsize = 25)
ax2.set_ylim([0,20])
ax2.set_yticks([0,5,10,15])
ax2.set_yticklabels(['0','5','10','15'],fontsize = 12)
ax2.plot(i, np.abs(w3[0][2])*y, 'b--', label = '212 ICRF' )
ax2.plot(i, np.abs(w3[1][2])*y, 'g--', label = '295 ICRF')
ax2.plot(i, np.abs(w3[2][2])*y, 'y--', label = '247 MFV' )
ax2.plot(i, np.abs(w3[3][2])*y, 'k--', label = '260 AMS' )

ax3.plot(i, np.abs(WZ) , 'b', linewidth=3)
ax3.plot(i, np.abs(WZg), 'r', linewidth=3)
ax3.set_ylabel('$r_3$',fontsize = 25)
ax3.set_ylim([0, 15])
ax3.set_yticks(np.arange(0, 15, 5))
ax3.set_yticklabels(['0','5','10'],fontsize = 12)
ax3.plot(i, w3[0][3]*y, 'b--', label = '212 ICRF' )
ax3.plot(i, w3[1][3]*y, 'g--', label = '295 ICRF')
ax3.plot(i, w3[2][3]*y, 'y--', label = '247 MFV' )
ax3.plot(i, w3[3][3]*y, 'k--', label = '260 AMS' )

ax4.plot(i, W, 'b', linewidth=3)
ax4.plot(i, Wg, 'r', linewidth=3)
ax4.set_ylabel('$r$', fontsize=25)
ax4.set_ylim([0,20])
ax4.set_yticks(np.arange(0, 20, 5))
ax4.set_yticklabels(['0','5','10','15'],fontsize = 12)
ax4.plot(i, w3[0][0]*y, 'b--' , label = '212 ICRF' )
ax4.plot(i, w3[1][0]*y, 'g--', label = '295 ICRF' )
ax4.plot(i, w3[2][0]*y, 'y--', label = '247 MFV' )
ax4.plot(i, w3[3][0]*y, 'k--', label = '260 AMS' )
ax4.set_xlim([100,max(i)])
ax4.set_xticks([100,150,200,250,300,350,400,450,500,550, max(i)])
ax4.set_xticklabels(['100','','200','','300','','400','','500', ''],fontsize = 15)
ax4.legend(loc=0, fontsize=10)
ax4.set_xlabel('No. Sources', fontsize=15)

plt.show()
plt.savefig('../plot/Rotation_No.eps', dpi=100)
plt.close()

print('Done!')


print("genera lo numero del 1 al 10: ")
input()

lista = [0,1,2,3,4,5,6,7,8,9]

numero = 1

range = (10)

for numero in lista:
  print(numero)


#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import os
import sys
import rospy
import numpy as np

import cv2
from sensor_msgs.msg import Image, CompressedImage
from cv_bridge import CvBridge, CvBridgeError

from darknet_ros_msgs.msg import BoundingBoxes, ObjectCount

class Bridge(object):
    """압축된 이미지를 센서 메세지 형태로 변환한다.."""

    def __init__(self):
        # 글로벌 변수 설정
        self.bridge = CvBridge()
        self.bounding_boxes = BoundingBoxes()
        self.image = None

        # 발행 설정
        self.compressed_detection_image_pub = rospy.Publisher("/detection_image/compressed", CompressedImage, queue_size=1)

        # 구독 설정
        compressed_color_image_sub = rospy.Subscriber("camera/color/image_raw/compressed", CompressedImage, self.bridge_color_image)
        bounding_boxes_sub = rospy.Subscriber('darknet_ros/bounding_boxes', BoundingBoxes, self.update_bounding_boxes)

    def bridge_color_image(self, data):
        """
        """

        # 압축 데이터를 CV 배열로 변환
        np_arr = np.fromstring(data.data, np.uint8)
        self.image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)

        # try:
        #     self.color_image_pub.publish(self.bridge.cv2_to_imgmsg(color_image, "bgr8"))

        # except CvBridgeError as e:
        #     print(e)

    def update_bounding_boxes(self, data):
        bounding_boxes = data

        for i in range(len(self.bounding_boxes.bounding_boxes)):
            try:
                if self.bounding_boxes.bounding_boxes[i].Class == 'person':
                    probability = self.bounding_boxes.bounding_boxes[i].probability
                    xmin = self.bounding_boxes.bounding_boxes[i].xmin
                    ymin = self.bounding_boxes.bounding_boxes[i].ymin
                    xmax = self.bounding_boxes.bounding_boxes[i].xmax
                    ymax = self.bounding_boxes.bounding_boxes[i].ymax
                    _id = i + 1
                    _class = self.bounding_boxes.bounding_boxes[i].Class
            except:
                pass

    # def bridge_detection_image(self, data):
    #     """
    #     """
    #     # try:
    #     detection_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
    #     # except CvBridgeError as e:
    #     #     print(e)

    #     compressed_detection_image = CompressedImage()
    #     compressed_detection_image.header.stamp = rospy.Time.now()
    #     compressed_detection_image.format = "jpeg"
    #     compressed_detection_image.data = cv2.imencode('.jpg', detection_image)[1].tostring()

    #     try:
    #         self.compressed_detection_image_pub.publish(compressed_detection_image)

    #     except CvBridgeError as e:
    #         print(e)

if __name__ == '__main__':
    rospy.init_node('bridge', anonymous=False)
    bridge = Bridge()
    rospy.spin()


""" CONTROLLER.PY
    The site controller controlls the production of the response
    for requests to the website. The controller creates and interacts
    with both, the SiteModel and the SiteViews. A call to the controller
    calls start_response and returns the contents of the response.

    Upgrade to multi-site:
    ./ set up with config in apache config
    ./ changes to main
      ./ read and open config
      ./ set paths from config
      ./ check if import weberror works else set flag
    ./ changes to controller
      ./ look for script_name split into sitename and responsearr
        (keep older code arround but commented out)
      ./ update config if section with name exists
      ./ clean up baseurlpath or replace with siteurl where appropriate
    ./ test on current site
      ./ make 2 sites with 2 different folders and names (also check if basename works)
      ./ also check if old system with scriptalias still works
    ./ changes to main with extra error
      ./ make changes to have both error functions, call of correct application at bottom
      ./ test both errors
    - look at main <-> controller: does split make sense?
    - update log in controller

    Add search tab

"""

### Preparation
# Import
import sys # System Library
import os # OS Library
import time # Time Library
import logging.config # Logging Config Object
#import urlparse # URLParse Library (should be used instead of CGI)
import cgi # CGI library (needed because urlparse.parse_qs broken in py2.5)
import hashlib # Hashlib Library
import shelve # Shelve Module
from configobj import ConfigObj # Configuration Object
from views import SiteViews # Site Views Object
from model import SiteModel # Site Model Object

class SiteController(object):
    """ Controller object that formulates the response to the http
        request.
    """
    def __init__(self):
        """ Constructor: declares the variables
        """
        # Declare Variables
        self.env = {'No Env':0} # Environment
        self.conf = None # Configuration Object
        self.output = 'No Output' # Output
        self.log = None # Logging Object
        self.sid = '' # Session ID
        self.session = {} # Session Variables
        self.request = {} # Request Variables
        self.views = None # The views object
        self.model = None # The model object

    def __call__(self,environ,start_response):
        """ Object Call: creates the response
        """
        ### Setup / Preparation
        errormsg = ''
        # Set Environment
        self.env = environ
        # Split URI into sitename and RESPONSEARR with path info -> fill / update session vars
        # response = environ.get('PATH_INFO','list') # Old code: PATH_INFO not available using SciptAliasMatch
        #responsearr = environ.get('SCRIPT_NAME').strip('/').split('/') # Does not work with older browsers
        responsearr = environ.get('REQUEST_URI').strip('/').split('/')
        if len(responsearr) > 0:
            siteurl = responsearr[0]
            responsearr = responsearr[1:]
        else: siteurl = ''
        # Load Configuration
        self.conf = ConfigObj(environ.get('WEBVIEW_CONFIG'))
        # Add configuration from site_sitename
        if 'site_'+siteurl in self.conf:
            self.conf.merge(self.conf['site_'+siteurl])
        # Edit siteurl in config
        if len(siteurl):
            self.conf['path']['siteurl'] = '/'+siteurl
        # Set up logging & print message
        logfile = os.path.join(self.conf['path']['basepath'],
                               self.conf['ctrl']['logfile'])
        logging.basicConfig(level='DEBUG',filename = logfile,
                            format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.log = logging.getLogger('webview.control')
        self.log.info('********* Started Controller')
        self.log.info('          Request from %s to %s'
                       % (environ.get('REMOTE_ADDR'),
                          environ.get('REQUEST_URI')))
        # Get Post request parameters (decode if needed)
        try:
            request_size = int(environ.get('CONTENT_LENGTH', 0))
        except (ValueError):
            request_size = 0
        request_body = environ['wsgi.input'].read(request_size)
        try:
            request_body = request_body.decode()
        except(UnicodeDecodeError,AttributeError):
            pass
        request_params = cgi.parse_qs(request_body)
        # Attach GET request parameters
        query_string = environ['QUERY_STRING']
        request_params.update(cgi.parse_qs(query_string))
        self.request = request_params
        # Get session id from Post request
        self.log.debug('Request Params = ' + repr(request_params))
        self.sid = request_params.get('sid',[''])[0]
        if len(self.sid):
            self.log.info('Existing Session SID = %s' % self.sid)
        else:
            self.log.info('New Session')
            self.sid = hashlib.sha1((repr(time.time())+environ['REMOTE_ADDR']).encode('utf-8')).hexdigest()
        # Get session information / make new session file
        sessionfile = os.path.join(self.conf['path']['basepath'],
                                   self.conf['path']['session'],
                                   'sess_%s' % self.sid)
        self.session = shelve.open(sessionfile, writeback = True)
        self.session['sid'] = self.sid
        # Make other objects
        self.views = SiteViews(self.env, self.session, self.conf)
        self.model = SiteModel(self.env, self.session, self.conf)
        self.views.model = self.model
        ###### Compute response (format is page/request)
        # Select Response and Query from URI -> fill / update session vars
        if len(responsearr) > 0:  self.session['page'] = responsearr[0].lower()
        else: self.session['page'] = 'list'
        if not (self.session['page'] in ['data','error','log', 'list', 'search', 'test']):
            self.session['page'] = 'list'
        self.log.info('Page Type is = %s' % self.session['page'])
        #-- DATA Response: update session variables and validate request
        self.session['request'] = '' # Clear request
        if self.session['page'] == 'data':
            responsefolder = '' # variable to allow check if folder is valid
            # Get and Validate request
            if responsearr[-1].lower() in ['raw']:
                self.session['request'] = responsearr[-1].lower()
                responsearr = responsearr[0:-1]
            # FOLDER selection from request parameters or response path array
            if 'folder_selection' in request_params:
                self.session['folder'] = request_params.get('folder_selection')[0]
            elif len(responsearr) > 1:
                responsefolder = os.path.join(*responsearr[1:])
                self.session['folder'] = responsefolder
            # FILE selection from request parameters
            if 'file_selection' in request_params:
                self.session['file'] = request_params.get('file_selection')[0]
            # STEP selection from request parameters
            if 'step_selection' in request_params:
                self.session['step'] = request_params.get('step_selection')[0]
            # DATA selection from request parameters
            if 'data_selection' in request_params:
                self.session['data'] = request_params.get('data_selection')[0]
            # PLANE selection from request parameters
            if 'plane_selection' in request_params:
                self.session['plane'] = request_params.get('plane_selection')[0]
            # Validate / Set session variables
            self.model.set_selection()
            # if no data available -> error
            if len(self.session['data']) == 0:
                self.session['page'] = 'error'
                errormsg = 'No FITS data avaialable:
  '
                errormsg += ' folder = <%s>' % (self.session['folder'])
                errormsg += ' file = <%s>' % (self.session['file'])
                errormsg += ' step = <%s>' % (self.session['step'])
                errormsg += ' data = <%s>' % (self.session['data'])
                errormsg += ' plane = <%s>' % (self.session['plane'])
            # if responsefolder was invalid raise error
            if ( len(responsefolder) and not responsefolder in self.session['folder'] and
                 int(self.conf['ctrl']['erronbadurl']) ):
                self.session['page'] = 'error'
                errormsg = 'Nonexistent or empty folder requested: %s is not available or contains no data' % responsefolder
        #-- LOG Response: update session variables and validate request
        if self.session['page'] == 'log':
            # Get and Validate request
            if responsearr[-1].lower() in ['update']:
                self.session['request'] = responsearr[-1].lower()
            # LOG_LEVEL selection from request parameters
            if 'log_level' in request_params:
                level = request_params.get('log_level')[0]
                if level in 'DEBUG INFO WARNING ERROR CRITICAL':
                    self.session['loglevel'] = level
            elif not 'loglevel' in self.session:
                self.session['loglevel'] = 'INFO'
        #-- LIST Response: update session variables and validate request
        if self.session['page'] == 'list':
            # LIST_FOLDER selection from response path array
            responsefolder = '' # variable to allow check if folder is valid
            if len(responsearr) > 1:
                responsefolder = responsearr[1]
                self.session['listfolder'] = responsefolder
            else:
                self.session['listfolder'] = ''
            # Get Folder list and make sure there's something there
            folderlist = self.model.folderlist(0)
            if len(folderlist) == 0:
                self.session['page'] = 'error'
                errormsg = 'NO Data Folders Available
 No folders were found under '
                errormsg += os.path.join(self.conf['path']['basepath'], self.conf['path']['datapath'])
                errormsg += '. Check the server settings or contact the administrator.'
            elif ( len(responsefolder) and not responsefolder in folderlist and
                   int(self.conf['ctrl']['erronbadurl'])):
                self.session['page'] = 'error'
                errormsg = 'Nonexistent folder requested: %s is not available or contains no data' % responsefolder
            else:
                # Set list_folder
                if not self.session['listfolder'] in folderlist:
                    self.session['listfolder'] = folderlist[-1]
        #-- TEST Response: log the messages
        if self.session['page'] == 'test':
            if 'messagetext' in request_params:
                self.log.debug('Test - Message from %s: %s' %
                               (environ.get('REMOTE_ADDR'), request_params['messagetext'][0]) )
        # Print request if it came up
        if len(self.session['request']) > 0:
            self.log.info('Request Type is = %s' % self.session['request'])
        ###### Make response page
        # Initialize Response
        status = '200 OK'
        response_headers = [('Content-Type','text/html')]
        self.output = ''
        # If there is no request -> return regular page
        if len(self.session['request']) == 0 or self.session['page'] == 'error':
            # Create Response Header
            self.output += self.views.header()
            # Create Text
            if self.session['page'] == 'data':
                # Request is to see data
                self.output += self.views.data()
            elif self.session['page'] == 'error':
                # Request is an Error
                self.output += self.views.error(errormsg)
            elif self.session['page'] == 'log':
                # Request is log
                self.output += self.views.pipelog()
            elif self.session['page'] == 'list':
                # Request is list
                self.output += self.views.folderlist()
            elif self.session['page'] == 'search':
                # Request is search
                self.output += self.views.search()
            elif self.session['page'] == 'test':
                # Request is test
                self.output += self.views.test()
            # Close Response
            self.log.debug('debuginfo = %d' % int(self.conf['ctrl']['debuginfo']) )
            if( int(self.conf['ctrl']['debuginfo']) > 0 or
                self.session['page'] == 'test' ):
                self.list_env()
            self.output += ''
        # If there is a querry -> return request text instead
        else:
            # Data, Raw request
            if self.session['page']+'-'+self.session['request'] == 'data-raw':
                self.output += self.views.dataraw()
            # Logging, Update request
            if self.session['page']+'-'+self.session['request'] == 'log-update':
                self.output += self.views.logupdate()
        # Return
        start_response(status, response_headers)
        self.log.info('********* Finished Controller')
        return self.output

    def list_env(self):
        """ Creates a response containing path and environment variables.
        """
        # Initialize Output
        output = "
\n
Environment Setup
\n"
        # Add request text
        reqtext = ['
%s: %s' % (key, self.request[key])
                   for key in self.request]
        reqtext = '\n'.join(reqtext)
        output += 'Request:
\n' + reqtext + '
\n'
        # Add current path
        output += 'Current Path: %s
\n' % os.getcwd()
        # Add session variables
        sesstext = ['
%s: %s' % (key, self.session[key])
                   for key in self.session]
        sesstext = '\n'.join(sesstext)
        output += 'Session Variables:
\n' + sesstext + '
\n'
        # Add environment Variables
        envstr = ['
%s: %s' % (key,self.env[key])
                  for key in sorted(self.env.keys())]
        envstr = '\n'.join(envstr)
        output += 'Environment Variables:
\n' + envstr + '
\n'
        # Add path
        pathstr = ['
%s' % p for p in sorted(sys.path) ]
        pathstr = '\n'.join(pathstr)
        output += 'Path Settings:
\n' + pathstr + '
\n'
        # Return answer
        self.output += output

""" === History ===
    2021-4 Marc Berthoud, remove use of logconfig
    2020 Marc Berthoud, Upgrade to multi-site
    2020-1-10 Marc Berthoud,
        * removed [path][baseurlpath from config: Either use absolute paths
          or use siteurl (which is set automatically), also in logscripts.js
        * Config now comes from environment variable WEBVIEW_CONFIG
        * Load site_siteurl preferences from config section into config
          to allow multiple sites on a server.
        * Main.py now loads pythonpaths from config file
        * Main.py checks if weberror.errormiddleware exists else uses
          simpler error reporting function
    2015-2-20 Marc Berthoud, Various improvements
        * Update code for using astropy.io.fits
    2014-4-3 Marc Berthoud, Added self.infohead to model object to specify
        which header contains main information.
    2012-11-13 Marc Berthoud, Ability to specify instrument name and icons
        * Ability to have information come from specific headers
        * Configuration file name is now in main.py
    2012-9-13 Marc Berthoud, Added file name and format flexibility
        * Added flexible detection of pipe step in file name (model.filelist)
        * Added ability to have no image in primary FITS header
    2012-6-15 Marc Berthoud, Added use of jQuery for JavaScript elements
        * New ['scripts'] section in the configuration, scripts are now
          loaded in the page header
        * Updated logscripts.js for use of jQuery
    2012-4-12 Marc Berthoud, Various improvements during system testing
        * Validate flights and aors to make sure data is present
        * Add INSTMODE to the end of AOR entries in data
    2011-11-23 Marc Berthoud, Ver0.2: Added imageanalysis javascript object
        to the viewer to manage client side user interface.
    2011-1-31 Marc Berthoud, Ver0.1: Wrote and Tested
"""


import markovify
import sys
import argparse
import configparser
import twitter

model_depth_default = 2
model_depth = model_depth_default

def main():
	arg_parser = argparse.ArgumentParser(description="Generate text with Markov chains based on a source corpus.")
	subparser = arg_parser.add_subparsers(dest="subparser_name")

	subparser_train = subparser.add_parser("train")
	subparser_train.add_argument("corpus", help="Path to a corpus to train with.")
	subparser_train.add_argument("savepath", help="Path to where to save the model, in JSON format.")

	subparser_tweet = subparser.add_parser("tweet")
	subparser_tweet.add_argument("corpus", help="Path to a corpus.")
	subparser_tweet.add_argument("modelpath", help="Path to a model built with \"train\"")
	subparser_tweet.add_argument("--no-post", help="Do not post to Twitter, write to stdout and exit.", action="store_true")

	args = arg_parser.parse_args()

	config = configparser.ConfigParser()
	config.read("poorlytrained.ini")
	twitter_consumer_key = config["keys"]["consumerkey"]
	twitter_consumer_secret = config["keys"]["consumersecret"]
	twitter_access_token = config["keys"]["accesstoken"]
	twitter_access_token_secret = config["keys"]["accesstokensecret"]

	try:
		model_depth = config["markov"]["modeldepth"]
	except:
		sys.stderr.write("WARNING: Could not read model depth from configuration file. Defaulting to {}.\n".format(model_depth_default))

	if(args.subparser_name == "train"):
		with open(args.corpus) as f:
			text = f.read()

		text_model = markovify.Text(text)

		with open(args.savepath, "w") as f:
			f.write(text_model.chain.to_json())

	elif(args.subparser_name == "tweet"):
		with open(args.corpus) as corpus:
			with open(args.modelpath) as model:
				model_chain = markovify.Chain.from_json(model.read())
				text_model = markovify.Text(corpus.read(), model_depth, model_chain)

		tweet_message = text_model.make_short_sentence(140)
		print(tweet_message)

		if(args.no_post == False): # If --no-post was not specified, go ahead and post.
			tapi = twitter.Api(twitter_consumer_key, twitter_consumer_secret, twitter_access_token, twitter_access_token_secret)
			tapi.PostUpdate(tweet_message)
if __name__ == "__main__":
	main()


# encoding = utf-8

class FirstClass():
    name = 'javaAndBidata'

    def javaAndBigdata_method(self):
        '''
        方法定义的时候必须存在一个形参，默认为self，否则会报错
        self即为对象本身
        :return:
        '''
        print("this is javaAndBigdata's method!!!")
        return self.name  # 表明self为对象本身

    @classmethod
    def class_method(cls):
        print("类方法，用到了 classmethod 装饰器！！")

    @staticmethod
    def static_method():
        print("静态方法，一般与类无关，常常为工具方法！！！")

javaAndBigdataInstance = FirstClass()
print(javaAndBigdataInstance.name)
print(javaAndBigdataInstance.javaAndBigdata_method())
FirstClass.class_method()
FirstClass.static_method()


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

from tensorflow.keras.applications.resnet_v2 import ResNet152V2, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
import numpy as np

def classifyImg(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    # print(x)
    x = np.expand_dims(x, axis = 0)
    # print(x)
    x = preprocess_input(x)

    # Create the model
    model = ResNet152V2(weights='imagenet')

    # output prediction
    prediction = model.predict(x)

    # decode output
    print('prediction: ', decode_predictions(prediction, top=3)[0])

img_path1 = 'fig/monkey.jpg'
classifyImg(img_path1)
img_path2 = 'fig/bird.jpg'
classifyImg(img_path2)
img_path3 = 'fig/taj.jpg'
classifyImg(img_path3)
img_path4 = 'fig/car.jpeg'
classifyImg(img_path4)


import torch
from .logger_utils import get_logger
import matplotlib.pyplot as plt
import numpy as np
import itertools

logger = get_logger()
def prediction(*, test_data, model, device):
    """Predict on test data and generate confusion matrix.

    Args:
        test_data (torch.utils.data.Dataset): Test dataset.
        model (torch.nn.Module): Model.
        device (str): Device (cpu or gpu or mps)
    """
    num_classes = 10
    class_names = [
        "T-shirt/top",
        "Trouser",
        "Pullover",
        "Dress",
        "Coat",
        "Sandal",
        "Shirt",
        "Sneaker",
        "Bag",
        "Ankle boot",
    ]
    confusion_matrix = torch.zeros(num_classes, num_classes)

    with torch.no_grad():
        for X, y in test_data:
            X = X.unsqueeze(0).to(device)
            y = torch.tensor([y]).to(device)

            outputs = model(X)
            _, predicted = torch.max(outputs.data, 1)

            for t, p in zip(y.view(-1), predicted.view(-1)):
                confusion_matrix[t.long(), p.long()] += 1

    plt.figure(figsize=(10,10))
    plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues)
    plt.title('Confusion matrix')
    plt.colorbar()
    tick_marks = np.arange(len(class_names))
    plt.xticks(tick_marks, class_names, rotation=45)
    plt.yticks(tick_marks, class_names)

    thresh = confusion_matrix.max() / 2.
    for i, j in itertools.product(range(confusion_matrix.shape[0]), range(confusion_matrix.shape[1])):
        plt.text(j, i, format(confusion_matrix[i, j], '.1f'),
                 horizontalalignment="center",
                 color="white" if confusion_matrix[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.savefig('confusion_matrix.png')
    logger.info('Confusion Matrix saved as confusion_matrix.png')


from typing import Callable

def format_number(number: int) -> str:
    num = float(f"{number:.3g}")
    magnitude = 0

    format_human: Callable[[float], str] = lambda x: f"{x:f}".rstrip("0").rstrip(".")

    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0

    return f"{format_human(num)}{['', 'K', 'M', 'G', 'T', 'P'][magnitude]}"


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
#from django.template import loader  # no longer needed b/c of render shortcut

from .models import Question, Choice

# Create your views here.
class IndexView(generic.ListView):
    """
    """
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    """
    This is a generic view. Each generic view needs to know
    what model it will be acting upon. This is provided using
    the model attribute. The detail view expects the primary key
    value captured from the url to be called 'pk' so we changed
    question_id to pk for the generic views.
    """
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(generic.DetailView):
    """
    This is a generic view
    """
    model = Question
    template_name = 'polls/results.html'

def vote(request, question_id):
    """
    This function will increase the number of votes a selected
    question have, if it exists, and then redirect us to the results
    page. If said question fails, we are given a 404 error!

    Reverse will take us to the view specified by arg1 along with the
    variable portion of the url specified by arg2.
    """
    question = get_object_or_404(Question, pk=question_id)
    try:
        # this will obtain the id of the selected choice as a string
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # error message if choice isn't given
        return render(request, 'polls/detail.html', {'question': question, 'error_message': "You didn't select a choice."})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # redirected to this url - always return a redirect after successfully
        # dealing with POST data - prevents data from being posted twice if the
        # user hits the back button
        return HttpResponseRedirect(reverse('polls:results', args=(question_id,)))

#################################################################################################################3
### Previous versions of functions below!
#################################################################################################################3

#def index(request):
    #"""
    #index will display the latest 5 poll questions in the system, separated by commans,
    #according to the publication date.
    #"""
    #latest_question_list = Question.objects.order_by('-pub_date')[:5]
    #template = loader.get_template('polls/index.html')
    #context = {
        #'latest_question_list': latest_question_list
    #}
    # httpresponse is common, but render is a shortcut!
    #return HttpResponse(template.render(context, request))

#def index(request):
    #"""
    #The simplest view possible in Django
    #"""
    #return HttpResponse("Hello world! You're at the polls index!")

# one way of writing a 404 error
#def detail(request, question_id):
    #"""
    #Returns a simple template response.
    #"""
    #try:
        #question = Question.objects.get(pk=question_id)
    #except Question.DoesNotExist:
        #raise Http404("Question does not exist!")
    #return render(request, 'polls/detail.html', {'question': question})


from enum import Enum
from dynsimf.models.helpers.ConfigValidator import ConfigValidator
from dynsimf.models.components.conditions.Condition import Condition

__author__ = "Mathijs Maijer"
__email__ = "m.f.maijer@gmail.com"

class UpdateType(Enum):
    '''
    An Enum to specify the type of the update
    '''
    STATE = 0
    NETWORK = 1
    EDGE_VALUES = 2

class UpdateConfiguration(object):
    '''
    Configuration for Updates

    :var config: The dictionary containing the key/value pairs of the members of this class,
        if no key/value pair is provided, a default value is used instead
    :vartype config: dict
    :var arguments: A dictionary with arguments for the update function, defaults to empty dict
    :vartype arguments: dict
    :var condition: A condition for nodes that must be met before the update is executed on them
    :vartype condition: Condition or None
    :var get_nodes: A boolean indicating whether the update function should receive a list of sampled nodes as argument,
        defaults to None
    :vartype get-nodes: bool or None
    :var update_type: A value from the `UpdateType` enum, indicating what kind of update is being performed,
        defaults to `UpdateType.STATE`
    :vartype update_type: UpdateType
    '''
    def __init__(self, config=None):
        self.set_config(config)
        self.validate()

    def set_config(self, config):
        '''
        Set the values for the members of the class by reading them from the config or setting their default values

        :param dict config: The configuration dictionary with the key/value pairs for the class members
        '''
        self.config = config if config else {}
        self.arguments = config['arguments'] if 'arguments' in self.config else {}
        self.condition = config['condition'] if 'condition' in self.config else None
        self.get_nodes = config['get_nodes'] if 'get_nodes' in self.config else None
        self.update_type = config['update_type'] if 'update_type' in self.config else UpdateType.STATE

    def validate(self):
        '''
        Validate the update configuration

        :raises ValueError: if the `update_type` member is not of type `UpdateType`
        '''
        ConfigValidator.validate('arguments', self.arguments, dict)
        ConfigValidator.validate('condition', self.condition, Condition, optional=True)
        ConfigValidator.validate('get_nodes', self.get_nodes, bool, optional=True)
        ConfigValidator.validate('update_type', self.update_type, UpdateType)
        if not isinstance(self.update_type, UpdateType):
            raise ValueError('Update type should of enum UpdateType')

class Update(object):
    """
    Update class

    :var fun: The update function that should be executed
    :vartype fun: function
    :var config: UpdateConfiguration object, defaults to a new UpdateConfiguration object
    :vartype config: UpdateConfiguration
    :var arguments: A dictionary with arguments for the update function, defaults to empty dict
    :vartype arguments: dict
    :var condition: A condition for nodes that must be met before the update is executed on them
    :vartype condition: Condition or None
    :var get_nodes: A boolean indicating whether the update function should receive a list of sampled nodes as argument,
        defaults to None
    :vartype get-nodes: bool or None
    :var update_type: A value from the `UpdateType` enum, indicating what kind of update is being performed,
        defaults to `UpdateType.STATE`
    :vartype update_type: UpdateType
    """

    def __init__(self, fun, config=None):
        '''
        Initialise the update by setting the class members to their values defined in the config

        :param function fun: The update function to execute
        :param config: The configuration object containing the values for the class members
        :type config: UpdateConfiguration, optional
        '''
        self.function = fun
        self.config = config if config else UpdateConfiguration()
        self.arguments = self.config.arguments
        self.condition = self.config.condition
        self.get_nodes = self.config.get_nodes
        self.update_type = self.config.update_type

    def execute(self, nodes=None):
        '''
        Execute the update function with or without the sampled nodes from the scheme/condition
        and return the output

        :param nodes: An optional list of nodes that the update function should be applied on.
            The given nodes are filtered by the schemes and conditions
        :type nodes: list, optional
        '''
        if self.get_nodes:
            output = self.function(nodes, **self.arguments)
        else:
            output = self.function(**self.arguments)
        return output


from torch.utils.data import Dataset
import numpy as np
from pathlib import Path
import pandas as pd
import torch
from dpipe.io import load_numpy

class BraTSDataset(Dataset):
    def __init__(self, meta: pd.DataFrame, source_folder: [str, Path], nonzero_mask=False, transform=None):
        if isinstance(source_folder, str):
            source_folder = Path(source_folder)

        if nonzero_mask:
            meta = meta[meta.sample_id.isin(meta.query('is_nonzero_mask == True').sample_id)]

        self.source_folder = source_folder
        self.meta_images = meta.query('is_mask == False').sort_values(by='sample_id').reset_index(drop=True)
        self.meta_masks = meta.query('is_mask == True').sort_values(by='sample_id').reset_index(drop=True)
        self.transform = transform

    def __len__(self):
        return self.meta_images.shape[0]

    def __getitem__(self, i):
        image = load_numpy(self.source_folder / self.meta_images.iloc[i]['relative_path'], allow_pickle=True, decompress=True)
        mask = load_numpy(self.source_folder / self.meta_masks.iloc[i]['relative_path'], allow_pickle=True, decompress=True)
        sample = image, mask

        if self.transform:
            image, mask = self.transform(sample)

        return torch.from_numpy(image).reshape(1, 240, 240), torch.from_numpy(mask).reshape(1, 240, 240).double()


import os
import zipfile
from abc import ABCMeta
from pathlib import Path
from typing import Optional, Union
from urllib.request import urlretrieve

class BaseDownloader(metaclass=ABCMeta):
    """Base downloader for all Movielens datasets."""

    DOWNLOAD_URL: str
    DEFAULT_PATH: str

    def __init__(self, zip_path: Optional[Union[Path, str]] = None):
        if zip_path is None:
            zip_path = self.DEFAULT_PATH
        else:
            zip_path = zip_path
        self.zip_path = Path(zip_path)
        if not self.zip_path.exists():
            self._retrieve()

    def _retrieve(self) -> None:
        url: str = self.DOWNLOAD_URL
        file_name: str = str(self.zip_path) + ".zip"
        urlretrieve(url, filename=file_name)
        with zipfile.ZipFile(file_name) as zf:
            zf.extractall(self.zip_path.parent)
        os.remove(file_name)


#!/usr/bin/env python
import os
import re
import glob

def printPackages():
    paths = glob.glob(os.path.join('/usr/share', 'cmake*/Modules'))
    modules = [package for path in paths for package in os.listdir(path)]
    [print(module[4:-6]) for module in modules if re.search("^Find", module) and module[4:-6] != '']

def run():
    printPackages()

if __name__ == '__main__':
    run()


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os

def MyPlotSO(CompMethod,trials,MaxFuncEvals,method,problem):
    ##% Plot
    figcount=0
    Convergence = np.zeros((int(CompMethod.shape[0]/trials), MaxFuncEvals))
    count=-1
    for i in range(0,int(CompMethod.shape[0]),trials):
        count+=1
        for j in range(trials):
            a=np.array(CompMethod[i+j,4])
            b=np.array(Convergence[count,:])
            Convergence[count,:] = a + b
    Convergence=problem['Max/Min']*Convergence
    Convergence= Convergence / trials
    ##% Convergence curves
    PlotConvergence(Convergence,method)
    figcount+=1
    savefigures(figcount,plt)
    #savefigures(plots)
    ##% Violin Plots
    for i in range(2,4):
        #print(i)
        vec = CompMethod[:, i]
        matrix = vec.reshape((int(CompMethod.shape[0]/trials)),trials)
        matrix=matrix.T
        ViolinPlotting(matrix,trials,method)
        figcount+=1
        savefigures(figcount,plt)
    return

def PlotConvergence(Convergence,method):
    # Define colors, styles, and symbols for each line
    colors = ['red', 'blue', 'green', 'orange', 'purple']
    linestyles = ['-', '--', '-.', ':', '-']
    #markers = ['o', 's', 'D', '*', '^']
    # Create a figure and axes
    fig, ax = plt.subplots()
    # Loop through each row of the matrix and plot it as a separate line
    for i in range(Convergence.shape[0]):
        ax.plot(Convergence[i], color=colors[i], linestyle=linestyles[i], label=method[i])
    # Add a legend to the plot
    ax.legend()
    ax.grid()
    # Add title and axis labels
    ax.set_title('Convergence characteristic curves')
    ax.set_xlabel('Function evaluations')
    ax.set_ylabel('Objective function value')
    # Display the plot
    #ax.show()
    return plt

def ViolinPlotting(matrix,trials,method):
    df = pd.DataFrame(matrix, columns=method)
    sns.set_context("talk", font_scale=1)
    plt.figure(figsize=(7,2*matrix.shape[1]))
    plt.grid()
    sns.violinplot(data=df, palette='pastel', bw=.5,orient="h")
    sns.stripplot(data=df,color="black", edgecolor="gray", orient="h")
    return plt

def plot_3d(func, points_by_dim = 50, title = '', bounds = None, cmap = 'twilight', plot_surface = True, plot_heatmap = True):
    from matplotlib.ticker import MaxNLocator, LinearLocator
    """
    Plots function surface and/or heatmap
    Parameters
    ----------
    func : class callable object
        Object which can be called as function.
    points_by_dim : int, optional
        points for each dimension of plotting (50x50, 100x100...). The default is 50.
    title : str, optional
        title of plot with LaTeX notation. The default is ''.
    bounds : tuple, optional
        space bounds with structure (xmin, xmax, ymin, ymax). The default is None.
    save_as : str/None, optional
        file path to save image (None if not needed). The default is None.
    cmap : str, optional
        color map of plot. The default is 'twilight'.
    plot_surface : boolean, optional
        plot 3D surface. The default is True.
    plot_heatmap : boolean, optional
        plot 2D heatmap. The default is True.
    """
    assert (plot_surface or plot_heatmap), "should be plotted at least surface or heatmap!"
    xmin, xmax, ymin, ymax = bounds
    x = np.linspace(xmin, xmax, points_by_dim)
    y = np.linspace(ymin, ymax, points_by_dim)
    a, b = np.meshgrid(x, y)
    data = np.empty((points_by_dim, points_by_dim))
    for i in range(points_by_dim):
        for j in range(points_by_dim):
            data[i,j] = func(np.array([x[i], y[j]]))
    a = a.T
    b = b.T
    l_a, r_a, l_b, r_b = xmin, xmax, ymin, ymax
    l_c, r_c = data.min(), data.max()
    levels = MaxNLocator(nbins=15).tick_values(l_c,r_c)
    if plot_heatmap and plot_surface:
        fig = plt.figure(figsize=(16, 6))
        ax1 = fig.add_subplot(1,2,1)
        ax2 = fig.add_subplot(1,2,2, projection='3d')
    else:
        fig = plt.figure()
        if plot_heatmap:
            ax1 = fig.gca()
        else:
            ax2 = fig.gca(projection='3d')
    #title = r"$\bf{" + title+ r"}$"
    #min_title = title[::]
    def base_plot():
        c = ax1.contourf(a, b, data , cmap=cmap, levels = levels, vmin=l_c, vmax=r_c)
        name = title
        ax1.set_title( name, fontsize = 15)
        ax1.axis([l_a, r_a, l_b, r_b])
        fig.colorbar(c)
    if plot_surface:
        # Plot the surface.
        surf = ax2.plot_surface(a, b, data, cmap =  cmap,  linewidth=0, antialiased=False)
        ax2.contour(a, b, data, zdir='z', levels=30, offset=np.min(data), cmap=cmap)
        # Customize the z axis.
        ax2.set_xlabel('1st dim', fontsize=15)
        ax2.set_ylabel('2nd dim', fontsize=15)
        #ax2.set_zlabel('second dim', fontsize=10)
        ax2.set_zlim(l_c, r_c)
        ax2.zaxis.set_major_locator(LinearLocator(5))
        #ax2.zaxis.set_major_formatter(FormatStrFormatter('%.2f'))
        ax2.tick_params(axis='z', pad=10)
        # Add a color bar which maps values to colors.
        if not plot_heatmap: fig.colorbar(surf)#, shrink=0.5, aspect=5)
        ax2.contour(a, b, data, zdir='z', offset=0, cmap =  cmap)
        ax2.view_init(30, 50)
        #ax2.set_title( min_title , fontsize = 15, loc = 'right')
    if plot_heatmap: base_plot()
    fig.tight_layout()
    #if save_as != None:
    #    plt.savefig(save_as, dpi = 900)
    plt.show()
    return fig

def savefigures(figcount,plt):
    # create a directory to store the figures
    if not os.path.exists('results'):
        os.makedirs('results')
    plt.savefig('results/figure_{}.png'.format(figcount), dpi=900, bbox_inches="tight")
    return


import pickle
import pandas as pd
from rs import recommend_system

def main():
    data = pd.read_csv('data/ratings_train.csv')

    users = data.userId.tolist()
    items = data.movieId.tolist()

    ratings = data.rating.tolist()

    rec_sys = recommend_system(100)
    rec_sys.fit(users, items, ratings)

    with open('data/rec-sys', 'wb') as f:
        pickle.dump(rec_sys, f)

if __name__ == '__main__':
    main()


def soma_vetores(vetor1: list, vetor2:list) -> list:
    vetor_soma = []
    maior = max(len(vetor1), len(vetor2))
    for i in range(maior):
        valor1 = vetor1[i] if i < len(vetor1) else 0
        valor2 = vetor2[i] if i < len(vetor2) else 0

        vetor_soma.append(valor1 + valor2)
    return vetor_soma

l1 = [1, 2, 3]
l2 = [7, 8, 9, 6]
l3 = soma_vetores(l1, l2)
print(l3)


import numpy as np

import sofacontrol.utils as scutils
from sofacontrol.mor import pod

class LinearROM():
    """
    Linear ROM, written for compatibility with TPWL class
    """

    def __init__(self, data, dt, Cf=None, Hf=None):
        if not isinstance(data, dict):
            data = scutils.load_data(data)

        # Discretize dynamics via zero-order hold
        self.A_d, self.B_d, self.d_d = scutils.zoh_affine(data['A_c'], data['B_c'], data['d_c'], dt)

        # Build ROM object in case it is needed
        if data['rom_info']['type'] == 'POD':
            self.rom = pod.POD(data['rom_info'])
        else:
            raise NotImplementedError("Unknown ROM type")

        self.state_dim = self.A_d.shape[0]
        self.N = self.state_dim
        self.input_dim = self.B_d.shape[1]

        # Optionally set output and measurement models
        if Cf is not None:
            self.set_measurement_model(Cf)
        else:
            self.C = None
            self.y_ref = None
            self.meas_dim = None

        if Hf is not None:
            self.set_output_model(Hf)
        else:
            self.H = None
            self.z_ref = None
            self.output_dim = None

    def update_state(self, x, u):
        return self.A_d @ x + np.squeeze(self.B_d @ u) + self.d_d

    def set_measurement_model(self, Cf):
        self.C = Cf @ self.rom.V
        self.y_ref = Cf @ self.rom.x_ref
        self.meas_dim = self.C.shape[0]

    def set_output_model(self, Hf):
        self.H = Hf @ self.rom.V
        self.z_ref = Hf @ self.rom.x_ref
        self.output_dim = self.H.shape[0]

    def zfyf_to_zy(self, zf=None, yf=None):
        """
        :zf: (N, n_z) or (n_z,) array
        :yf: (N, n_y) or (n_y,) array
        """
        if zf is not None and self.z_ref is not None:
            return zf - self.z_ref
        elif yf is not None and self.y_ref is not None:
            return yf - self.y_ref
        else:
            raise RuntimeError('Need to set output or meas. model')

    def zy_to_zfyf(self, z=None, y=None):
        """
        :z: (N, n_z) or (n_z,) array
        :y: (N, n_y) or (n_y,) array
        """
        if z is not None and self.z_ref is not None:
            return z + self.z_ref
        elif y is not None and self.y_ref is not None:
            return y + self.y_ref
        else:
            raise RuntimeError('Need to set output or meas. model')

    def x_to_zfyf(self, x, zf=False, yf=False):
        """
        :x: (N, n_x) or (n_x,) array
        :zf: boolean
        :yf: boolean
        """
        if zf and self.H is not None:
            return np.transpose(self.H @ x.T) + self.z_ref
        elif yf and self.C is not None:
            return np.transpose(self.C @ x.T) + self.y_ref
        else:
            raise RuntimeError('Need to set output or meas. model')

    def x_to_zy(self, x, z=False, y=False):
        """
        :x: (N, n_x) or (n_x,) array
        :z: boolean
        :y: boolean
        """
        if z and self.H is not None:
            return np.transpose(self.H @ x.T)
        elif y and self.C is not None:
            return np.transpose(self.C @ y.T)
        else:
            raise RuntimeError('Need to set output or meas. model')

    def get_state_dim(self):
        return self.state_dim

    def get_input_dim(self):
        return self.input_dim

    def get_output_dim(self):
        return self.output_dim

    def get_meas_dim(self):
        return self.meas_dim

    def get_rom_info(self):
        return self.tpwl_dict['rom_info']

def TPWL2LinearROM(tpwl_loc, save_loc):
    """
    Generates linearized ROM from existing TPWL ROM by taking the first linearization point.

    :param tpwl_loc: absolute path to location of tpwl model pickle file
    :param save_loc: absolutel path to location to save linear rom pickle file
    """

    tpwl_data = scutils.load_data(tpwl_loc)

    linrom_data = dict()
    linrom_data['A_c'] = tpwl_data['A_c'][0]
    linrom_data['B_c'] = tpwl_data['B_c'][0]
    linrom_data['d_c'] = tpwl_data['d_c'][0]
    linrom_data['rom_info'] = tpwl_data['rom_info']

    scutils.save_data(save_loc, linrom_data)