dados = list()
pessoa = dict()
soma = media = 0
while True:
    pessoa.clear
    pessoa['nome'] = str(input('Nome:'))
    while True:
        pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper()[0]
        if pessoa['sexo'] in 'MF':
            break
        print('ERRO! Por favor, digite apenas M ou F')
    pessoa['idade'] = int(input('Idade: '))
    soma += pessoa['idade']
    dados.append(pessoa.copy())
    while True:
        cont = str(input('Quer continuar? ')).upper()[0]
        if cont in 'SN':
            break
        print('ERRO! Responda apenas S ou N')
    if cont == 'N':
        break
print('-' * 30)
print(f'A) Ao todo temos {len(dados)} pessoas cadastradas')
media = soma / len(dados)
print(f'B) A média de idade é de {media:5.2f} anos')
print('C) As mulheres cadastradas foram ', end='')
for p in dados:
    if p['sexo'] == 'F':
        print(f'{p["nome"]} ', end='')
print()
print(f'D) Lista de pessoas que estão acima da média: ' )
for p in dados:
    if p['idade'] >= media:
        print('    ', end='')
        for k, v in p.items():
            print(f'{k} = {v}; ', end='')
        print()
print('<< ENCERRADO >>')


class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        foundL, foundR = -1, -1

        left, right = 0, n # search left pos
        while left < right:
            mid = (left+right) // 2
            # 找到 target 时不要立即返回，而是缩小“搜索区间”的上界 right，
            # 在区间 [left, mid) 中继续搜索，即不断向左收缩，达到锁定左侧边界的目的
            if target == nums[mid]:
                right = mid

            elif target < nums[mid]:
                right = mid

            elif target > nums[mid]:
                left = mid+1

        if left < n and nums[left] == target:
            foundL = left

        left, right = 0, n # search right pos
        while left < right:
            mid = (left+right) // 2
            if target == nums[mid]:
                # 当 nums[mid] == target 时，不要立即返回，
                # 而是增大“搜索区间”的左边界 left，使得区间不断向右靠拢，达到锁定右侧边界的目的
                left = mid+1

            elif target < nums[mid]:
                right = mid

            elif target > nums[mid]:
                left = mid+1

        # 因为我们对 left 的更新必须是 left = mid + 1，就是说 while 循环结束时，nums[left] 一定不等于 target 了，而 nums[left-1] 可能是 target。
        # 至于为什么 left 的更新必须是 left = mid + 1，当然是为了把 nums[mid] 排除出搜索区间，这里就不再赘述。
        if right-1 >= 0 and nums[right-1] == target:
            foundR = right-1

        return [foundL, foundR]

binary-search/34. Find First and Last Position of Element in Sorted Array.py


from collections import deque

def solution(rc, operations):
    answer = []
    # 안녕하세요
    top = deque([])
    bottom = deque([])
    left = deque([])
    right = deque([])
    center = deque([])
    for i in range(len(rc)):
        line = rc[i]
        left.append(line[0])
        right.append(line[-1])
        if i == 0:
            top = deque(line[1:-1])
        elif i == len(rc)-1:
            bottom = deque(line[1:-1])
        else:
            center.append(deque(line[1:-1]))

    def shift_row():
        nonlocal top, bottom, left, right, center
        left.appendleft(left.pop())
        right.appendleft(right.pop())
        center.appendleft(top)
        top = bottom
        bottom = center.pop()

    def rotate():
        nonlocal top, bottom, left, right
        top.appendleft(left.popleft())
        right.appendleft(top.pop())
        bottom.append(right.pop())
        left.append(bottom.popleft())

    for operation in operations:
        if operation == 'ShiftRow':
            shift_row()
        else:
            rotate()
    top.appendleft(left[0])
    top.append(right[0])
    answer.append(list(top))
    for i in range(len(center)):
        line = center[i]
        line.appendleft(left[i+1])
        line.append(right[i+1])
        answer.append(list(line))
    bottom.appendleft(left[-1])
    bottom.append(right[-1])
    answer.append(list(bottom))
    print(answer)
    return answer

solution([[1, 2], [3, 4], [5, 6]], ["Rotate", "ShiftRow"])


#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      CHRISTOPHER_IRWIN
#
# Created:     22/01/2013
# Copyright:   (c) CHRISTOPHER_IRWIN 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import string

s = "map"
t = ""
alphafrom = ""
alphato = ""
for x in range(97,123):
    alphafrom += chr(x)

print(alphafrom)

for x in range(99,125):
    alphato += chr(x)

alphato = alphato.replace(chr(123),chr(97))
alphato = alphato.replace(chr(124),chr(98))

alphadict = dict()

for i,c in enumerate(alphafrom):
    alphadict[c] = alphato[i]

print(alphato)

for c in s:
    if c in string.ascii_lowercase:
        t+=alphadict[c]
    else:
        t+=c

print(t)


from chapter_10.dqn import *

class SumTree:
    write = 0
    def __init__(self, capacity):
        self.capacity = capacity
        self.nodes = np.zeros(2 * capacity - 1)
        self.data = np.zeros(capacity, dtype=object)
        self.n_entries = 0

    def _propagate(self, idx, change):
        parent = (idx - 1) // 2
        self.nodes[parent] += change
        if parent != 0:
            self._propagate(parent, change)

    def _retrieve(self, idx, s):
        left = 2 * idx + 1
        right = left + 1
        if left >= len(self.nodes):
            return idx
        if s <= self.nodes[left]:
            return self._retrieve(left, s)
        else:
            return self._retrieve(right, s - self.nodes[left])

    def total(self):
        return self.nodes[0]

    def add(self, data, priority):
        idx = self.write + self.capacity - 1
        self.data[self.write] = data
        self.update(idx, priority)
        self.write += 1
        if self.write >= self.capacity:
            self.write = 0
        if self.n_entries < self.capacity:
            self.n_entries += 1

    def update(self, idx, priority):
        change = priority - self.nodes[idx]
        self.nodes[idx] = priority
        self._propagate(idx, change)

    def get(self, s):
        idx = self._retrieve(0, s)
        data_idx = idx - self.capacity + 1
        priority = self.nodes[idx]
        return idx, self.data[data_idx], priority

class PrioritizedExperienceReplayMemory:  # stored as ( s, a, r, s', p ) in SumTree
    e = 0.001
    alpha = 0.6
    beta = 0.4
    beta_increment_per_sampling = 0.001

    def __init__(self, capacity):
        self.__name__ = "Prioritized Experience Replay Memory"
        self.capacity = capacity
        self.sum_tree = SumTree(capacity)

    def reset(self):
        self.sum_tree = SumTree(self.capacity)

    def _getPriority(self, error):
        return (error + self.e) ** self.alpha

    def put(self, transition, error=10000.0):
        priority = self._getPriority(error)
        self.sum_tree.add(transition, priority)

    def size(self):
        return self.sum_tree.n_entries

    def get_random_batch(self, size):
        priorities = []
        batch = []
        idxs = []

        num_segment = self.sum_tree.total() / size

        self.beta = np.min([1., self.beta + self.beta_increment_per_sampling])

        for i in range(size):
            a = num_segment * i
            b = num_segment * (i + 1)

            s = random.uniform(a, b)
            idx, transition, priority = self.sum_tree.get(s)
            priorities.append(priority)
            batch.append(transition)
            idxs.append(idx)

        sampling_probabilities = priorities / self.sum_tree.total()
        is_weight = np.power(self.sum_tree.n_entries * sampling_probabilities, -self.beta)
        is_weight /= is_weight.max()

        return batch, idxs, is_weight

    def update_priority(self, idx, error):
        priority = self._getPriority(error)
        self.sum_tree.update(idx, priority)

class PerDqnAgent(DqnAgent):
    def __init__(self, env, args):
        super().__init__(env, args)
        self.__name__ = "per_dqn"
        self.buffer = PrioritizedExperienceReplayMemory(args.replay_memory_capacity)

    def q_net_optimize(self):
        batch, idxs, is_weight = self.buffer.get_random_batch(self.args.batch_size)
        states, actions, rewards, next_states, dones = map(np.asarray, zip(*batch))

        # Nature DQN
        next_q_values = np.where(dones, 0, np.max(self.target_q_net.forward(next_states), axis=1))
        target_q_values = np.where(dones, rewards, rewards + self.args.gamma * next_q_values)

        with tf.GradientTape() as tape:
            current_q_values = tf.math.reduce_sum(
                self.train_q_net.forward(states) * tf.one_hot(actions, self.action_dim), axis=1
            )
            loss = tf.math.reduce_mean(tf.square(target_q_values - current_q_values) * is_weight)

        # td_error로 우선순위 업데이트
        self.buffer_update(target_q_values, current_q_values, idxs)

        # train_q_net 가중치 갱신
        variables = self.train_q_net.trainable_variables
        gradients = tape.gradient(loss, variables)

        self.optimizer.apply_gradients(zip(gradients, variables))

        return loss.numpy()

    def buffer_update(self, target_q_values, current_q_values, idxs):
        td_error = np.abs(target_q_values - current_q_values)
        for i in range(self.args.batch_size):
            idx = idxs[i]
            self.buffer.update_priority(idx, td_error[i])

def prioritized_experience_memory_test():
    memory = PrioritizedExperienceReplayMemory(capacity=4)
    memory.put(transition="A")
    memory.put(transition="B", error=2.0)
    memory.put(transition="C", error=3.0)
    memory.put(transition="D", error=100.0)
    c = memory.get_random_batch(10)
    print(memory)
    print(c)

def train(args):
    env = gym.make(args.env)

    per_dqn_agent = PerDqnAgent(env, args)
    per_dqn_agent.print_q_network_and_replay_memory_type()
    per_dqn_agent.learn()
    per_dqn_agent.save_model()

def play(args):
    env = gym.make(args.env)

    per_dqn_agent2 = PerDqnAgent(env, args)
    per_dqn_agent2.save_model()
    execution(env, per_dqn_agent2)

def main():
    args = argument_parse()
    print_args(args)

    train(args)

    # 테스트시에는 CartPole-v1을 사용하여 테스트
    # CartPole-v1의 MAX 스텝: 500 vs. CartPole-v0의 MAX 스텝: 200
    args.env = 'CartPole-v1'
    play(args)

if __name__ == "__main__":
    #prioritized_experience_memory_test()
    main()


import json
import sys
import warnings
import csv
import fncs
from ppcasefile import ppcasefile
import pypower.api as pp
import math
import re

def defaultinitilization():

    return 0

def initAuction(auctionDict):

    return 0

def check_voltage(voltage_list):
	LeastVoltage = 2401.7771
	HighestVoltage = 0.0
	#phase = voltage_list[0][1]
	for item in voltage_list:
		if item[2] < LeastVoltage:
			LeastVoltage = item[2]
	for item in voltage_list:
		if item[2] > HighestVoltage:
			HighestVoltage = item[2]
	if LeastVoltage < (0.9*2401.7771):
		Adjust_tap = 1
	elif HighestVoltage > (1.1*2401.7771):
		Adjust_tap = -1
	else:
		Adjust_tap = 0
	return Adjust_tap

def monitor_powerflow(power_listz,power_maximum):
	for power_list in power_listz:
		for i in range(15):
			#print(power_list)
			if ((power_list[0]==node_index[i]) and (power_list[1]==phase_index[i])):

				if (power_list[2]>power_maximum):
					for j in range(12):
						fncs.publish('house_'+str(i+1)+'_'+str(j+1), ThermostatMode_action)
				else:
					for j in range(12):
						fncs.publish('house_'+str(i+1)+'_'+str(j+1), ThermostatMode_default)
	return 0
def monitor_energyflow():
	return 0

    # ====================extract float from string ===============================
def get_num(self,fncs_string):
    return float(''.join(ele for ele in fncs_string if ele.isdigit() or ele == '.'))
def get_number(value):
        return float(''.join(ele for ele in value if ele.isdigit() or ele == '.'))

def subscribeVal(fncs_sub_value_String):
    # Assign values to buyers
    #P = []
    #Pi = []
    if "controller" in fncs_sub_value_String:
        controllerKeys = list (fncs_sub_value_String['controller'].keys())
        print('checking controllerKeys length', len(controllerKeys), flush = True)
        for i in range(len(controllerKeys)):
            #print('checking controller length', len(controller['name']), flush = True)
            for j in range(len(controller['name'])):
                #print('checking if condition: ', controller['name'][j], controllerKeys[i], flush = True)
                if controller['name'][j] == controllerKeys[i]:
                    print('air temperature: ', fncs_sub_value_String['controller'][controllerKeys[i]]['air_temperature'], flush=True)
                    controller['air_temperature'][j] = fncs_sub_value_String['controller'][controllerKeys[i]]['air_temperature']
                    Pi.append(controller['theta'][j] * fncs_sub_value_String['controller'][controllerKeys[i]]['air_temperature'])
                    P.append(controller['P'][j])
                    #print('P value: ', controller['P'][j], flush=True)
                    #print('Pi value: ', controller['theta'][j] * fncs_sub_value_String['controller'][controllerKeys[i]]['air_temperature'], flush=True)
                    #print('Pi vector: ', Pi)
                #print('Pi val: ', Pi, flush= True)
        #print('P val: ', P, flush=True)
    return 0

def calClearPrice(error, Pi):
    sum = 0
    #[Pi_sorted, indexlist] = sort_prices(Pi)
    indexlist = []
    CP = 1.0
    sortedlist = sorted(enumerate(Pi), key = lambda x: x[1])
    print('printing sorted list:', sortedlist, flush = True)
    for i in sortedlist:
        indexlist.append(i[0])
        Pi_sorted.append(i[1])
    print('printing index list:', indexlist, flush = True)
    print('printing Pi_sorted list:', Pi_sorted, flush = True)

    for i in range(len(indexlist)):
        P_sorted.append(P[indexlist[i]])
    print('printing P_sorted list:', P_sorted, flush = True)

    for i in range(len(P_sorted)):
        sum = sum + P_sorted[i]
        print('printing sum:', sum, error, flush = True)
        if sum >= error:
            print('printing sum again:', sum, error, Pi_sorted[i], flush = True)
            CP = Pi_sorted[i]
            return Pi_sorted[i]
    return CP

def sort_prices(Pi):
	valueslist = []
	indexlist =[]
	sortedlist = sorted(enumerate(Pi), key = lambda x: x[1])
	for i in sortedlist:
		indexlist.append(i[0])
		valueslist.append(i[1])
	print('Values list: ', valueslist, flush=True)
	return [valueslist, indexlist]

def publish_Price(value):
	#print('checking before updation',fncs_publish['auction'][market['name']]['price_cap']['propertyValue'], flush = True)
	fncs_publish['auction'][market['name']]['market_id']['propertyValue'] = 1
	fncs_publish['auction'][market['name']]['std_dev']['propertyValue'] = 0.01
	fncs_publish['auction'][market['name']]['average_price']['propertyValue'] = 0.02078
	fncs_publish['auction'][market['name']]['clear_price'] = value
	fncs_publish['auction'][market['name']]['price_cap']['propertyValue'] = 3.78
	fncs_publish['auction'][market['name']]['period']['propertyValue'] = 300
	fncs_publish['auction'][market['name']]['initial_price']['propertyValue'] = 0.02078

	fncs_publishString = json.dumps(fncs_publish)
	fncs.agentPublish(fncs_publishString)
	fncs.publish('clear_price', value)
	# for i in range(15):
		# for j in range(12):
			# print('publishing WP: ', value,flush = True)
			# fncs.publish('clear_price'+'_'+'house_'+str(i+1)+'_'+str(j+1), value)
	return 0

tapA = 0
tapB = 0
tapC = 0
voltage_listA=[]
voltage_listB=[]
voltage_listC=[]

power_listA=[]
power_listB=[]
power_listC=[]
energy_listA = []
energy_listQ = []
WP = [0.0 for i in range(24)]
WRP = [0.0 for i in range(24*60)]
delTWRP = 60
delTAuction = 1

with warnings.catch_warnings():
	warnings.simplefilter("ignore") # TODO - pypower is using NumPy doubles for integer indices
	#warnings.filterwarnings("ignore",category=DeprecationWarning)
	stats = {'stat_mode': [], 'interval': [], 'stat_type': [], 'value': [], 'statistic_count': 0}
	market = {'name': 'none',' period': -1, 'latency': 0, 'market_id': 1, 'network': 'none', 'linkref': 'none', 'pricecap': 0.0,
					'special_mode': 'MD_NONE', 'statistic_mode': 1, 'fixed_price': 50.0, 'fixed_quantity': 0.0,
					'init_price': 0.0, 'init_stdev': 0.0, 'future_mean_price': 0.0, 'use_future_mean_price': 0,
					'capacity_reference_object': {'name': 'none', 'capacity_reference_property': 0.0, 'capacity_reference_bid_price': 0.0,
                                                 'max_capacity_reference_bid_quantity': 0.0, 'capacity_reference_bid_quantity': 0.0},
					'current_frame': {'start_time': 0.0, 'end_time': 0.0, 'clearing_price':0.0, 'clearing_quantity': 0.0, 'clearing_type': 'CT_NULL',
                                      'marginal_quantity': 0.0, 'total_marginal_quantity': 0.0, 'marginal_frac': 0.0, 'seller_total_quantity': 0.0,
                                      'buyer_total_quantity': 0.0, 'seller_min_price': 0.0, 'buyer_total_unrep': 0.0, 'cap_ref_unrep': 0.0,
                                      'statistics': []},
					'past_frame': {'start_time': 0.0, 'end_time': 0.0, 'clearing_price':0.0, 'clearing_quantity': 0.0, 'clearing_type': 'CT_NULL',
                                      'marginal_quantity': 0.0, 'total_marginal_quantity': 0.0, 'marginal_frac': 0.0, 'seller_total_quantity': 0.0,
                                      'buyer_total_quantity': 0.0, 'seller_min_price': 0.0, 'buyer_total_unrep': 0.0, 'cap_ref_unrep': 0.0,
                                      'statistics': []},
					'cleared_frame': {'start_time': 0.0, 'end_time': 0.0, 'clearing_price':0.0, 'clearing_quantity': 0.0, 'clearing_type': 'CT_NULL',
                                      'marginal_quantity': 0.0, 'total_marginal_quantity': 0.0, 'marginal_frac': 0.0, 'seller_total_quantity': 0.0,
                                      'buyer_total_quantity': 0.0, 'seller_min_price': 0.0, 'buyer_total_unrep': 0.0, 'cap_ref_unrep': 0.0,
                                      'statistics': []},
					'margin_mode': 'AM_NONE', 'ignore_pricecap': 0,'ignore_failedmarket': 0, 'warmup': 1,
					'total_samples': 0,'clearat': 0,  'clearing_scalar': 0.5, 'longest_statistic': 0.0}

	market_output = {'std': -1, 'mean': -1, 'clear_price': -1, 'market_id': 'none', 'pricecap': 0.0} # Initialize market output with default values
	buyer = {'name': [], 'price': [], 'quantity': [], 'state': [], 'bid_id': []}
	seller = {'name': [], 'price': [], 'quantity': [], 'state': [], 'bid_id': []}
	nextClear = {'from':0, 'quantity':0, 'price':0}
	offers = {'name': [], 'price': [], 'quantity': []}
	controller = {'name': [], 'price': [], 'quantity': [], 'state': [], 'Tbliss': [], 'd': [], 'theta': [], 'P': [], 'houseType': [], 'air_temperature': []}
	housedata = {'name': 'none', 'air_temperature': 78, 'state': 'ON', 'Tbliss': 75, 'd': 10, 'theta': 1.0, 'P': 2.1, 'houseType': 'none', 'price': 0.0, 'quantity': 0.0}
	housedataArray = []
	PControlSignal = 10

	if len(sys.argv) == 6:
		filename = sys.argv[1]
		rootname = sys.argv[2]
		StartTime = sys.argv[3]
		tmax = int(sys.argv[4])
		dt = int(sys.argv[5])
	elif len(sys.argv) == 1:
		rootname = 'ppcase'
		StartTime = "2013-07-01 00:00:00"
		dt = 3600
		tmax = 2 * 24 * 3600
	else:
		print ('usage: python fncsPYPOWER.py [rootname StartTime tmax dt]')
		sys.exit()
	lp = open(filename).read()
	auctionDict = json.loads(lp)
	agentRegistration = auctionDict['registration']
	agentInitialVal = auctionDict['initial_values']
	print('Market Name', agentRegistration['agentName'], market['name'], flush = True)
	market['name'] = agentRegistration['agentName']
	print('Market Name', agentRegistration['agentName'], market['name'], flush = True)
	# Read and assign initial values from agentInitialVal
	# Market information
	market['special_mode'] = agentInitialVal['market_information']['special_mode']
	market['market_id'] = agentInitialVal['market_information']['market_id']
	market['use_future_mean_price'] = agentInitialVal['market_information']['use_future_mean_price']
	market['pricecap'] = agentInitialVal['market_information']['pricecap']
	market['clearing_scalar'] = agentInitialVal['market_information']['clearing_scalar']
	market['period'] = agentInitialVal['market_information']['period']
	market['latency'] = agentInitialVal['market_information']['latency']
	market['init_price'] = agentInitialVal['market_information']['init_price']
	market['init_stdev'] = agentInitialVal['market_information']['init_stdev']
	market['ignore_pricecap'] = agentInitialVal['market_information']['ignore_pricecap']
	market['ignore_failedmarket'] = agentInitialVal['market_information']['ignore_failedmarket']
	market['statistic_mode'] = agentInitialVal['market_information']['statistic_mode']
	market['capacity_reference_object']['name'] = agentInitialVal['market_information']['capacity_reference_object']
	market['capacity_reference_object']['max_capacity_reference_bid_quantity'] = agentInitialVal['market_information']['max_capacity_reference_bid_quantity']

    # Stats information
	stats['stat_mode'] = agentInitialVal['statistics_information']['stat_mode']
	stats['interval'] = agentInitialVal['statistics_information']['interval']
	stats['stat_type'] = agentInitialVal['statistics_information']['stat_type']
	stats['value'] = agentInitialVal['statistics_information']['value']

    # Controller information
	controller['name'] = agentInitialVal['controller_information']['name']
	controller['price'] = agentInitialVal['controller_information']['price']
	controller['quantity'] = agentInitialVal['controller_information']['quantity']
	controller['state'] = agentInitialVal['controller_information']['state']
	print('check Tbliss:', agentInitialVal['controller_information']['Tbliss'], flush = True)
	controller['Tbliss'] = agentInitialVal['controller_information']['Tbliss']
	controller['d'] = agentInitialVal['controller_information']['d']
	controller['theta'] = agentInitialVal['controller_information']['theta']
	controller['P'] = agentInitialVal['controller_information']['P']
	controller['houseType'] = agentInitialVal['controller_information']['houseType']
	controller['air_temperature'] = agentInitialVal['controller_information']['air_temperature']

	RealPowerkWh = {}
	for i in range(len(controller['name'])):
		S = controller['name'][i].split('_thermostat_controller')
		RealPowerkWh[S[0]] = {'real_power_kWh' : 0.0, 'energybillmin': 0.0, 'Prev_real_power_kWh' : 0.0}
	print('Realpowerkwhhouse: ', RealPowerkWh, flush=True)
	for i in range(0,len(agentInitialVal)):
		s = agentInitialVal['controller_information']['name'][i]
		print('s', s, flush = True)
		housedata['name'] = s
		housedata['price'] = agentInitialVal['controller_information']['price'][i]
		housedata['quantity'] = agentInitialVal['controller_information']['quantity'][i]
		housedata['state'] = agentInitialVal['controller_information']['state'][i]
		housedata['Tbliss'] = agentInitialVal['controller_information']['Tbliss'][i]
		housedata['d'] = agentInitialVal['controller_information']['d'][i]
		housedata['theta'] = agentInitialVal['controller_information']['theta'][i]
		housedata['P'] = agentInitialVal['controller_information']['P'][i]
		housedata['houseType'] = agentInitialVal['controller_information']['houseType'][i]
		housedata['air_temperature'] = agentInitialVal['controller_information']['air_temperature'][i]
		housedataArray.append(housedata)

    # Generate agent publication dictionary
	fncs_publish = {
		'auction': {
			market['name']: {
				'market_id': {'propertyType': 'integer', 'propertyUnit': 'none', 'propertyValue': 0},
				'std_dev': {'propertyType': 'integer', 'propertyUnit': 'none', 'propertyValue': 0.0},
				'average_price': {'propertyType': 'double', 'propertyUnit': 'none', 'propertyValue': 0.0},
				'clear_price': {'propertyType': 'double', 'propertyUnit': 'none', 'propertyValue': 0.0},
				'price_cap': {'propertyType': 'integer', 'propertyUnit': 'none', 'propertyValue': 0.0},
				'period': {'propertyType': 'double', 'propertyUnit': 'none', 'propertyValue': -1.0},
				'initial_price':{'propertyType': 'double', 'propertyUnit': 'none', 'propertyValue': 0.0}
				}
			}
		}
	fncs_publish['auction'][market['name']]['clear_price'] = 0.002
	fncs.publish('clear_price', 0.002)
	ts = 0
	tnext = 0
	tnextBill = 300
	dtBill = 300 #2592000
	MonthlyBill = 20
	fncs.initialize()
	iter = 1

#	ts = -dt
#	while ts <= tmax:
#		ts += dt
	p = 0.0167
	a = 0.004
	c = -1
	while ts <= tmax:
		print ("looping", ts, tnext, tmax, flush=True)
		# if ts >= tnext:
			# c = c + 1
			# fncs.publish('LMP_B7', 0.0157)
			# tnext += dt
			# if tnext > tmax:
				# print ('breaking out at',tnext,flush=True)
				# break
		if ts >= tnextBill:
			fncs.publish('MonthlyBill', MonthlyBill)
			tnextBill += dtBill
			if tnextBill > tmax:
				print ('breaking out at',tnextBill,flush=True)
				break
		tnext += delTAuction
		ts = fncs.time_request(tnext)
		fncs_sub_value_unicode = (fncs.agentGetEvents()).decode()
		if fncs_sub_value_unicode != '':
			#Global variables
			P = []
			Pi = []
			P_sorted = []
			Pi_sorted = []
			fncs_sub_value_String = json.loads(fncs_sub_value_unicode)
			subscribeVal(fncs_sub_value_String)
			#printing data to test sorting:
			#print('Pi values: ', Pi, flush=True)
			#print('P values: ', P, flush=True)
			#print('Clear Price: ', calClearPrice(100,Pi), flush = True)
			#print('Pi_sorted values: ', Pi_sorted, flush=True)
		events = fncs.get_events()
		for key in events:
			title = key.decode()
			value = fncs.get_value(key).decode()
			if title.startswith('RealPowerkWh'):
				S = title.split('#')
				RealPowerkWh[S[1]]['real_power_kWh']= get_number(value)
				print ('RealPowerkWh: ',RealPowerkWh[S[1]]['real_power_kWh'], flush = True)
				if ts % delTWRP == 0:
					for i in range(len(RealPowerkWh)):
						if ts!=0:
							# print ('checking..', RealPowerkWh[S[1]]['energybillmin'], flush = True)
							# print ('checking..', RealPowerkWh[S[1]]['Prev_real_power_kWh'], flush = True)
							# print ('checking..', RealPowerkWh[S[1]]['real_power_kWh'], flush = True)
							# print ('checking..', iter, flush = True)
							# print ('checking..', WRP[iter-1], flush = True)
							RealPowerkWh[S[1]]['energybillmin'] = RealPowerkWh[S[1]]['energybillmin'] + WRP[iter-1] * (RealPowerkWh[S[1]]['real_power_kWh'] - RealPowerkWh[S[1]]['Prev_real_power_kWh'])
							iter += 1
							if iter > 24*60:
								iter = 1
							RealPowerkWh[S[1]]['Prev_real_power_kWh'] = RealPowerkWh[S[1]]['real_power_kWh']
					print('printing WRP', WRP[iter], flush = True)
					publish_Price(WRP[iter])
				#fncs.publish('ResetRealPower', 0)
			if title.startswith('tap'):
				if title == 'tapA':
					tapA = int(value)
				elif title == 'tapB':
					tapB = int(value)
				elif title == 'tapC':
					tapC = int(value)
				#print('tapABC', tapA, tapB, tapC, flush = True)
			# price
			if title.startswith('Error'):
				ErrorSignal = float(value)
				Pi_Cleared = calClearPrice(ErrorSignal,Pi)
				print('Pi_sorted values: ', Pi_sorted, flush=True)
				print('Clear Price: ', Pi_Cleared, flush = True)
				#publish_Price(Pi_Cleared)
			if title.startswith('WholesalePriceDAM'):
				WP = value
				WRP = [i for i in WP for j in range(60)]
				#publish_Price(float(value))
				#print('checking outside method',fncs_publish['auction'][market['name']]['price_cap']['propertyValue'], flush = True)
			# if title.startswith('WP'):
				# print('wp:price',value,flush = True)
				# fncs.publish('WP', value)
				#publish_WP(value)
			# voltage
			#fncs.publish('LMP_DSO', 0.0164)
			if title.startswith('voltage'):
				if value.endswith('V'):
					valuesplit = value.split(' ')
					valuedecoded = valuesplit[0]
					valuecomplex = complex(valuedecoded)
					absvalue = abs(valuecomplex)
					#print('Split: ', valuecomplex, absvalue, flush = True)
				if title[-2:]=='AN':
					if len(voltage_listA)>0:
						for item in voltage_listA:
							if item[0]==title[-5:-2]:
								item[2] = absvalue
							else:
								voltage_listA.append([title[-5:-2], title[-2:], absvalue])
					else:
						voltage_listA.append([title[-5:-2], title[-2:], absvalue])
	#				node_listA.append()
				if title[-2:]=='BN':
					if len(voltage_listB)>0:
						for item in voltage_listB:
							if item[0]==title[-5:-2]:
								item[2] = absvalue
							else:
								voltage_listB.append([title[-5:-2], title[-2:], absvalue])
					else:
						voltage_listB.append([title[-5:-2], title[-2:], absvalue])
				if title[-2:]=='CN':
					if len(voltage_listC)>0:
						for item in voltage_listC:
							if item[0]==title[-5:-2]:
								item[2] = absvalue
							else:
								voltage_listC.append([title[-5:-2], title[-2:], absvalue])
					else:
						voltage_listC.append([title[-5:-2], title[-2:], absvalue])

		#print('tapABC', tapA, tapB, tapC, flush = True)
		Adjust_tap_A = check_voltage(voltage_listA)
		UpdateTapA = tapA + Adjust_tap_A
		#print('Adjust TapA', Adjust_tap_A, 'Updated TapA', UpdateTapA, flush = True)
		fncs.publish('reg_statusTapA', UpdateTapA)
		Adjust_tap_B = check_voltage(voltage_listB)
		UpdateTapB = tapB + Adjust_tap_B
		#print('Adjust TapB', Adjust_tap_B, 'Updated TapB', UpdateTapB, flush = True)
		fncs.publish('reg_statusTapB', UpdateTapB)
		Adjust_tap_C = check_voltage(voltage_listC)
		UpdateTapC = tapC + Adjust_tap_C
		#print('Adjust TapC', Adjust_tap_C, 'Updated TapC', UpdateTapC, flush = True)
		fncs.publish('reg_statusTapC', UpdateTapC)
		# for key in events:
			# substation = key.decode()
			# GLDload = parse_mva (fncs.get_value(key).decode())
# #			print ('  **', ts, substation, GLDload)
			# for row in fncsBus:
				# if substation == row[1]:
# #					print('    assigning',substation,GLDload)
					# row[3] = GLDload[0]

#	summarize_opf(res)
	# print ('writing metrics', flush=True)
	# print (json.dumps(bus_metrics), file=bus_mp, flush=True)
	# print (json.dumps(gen_metrics), file=gen_mp, flush=True)
	# print (json.dumps(sys_metrics), file=sys_mp, flush=True)
	# print ('closing files', flush=True)
	# bus_mp.close()
	# gen_mp.close()
	# sys_mp.close()
	# op.close()
	print ('finalizing FNCS', flush=True)
	fncs.finalize()


'''
将一个给定字符串 s 根据给定的行数 numRows ，以从上往下、从左到右进行 Z 字形排列。

思路： 按行排序
根据字符串索引很容易找到它在z字符的行数,只需要两个参数，当前行与下一行的方向
'''

from math import ceil

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        n = len(s)
        rows = [[] for _ in range(min(n, numRows))]
        d = -1      #设置方向
        curIndex = 0    #设置当前行
        for i in range(n):
            rows[curIndex].append(s[i])
            # 每次走到z的最上方或者最下方时候，就要改变当前行的方向
            if curIndex == (min(n,numRows) -1) or curIndex == 0:
                d = -d
            curIndex += d
        zs = ""
        for i in rows:
            zs = zs +  "".join(rows[i])
        return zs

if __name__ == '__main__':
    ss = ['PAYPALISHIRING','ab']
    results = ['PAHNAPLSIIGYIR','ab']
    rows = [3,1]
    solution = Solution()
    for i in range(len(ss)):
        print(solution.convert(ss[i], rows[i]),'(',results[i],')')


import random
import db
import ag_utilities

def setup():
    # init game data storage...
    # provides efficient configurability and extensibility of game
    # includes locations (that player can enter), and content that
    # will be available in the locations
    # also initiates player status - score, health, inventory, etc.

    env = []

    # init content_type table and meta data
    env = db.ins_tab(env, "content_type")
    env = db.ins_rec(env, "content_type", [["name", "armor"],
                                           ["action", "Pickup"]])
    env = db.ins_rec(env, "content_type", [["name", "adversary"],
                                           ["action", "Fight"]])
    env = db.ins_rec(env, "content_type", [["name", "treasure"],
                                           ["action", "Pickup"]])
    env = db.ins_rec(env, "content_type", [["name", "weapon"],
                                           ["action", "Pickup"]])

    # init table - adversary
    env = db.ins_tab(env, "adversary")
    env = db.ins_rec(env, "adversary", [["name", "dragon"],
                                        ["health", 100],
                                        ["power", 40],
                                        ["points", 75]])
    env = db.ins_rec(env, "adversary", [["name", "dementor"],
                                        ["health", 80],
                                        ["power", 30],
                                        ["points", 60]])
    env = db.ins_rec(env, "adversary", [["name", "troll"],
                                        ["health", 60],
                                        ["power", 20],
                                        ["points", 50]])
    env = db.ins_rec(env, "adversary", [["name", "ogre"],
                                        ["health", 40],
                                        ["power", 10],
                                        ["points", 40]])
    env = db.ins_rec(env, "adversary", [["name", "nymph"],
                                        ["health", 30],
                                        ["power", 5],
                                        ["points", 20]])

    # init table - armor
    env = db.ins_tab(env, "armor")
    env = db.ins_rec(env, "armor", [["name", "breast plate"],
                                    ["protection", 40],
                                    ["points", 30]])
    env = db.ins_rec(env, "armor", [["name", "shield"],
                                    ["protection", 30],
                                    ["points", 20]])
    env = db.ins_rec(env, "armor", [["name", "helmet"],
                                    ["protection", 20],
                                    ["points", 10]])

    # init table - treasure
    env = db.ins_tab(env, "treasure")
    env = db.ins_rec(env, "treasure", [["name", "crown"], ["points", 75]])
    env = db.ins_rec(env, "treasure", [["name", "chalis"], ["points", 60]])
    env = db.ins_rec(env, "treasure", [["name", "necklace"], ["points", 45]])
    env = db.ins_rec(env, "treasure", [["name", "ring"], ["points", 30]])

    # init table - weapon
    env = db.ins_tab(env, "weapon")
    env = db.ins_rec(env, "weapon", [["name", "sword"],
                                     ["power", 30],
                                     ["points", 50]])
    env = db.ins_rec(env, "weapon", [["name", "staff"],
                                     ["power", 20],
                                     ["points", 40]])
    env = db.ins_rec(env, "weapon", [["name", "dagger"],
                                     ["power", 15],
                                     ["points", 30]])
    env = db.ins_rec(env, "weapon", [["name", "hand"],
                                     ["power", 5],
                                     ["points", 10]])

    # init table - locations
    # scramble locations so order is different each play
    locations = ["castle", "cave", "field", "forest", "village"]
    locations = ag_utilities.sample(env, locations)

    env = db.ins_tab(env, "location")
    for location in locations:
        fbg_mode = ag_utilities.flip_coin()
        env = db.ins_rec(env, "location", [["name", location],
                                           ["fight_before_gather", fbg_mode]])

    # init table - content
    # distribute content among locations
    env = db.ins_tab(env, "content")

    content_types = db.rec_list(env, "content_type", "name")
    locations = db.rec_list(env, "location", "name")
    locations_cnt = len(locations)
    idx_item = -1

    for content_type in content_types:
        # get list of contents of type content_type
        contents = db.rec_list(env, content_type, "name")

        # scramble list so locations have different content each play
        contents = ag_utilities.sample(env, contents)

        for item in contents:
            idx_item += 1
            location_idx = idx_item % locations_cnt

            # add data of content record
            # create content record
            env = db.ins_rec(env, "content",
                             [["location", locations[location_idx]],
                              ["content_type", content_type],
                              ["name", item],
                              ["available", True],
                              ["active", False],
                              ["menu_idx", ""]
                              ])

    # set health based on the number of adversaries
    adversary_count = db.rec_cnt(env, "adversary", [[]])
    health_per_adversary = 35
    health = adversary_count * health_per_adversary

    # init table - player
    # use id=0 to represent single player in game
    env = db.ins_tab(env, "player")
    env = db.ins_rec(env, "player",
                     [["id", 0],
                      ["points_earned", 0],
                      ["objectives", ["crown"]],
                      ["health", health],
                      ["location", ""],
                      ["adversary", []],
                      ["armor", []],
                      ["treasure", []],
                      ["weapon", []],
                      ["game_end_type", ""]
                      ])

    # init player with "hand" by adding "hand" to players weapon inventory
    env = db.upd_val(env, "player", "id", 0, "weapon", ["hand"])
    env = db.upd_val(env, "content", "name", "hand", "available", False)

    return env


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   1544. 整理字符串.py
@Contact :   muyisanshuiliang@hotmail.com

@Modify Time      @Author               @Version
------------      -------               --------
2021/3/15 16:11   muyisanshuiliang      3.9
@Description:
---------------------------------------------------------------
给你一个由大小写英文字母组成的字符串 s 。
一个整理好的字符串中，两个相邻字符 s[i] 和 s[i+1]，其中 0<= i <= s.length-2 ，要满足如下条件:
若 s[i] 是小写字符，则 s[i+1] 不可以是相同的大写字符。
若 s[i] 是大写字符，则 s[i+1] 不可以是相同的小写字符。
请你将字符串整理好，每次你都可以从字符串中选出满足上述条件的 两个相邻 字符并删除，直到字符串整理好为止。
请返回整理好的 字符串 。题目保证在给出的约束条件下，测试样例对应的答案是唯一的。
注意：空字符串也属于整理好的字符串，尽管其中没有任何字符。

示例 1：
输入：s = "leEeetcode"
输出："leetcode"
解释：无论你第一次选的是 i = 1 还是 i = 2，都会使 "leEeetcode" 缩减为 "leetcode" 。

示例 2：
输入：s = "abBAcC"
输出：""
解释：存在多种不同情况，但所有的情况都会导致相同的结果。例如：
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

示例 3：
输入：s = "s"
输出："s"

提示：
1 <= s.length <= 100
s 只包含小写和大写英文字母
'''

# import lib
class Solution:
    def makeGood(self, s: str) -> str:

        # if not s:
        #     return ''
        # stack = []
        # for item_inx in range(0, len(s)):
        #     num = ord(s[item_inx])
        #     if stack:
        #         if stack[-1] + 32 == num or num + 32 == stack[-1]:
        #             stack.pop()
        #             continue
        #     stack.append(num)
        # return ''.join(chr(item) for item in stack)

        if not s:
            return ''
        stack = []
        for item_inx in range(0, len(s)):
            temp = s[item_inx]
            if stack and stack[-1] != temp and stack[-1].lower() == temp.lower():
                stack.pop()
            else:
                stack.append(temp)
        return ''.join(stack)

solution = Solution()
print(solution.makeGood("leEeetcode"))
print(solution.makeGood("abBAcC"))


import pkg_resources
import importlib.metadata as stowMeta

def Version():
    """Get Version From Dist Folder

    Returns:
        version : current version
    """
    version = ''
    try:
        version = pkg_resources.require('stowtui')[0].version
    except Exception as e:    # pragma: no cover
        version = 'Error: ' + str(e)
    return version

def Author():
    """Get Author From Dist Folder

    Returns:
        Author : Author Name
    """
    author = ''
    try:
        author = stowMeta.metadata('stowtui')['Author']
    except Exception as e:
        author = 'Error: ' + str(e)
    return author

def Email():
    """Get Author Email From Dist Folder

    Returns:
        Email : Author Email
    """
    email = ''
    try:
        email = stowMeta.metadata('stowtui')['Author-email']
    except Exception as e:
        email = 'Error: ' + str(e)
    return email

def app_name():
    """Get App Name

    Returns:
        Name : App Name
    """
    app_name = ''
    try:
        app_name = stowMeta.metadata('stowtui')['Name']
    except Exception as e:
        app_name = 'Error: ' + str(e)
    return app_name


import datetime
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator
from django.db.models import Sum, Q
from django.shortcuts import render
from django.utils import timezone
from django.core.cache import cache
from blog.models import Blog
from blog.utils import get_seven_days_read_data, get_today_hot_data, get_yesterday_hot_data

def get_7_days_hot_data():
    today = timezone.now().date()
    date = today - datetime.timedelta(days=7)
    # 根据object_id分组求和
    blogs = Blog.objects\
                 .filter(read_details__date__lt=today, read_details__date__gte=date)\
                 .values('id', 'title')\
                 .annotate(read_num_sum=Sum('read_details__read_num'))\
                 .order_by('-read_num_sum')
    return blogs[:7]

def get_30_days_hot_data():
    today = timezone.now().date()
    date = today - datetime.timedelta(days=30)
    # 根据object_id分组求和
    blogs = Blog.objects\
                 .filter(read_details__date__lt=today, read_details__date__gte=date)\
                 .values('id', 'title')\
                 .annotate(read_num_sum=Sum('read_details__read_num'))\
                 .order_by('-read_num_sum')
    return blogs[:7]

def home(request):
    blog_content_type = ContentType.objects.get_for_model(Blog)
    dates, read_nums = get_seven_days_read_data(blog_content_type)
    seven_days_hot_data = cache.get('7_days_hot_data')
    if seven_days_hot_data is None:
        seven_days_hot_data = get_7_days_hot_data()
        cache.set('7_days_hot_data', seven_days_hot_data, 3600)  # 有效期1小时

    one_month_hot_data = cache.get('30_days_hot_data')
    if one_month_hot_data is None:
        one_month_hot_data = get_30_days_hot_data()
        cache.set('30_days_hot_data', one_month_hot_data, 3600)  # 有效期1小时

    context = {
        'read_nums': read_nums,
        'dates': dates,
        'today_hot_data': get_today_hot_data(blog_content_type),
        'yesterday_hot_data': get_yesterday_hot_data(blog_content_type),
        '7_days_hot_data': seven_days_hot_data,
        '30_days_hot_data': one_month_hot_data,
    }
    return render(request, 'home.html', context)

class CustomPaginator(Paginator):
    def __init__(self, current_page, max_pager_num, *args, **kwargs):
        """
        :param current_page: 当前页
        :param max_pager_num:最多显示的页码个数
        :param args:
        :param kwargs:
        :return:
        """
        self.current_page = int(current_page)
        self.max_pager_num = max_pager_num
        super(CustomPaginator, self).__init__(*args, **kwargs)

    def page_num_range(self):
        # 当前页面
        # self.current_page
        # 总页数
        # self.num_pages
        # 最多显示的页码个数
        # self.max_pager_num

        if self.num_pages < self.max_pager_num:
            return range(1, self.num_pages + 1)

        part = int(self.max_pager_num / 2)
        if self.current_page - part < 1:
            return range(1, self.max_pager_num + 1)

        if self.current_page + part > self.num_pages:
            return range(self.num_pages + 1 - self.max_pager_num, self.num_pages + 1)

        return range(self.current_page - part, self.current_page + part + 1)

def get_blog_list_common_data(request, search_blogs):
    search_blogs_count = search_blogs.count()
    current_page = request.GET.get('p', 1)
    paginator = CustomPaginator(current_page, 2, search_blogs, 6)
    page_of_blog = paginator.get_page(current_page)
    page_range = list(paginator.page_num_range())
    # 加上省略页码表级
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:
        page_range.append('...')
    # 加上首页和尾页
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)

    context = {
        'search_blogs': page_of_blog.object_list,
        'page_of_blog': page_of_blog,
        'page_range': page_range,
        'search_blogs_count': search_blogs_count,
    }
    return context

def search(request):
    wd = request.GET.get('wd', '').strip()
    condition = None
    for word in wd.split(' '):
        if condition is None:
            condition = Q(title__icontains=word)
        else:
            condition = condition | Q(title__icontains=word)
    if condition is not None:
        search_blogs = Blog.objects.filter(condition)   # i忽略大小写
    context = get_blog_list_common_data(request, search_blogs)
    context['search_word'] = wd
    return render(request, 'search.html', context)


# Вычисление чисел Фибоначчи
from functools import lru_cache
from typing import Dict, Generator

# Бесконечная рекурсия- нет базового случая

def fib1(n: int) -> int:
    return fib1(n-1) + fib1(n-2)

# Классическая реализация
# n=50 уже не работает, слишком много вызов
def fib2(n: int) -> int:
    if n < 2:
        return n
    return fib2(n-1) + fib2(n-2)

# Мемоизация
# Запоминаем результаты всех вызовов
memo: Dict[int, int] = {0: 0, 1: 1}         # два базовых случая

def fib3(n: int) -> int:
    if n not in memo:
        memo[n] = fib3(n-1) + fib3(n-2)
    return memo[n]

# Автоматическая мемоизация с помощью декоратора
@lru_cache(maxsize=None)
def fib4(n: int) -> int:                    # Точно такая же реализация, как в классической реализации
    if n < 2:
        return n
    return fib4(n-1) + fib4(n-2)

# Итеративный способ
def fib5(n: int) -> int:
    if n == 0:                  # специальный случай
        return n
    last: int = 0               # fib(0)
    next: int = 1               # fib(1)
    for _ in range(1, n):
        last, next = next, next + last
        # new_next = next + last
        # last = next
        # next = new_next
    return next

# Генератор чисел Фибоначчи
def fib6(n: int) -> Generator[int, None, None]:
    # специальный случай (возвращаем 0, но не покидаем функции - следующий вызов функции со след. строки)
    yield 0                     # fib(0)

    if n > 0:                   # fib(1)
        yield 1

    last: int = 0               # начальное значение fib(0) - уже прошли, см. выше
    next: int = 1               # начальное значение fib(1) - уже прошли, см. выше
    for _ in range(1, n):
        last, next = next, next + last
        yield next

# Это вызов главной функции
if __name__ == '__main__':
    print('Iterator = ', fib5(10))
    print('\n From generator = ')
    for i in fib6(10):
        print(i)


from setuptools import setup
from distutils.util import convert_path

versionholder = {}
ver_path = convert_path('originator/__init__.py')
with open(ver_path) as init_file:
    exec(init_file.read(), versionholder)

setup(name='originator',
    version=versionholder['__version__'],
    description='Rotate circular replicon to start with dnaA gene',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Science/Research',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering :: Bio-Informatics',
        'Topic :: Scientific/Engineering :: Medical Science Apps.'
    ],
    keywords=['dnaA','ori','origin','replication','circular'],
    author='Ola Brynildsrud',
    author_email='ola.brynildsrud@fhi.no',
    packages=['originator'],
    install_requires=[
        'biopython'],
    entry_points={
        'console_scripts': ['originator=originator.originator:main']
    },
    package_data={'originator': ['setup.py','originator/db/*']},
    include_package_data=True
)


import numpy as np
from agent.mctsAgent import MCTSAgent
from agent.policyAgent import PolicyAgent

import datetime
import h5py
from scipy.stats import binom_test
import tensorflow as tf
from rl.experience import ExperienceCollector, combine_experience
import time
from agent.actorCriticAgent import ActorCriticAgent
from multiprocessing import Process, Value, Lock
from encoder.base import get_encoder_by_name
from fiveinarow import check_for_done, draw_board, render, check_for_done

class SimulationEngine:
    def __init__(self, bot_white, bot_black):
        self.bot_1 = bot_white
        self.bot_2 = bot_black
        self.player_bot_dict = {1: self.bot_1, -1: self.bot_2}
        self.M = 8

    def pygame_self_play(self):
        import pygame
        pygame.init()
        screen = pygame.display.set_mode((640, 640))
        draw_board(screen)
        pygame.display.update()

        while True:
            step_num = 0
            mat = np.zeros((self.M, self.M))
            cur_move = None
            cur_player = 1
            while check_for_done(mat)[0] is False:
                render(screen, mat)
                mat, cur_move = self.player_bot_dict[cur_player].select_move(mat, cur_move)
                cur_player *= -1
                step_num +=1

                print('Step Number', step_num)
                print(mat)
                print("--------------------------")
                render(screen, mat)

        pygame.quit()

    def self_play_monte_carlo(self, encoder, saving_perod = 50, file_path = 'game_data/'):
        print("self play started")
        date_string = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        start_time = time.time()
        file_length = 0
        master_mat = []
        master_move = []
        master_result = []

        while True:
            step_num = 0
            mat = np.zeros((self.M, self.M))
            cur_move = None
            cur_player = 1

            while check_for_done(mat)[0] is False:

                # Saving the mat before the game
                master_mat.append(encoder.encode(mat, cur_player))

                # Use the agent to take move
                mat, cur_move = self.player_bot_dict[cur_player].select_move(mat, cur_move)

                # Saving the move information
                master_move.append(encoder.encode_point(cur_move))
                cur_player *= -1
                step_num += 1
            master_result += [check_for_done(mat)[1] for _ in range(step_num)]

            time_diff = time.time() - start_time
            print(f'Done for one game with {step_num} moves.Time Spent :{time_diff}.Rate: {time_diff/len(master_move)}')

            if len(master_move) > file_length + saving_perod:
                master_mat_save = np.array(master_mat)
                master_move_save = np.array(master_move)
                master_result_save = np.array(master_result)
                time_diff = time.time() - start_time
                print(f"Saving file for {len(master_move)} steps now. Time Spent :{time_diff}. Rate: {time_diff/len(master_move)}")

                print(master_mat_save.shape)
                print(master_move_save.shape)
                print(master_result_save.shape)

                np.save(file_path + f"master_mat_rule_{date_string}.npy", master_mat_save)
                np.save(file_path + f"master_move_rule_{date_string}.npy", master_move_save)
                np.save(file_path + f"master_result_rule_{date_string}.npy", master_result_save)
                file_length = len(master_move)

    def self_play_RL(self, num_games, file_path = "experience_data/"):
        time_start = time.time()
        white_win = 0
        draw = 0
        cur_player = 1

        collector1 = ExperienceCollector()
        collector2 = ExperienceCollector()

        self.bot_1.set_collector(collector1)
        self.bot_2.set_collector(collector2)

        self.bot_1.set_temperature(0.005)
        self.bot_2.set_temperature(0.005)

        for i in range(num_games):
            collector1.begin_episode()
            collector2.begin_episode()

            winner = self.simulate_game(cur_player=cur_player)

            if winner == 1:
                collector1.complete_episode(reward=1)
                collector2.complete_episode(reward=-1)
                white_win += 1
            elif winner == -1:
                collector1.complete_episode(reward=-1)
                collector2.complete_episode(reward=1)
            else:
                collector1.complete_episode(reward=0)
                collector2.complete_episode(reward=0)
                draw +=1

            cur_player *= -1

        experience = combine_experience([collector1,collector2])

        date_string = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        with h5py.File(file_path + "experiment_" +date_string , 'w') as experience_outf:
            experience.serialize(experience_outf)

        time_spent = time.time() - time_start
        print(f"Completed self play for {num_games} game. Total time: {time_spent}. Rate {time_spent/num_games}")
        print(f"White win num:{white_win}; Black win num: {num_games-white_win-draw}")

    def simulate_game(self, cur_player=1):
        game_state = np.zeros((self.M, self.M))
        cur_move = None

        while check_for_done(game_state)[0] is False:
            game_state, cur_move = self.player_bot_dict[cur_player].select_move(game_state, cur_move)
            cur_player *= -1

        print("Done for one game")
        return check_for_done(game_state)[1]

    def test_RL_Agents(self, num_games):
        time_start = time.time()
        wins = 0
        losses = 0
        draws = 0
        start_player = 1
        while wins + losses < num_games:
            winner = self.simulate_game(cur_player=start_player)
            start_player *= -1
            if winner == 1:
                wins += 1
            elif winner == -1:
                losses += 1
            else:
                draws +=1

        time_spent = time.time() - time_start
        print('Agent 1 (Testing Agent)')
        print('Total Win: %d' % (wins))
        print('Total Draws: %d' % (draws))
        print('Total Losses: %d' % (losses))
        print(f'Total Win percentage: {wins/(wins+losses)}')
        print(f"Total time: {time_spent}")
        print(f"p value {binom_test(wins, wins+losses, 0.5)}")

if __name__ == "__main__":

    """Reinforcement learning self play"""
    # model = tf.keras.models.load_model('saved_model/layer_20_model')
    # encoder = get_encoder_by_name('layer_20_encoder', (8,8))
    # bot_white = PolicyAgent(model, encoder, 1)
    # bot_black = PolicyAgent(model, encoder, -1)
    # bot_black.set_temperature(0.005)
    # bot_white.set_temperature(0.005)
    # simulation = SimulationEngine(bot_white, bot_black)
    # simulation.self_play_RL(num_games=2000)

    # model = tf.keras.models.load_model('saved_model/actor_critic_net')
    # encoder = get_encoder_by_name('layer_20_encoder', (8,8))
    # bot_white = ActorCriticAgent(model, encoder, 1)
    # bot_black = ActorCriticAgent(model, encoder, -1)
    # simulation = SimulationEngine(bot_white, bot_black)
    # simulation.self_play_RL(10)

    # See whether we can parallel in the future
    # num_cpu = 10
    # workers = []
    # for i in range(num_cpu):
    #     model = tf.keras.models.load_model('saved_model/layer_20_model')
    #     encoder = get_encoder_by_name('layer_20_encoder', (8, 8))
    #     bot_white = PolicyAgent(model, encoder, 1)
    #     bot_black = PolicyAgent(model, encoder, -1)
    #     simulation = SimulationEngine(bot_white, bot_black)
    #     worker = Process(simulation.self_play_RL,
    #                      args=(10))
    #     worker.start()
    #     workers.append(worker)
    # print('Waiting for workers...')
    # for worker in workers:
    #     worker.join()

    """Monte Carlo Geneerate Data"""
    # SIMULATION_NUMBER = 15000
    # TEMPERATURE = 0.5
    # encoder = get_encoder_by_name('oneplane', 8)
    # bot_white = MCTSAgent(simulation_number=SIMULATION_NUMBER,
    #                       temperature=TEMPERATURE,
    #                       cur_player=1)
    # bot_black = MCTSAgent(simulation_number=SIMULATION_NUMBER,
    #                       temperature=TEMPERATURE,
    #                       cur_player=-1)
    # simulation = SimulationEngine(bot_white, bot_black)
    # simulation.self_play_monte_carlo(encoder)

    # """Agent self play"""
    model = tf.keras.models.load_model('saved_model/layer_20_model')
    encoder = get_encoder_by_name('layer_20_encoder', (8,8))
    bot_white = PolicyAgent(model, encoder, 1)

    model = tf.keras.models.load_model('saved_model/pg_model_V2_00002_rate')
    bot_black = PolicyAgent(model, encoder, -1)

    bot_black.set_temperature(0)
    bot_white.set_temperature(0)

    simulation = SimulationEngine(bot_white, bot_black)
    simulation.test_RL_Agents(100)


import Queue
import os
from mock import patch
import unittest

import imp

tiny = imp.load_source('tinydash', os.path.join(os.path.dirname(__file__), '..', 'bin', 'tiny-dash.py'))

add_callback_called = False

class MockDeferred:
    def addCallback(self, cb):
        global add_callback_called
        add_callback_called = True

called_program = 'not called'

def getProcessValue(a, b, env):
    global called_program
    called_program = a
    return MockDeferred()

class TestSensorBase(unittest.TestCase):
    @patch('tinydash.SensorBase')
    @patch('tinydash.utils.getProcessValue', getProcessValue)
    def test_sensor(self, SensorBaseMock):
        queue = Queue.Queue()
        sensor = tiny.StatusSensor(queue, {'update-interval': 0.1, 'program': ['foobar']})
        sensor.run()
        self.assertEqual('foobar', called_program)
        self.assertTrue(add_callback_called)

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


import git
import os
import time
from git import *

LocalRepositoryName = "Local"
LocalDirectoryPath = 'C:\\Devworkspace\\GitWorkspace\\RepOne\\Rep13'
LocalGITRepo = 'C:\\Users\\SANUMOLU'
giturl =  'https://github.com/seshikanth/RepoOne.git'

repo = git.Repo(LocalGITRepo)
origin = repo.remotes.origin

assert origin == repo.remotes.origin
origin.fetch()                  # assure we actually have data. fetch() returns useful information
print(origin.fetch())
origin.push()


class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        list_Ge = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
        list_shi=["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
        list_bai = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
        list_qian = ["M", "MM", "MMM"]
        listzong = [list_Ge,list_shi,list_bai,list_qian]
        resultLIst = []
        thelocal = 0
        stop = False
        while True:
            if num//10 > 0 :
                theflag = num%10
                num //=10
            else:
                theflag = num
                stop = True
            if theflag!=0:
                resultLIst.append(listzong[thelocal][theflag-1])
            else:
                resultLIst.append('')
            thelocal+=1
            if stop:
                break
        resultLIst.reverse()
        return ''.join(resultLIst)

if __name__ == '__main__':
    test =Solution()
    print(test.intToRoman(1001))


s = "ccbb"
wordDict = ["bc", "cb"]

diction = sorted(wordDict,key=lambda x:len(x), reverse = True)
memo = {}

def wb(s):
    if s in memo:
        return memo[s]

    temp=s
    for word in diction:
        temp = s.replace(word," ").strip()
        if temp == s:
            continue
        if len(temp)==0 or wb(temp):
            memo[temp] = True
            return True
    memo[temp] = False
    return False

print(wb(s))


import math
from collections import Counter
import numpy as np

from ._decision_tree import DecisionTree
from ..metrics import binary_gini, gini, entropy
from .._base import BaseClassifier

class DecisionTreeClassifier(BaseClassifier, DecisionTree):
    def __init__(self, criterion='gini', max_depth=None, algorithm='greedy', max_features='auto'):

        super().__init__(max_depth=max_depth, algorithm=algorithm, max_features=max_features)

        if criterion == 'gini':
            self.criterion = gini
        elif criterion == 'binary_gini':
            self.criterion = binary_gini
        elif criterion == 'entropy':
            self.criterion = entropy
        else:
            raise Exception('Cannot find this criterion')

    def _evaluate_leaf(self, node):
        labels = self.y[node.values]
        counter = Counter(labels)
        most_frequent_class = counter.most_common()[0][0]

        return most_frequent_class


import json

import geopandas as gpd
import pandas as pd
import requests
import shapely

from src.components import Collector

class LimeVehiclePositionCollector(Collector):
    def run(self):
        endpoint = "https://data.lime.bike/api/partners/v2/gbfs/brussels/free_bike_status"
        response_json = requests.get(endpoint).json()
        response_df = pd.json_normalize(response_json["data"]["bikes"])
        response_gdf = gpd.GeoDataFrame(
            response_df,
            crs="epsg:4326",
            geometry=[
                shapely.geometry.Point(xy)
                for xy in zip(response_df["lon"], response_df["lat"])
            ],
        )
        # Drop lat and lon columns
        response_gdf = response_gdf.drop(columns=["lat", "lon"])

        return json.loads(response_gdf.to_json())


import argparse

from train_supervised import add_parms_supervised, train_supervised
from load_data import loading_data, add_params_data
from Reports.ReportWriting import add_params_report
from meanTeacher import train_MeanTeacher, add_params_mt

if __name__ == '__main__':
    # parameters from arugument parser
    parser = argparse.ArgumentParser()
    parser.add_argument('--lr', default=0.0001, type=int)
    parser.add_argument('--epochs', default=10, type=int)
    parser.add_argument('--batchSize', default=64, type=int)
    parser.add_argument('--ratio', default=0.5, type=int)
    parser.add_argument('--alpha', type=int, default=0.97)
    parser.add_argument('--threashold', type=int, default=0.51)

    # Adding parameters from other python files
    parser = add_parms_supervised(parser)
    parser = add_params_data(parser)
    parser = add_params_report(parser)
    parser = add_params_mt(parser)
    args = parser.parse_args()

    for i in range(0,1):
        args.alpha = args.alpha+0.01
        for i in range(0,1):
            train_supervised(args)
            train_MeanTeacher(args)
    print('finished')


from seleniumbase import BaseCase
from POM_auto.page_object_model import PageObject
#some text from pc
class Saucedemo(BaseCase):

    def setUp(self):
        super().setUp()
        print("RUNNING BEFORE EACH TEST")
        PageObject.open_page(self)
        PageObject.login(self)

    def tearDown(self):
        print("RUNNING AFTER EACH TEST")
        PageObject.logout(self)
        super().tearDown()

    def test_saucedemo(self):
        PageObject.adding_items(self)

    def test_check_basket(self):
        PageObject.adding_items(self)
        PageObject.open_basket(self)
        self.assert_text("Sauce Labs Backpack", PageObject.backpack_text)
        self.assert_text("Sauce Labs Bike Light", PageObject.bike_light_text)
        self.assert_text("Sauce Labs Bolt T-Shirt", PageObject.tshirt_text)


import unicodedata
from typing import Union, Tuple

from lxml.etree import _Element

from arxivnlp import xml_match as xm
from arxivnlp.examples.quantities.center import Scalars, ScalarNotation
from arxivnlp.examples.quantities.quantity_kb import Notation, UnitNotation
from arxivnlp.xml_match import LabelTree

class UndesirableMatchException(Exception):
    """
        A match cannot be processed or is rejected, even though it should be a valid match according to the matcher.
        You could say it's a logical error, not a syntax error.
    """
    pass

# ***************
# * BASIC NODES *
# ***************

mrow = xm.tag('mrow')
mo = xm.tag('mo')
mn = xm.tag('mn')
mtext = xm.tag('mtext')
msup = xm.tag('msup')

relational_mo = mo.with_text(
    '[' + ''.join({'=', '≈', '<', '>', '≪', '≫', '≥', '⩾', '≤', '⩽', '∼', '≲', '≳'}) + ']')
empty_tag = xm.any_tag.with_text('^$')
space = mtext.with_text(r'\s*')
base = xm.tag('math') / xm.tag('semantics')

# ***********************
# * NUMBERS AND SCALARS *
# ***********************

def mn_to_number(mn_text: str) -> Union[float, int]:
    reduced = ''
    for c in mn_text:
        if c.isnumeric():
            reduced += c
        elif c == '.':
            reduced += c
        elif c.isspace():
            continue
        else:
            print(f'Can\'t convert mn {repr(mn_text)}')
    return float(reduced) if '.' in reduced else int(reduced)

simple_number = (
                        mn ** 'numeral' |
                        mrow / xm.seq(mo.with_text(r'[-–]') ** 'negative', mn ** 'numeral')
                ) ** 'simplenumber'
power_of_10 = (msup / xm.seq(mn.with_text('^10$'), simple_number ** 'exponent')) ** 'powerof10'
scientific_number = (mrow / xm.seq(simple_number ** 'factor', mtext.with_text('[×]'),
                                   power_of_10)) ** 'scientific'

def tree_to_number(lt: LabelTree) -> Tuple[Union[int, float], str]:
    if lt.label == 'simplenumber':
        sign = -1 if 'negative' in lt else 1
        return sign * mn_to_number(lt['numeral'].node.text), 'simple'
    elif lt.label == 'scientific':
        return tree_to_number(lt['factor'])[0] * tree_to_number(lt['powerof10'])[0], 'scientific'
    elif lt.label == 'powerof10':
        return 10 ** tree_to_number(lt['exponent'])[0], 'powerof10'
    elif len(lt.children) == 1:
        return tree_to_number(lt.children[0])
    raise Exception(f'Unsupported tree: {lt}')

scalar = (simple_number | scientific_number | power_of_10 |
          (mrow / xm.seq(empty_tag, mo.with_text(f'^{unicodedata.lookup("INVISIBLE TIMES")}$'),
                         power_of_10))  # presumably this happens when using siunitx and leaving the factor empty
          ) ** 'scalar'

def scalar_to_scalars(lt: LabelTree) -> Scalars:
    number, type_ = tree_to_number(lt)
    scalar_notation = ScalarNotation(0)
    if type(number) == int:
        scalar_notation |= ScalarNotation.IS_INT
    if type_ == 'scientific':
        scalar_notation |= ScalarNotation.SCIENTIFIC
    return Scalars(float(number), scalar_notation=scalar_notation)

# ***********
# * SYMBOLS *
# ***********

simple_symbol = xm.tag('mi') | xm.tag('mo')
complex_symbol = (
                     (xm.tag('msub') / xm.seq(simple_symbol, xm.any_tag)) |
                     (xm.tag('msup') / xm.seq(simple_symbol, xm.any_tag)) |
                     (xm.tag('msubsup') / xm.seq(simple_symbol, xm.any_tag, xm.any_tag))
)
symbol = simple_symbol | complex_symbol

def symbol_to_notation(node: _Element) -> Notation:
    # TODO: Invisible characters?
    if node.tag in {'mi', 'mn', 'mo'}:
        attr = {'val': node.text}
        if node.tag == 'mi' and node.text and len(node.text) == 1 and node.get('mathvariant') != 'normal':
            attr['isitalic'] = True
        return Notation('i', attr, [])
    elif node.tag in {'msup', 'msub', 'msubsup'}:
        return Notation(node.tag[1:], {}, [symbol_to_notation(child) for child in node.getchildren()])
    elif node.tag == 'mrow':
        # TODO: We need some kind of normalization (merge consecutive identifiers etc.)
        return Notation('seq', {}, [symbol_to_notation(child) for child in node.getchildren()])
    raise Exception('Unsupported symbol node: ' + node.tag)

# *********
# * UNITS *
# *********

simple_unit = (simple_symbol | (xm.tag('msub') / xm.seq(simple_symbol, xm.any_tag))) ** 'simpleunit'
# simple_unit = simple_symbol ** 'simpleunit'

def simple_unit_to_notation(lt: LabelTree) -> Notation:
    assert lt.label == 'simpleunit'
    # TODO: This will get much more complex
    node = lt.node
    return symbol_to_notation(node)

unit_power = (xm.tag('msup') / xm.seq(simple_unit, simple_number ** 'exponent')) ** 'unitpower'
unit_times2 = (mrow / xm.seq(simple_unit | unit_power, xm.maybe(space), simple_unit | unit_power)) ** 'unittimes'
unit_times3 = (mrow / xm.seq(simple_unit | unit_power, xm.maybe(space), simple_unit | unit_power, xm.maybe(space),
                             simple_unit | unit_power)) ** 'unittimes'
unit = (simple_unit | unit_power | unit_times2 | unit_times3) ** 'unit'

def unit_to_unit_notation(lt: LabelTree) -> UnitNotation:
    if lt.label == 'unit':
        assert len(lt.children) == 1
        return unit_to_unit_notation(lt.children[0])
    elif lt.label == 'simpleunit':
        notation = simple_unit_to_notation(lt)
        return UnitNotation([(notation, 1)])
    elif lt.label == 'unitpower':
        notation = simple_unit_to_notation(lt['simpleunit'])
        exponent = tree_to_number(lt['exponent'])[0]
        if exponent not in range(-10, 10):
            raise UndesirableMatchException(f'Bad exponent for a unit: {exponent}')
        return UnitNotation([(notation, exponent)])
    elif lt.label == 'unittimes':
        parts = []
        for subunit in lt.children:
            parts += unit_to_unit_notation(subunit).parts
        return UnitNotation(parts)
    raise Exception(f'Unsupported node: {lt.label}')

# **************
# * QUANTITIES *
# **************

quantity = mrow / xm.seq(scalar, xm.maybe(space), unit)
quantity_in_rel = mrow / xm.seq(xm.maybe(xm.any_tag), relational_mo, quantity)


#!/usr/bin/python3

import platform
import subprocess as sp
import threading
import time

import vrep

class SimHelper(object):
    def __init__(self):
        if platform.system() != 'Darwin':
            self.start_vrep()
        self.setup_vrep_remote()
        if platform.system() != 'Darwin':
            self.check_vrep()

    '''
    Turn on V-REP application
    '''

    def start_vrep(self):
        try:
            check_vrep_running = sp.check_output(["pidof", "vrep"])
            self.pid = int(check_vrep_running.split()[0])
            print("V-REP already running...")
            launch_vrep = False
        except sp.CalledProcessError:
            launch_vrep = True
            pass

        if launch_vrep:
            print("Starting V-REP...")
            sp.call(['/bin/bash', '-i', '-c', "vrep"])
            time.sleep(5.0)
            check_vrep_running = sp.check_output(["pidof", "vrep"])
            self.pid = int(check_vrep_running.split()[0])
            pass

    '''
    Setup V-REP remote connection
    '''

    def setup_vrep_remote(self):
        try:
            vrep.simxFinish(-1)
            self.clientID = vrep.simxStart('127.0.0.1', 19999, True, True, 5000, 5)
            if self.clientID == -1:
                print("Failed to connect to remote API Server")
                self.sim_functions.exit_sim()
        except KeyboardInterrupt:
            self.exit_sim()

    '''
    Check V-REP running
    '''

    def check_vrep(self):
        t = threading.Timer(10.0, self.check_vrep)
        t.daemon = True
        print("Checking V-REP")
        t.start()
        self.start_vrep()

    '''
    Start V-REP simulation
    '''

    def start_sim(self):
        # Set Simulator
        vrep.simxSynchronous(self.clientID, True)
        dt = .05
        vrep.simxSetFloatingParameter(self.clientID,
                                      vrep.sim_floatparam_simulation_time_step,
                                      dt,  # specify a simulation time step
                                      vrep.simx_opmode_oneshot)
        vrep.simxStartSimulation(self.clientID, vrep.simx_opmode_blocking)
        return

    '''
        Stop V-REP simulation
    '''

    def stop_sim(self):
        vrep.simxStopSimulation(self.clientID, vrep.simx_opmode_oneshot_wait)
        return

    '''
    Pause V-REP simulation
    '''

    def pause_sim(self):
        vrep.simxPauseSimulation(self.clientID, vrep.simx_opmode_oneshot_wait)
        return

    '''
    Exit sequence
    '''

    def exit_sim(self):
        self.stop_sim()
        vrep.simxFinish(self.clientID)
        return

    '''
    Step V-REP simulation
    '''

    def step_sim(self):
        vrep.simxSynchronousTrigger(self.clientID)
        return

    '''
    Reset V-REP simulation
    '''

    def reset(self, display_disabled):
        self.stop_sim()
        time.sleep(0.1)
        self.start_sim()
        if display_disabled:
            self.display_disabled()
        return

    '''
    Fetch handle for object
    '''

    def get_handle(self, obj_name):
        err, handle = vrep.simxGetObjectHandle(self.clientID, obj_name, vrep.simx_opmode_blocking)
        return handle

    '''
    Load V-REP scene
    '''

    def load_scene(self, scene_name):
        vrep.simxLoadScene(self.clientID, scene_name + ".ttt", 0xFF, vrep.simx_opmode_blocking)
        return

    '''
    Turn off V-REP display
    '''

    def display_disabled(self):
        vrep.simxSetBooleanParameter(self.clientID, vrep.sim_boolparam_display_enabled, False,
                                     vrep.simx_opmode_oneshot_wait)
        vrep.simxSetBooleanParameter(self.clientID, vrep.sim_boolparam_browser_visible, False,
                                     vrep.simx_opmode_oneshot_wait)
        vrep.simxSetBooleanParameter(self.clientID, vrep.sim_boolparam_hierarchy_visible, False,
                                     vrep.simx_opmode_oneshot_wait)
        return


from datetime import datetime
from statistics import median, mean

from session_tools.writers.markdown_writer import MarkDownWriter

def markdown_analyzer(sessions):
    report_types = set()
    for note_types in [session["to_report"] for session in sessions]:
        for note_type in note_types:
            report_types.add(note_type)
    report_types = list(sorted(report_types))

    report_notes = {}
    for report_type in report_types:
        report_notes[report_type] = list()
    for session in sessions:
        for note in session["session"]:
            if note[1] in report_types:
                report_notes[note[1]].append((session["filename"], note[2]))

    task_breakdown_types = set()
    for task_types in [session["task_breakdown"] for session in sessions]:
        for task_type in task_types:
            task_breakdown_types.add(task_type)
    task_breakdown_types = list(sorted(task_breakdown_types))

    with MarkDownWriter(
        f"analysis-{datetime.now().strftime('%Y%m%dT%H%M%S')}.md"
    ) as md_writer:
        col_width_default = 32
        col_width_wide = 52
        col_width_narrow = 16

        md_writer.header_1("Session analysis")

        # Overview
        md_writer.header_2("Overview")

        # Overview - time spent, number of bugs, issues, questions
        overview_1_columns = [
            ("", col_width_narrow, "L"),
            ("sessions", col_width_narrow, "C"),
            ("planned (min)", col_width_narrow, "C"),
            ("spent (min)", col_width_narrow, "C"),
        ]
        for category in report_types:
            overview_1_columns.append((category, col_width_narrow, "C"))

        overview_1_data = [
            [
                "totals",
                len(sessions),
                sum([int(session["metadata"]["duration"]) for session in sessions]),
                sum(
                    [
                        int(session["metadata"]["actual_duration"])
                        for session in sessions
                    ]
                ),
            ]
        ]

        for notes in report_notes.values():
            overview_1_data[0].append(len(notes))

        md_writer.table(overview_1_columns, overview_1_data)

        # Overview - charters
        overview_2_columns = [
            ("File", col_width_default, "L"),
            ("Tester", col_width_narrow, "L"),
            ("Charter", col_width_wide, "L"),
        ]
        overview_2_data = [
            (
                session["filename"],
                session["metadata"]["tester"],
                session["metadata"]["charter"],
            )
            for session in sessions
        ]
        md_writer.table(overview_2_columns, overview_2_data)

        # The numbers on how time spent, task breakdown
        md_writer.header_2("The numbers")

        numbers_columns = [
            ("File", col_width_default, "L"),
            ("planned (min)", col_width_narrow, "C"),
            ("spent (min)", col_width_narrow, "C"),
        ]
        for category in task_breakdown_types:
            numbers_columns.append((f"{category} (%)", col_width_narrow, "C"))

        numbers_data = []

        for session in sessions:
            session_data = [
                session["filename"],
                session["metadata"]["duration"],
                session["metadata"]["actual_duration"],
            ]

            for category in task_breakdown_types:
                session_data.append(session["task_breakdown"][category])

            numbers_data.append(session_data)

        separator = (
            " -   -   -",
            " -   -   -",
            " -   -   -",
            " -   -   -",
            " -   -   -",
            " -   -   -",
        )
        # ToDo: construct separator based on len(number_of_columns)
        numbers_data.append(separator)

        means = [
            "mean",
            round(mean([int(session["metadata"]["duration"]) for session in sessions])),
            round(
                mean(
                    [
                        int(session["metadata"]["actual_duration"])
                        for session in sessions
                    ]
                )
            ),
        ]
        for category in task_breakdown_types:
            result = round(
                mean([int(session["task_breakdown"][category]) for session in sessions])
            )
            means.append(result)
        numbers_data.append(means)

        medians = [
            "median",
            round(
                median([int(session["metadata"]["duration"]) for session in sessions])
            ),
            round(
                median(
                    [
                        int(session["metadata"]["actual_duration"])
                        for session in sessions
                    ]
                )
            ),
        ]
        for category in task_breakdown_types:
            result = round(
                median(
                    [int(session["task_breakdown"][category]) for session in sessions]
                )
            )
            medians.append(result)
        numbers_data.append(medians)

        md_writer.table(numbers_columns, numbers_data)

        for note_type, notes in report_notes.items():
            md_writer.header_2(f"{note_type.capitalize()}s")
            if len(notes) > 0:
                columns = [
                    ("File", col_width_default, "L"),
                    (note_type, col_width_wide, "L"),
                ]
                md_writer.table(columns, notes)
            else:
                md_writer.add_line(f"No {note_type}s.")


from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost import plot_importance
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score   # 准确率
import numpy as np
from sklearn.preprocessing import StandardScaler as SS
#from keras.utils import np_utils, generic_utils
# 加载样本数据集
# iris = load_iris()
# X,y = iris.data,iris.target
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234565) # 数据集分割
# print(y_train,'2222')
# dt=np.loadtxt(r'/Users/libingrui/Desktop/Work_file/Data/0610_path_data.txt',dtype=np.float32)
# label = np.loadtxt(r'/Users/libingrui/Desktop/Work_file/Data/0610_label.txt',dtype=np.int32)
label=[]
with open (r'/Users/libingrui/Desktop/Work_file/Data/0610_path_data.txt','r') as mesh_file:
        all_list=[]
        all_data=[]
        for mesh_lines in mesh_file:
            mesh_lines=mesh_lines.strip().split('\t')
            all_list.append(mesh_lines)
with open(r'/Users/libingrui/Desktop/Work_file/Data/0610_label.txt','r') as label_file:
        for label_line in label_file:
            label_line=label_line.strip()
            label.append(int(label_line))
# X=dt
# y=label
all_data=np.array(all_list)
all_data=SS().fit_transform(all_data)
#label=np_utils.to_categorical(label)
X_train=all_data[:3000]
X_test=all_data[30001:3985]
y_train=label[:3000]
y_test=label[3001:3985]
#print(y_train)
# 算法参数
params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 6,
    'gamma': 0.1,
    'max_depth': 6,
    'lambda': 2,
    'subsample': 0.7,
    'colsample_bytree': 0.7,
    'min_child_weight': 3,
    'silent': 1,
    'eta': 0.1,
    'seed': 1000,
    'nthread': 4,
}

plst = params.items()

dtrain = xgb.DMatrix(X_train, y_train) # 生成数据集格式
# print('11111111')
num_rounds = 500
model = xgb.train(plst, dtrain, num_rounds) # xgboost模型训练

# 对测试集进行预测
dtest = xgb.DMatrix(X_test)
y_pred = model.predict(dtest)

# 计算准确率
accuracy = accuracy_score(y_test,y_pred)
print("accuarcy: %.2f%%" % (accuracy*100.0))


def shell_sort(array):
    length = len(array)
    gap = length // 2

    while gap > 0:
        for i in range(gap, length):
            anchor = array[i]
            j = i
            while j >= gap and array[j - gap] > anchor:
                array[j] = array[j - gap]
                j -= gap
            array[j] = anchor
        gap //= 2

    return array


import dv_project
import dv_comp_render

class dv_build():

    def __init__(self):
        self.dv_proj = dv_project.dv_project()
        self.dv_proj.read_project()

    def command_build(self,name):
        dv_render = dv_comp_render.dv_comp_render()
        data = self.dv_proj.read_project()

        tpl_dir = data['about']['template_dir']
        context = data['objects'][name]
        #for chld in data['objects'][]
        #context['children'].update()

        if (data['objects'][name]['kind'] == 'agent'):
            output = dv_render.render(tpl_dir + '/agent/uvm_agent_driver.svh' , context)
            print (output)
        else:
            output = dv_render.render(tpl_dir + '/uvm_object.svh' , context)
            print (output)


import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例1(self):
        input = """abcabc
2"""
        output = """3"""
        self.assertIO(input, output)

    def test_入力例2(self):
        input = """aaaaa
1"""
        output = """1"""
        self.assertIO(input, output)

    def test_入力例3(self):
        input = """hello
10"""
        output = """0"""
        self.assertIO(input, output)

def resolve():
  inf = 10**18+1
  # S が短いので全パターン set に投げ込めば良さそう。
  S = input()
  K = int(input())
  ans = set()
  for i in range(len(S) - K + 1):
    ans.add(S[i:i+K])
  print(len(ans))

resolve()

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


"""
    Exercício 82

    Crie um programa que vai ler vários números e colocar em uma lista
Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados,
respectivamente.
Ao final, mostre o conteúdo das três listas geradas.
"""

valores = []
par = []
impar = []

while True:
    valores.append(int(input('Digite um número: ')))

    resposta = str(input('Quer continuar? [S/N] ')).upper()
    while resposta not in 'SN':
        resposta = str(input('Quer continuar? [S/N] ')).upper()

    if resposta == 'N':
        break

for c in valores:
    if c % 2 == 0:
        par.append(c)
    else:
        impar.append(c)

print('-='*30)
print(f'''A lista completa é {sorted(valores)}
A lista de pares é {sorted(par)}
A Lista de ímpares é {sorted(impar)}''')

Exercícios Mundo 3 ( 72 à 115 )/ex082.py


import numpy as np
import math  as m
import sys

# Respostas analiticas para os autovalores e autovetores
def gabaritoA(n):
    vet = np.eye(n)
    val = np.zeros(n)

    for i in range(n):
        for j in range(n):
            vet[j][n - 1 - i] = m.sin((m.pi / (n + 1)) * (j + 1) * (i + 1))

    for l in range(n):
        val[n - 1 - l] = 2 * (1 - m.cos((m.pi / (n + 1)) * (l + 1)))

    return vet, val

# Funcao sgn
def sgn(d):
    if d >= 0:
        result =  1
    else:
        result = -1
    return result

# Funcao para a heuristica de wilkinson
def wilkinson(a_n1, a_n, b_n1):
    d_k = (a_n1 - a_n)/2
    if (d_k ** 2) >= (b_n1 ** 2):
        mu_k = a_n + d_k - sgn(d_k) * m.sqrt((d_k ** 2) - (b_n1 ** 2))
    else:
        mu_k = 0.0

    return mu_k

def QR_factorization(a, n, mu_k, v):
    c = np.zeros(n - 1)  # vetor de 0's de tamanho n-1
    s = np.zeros(n - 1)

    QkTo = np.eye(n)
    QkT = np.eye(n)

    # Vamos encontrar a matriz Qk e QkT:
    for k in range(0, n - 1, 1):
        Qk = np.eye(n)

        # Definindo os ck e sk
        ck = a[k][k] / m.sqrt(a[k][k] ** 2 + a[k + 1][k] ** 2)
        sk = -a[k + 1][k] / m.sqrt(a[k][k] ** 2 + a[k + 1][k] ** 2)

        # Definindo Qk
        for i in range(n):
            for j in range(n):
                if i == k and j == k:
                    Qk[i][j] = ck
                    Qk[i + 1][j + 1] = ck
                    Qk[i][j + 1] = -sk
                    Qk[i + 1][j] = sk

        QkT = Qk.transpose()
        QkT = np.dot(QkTo, QkT)
        QkTo = QkT

        a = np.dot(Qk, a)  # Ao final, esta sera a matriz R

    # Vamos determinar a matriz A^(k + 1):
    a = np.dot(a, QkT)

    # Ajuste da diagonal principal de A^(k + 1)
    for i in range(n):
        a[i][i] = a[i][i] + mu_k

    # Agora vamos calcular a matriz V^(k + 1):
    v = np.dot(v, QkT)

    return a, v

def QR_algorithm(a, n, eps):
    k = 0
    v = np.eye(n)     # matriz identidade de tamanho nxn

    #  "1" para QR com deslocamento espectral ou "0" para QR sem deslocamento espectral
    desloc = sys.argv[3]

    for l in range(n - 1, 0, -1):

        while m.fabs(a[l - 1][l - 2]) >= eps:

            if k > 0 and desloc == "1":
                mu_k = wilkinson(a[n - 2][n - 2], a[n - 1][n - 1], a[n - 1][n - 2])

            else:
                mu_k = 0.0

            # atualizando a diagonal principal, linha 6 do pseudocodigo
            for i in range(n):
                a[i][i] = a[i][i] - mu_k

            # fatoracao QR
            a, v = QR_factorization(a, n, mu_k, v)

            k = k + 1

    print("\nNúmero de passos computados: ", k)
    return a, v

if __name__ == '__main__':
    # n desejado
    n = int(sys.argv[1])

    # epsilon desejado (utilizar ponto no lugar da vírgula)
    eps = float(sys.argv[2])

    a = np.zeros((n, n))

    # Definindo a matriz A de acordo com o exercicio A do enunciado
    for i in range(1, n - 1, 1):
        a[i - 1][i] = -1.0
        a[i][i]     =  2.0
        a[i + 1][i] = -1.0

    a[0][0] = 2.0
    a[1][0] = -1.0
    a[n - 2][n - 1] = -1.0
    a[n - 1][n - 1] =  2.0

    a, v = QR_algorithm(a, n, eps) # chamando a funcao que faz o calculo numerico

    vet, val = gabaritoA(n)        # chamando a funcao gabarito

    print("\nGabarito autovalores:")
    for i in range(n):
        print("a[{}]: {}".format(i, val[i]))

    print("\nAutovalores obtidos:")
    for i in range(n):
        print("a[{}]: {}".format(i, np.round(a[i][i], 2)))

    print("\nGabarito autovetores: \n", vet)
    print("\nAutovetores obtidos(arredondado): \n", np.round(v, 2))

    # Calculo dos erros relativos dos autovalores, em percentual
    compval = np.zeros(n)

    for i in range(n):
        compval[i] = val[i] - a[i][i]
        compval[i] = (compval[i] / val[i]) * 100

    print("\nErro relativo dos autovalores (em %): \n", compval)


import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt

from model import AlexNet

def main():
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print("using {} device".format(device))

    data_transform = transforms.Compose(
        [transforms.Resize((224, 224)),
         transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
    )

    base_path = "C:\\Users\\zhangshangyuan\\Desktop\\machine_learning\\AlexNet花朵数据集\\"
    # load_image
    img_path = base_path + "flower\\val\\roses\\1402130395_0b89d76029.jpg"
    assert os.path.exists(img_path), "file '{}' does not exit".format(img_path)
    img = Image.open(img_path)
    plt.imshow(img)

    img = data_transform(img)
    img = torch.unsqueeze(img, dim=0)

    json_path = base_path + "flower\\class_indices.json"
    assert os.path.exists(
        json_path), "file '{}' does not exit".format(json_path)
    json_file = open(json_path, "r")
    # {'0': 'daisy', '1': 'dandelion', '2': 'roses', '3': 'sunflowers', '4': 'tulips'}
    class_index = json.load(json_file)

    # create model and load parameters
    model = AlexNet(num_class=5).to(device)
    weights_path = base_path + 'AlexNet\\checkpoints\\AlexNet_for_flower.pth'
    assert os.path.exists(
        weights_path), "file '{}' does not exit".format(weights_path)
    model.load_state_dict(torch.load(weights_path))

    # infer
    model.eval()
    with torch.no_grad():
        # predict class
        output = torch.squeeze(model(img.to(device))).cpu()
        predict = torch.softmax(output, dim=0)
        predict_class = torch.argmax(predict).numpy()

    print_res = "class: {}   prob: {:.3}".format(class_index[str(predict_class)],
                                                 predict[predict_class].numpy())
    plt.title(print_res)
    for i in range(len(predict)):
        print("class: {:10}   prob: {:.3}".format(class_index[str(i)],
                                                  predict[i].numpy()))
    plt.show()

if __name__ == '__main__':
    main()


"""
    This program sends a message to a queue.
    The csv used in this program simulates end of period scores for a night of hockey in the NHL.
    In real life, these messages would be sent at the end of each period. For the sake of this project, messages are sent at 30 second intervals.

    Author: Dylan Eggemeyer
    Date: February 20, 2023

"""
import pika
import sys
import webbrowser
import csv
import time

# Define Global Variables

# decide if you want to show the offer to open RabbitMQ admin site
# Input "True" or "False"
show_offer = "False"

def offer_rabbitmq_admin_site():
    """Offer to open the RabbitMQ Admin website"""
    ans = input("Would you like to monitor RabbitMQ queues? y or n ")
    print()
    if ans.lower() == "y":
        webbrowser.open_new("http://localhost:15672/#/queues")
        print()

def send_message(host: str):
    """
    Creates and sends a message to the queue each execution.
    This process runs and finishes.

    Parameters:
        host (str): the host name or IP address of the RabbitMQ server
    """

    try:
        # create a blocking connection to the RabbitMQ server
        conn = pika.BlockingConnection(pika.ConnectionParameters(host))
        # use the connection to create a communication channel
        ch = conn.channel()
        # use the channel to delete the queue
        ch.queue_delete(queue="hockey_queue")
        # use the channel to declare the durable queue
        ch.queue_declare(queue="hockey_queue", durable=True)

        # open the input file
        input_file = open("hockey_scores.csv", "r")
        # read the input file
        reader = csv.reader(input_file,delimiter=",")
        # skip the headers
        next(reader, None)
        # get message from each row of file
        for row in reader:
            # read a row from the file
            Period, Team1, Team1_Score, Team2, Team2_Score  = row

            # use f string to create message from data
            f_message = f"{Period}, {Team1}, {Team1_Score}, {Team2}, {Team2_Score}"

            # Serialize the message into binary data
            message = f_message.encode()

            # send the message to an individual queue
            ch.basic_publish(exchange="", routing_key="hockey_queue", body=message)

            # print a message to the console for the user
            print(f" [x] Sent {message}")

            # wait 30 seconds before sending next score
            time.sleep(30)
        # close the file
        input_file.close()

    except pika.exceptions.AMQPConnectionError as e:
        print(f"Error: Connection to RabbitMQ server failed: {e}")
        sys.exit(1)
    finally:
        # close the connection to the server
        conn.close()

# Standard Python idiom to indicate main program entry point
# This allows us to import this module and use its functions
# without executing the code below.
# If this is the program being run, then execute the code below
if __name__ == "__main__":
    # show the offer to open Admin Site if show_offer is set to true, else open automatically
    if show_offer == "True":
        offer_rabbitmq_admin_site()
    else:
        webbrowser.open_new("http://localhost:15672/#/queues")
        print()
    # Use the send_message function to start the stream
    send_message("localhost")


from mimetypes import init
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import os

db = SQLAlchemy()
BASEDIR = os.path.dirname(os.path.realpath(__file__))

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'thisisaverysecretkey'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///movies.db'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'

    from .models import Users

    init_db(app)

    @login_manager.user_loader
    def load_user(id):
        return Users.query.get(id)

    from .views import views as views_blueprint
    app.register_blueprint(views_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
    from .request import get_movie_genres
    app.jinja_env.globals.update(get_movie_genres=get_movie_genres)

    return app

def init_db(app):
    if not os.path.lexists(os.path.join(BASEDIR, '\movies.db')):
        db.create_all(app=app)


def run(shell, args):
    if args:
        path = shell.sabs_path(args[0])
    else:
        path = shell.get_path()
    global fs
    fs = shell.syscall
    tree = tree_gen(path)
    shell.stdout.write(tree_print(tree))

def sorter(x):
    return ("f" if fs.is_file(x) else "d") + x.lower()

def tree_gen(path):
    pathtree = [path]
    if fs.is_dir(path):
        listing = sorted([fs.join_path(path, x) for x in fs.list_dir(path)],
                 key=sorter)
        for x in listing:
            pathtree.append(tree_gen(fs.join_path(path, x)))
    return pathtree

def tree_print(tree, level=0, extra="", idx=None):
    string = ''
    for i, x in enumerate(tree):
        spacing = "   " if (level > 1) else ''
        bar = "|" if (level > 0) else ''
        added = extra + spacing + bar
        if type(x) is list:
            string += tree_print(x, level + 1, added, len(tree) - 1 == i)
        else:
            char = "-- " if fs.is_file(x) else "++ "
            if x != "/":
                x = fs.base_name(x)
            end = "%s%s\n" % (char if (level > 0) else '', x)
            if not idx:
                string += "%s%s" % (added, end)
            else:
                string += "%s`%s" % (added[:-1], end)
    return string

def help():
    a = """
    Tree

    Returns the file/directory tree of the given directory.

    usage: tree [directory]
    """
    return a


import os
import argparse
import operator
import numpy as np
from tqdm import tqdm

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('output')
    parser.add_argument('--num_sample', type=int, default=1000)
    parser.add_argument('--min', type=int, default=0)
    parser.add_argument('--max', type=int, default=999)
    parser.add_argument('--num_op', type=int, default=2)

    args = parser.parse_args()
    return args

if __name__=='__main__':
    args = get_args()
    op = [operator.add, operator.sub, operator.mul, operator.ifloordiv]
    str_op = ['+', '-', '*', '/']
    with open(args.output, 'w') as f:
        for i in tqdm(range(args.num_sample)):
            a = np.random.randint(args.min, args.max)
            b = np.random.randint(args.min, args.max)
            o = np.random.randint(0,args.num_op)
            c = op[o](a,b)
            s = str(a)+str(str_op[o])+str(b)+'=^'+str(c)+'$\n'
            f.write(s)