from enum import Enum
from typing import List
import sys

import math

class Pos:
    def __init__(self, y: int, x: int):
        self.y = y
        self.x = x

class Response(Enum):
    NOT_BROKEN = 0
    BROKEN = 1
    FINISH = 2
    INVALID = -1

class Field:

    def __init__(self, N: int, C: int):
        self.C = C
        self.is_broken = [[False] * N for _ in range(N)]
        self.total_cost = 0

    def query(self, y: int, x: int, power: int) -> Response:
        self.total_cost += power + self.C
        print(f"{y} {x} {power}", flush=True)
        res = Response(int(input()))
        if res in (Response.BROKEN, Response.FINISH):
            self.is_broken[y][x] = True
        return res

class Solver:

    # def __init__(self, N: int, source_pos: List[Pos], house_pos: List[Pos], C: int, P: int, house_joint_indices: List, MST_min_source: Pos, test_destruct: List[Pos]):
    def __init__(self, N: int, source_pos: List[Pos], house_pos: List[Pos], C: int, P: int):
        self.N = N
        self.source_pos = source_pos
        self.source_pos_org = source_pos[:]
        self.house_pos = house_pos
        self.house_pos_org = house_pos[:]
        self.C = C
        self.P = P
        self.field = Field(N, C)
        self.field_org = Field(N, C)

    # def test_destruction(self):
    #     for test_dest in self.test_destruct:
    #         y, x = test_dest.y, test_dest.x
    #         res = self.destruct_test(y, x)
    #         if res == Response.BROKEN:
    #             self.house_pos.append(Pos(y, x))
    #     self.house_pos_org = self.house_pos[:]

    def grid_test_destruction(self, test_destruct, power):
        BROKEN_pos = []
        for test_dest in test_destruct:
            y, x = test_dest.y, test_dest.x
            res = self.do_grid_test_destruction(y, x, power)
            if res == Response.BROKEN:
                BROKEN_pos.append(Pos(y, x))
        return BROKEN_pos

    def solve(self):
        return 0

    def move(self, start: Pos, goal: Pos):
        # you can output comment
        print(f"# move from ({start.y},{start.x}) to ({goal.y},{goal.x})")

        now_y = start.y
        now_x = start.x

        down_up_list = []
        right_left_list = []

        destructed_field_list = []

        # down/up
        if start.y < goal.y:
            down_up_list += [1] * abs(goal.y - start.y)
        else:
            down_up_list += [-1] * abs(goal.y - start.y)

        # right/left
        if start.x < goal.x:
            right_left_list += [1] * abs(goal.x - start.x)
        else:
            right_left_list += [-1] * abs(goal.x - start.x)

        down_up_list += [0]
        right_left_list += [0]

        move_continue_flg = True
        move_trans_flg = False  # ヨコ移動から開始
        x_None_flg = False
        y_None_flg = False
        bef_destruct_cnt = 5010
        now_destruct_cnt = 5010

        trans_cnt = 0
        trans_continuous_flg = False
        trans_continuous_flg_cnt = 0
        tmp_down_up = 0
        tmp_right_left = 0

        while move_continue_flg:
            if move_trans_flg:
                # タテ移動
                if len(down_up_list) == 0:
                    y_None_flg = True
                    move_trans_flg = False
                else:
                    tmp_down_up = down_up_list.pop()
                    now_y += tmp_down_up
                    now_destruct_cnt = self.destruct(now_y, now_x)
                    # 破壊した岩盤が比較的やわらかい場合は水源として追加
                    if now_destruct_cnt * self.P <= 300:
                        destructed_field_list.append([now_y, now_x])

            else:
                # ヨコ移動
                if len(right_left_list) == 0:
                    x_None_flg = True
                    move_trans_flg = True
                else:
                    tmp_right_left = right_left_list.pop()
                    now_x += tmp_right_left
                    now_destruct_cnt = self.destruct(now_y, now_x)
                    # 破壊した岩盤が比較的やわらかい場合は水源として追加
                    if now_destruct_cnt * self.P <= 300:
                        destructed_field_list.append([now_y, now_x])

            # 岩盤の硬いほうに進んでいる場合はタテヨコ移動を切り替え
            if (now_destruct_cnt > bef_destruct_cnt) and not trans_continuous_flg:
                move_trans_flg = not move_trans_flg
                trans_cnt += 1
            else:
                trans_cnt = 0

            # 連続してタテヨコ移動が切り替わっている場合
            # タテヨコ切り替えOFF
            if trans_cnt >= 4:
                trans_continuous_flg = True

            # 数カウント後に trans_continuous_flg : True -> False
            # タテヨコ切り替えをONに戻す
            if trans_continuous_flg:
                trans_continuous_flg_cnt += 1
                if trans_continuous_flg_cnt >= 30:
                    trans_continuous_flg = False

            # bef_destruct_cnt の更新
            bef_destruct_cnt = now_destruct_cnt

            # while ループの終了条件の更新
            if x_None_flg and y_None_flg:
                move_continue_flg = False

        # 水源到達時には、破壊した岩盤すべてに水が流れている
        # 破壊した岩盤のうちやわらかいもの(S_ij <= 500)を水源に追加する
        for destructed_field in destructed_field_list:
            y, x = destructed_field[0], destructed_field[1]
            self.source_pos.append(Pos(y, x))

    def destruct(self, y: int, x: int):
        # excavate (y, x) with fixed power until destruction
        power = self.P

        destruct_cnt = 0

        while not self.field.is_broken[y][x]:
            destruct_cnt += 1
            result = self.field.query(y, x, power)
            if result == Response.FINISH:
                print(f"total_cost={self.field.total_cost}", file=sys.stderr)
                sys.exit(0)
            elif result == Response.INVALID:
                print(f"invalid: y={y} x={x}", file=sys.stderr)
                sys.exit(1)

        return destruct_cnt

    def do_grid_test_destruction(self, y: int, x: int, p: int):
        # excavate (y, x) with fixed power until destruction
        power = p

        if not self.field.is_broken[y][x]:
            result = self.field.query(y, x, power)
            if result == Response.FINISH:
                print(f"total_cost={self.field.total_cost}", file=sys.stderr)
                sys.exit(0)
            elif result == Response.INVALID:
                print(f"invalid: y={y} x={x}", file=sys.stderr)
                sys.exit(1)
            elif result == Response.BROKEN:
                return result
            elif result == Response.NOT_BROKEN:
                return result

def Manhattan_dist(y1, x1, y2, x2):
    z1 = x1 + y1
    z2 = x2 + y2
    w1 = x1 - y1
    w2 = x2 - y2
    # dist = max(abs(z1 - z2), abs(w1 - w2))
    dist = abs(y2-y1) + abs(x2-x1)
    return dist

def min_Manhattan_dist_source(house_pos_i, source_pos):
    min_dist = 100000 # N=200 より, マンハッタン距離は400以下
    min_dist_source = source_pos[0]
    y1 = house_pos_i.y
    x1 = house_pos_i.x

    # house_pos_i から最短距離にある source を全探索で探す
    for source in source_pos:
        y2 = source.y
        x2 = source.x
        tmp_dist = Manhattan_dist(y1, x1, y2, x2)
        if tmp_dist < min_dist:
            min_dist = tmp_dist
            min_dist_source = source

    return min_dist_source

def dijkstra(matrix_list, start, terminal):

    import math

    route_list = matrix_list # 初期のノード間の距離のリスト

    isolate_num = 0
    isolated_list = []
    node_num = len(route_list) #ノードの数
    unsearched_nodes = list(range(node_num)) # 未探索ノード
    distance = [math.inf] * node_num # ノードごとの距離のリスト
    previous_nodes = [-1] * node_num # 最短経路でそのノードのひとつ前に到達するノードのリスト
    distance[start] = 0 # 初期のノードの距離は0とする

    for isolate in unsearched_nodes:#孤立したノードを探索済にする
        if route_list[isolate].count(0) == node_num:
            unsearched_nodes.remove(isolate)
            distance[isolate] = -isolate

    while(len(unsearched_nodes) != 0): #未探索ノードがなくなるまで繰り返す
        possible_min_distance = math.inf # 最小のdistanceを見つけるための一時的なdistance。初期値は inf に設定。
         # まず未探索ノードのうちdistanceが最小のものを選択する
        min = math.inf
        target_min_index = unsearched_nodes[0] # target_min_index の初期化
        for target in unsearched_nodes:
            if distance[target] < min:
                min = distance[target]
                target_min_index = target
        unsearched_nodes.remove(target_min_index) # 探索するので未探索リストから除去
        target_edge = route_list[target_min_index] # ターゲットになるノードからのびるエッジのリスト
        for index, route_dis in enumerate(target_edge):
            if route_dis != 0:
                if distance[index] > (distance[target_min_index] + route_dis):
                    distance[index] = distance[target_min_index] + route_dis # 過去に設定されたdistanceよりも小さい場合はdistanceを更新
                    if index != start:
                        previous_nodes[index] =  target_min_index #　ひとつ前に到達するノードのリストも更新

    # 経路を格納
    previous_node = terminal
    path = []
    while previous_node != -1:
        path.append(previous_node)
        previous_node = previous_nodes[previous_node]
    path.reverse()

    return distance[terminal], path

def pos2Gidx(pos, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x):
    Gidx = grid_num_x * ((pos.y-grid_start_y)//grid_interval_y) + 1 * ((pos.x-grid_start_x)//grid_interval_x)
    return Gidx

def Gidx2pos(Gidx, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x):
    tmp_y = grid_start_y + (Gidx // grid_num_x) * grid_interval_y
    tmp_x = grid_start_x + (Gidx % grid_num_x) * grid_interval_x
    tmp_pos = Pos(tmp_y, tmp_x)
    return tmp_pos

def main():
    N, W, K, C = [int(v) for v in input().split(" ")]

    source_pos = []
    for _ in range(W):
        y, x = (int(v) for v in input().split(" "))
        source_pos.append(Pos(y, x))

    house_pos = []
    for _ in range(K):
        y, x = (int(v) for v in input().split(" "))
        house_pos.append(Pos(y, x))

    # 掘削の power を決定する
    P = 100

    # グリッド状に試し掘りをする
    # 試し掘りに使う変数の値を指定
    grid_start_y = 8 # grid の y 方向の始点
    grid_start_x = 8 # grid の x 方向の始点
    grid_interval_y = 8 # grid の y 方向の点の間隔
    grid_interval_x = 8 # grid の x 方向の点の間隔
    grid_num_y = 1 + ((N-grid_start_y) // grid_interval_y) # grid の y 方向の点の数
    grid_num_x = 1 + ((N-grid_start_x) // grid_interval_x) # grid の x 方向の点の数

    # グリッド上の試し掘りする点を指定(リストとして用意)
    test_destruct_grid = []
    test_destruct_grid_broken = [[0] * grid_num_x for _ in range(grid_num_y)]
    for y in range(grid_start_y, N, grid_interval_y):
        for x in range(grid_start_x, N, grid_interval_x):
            test_destruct_grid.append(Pos(y, x))

    # 処理

    # Solver インスタンス生成
    solver = Solver(N, source_pos, house_pos, C, P)

    # 試し掘り実行
    from collections import defaultdict
    broken_pos = []
    broken_pos_and_cost = defaultdict(lambda: 0)

    test_P1 = 64
    # 1週目の試し掘り
    tmp_broken_pos = solver.grid_test_destruction(test_destruct_grid, test_P1)
    broken_pos += tmp_broken_pos
    for tmp_pos in tmp_broken_pos:
        broken_pos_and_cost[str(tmp_pos.y) + "," + str(tmp_pos.x)] += test_P1

    # test_P2 = test_P1*4
    # # 2週目の試し掘り
    # tmp_broken_pos = solver.test_destruction_hoge(test_destruct_grid, test_P2)
    # broken_pos += tmp_broken_pos
    # for tmp_pos in tmp_broken_pos:
    #     broken_pos_and_cost[str(tmp_pos.y) + "," + str(tmp_pos.x)] += (test_P1 + test_P2)

    # 試し掘りで破壊済みの岩盤を記録
    for pos in broken_pos:
        test_destruct_grid_broken[(pos.y-grid_start_y) // grid_interval_y][(pos.x-grid_start_x) // grid_interval_x] = 1

    # 隣接リストの作成（重み付きグラフなので、各辺について (隣接頂点, 重み) のタプルを記録する）
    G = [ [0]*(grid_num_y*grid_num_x) for i in range(grid_num_y*grid_num_x) ]
    for pos1 in test_destruct_grid:
        for pos2 in test_destruct_grid:
                # pos1 == pos2 はスキップ
                if (pos1.y == pos2.y) and (pos1.x == pos2.x):
                    continue
                # pos1, pos2 がグリッド上で隣接していない場合はスキップ
                if (pos1.y == pos2.y) and abs(pos1.x - pos2.x) == grid_interval_x:
                    pass
                elif (pos1.x == pos2.x) and abs(pos1.y - pos2.y) == grid_interval_y:
                    pass
                else:
                    continue

                # pos1, pos2 の岩盤が破壊済みか否か
                pos1_broken_flg = False
                pos2_broken_flg = False
                if test_destruct_grid_broken[(pos1.y-grid_start_y) // grid_interval_y][(pos1.x-grid_start_x) // grid_interval_x]:
                    pos1_broken_flg = True
                if test_destruct_grid_broken[(pos2.y-grid_start_y) // grid_interval_y][(pos2.x-grid_start_x) // grid_interval_x]:
                    pos2_broken_flg = True

                # 隣接リストに値を設定
                a = pos2Gidx(pos1, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x)
                b = pos2Gidx(pos2, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x)

                # pos1, pos2 どちらの岩盤も破壊済みの場合
                if pos1_broken_flg and pos2_broken_flg:
                    c = 1 * 10 # 採掘回数の目安
                    G[a][b] = broken_pos_and_cost[str(pos2.y) + "," + str(pos2.x)]
                    G[b][a] = broken_pos_and_cost[str(pos1.y) + "," + str(pos1.x)]
                # pos1, pos2 のどちらかの岩盤のみ破壊済み
                elif (pos1_broken_flg and not pos2_broken_flg) or (not pos1_broken_flg and pos2_broken_flg):
                    c = ((500000 // P) * 10) // 2
                    G[a][b] = c
                    G[b][a] = c
                # pos1, pos2 どちらの岩盤も破壊されていない場合
                elif (not pos1_broken_flg) and (not pos2_broken_flg):
                    c = (500000 // P) * 10
                    G[a][b] = c
                    G[b][a] = c

    # それぞれの家と最近傍の broken_pos をつなげる
    house_broken_pos = [] # それぞれの家と最近傍の broken_pos のリスト
    for start_pos in house_pos:
        goal_pos = min_Manhattan_dist_source(start_pos, broken_pos)
        house_broken_pos.append([start_pos, goal_pos])

    source_broken_pos = [] # それぞれの水源と最近傍の broken_pos のリスト
    for start_pos in source_pos:
        goal_pos = min_Manhattan_dist_source(start_pos, broken_pos)
        source_broken_pos.append([start_pos, goal_pos])

    # broken_pos(家と連結) から すべての broken_pos(水源と連結) へダイクストラ
    # 経路が最短のものを採用
    for house_broken_pos_i in house_broken_pos:
        # broken_pos(家と連結)
        h_broken_pos = house_broken_pos_i[1]
        now_dist = math.inf
        now_path = []
        for source_broken_pos_i in source_broken_pos:
            # broken_pos(水源と連結)
            s_broken_pos = source_broken_pos_i[1]

            # h_broken_pos, s_broken_pos でダイクストラ
            # 経路長と経路を記録
            # tmp_dist, tmp_path = dijkstra(G, pos2Gidx(h_broken_pos, grid_num, grid_interval), pos2Gidx(s_broken_pos, grid_num, grid_interval))
            tmp_dist, tmp_path = dijkstra(G, pos2Gidx(h_broken_pos, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x), pos2Gidx(s_broken_pos, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x))
            # 経路長が最短のものを採用
            if tmp_dist < now_dist:
                now_path = tmp_path
                now_dist = tmp_dist

        # broken_pos(家と連結) から broken_pos(水源と連結) の最短経路を掘る
        s_pos = h_broken_pos
        g_pos = h_broken_pos
        for goal_idx in now_path:
            g_pos = Gidx2pos(goal_idx, grid_start_y, grid_start_x, grid_num_y, grid_num_x, grid_interval_y, grid_interval_x)
            solver.move(s_pos, g_pos)
            s_pos = g_pos

    # それぞれの家と最近傍の broken_pos をつなげる
    for house_broken_pos_i in house_broken_pos:
        solver.move(house_broken_pos_i[0], house_broken_pos_i[1])

    # それぞれの水源と最近傍の broken_pos をつなげる
    for source_broken_pos_i in source_broken_pos:
        solver.move(source_broken_pos_i[0], source_broken_pos_i[1])

if __name__ == "__main__":
    main()


import sys

n, m, k = map(int, sys.stdin.readline().rstrip().split())
data = list(map(int, sys.stdin.readline().rstrip().split()))

data.sort()

first = data[n-1]
second = data[n-2]

result = 0

# for i in range(1,m+1):
#     if i//k>=1 and i%k==1:
#         result += second
#     else:
#         result += first

# 가장 큰 수를 더하는 횟수 계산
count = (m//(k+1))*k
count += m%(k+1)

# 결과 계산
result += (count*first)
result += (m-count)*second

print(result)


from collections import defaultdict
from collections import namedtuple

from oslo_log import log

from oslo_utils import uuidutils

from vitrage.evaluator.base import Template
from vitrage.evaluator.equivalence_repository import EquivalenceRepository
from vitrage.evaluator.template_data import TemplateData
from vitrage.evaluator.template_validation.content.template_content_validator \
    import content_validation
from vitrage.evaluator.template_validation.template_syntax_validator import \
    syntax_validation
from vitrage.utils import datetime as datetime_utils
from vitrage.utils import file as file_utils

LOG = log.getLogger(__name__)

EdgeKeyScenario = namedtuple('EdgeKeyScenario', ['label', 'source', 'target'])

class ScenarioRepository(object):
    def __init__(self, conf):
        self._templates = {}
        self.entity_equivalences = EquivalenceRepository().load_files(
            conf.evaluator.equivalences_dir)
        self.relationship_scenarios = defaultdict(list)
        self.entity_scenarios = defaultdict(list)
        self._load_templates_files(conf)

    @property
    def templates(self):
        return self._templates

    @templates.setter
    def templates(self, templates):
        self._templates = templates

    def get_scenarios_by_vertex(self, vertex):

        entity_key = frozenset(vertex.properties.items())

        scenarios = []
        for scenario_key, value in self.entity_scenarios.items():
            if scenario_key.issubset(entity_key):
                scenarios += value
        return scenarios

    def get_scenarios_by_edge(self, edge_description):

        key = self._create_edge_scenario_key(edge_description)
        scenarios = []

        for scenario_key, value in self.relationship_scenarios.items():

            check_label = key.label == scenario_key.label
            check_source_issubset = scenario_key.source.issubset(key.source)
            check_target_issubset = scenario_key.target.issubset(key.target)

            if check_label and check_source_issubset and check_target_issubset:
                scenarios += value

        return scenarios

    def add_template(self, template_def):

        current_time = datetime_utils.utcnow()

        result = syntax_validation(template_def)
        if not result.is_valid_config:
            LOG.info('Unable to load template: %s' % result.comment)
        else:
            result = content_validation(template_def)
            if not result.is_valid_config:
                LOG.info('Unable to load template: %s' % result.comment)

        template_uuid = uuidutils.generate_uuid()
        self.templates[str(template_uuid)] = Template(template_uuid,
                                                      template_def,
                                                      current_time,
                                                      result)
        if result.is_valid_config:
            template_data = TemplateData(template_def)
            for scenario in template_data.scenarios:
                for equivalent_scenario in self._expand_equivalence(scenario):
                    self._add_scenario(equivalent_scenario)

    def _expand_equivalence(self, scenario):
        equivalent_scenarios = [scenario]
        for symbol_name, entity in scenario.entities.items():
            entity_key = frozenset(entity.properties.items())
            if entity_key not in self.entity_equivalences:
                continue
            equivalent_scenarios = self._expand_on_symbol(
                equivalent_scenarios,
                symbol_name,
                self.entity_equivalences[entity_key] - {entity_key})
        return equivalent_scenarios

    @staticmethod
    def _expand_on_symbol(scenarios_in, symbol_name, entity_keys):
        scenarios_out = list(scenarios_in)
        for entity_key in entity_keys:
            for scenario in scenarios_in:
                equivalent_scenario = TemplateData.ScenarioData.\
                    build_equivalent_scenario(scenario,
                                              symbol_name,
                                              entity_key)
                scenarios_out.append(equivalent_scenario)
        return scenarios_out

    def _add_scenario(self, scenario):
        for entity in scenario.entities.values():
            self._add_entity_scenario(scenario, entity)
        for relationship in scenario.relationships.values():
            self._add_relationship_scenario(scenario, relationship)

    def _load_templates_files(self, conf):

        templates_dir = conf.evaluator.templates_dir
        template_defs = file_utils.load_yaml_files(templates_dir)

        for template_def in template_defs:
            self.add_template(template_def)

    @staticmethod
    def _create_scenario_key(properties):
        return frozenset(properties)

    def _add_relationship_scenario(self, scenario, edge_desc):

        key = self._create_edge_scenario_key(edge_desc)
        self.relationship_scenarios[key].append((edge_desc, scenario))

    @staticmethod
    def _create_edge_scenario_key(edge_desc):
        return EdgeKeyScenario(edge_desc.edge.label,
                               frozenset(edge_desc.source.properties.items()),
                               frozenset(edge_desc.target.properties.items()))

    def _add_entity_scenario(self, scenario, entity):

        key = frozenset(list(entity.properties.items()))
        self.entity_scenarios[key].append((entity, scenario))


# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response
from django import forms #重点要导入,使用 Django 的 表单
from django.http import HttpResponse
import math
import numpy as np
import tensorflow as tf

def submission(request):
    return render(request, 'submission.html')

def help(request):
    return render(request, 'help.html')

def developers(request):
    return render(request, 'developers.html')

def home(request):
    return render(request, 'home.html')

def get_weight(shape):
    return tf.Variable(tf.random_normal(shape),dtype=tf.float32)

#初始化权值
def weight_variable(shape,name):
    initial = tf.truncated_normal(shape,stddev=0.1)#生成一个截断的正态分布
    return tf.Variable(initial,name=name) # 返回初始化的结果

#初始化偏置
def bias_variable(shape,name):
    initial = tf.constant(0.1,shape=shape)
    return tf.Variable(initial,name=name)

def conv2d(x,W):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

def conv3d(x,W):
    return tf.nn.conv3d(x,W,strides=[1,1,1,1,1],padding='SAME')

def max_pool_2(x):
    return tf.nn.max_pool(x,ksize=[1,5,1,1],strides=[1,5,1,1],padding='SAME')

def max_pool_3(x):
    return tf.nn.max_pool3d(x,ksize=[1,2,2,2,1],strides=[1,2,2,2,1],padding='SAME')

def model(xonehot,x343):
    with tf.name_scope('x_input1'):
        x_conv1 = tf.placeholder(tf.float32,[None,549*7],name='x_conv1')
        x_input1 = tf.reshape(x_conv1,[-1,549,1,7],name='x_input1')

    with tf.name_scope('x_input2'):
        x_conv2 = tf.placeholder(tf.float32,[None,7,7,7],name='x_conv2')
        x_input2 = tf.reshape(x_conv2,[-1,7,7,7,1],name='x_input2')

    with tf.name_scope('Conv11'):
        W_conv11 = weight_variable([3,1,7,7],name='W_conv11')
        b_conv11 = bias_variable([7],name='b_conv11')
        conv_11 = conv2d(x_input1,W_conv11)+b_conv11
        bn11 = tf.layers.batch_normalization(conv_11)
        relu11 = tf.nn.relu(bn11)
        h_pool11 = max_pool_2(relu11)

    with tf.name_scope('Conv12'):
        W_conv12 = weight_variable([5,1,7,7],name='W_conv12')
        b_conv12 = bias_variable([7],name='b_conv12')
        conv_12 = conv2d(h_pool11,W_conv12)+b_conv12
        bn12 = tf.layers.batch_normalization(conv_12)
        relu12 = tf.nn.relu(bn12)
        h_pool12 = max_pool_2(relu12)
        reshape1 = tf.reshape(h_pool12,[-1,22*7])

    with tf.name_scope('Conv21'):
        W_conv21 = weight_variable([1,1,1,1,1],name='W_conv21')
        b_conv21 = bias_variable([1],name='b_conv21')
        conv_21 = conv3d(x_input2,W_conv21)+b_conv21
        bn21 = tf.layers.batch_normalization(conv_21)
        relu21 = tf.nn.relu(bn21)

    with tf.name_scope('Conv22'):
        W_conv22 = weight_variable([3,3,3,1,1],name='W_conv22')
        b_conv22 = bias_variable([1],name='b_conv22')
        conv_22 = conv3d(relu21,W_conv22)+b_conv22
        bn22 = tf.layers.batch_normalization(conv_22)
        relu22 = tf.nn.relu(bn22)

    with tf.name_scope('Conv23'):
        W_conv23 = weight_variable([3,3,3,1,1],name='W_conv23')
        b_conv23 = bias_variable([1],name='b_conv23')
        conv_23 = conv3d(relu22,W_conv23)+b_conv23
        bn23 = tf.layers.batch_normalization(conv_23)
        relu23 = tf.nn.relu(bn23)
        add = tf.add(relu23,x_input2)
        reshape2 = tf.reshape(add,[-1,7*7*7])

    with tf.name_scope('concat'):
        flat = tf.concat([reshape1,reshape2],1,name='flat')

    with tf.name_scope('fc1'):
        with tf.name_scope('W_fc1'):
            W_fc1 = weight_variable([22*7+7*7*7,1024],name='W_fc1')#上一场有64个神经元，全连接层有1024个神经元
        with tf.name_scope('b_fc1'):
            b_fc1 = bias_variable([1024],name='b_fc1')#1024个节点
        with tf.name_scope('wx_plus_b1'):
            wx_plus_b1 = tf.matmul(flat,W_fc1) + b_fc1
        with tf.name_scope('relu1'):
            h_fc1 = tf.nn.relu(wx_plus_b1)   # 第一个全连接层的输出

    with tf.name_scope('keep_prob'):
        keep_prob = tf.placeholder(tf.float32,name='keep_prob')
    with tf.name_scope('h_fc1_drop'):
        h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob,name='h_fc1_drop')

    with tf.name_scope('fc2'):
        with tf.name_scope('W_fc2'):
            W_fc2 = weight_variable([1024,2],name='W_fc2')
        with tf.name_scope('b_fc2'):
            b_fc2 = bias_variable([2],name='b_fc2')
        with tf.name_scope('wx_plus_b2'):
            wx_plus_b2 = tf.matmul(h_fc1_drop,W_fc2) + b_fc2
        with tf.name_scope('softmax'):
            prediction = tf.nn.softmax(wx_plus_b2)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        model_file = tf.train.latest_checkpoint('D:/项目/python sourse code self/my_net/')
        tf.train.Saver().restore(sess,model_file)
        y_ = sess.run(prediction,feed_dict={x_conv1:xonehot,
											x_conv2:x343,
											keep_prob:0.5})
    return y_

def remove(x):
    x = x.replace(',','')
    x = x.replace("'",'')
    x = x.replace("\n",'')
    x = x.replace(' ','')
    x = x.replace('[','')
    x = x.replace(']','')
    return x

def process_onehot(x):
    data = []
    for line in x:
        line = str(line)
        line = remove(line)
        line = line.replace('0','0000000')
        line = line.replace('1','1000000')
        line = line.replace('2','0100000')
        line = line.replace('3','0010000')
        line = line.replace('4','0001000')
        line = line.replace('5','0000100')
        line = line.replace('6','0000010')
        line = line.replace('7','0000001')
        line = list(line)
        line = np.array(line,dtype=int)
        data.append(line)
    data = np.array(data)
    return data

def process_343(x):
    data = []
    for line in x:
        line = str(line)
        line = remove(line)
        length = len(line)
        time =np.zeros((7,7,7))
        for i in range(length - 2):
            time[int(line[i]) - int('1')][int(line[i + 1]) - int('1')][int(line[i + 2]) - int('1')] += 1
        mi = 10
        mx = 0
        for i in range(7):
            for j in range(7):
                for k in range(7):
                    if(time[i][j][k] < mi):
                        mi = time[i][j][k]
                    if(time[i][j][k] > mx):
                        mx = time[i][j][k]
        for i in range(7):
            for j in range(7):
                for k in range(7):
                    time[i][j][k] = (time[i][j][k] - mi) / mx
        data.append(time)
    data = np.array(data)
    return data

def process_data(file_name):
    data = []
    head = []
    with open(file_name, 'r') as f:
        for line in f:
            if line[0]!='>':
                line = line.strip('\n')
                line = line.replace('A','1')
                line = line.replace('G','1')
                line = line.replace('V','1')
                line = line.replace('I','2')
                line = line.replace('L','2')
                line = line.replace('F','2')
                line = line.replace('P','2')
                line = line.replace('Y','3')
                line = line.replace('M','3')
                line = line.replace('T','3')
                line = line.replace('S','3')
                line = line.replace('H','4')
                line = line.replace('N','4')
                line = line.replace('Q','4')
                line = line.replace('W','4')
                line = line.replace('R','5')
                line = line.replace('K','5')
                line = line.replace('D','6')
                line = line.replace('E','6')
                line = line.replace('C','7')
                data.append(list(line))
            else:
                head.append(line)
    f.close()
    x343 = process_343(data)
    avelength = 549
    for line in data:
        if len(line) >= avelength:
            data[data.index(line)] = line[0:avelength]
        else:
            new_line = line
            for _ in range(avelength-len(line)):
                new_line.append('0')
            data[data.index(line)] = new_line
    xonehot = process_onehot(data)
    return xonehot,x343,head

class UserForm(forms.Form):
    #title = forms.CharField(max_length=50)
    file = forms.FileField()

def handle_uploaded_file(f):
    file_name = 'some/file/temp.fasta'
    with open(file_name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    xonehot,x343,head = process_data(file_name)
    result = model(xonehot,x343)
    y_predict = np.argmax(result,1)
    data = []
    for i in range(len(y_predict)):
        if y_predict[i]==0:
            data.append(str(head[i])+'
'+'binding protein'+'
')
        else:
            data.append(str(head[i])+'
'+'non binding protein'+'
')
    return data

def register(request):
	if request.method == 'POST':
		uf = UserForm(request.POST, request.FILES)#uf为表单
		if uf.is_valid():
			result = handle_uploaded_file(request.FILES['file'])
			return HttpResponse(result)
	else:
		uf = UserForm()
	return render(request,'register.html', {'uf':uf})


# https://leetcode.com/problems/sentence-screen-fitting/

class Solution(object):
    def wordsTyping(self, sentence, rows, cols):
        """
        :type sentence: List[str]
        :type rows: int
        :type cols: int
        :rtype: int
        """
        s = " ".join(sentence) + " "
        l = len(s)
        start = 0
        for r in xrange(rows):
            start += cols
            # if we can fit to row without using extra space
            # increment start counter
            if s[start % l] == " ":
                start += 1
            else:
                # we cannot fit perfectly we might need to adjust
                # the new start position
                while start >= 0 and s[(start-1) % l] != " ":
                    start -= 1
        return start/l


import tkinter as tk
import subprocess

def create_ssh_tunnel(local_port, remote_port, remote_ip, key_file, dynamic):
  if dynamic:
    command = "ssh -i {} -D {} -N".format(key_file, local_port)
  else:
    command = "ssh -i {} -R {}:{}:{} -N".format(key_file, remote_port, remote_ip, local_port)
  subprocess.call(command.split())

def submit():
  local_port = local_port_entry.get()
  remote_port = remote_port_entry.get()
  remote_ip = remote_ip_entry.get()
  key_file = key_file_entry.get()
  dynamic = dynamic_checkbox.get()

  create_ssh_tunnel(local_port, remote_port, remote_ip, key_file, dynamic)

root = tk.Tk()
root.title("Tunnel SSH")

local_port_label = tk.Label(root, text="Port local:")
local_port_label.grid(row=0, column=0)
local_port_entry = tk.Entry(root)
local_port_entry.grid(row=0, column=1)

remote_port_label = tk.Label(root, text="Port de destination:")
remote_port_label.grid(row=1, column=0)
remote_port_entry = tk.Entry(root)
remote_port_entry.grid(row=1, column=1)

remote_ip_label = tk.Label(root, text="Adresse IP de destination:")
remote_ip_label.grid(row=2, column=0)
remote_ip_entry = tk.Entry(root)
remote_ip_entry.grid(row=2, column=1)

key_file_label = tk.Label(root, text="Chemin de la clé:")
key_file_label.grid(row=3, column=0)
key_file_entry = tk.Entry(root)
key_file_entry.grid(row=3, column=1)

dynamic_checkbox = tk.Checkbutton(root, text="Tunnel dynamique")
dynamic_checkbox.grid(row=4, column=0, columnspan=2)

submit_button = tk.Button(root, text="Envoyer", command=submit)
submit_button.grid(row=5, column=0, columnspan=2)

root.mainloop()


import cv2
import os

if __name__ == '__main__':
	root = 'training_images/'
	classes = ['appy', 'fanta', 'appyfizz', 'sprite']

	txt_files = os.listdir('labels')

	if '.DS_Store' in txt_files:
		txt_files.remove('.DS_Store')

	for file in txt_files:
		filename = file.split('.')[0] + '.jpg'
		print(filename)

		with open('labels/'+file, 'r') as f:
			arr = f.read().rstrip().split(" ")

			class_id = int(arr[0])
			x = int(float(arr[1])*320)
			y = int(float(arr[2])*320)
			w = int(float(arr[3])*320)
			h = int(float(arr[4])*320)
			img = cv2.imread(root + str(classes[class_id]) + '/' + filename)

			cv2.imwrite('cooldrinks/' +str(classes[class_id])+'/'+filename, img[y:y+h,x:x+w])

		# break


# Этот код пербирает текстовый файл с матами
# в файл формата json
# для последующей его обработки ботом.

import json

ar = []

with open('cenz.txt', 'r', encoding='utf-8') as r:
    for i in r:
        n = i.lower().split('\n')[0]
        if n != '':
            print(n)
            ar.append(n)

print(ar)

with open('cenz.json', 'w', encoding='utf-8') as e:
    json.dump(ar, e, ensure_ascii=False)

y = json.dumps(ar)
print('tr')
print(ar)


#For Files Sorting
import csv
import os
import json
import pandas as pd
#For API call
from time import sleep
import requests
#remove warning
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

##TAKING DATA FROM ALL JSON FILES TO OUTPUT INTO OUTPUT FILE
pathto = "jsonFiles\\"
steamApiKey = ""

def createNodes(json_files):
    mdata = pd.read_csv(pathto+'csvFiles\\Nodetemplate.csv')
    for f in json_files:
        #Loads Json API data to then deposit it all into a new file
        with open(pathto+f,"r") as json_fil:
            data = json.load(json_fil)
            if bool(data)==False:
                continue
            for i in range(len(data['friends'])):
                inse = data['friends'][i]['steamid']
                if inse not in mdata.values:
                    mdata = mdata.append({'Name':inse},ignore_index=True)
    print(mdata)
    mdata.to_csv(pathto+"csvFiles\outputNodes.csv")

    data = pd.read_csv(pathto+'csvFiles\outputNodes.csv')
    data.rename(columns={'Unnamed: 0':'ID'},inplace=True)
    data.to_csv(pathto+"csvFiles\outputNodes.csv",index=False)

def removeFL(jsonFileNs):
    for p in jsonFileNs:
        with open(pathto+p,"r+") as json_fil:
            data = json.load(json_fil)
            if "friendslist" in data:
                data.update(data.pop("friendslist"))
                for i in range(len(data['friends'])):
                    del data['friends'][i]['relationship']
                    del data['friends'][i]['friend_since']
                json_fil.truncate(0)
                json_fil.seek(0)
                #print("success")
                json_fil.write(json.dumps(data))

def APICall(sID):
    steamID = str(sID)

    sl1 = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key="
    sl2 = "&steamid=" + steamID + "&relationship=friend&format=json"
    slk = sl1 + steamApiKey + sl2
    r = requests.get(slk)

    steam = r.json()
    jFC = open(pathto+steamID+".json",'w')
    jFC.write(json.dumps(steam))
    jFC.close()

def createEdges(json_files):
    odata = pd.read_csv(pathto+'csvFiles\EdgesTemplate.csv')
    mdata = pd.read_csv(pathto+'csvFiles\outputNodes.csv', dtype=str,index_col=None)
    for f in json_files:
        with open(pathto+f,"r") as json_fil:
            data = json.load(json_fil)
            if bool(data)==False:
                continue
            source = mdata.loc[mdata['Name'] == f[:-5]].index[0]
            for i in range(len(data['friends'])):
                inse = data['friends'][i]['steamid']
                target = mdata.loc[mdata['Name'] == inse].index[0]
                odata = odata.append({'Source':source,'Target':target,'Type':'Undirected','Weight':1},ignore_index=True)
    odata.to_csv(pathto+"csvFiles\outputEdges.csv",index=False)

#Initial Indexing of folder
jFiles = [pos_json for pos_json in os.listdir(pathto) if pos_json.endswith(".json")]
#Starting Json File
jFile = input("Please Enter Valid Steam Id to search: ")
if jFile+'.json' not in jFiles:
    APICall(jFile)
removeFL([jFile+".json"])

#2nd indexing of folder after initial steam id is read
jFiles = [pos_json for pos_json in os.listdir(pathto) if pos_json.endswith(".json")]

#Calls all friends lists from base steamID to get 3 degrees of seperation
with open(pathto+jFile+'.json',"r") as json_fil:
    fridata = json.load(json_fil)
    for i in range(len(fridata['friends'])):
        if fridata['friends'][i]['steamid']+'.json' not in jFiles:
            APICall(fridata['friends'][i]['steamid'])
            sleep(0.02)

#last Indexing to send all JSON File names to function
jFile = [pos_json for pos_json in os.listdir(pathto) if pos_json.endswith(".json")]
removeFL(jFile)
createNodes(jFile)
createEdges(jFiles)


def read_list(f):
    return [int(x) for x in f.readline().split()]
def read_tuple(f):
    return tuple(read_list(f))

def load_single_case(f):
    _,n=read_tuple(f)
    return n,read_list(f)

def load_cases(path):
    with open(path) as f:
        n=int(f.readline())
        cases=[]
        for _ in xrange(n):
            cases.append(load_single_case(f))
    return cases

def get_served(t,mk):
    n=0
    for m in mk:
        n=n+t//m+1
    return n
def find_start(n,mk):
    k=1
    while get_served(k,mk)<n:
        k=k*2
    return k
def find_div(n,mk):
    k=find_start(n,mk)
    a,b=0,k
    while b-a>1:
        assert b>a
        c=(b+a)//2
        s=get_served(c,mk)
        if s>=n:
            b=c
        else:
            a=c
    return b
def find_server(b,n,mk):
    np=get_served(b-1,mk)
    assert np<n
    exs=n-np
    for i,m in enumerate(mk):
        if b%m==0:
            exs=exs-1
            if exs==0:
                return i
    assert False
def solve(case):
    n,mk=case
    if len(mk)>=n:
        return n
    b=find_div(n,mk)
    #print b, get_served(b-1,mk), get_served(b,mk)
    return find_server(b,n,mk)+1

def outcome_string(outcome):
    return "{}".format(outcome)

def save_outcomes(path, outcomes):
    with open(path,'w') as f:
        for n,o in enumerate(outcomes):
                f.write("Case #{0}: {1}\n".format( n+1 , outcome_string(o) ))
def process(path_in, path_out=None):
    if path_out==None:
        path_out=path_in.rsplit(".",1)[0]+".out"
    cases=load_cases(path_in)
    outcomes=[solve(c) for c in cases]
    save_outcomes(path_out, outcomes)


from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from werkzeug.utils import secure_filename
import os
from wtforms.validators import InputRequired
import tensorflow as tf
from keras.models import load_model
from keras_preprocessing import image
import numpy as np
from PIL import Image

model = load_model('model.h5')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'
app.config['UPLOAD_FOLDER'] = 'static/files'

class UploadFileForm(FlaskForm):
    file = FileField("File", validators=[InputRequired()])
    submit = SubmitField("Upload File")

@app.route('/', methods=['GET', "POST"])
@app.route('/home', methods=['GET', "POST"])
def home():
    form = UploadFileForm()
    if form.validate_on_submit():
        file = form.file.data
        file.save(os.path.join(os.path.abspath(os.path.dirname(__file__)), app.config['UPLOAD_FOLDER'], secure_filename(file.filename)))
        ipath = f'static/files/{file.filename}'
        img = image.load_img(ipath, target_size=(200, 200), color_mode='grayscale')
        img_tensor = image.img_to_array(img)
        img_tensor = np.expand_dims(img_tensor, axis=0)
        img_tensor /= 255.
        ff = model.predict(img_tensor)
        ff = max(ff).tolist()
        for i in range(len(ff)):
            ff[i] = ff[i] * 100
            ff[i] = round(ff[i], 2)
        ff = 'Cyst: ' + str(ff[0]) + '\n' + 'Normal: ' + str(ff[1]) + '\n' + 'Stone: ' + str(ff[2]) + '\n' + 'Tumor: ' + str(ff[3])
        os.remove(ipath)
        return str(ff)
    return render_template('index.html', form=form)
if __name__ == '__main__':
    app.run(debug=True)


import unittest
import ast
from xml.etree import ElementTree
import xmlnodegenerator

# The most up to date description of the AST is
# https://docs.python.org/3.6/library/ast.html

def createTree(source: str):
    tree = ast.parse(source)
    generator = xmlnodegenerator.XmlNodeGenerator(source)
    root = generator.visitModule(tree)
    return root

# Statements

class ClassDefinitionTest(unittest.TestCase):
    def testClassWithExtension(self):
        root = createTree('''class MyClass(object):
    def foo(self, arg: str):
        pass''')

        classDefinitionNode = root.find("Statements/Class[@Name='MyClass']")
        assert classDefinitionNode != None

        extension = classDefinitionNode.find("Bases/Name[@Id='object']")
        assert extension != None

    def testClassNoExtension(self):
        root = createTree('''class MyClass:
    def foo():
        pass''')

        classDefinitionNode = root.find("Statements/Class[@Name='MyClass']")
        assert classDefinitionNode != None

        extension = root.find("Statements/Class/Bases/*")
        assert extension is None

    def testClassWithAttributedExtension(self):
        root = createTree('''class FuncCallVisitor(ast.NodeVisitor):
    def foo():
        pass''')

        classDefinitionNode = root.find("Statements/Class[@Name='FuncCallVisitor']")
        assert classDefinitionNode != None

        extension = classDefinitionNode.find("Bases/Attribute[@Id='NodeVisitor']/Name[@Id='ast']")
        assert extension != None

    def testClassWithComments(self):
        root = createTree('''class Bar:
    'This is a comment'
    def foo():
        pass''')

        classDefinitionNode = root.find("Statements/Class[@Name='Bar']")
        assert classDefinitionNode != None

        classDefinitionNode = root.find("Statements/Class[@Comment='This is a comment']")
        assert classDefinitionNode != None

class FunctionDefTest(unittest.TestCase):
    def testFunctionDefNoArgs(self):
        root = createTree('''def foo(): pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Arguments")
        assert functionDefinitionNode != None

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Arguments/*")
        assert functionDefinitionNode is None

    def testFunctionDefWithComment(self):
        root = createTree('''
def foo():
    'Interesting function'
    pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Comment='Interesting function']")
        assert functionDefinitionNode != None

    def testFunctionDefSimpleArgs(self):
        root =  createTree('''def foo(self, banana): pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        argumentNode = argumentsNode.find("Argument[@Name='self']")
        assert argumentNode != None

        argumentNode = argumentsNode.find("Argument[@Name='banana']")
        assert argumentNode != None

    def testFunctionDefNoArgsWithReturn(self):
        root = createTree('''def foo() ->None: pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Arguments")
        assert functionDefinitionNode != None

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Arguments/*")
        assert functionDefinitionNode is None

        # The return annotation is 'None'
        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Returns/NameConstant[@Name='None']")
        assert functionDefinitionNode != None

    def testFunctionDefDefaultArgs(self):
        root =  createTree('''def foo(self, banana=1, orange=""): pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        argumentNode = argumentsNode.find("Argument[@Name='self']")
        assert argumentNode != None

        argumentNode = argumentsNode.find("Argument[@Name='banana']/NumberLiteral[@Value='1']")
        assert argumentNode != None

        argumentNode = argumentsNode.find("Argument[@Name='orange']/StringLiteral[@Value='']")
        assert argumentNode != None

    def testFunctionDefStarredArgs(self):
        root =  createTree('''def foo(self, *arg1, **arg2): pass''')
        # In this syntax, the *arg means that all the positional parameters should
        # be passed as a list, while the **args causes the keyword parameters to be
        # collected in a dictionary (in the args2 parameter).

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        argumentNode = argumentsNode.find("Argument[@Name='self']")
        assert argumentNode != None

        argumentNode = argumentsNode.find("Vararg/Argument[@Name='arg1']")
        assert argumentNode != None

        argumentNode = argumentsNode.find("KeywordArg/Argument[@Name='arg2']")
        assert argumentNode != None

    def testFunctionDefAnnotatedArgs(self):
        root = createTree('''def foo(self: int, banana: str) -> str: pass''')

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        argumentNode = argumentsNode.find("Argument[@Name='self']")
        assert argumentNode != None
        parameterAnnotationNode = argumentNode.find("Annotation")
        assert parameterAnnotationNode != None

        argumentNode = argumentsNode.find("Argument[@Name='banana']")
        assert argumentNode != None
        parameterAnnotationNode = argumentNode.find("Annotation")
        assert parameterAnnotationNode != None

        functionDefinitionNode = root.find("Statements/FunctionDefinition[@Name='foo']/Returns/Name[@Id='str']")
        assert functionDefinitionNode != None

    def testAsyncFunctionDefWithPredefReturnNone(self):
        root = createTree('''async def foo() -> None: pass''')

        functionDefinitionNode = root.find("Statements/AsyncFunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        functionDefinitionNode = root.find("Statements/AsyncFunctionDefinition[@Name='foo']/Returns/NameConstant[@Name='None']")
        assert functionDefinitionNode != None

    def testAsyncFunctionDefWithPredefReturnStr(self):
        root = createTree('''async def foo() -> str: pass''')

        functionDefinitionNode = root.find("Statements/AsyncFunctionDefinition[@Name='foo']")
        assert functionDefinitionNode != None

        # There are no parameters:
        argumentsNode = functionDefinitionNode.find("Arguments")
        assert argumentsNode != None

        functionDefinitionNode = root.find("Statements/AsyncFunctionDefinition[@Name='foo']/Returns/Name[@Id='str']")
        assert functionDefinitionNode != None

class ImportTest(unittest.TestCase):
    def runTest(self):
        source = "import ast"
        root = createTree(source)

        # Check that the tree contains the a Module element.
        assert root.tag == 'Module'

        importNode = root.find("Statements/Import")

        assert importNode != None
        # assert s == source

class ImportFromTest(unittest.TestCase):
    def testSimpleImportFrom(self):
        root = createTree("from MyModule import Banana")

        importFromNode = root.find("Statements/ImportFrom[@Module='MyModule']")
        assert importFromNode != None

        namesNode = importFromNode.find("Names/Name[@Id='Banana']")
        assert namesNode != None

    def testMultipleImportFrom(self):
        root = createTree("from MyModule import Banana as b, Orange as s")

        importFromNode = root.find("Statements/ImportFrom[@Module='MyModule']")
        assert importFromNode != None

        namesNode = importFromNode.find("Names/Name[@Id='Banana']")
        assert namesNode != None

        namesNode = importFromNode.find("Names/Name[@AsName='b']")
        assert namesNode != None

        namesNode = importFromNode.find("Names/Name[@Id='Orange']")
        assert namesNode != None

        namesNode = importFromNode.find("Names/Name[@AsName='s']")
        assert namesNode != None

    def testImportFromAll(self):
        root = createTree("from MyModule import *")

        importFromNode = root.find("Statements/ImportFrom[@Module='MyModule']")
        assert importFromNode != None

        namesNode = importFromNode.find("Names/Name[@Id='*']")
        assert namesNode != None

    def testImportWithParentDirSpec(self):
        root = createTree("from .. import Banana")
        assert root != None

        node = root.find("Statements/ImportFrom/Names/Name[@Id='Banana']")
        assert node != None

class WhileTest(unittest.TestCase):
    def testSimpleWhile(self):
        root = createTree("while 1: pass")

        whileStatement = root.find("Statements/While")
        assert whileStatement

        testNode = whileStatement.find("NumberLiteral")
        assert testNode != None

        bodyNode = root.find("Statements/While/Statements[1]/Pass")
        assert bodyNode != None

        orelseNode = root.find("Statements/While/Statements[2]/*")
        assert orelseNode is None

    def testWhileWithOrElse(self):
        root = createTree('''while 1:
    pass
else: return''')

        whileStatement = root.find("Statements/While")
        assert whileStatement

        testNode = whileStatement.find("NumberLiteral")
        assert testNode != None

        bodyNode = root.find("Statements/While/Statements[1]/Pass")
        assert bodyNode != None

        orelseNode = root.find("Statements/While/Statements[2]/Return")
        assert orelseNode != None

class ForTest(unittest.TestCase):
    def testSimpleFor(self):
        root = createTree("for i in foo(10, banana=4): pass")

        forStatement = root.find("Statements/For")
        assert forStatement

        # TODO check the name (i in this case)
        # TODO Check the expression

        bodyNode = forStatement.find("Statements[1]/Pass")
        assert bodyNode != None

        orelseNode = forStatement.find("Statements[2]/*")
        assert orelseNode is None

    def testAsyncFor(self):
        root = createTree('''async def f():
    async for i in foo(10, banana=4):
        pass''')

        forStatement = root.find("Statements/AsyncFunctionDefinition/Statements/AsyncFor")
        assert forStatement

        bodyNode = forStatement.find("Statements/Pass")
        assert bodyNode != None

        orelseNode = forStatement.find("Statements[2]/*")
        assert orelseNode is None

class TryExceptionTest(unittest.TestCase):
    def testTryExceptionSingle(self):
        root = createTree('''try:
    return 1
except IOError:
    return 2''')

        node = root.find("Statements/TryExcept/Statements/Return/NumberLiteral[@Value='1']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Statements/Return/NumberLiteral[@Value='2']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Name[@Id='IOError']")
        assert node != None

    def testTryExceptionSingleWithAlias(self):
        root = createTree('''try:
    return 1
except IOError as name:
    return 2''')

        node = root.find("Statements/TryExcept/Handler[@Alias='name']")
        assert node != None

    def testTryExceptionMultiple(self):
        root = createTree('''try:
    return 1
except (IOError, ValueError):
    return 2''')

        node = root.find("Statements/TryExcept/Statements/Return/NumberLiteral[@Value='1']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Statements/Return/NumberLiteral[@Value='2']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Tuple/Name[@Id='IOError']")
        assert node != None
        node = root.find("Statements/TryExcept/Handler/Tuple/Name[@Id='ValueError']")
        assert node != None

    def testTryExceptionWithCatchAll(self):
        root = createTree('''try:
    return 1
except:
    return 2''')

        node = root.find("Statements/TryExcept/Statements/Return/NumberLiteral[@Value='1']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Statements/Return/NumberLiteral[@Value='2']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Name")
        assert node is None

    def testTryExceptionWithElse(self):
        root = createTree('''try:
    return 1
except:
    return 2
else:
    return 3''')

        node = root.find("Statements/TryExcept/Statements[1]/Return/NumberLiteral[@Value='1']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Name")
        assert node is None

        node = root.find("Statements/TryExcept/Handler/Statements/Return/NumberLiteral[@Value='2']")
        assert node != None

        node = root.find("Statements/TryExcept/Statements[2]/Return/NumberLiteral[@Value='3']")
        assert node != None

    def testTryExceptionElseAndFinally(self):
        root = createTree('''try:
    return 1
except:
    return 2
else:
    return 3
finally:
    return 4''')

        node = root.find("Statements/TryExcept/Statements[1]/Return/NumberLiteral[@Value='1']")
        assert node != None

        node = root.find("Statements/TryExcept/Handler/Name")
        assert node is None

        node = root.find("Statements/TryExcept/Handler/Statements/Return/NumberLiteral[@Value='2']")
        assert node != None

        node = root.find("Statements/TryExcept/Statements[2]/Return/NumberLiteral[@Value='3']")
        assert node != None

        node = root.find("Statements/TryExcept/Statements[3]/Return/NumberLiteral[@Value='4']")
        assert node != None

class RaiseTest(unittest.TestCase):
    def testRaiseWithoutArguments(self):
        root = createTree("raise")

        node = root.find("Statements/Raise")
        assert node != None

    def testRaiseWithSingleArgument(self):
        root = createTree("raise IOError()")

        node = root.find("Statements/Raise/Call")
        assert node != None

    def testRaiseWithTwoArguments(self):
        root = createTree("raise IOError from original")

        node = root.find("Statements/Raise")
        assert node != None

class ReturnTests(unittest.TestCase):
    def testReturnNoValue(self):
        root = createTree("return")

        # Check that the tree contains the a Return element.
        assert root.findall("Statements/Return")

        # ... without any subtree for the expression
        assert not root.findall("Statements/Return/*")

    def testReturnWithValue(self):
        root = createTree("return 1")

        # Check that the tree contains the a Return element.
        returnNode = root.find("Statements/Return")
        assert returnNode != None

        # ... with a subtree for the expression
        returnNodeWithSubtree = root.findall("Statements/Return/NumberLiteral[@Value='1']")
        assert returnNodeWithSubtree != None

class PassTest(unittest.TestCase):
    def runTest(self):
        root = createTree("pass")

        passNode = root.find("Statements/Pass")
        assert passNode != None

class BreakTest(unittest.TestCase):
    def runTest(self):
        root = createTree("break")

        node = root.find("Statements/Break")
        assert node != None

class ContinueTest(unittest.TestCase):
    def runTest(self):
        root = createTree("continue")

        # Check that the tree contains the a Return element.
        node = root.find("Statements/Continue")
        assert node != None

class WithTest(unittest.TestCase):
    def testWithSimple(self):
        root = createTree('''with open("x.txt") as f: pass''')

        node = root.find("Statements/With")
        assert node != None

        node = root.find("Statements/With/Item/Name[@Id='f']")
        assert node != None

        node = root.find("Statements/With/Item/Call/Name[@Id='open']")
        assert node != None

        node = root.find("Statements/With/Statements/Pass")
        assert node != None

    def testWithAsync(self):
        root = createTree('''async def foo():
    async with open("x.txt") as f:
        pass''')

        withNode = root.find("Statements/AsyncFunctionDefinition/Statements/AsyncWith")
        assert withNode != None

        node = withNode.find("Item/Name[@Id='f']")
        assert node != None

        node = withNode.find("Item/Call/Name[@Id='open']")
        assert node != None

        node = withNode.find("Statements/Pass")
        assert node != None

class IfTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''if 1:
    return 10
else:
    return 20''')

        assert root.find("Statements/If")

        ifPart = root.find("Statements/If/Statements/Return/NumberLiteral[@Value='10']")
        elsePart = root.find("Statements/If/Statements/Return/NumberLiteral[@Value='20']")

        # ... with a subtree for the expression
        assert ifPart != None, "If part was not found"
        assert elsePart != None, "Else part not found"

class AssertTest(unittest.TestCase):
    def testAssertSimple(self):
        root = createTree("assert a is None")

        node = root.find("Statements/Assert/Is")
        assert node != None

    def testAssertWithExplanation(self):
        root = createTree('''assert a is None, "a should not be empty"''')

        node = root.find("Statements/Assert/Is")
        assert node != None

        node = root.find("Statements/Assert/StringLiteral")
        assert node != None

class AssignTest(unittest.TestCase):
    def testAssignSimple(self):
        root = createTree("a = 3")

        node = root.find("Statements/Assign/NumberLiteral[@Value='3']")
        assert node != None

    def testAssignMultiple(self):
        root = createTree("[a, b] = 3, 4")

        node = root.find("Statements/Assign/List/Name[@Id='a']")
        assert node != None
        node = root.find("Statements/Assign/List/Name[@Id='b']")
        assert node != None

        node = root.find("Statements/Assign/Tuple/NumberLiteral[@Value='3']")
        assert node != None

        node = root.find("Statements/Assign/Tuple/NumberLiteral[@Value='4']")
        assert node != None

    def testAugmentedAssignPlus(self):
        root = createTree("a += 3")

        node = root.find("Statements/AugmentedAssign[@op='Plus']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMinus(self):
        root = createTree("a -= 3")

        node = root.find("Statements/AugmentedAssign[@op='Minus']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMultiply(self):
        root = createTree("a *= 3")

        node = root.find("Statements/AugmentedAssign[@op='Multiply']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignDivide(self):
        root = createTree("a /= 3")

        node = root.find("Statements/AugmentedAssign[@op='Divide']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a %= 3")

        node = root.find("Statements/AugmentedAssign[@op='Mod']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a **= 3")

        node = root.find("Statements/AugmentedAssign[@op='Power']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a <<= 3")

        node = root.find("Statements/AugmentedAssign[@op='LeftShift']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a >>= 3")

        node = root.find("Statements/AugmentedAssign[@op='RightShift']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a &= 3")

        node = root.find("Statements/AugmentedAssign[@op='And']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a %= 3")

        node = root.find("Statements/AugmentedAssign[@op='Mod']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignMod(self):
        root = createTree("a ^= 3")

        node = root.find("Statements/AugmentedAssign[@op='Xor']/NumberLiteral[@Value='3']")
        assert node != None

    def testAugmentedAssignFloorDiv(self):
        root = createTree("a //= 3")

        node = root.find("Statements/AugmentedAssign[@op='FloorDiv']/NumberLiteral[@Value='3']")
        assert node != None

    def testAnnotatedAssignment(self): # TODO
        root = createTree("v: int = 44")
        assert root != None

        node = root.find("Statements/AnnotatedAssign")
        assert node != None

        node = root.find("Statements/AnnotatedAssign[@Simple='1']")
        assert node != None

        node = root.find("Statements/AnnotatedAssign/*[1][@Id='v']")
        assert node != None

        node = root.find("Statements/AnnotatedAssign/*[2][@Id='int']")
        assert node != None

        node = root.find("Statements/AnnotatedAssign/NumberLiteral[@Value='44']")
        assert node != None

class DelTest(unittest.TestCase):
    def testDel(self):
        root = createTree("del a")

        node = root.find("Statements/Del/Name[@Id='a']")
        assert node != None

class ScopeTest(unittest.TestCase):
    def testGlobal(self):
        root = createTree("global a,b")
        assert root != None, "Unable to parse the global statement"

        node = root.find("Statements/Global")
        assert node != None, "Did not find global statement"

        # Check the Identifier children
        node = root.find("Statements/Global/Identifier[@Name='a']")
        assert node != None, "Did not find first global identifier"

        node = root.find("Statements/Global/Identifier[@Name='b']")
        assert node != None, "Did not find second global identifier"

    def testNonlocal(self):
        root = createTree("nonlocal a,b")
        assert root != None, "Unable to parse the nonlocal statement"

        node = root.find("Statements/Nonlocal")
        assert node != None, "Did not find nonlocal statement"

        # Check the Identifier children
        node = root.find("Statements/Nonlocal/Identifier[@Name='a']")
        assert node != None, "Did not find first nonlocal identifier"

        node = root.find("Statements/Nonlocal/Identifier[@Name='b']")
        assert node != None, "Did not find second nonlocal identifier"

# Expression tests
class LiteralTest(unittest.TestCase):
    def testJoinedStr(self):
        root = createTree('''f"{1}{2}"''')
        assert root != None, "No joined string found"

        node = root.find("Statements/ExpressionStatement/JoinedStr")
        assert node != None, "Tree does not contain joined string"

        node = root.find("Statements/ExpressionStatement/JoinedStr/FormattedValue/NumberLiteral[@Value='1']")
        assert node != None, "First number literal not found"
        node = root.find("Statements/ExpressionStatement/JoinedStr/FormattedValue/NumberLiteral[@Value='2']")
        assert node != None, "Second number literal not found"

class AddTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''1 + 2''')

        node = root.find("Statements/ExpressionStatement/Add")
        assert node != None, "No add node found"

class SubtractTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''1 - 2''')

        node = root.find("Statements/ExpressionStatement/Subtract")
        assert node != None, "No subtract node found"

class MultiplyTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''1 * 2''')

        node = root.find("Statements/ExpressionStatement/Multiply")
        assert node != None, "No multiply node found"

class DivideTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''1 / 2''')

        node = root.find("Statements/ExpressionStatement/Divide")
        assert node != None, "No divide node found"

class FloorDivideTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''1 // 2''')

        node = root.find("Statements/ExpressionStatement/FloorDivide")
        assert node != None, "No floor divide node found"

class PowerTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 ** 3''')

        node = root.find("Statements/ExpressionStatement/Power")
        assert node != None, "No power node found"

class BitAndTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 & 3''')

        node = root.find("Statements/ExpressionStatement/BitwiseAnd")
        assert node != None, "No bitwise and node found"

class BitOrTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 | 3''')

        node = root.find("Statements/ExpressionStatement/BitwiseOr")
        assert node != None, "No bitwise or node found"

class BitXorTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 ^ 3''')

        node = root.find("Statements/ExpressionStatement/BitwiseXor")
        assert node != None, "No bitwise xor node found"

class BitLeftShiftTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 << 3''')

        node = root.find("Statements/ExpressionStatement/LeftShift")
        assert node != None, "No left shift node found"

class BitRightShiftTest(unittest.TestCase):
    def runTest(self):
        root = createTree('''2 >> 3''')

        node = root.find("Statements/ExpressionStatement/RightShift")
        assert node != None, "No right shift node found"

class MonadicOperatorTests(unittest.TestCase):
    def testMonadicMinus(self):
        root = createTree('''-1''')

        node = root.find("Statements/ExpressionStatement/MonadicMinus")
        assert node != None, "No monadic minus node found"

    def testMonadicPlus(self):
        root = createTree('''+1''')

        node = root.find("Statements/ExpressionStatement/MonadicPlus")
        assert node != None, "No monadic plus node found"

    def testMonadicInvert(self):
        root = createTree('''~1''')

        node = root.find("Statements/ExpressionStatement/Invert")
        assert node != None, "No monadic invert (~) node found"

    def testMonadicNot(self):
        root = createTree('''not True''')

        node = root.find("Statements/ExpressionStatement/Not")
        assert node != None, "No monadic not node found"

class LogicalOperatorTests(unittest.TestCase):
    def testAndOperator(self):
        root = createTree('''1 and 2''')

        node = root.find("Statements/ExpressionStatement/And")
        assert node != None

    def testOrOperator(self):
        root = createTree('''1 or 2''')

        node = root.find("Statements/ExpressionStatement/Or")
        assert node != None

class RelationalOperatorTests(unittest.TestCase):
    def testRelationalEquals(self):
        root = createTree('''1 == 2''')

        node = root.find("Statements/ExpressionStatement/Equals/NumberLiteral[@Value='1']")
        assert node != None, "Left node of == node not found"

        node = root.find("Statements/ExpressionStatement/Equals/NumberLiteral[@Value='2']")
        assert node != None, "Right node of == node not found"

    def testRelationalNotEquals(self):
        root = createTree('''1 != 2''')

        node = root.find("Statements/ExpressionStatement/NotEquals/NumberLiteral[@Value='1']")
        assert node != None, "Left node of != node not found"

        node = root.find("Statements/ExpressionStatement/NotEquals/NumberLiteral[@Value='2']")
        assert node != None, "Right node of != node not found"

    def testRelationalGreaterThan(self):
        root = createTree('''1 > 2''')

        node = root.find("Statements/ExpressionStatement/GreaterThan/NumberLiteral[@Value='1']")
        assert node != None, "Left node of > node not found"

        node = root.find("Statements/ExpressionStatement/GreaterThan/NumberLiteral[@Value='2']")
        assert node != None, "Right node of > node not found"

    def testRelationalGreaterOrEqual(self):
        root = createTree('''1 >= 2''')

        node = root.find("Statements/ExpressionStatement/GreaterThanOrEqual/NumberLiteral[@Value='1']")
        assert node != None, "Left node of >= node not found"

        node = root.find("Statements/ExpressionStatement/GreaterThanOrEqual/NumberLiteral[@Value='2']")
        assert node != None, "Right node of >= node not found"

    def testRelationalLessThan(self):
        root = createTree('''1 < 2''')

        node = root.find("Statements/ExpressionStatement/LessThan/NumberLiteral[@Value='1']")
        assert node != None, "Left node of < node not found"

        node = root.find("Statements/ExpressionStatement/LessThan/NumberLiteral[@Value='2']")
        assert node != None, "Right node of < node not found"

    def testRelationalLessThanOrEqual(self):
        root = createTree('''1 <= 2''')

        node = root.find("Statements/ExpressionStatement/LessThanOrEqual/NumberLiteral[@Value='1']")
        assert node != None, "Left node of <= node not found"

        node = root.find("Statements/ExpressionStatement/LessThanOrEqual/NumberLiteral[@Value='2']")
        assert node != None, "Right node of <= node not found"

    def testRelationalBetween(self):
        root = createTree('''1 < x < 2''')

        node = root.find("Statements/ExpressionStatement/LessThan/NumberLiteral[@Value='1']")
        assert node != None, "Left node of < node not found"

        node = root.find("Statements/ExpressionStatement/LessThan/LessThan/Name[@Id='x']")
        assert node != None, "Right node of < node not found"

        node = root.find("Statements/ExpressionStatement/LessThan/LessThan/NumberLiteral[@Value='2']")
        assert node != None, "Right node of < node not found"

class TernaryIfExpressionTests(unittest.TestCase):
    def testIfExpression(self):
        root = createTree("a if condition else b")

        node = root.find("Statements/ExpressionStatement/Conditional")
        assert node != None
        assert len(node) == 3

        node = root.find("Statements/ExpressionStatement/Conditional/Name[@Id='a']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Conditional/Name[@Id='condition']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Conditional/Name[@Id='b']")
        assert node != None

class CallTest(unittest.TestCase):
    def testCallDefaultAndPositionalArg(self):
        root = createTree("foo(1,3,5, sep='.', end='<', flush=True)")

        printNode = root.find("Statements/ExpressionStatement/Call/Name[@Id='foo']")
        assert printNode != None

        positionalParameters = root.findall('Statements/ExpressionStatement/Call/PositionalArgument')
        assert len(positionalParameters) == 3

        keywordParameters = root.findall('Statements/ExpressionStatement/Call/KeywordArgument')
        assert len(keywordParameters) == 3

    def testCallWithAttribute(self):
        root = createTree("compile(ast.PyCF_ONLY_AST)")

        attr = root.find("Statements/ExpressionStatement/Call/PositionalArgument/Attribute[@Id='PyCF_ONLY_AST']")
        assert attr != None

        name = attr.find("Name[@Id='ast']")
        assert name != None

    def testCallWithParameterLists(self):
        root = createTree("Foo(*args, **kwargs)")

        call = root.find("Statements/ExpressionStatement/Call");
        assert call != None

        positional = call.find("PositionalArgument/Starred/Name[@Id='args']")
        assert positional != None

        keyword = call.find("KeywordArgument/Name[@Id='kwargs']")
        assert keyword != None

class SliceTest(unittest.TestCase):
    def testSliceNone(self):
        root = createTree("a[:]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/*")
        assert node is None

        node = slice.find("Upper/*")
        assert node is None

        node = slice.find("Step/*")
        assert node is None

    def testSliceOnlyLower(self):
        root = createTree("a[1:]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/NumberLiteral[@Value='1']")
        assert node != None

        node = slice.find("Upper/*")
        assert node is None

        node = slice.find("Step/*")
        assert node is None

    def testSliceOnlyUpper(self):
        root = createTree("a[:10]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/*")
        assert node is None

        node = slice.find("Upper/NumberLiteral[@Value='10']")
        assert node != None

        node = slice.find("Step/*")
        assert node is None

    def testSliceLowerAndUpper(self):
        root = createTree("a[1:10]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/NumberLiteral[@Value='1']")
        assert node != None

        node = slice.find("Upper/NumberLiteral[@Value='10']")
        assert node != None

        node = slice.find("Step/*")
        assert node is None

    def testSliceNoneWithStep(self):
        root = createTree("a[::1]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/*")
        assert node is None

        node = slice.find("Upper/*")
        assert node is None

        node = slice.find("Step/NumberLiteral[@Value='1']")
        assert node != None

    def testSliceOnlyLowerWithStep(self):
        root = createTree("a[1::1]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/NumberLiteral[@Value='1']")
        assert node != None

        node = slice.find("Upper/*")
        assert node is None

        node = slice.find("Step/NumberLiteral[@Value='1']")
        assert node != None

    def testSliceOnlyUpperWithStep(self):
        root = createTree("a[:10:1]")
        assert root != None

        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/*")
        assert node is None

        node = slice.find("Upper/NumberLiteral[@Value='10']")
        assert node != None

        node = slice.find("Step/NumberLiteral[@Value='1']")
        assert node != None

    def testSliceLowerAndUpperWithStep(self):
        root = createTree("a[1:10:1]")
        assert root != None
        slice = root.find("Statements/ExpressionStatement/Subscript/Slice")
        assert slice != None

        node = slice.find("Lower/NumberLiteral[@Value='1']")
        assert node != None

        node = slice.find("Upper/NumberLiteral[@Value='10']")
        assert node != None

        node = slice.find("Step/NumberLiteral[@Value='1']")
        assert node != None

class StarTest(unittest.TestCase):
    def testStar(self):
        root = createTree("a, *b = (1, 2, 3)")
        assert root != None

        assign = root.find("Statements/Assign")
        assert assign != None

        a = assign.find("Tuple/Name[@Id='a']")
        assert a != None

        b = assign.find("Tuple/Starred/Name[@Id='b']")
        assert b != None

class ComprehensionTests(unittest.TestCase):
    def _checkComprehension(self, comprehension):
        name = comprehension.find("Name[@Id='x']")
        assert name != None

        function = comprehension.find("Call/Name[@Id='range']")
        assert function != None

        assert comprehension.find("Equals/NumberLiteral[@Value='0']") != None

    def testListComprehension(self):
        root = createTree("[x for x in range(10) if x % 2 == 0]")

        listComprehension = root.find("Statements/ExpressionStatement/ListComprehension")
        assert listComprehension != None

        name = listComprehension.find("Name[@Id='x']")
        assert name != None

        comprehension = listComprehension.find("Comprehension")
        assert comprehension != None

        self._checkComprehension(comprehension)

    def testSetComprehension(self):
        root = createTree("{x for x in range(10) if x % 2 == 0}")

        setComprehension = root.find("Statements/ExpressionStatement/SetComprehension")
        assert setComprehension != None

        name = setComprehension.find("Name[@Id='x']")
        assert name != None

        comprehension = setComprehension.find("Comprehension")
        assert comprehension != None

        self._checkComprehension(comprehension)

    def testDictComprehension(self):
        root = createTree("{x : chr(65+x) for x in range(10) if x % 2 == 0}")

        dictComprehension = root.find("Statements/ExpressionStatement/DictComprehension")
        assert dictComprehension != None

        name = dictComprehension.find("Name[@Id='x']")
        assert name != None

        comprehension = dictComprehension.find("Comprehension")
        assert comprehension != None

        self._checkComprehension(comprehension)

    def testGenerator(self):
        root = createTree("(x for x in range(10) if x % 2 == 0)")

        generator = root.find("Statements/ExpressionStatement/Generator")
        assert generator != None

        name = generator.find("Name[@Id='x']")
        assert name != None

        comprehension = generator.find("Comprehension")
        assert comprehension != None

        self._checkComprehension(comprehension)

class YieldTests(unittest.TestCase):
    def testYield(self):
        root = createTree("yield 1")
        assert root != None

        node = root.find("Statements/ExpressionStatement/Yield/NumberLiteral[@Value='1']")
        assert node != None

    def testYieldFrom(self):
        root = createTree("yield from generator()")
        assert root != None

        node = root.find("Statements/ExpressionStatement/YieldFrom/Call/Name[@Id='generator']")
        assert node != None

    def testAwait(self):
        root = createTree('''async def ping_local():
    return await ping_server('192.168.1.1')''')
        assert root != None

        node = root.find("Statements/AsyncFunctionDefinition/Statements/Return/Await/Call/Name[@Id='ping_server']")
        assert node != None

class NameConstantTests(unittest.TestCase):
    def testNoneConstant(self):
        root = createTree("None")

        node = root.find("Statements/ExpressionStatement/NameConstant[@Name='None']")
        assert root != None

    def testTrueConstant(self):
        root = createTree("True")

        node = root.find("Statements/ExpressionStatement/NameConstant[@Name='True']")
        assert root != None

    def testFalseConstant(self):
        root = createTree("False")

        node = root.find("Statements/ExpressionStatement/NameConstant[@Name='False']")
        assert root != None

class ListTests(unittest.TestCase):
    def testEmptyList(self):
        root = createTree("[]")

        node = root.find("Statements/ExpressionStatement/List")
        assert node != None

        node = root.find("Statements/ExpressionStatement/List/*")
        assert node is None

    def testNonEmptyList(self):
        root = createTree("[1, 2, 3]")

        node = root.find("Statements/ExpressionStatement/List/NumberLiteral[@Value='1']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/List/NumberLiteral[@Value='2']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/List/NumberLiteral[@Value='3']")
        assert node != None

class SetTests(unittest.TestCase):

    # Note that {} designates an empty dict, not an empty set.

    def testNonEmptySet(self):
        root = createTree("{1, 2, 3}")

        node = root.find("Statements/ExpressionStatement/Set/NumberLiteral[@Value='1']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Set/NumberLiteral[@Value='2']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Set/NumberLiteral[@Value='3']")
        assert node != None

class DictTests(unittest.TestCase):
    def testEmptyDict(self):
        root = createTree("{}")

        node = root.find("Statements/ExpressionStatement/Dict")
        assert node != None

        node = root.find("Statements/ExpressionStatement/Dict/*")
        assert node is None

    def testNonEmptyDict(self):
        root = createTree("{'one': 1, 'two': 2, 'three': 3}")

        node = root.find("Statements/ExpressionStatement/Dict/DictElement/StringLiteral[@Value='one']../NumberLiteral[@Value='1']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Dict/DictElement/StringLiteral[@Value='two']../NumberLiteral[@Value='2']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Dict/DictElement/StringLiteral[@Value='three']../NumberLiteral[@Value='3']")
        assert node != None

class TupleTests(unittest.TestCase):
    def testEmptyTuple(self):
        root = createTree("()")

        node = root.find("Statements/ExpressionStatement/Tuple")
        assert node != None

        node = root.find("Statements/ExpressionStatement/Tuple/*")
        assert node is None

    def testNonEmptyTuple(self):
        root = createTree("(1, 'one')")

        node = root.find("Statements/ExpressionStatement/Tuple/StringLiteral[@Value='one']../NumberLiteral[@Value='1']")
        assert node != None
        node = root.find("Statements/ExpressionStatement/Tuple/NumberLiteral[@Value='1']")
        assert node != None

class LambdaTests(unittest.TestCase):
    def testLambdaWithArgs(self):
        root = createTree("lambda x: x + 2")
        assert root != None

        lambdaNode = root.find("Statements/ExpressionStatement/Lambda")
        assert lambdaNode != None

        arg = lambdaNode.find("Arguments/Argument[@Name='x']")
        assert arg != None

        body = lambdaNode.find("Add")
        assert body != None

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


import librosa, librosa.display
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import euclidean
from sklearn.metrics.pairwise import euclidean_distances
from numpy import genfromtxt

def oti_func(original_features, cover_features):
    profile1 = np.sum(original_features.T, axis = 1)
    profile2 = np.sum(cover_features.T, axis = 1)
    oti = [0] * 12
    for i in range(profile2.shape[0]):
        oti[i] = np.dot(profile1, np.roll(profile2, i))
    oti.sort(reverse=True)
    newmusic = np.roll(cover_features.T, int(oti[0]))
    return newmusic.T

def extract_features(signal):
    return librosa.feature.chroma_stft(signal)[:12, :180].T

def sim_matrix(original_features, cover_features):
    similarity_matrix = []
    for each in original_features:
        sm = []
        for beach in cover_features:
            sm.append(euclidean(each, beach))
        similarity_matrix.append(sm)
    return np.array(similarity_matrix)

original_song = "../data/test_data/take_on_me.mp3"
cover_song = "../data/test_data/take_on_me_cover.mp3"

original_signal = librosa.load(original_song)[0]
cover_signal = librosa.load(cover_song)[0]

original_features = extract_features(original_signal)
cover_features = extract_features(cover_signal)

oti_cover_features = oti_func(original_features, cover_features)

mat = sim_matrix(original_features, oti_cover_features)
plt.imshow(mat, cmap='hot', interpolation='nearest')
plt.show()


import tabulate
agenda = {}

#Essa função busca as chaves de dicionários presentes na agenda.
#Após buscar as chaves a fução vai inserir as chaves dos contatos na lista "Chaves".
def chavescon(agenda, nome):
    chaves = []
    for chave in agenda:
        if chave.startswith(nome):
            chaves.append(chave)
    return chaves

# Esse é o bloco de código responsável por adicionar um contato na agenda.
# Além disso o usuário pode definir a quantidade de contatos que ele pode adicionar e após cadastrar, os dados ficam salvo em um dicionário.
def adicionar():
    Qtdcontatos = int(input('Quantos contatos deseja adicionar? '))
    while Qtdcontatos > 0:
        Nome = input("Digite o nome do contato:")
        Telefone = input("Digite o telefone do contato: ")
        Email = input("Digite o email do contato: ")
        Twitter = input("Digite o Twitter do contato: ")
        Instagram = input("Digite o Instagram do contato: ")
        agenda[Nome] = {
            'Nome': Nome,
            'Telefone': Telefone,
            'Email': Email,
            'Twitter': Twitter,
            'Instagram': Instagram }
        print('O contato {} foi cadastrado com sucesso!'.format(Nome))
        Qtdcontatos = Qtdcontatos - 1

#Esse bloco é o responsável por buscar um contato especifico através do nome na agenda!
#Após buscar os dados do contato, o contado aparece na tela com todos os dados!
def procurarcontato(nome, agenda):
    contatodebusca = []
    chaves1 = chavescon(agenda, nome)
    if len(chaves1) > 0:
        for chave in chaves1:
            contatodebusca.append([
                agenda[chave]["Nome"], agenda[chave]["Telefone"], agenda[chave]["Email"],
                agenda[chave]["Twitter"], agenda[chave]["Instagram"]
            ])
            print(contatodebusca)

#Esse bloco de código é responsável por buscar um contato através do Nome.
#Depois de buscar o contato, ele vai excluir o contato cadastrado.
def apagar(agenda, nome):
    if len(agenda) > 0:
      for contato in list(agenda):
        if contato == nome:
            agenda.pop(nome)
            print("O contato {} foi apagado da agenda!".format(nome))

# Esse bloco de código vai primeiramente buscar o contato cadastrado e os seus dados através do nome.
# Após localizar o contato ele vai pedir para voce inserir os novos dados do contato que deseja alterar.
# Por fim ele vai substituir todos os dados que estavam cadastrados anteriomente!
def Editar(agenda, nome):
    if len(agenda) > 0:
        for chavdocontato in agenda:
            if chavdocontato == nome:
                novo_nome = input('Digite o novo nome do contato: ')
                novo_telefone = input('Digite o novo telefone do contato: ')
                novo_email = input('Digite o novo email do contato: ')
                novo_twitter = input('Digite o novo Twitter do contato: ')
                novo_instagram = input('Informe o novo Instagram do contato: ')
                agenda[novo_nome] = agenda.pop(nome)
                agenda[novo_nome] = {
                    "Nome": novo_nome,
                    "Telefone": novo_telefone,
                    "Email": novo_email,
                    "Twitter": novo_twitter,
                    "Instagram": novo_instagram
                }
                print("Os dados do contato {} foram alterados com sucesso!".format(nome))
                break

#Esse bloco de código é responsável por gerar um relatorio de todos os contatos que estão cadastrados na agenda
#Obs: só consegui gerar o relatorio usando a biblioteca tabulate. Essa biblioteca mostra os contatos em forma de tabela
def relatorio(agenda):
    contatos = []
    if len(agenda) > 0:
        for chave in agenda:
            contatos.append([
                agenda[chave]["Nome"], agenda[chave]["Telefone"], agenda[chave]["Email"], agenda[chave]["Twitter"],
                agenda[chave]["Instagram"]
            ])
        print(tabulate.tabulate(contatos, headers=["Nome", "Telefone", "E-mail", "Twitter", "Instagram"], tablefmt="grid"))
    else:
        print("Agenda vazia!")

# Esse é o menu da minha agenda, onde estão localizadas todas opções.
def menu():
    while True:
        print('--> AGENDA TELEFONICA <--')
        print('1 - Adicionar contato')
        print('2 - Consultar contato')
        print('3 - Excluir contato')
        print('4 - Editar contato')
        print('5 - Lista de contatos')
        print('6 - Sair')
        opc = int(input('Qual a opção desejada: ->'))

        if opc == 1:
            adicionar()
        elif opc == 2:
            nome = input('Digite o Nome que deseja buscar: ')
            procurarcontato(nome, agenda)
        elif opc == 3:
            nome = input('Digite o Nome do contato que deseja excluir: ')
            apagar(agenda, nome)
        elif opc == 4:
            nome = input('Digite o nome do contato que deseja alterar: ')
            Editar(agenda, nome)
        elif opc == 5:
            relatorio(agenda)
        elif opc == 6:
            print('Agenda fechada!')
            break
        else:
            print('Opção invalida, selecione uma opção válida!')
menu()


from __future__ import print_function, absolute_import
import numpy as np
import copy
import torch

from re_ranking import re_ranking

def evaluate(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50):
    num_q, num_g = distmat.shape
    if num_g < max_rank:
        max_rank = num_g
        print("Note: number of gallery samples is quite small, got {}".format(num_g))
    indices = np.argsort(distmat, axis=1)
    matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32)

    # compute cmc curve for each query
    all_cmc = []
    all_AP = []
    num_valid_q = 0.
    for q_idx in range(num_q):
        # get query pid and camid
        q_pid = q_pids[q_idx]
        q_camid = q_camids[q_idx]

        # remove gallery samples that have the same pid and camid with query
        order = indices[q_idx]
        remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid)
        keep = np.invert(remove)

        # compute cmc curve
        orig_cmc = matches[q_idx][keep] # binary vector, positions with value 1 are correct matches
        if not np.any(orig_cmc):
            # this condition is true when query identity does not appear in gallery
            continue

        cmc = orig_cmc.cumsum()
        cmc[cmc > 1] = 1

        all_cmc.append(cmc[:max_rank])
        num_valid_q += 1.

        # compute average precision
        # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision
        num_rel = orig_cmc.sum()
        tmp_cmc = orig_cmc.cumsum()
        tmp_cmc = [x / (i+1.) for i, x in enumerate(tmp_cmc)]
        tmp_cmc = np.asarray(tmp_cmc) * orig_cmc
        AP = tmp_cmc.sum() / num_rel
        all_AP.append(AP)

    assert num_valid_q > 0, "Error: all query identities do not appear in gallery"

    all_cmc = np.asarray(all_cmc).astype(np.float32)
    all_cmc = all_cmc.sum(0) / num_valid_q
    mAP = np.mean(all_AP)

    return all_cmc, mAP

def evaluate_reranking(qf, q_pids, q_camids, gf, g_pids, g_camids, ranks):
    m, n = qf.size(0), gf.size(0)

    q_g_dist = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \
               torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()
    q_g_dist.addmm_(1, -2, qf, gf.t())
    q_q_dist = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, m) + \
               torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, m).t()
    q_q_dist.addmm_(1, -2, qf, qf.t())
    g_g_dist = torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, n) + \
               torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, n).t()
    g_g_dist.addmm_(1, -2, gf, gf.t())

    q_g_dist = q_g_dist.cpu().numpy()

    print("Computing CMC and mAP")
    cmc, mAP = evaluate(q_g_dist, q_pids, g_pids, q_camids, g_camids)

    print("Results ----------")
    print("mAP: {:.1%}".format(mAP))
    print("CMC curve")
    for r in ranks:
        print("Rank-{:<3}: {:.1%}".format(r, cmc[r - 1]))
    print("------------------")

    q_q_dist = q_q_dist.cpu().numpy()
    g_g_dist = g_g_dist.cpu().numpy()
    rerank_dis = re_ranking(q_g_dist, q_q_dist, g_g_dist)

    print("Computing rerank CMC and mAP")
    rerank_cmc, rerank_mAP = evaluate(rerank_dis, q_pids, g_pids, q_camids, g_camids)

    print("rerank Results ----------")
    print("mAP: {:.1%}".format(rerank_mAP))
    print("CMC curve")
    for r in ranks:
        print("rerank Rank-{:<3}: {:.1%}".format(r, rerank_cmc[r - 1]))
    print("------------------")
    return cmc + [mAP]

if __name__ == "__main__":
    a = np.random.rand(3, 2)
    b = np.random.rand(4, 2)
    q_g_dist = np.power(a, 2).sum(1, keepdims=True).repeat(4, axis=1) + \
               np.power(b, 2).sum(1, keepdims=True).repeat(3, axis=1).t()
    q_g_dist = q_g_dist - 2 * a.matmul(b.t())

    a = torch.Tensor(a)
    b = torch.Tensor(b)
    q_g_dist2 = torch.pow(a, 2).sum(dim=1, keepdim=True).expand(3, 4) + \
               torch.pow(b, 2).sum(dim=1, keepdim=True).expand(4, 3).t()
    q_g_dist2.addmm_(1, -2, a, b.t())