import random, pygame, sys, const, random, os, copy, shelve

# FOR TESTING:
# rm winner.txt rounds.txt
# for i in {1..1000}; do python game.py; done
# rounds.txt and winner.txt will contain 1000 games, with the number of rounds or winner as comma separated values for the respective file
# interpret the results with this: https://www.calculatorsoup.com/calculators/statistics/standard-deviation-calculator.php
# put everything in the readme

# to reset the q-learning weights delete shelved_features.db
# rm shelved_attack_features.db shelved_fortify_features.db

def main():
	winner = 0
	rounds = 0
	f1 = open("winner.txt", "a")
	f2 = open("rounds.txt", "a")
	shelved_attack_features = shelve.open("shelved_attack_features.db", writeback=True)
	shelved_fortify_features = shelve.open("shelved_fortify_features.db", writeback=True)
	occupied_shelf = shelved_attack_features.has_key("controlled_territories")
	if (not occupied_shelf):
		shelved_attack_features.update(const.attack_features)
		shelved_fortify_features.update(const.fortify_features)
	const.attack_features = shelved_attack_features
	const.fortify_features = shelved_fortify_features
	game_active = True
	# for testing: first agent call is player 1, second is player 2
	while (game_active):
			game_active = approximate_agent(const.PLAYERS[0])
			if game_active:
				game_active = random_agent(const.PLAYERS[1])
			else:
				winner = 1
			rounds += 1
	if (winner != 1):
		winner = 2
	max_weighting_value = 0
	# we standardize the weights by dividing by the largest absolute value
	for feature in const.attack_features.values():
		if (abs(feature["weighting"]) > abs(max_weighting_value)):
			max_weighting_value = abs(feature["weighting"])
	for feature in const.attack_features.values():
		feature["weighting"] = feature["weighting"] / max_weighting_value
	f1.write(str(winner) + ",")
	f2.write(str(rounds) + ",")
	print("player " + str(winner) + " wins after " + str(rounds) + " rounds")

# our benchmark random agent
def random_agent(player):
	# inital claiming stage
	can_claim = unclaimed_territories()
	if (unclaimedTerritory()):
		claim_territory(random.choice(can_claim), player)
		player["troops_to_place"] = 1

	#	6 rounds of troop placement
	elif (const.fortifying_round < 7):
		player["troops_to_place"] = 3
		friendlies = all_friendly_territories(player, const.TERRITORIES)
		while (player["troops_to_place"] > 0):
			place(random.choice(friendlies), player)
		if (player["player"] == len(const.PLAYERS)):
			const.fortifying_round += 1

	# first phase of normal play, placing troops
	if (const.ACTIVITY == const.PLACE and const.fortifying_round == 7):
		reinforce_player(player)
		friendlies = all_friendly_territories(player, const.TERRITORIES)
		while (player["troops_to_place"] > 0):
			place(random.choice(friendlies), player)
		const.ACTIVITY = const.ATTACK

	# second phase of normal play, attacking
	if (const.ACTIVITY == const.ATTACK):
		can_attack = territories_available_to_attack(player)
		attack_times = random.randint(0, len(can_attack))
		tries = 0
		while (len(can_attack) > 0 and attack_times > 0 and tries < 500):
			can_attack = territories_available_to_attack(player)
			if (len(can_attack) > 0):
				attacking = random.choice(can_attack)
				can_defend = specific_enemy_neighbors(attacking, const.TERRITORIES)
				tries += 1
				if (len(can_defend) > 0):
					defending = random.choice(can_defend)
					attack(attacking, defending, player)
					attack_times -= 1
		const.ACTIVITY = const.FORT

	#	last phase of normal play, troop movement/fortification
	if (const.ACTIVITY == const.FORT):
		can_fortify = territories_available_to_fortify(player, const.TERRITORIES)
		fortify_times = random.randint(0, len(can_fortify))
		while (len(can_fortify) > 0 and fortify_times > 0):
			can_fortify = territories_available_to_fortify(player, const.TERRITORIES)
			if (len(can_fortify) > 0):
				origin = random.choice(can_fortify)
				add_to_fortify_queue(origin, player)
				can_receive = specific_friendly_neighbors(origin)
				if (len(can_receive) > 0):
					destination = random.choice(can_receive)
					place_from_fortify_queue(origin, destination, player)
					fortify_times -= 1
		const.ACTIVITY = const.PLACE
		if is_terminal():
			return False
	return True

# our reflex agent
def choosy_agent(player):
	# inital claiming stage
	can_claim = unclaimed_territories()
	if (unclaimedTerritory()):
		best_territory = None
		best = -1000
		for territory in can_claim:
			enemy_territories = enemy_territories_in_continent(player, territory, const.TERRITORIES)
			friendly_territories = friendly_territories_in_continent(player, territory)

			current = friendly_territories - enemy_territories
			if current > best:
				best = current
				best_territory = territory

		claim_territory(best_territory, player)
		player["troops_to_place"] = 1

	#	6 rounds of troop placement
	elif (const.fortifying_round < 7):
		player["troops_to_place"] = 3
		friendlies = all_friendly_territories(player, const.TERRITORIES)
		bfs = all_border_friendlies(const.TERRITORIES, player)
		while (player["troops_to_place"] > 0):
			greatest_enemy_threat = float("-inf")
			territories_to_fortify = []

			for border_friendly in bfs:
				neighboring_enemy_troops = 0
				friendly_troops = border_friendly["troops"]

				for enemy_neighbor in specific_enemy_neighbors(border_friendly, const.TERRITORIES):
					neighboring_enemy_troops += enemy_neighbor["troops"]

				if (neighboring_enemy_troops - friendly_troops > greatest_enemy_threat):
					greatest_enemy_threat = neighboring_enemy_troops - friendly_troops
					territories_to_fortify = [border_friendly]

				elif (neighboring_enemy_troops - friendly_troops == greatest_enemy_threat):
					territories_to_fortify.append(border_friendly)
			if (len(territories_to_fortify) > 0):
				place(random.choice(territories_to_fortify), player)
		if (player["player"] == len(const.PLAYERS)):
			const.fortifying_round += 1

	# first phase of normal play, placing troops
	if (const.ACTIVITY == const.PLACE and const.fortifying_round == 7):
		reinforce_player(player)
		while (player["troops_to_place"] > 0):
			friendlies = all_friendly_territories(player, const.TERRITORIES)
			bfs = all_border_friendlies(const.TERRITORIES, player)
			greatest_enemy_threat = float("-inf")
			territories_to_fortify = []

			for border_friendly in bfs:
				neighboring_enemy_troops = 0
				friendly_troops = border_friendly["troops"]

				for enemy_neighbor in specific_enemy_neighbors(border_friendly, const.TERRITORIES):
					neighboring_enemy_troops += enemy_neighbor["troops"]

				if ((neighboring_enemy_troops - friendly_troops) > greatest_enemy_threat):
					greatest_enemy_threat = neighboring_enemy_troops - friendly_troops
					territories_to_fortify = [border_friendly]

				elif (neighboring_enemy_troops - friendly_troops == greatest_enemy_threat):
					territories_to_fortify.append(border_friendly)
			if (len(territories_to_fortify) > 0):
				place(random.choice(territories_to_fortify), player)
			else:
				break
		const.ACTIVITY = const.ATTACK

	# second phase of normal play, attacking
	if (const.ACTIVITY == const.ATTACK):
		attacks = decide_attack(player)
		while(len(attacks) > 0):
			attacks = decide_attack(player)
			for action in attacks:
				attack(action[0], action[1], player)
		const.ACTIVITY = const.FORT

	#	last phase of normal play, troop movement/fortification
	if (const.ACTIVITY == const.FORT):
		fortifying_flag = True
		while(fortifying_flag):
			fortifying_flag = False
			friendlies_with_troops = territories_available_to_fortify(player, const.TERRITORIES)
			bfs = all_border_friendlies(const.TERRITORIES, player)
			if (len(bfs) == 0):
				break
			for friendly in friendlies_with_troops:
				if (friendly not in bfs):
					fortifying_flag = True
					add_to_fortify_queue(friendly, player)
					inital = player["troops_to_place"]
					while (player["troops_to_place"] > 0):
						for neighbor in specific_friendly_neighbors(friendly):
							if (neighbor in bfs):
								place_from_fortify_queue(friendly, neighbor, player)
						if (player["troops_to_place"] == inital):
							break
					while (player["troops_to_place"] > 0):
								neighbor = random.choice(specific_friendly_neighbors(friendly))
								place_from_fortify_queue(friendly, neighbor, player)

		const.ACTIVITY = const.PLACE
		if is_terminal():
			return False
	return True

# our approximate learning agent
def approximate_agent(player):
	# inital claiming stage
	can_claim = unclaimed_territories()
	if (unclaimedTerritory()):
		best_territory = None
		best = -1000
		for territory in can_claim:
			enemy_territories = enemy_territories_in_continent(player, territory, const.TERRITORIES)
			friendly_territories = friendly_territories_in_continent(player, territory)

			current = friendly_territories - enemy_territories
			if current > best:
				best = current
				best_territory = territory

		claim_territory(best_territory, player)
		player["troops_to_place"] = 1

	#	6 rounds of troop placement
	elif (const.fortifying_round < 7):
		player["troops_to_place"] = 3
		friendlies = all_friendly_territories(player, const.TERRITORIES)
		bfs = all_border_friendlies(const.TERRITORIES, player)
		while (player["troops_to_place"] > 0):
			greatest_enemy_threat = float("-inf")
			territories_to_fortify = []

			for border_friendly in bfs:
				neighboring_enemy_troops = 0
				friendly_troops = border_friendly["troops"]

				for enemy_neighbor in specific_enemy_neighbors(border_friendly, const.TERRITORIES):
					neighboring_enemy_troops += enemy_neighbor["troops"]

				if (neighboring_enemy_troops - friendly_troops > greatest_enemy_threat):
					greatest_enemy_threat = neighboring_enemy_troops - friendly_troops
					territories_to_fortify = [border_friendly]

				elif (neighboring_enemy_troops - friendly_troops == greatest_enemy_threat):
					territories_to_fortify.append(border_friendly)
			if (len(territories_to_fortify) > 0):
				place(random.choice(territories_to_fortify), player)
		if (player["player"] == len(const.PLAYERS)):
			const.fortifying_round += 1

	# first phase of normal play, placing troops
	if (const.ACTIVITY == const.PLACE and const.fortifying_round == 7):
		reinforce_player(player)
		while (player["troops_to_place"] > 0):
			bfs = all_border_friendlies(const.TERRITORIES, player)
			greatest_enemy_threat = float("-inf")
			territories_to_fortify = []

			for border_friendly in bfs:
				neighboring_enemy_troops = 0
				friendly_troops = border_friendly["troops"]

				for enemy_neighbor in specific_enemy_neighbors(border_friendly, const.TERRITORIES):
					neighboring_enemy_troops += enemy_neighbor["troops"]

				if ((neighboring_enemy_troops - friendly_troops) > greatest_enemy_threat):
					greatest_enemy_threat = neighboring_enemy_troops - friendly_troops
					territories_to_fortify = [border_friendly]

				elif (neighboring_enemy_troops - friendly_troops == greatest_enemy_threat):
					territories_to_fortify.append(border_friendly)
			if (len(territories_to_fortify) > 0):
				place(random.choice(territories_to_fortify), player)
			else:
				break
		const.ACTIVITY = const.ATTACK

	# second phase of normal play, attacking
	if (const.ACTIVITY == const.ATTACK):
		friendlies_with_troops = territories_available_to_attack(player)
		attacking_flag = True
		while (attacking_flag):
			attacking_flag = False
			value = evaluate(const.TERRITORIES, player)
			for friendly in friendlies_with_troops:
				for enemy in specific_enemy_neighbors(friendly, const.TERRITORIES):
					attack_value = evaluate_attack(friendly, enemy, const.TERRITORIES, player)
					if (attack_value > value):
						attacking_flag = True
						state = copy.deepcopy(const.TERRITORIES)
						attack(friendly, enemy, player)
						reward = evaluate(const.TERRITORIES, player) - value
						update_after_attack(player, state, reward, attack_value)
		const.ACTIVITY = const.FORT

	#	last phase of normal play, troop movement/fortification
	if (const.ACTIVITY == const.FORT):
		fortifying_flag = True
		while(fortifying_flag):
			fortifying_flag = False
			state = const.TERRITORIES
			friendlies_with_troops = territories_available_to_fortify(player, const.TERRITORIES)
			bfs = all_border_friendlies(const.TERRITORIES, player)
			if (len(bfs) == 0):
				break
			for friendly in friendlies_with_troops:
				if (friendly not in bfs):
					fortifying_flag = True
					add_to_fortify_queue(friendly, player)
					inital = player["troops_to_place"]
					while (player["troops_to_place"] > 0):
						value = evaluate_fortify(state, player)
						best_origin_dest_value = (None, None, value)
						for neighbor in specific_friendly_neighbors(friendly):
							if (neighbor in bfs):
								temp_state = copy.deepcopy(state)
								place_from_fortify_queue(temp_state[temp_state.index(friendly)], temp_state[temp_state.index(neighbor)], player)
								new_value = evaluate_fortify(temp_state, player)
								if (new_value > best_origin_dest_value[2]):
									best_origin_dest_value = (friendly, neighbor, new_value)
						if (best_origin_dest_value[0]):
							place_from_fortify_queue(best_origin_dest_value[0], best_origin_dest_value[1], player)
							reward = best_origin_dest_value[2] - value
							update_after_fortify(player, state, reward, best_origin_dest_value[2])
						else:
							break
					while (player["troops_to_place"] > 0):
								neighbor = random.choice(specific_friendly_neighbors(friendly))
								place_from_fortify_queue(friendly, neighbor, player)

		const.ACTIVITY = const.PLACE
		if is_terminal():
			return False
	return True

# returns a list of all friendly territories that border the enemy
def all_border_friendlies(state, player):
	friendlies = all_friendly_territories(player, state)
	border_friendlies = []
	for f in friendlies:
		if (len(specific_enemy_neighbors(f, state)) > 0):
			border_friendlies.append(f)
	return border_friendlies

# return a total border troop difference, with positive numbers being favorable
def border_troop_imbalance(state, player):
	friendlies = all_friendly_territories(player, state)
	bfs = all_border_friendlies(const.TERRITORIES, player)
	troop_imbalance = 0
	enemy_ters = []
	for ter in bfs:
		troop_imbalance += ter["troops"]
		for enemy_ter in specific_enemy_neighbors(ter, state):
			if enemy_ter not in enemy_ters:
				enemy_ters.append(enemy_ter)
				troop_imbalance -= enemy_ter["troops"]
	return troop_imbalance

# return the total number of controlled territories
def controlled_territories(state, player):
	value = 0
	for ter in state:
		if ter["color"] == player["color"]:
			value += 1
	return value

# returns the total number of controlled continents
def controlled_continents(state, player):
	continents = []
	for ter in state:
		if ter["color"] == player["color"]:
			if enemy_territories_in_continent(player, ter, state) == 0:
				for c in const.CONTINENTS:
					if ter in c["territories"]:
						continent = c
						if continent not in continents:
							continents.append(continent)
	return len(continents)

# returns the number of neighboring enemy troops across all enemey neighbors
def num_neighboring_enemy_troops(state, player):
	friendlies = all_friendly_territories(player, const.TERRITORIES)
	enemies = total_enemy_neighbors(friendlies)
	enemy_troops = 0
	for enemy in enemies:
		enemy_troops += enemy["troops"]
	return enemy_troops

# number of bordering enemy territories
def num_neighboring_enemy_territories(state, player):
	friendlies = all_friendly_territories(player, const.TERRITORIES)
	enemies = total_enemy_neighbors(friendlies)
	return len(enemies)

# all enemy troops, regardless of territory
def num_total_enemy_troops(state, player):
	enemies = []
	for ter in state:
		if ter["color"] != player["color"]:
			enemies.append(ter)
	enemy_troops = 0
	for enemy in enemies:
		enemy_troops += enemy["troops"]
	return enemy_troops

# how many enemy players are still left (multiplayer)
def num_remaining_enemies(state, player):
	enemy_colors = []
	for ter in state:
		if ter["color"] != player["color"]:
			if ter["color"] not in enemy_colors:
				enemy_colors.append(ter["color"])
	return len(enemy_colors)

# helper function for evaluate_attack
def update_for_battle(attacking, defending, state, player):
	iA = state.index(attacking)
	iD = state.index(defending)
	if (defending["troops"] < 1):
			defending["troops"] = (attacking["troops"] - 1)
			attacking["troops"] = 1
			defending["color"] = attacking["color"]
			state[iA] = attacking
			state[iD] = defending

# this enormous function takes the known battle probabilities and weights state
# evaluation by those probabilites for each type of possible battle
def evaluate_attack(attacking, defending, state, player):
	value = evaluate(state, player)
	if (attacking["troops"] > 3):
		if (defending["troops"] > 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 2
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 2
			temp_state3 = copy.deepcopy(state)
			iD = temp_state3.index(defending)
			iA = temp_state3.index(attacking)
			temp_state3[iD]["troops"] -= 1
			temp_state3[iA]["troops"] -= 1
			update_for_battle(temp_state3[iA], temp_state3[iD], temp_state3, player)
			value = .372 * evaluate(temp_state1, player)\
						+ .292 * evaluate(temp_state2, player)\
						+ .336 * evaluate(temp_state3, player)
		if (defending["troops"] == 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 1
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 1
			value = .66 * evaluate(temp_state1, player)\
						+ .34 * evaluate(temp_state2, player)
	# rolling 2 die
	if (attacking["troops"] == 3):
		if (defending["troops"] > 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 2
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 2
			temp_state3 = copy.deepcopy(state)
			iD = temp_state3.index(defending)
			iA = temp_state3.index(attacking)
			temp_state3[iD]["troops"] -= 1
			temp_state3[iA]["troops"] -= 1
			update_for_battle(temp_state3[iA], temp_state3[iD], temp_state3, player)
			value = .228 * evaluate(temp_state1, player)\
						+ .448 * evaluate(temp_state2, player)\
						+ .324 * evaluate(temp_state3, player)
		if (defending["troops"] == 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 1
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 1
			value = .579 * evaluate(temp_state1, player)\
						+ .421 * evaluate(temp_state2, player)
	# rolling 1 die
	if (attacking["troops"] == 2):
		if (defending["troops"] > 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 1
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 1
			value = .255 * evaluate(temp_state1, player)\
						+ .745 * evaluate(temp_state2, player)
		if (defending["troops"] == 1):
			temp_state1 = copy.deepcopy(state)
			i = temp_state1.index(defending)
			temp_state1[i]["troops"] -= 1
			update_for_battle(temp_state1[temp_state1.index(attacking)], temp_state1[i], temp_state1, player)
			temp_state2 = copy.deepcopy(state)
			temp_state2[temp_state2.index(attacking)]["troops"] -= 1
			value = .417 * evaluate(temp_state1, player)\
						+ .583 * evaluate(temp_state2, player)
	return value

# evaluates a state using the attack features
def evaluate(state, player):
	value = 0
	for feature_name, feature in const.attack_features.iteritems():
		feature["value"] = globals()[feature_name](state, player)
		value += feature["value"] * feature["weighting"]
	return value

# evaluate a state using fortify features (other phases also use this)
def evaluate_fortify(state, player):
	value = 0
	for feature_name, feature in const.fortify_features.iteritems():
		feature["value"] = globals()[feature_name](state, player)
		value += feature["value"] * feature["weighting"]
	return value

# learning update equation from lecture notes
def update_after_attack(player, state, reward, prev_value):
	discount = 0.9
	alpha = 0.00001
	difference = (reward + discount * evaluate(state, player)) - prev_value
	for feature_name, feature in const.attack_features.iteritems():
		feature["value"] = globals()[feature_name](state, player)
		feature["weighting"] += alpha * difference * feature["value"]

# learning update equation from lecture notes
def update_after_fortify(player, state, reward, prev_value):
	discount = 0.9
	alpha = 0.00001
	difference = (reward + discount * evaluate_fortify(state, player)) - prev_value
	for feature_name, feature in const.attack_features.iteritems():
		feature["value"] = globals()[feature_name](state, player)
		feature["weighting"] += alpha * difference * feature["value"]

# return a list of all attacks above a threshold of advantage
def decide_attack(player):
	friendlies = all_friendly_territories(player, const.TERRITORIES)
	friendlies_with_troops = territories_available_to_attack(player)

	attackable_enemy_territories = total_enemy_neighbors(friendlies_with_troops)

	best_troop_difference = float("-inf")

	attacks = []

	attacking = None
	defending = None

	for enemy_territory in attackable_enemy_territories:
		enemy_troops = enemy_territory["troops"]
		for f in specific_enemy_neighbors(enemy_territory, const.TERRITORIES):
			if (f["color"] == player["color"]):
				troop_difference = f["troops"] - enemy_troops
				if (troop_difference > 3):
					attacks.append((f, enemy_territory))

	return attacks

# friendly territories with at least two troops who have enemy neighbors
def territories_available_to_attack(player):
	friendlies = all_friendly_territories(player, const.TERRITORIES)
	bfs = all_border_friendlies(const.TERRITORIES, player)
	can_attack = []
	for border_friendly in bfs:
		if (border_friendly["color"] == player["color"] and border_friendly["troops"] > 1):
			can_attack.append(border_friendly)
	return can_attack

# friendly territories with at least two troops
def territories_available_to_fortify(player, state):
	can_fortify = []
	for territory in state:
		if (territory["color"] == player["color"] and territory["troops"] > 1):
			can_fortify.append(territory)
	return can_fortify

# all of player's territories in a list
def all_friendly_territories(player, state):
	friendly_territories = []

	for t in state:
		if t["color"] == player["color"]:
			friendly_territories.append(t)

	return friendly_territories

# friendly neighbors of a given territory in a list
def specific_friendly_neighbors(territory):
	color = territory["color"]

	neighbors = []

	for neighbor in const.NEIGHBORS:
		if neighbor["territory"] == territory:
			neighbors = neighbor["neighbors"]

	friendly_territories = []

	for n in neighbors:
		if n["color"] == color:
		  friendly_territories.append(n)

	return friendly_territories

# enemy neighbors of a specific territory in a list
def specific_enemy_neighbors(territory, state):
	color = territory["color"]

	neighbors = []

	for neighbor in const.NEIGHBORS:
		if neighbor["territory"] == territory:
			if (state != const.TERRITORIES):
				neighbors = []
				ns = neighbor["neighbors"]
				for n in ns:
					neighbors.append(state[const.TERRITORIES.index(n)])
			else:
				neighbors = neighbor["neighbors"]

	enemy_territories = []

	for n in neighbors:
		if n["color"] != color:
		  enemy_territories.append(n)

	return enemy_territories

# all enemy neighbors of the territories passed in as friendlies
def total_enemy_neighbors(friendlies):
	enemy_neighbors = []

	for f in friendlies:
		enemies = specific_enemy_neighbors(f, const.TERRITORIES)
		for enemy in enemies:
			if enemy not in enemy_neighbors:
				enemy_neighbors.append(enemy)

	return enemy_neighbors

# sum of all friendly troops on the board
def total_troop_strength(player):
	territories = all_friendly_territories(player, const.TERRITORIES)
	troops = [specific_troop_strength(t) for t in territories]
	total_troops = sum(troops)

	return troops

# enemy territory count in the continent to which territory belongs
def enemy_territories_in_continent(player, territory, state):
	continent = None

	ter = const.TERRITORIES[state.index(territory)]

	for c in const.CONTINENTS:
		if ter in c["territories"]:
			continent = c

	color = None

	enemy_territories = 0
	if (continent):
		for t in continent["territories"]:
			terri = state[const.TERRITORIES.index(t)]
			if (terri["color"] != player["color"]) and (terri["color"]!= const.GRAY):
				enemy_territories += 1

	return enemy_territories

# friendly territory count in the continent to which territory belongs
def friendly_territories_in_continent(player, territory):
	continent = None

	for c in const.CONTINENTS:
		if territory in c["territories"]:
			continent = c

	color = None

	friendly_territories = 0
	if (continent):
		for t in continent["territories"]:
			if (t["color"] == player["color"]) and (t["color"]!= const.GRAY):
				friendly_territories += 1

	return friendly_territories

# returns true if there are unclaimed (gray) territories
def unclaimedTerritory():
  for territory in const.TERRITORIES:
    if (territory["color"] == const.GRAY):
      return True
  return False

# actually claims the territory and changes board state
def claim_territory(territory, player):
	if (territory["color"] == const.GRAY):
		territory["troops"] += 1
		territory["color"] = player["color"]
		player["troops_to_place"] -= 1

# place one troop in given destination territory
def place(destination, player):
	if (destination["color"] == player["color"]):
		destination["troops"] += 1
		player["troops_to_place"] -= 1

# maximum number of die will always be rolled for attacker and defender
# battle probabilites are hard coded using values obtained by simulation
# for speedy battles, this executes a battle and changes board state

def attack(attacking, defending, player):
	# calling attack
	if (attacking in all_friendly_territories(player, const.TERRITORIES)) and (defending in specific_enemy_neighbors(attacking, const.TERRITORIES)):
		p = random.random()
		# rolling 3 die
		if (attacking["troops"] > 3):
			if (defending["troops"] > 1):
				if (p < .372):
					defending["troops"] -= 2
				if (p > .708):
					attacking["troops"] -= 2
				else:
					attacking["troops"] -= 1
					defending["troops"] -= 1
			if (defending["troops"] == 1):
				if (p < .66):
					defending["troops"] -= 1
				else:
					attacking["troops"] -= 1
		# rolling 2 die
		if (attacking["troops"] == 3):
			if (defending["troops"] > 1):
				if (p < .228):
					defending["troops"] -= 2
				if (p > .552):
					attacking["troops"] -= 2
				else:
					attacking["troops"] -= 1
					defending["troops"] -= 1
			if (defending["troops"] == 1):
				if (p < .579):
					defending["troops"] -= 1
				else:
					attacking["troops"] -= 1
		# rolling 1 die
		if (attacking["troops"] == 2):
			if (defending["troops"] > 1):
				if (p < .255):
					defending["troops"] -= 1
				else:
					attacking["troops"] -= 1
			if (defending["troops"] == 1):
				if (p < .417):
					defending["troops"] -= 1
				else:
					attacking["troops"] -= 1
		if (defending["troops"] < 1):
			defending["troops"] = (attacking["troops"] - 1)
			attacking["troops"] = 1
			defending["color"] = attacking["color"]

# remove troops from board, put into placement queue
def add_to_fortify_queue(origin, player):
	if (origin["color"] == player["color"]):
		player["troops_to_place"] += (origin["troops"] - 1)
		origin["troops"] = 1

# remove troops from placement queue, put onto board in destination with logic checking
def place_from_fortify_queue(origin, destination, player):
	 if (destination in specific_friendly_neighbors(origin) or destination == origin):
		 destination["troops"] += 1
		 player["troops_to_place"] -= 1

# returns the number of troops a player should receieve given continent and territory bonuses
def reinforce_player(player):
	player["troops_to_place"] = 3

	friendlies = all_friendly_territories(player, const.TERRITORIES)

	player["troops_to_place"] += int(len(friendlies)/3)

	player_territories = friendlies

	NORTH_AMERICA_owned = EUROPE_owned = SOUTH_AMERICA_owned = AFRICA_owned = ASIA_owned = OCEANIA_owned = False

	for territory in player_territories:
		if enemy_territories_in_continent(player, territory, const.TERRITORIES) == 0:

			if territory in const.NORTH_AMERICA["territories"] and NORTH_AMERICA_owned == False:
				player["troops_to_place"] += const.NORTH_AMERICA["bonus"]
				NORTH_AMERICA_owned = True

			if territory in const.EUROPE["territories"] and EUROPE_owned == False:
				player["troops_to_place"] += const.EUROPE["bonus"]
				EUROPE_owned = True

			if territory in const.SOUTH_AMERICA["territories"] and SOUTH_AMERICA_owned == False:
				player["troops_to_place"] += const.SOUTH_AMERICA["bonus"]
				SOUTH_AMERICA_owned = True

			if territory in const.AFRICA["territories"] and AFRICA_owned == False:
				player["troops_to_place"] += const.AFRICA["bonus"]
				AFRICA_owned = True

			if territory in const.ASIA["territories"] and ASIA_owned == False:
				player["troops_to_place"] += const.ASIA["bonus"]
				ASIA_owned = True

			if territory in const.OCEANIA["territories"] and OCEANIA_owned == False:
				player["troops_to_place"] += const.OCEANIA["bonus"]
				OCEANIA_owned = True

# press x to use this function in GUI, assigns all territories for testing purposes
def assign_territories():
	i = 0
	while (i < len(const.TERRITORIES)):
		for p in const.PLAYERS:
			const.TERRITORIES[i]["color"] = p["color"]
			const.TERRITORIES[i]["troops"] = 1
			i += 1

# determine if game is won
def is_terminal():
	color = const.TERRITORIES[0]["color"]
	for territory in const.TERRITORIES:
		if territory["color"] != color:
			return False
	return True

# returns a list of legal attack actions a player can take in this form: (attacking, defending)
def get_legal_attacks(player):
	friendlies_with_troops = territories_available_to_attack(player)
	actions = []
	for attacking in friendlies_with_troops:
		for defending in specific_enemy_neighbors(attacking, const.TERRITORIES):
			actions.append(attacking, defending)

# returns a list of unclaimed territories
def unclaimed_territories():
	ret = []
	for territory in const.TERRITORIES:
		if territory["color"] == const.GRAY:
			ret.append(territory)
	return ret

if __name__ == '__main__':
    main()


import sys
sys.setrecursionlimit(10**6)
N, Q = map(int, input().split())
lr = [map(int, input().split()) for _ in range(Q)]
l, r = [list(i) for i in zip(*lr)]

class UnionFind:
    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def union(self, i, j):
        i = self.find(i)
        j = self.find(j)
        if i < j:
            self.parent[i] = j
        else:
            self.parent[j] = i

    def find(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.find(self.parent[i])
        return self.parent[i]

    def is_connect(self, i, j):
        if self.find(i) == self.find(j):
            return True
        return False

uf = UnionFind(N+1)
for i in range(Q):
    uf.union(r[i], l[i]-1)
if uf.is_connect(0, N):
    print("Yes")
else:
    print("No")


'''
Discord image history viewer
Attempts to guessimate unique ID keyspace in image URIs that are publically available
Author: @jcobu
'''
from sys import exit
import requests, random
foundList = []

class urlTemplate:

    def __init__(self, uuid, uuid2, fname):
        self.uuid = uuid
        self.uuid2 = uuid2
        self.fname = fname

    def combinedURL(self):
        urlPrefix = 'https://media.discordapp.net/attachments'
        urlComplete = (f'{urlPrefix}/{self.uuid}/{self.uuid2}/{self.fname}')
        print(urlComplete)
        return urlComplete

# Temporary array keeping track of valid urls
def ifFound(code, url):
    if code == 200:
        for a in foundList:
            if url != a:
                foundList.append(url)

# Prints the final foundList array vertically
def printStuff():
    for i in foundList:
        print('Valid links: ' + i)

# Main menu
def menu():
    while(True):
        print('(1) for manual')
        print('(2) for automatic sifting')
        selection = input('Selection: ')

        if selection == '1':
            print('Starting manual\n')
            manualBuilder()
        elif selection == '2':
            print('Starting automatic\n')
            automatedBuilder()
        else:
            print('Exiting\n')
            exit(0)

# Picks random 3, 6 digit numbers and appends them to a single str var
def combiner():
    # Open pre-generated 6 digit list
    lines = open('numbers.txt').read().splitlines()
    list = str(random.choice(lines))
    return list
    # Closes the file
    lines.close()

# Manual search
def manualBuilder():
    print('Example: https://media.discordapp.net/attachments/<useruuid>/<secondaryuuid>/<unknown.png>')
    userUUID = input('User UUID: ')
    userFile = input('File name (if known): ')
    if userFile == '':
        userFile = 'unknown.png'

    for a in range(10):
        alist = ''
        for x in range(3):
            alist += combiner()

        # Combines the provided info
        userInput = urlTemplate(userUUID, '909926715197902868', userFile)
        resp = requests.get(userInput.combinedURL())
        print(resp.status_code)
        ifFound(resp.status_code, userInput.combinedURL())

        printStuff()

# Automated search based on wordlists
def automatedBuilder():
    for z in range(10):
        alist = ''
        blist = ''
        for x in range(3):
            alist += combiner()
            blist += combiner()

        # Combines the provided info using classes
        automatedInput = urlTemplate(alist, blist, 'unknown.png')
        resp = requests.get(automatedInput.combinedURL())
        print(resp.status_code)
        ifFound(resp.status_code, automatedInput.combinedURL())

        printStuff()

menu()


import unittest
import os
from coreapis.peoplesearch import tokens

class TestTokens(unittest.TestCase):
    def test_decryptable(self):
        key = os.urandom(32)
        msg = 'My secret'
        token = tokens.crypt_token(msg, key)
        assert token != msg
        msg2 = tokens.decrypt_token(token, key)
        assert msg2 == msg


import numpy as np
import math
with open('../data/smoke_basin') as f:
    lines = f.readlines()

data = np.array([[int(i) for i in line.strip()] for line in lines])

num_rows, num_cols = len(data), len(data[0])

basin_counts = []

def increase_basin(row,col):
    # basin spread stops for these conditions: 1) square boundary reached, 2) square counted already, 3) square is value 9
    if row < 0 or row >= num_rows or col < 0 or col >= num_cols or data[row][col]== -1 or data[row][col]==9:
        return
    data[row][col] = -1 # mark square as counted
    basin_counts[-1] += 1 #
    # Iterate for surrounding squares recursively
    new_locs = [[row+1,col],[row-1,col],[row,col+1],[row,col-1]]
    for new_loc in new_locs:
        increase_basin(new_loc[0],new_loc[1])

for row in range(num_rows):
    for col in range(num_cols):
        basin_counts += [0]
        increase_basin(row,col)

basin_counts_sorted = sorted([i for i in basin_counts if i!=0])
print(math.prod(basin_counts_sorted[-3:]))


import argparse
import copy
import json
import os
import glob
import sys
import urllib
import urllib.request
import shutil
import zipfile
import numpy
import nibabel
import tarfile
import re
import nrrd
import xml.etree.ElementTree as et
from collections import defaultdict
from nipype.interfaces.ants import ApplyTransforms
from nipype.interfaces.ants.base import ANTSCommand, ANTSCommandInputSpec
from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, traits, File, Str, TraitedSpec, Directory, CommandLineInputSpec, CommandLine, InputMultiPath, isdefined, Bunch, OutputMultiPath

#from nipype.interfaces.fsl import fslorient

API_SERVER = "http://api.brain-map.org/"
API_DATA_PATH = API_SERVER + "api/v2/data/"

def GetExpID(startRow=0,numRows=2000,totalRows = -1):
	"""
	Queries the Allen Mouse Brain Institute website for all gene expression data available for download.

	Returns:
	--------
	GeneNames: list[dict()]
		list of all genes where expression data is available for download. Dict contains experiment/gene metadata.

	SectionDataSetID : list(int)
		corresponding SectionDataSetID (SectionDataSet: see "http://help.brain-map.org/display/api/Data+Model")
		ID needed to specify download target.

	"""

	startRow = startRow
	numRows = numRows
	totalRows = totalRows
	rows = []
	GeneNames = []
	SectionDataSetID = []
	info = list()
	done = False

	while not done:
		r = "&start_row={0}&num_rows={1}".format(startRow,numRows)
		pagedUrl = API_DATA_PATH + "query.json?criteria=model::SectionDataSet,rma::criteria,products%5Bid$eq5%5D,rma::include,specimen(stereotaxic_injections(primary_injection_structure,structures))" + r
		source = urllib.request.urlopen(pagedUrl).read()
		response = json.loads(source)
		rows += response['msg']
		for x in response['msg']:

			if x['failed'] == False :
				print(x['id'])
				info.append(x['id'])
		if totalRows < 0:
			totalRows = int(response['total_rows'])

		startRow += len(response['msg'])

		if startRow >= totalRows:
			done = True

	return info

def nrrd_to_nifti(file):
	print("Reading " + file)
	readnrrd = nrrd.read(file)
	data = readnrrd[0]
	header = readnrrd[1]
	print(header)
	print("Converting " + file)

	affine_matrix = numpy.array(header["space directions"],dtype=numpy.float)
	affine_matrix = affine_matrix*0.001
	affine_matrix = numpy.insert(affine_matrix,3,[0,0,0], axis=1)
	affine_matrix = numpy.insert(affine_matrix,3,[0,0,0,1], axis=0)

	#Change Orientation from PIR to RAS. Steps: PIR -> RIP -> RPI -> RPS -> RAS
	data.setflags(write=1)
	data = numpy.swapaxes(data,0,2)
	data = numpy.swapaxes(data,1,2)
	data = data[:,:,::-1]
	data = data[:,::-1,:]
	data = data[::-1,:,:] #TODO: Check for Atlas files!!!!!!
	img = nibabel.Nifti1Image(data,affine_matrix)
	nii_path = os.path.join(os.path.dirname(file), os.path.basename(file).split(".")[0] + '.nii')
	nibabel.save(img,nii_path)

	return nii_path

def get_identifying_structure(metadata):
	tree = et.parse(metadata)
	root = tree.getroot()
	struc = root.findall('.//primary-injection-structure/safe-name')[0]
	return struc.text

def get_exp_metadata(exp,path):
	url_meta = API_DATA_PATH + "/SectionDataSet/query.xml?id=" + str(exp) + "&include=specimen(stereotaxic_injections(primary_injection_structure,structures))"
	filename = str(exp) + "_experiment_metadata.xml"
	s = urllib.request.urlopen(url_meta)
	contents = s.read()
	path_to_metadata = os.path.join(path,filename)
	file = open(path_to_metadata, 'wb')
	file.write(contents)
	file.close()

	return path_to_metadata

def download_all_connectivity(info,folder_name,resolution=200):
	"""
	Download all given genes corresponding to SectionDataSetID given in 100um and 25um resolution, converts nrrd to nii, registers to dsurqec... and resamples files to 40 and 200 respectively.

	Parameters:
	-----------
	SectionDataSetID : list(int)
		o=[0.200000002980232 0 0 -6.26999998092651; 0 0.200000002980232 0 -10.6000003814697; 0 0 0.200000002980232 -7.88000011444092; 0 0 0 1]list of SectionDataSetID to download.
	"""
	print(resolution==200)
	if resolution is None:
		res=[100,25]
	elif resolution==40:
		res=[25]
	elif resolution==200:
		res=[100]
		print(res)
	else:
		res = [99]
	print(resolution)
	download_url = "http://api.brain-map.org/grid_data/download_file/"
	print(res)
	for resolution in res:
		if resolution == 100: path_to_res = folder_name
		if resolution == 25: path_to_res = folder_name + "HD"
		if not os.path.isdir(path_to_res):os.mkdir(path_to_res)
		for exp in info:
			path_to_exp = os.path.join(path_to_res,str(exp))
			#TODO: look inside if stuff is there...
			os.mkdir(path_to_exp)
			path_to_metadata = get_exp_metadata(exp,path_to_exp) #TODO: so far no coordinate info. Also, avoid downloading twice
			struc_name=get_identifying_structure(path_to_metadata)
			struc_name = struc_name.lower()
			struc_name= re.sub(" ","_",struc_name)
			struc_name=re.sub("[()]","",struc_name)
			new_name = struc_name + "-" + os.path.basename(path_to_exp)
			new_path = os.path.join(os.path.dirname(path_to_exp),new_name)
			os.rename(path_to_exp,new_path)
			resolution_url = "?image=projection_density&resolution=" + str(resolution)
			url = download_url + str(exp) + resolution_url
			fh = urllib.request.urlretrieve(url)
			filename = str.split((fh[1]._headers[6][1]),'filename=')[1] #TODO: Consistent??
			#TODO: do that differenttly ...
			filename = str.split(filename,";")[0]
			file_path_nrrd = os.path.join(new_path,filename)
			shutil.copy(fh[0],file_path_nrrd)
			os.remove(fh[0])
			#os.rename(fh[0],file_path_nrrd) only works if source and dest are on the same filesystem
			file_path_nii = nrrd_to_nifti(file_path_nrrd)
			os.remove(file_path_nrrd)
			file_path_2dsurqec = apply_composite(file_path_nii,resolution)
			os.remove(file_path_nii)
			#create archives

		if resolution == 25:
			sort_and_archive()

		elif resolution == 100:
			save_info(info,folder_name)
			tarname=folder_name + ".tar.xz"
			create_archive(tarname,folder_name)

	return

def apply_composite(file,resolution):
	#TODO: does this downsample if composite file is low resolution? Currently composite file is 40um. If it does,is it a problem? Target resolution is 40 anyway, but maybe get a
	#composite file at 25um as well? ResampleImage is possibly not needed otherwise, just specify reference image resolution of 40 and 200
	"""
	Uses ANTS ApplyTransforms to register image to

	Parameters :
	------------

	file : str
		path to image

	"""
	at = ApplyTransforms()
	at.inputs.dimension = 3
	at.inputs.input_image = file
	if resolution == 100:
		ref_image = '/usr/share/mouse-brain-atlases/dsurqec_200micron_masked.nii'
		resolution = 200
	else:
		ref_image = '/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii'
		resolution = 40

	#TODO: theres got to be an easier way...
	output_image = ""
	for s in os.path.basename(file).split("_"):
		if "um" not in s :
			output_image += s + "_"
		else:
			output_image += (str(resolution) + "um_")
	output_image = output_image[:-1]
	output_image = os.path.join(os.path.dirname(file),output_image)

	at.inputs.reference_image = ref_image
	name = str.split(os.path.basename(output_image),'.nii')[0] + '_2dsurqec.nii.gz'
	#at.inputs.interpolation = 'NearestNeighbor' #TODO: Sure??
	at.inputs.interpolation = 'BSpline'
	output_image = os.path.join(os.path.dirname(output_image),name)
	at.inputs.output_image = output_image
	at.inputs.transforms = '/usr/share/mouse-brain-atlases/abi2dsurqec_Composite.h5'
	at.run()

	#TODO sform to qform
	return output_image

def download_annotation_file(path):
	anno_url_json = "http://api.brain-map.org/api/v2/structure_graph_download/1.json"
	anno_url_xml = "http://api.brain-map.org/api/v2/structure_graph_download/1.xml"
	filename_xml = "structure_graph.xml"
	filename_json = "structure_graph.json"

	if not os.path.isdir(path):os.mkdir(path)

	s = urllib.request.urlopen(anno_url_json)
	contents = s.read()
	file = open(os.path.join(path,filename_json), 'wb')
	file.write(contents)
	file.close()

	s = urllib.request.urlopen(anno_url_xml)
	contents = s.read()
	file = open(os.path.join(path,filename_xml), 'wb')
	file.write(contents)
	file.close()

def sort_and_archive(path="ABI-connectivity-dataHD"):
	arch = dict()
	arch_names_suff = dict()
	#TODO: There has to be an easier way...
	#TODO:check for any file that does not start with a letter
	arch[1] = glob.glob(os.path.join(path,"[Aa]*"))
	arch_names_suff[1] = "a"
	arch[2] = glob.glob(os.path.join(path,"[BbCc]*"))
	arch_names_suff[2] = "b-c"
	arch[3] = glob.glob(os.path.join(path,"[DdEe]*"))
	arch_names_suff[1] = "d-e"
	arch[4] = glob.glob(os.path.join(path,"[FfGgHhIiJj]*"))
	arch_names_suff[4] = "f-j"
	arch[5]= glob.glob(os.path.join(path,"[KkLl]*"))
	arch_names_suff[5] = "k-l"
	arch[6] = glob.glob(os.path.join(path,"[Mm]*"))
	arch_names_suff[6] = "m"
	arch[7] = glob.glob(os.path.join(path,"[NnOo]*"))
	arch_names_suff[7] = "n-o"
	p_list = sorted(glob.glob(os.path.join(path,"[Pp]*")))
	ind = [p_list.index(i) for i in p_list if 'Primary' in i][0]
	arch[8] = p_list[0:ind]
	arch_names_suff[8] = "pa-pre"
	arch[9]= p_list[ind:len(p_list)]
	arch_names_suff[9] = "pri-po"
	arch[10] = glob.glob(os.path.join(path,"[QqRR]*"))
	arch_names_suff[10] = "q-r"
	arch[11] = glob.glob(os.path.join(path,"[Ss]*"))
	arch_names_suff[1] = "a"
	arch[12] = glob.glob(os.path.join(path,"[TtUuVvWwXxYyZz]*"))
	arch_names_suff[12] = "t-z"
	number_of_archives = 12
	number_of_folders = len(os.listdir(path))

	for i in range(1,(number_of_archives+1)):
		folder_name= os.path.join(path,"ABI-connectivity-dataHD_" + arch[i] + "-0.1")
		if not os.path.isdir(folder_name):os.mkdir(folder_name)
		for file in arch[i]:
			new_path = os.path.join(folder_name,os.path.basename(file))
			os.rename(file,new_path)
		tarname=folder_name + ".tar.xz"
		create_archive(tarname,folder_name)

def create_archive(tarname,path):
	path = path
	tar_name = tarname
	print(path)
	print(tar_name)
	with tarfile.open(tar_name, "w:xz") as tar_handle:
		for root,dirs,files in os.walk(path):
			for file in files:
				tar_handle.add(os.path.join(root,file))

#TODO: Do I really need that? Usefule for expression data, but here?
def save_info(info,folder_name):
	path= os.path.join(folder_name,"ABI-connectivity-ids.csv")
	f = open(path,"w")
	for exp in info:
		f.write('\n')
		f.write(str(exp))

def main():
	#TODO: some sort of parallel download should be possible, stating totalrows and startrows differently for simultaneous download
	#TODO: timeout for urllib
	parser = argparse.ArgumentParser(description="Similarity",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument('--package_name','-n',type=str,default="ABI-connectivity-data")
	parser.add_argument('--package_version','-v',type=str,default="9999")
	parser.add_argument('--startRow','-s',type=int,default=0)
	parser.add_argument('--numRows','-r',type=int,default=2000)
	parser.add_argument('--totalRows','-t',type=int,default=-1)
	parser.add_argument('--resolution','-x',type=int)
	args=parser.parse_args()

	folder_name = args.package_name + "-" + args.package_version
	download_annotation_file(folder_name)
	info=GetExpID(startRow=args.startRow,numRows=args.numRows,totalRows=args.totalRows)
	download_all_connectivity(info,folder_name=folder_name,resolution=args.resolution)
	#save_info(info)
	#create_archive()
	#sort_and_archive()

if __name__ == "__main__":
	main()


from tkinter import *
from PIL import Image, ImageTk
import tkinter as tk

def Registrationform():
    global reg_screen
    reg_screen = Tk()
    reg_screen.title("فرم حضور غیاب گلبرگ دنیا")
    reg_screen.iconphoto(False, PhotoImage(file='images/logos.png'))
    reg_screen.geometry("600x380")

    fram1 = tk.Frame(reg_screen, width=150, height=340, relief=SUNKEN,borderwidth=1)
    fram1.place(x=0,y=40)

    # TOP RIBBON
    Label(reg_screen, width="300", text=" سلام، روز خوش! لطفا منوی مورد نظر را انتخاب نمایید ", bg="purple", fg="white").pack(anchor='e')
    canvas = Canvas(reg_screen, width=160, height=45)
    canvas.place(x=-15,y=45)
    new_image = ImageTk.PhotoImage((Image.open("images/logo farsi eng.png")).resize((160, 40), Image.ANTIALIAS))
    canvas.create_image(10, 10, anchor=NW, image=new_image)

    fram2 = tk.Frame(reg_screen, width=450, height=340, relief=SUNKEN, borderwidth=1)
    fram2.place(x=150, y=40)
    canvas2 = Canvas(fram2, width=450, height=340)
    canvas2.place(x=0,y=0)
    new_image2 = ImageTk.PhotoImage((Image.open("images/Back1.png")).resize((450, 340), Image.ANTIALIAS))
    canvas2.create_image(1, 1, anchor=NW, image=new_image2)

    ###MENUE  hozoor ghiab
    def clickon0():
        B1.config(fg='White', bg='Purple')
        B2.config(fg='black', bg='White')
        B3.config(fg='black', bg='White')
        fram2 = tk.Frame(reg_screen, width=0, height=0)
        for widgets in fram2.winfo_children():
            widgets.destroy()
        import subpages.MenueSelectDate
        subpages.MenueSelectDate.menueSelectDate(reg_screen)
      # کلیک روی مدیریت پروفایل ها
    def clickon1():
        B1.config(fg='black', bg='White')
        B2.config(fg='White', bg='Purple')
        B3.config(fg='black', bg='White')
        fram2 = tk.Frame(reg_screen, width=0, height=0)
        for widgets in fram2.winfo_children():
            widgets.destroy()
        import subpages.MenueModidateProfile
        subpages.MenueModidateProfile.MenueModiriatProfile(reg_screen)

    # کلیک روی بررسی وضعیت کارمندان
    def clickon2():
        B1.config(fg='black', bg='White')
        B2.config(fg='black', bg='White')
        B3.config(fg='White', bg='Purple')
        fram2 = tk.Frame(reg_screen, width=0, height=0)
        for widgets in fram2.winfo_children():
            widgets.destroy()
        import subpages.MenueBarresiVaziat
        subpages.MenueBarresiVaziat.MenueVaziateKarmand(reg_screen)

    # ERROR

    B1 = Button(reg_screen, text=' لیست حضور و غیاب', command=lambda: clickon0(), width="17", bg='white',
                fg='black')
    B1.place(x=10, y=130)
    B2 = Button(reg_screen, text='مدیریت پروفایل ها', command=lambda: clickon1(), bg='white', fg='black',
                width="17")
    B2.place(x=10, y=170)
    B3 = Button(reg_screen, text='بررسی وضعیت کارمندان ', command=lambda: clickon2(), bg='white', fg='black',
                width="17")
    B3.place(x=10, y=210)

    reg_screen.mainloop()

Registrationform()


#!/usr/bin/env python
#_*_coding:utf-8_*_

import argparse
import numpy as np
import pandas as pd
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path + '/repDNA/')
from repDNA.nac import *
from repDNA.psenac import *
from repDNA.ac import *
from Bio import SeqIO

def feature_extraction_repdna(finput, label):

	names_seq = []
	for seq_record in SeqIO.parse(finput, "fasta"):
		name = seq_record.name
		names_seq.append(name)

	rev_kmer = RevcKmer(k=3, normalize=True, upto=True)
	data_kmer = rev_kmer.make_revckmer_vec(open(finput))
	data_kmer = pd.DataFrame(data_kmer)

	psednc = PseDNC()
	data_psednc = psednc.make_psednc_vec(open(finput))
	data_psednc = pd.DataFrame(data_psednc)

	pseknc = PseKNC()
	data_pseknc = pseknc.make_pseknc_vec(open(finput))
	data_pseknc = pd.DataFrame(data_pseknc)

	sc_psednc = SCPseDNC()
	data_sc_psednc = sc_psednc.make_scpsednc_vec(open(finput), all_property=True)
	data_sc_psednc = pd.DataFrame(data_sc_psednc)

	sc_psetnc = SCPseTNC(lamada=2, w=0.05)
	data_sc_psetnc = sc_psetnc.make_scpsetnc_vec(open(finput), all_property=True)
	data_sc_psetnc = pd.DataFrame(data_sc_psetnc)

	dac = DAC(2)
	data_dac = dac.make_dac_vec(open(finput), all_property=True)
	data_dac = pd.DataFrame(data_dac)

	tac = TAC(2)
	data_tac = tac.make_tac_vec(open(finput), all_property=True)
	data_tac = pd.DataFrame(data_tac)

	tcc = TCC(2)
	data_tcc = tcc.make_tcc_vec(open(finput), all_property=True)
	data_tcc = pd.DataFrame(data_tcc)

	tacc = TACC(2)
	data_tacc = tacc.make_tacc_vec(open(finput), all_property=True)
	data_tacc = pd.DataFrame(data_tacc)

	df = pd.concat([data_kmer,
					data_psednc,
					data_pseknc,
					data_sc_psednc,
					data_sc_psetnc,
					data_dac,
					data_tac,
					data_tcc,
					data_tacc],
				   axis=1, ignore_index=False)

	df.insert(0, "nameseq", names_seq)
	df.insert(len(df.columns), "label", label)

	return df

if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument("--file", dest='file')
	parser.add_argument("--output", dest='outFile',
						help="the generated descriptor file")
	parser.add_argument("--label", dest='labelFile')
	args = parser.parse_args()
	input_file = str(args.file)
	label = str(args.labelFile)
	output_file = str(args.outFile)

	df = feature_extraction_repdna(input_file, label)
	df.to_csv(output_file, index=False, mode='a')

# Documentation: http://bioinformatics.hitsz.edu.cn/repDNA/static/download/repDNA_manual.pdf


import pytest
import asyncio

from db import Store

class TestStore():
    def setup(self):
        self.test_string = {'name': 'UserForm', 'phone': 'phone', 'e_mail': 'mail'}
        self.store = Store(host='172.23.0.1')

    def test_get_list_from_store(self):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.store.get_documents_from_db())
        assert self.store.list_records[0]['name'] == self.test_string['name']
        assert self.store.list_records[0]['phone'] == self.test_string['phone']
        assert self.store.list_records[0]['e_mail'] == self.test_string['e_mail']


import sys
import os
import tempfile
import shutil
import argparse

from pykickstart.parser import *
from pykickstart.version import makeVersion
import yum

class KickstartPackageResolver(object):
    def __init__(self, ks_path, blacklist=None):
        self.ks_path = ks_path
        if blacklist is None:
            self.blacklist = []
        else:
            self.blacklist = blacklist

        # create a kickstart parser from the latest version
        self.ksparser = KickstartParser(makeVersion())
        self.yb = yum.YumBase()

        self._repo_problems = False

    def parse(self):
        self.ksparser.readKickstart(self.ks_path)
        selected_package_names = list(self.ksparser.handler.packages.packageList)
        selected_group_names = list(self.ksparser.handler.packages.groupList)
        excluded_package_names = list(self.ksparser.handler.packages.excludedList)

        self.setup_yum()
        self.exclude_packages(excluded_package_names + self.blacklist)

        found, missing = self._find_packages(selected_package_names)
        if missing:
            raise Exception("failed to find %s" % (' '.join(missing),))

        for p in found:
            self.yb.install(p)
        for group in selected_group_names:
            tx_members = self.yb.selectGroup(group.name)

        result,msgs = self.yb.buildTransaction()
        self._repo_problems = result != 2
        if self._repo_problems:
            sys.stderr.write("\n".join(msgs) + "\n")

    def cleanup(self):
        shutil.rmtree(self.tmpdir)

    @property
    def selected_packages(self):
        return [m.po for m in self.yb.tsInfo]

    def setup_yum(self):
        self.tmpdir = tempfile.mkdtemp(suffix=".ksparser")
        yum_conf = os.path.join(self.tmpdir, "fakyum.conf")
        yum_cache = os.path.join(self.tmpdir, "yumcache")

        # populate temporary yum tree
        open(yum_conf, "a").close()
        os.mkdir(yum_cache)
        os.mkdir(os.path.join(self.tmpdir, "etc"))
        os.mkdir(os.path.join(self.tmpdir, "etc/yum"))
        os.mkdir(os.path.join(self.tmpdir, "etc/yum/repos.d"))
        os.mkdir(os.path.join(self.tmpdir, "etc/yum.repos.d"))
        os.mkdir(os.path.join(self.tmpdir, "var"))
        os.mkdir(os.path.join(self.tmpdir, "var/lib"))
        os.mkdir(os.path.join(self.tmpdir, "var/lib/rpm"))

        self.yb.preconf.fn=yum_conf
        self.yb.preconf.root=self.tmpdir
        self.yb._getConfig()
        self.yb.repos.disableRepo('*')
        self.yb.setCacheDir(force=True, tmpdir=yum_cache)

        # add and enable yum repos defined in the kickstart
        for repodata in self.ksparser.handler.repo.repoList:
            self.yb.add_enable_repo(repodata.name, [repodata.baseurl])

        self.yb.pkgSack.excludeArchs(['x86_64', 'noarch'])

    def _find_packages(self, pkg_names, newest_only=True):
        found = []
        missing = []
        if newest_only:
            find_func = self.yb.pkgSack.returnNewestByName
        else:
            find_func = self.yb.pkgSack.returnPackages

        # some package patterns did not match, so look one at a time
        for pkg_name in pkg_names:
            try:
                matches = find_func(patterns=[pkg_name])
                found.extend(matches)
            except:
                missing.append(pkg_name)
        return (found, missing)

    def exclude_packages(self, package_names):
        excluded_packages,_ = self._find_packages(package_names, newest_only=False)
        for p in excluded_packages:
            p.exclude()

    def what_requires(self, dep_name):
        for txm in self.yb.tsInfo:
            if txm.name == dep_name:
                required_by = [p[0].name for p in txm.relatedto]
                groups = ["@%s" % (g,) for g in txm.groups]
                result = required_by + groups or ["kickstart"]
                return result
        return None

    @property
    def problems(self):
        return self._repo_problems

    @property
    def packages_nvra(self):
        nvra = [p.nvra for p in self.selected_packages]
        nvra.sort()
        return nvra

    def write_packages_info(self, out=sys.stdout):
        out.write("\n".join(self.packages_nvra) + "\n")

    @property
    def packages_meta(self):
        meta = [(p.nvra, self.package_hash(p)) for p in self.selected_packages]
        meta.sort()
        return meta

    def package_hash(self, po):
        # TODO: canonicalize package metadata and return a hash of that
        # rather than a hash of the package file
        return po.pkgId

    def write_packages_meta(self, out=sys.stdout):
        meta = self.packages_meta
        out.write("\n".join([','.join(m) for m in meta]) + "\n")

    def strip_pseudo_pkgs(self, package_names):
        return [p for p in package_names if not p.startswith("gpg-pubkey-")]

    def get_extra_packages(self, baseline_packages):
        '''
        return a list of packages that are selected in the kickstart but
        are not present in baseline_packages
        '''
        extra = list(set(self.packages_nvra) - set(self.strip_pseudo_pkgs(baseline_packages)))
        extra.sort()
        return extra

    def write_extra_packages(self, baseline_packages, out=sys.stdout):
        extra = self.get_extra_packages(baseline_packages)
        out.write("\n".join(extra) + "\n")

    def write_extra_packages_and_why(self, baseline_packages, out=sys.stdout):
        extra = self.get_extra_packages(baseline_packages)
        extra_packages = self.get_selected_package_objects_by_nvra(extra)
        for p in extra_packages:
            requires = self.what_requires(p.name)
            if requires is None:
                msg = "%s is not selected" % (p.nvra,)
            elif not requires:
                msg = "%s required by nothing" % (p.nvra,)
            else:
                msg = "%s required by %s" % (p.nvra, ' '.join(requires))
            out.write(msg + "\n")

    def get_selected_package_objects_by_nvra(self, packages_nvra):
        ''' return the list of selected package objects that match the list of nvra strings '''
        matching_packages = []
        for package in self.selected_packages:
            for nvra in packages_nvra:
                if package.nvra == nvra:
                    matching_packages.append(package)
        return matching_packages

    def get_missing_packages(self, baseline_packages):
        '''
        return a list of packages that are present in baseline_packages
        but are not selected in the kickstart
        '''
        missing = list(set(self.strip_pseudo_pkgs(baseline_packages)) - set(self.packages_nvra))
        missing.sort()
        return missing

    def write_missing_packages(self, baseline_packages, out=sys.stdout):
        missing = self.get_missing_packages(baseline_packages)
        out.write("\n".join(missing) + "\n")

def package_list_file(path):
    if not os.path.exists(path):
        raise argparse.ArgumentTypeError("path %s does not exist" % (path,))
    value = []
    for line in file(path):
        line = line.strip()
        if not line or line[0] == '#':
            continue
        value.append(line)
    return value

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("-b", "--blacklist",
                        help="path to a file containing packages to exclude",
                        type=package_list_file)
    parser.add_argument("-o", "--output",
                        help="path to a file to output selected package info",
                        type=argparse.FileType("w"))
    parser.add_argument("--expected",
                        help="path to a file containing expected package results",
                        type=package_list_file)
    parser.add_argument("--missing",
                        help="path to a file to output packages missing when compared to expected",
                        type=argparse.FileType("w"))
    parser.add_argument("--extra",
                        help="path to a file to output extra packages when compared to expected",
                        type=argparse.FileType("w"))
    parser.add_argument("--why-extra",
                        help="also output info for why extra packages are present when used in conjunction with --extra",
                        action="store_true")
    parser.add_argument("--with-meta",
                        help="also output metadata for packages",
                        action="store_true")
    parser.add_argument("kickstart", help="path to the kickstart file")
    args = parser.parse_args(argv)

    if not args.expected and (args.missing or args.extra):
        parser.error("--missing and --extra require --expected")

    pkg_resolver = KickstartPackageResolver(args.kickstart, args.blacklist)
    pkg_resolver.parse()
    if pkg_resolver.problems:
        sys.stderr.write("error: something is wrong with the kickstart or yum repos\n")
        sys.exit(1)

    if args.output:
        args.output.write("# selected packages\n")
        if args.with_meta:
            pkg_resolver.write_packages_meta(args.output)
        else:
            pkg_resolver.write_packages_info(args.output)

    if args.missing:
        args.missing.write("# missing packages\n")
        pkg_resolver.write_missing_packages(args.expected)

    if args.extra:
        args.extra.write("# extra packages\n")
        if args.why_extra:
            pkg_resolver.write_extra_packages_and_why(args.expected)
        else:
            pkg_resolver.write_extra_packages(args.expected)

    pkg_resolver.cleanup()

    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))


from flask import Flask, make_response, jsonify
from flask.json import jsonify
from flask_restful import Resource, Api

import unioptapi

app = Flask(__name__)
api = Api(app)

class ApiRoot(Resource):
    """
    api controller of the path [/uniopt] which retrieves the api meta information
    """
    def get(self):
        root_data = {
            "name": "uniopt-api",
            "version": unioptapi.__version__
        }
        return make_response(jsonify(root_data), 200)

class ApiVer(Resource):
    """
    api controller of the path [/uniopt/api] which retrieves the api version
    """
    def get(self):
        return make_response(jsonify(unioptapi.__version__), 200)

api.add_resource(ApiRoot, '/uniopt')
api.add_resource(ApiVer, '/uniopt/api')

if __name__ == '__main__':
    app.run(debug=True)


import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
#위에 4줄 한이유는 Atom에서 한글을 출력하지 못하기 떄문에 문제 해결하기 위해 설정한다.

#self 이해하기
class SelfTest():
    def function1():
        print("function1 called!")

    def function2(self):
        print(id(self))
        print("function2 called!")

f = SelfTest()
#print(dir(f))

f.function1() #오류 발생, TypeError: function1() takes 0 positional arguments but 1 was given
f.function2() #성공, 즉 자동으로 뭔가 넘어감...
print(id(f)) #3059900794248  ,  3059900794248 주소값이 일치한다.
#설명: 인스턴스의 주소값이 self에 담겨서 넘어간다. 즉,

#그렇다면 function1을 self없이 접근 하려면?
print(SelfTest.function1())


import datetime
import random
import time
import unittest
import uuid

from pamqp import body, commands, constants, header

from aiorabbit import message

class TestCase(unittest.TestCase):

    def setUp(self) -> None:
        self.exchange = str(uuid.uuid4())
        self.routing_key = str(uuid.uuid4())
        self.app_id = str(uuid.uuid4())
        self.content_encoding = str(uuid.uuid4())
        self.content_type = str(uuid.uuid4())
        self.correlation_id = str(uuid.uuid4())
        self.delivery_mode = random.randint(1, 2)
        self.expiration = str(int(time.time()) + random.randint(60, 300))
        self.headers = {str(uuid.uuid4()): str(uuid.uuid4())}
        self.message_id = str(uuid.uuid4())
        self.message_type = str(uuid.uuid4())
        self.priority = random.randint(0, 255)
        self.reply_to = str(uuid.uuid4())
        self.timestamp = datetime.datetime.now()
        self.user_id = str(uuid.uuid4())
        self.body = b'-'.join(
            [str(uuid.uuid4()).encode('latin-1')
             for _offset in range(0, random.randint(1, 100))])

        self.message = message.Message(self.get_method())
        self.message.header = header.ContentHeader(
            0, len(self.body),
            commands.Basic.Properties(
                app_id=self.app_id,
                content_encoding=self.content_encoding,
                content_type=self.content_type,
                correlation_id=self.correlation_id,
                delivery_mode=self.delivery_mode,
                expiration=self.expiration,
                headers=self.headers,
                message_id=self.message_id,
                message_type=self.message_type,
                priority=self.priority,
                reply_to=self.reply_to,
                timestamp=self.timestamp,
                user_id=self.user_id))

        value = bytes(self.body)
        while value:
            self.message.body_frames.append(
                body.ContentBody(value[:constants.FRAME_MAX_SIZE]))
            value = value[constants.FRAME_MAX_SIZE:]

    def get_method(self):
        raise NotImplementedError

    def compare_message(self):
        for attribute in [
                'exchange', 'routing_key', 'app_id', 'content_encoding',
                'content_type', 'correlation_id', 'delivery_mode',
                'expiration', 'headers', 'message_id', 'message_type',
                'priority', 'reply_to', 'timestamp', 'user_id', 'body']:
            expectation = getattr(self, attribute)
            value = getattr(self.message, attribute)
            if isinstance(expectation, dict):
                self.assertDictEqual(value, expectation)
            else:
                self.assertEqual(value, expectation)
        self.assertEqual(bytes(self.message), self.body)
        self.assertEqual(len(self.message), len(self.body))
        self.assertTrue(self.message.is_complete)

class BasicDeliverTestCase(TestCase):

    def setUp(self) -> None:
        self.consumer_tag = uuid.uuid4().hex
        self.delivery_tag = random.randint(0, 100000000)
        self.redelivered = bool(random.randint(0, 1))
        super().setUp()

    def get_method(self):
        return commands.Basic.Deliver(
            self.consumer_tag, self.delivery_tag, self.redelivered,
            self.exchange, self.routing_key)

    def test_properties(self):
        self.assertEqual(self.message.consumer_tag, self.consumer_tag)
        self.assertEqual(self.message.delivery_tag, self.delivery_tag)
        self.assertEqual(self.message.redelivered, self.redelivered)
        self.assertIsNone(self.message.message_count)
        self.assertIsNone(self.message.reply_code)
        self.assertIsNone(self.message.reply_text)
        self.compare_message()

class BasicGetOkTestCase(TestCase):

    def setUp(self) -> None:
        self.delivery_tag = random.randint(0, 100000000)
        self.message_count = random.randint(0, 1000)
        self.redelivered = bool(random.randint(0, 1))
        super().setUp()

    def get_method(self):
        return commands.Basic.GetOk(
            self.delivery_tag, self.redelivered, self.exchange,
            self.routing_key, self.message_count)

    def test_properties(self):
        self.assertEqual(self.message.delivery_tag, self.delivery_tag)
        self.assertEqual(self.message.message_count, self.message_count)
        self.assertEqual(self.message.redelivered, self.redelivered)
        self.assertIsNone(self.message.reply_code)
        self.assertIsNone(self.message.reply_text)
        self.compare_message()

class BasicReturnTestCase(TestCase):

    def setUp(self) -> None:
        self.reply_code = random.randint(200, 500)
        self.reply_text = str(uuid.uuid4())
        super().setUp()

    def get_method(self):
        return commands.Basic.Return(
            self.reply_code, self.reply_text, self.exchange, self.routing_key)

    def test_properties(self):
        self.assertEqual(self.message.reply_code, self.reply_code)
        self.assertEqual(self.message.reply_text, self.reply_text)
        self.assertIsNone(self.message.consumer_tag)
        self.assertIsNone(self.message.delivery_tag)
        self.assertIsNone(self.message.message_count)
        self.assertIsNone(self.message.redelivered)
        self.compare_message()


"""Module containing helpers to operate with file objects."""
import io
import typing

import magic

class MimeTypeDetectingFileObject(io.RawIOBase):
    """File like class which tries to detect the mimetime as soon as enough data is availabe."""

    def __init__(self, orig_obj: io.RawIOBase,
                 detection_callback: typing.Callable[[str], None], max_buffer_size: int=1024):
        """Init.

        :param orig_obj: the file object to wrap
        :param detection_callback: a function pointer taking a string as argument, called if either
               the max_buffer_size has been read or the file has ended before.
        :param max_buffer_size: maximum data collected to pass to magic
        """
        super().__init__()
        self._orig_obj = orig_obj
        self.read_count = 0

        self.max_buffer_size = max_buffer_size

        # this buffer stores the bytes
        self.buffer = b''

        self.detection_callback = detection_callback
        self.called_back = False

    def read(self, count=None):
        """Pass the read to the orig_obj and tries to find out the mime-type."""
        buffer = self._orig_obj.read(count)

        if len(self.buffer) < self.max_buffer_size and not self.called_back:
            # lets add the buffer
            self.buffer += buffer

        if (len(self.buffer) >= self.max_buffer_size or len(
                buffer) != count) and not self.called_back:
            self.detection_callback(magic.from_buffer(self.buffer, mime=True))
            self.called_back = True
            self.buffer = b''
        return buffer


from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
import matplotlib.lines as mlines
import pandas as pd

def show_animation(series_q,dt):
    q = series_q[:,1:]

    geometrical_parameters=pd.read_excel('geometrical_parameters.xlsx')

    fig = plt.figure()

    #如有必要手动调整坐标轴范围
    ax = fig.add_subplot(111, autoscale_on=False, xlim=(-10,10), ylim=(-10, 10))
    ax.set_aspect('equal')
    ax.grid()

    color=['b','g','r','c','m','y','k']
    lines = [mlines.Line2D([], [], ls='-',color=color[x]) for x in range(geometrical_parameters.shape[0])]

    for line in lines:
        ax.add_line(line)

    def init():
        for line in lines:
            line.set_data([], [])
        return lines

    def animate(i):
        for k, row in geometrical_parameters.iterrows():
            line=lines[k]
            thisx = [q[k*3,i]+row['xl']*cos(q[2+k*3,i]), q[k*3,i]+row['xr']*cos(q[2+k*3,i])]
            thisy = [q[1+k*3,i]+row['xl']*sin(q[2+k*3,i]), q[1+k*3,i]+row['xr']*sin(q[2+k*3,i])]
            line.set_data(thisx, thisy)
        return lines
    # 通过调整dt*3000的系数可以改变快慢，改变range(100)的参数可以改变帧数
    ani = animation.FuncAnimation(fig, animate, range(100),
                                interval=dt*3000, blit=True, init_func=init)
    ani.save("test.gif",writer='pillow')
    plt.show()


# Import modules
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import numpy as np
from torchvision import models, transforms
import matplotlib.pyplot as plt

import itertools
import torchvision.transforms.functional as functional
import torch.nn.functional as F
from collections import Counter
import random
from PIL import Image

# Define classes
# classes = ('normal', 'bacteria', 'TB', 'viral_and_COVID')
classes = ('Normal', 'LCA')

def make_weights_for_balanced_classes_customloader(images_dic, nclasses):
    count = [0] * nclasses
    for image in images_dic:
        count[images_dic[image]] += 1
    weight_per_class = [0.] * nclasses
    N = float(sum(count))
    for i in range(nclasses):
        weight_per_class[i] = N/float(count[i])
    weight = [0] * len(images_dic)
    for idx, image in enumerate(images_dic):
        weight[idx] = weight_per_class[images_dic[image]]
    return weight

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)

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

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

def augmentation(image, rand_p, mode):

    # if mode == 'train':
    #     # random vertical flip
    #     # if rand_p > 0.5:
    #     #     image = functional.hflip(np.asarray(image))
    #     # else:
    #     #     pass
    #     #
    #     # rot_angle = random.randint(-5, 5)
    #     #
    #     # image = functional.rotate(img=Image.fromarray(image), angle=rot_angle)
    #     pass
    # elif mode == 'val':
    #     pass
    # elif mode == 'test':
    #     pass
    # else:
    #     print('Error: not a valid phase option.')
    pass
    return image

def matplotlib_imshow(img, one_channel=False):
    if one_channel:
        img = img.mean(dim=0)
    img = img / 2 + 0.5     # unnormalize
    npimg = np.asarray(img.cpu())
    if one_channel:
        plt.imshow(npimg, cmap="Greys")
    else:
        plt.imshow(np.transpose(npimg, (1, 2, 0)))

def images_to_probs_single(net, images):
    '''
    Generates predictions and corresponding probabilities from a trained
    network and a list of images
    '''
    output = net(images)
    # convert output probabilities to predicted class
    _, preds_tensor = torch.max(output, 1)
    preds = np.asarray(preds_tensor.cpu())
    # preds = np.squeeze(preds_tensor.cpu().numpy())
    return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)]

def plot_classes_preds_single(net, images, labels):
    '''
    Generates matplotlib Figure using a trained network, along with images
    and labels from a batch, that shows the network's top prediction along
    with its probability, alongside the actual label, coloring this
    information based on whether the prediction was correct or not.
    Uses the "images_to_probs" function.
    '''
    preds, probs = images_to_probs_single(net, images)
    # plot the images in the batch, along with predicted and true labels
    fig = plt.figure(figsize=(12, 48))
    for idx in np.arange(4):
        ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[])
        matplotlib_imshow(images[idx], one_channel=True)
        ax.set_title("{0}, {1:.1f}%\n(label: {2})".format(
            classes[preds[idx]],
            probs[idx] * 100.0,
            classes[labels[idx]]),
                    color=("green" if preds[idx]==labels[idx].item() else "red"))
    return fig

def most_common_top_1(candidates):
    assert isinstance(candidates, list), 'Must be a list type'
    if len(candidates) == 0: return None
    return Counter(candidates).most_common(n=1)[0][0]


"""
✔ Напишите функцию, которая принимает строку текста.
Вывести функцией каждое слово с новой строки.
✔ Строки нумеруются начиная с единицы.
✔ Слова выводятся отсортированными согласно кодировки Unicode.
✔ Текст выравнивается по правому краю так, чтобы у самого
длинного слова был один пробел между ним и номером строки.
"""

my_text = "Какая-то строка текста! Для преобразования"

def sort_my_unicode(text):
    lst_sorted = sorted(text.split())
    max_word = len(max(lst_sorted, key=len))
    for element, item in enumerate(lst_sorted, start=1):
        print(f"{element} {item:>{max_word}}")

sort_my_unicode(my_text)

Урок 4. Функции/Семинар/task_1.py


import tkinter as tk

#declare window
window = tk.Tk()
window.title("My Z-Score Calculator")
window.geometry("400x450")
window.configure(background='pink')

#Function

def x_value():
    xVals = int(entry_field1.get())
    meanVals = int(entry_field2.get())
    deviationVals = int (entry_field3.get())
    zScore = float ((xVals - meanVals)/deviationVals)
    return zScore

def zscore_display():
    zScore = x_value()
    calculation_display = tk.Text(master=window, height = 10, width=30)
    calculation_display.grid(column=0,row=13)
    calculation_display.insert(tk.END, zScore)

#LABEL
title = tk.Label(text="Welcome to my Z-Score Calculator App",font=("Comic Sans MS",20),background='pink')
title.grid(row=0, column=0)

#LABEl X Value
label1 = tk.Label(text="Please enter the x value, the score achieved:",font=("Comic Sans", 15, "italic"),background='pink')
label1.grid(row=1, column=0)

#Entry Field
entry_field1 = tk.Entry()
entry_field1.grid(row=2, column=0)

#LABEl mean value
label2 = tk.Label(text="Please enter the mean value of the dataset:",font=("Comic Sans", 15, "italic"),background='pink')
label2.grid(row=3, column=0)

#Entry Field
entry_field2 = tk.Entry()
entry_field2.grid(row=4, column=0)

#LABEl S value
label3 = tk.Label(text="Please enter the s value, the standard deviation:",font=("Comic Sans", 15, "italic"),background='pink')
label3.grid(row=5, column=0)

#Entry Field
entry_field3 = tk.Entry()
entry_field3.grid(row=6, column=0)

#Button
button1 = tk.Button(text="Calculate Z-Score!", command= zscore_display)
button1.grid(row=9, column=0,padx = 10, pady =10 )

#Label
label4 = tk.Label(text="Your Z-Score is...",font=("Comic Sans", 15, "italic"),background='pink')
label4.grid(row=12, column=0)

#run window
window.mainloop()


from ProjectUtility import user32, PROJECT_NAME, STORAGE_SERVER, getDLL
StorageManager = getDLL("StorageManager")
LocalStorage = getattr(StorageManager, "LocalStorage")

from .thread import TaskThread

from PyQt5.QtWidgets import QWidget, QLabel, QProgressBar
from PyQt5.QtCore import Qt, QTimer, pyqtSignal
from PyQt5.QtGui import QIcon, QImage, QPixmap

from PIL import Image
import requests as rq
import random, os, io

def imageToPixmap(im):
    if im.mode == "RGB":
        r, g, b = im.split()
        im = Image.merge("RGB", (b, g, r))
    elif  im.mode == "RGBA":
        r, g, b, a = im.split()
        im = Image.merge("RGBA", (b, g, r, a))
    elif im.mode == "L":
        im = im.convert("RGBA")
    elif im.mode == "P":
        im = im.convert("RGBA")
        r, g, b, a = im.split()
        im = Image.merge("RGBA", (b, g, r, a))
    im2 = im.convert("RGBA")
    data = im2.tobytes("raw", "RGBA")
    qim = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    pixmap = QPixmap.fromImage(qim)
    return pixmap

def loadBytesImage(bstring):
    return Image.open(io.BytesIO(bstring))

class AbstractLoadingWindow(QWidget):
    iconPath = LocalStorage(STORAGE_SERVER, PROJECT_NAME).path(os.path.join("logo", "Filled.png"), True)

    displayLoadingStatusSignal = pyqtSignal()

    _size = int(user32.GetSystemMetrics(1) / 4)
    _padding = int(_size / 10)
    _fontsize = int(_padding / 3)

    def __init__(self):
        super(AbstractLoadingWindow, self).__init__()
        self.status = ["載入中 . . .", 0]
        self.loadingTimer = QTimer(self)
        self.splashArtTimer = QTimer(self)
        self.loadingFunctions = []
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle(f"{PROJECT_NAME}-{self.__class__.__name__}")
        self.setWindowIcon(QIcon(self.iconPath))
        self.resize(self._size*1.65, self._size)
        self.setupComponents()
        self.splashArtTimer.timeout.connect(self.changeBackgroundSplashArt)
        self.splashArtTimer.timeout.emit()
        self.splashArtTimer.setInterval(10000)
        self.splashArtTimer.start()
        self.displayLoadingStatusSignal.connect(self.displayLoadingStatus)

    def notify(self, obj, event):
        error = False
        try:
            super().notify(obj, event)
        except Exception as e:
            error = True
        finally:
            if error: self.close()

    def setLoadingTimer(self, intervalFunction, interval):
        self.loadingTimer.timeout.connect(intervalFunction)
        self.loadingTimer.timeout.emit()
        self.loadingTimer.setInterval(interval)
        self.loadingTimer.start()

    def setupComponents(self):
        self.LoadingSplashArt = QLabel(self)
        self.LoadingSplashArt.setGeometry(0, 0, self.width(), self.height())

        self.LoadingProgress = QProgressBar(self)
        self.LoadingProgress.setRange(0, 100)
        self.LoadingProgress.setTextVisible(False)
        self.LoadingProgress.setOrientation(Qt.Horizontal)
        self.LoadingProgress.move(self._padding, self.height()-(self._padding*2))
        self.LoadingProgress.resize(self.width()-(self._padding*2), self._padding)

        self.LoadingStatus = QLabel(self)
        self.LoadingStatus.setText("載入中 . . .")
        self.LoadingStatus.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.LoadingStatus.font().setPointSize(self._fontsize)
        self.LoadingStatus.setStyleSheet(f"color:#000000;padding:0 {int(self._padding/2)}px;")
        self.LoadingStatus.move(self._padding, self.height()-(self._padding*2))
        self.LoadingStatus.resize(self.width()-(self._padding*2), self._padding)

        self.ProgressLabel = QLabel(self)
        self.ProgressLabel.setText("0%")
        self.ProgressLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.ProgressLabel.font().setPointSize(self._fontsize)
        self.ProgressLabel.setStyleSheet(f"color:#000000;padding:0 {int(self._padding/2)}px;")
        self.ProgressLabel.move(self._padding, self.height()-(self._padding*2))
        self.ProgressLabel.resize(self.width()-(self._padding*2), self._padding)

    def getRandomSplashArt(self):
        LATEST_RDD_VERSION = rq.get("http://ddragon.leagueoflegends.com/api/versions.json").json()[0]
        championJson = rq.get(f"http://ddragon.leagueoflegends.com/cdn/{LATEST_RDD_VERSION}/data/zh_TW/champion.json").json()
        championNames = list(championJson["data"].keys())
        random.shuffle(championNames)
        for champion in championNames:
            try:
                data = rq.get(f"http://ddragon.leagueoflegends.com/cdn/{LATEST_RDD_VERSION}/data/en_US/champion/{champion}.json").json()
                skin = random.choice(data["data"][champion]["skins"])["num"]
                data = rq.get(f"http://ddragon.leagueoflegends.com/cdn/img/champion/splash/{champion}_{skin}.jpg")
            except Exception as e:
                continue
            return data.content

    def changeBackgroundSplashArt(self):
        splashArtByte = self.getRandomSplashArt()
        if(splashArtByte):
            splashArtLabelGeometry = self.LoadingSplashArt.frameGeometry()
            splashArt = loadBytesImage(splashArtByte)
            splashArtWidth, splashArtHeight = splashArt.size
            if(int(splashArtHeight * (splashArtLabelGeometry.width()/splashArtWidth)) >= splashArtLabelGeometry.height()):
                resizeRatio = (splashArtLabelGeometry.width()/splashArtWidth)
            else: resizeRatio = (splashArtLabelGeometry.height()/splashArtHeight)
            splashArtTargetSize = (int(splashArtWidth*resizeRatio), int(splashArtHeight*resizeRatio))
            resizedSplashArt = splashArt.resize(splashArtTargetSize)
            pixmap = imageToPixmap(resizedSplashArt)
            self.LoadingSplashArt.setPixmap(pixmap)

    def updateLoadingStatus(self, status=None, progress=None):
        if(isinstance(status, str)): self.status[0] = status
        if(isinstance(progress, int)): self.status[1] = progress
        return True

    def displayLoadingStatus(self):
        self.LoadingStatus.setText(self.status[0])
        self.LoadingStatus.repaint()
        self.ProgressLabel.setText(f"{self.status[1]}%")
        self.ProgressLabel.repaint()
        self.LoadingProgress.setValue(self.status[1])
        self.LoadingProgress.repaint()

    def startLoadingIndex(self, idx):
        if(idx < len(self.loadingFunctions)):
            self.displayLoadingStatusSignal.emit()
            self.loadingThreadWorker = TaskThread(
                target=self.loadingFunctions[idx],
                delay=0.1,
                tries=10,
                onFinished=lambda i=idx+1:self.startLoadingIndex(i)
            ).start()
        else: self.close()

    def startLoading(self):
        self.startLoadingIndex(0)
        self.setLoadingTimer(self.displayLoadingStatusSignal.emit, 1000)

    def closeEvent(self, e):
        self.loadingTimer.stop()
        super().closeEvent(e)
        os._exit(0)

    def showEvent(self, e):
        super().showEvent(e)
        self.move(
            int((user32.GetSystemMetrics(0)-self.width())/2),
            int((user32.GetSystemMetrics(1)-self.height())/2)
        )


# imports - general
import time

# imports - linguistic
import re
import spacy
from scispacy.abbreviation import AbbreviationDetector

nlp = spacy.load("en_core_sci_sm")
# Add the abbreviation detector to spacy pipeline
nlp.add_pipe("abbreviation_detector")

'''
Description:
    The function removes trailing spaces from a string and replaces them with a single string

Args:
    string (str): free-text string

Returns:
    string (str): clean string
'''
def removeSpaceTrailsString(s):
    return " ".join(s.split())

'''
Description:
    The function extracts acronyms using Scispacy abbreviation detector

Args:
    string (str): free-text string

Returns:
    List (list): tuple with detected abbreviation and the long form of the abbreviation
'''
def fetchAcronyms(value):

    doc = nlp(value)

    altered_tok = [tok.text for tok in doc]

    abbreviations = []

    for abrv in doc._.abbreviations:
        altered_tok[abrv.start] = str(abrv._.long_form)

        # print(f"{abrv} \t ({abrv.start}, {abrv.end}) {abrv._.long_form} \t  {value}")
        # print( " ".join(altered_tok) )

        abbreviations.append( str(abrv) )
        abbreviations.append( str(abrv._.long_form) )
        # original = str(abrv._.long_form) + ' (' + str(abrv) + ')'
        # abbreviations.append( original  )

    if abbreviations:
        return abbreviations

'''
Description:
    The function fetches POS tags for the input string

Args:
    String: free-text string

Returns:
    Dictionary (dict): returns a dictionary containing free-text string with its tokenized string, token lemma, POS tags for the tokens, finer POS tags for the token
'''
def getPOStags(value):

    doc = nlp(value)

    pos_dict = dict()

    tokens = [ token.text for token in doc ]
    lemma = [ token.lemma_ for token in doc ]
    pos = [ token.pos_ for token in doc ]
    pos_fine = [ token.tag_ for token in doc ]
    depth = [ token.dep_ for token in doc ]
    shape = [ token.shape_ for token in doc ]
    is_alpha = [ token.is_alpha for token in doc ]
    is_stop = [ token.is_stop for token in doc ]

    pos_dict['text'] = value
    pos_dict['tokens'] = tokens
    pos_dict['lemma'] = lemma
    pos_dict['pos'] = pos
    pos_dict['pos_fine'] = pos_fine

    return pos_dict

'''
TODO
Description:

Args:
    Dictionary (dict): free-text string
        value (string):
        key (string):

Returns:
    Dictionary (dict):
'''
def appendPOSSED(expanded_dictionary, values, key):

    for value_i in values:
        possed_value = getPOStags(value_i)
        if key not in expanded_dictionary:
            expanded_dictionary[key] = [possed_value]
        else:
            expanded_dictionary[key].append( possed_value )

    return expanded_dictionary


a,b=2,4
n=b

prime=[True for i in range(n+1)]
i=2
while(i*i<=n):
    if(prime[i]==True):
        for j in range(i*i,n+1,i):
            prime[j]=False
    i+=1
prime_val=[]
for i in range(2,n+1):
    if(prime[i]==True ):
        prime_val.append(i)
prime_real_val=[]
for i in prime_val:
    if(i>=a and i<=b):
        prime_real_val.append(i)
print(len(prime_real_val))


'''
Runtime : 24 ms(100.00%)
Memory : 14.8 MB(79.52%)
문제 정말 쉬웠다. Modulo 연산 사용 안하려고 노력했다
'''
class Solution:
    def fizzBuzz(self, n):
        result = [str(x) for x in range(1, n + 1)]

        if n >= 3:
            for i in range(2, n, 3):
                result[i] = 'Fizz'

        if n >= 5:
            for i in range(4, n, 5):
                if result[i] == 'Fizz':
                    result[i] += 'Buzz'
                else:
                    result[i] = 'Buzz'

        return result