import os
import requests
import numpy as np
import pandas as pd
import yfinance as yf
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import matplotlib.style as style
import matplotlib.dates as mdates
from datetime import timedelta, date
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.experimental import enable_hist_gradient_boosting

# Ask the user for the stock ticker symbol
stock_ticker = input("Enter the stock ticker symbol: ")

# Get the date 1 week ago
one_week_ago = date.today() - timedelta(weeks=1)

# Download the stock data for the chosen stock
stock_data = yf.download(stock_ticker, start=one_week_ago)

# Check if the 'Date' column is present, if not create it
if 'Date' not in stock_data.columns:
 stock_data['Date'] = stock_data.index

# Convert the date column to a datetime object if it's not in the correct format
stock_data['Date'] = pd.to_datetime(stock_data['Date'])

# Set the date column as the index
stock_data.set_index('Date', inplace=True)

# Sort the data by date
stock_data.sort_index(inplace=True)

# Make the request to the Yahoo Finance website
url = f'https://finance.yahoo.com/quote/{stock_ticker}/news'
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')

# Find all the news articles
articles = soup.find_all('li', class_='js-stream-content')

news_data = []

# Print the title, source, and summary of each article
for article in articles:
    title = article.find('h3').text
    source = article.find('span', class_='C($c-fuji-grey-c) Fz(11px)').text
    summary = article.find('p').text
    date = article.find('time').text
    news_data.append({'title': title, 'source': source, 'summary': summary, 'date': date})

# Print the response content of the website
print(response.content)

# Print the first news article data in the list
print(pd.DataFrame(news_data))

# Convert the news data to a DataFrame
news_data = pd.DataFrame(news_data)

# Convert date to datetime format
news_data['Date'] = pd.to_datetime(news_data['Date'])

# Set the date column as the index
news_data.set_index('date', inplace=True)

# Sort the data by date
news_data.sort_index(inplace=True)

# Merge the stock and news data
data = pd.merge(stock_data, news_data, left_index=True, right_index=True)

# Select the last week's worth of data
last_week = data.iloc[-7:]

# Split the data into X (features) and y (target)
X = last_week.drop(columns=['Close'])
y = last_week['Close']

# Use CountVectorizer to extract features from the news articles
vectorizer = CountVectorizer()
X_news = vectorizer.fit_transform(X['Article'])

# Concatenate the news features with the other features
X = pd.concat([X.drop(columns=['Article']), pd.DataFrame(X_news.toarray())], axis=1)

# Train a random forest regressor on the data
model = RandomForestRegressor()
model.fit(X, y)

# Make predictions for the next 30 days
future_dates = pd.date_range(start=data.index[-1], periods=30, freq='D')
future_data = pd.DataFrame(index=future_dates, columns=X.columns)
predictions = model.predict(future_data)

# Calculate the standard deviation of the last year's close prices
std_dev = predictions.std()

# Generate random values with a standard deviation of 0.5 * the last year's close prices standard deviation
random_values = np.random.normal(0, 0.2 * std_dev, predictions.shape)

# Add the random values to the predicted prices
predictions += random_values
predictions_df = pd.DataFrame(predictions, index=future_dates, columns=['Close'])

# Concatenate the last_year and predictions dataframes
predictions_df = pd.concat([last_year, predictions_df])

# Create a new DataFrame to store the predictions
predictions_df = pd.DataFrame(index=future_dates, columns=['Prediction'])
predictions_df['Prediction'] = predictions

# Set the style to dark theme
style.use('dark_background')

# Create the plot
fig, ax = plt.subplots()
for i in range(len(predictions)):
    if predictions[i] < data['Close'].iloc[-1]:
        plt.plot(future_dates[i], predictions[i], '-or', label='Predicted')
    else:
        plt.plot(future_dates[i], predictions[i], '-og', label='Predicted')
plt.plot(data['Close'], label='Actual', color='blue')
plt.title('AAPL Stock Price Predictions')
plt.xlabel('Day')
plt.ylabel('Price (USD)')
plt.legend()

# Set the x-axis tick locator
ax.xaxis.set_major_locator(mdates.DayLocator(interval=55))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# Show the plot
plt.show()


# basic python and ML Libraries
import os
import random
import numpy as np
import pandas as pd
import math
import time

# for ignoring warnings
import warnings
warnings.filterwarnings('ignore')

# We will be reading images using OpenCV
import cv2

# matplotlib for visualization
import matplotlib.pyplot as plt
import matplotlib.patches as patches

# torchvision libraries
import torch
import torchvision
from torchvision import transforms as torchtrans
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor

# helper libraries
import utils
from coco_utils import get_coco_api_from_dataset
from coco_eval import CocoEvaluator

# for image augmentations
import albumentations as A
from albumentations.pytorch.transforms import ToTensorV2

##############
# Utils      #
##############
def plot_img_bbox(img, target):
  fig, a = plt.subplots(1,1)
  fig.set_size_inches(5,5)
  a.imshow(img)
  for box in (target['boxes']):
    box = box.cpu()

    x, y, width, height  = box[0], box[1], box[2]-box[0], box[3]-box[1]

    rect = patches.Rectangle(
      (x, y),
      width, height,
      linewidth = 2,
      edgecolor = 'r',
      facecolor = 'none'
    )

    a.add_patch(rect)
  plt.show()

##############
# Dataset    #
##############
class ConeImagesDataset(torch.utils.data.Dataset):
  def __init__(self, files_dir, width, height, transforms=None):
    self.transforms = transforms
    self.files_dir = files_dir
    self.height = height
    self.width = width

    self.imgs = [image for image in sorted(os.listdir(files_dir)) if image[-4:]=='.jpg']

    self.classes = ['background', 'cone']

  def __getitem__(self, idx):
    img_name = self.imgs[idx]
    image_path = os.path.join(self.files_dir, img_name)

    img = cv2.imread(image_path)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype(np.float32)
    img_res = cv2.resize(img_rgb, (self.width, self.height), cv2.INTER_AREA)
    img_res /= 255.0

    annot_filename = img_name[:-4] + '.txt'
    annot_file_path = os.path.join(self.files_dir, annot_filename)

    boxes = []
    labels = []

    wt = img.shape[1]
    ht = img.shape[0]

    # box coordinates for xml files are extracted and corrected for image size given
    with open(annot_file_path) as f:
      for line in f:
        labels.append(1)

        parsed = [float(x) for x in line.split(' ')]
        x_center = parsed[1]
        y_center = parsed[2]
        box_wt = parsed[3]
        box_ht = parsed[4]

        xmin = x_center - box_wt/2
        xmax = x_center + box_wt/2
        ymin = y_center - box_ht/2
        ymax = y_center + box_ht/2

        xmin_corr = int(xmin*self.width)
        xmax_corr = int(xmax*self.width)
        ymin_corr = int(ymin*self.height)
        ymax_corr = int(ymax*self.height)

        boxes.append([xmin_corr, ymin_corr, xmax_corr, ymax_corr])

    boxes = torch.as_tensor(boxes, dtype=torch.float32)
    area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])

    iscrowd = torch.zeros((boxes.shape[0],), dtype=torch.int64)
    labels = torch.as_tensor(labels, dtype=torch.int64)

    target = {}
    target["boxes"] = boxes
    target["labels"] = labels
    target["area"] = area
    target["iscrowd"] = iscrowd
    image_id = torch.tensor([idx])
    target["image_id"] = image_id

    if self.transforms:
      sample = self.transforms(image = img_res,
                                bboxes = target['boxes'],
                                labels = labels)
      img_res = sample['image']
      target['boxes'] = torch.Tensor(sample['bboxes'])

    return img_res, target

  def __len__(self):
    return len(self.imgs)

##############
# Analysis   #
##############
files_dir = './content/img/'
test_dir = './content/img1/'

dataset = ConeImagesDataset(files_dir, 224, 224)
img, target = dataset[78]

print('Length of dataset:', len(dataset), '\n')
print('Image shape:', img.shape)
print('Label example:', target)

img, target = dataset[25]
plot_img_bbox(img, target)

##############
# Transform  #
##############
train_transform = A.Compose(
      [
        A.HorizontalFlip(0.5),
        ToTensorV2(p=1.0)
      ],
      bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']}
    )

test_transform = A.Compose(
      [
        ToTensorV2(p=1.0)
      ],
      bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']}
    )

##############
# Data       #
##############

dataset = ConeImagesDataset(files_dir, 480, 480, transforms=train_transform)
dataset_test = ConeImagesDataset(files_dir, 480, 480, transforms=test_transform)

# split the dataset in train and test set
torch.manual_seed(1)
indices = torch.randperm(len(dataset)).tolist()

# train test split
test_split = 0.2
tsize = int(len(dataset)*test_split)
dataset = torch.utils.data.Subset(dataset, indices[:-tsize])
dataset_test = torch.utils.data.Subset(dataset_test, indices[-tsize:])

# define training and validation data loaders
data_loader = torch.utils.data.DataLoader(
  dataset,
  batch_size=1,
  shuffle=True,
  num_workers=1,
  collate_fn=utils.collate_fn,
)

data_loader_test = torch.utils.data.DataLoader(
  dataset_test,
  batch_size=1,
  shuffle=False,
  num_workers=1,
  collate_fn=utils.collate_fn,
)

def get_object_detection_model(num_classes):
  model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)

  in_features = model.roi_heads.box_predictor.cls_score.in_features
  model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
  return model

device =  torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
num_classes = 2 # IMPORTANT: One class is the background, the other the CONE
model = get_object_detection_model(num_classes)
model.to(device)

params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)
lr_scheduler = torch.optim.lr_scheduler.StepLR(
  optimizer,
  step_size=3,
  gamma=0.1
)

##############
# Training   #
##############
def train_epoch(model, optimizer, data_loader, device, epoch, print_freq):
    model.train()
    metric_logger = utils.MetricLogger(delimiter="  ")
    metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))
    header = 'Epoch: [{}]'.format(epoch)

    lr_scheduler = None
    if epoch == 0:
        warmup_factor = 1. / 1000
        warmup_iters = min(1000, len(data_loader) - 1)

        lr_scheduler = utils.warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor)

    for images, targets in metric_logger.log_every(data_loader, print_freq, header):
        images = list(image.to(device) for image in images)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]

        loss_dict = model(images, targets)

        losses = sum(loss for loss in loss_dict.values())

        # reduce losses over all GPUs for logging purposes
        loss_dict_reduced = utils.reduce_dict(loss_dict)
        losses_reduced = sum(loss for loss in loss_dict_reduced.values())

        loss_value = losses_reduced.item()

        if not math.isfinite(loss_value):
            print("Loss is {}, stopping training".format(loss_value))
            print(loss_dict_reduced)
            return

        optimizer.zero_grad()
        losses.backward()
        optimizer.step()

        if lr_scheduler is not None:
            lr_scheduler.step()

        metric_logger.update(loss=losses_reduced, **loss_dict_reduced)
        metric_logger.update(lr=optimizer.param_groups[0]["lr"])

@torch.no_grad()
def evaluate_model(model, data_loader, device):
    n_threads = torch.get_num_threads()
    torch.set_num_threads(1)
    cpu_device = torch.device("cpu")
    model.eval()
    metric_logger = utils.MetricLogger(delimiter="  ")
    header = 'Test:'

    coco = get_coco_api_from_dataset(data_loader.dataset)

    # IOU Type
    model_without_ddp = model
    if isinstance(model, torch.nn.parallel.DistributedDataParallel):
        model_without_ddp = model.module

    iou_types = ["bbox"]
    if isinstance(model_without_ddp, torchvision.models.detection.MaskRCNN):
        iou_types.append("segm")
    if isinstance(model_without_ddp, torchvision.models.detection.KeypointRCNN):
        iou_types.append("keypoints")
    #

    #coco_evaluator = CocoEvaluator(coco, iou_types)

    for image, targets in metric_logger.log_every(data_loader, 100, header):
        image = list(img.to(device) for img in image)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]

        torch.cuda.synchronize()
        model_time = time.time()
        outputs = model(image)
        outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs]
        model_time = time.time() - model_time

        res = {target["image_id"].item(): output for target, output in zip(targets, outputs)}
        evaluator_time = time.time()
        #coco_evaluator.update(res)
        evaluator_time = time.time() - evaluator_time
        metric_logger.update(model_time=model_time, evaluator_time=evaluator_time)

    metric_logger.synchronize_between_processes()
    print("Averaged stats:", metric_logger)
    #coco_evaluator.synchronize_between_processes()

    #coco_evaluator.accumulate()
    #coco_evaluator.summarize()
    torch.set_num_threads(n_threads)
    #return coco_evaluator

num_epochs = 1
for epoch in range(num_epochs):
    train_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)

    lr_scheduler.step()
    #evaluate_model(model, data_loader_test, device=device)

##############
# Evaluation #
##############
test_dataset = ConeImagesDataset(test_dir, 480, 480, transforms=train_transform)
img, target = test_dataset[10]

model.eval()
with torch.no_grad():
  prediction = model([img.to(device)])[0]

# Image
def torch_to_pil(img):
  return torchtrans.ToPILImage()(img).convert('RGB')
img = torch_to_pil(img.to(torch.device('cpu')))

# Predictions
def apply_nms(orig_prediction, iou_thresh=0.3):
  keep = torchvision.ops.nms(orig_prediction['boxes'], orig_prediction['scores'], iou_thresh)

  final_prediction = orig_prediction
  final_prediction['boxes'] = final_prediction['boxes'][keep]
  final_prediction['scores'] = final_prediction['scores'][keep]
  final_prediction['labels'] = final_prediction['labels'][keep]

  return final_prediction
nms_prediction = apply_nms(prediction, iou_thresh=0.01)

plot_img_bbox(img, nms_prediction)


from unittest import TestCase
from TickerLister import TickerLister
from config import *

class TestTickerLister(TestCase):
    def test_get_ticket_by_id(self):
        _,ret = TickerLister().get_ticket_by_id("abv")
        self.assertTrue(ret == INVALID_TICKET_ID)

    def test_get_tickets_by_page_url(self):
        res,status_code = TickerLister().get_tickets_by_page_url(f"{TICKETS_BY_PAGINATION}1")
        self.assertEqual(type(res),dict,"received invalid response")
        res = TickerLister().get_tickets_by_page_url("httP://dnmcbdscbldclk.com")
        self.assertEqual(res, None, "Invalid url check failed")


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm

from stochastic_synapses.parameters import param
from stochastic_synapses.utils import load_data, load_dataloader, update_probabilities, \
	reformat_data

if (param['dataloader']):
	trainloader, testloader = load_dataloader()
else:
	train_data, train_label_bin, train_label, test_data, test_label_bin, test_label = load_data(param['dataset'], 28,
	                                                                               28)
print(train_data.shape, train_label.shape)

class base_model(nn.Module):
	'''
	The basic MLP model
	'''

	def __init__(self):
		super(base_model, self).__init__()
		self.fc1 = nn.Linear(784, 200)
		self.fc2 = nn.Linear(200, 200)
		self.fc3 = nn.Linear(200, param['n_classes'])

	def forward(self, x):
		x = F.relu(self.fc1(x.view(x.shape[0], -1)))
		x = F.relu(self.fc2(x))
		x = F.softmax(self.fc3(x))
		return x

class stochastic_model(nn.Module):
	'''
	The model with the stochastic synapses
	Variables starting with m are the trainable weight magnitudes.
	Variables starting with p are the weight probabilities.
	Variables starting with b are the bernoulli distributions of the probabilities
	'''

	def __init__(self):
		super(stochastic_model, self).__init__()
		self.m1 = torch.nn.Parameter(torch.randn(param['input_size'], param['hidden_size']), requires_grad=True)
		self.p1 = torch.nn.Parameter(torch.empty(param['input_size'], param['hidden_size']).fill_(0.25),
		                             requires_grad=False)
		self.b1 = torch.nn.Parameter(torch.bernoulli(self.p1), requires_grad=False)
		self.m2 = torch.nn.Parameter(torch.randn(param['hidden_size'], param['hidden_size']), requires_grad=True)
		self.p2 = torch.nn.Parameter(torch.empty(param['hidden_size'], param['hidden_size']).fill_(0.25),
		                             requires_grad=False)
		self.b2 = torch.nn.Parameter(torch.bernoulli(self.p2), requires_grad=False)
		self.m3 = torch.nn.Parameter(torch.randn(param['hidden_size'], param['n_classes']), requires_grad=True)
		self.p3 = torch.nn.Parameter(torch.empty(param['hidden_size'], param['n_classes']).fill_(0.25),
		                             requires_grad=False)
		self.b3 = torch.nn.Parameter(torch.bernoulli(self.p3), requires_grad=False)

	def forward(self, x):
		x = x.view(x.shape[0], -1)
		x = F.relu(x.mm(torch.div(torch.mul(self.m1, torch.bernoulli(self.p1)), (self.p1))))
		x = F.relu(x.mm(torch.div(torch.mul(self.m2, torch.bernoulli(self.p2)), (self.p2))))
		x = F.softmax(x.mm(torch.div(torch.mul(self.m3, torch.bernoulli(self.p3)), (self.p3))))
		return x

# Instantiating the model
model = stochastic_model()

# Loss function and the optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=param['lr'])

# Arrange the task information for the network
taskID = np.arange(0, param['n_tasks'] * param['n_classes'], 1).reshape(param['n_tasks'], param['n_classes'])
_type_in_ = torch.FloatTensor
_type_label_ = torch.LongTensor

# The accuracy matrix for the task
_acc_ = np.zeros((param['n_tasks'], param['n_tasks']))
'''
# def grad_multiplier_hook(grad):
# 	grad_val = grad.clone()
# 	grad_val = torch.mul(grad_val, )
# print (param['p1'])
'''
# Storing the initial probability parameters
probability_lookup_list = []
for name, params in model.named_parameters():
	if name.__contains__('p'):
		print(params.data.shape)
		probability_lookup_list.append(params)

def train_model(model, train_image, label):
	'''
	Train the binary net
	:param model: The specified model to be trained
	:param train_image: The selected training sample
	:param label: The corresponding label
	:return: loss: the accumulated loss of the model
	:return: output: The predicted output of the model
	'''
	# Generic forward pass
	gradient_lookup_list = []
	output = model(train_image)
	loss = criterion(output, label)
	optimizer.zero_grad()
	loss.backward()

	# Product of the gradients with the probability factor
	for name, param in model.named_parameters():
		if name.__contains__('m'):
			gradient_lookup_list.append(param.grad)
			param.grad = torch.mul(param.grad, (1 - probability_lookup_list[int(name[1]) - 1].data))
	# Update the weights
	optimizer.step()

	# Update the network probabilities
	for name, param in model.named_parameters():
		if name.__contains__('p'):
			param.data = update_probabilities(gradient_lookup_list[int(name[1]) - 1].data, param.data)
			print((param.data == probability_lookup_list[int(name[1]) - 1]).sum(), "The similar element")
			probability_lookup_list[int(name[1]) - 1] = param.data
		# print(torch.max(param.d   ata), torch.mean(param.data), "After update")
	return loss, output

def calc_accuracy(model, test_images, test_labels):
	'''
	Perform inference on the model
	:param model: The specified model to be trained
	:param test_images: The test images in the model
 	:param test_labels: The test labels in the model
	:return: acc: The accuracy of the model
	'''
	output = model(test_images)
	return (output.argmax(dim=1).long() == test_labels).float().mean()

for task in range(param['n_tasks']):
	print("Starting training on task {} {} ....".format(task + 1, taskID[task]))
	train_data_tensor, train_label_tensor = reformat_data(taskID[task], train_data, train_label)
	running_loss = 0.0
	for epochs in range(param['n_epochs']):
		count = 0.0
		for input_sample in tqdm(range(train_data_tensor.shape[0])):
			loss, output = train_model(model, train_data_tensor[input_sample], train_label_tensor[input_sample])
			count += (output.argmax(dim=1).long() == train_label_tensor[input_sample]).float().mean()
			running_loss += loss.item()

			if input_sample % 20 == 19:  # print every 20 mini-batches
				print('[%d, %5d] loss: %.3f  accuracy: %.2f' %
				      (epochs + 1, input_sample + 1, running_loss / 20, count / input_sample))
				running_loss = 0.0

		print("The training accuracy in this epoch --> {}".format(count / train_data_tensor.shape[0]))

	for subtask in range(task + 1):
		print("Testing on subtask ---> {}".format(subtask))
		test_data_tensor, test_label_tensor = reformat_data(taskID[subtask], test_data, test_label)
		for input_sample in tqdm(range(test_data_tensor.shape[0])):
			_acc_[task][subtask] += calc_accuracy(model, test_data_tensor[input_sample],
			                                      test_label_tensor[input_sample])
		print("Accuracy in this subtask --> {}".format(_acc_[task][subtask] / test_data_tensor.shape[0]))
		_acc_[task][subtask] /= test_data_tensor.shape[0]

print("The accuracy matrix for the Split task \n {}".format(_acc_))

print("The mean accuracy on the Split MNIST task is {}".format(np.mean(_acc_[-1])))


import os
from anki import invoke
words ="sol,chevaux,verb,corps,embrasser,je,voiture,vÃªtement,garderobe".split(",")
# words ="je,suis"
donewords = []

def checkAnki():
  words = []
  f=open("out.txt", "r")
  if f.mode == 'r':
    for line in f:
      for word in line.split():
        words.append(word)
  print(len(words))
  notes = []

  for w in words:
    notes.append({
      "deckName": "French",
      "modelName": "2. Picture Words",
      "fields": {
        "Word": w,
      },
      "tags": [
          "asdf"
      ]
    })
  h = invoke("canAddNotes", notes=notes)
  print('h: ', h)
  i = 0
  for w in words:
    if not h[i]:
      print(w + " is in anki âœ…")
    i+=1

checkAnki()

def parsewords():
  os.system("echo " + " > out.txt")
  words = []
  f=open("hp1.txt", "r")
  if f.mode == 'r':
    for line in f:
      for word in line.split():
        words.append(word)

  for w in words:
    horse = os.popen("./dictionary " + w).read()
    # print("ðŸ”ðŸ”ðŸ”", word)
    # print('horse: ', horse)
    try:
      wrd = horse.split("|")[0].split(" ")[0]
      wrd.replace(",","")
      if wrd in donewords:
        continue
      donewords.append(wrd)
      st = wrd# + " " + horse.split("|")[1]+ ""
      horse = os.popen("echo \"" + st + "\" >> out.txt").read()
    except Exception as e:
      print("ðŸ‘Ž", e, word)
    # print('"./dictionary " + w + " > out.txt": ', "./dictionary " + w + " > out.txt")


import os
from typing import Any, Optional, List, Dict

import gspread
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials
import socket
from datetime import datetime
from time import sleep
import traceback

_current_experiment = None  # type: Optional[ExperimentParams]

def _experiment_running():
    return _current_experiment is not None

def log_experiment_id(experiment_id: str):
    """
    Sets experiment id
    :param experiment_id:
    :return:
    """
    if _experiment_running():
        _current_experiment.log_experiment_id(experiment_id)

def log_status(status: str):
    """
    Sets status of the current experiment
    :param status:
    """
    if _experiment_running():
        _current_experiment.log_status(status)

def log_comment(text: str):
    """
    Sets comment of the current experiment
    """
    if _experiment_running():
        _current_experiment.log_comment(text)

def log_progress(current: int, max_value: int):
    """
    Sets progress of the current experiment
    """
    if _experiment_running():
        _current_experiment.log_progress(current, max_value)

def log_metric(metric: str, value: Any):
    """
    Logs metric of the current experiment
    :param metric: metric name
    :param value: metric value
    """
    if _experiment_running():
        _current_experiment.log_metric(metric, value)

class ParamsException(Exception):
    pass

class ParamsSheet(object):
    def __init__(self, parser, client_credentials: str, params_sheet_id = None,
                 writable_column_types: Dict[str, Any]=None, experiment_id_column: str='experiment_id',
                 server_name: str=None, fill_empty_with_defaults=True):
        """
        ParamsSheet object represents state of google spreadsheet with parameters and all methods to access it.
        :param parser: Argparse parser object with no positional arguments
        :param writable_column_types: dict of names of model metric columns and their types.
        If it is None, writing unknown metrics won't generate warnings.
        :param experiment_id_column: str name of experiment id column.
        """
        self.client_credentials = client_credentials
        self.params_sheet_id = params_sheet_id
        self.experiment_id_column = experiment_id_column
        self.fill_empty_with_defaults = fill_empty_with_defaults
        self.parser = parser
        self.defaults = {
            _action.dest: _action.default
            for _action in self.parser._actions[1:]
        }

        # Setting up dictionaries holding column types
        self.metric_column_types = writable_column_types
        if self.metric_column_types is None:
            self.column_types = {}
        else:
            assert isinstance(self.metric_column_types, dict), "writable_column_types has to be a dict"
            self.column_types = writable_column_types.copy()
        self.column_types.update({
            _action.dest: _action.type
            for _action in self.parser._actions[1:]
        })

        # Getting server name
        if server_name is None:
            self.server = os.environ.get('SERVERNAME', None)
            if self.server is None:
                self.server = socket.gethostname()
        else:
            self.server = server_name + "_" + socket.gethostname()

        # Getting credentials
        self._generate_credentials()

    def update_cell(self, row, column_name, value):
        col = self.columns.index(column_name) + 1
        try:
            self.sheet.update_cell(row, col, value)
        except gspread.exceptions.APIError:
            self._generate_credentials()
            self.sheet.update_cell(row, col, value)

    def exec_loop(self, train_loop):
        """
        :param train_loop: train function that takes args namespace
        :return: None
        """
        global _current_experiment
        print("Starting worker...")
        timeout_power = 1
        while True:
            exp_params = None
            try:
                exp_params = self._get_params_for_training()
                _current_experiment = exp_params
                timeout_power = 4
                exp_params.log_status('running')
                exp_params.log_server()
                exp_params.log_time_to_column('time_started')
                train_loop(exp_params.args)
                exp_params.log_status('finished')
            except ParamsException:
                print("No params to process, waiting for {} seconds and checking again".format(2 ** timeout_power))
                sleep(2 ** timeout_power)
                if timeout_power <= 10:
                    timeout_power += 1
            except KeyboardInterrupt:
                if exp_params is not None:
                    exp_params.log_status('stopped')
                _current_experiment = None
            except Exception as e:
                tb = traceback.format_exc()
                print(tb)
                if exp_params is not None:
                    exp_params.log_comment(tb)
                    exp_params.log_status('error')
                _current_experiment = None

    def _generate_credentials(self):
        if isinstance(self.client_credentials, dict):
            credentials = ServiceAccountCredentials._from_parsed_json_keyfile(
                self.client_credentials, ['https://spreadsheets.google.com/feeds']
            )
        else:
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                self.client_credentials,['https://spreadsheets.google.com/feeds']
            )
        gc = gspread.authorize(credentials)
        self.sheet = gc.open_by_key(self.params_sheet_id).sheet1
        first_cell = self.sheet.cell(1, 1).value
        try:
            self.column_row_id = int(first_cell)
        except ValueError:
            self.column_row_id = 1
        self.columns = self.sheet.row_values(self.column_row_id)

    def _get_params_for_training(self) -> "ExperimentParams":
        """
        This function gets next experiment parameter settings
        """
        try:
            all_spreadsheet = pd.DataFrame(self.sheet.get_all_records(head=self.column_row_id, default_blank=""))
        except gspread.exceptions.APIError:
            self._generate_credentials()
            all_spreadsheet = pd.DataFrame(self.sheet.get_all_records(head=self.column_row_id, default_blank=""))
        params_to_process = all_spreadsheet[
            (all_spreadsheet.status == "") & (all_spreadsheet.server == "")]
        params_for_this_server = all_spreadsheet[
            (all_spreadsheet.status == "") & (all_spreadsheet.server == self.server)]
        if len(params_for_this_server):
            params_to_process = params_for_this_server
        if len(params_to_process) == 0:
            raise ParamsException("No params to process!")
        return ExperimentParams(
            params_to_process.index[0] + 1 + self.column_row_id,
            dict(params_to_process.iloc[0]),
            self, self.fill_empty_with_defaults)

class ExperimentParams(object):
    _system_columns = ('time_started', 'last_update', 'progress_bar', 'server', 'status', 'comment')

    def __init__(self, row_id, params, _params_sheet: ParamsSheet, fill_empty_with_defaults: bool):
        self._params_sheet = _params_sheet
        self._params_row_id = row_id
        self.args = _params_sheet.parser.parse_args()
        parameter_columns = set(_params_sheet.columns) - set(self._system_columns) - {_params_sheet.experiment_id_column}
        for _column_name in parameter_columns:
            # Skipping metric columns
            if _params_sheet.metric_column_types is not None and _column_name in _params_sheet.metric_column_types:
                continue

            parameter_value = params[_column_name]
            if isinstance(params[_column_name], str) and (params[_column_name] == ""):
                # This parameter field is empty
                if fill_empty_with_defaults:
                    parameter_value = getattr(self.args, _column_name, '')
                    self._params_sheet.update_cell(
                        self._params_row_id, _column_name,
                        parameter_value
                    )

            if _column_name not in _params_sheet.column_types:
                print("Unexpected column %s (known column: %s)" % (_column_name, ",".join(_params_sheet.column_types)))
                continue

            dtype = _params_sheet.column_types[_column_name]
            if dtype is None:  # type for bool is None
                dtype = lambda x: x.lower() == 'true'
            setattr(self.args, _column_name, dtype(parameter_value))

    def log_server(self):
        self._write_to_field('server', self._params_sheet.server)

    def log_time_to_column(self, column_name):
        now = datetime.now()
        self._write_to_field(column_name, now.strftime('%Y-%m-%d %H:%M:%S'))

    def log_status(self, status):
        self._write_to_field('status', status)

    def log_comment(self, text):
        self._write_to_field('comment', text)

    def log_progress(self, i, max_i):
        assert isinstance(i, int) and isinstance(max_i, int)
        if i == max_i:
            color = "green"
        else:
            color = "blue"
        formula = '=SPARKLINE({},{{"charttype","bar";"color1", "{}";"max",{}}})'.format(i, color, max_i)
        self._write_to_field('progress_bar', formula)
        self.log_time_to_column('last_update')

    def log_experiment_id(self, value):
        self._write_to_field(self._params_sheet.experiment_id_column, value)

    def log_metric(self, metric, value):
        if (self._params_sheet.metric_column_types is not None) and \
                (metric not in self._params_sheet.metric_column_types):
            print("Logging unknown metric %s" % metric)
        self._write_to_field(metric, value)
        self.log_time_to_column('last_update')

    def _write_to_field(self, column_name, value):
        self._params_sheet.update_cell(
            self._params_row_id,
            column_name,
            value)


import numpy as np
import pandas as pd
from tqdm import tqdm
import itertools, argparse, os, sys, random, logging, config, math
import scipy.stats as st

def chunker(df, batch_size):
	return [df[pos:pos + batch_size] for pos in range(0, len(df), batch_size)]

def compute_confidence_interval(outage_rounds, confidence=0.95):
	#return st.norm.interval(alpha=0.95, loc=np.mean(data), scale=st.sem(data))
	conf_interval = list(st.norm.interval(confidence, loc=np.mean(outage_rounds), scale=st.sem(outage_rounds)))

	if(math.isnan(conf_interval[0])):
		conf_interval[0] = 0

	if(math.isnan(conf_interval[1])):
		conf_interval[1] = 0

	return conf_interval

def computeOverallAccuracy(df_batch, threshold, n_branches):

	n_samples = len(df_batch)

	correct = df_batch.correct.sum()

	overall_acc = float(correct)/n_samples

	return overall_acc

def computeInferenceOutageProb(df_batches, threshold, n_branches):
	outage = 0
	for df_batch in df_batches:
		overall_acc = computeOverallAccuracy(df_batch, threshold, n_branches)
		outage += 1 if(overall_acc < threshold) else 0

	outage_prob = float(outage)/len(df_batches)
	return outage_prob

def computeAvgInferenceOutageProb(df, threshold, n_branches, n_rounds, n_batches):

	outage_rounds = []

	for n_round in range(n_rounds):
		#print("Number of Rounds: %s"%(n_round))

		df = df.sample(frac=1)
		df_batches = chunker(df, batch_size=n_batches)
		outage_prob = computeInferenceOutageProb(df_batches, threshold, n_branches)

		outage_rounds.append(outage_prob)

	outage_rounds = np.array(outage_rounds)

	avg_outage = np.mean(outage_rounds)

	ic_outage = compute_confidence_interval(outage_rounds)

	return avg_outage, ic_outage[0], ic_outage[1]

def getInfOutageProbThreshold(df, threshold, n_branches, n_rounds, n_batches, dist_type_data):

	avg_outage_list, bottom_ic_outage_list, upper_ic_outage_list = [], [], []

	for distortion_lvl in df.distortion_lvl.unique():
		df_dist_lvl = df[df.distortion_lvl == distortion_lvl]

		avg_outage, bottom_ic_outage, upper_ic_outage = computeAvgInferenceOutageProb(df, threshold, n_branches, n_rounds,
			n_batches)

		avg_outage_list.append(avg_outage), bottom_ic_outage_list.append(bottom_ic_outage)
		upper_ic_outage_list.append(upper_ic_outage)

	result_dict = {"avg_outage": avg_outage_list, "bottom_ic_outage": bottom_ic_outage_list,
	"upper_ic_outage": upper_ic_outage_list, "threshold": len(avg_outage_list)*[threshold],
	"distortion_lvl": df.distortion_lvl.unique(),
	"distortion_type_data": len(avg_outage_list)*[dist_type_data],
	"n_rounds": len(avg_outage_list)*[n_rounds], "n_batches": len(avg_outage_list)*[n_batches],
	"inf_mode": len(avg_outage_list)*["conventional"]}

	return result_dict

def main(args):

	overall_inf_outage_path = os.path.join(config.DIR_NAME, "inference_data", "caltech256", "mobilenet",
		"overall_inf_outage_prob_%s_branches_id_%s.csv"%(args.n_branches, args.model_id))

	inference_data_path = os.path.join(config.DIR_NAME, "inference_data", "caltech256", "mobilenet",
		"inference_data_backbone_id_%s_final_final.csv"%(args.model_id))

	threshold_list = np.arange(config.threshold_start, config.threshold_end, config.threshold_step)

	df_inf_data = pd.read_csv(inference_data_path)

	#print(df_inf_data.distortion_type_data.unique())

	df_pristine = df_inf_data[df_inf_data.distortion_type_data == "pristine"]
	df_blur = df_inf_data[df_inf_data.distortion_type_data == "gaussian_blur"]
	#df_noise = df_inf_data[df_inf_data.distortion_type_data == "gaussian_noise"]

	for threshold in threshold_list:
		print("Threshold: %s"%(threshold))

		pristine_outage = getInfOutageProbThreshold(df_pristine, threshold, args.n_branches, args.n_rounds,
			args.n_batches, dist_type_data="pristine")
		blur_outage = getInfOutageProbThreshold(df_blur, threshold, args.n_branches, args.n_rounds,
			args.n_batches, dist_type_data="gaussian_blur")

		save_outage_results(pristine_outage, edge_inf_outage_path)
		save_outage_results(blur_outage, edge_inf_outage_path)

if (__name__ == "__main__"):

	parser = argparse.ArgumentParser(description='UCB using MobileNet')
	parser.add_argument('--model_id', type=int, default=config.model_id, help='Model Id.')
	parser.add_argument('--distortion_type_model', type=str, default=config.distortion_type, help='Distortion Type.')
	parser.add_argument('--n_branches', type=int, default=config.n_branches, help='Number of exit exits.')
	parser.add_argument('--dataset_name', type=str, default=config.dataset_name, help='Dataset Name.')
	parser.add_argument('--model_name', type=str, default=config.model_name, help='Model name.')
	parser.add_argument('--cuda', type=bool, default=config.cuda, help='Cuda ?')
	parser.add_argument('--seed', type=int, default=config.seed, help='Seed.')
	parser.add_argument('--n_rounds', type=float, default=config.n_rounds_outage)
	parser.add_argument('--n_batches', type=int, default=config.batch_size_outage)

	args = parser.parse_args()
	main(args)


#!/usr/bin/python

"""
    Starter code for exploring the Enron dataset (emails + finances);
    loads up the dataset (pickled dict of dicts).

    The dataset has the form:
    enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }

    {features_dict} is a dictionary of features associated with that person.
    You should explore features_dict as part of the mini-project,
    but here's an example to get you started:

    enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000

"""

import pickle

enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "rb"))

# How many data points (people) are in the dataset?
print("How many data points (people) are in the dataset? ", len(enron_data))
print("How many data points (people) are in the dataset? ", len(enron_data.keys()))

# What features are available in this dataset?
print(enron_data[list(enron_data.keys())[0]].keys())

# For each person, how many features are available?
print("For each person, how many features are available?", \
	len(list(enron_data.values())[0]))
print("For each person, how many features are available?",
	len(enron_data[list(enron_data.keys())[0]].keys()))

# The “poi” feature records whether the person is a person of interest,
# How many POIs are there in the E+F dataset?
count = 0
for i in enron_data:
	if enron_data[i]["poi"] == 1:
		count += 1
print("How many POIs are there in the E+F dataset?", count)
print("How many email messages do we have from Wesley Colwell to persons of interest?", \
        enron_data['COLWELL WESLEY']['from_this_person_to_poi'])

# How Many POIs Exist?
poi_text = '/Users/yechenhua/version-control/ud120-projects/final_project/poi_names.txt'
poi_names = open(poi_text, 'rb')
fr = poi_names.readlines()
print("How many POI’s were there total?",len(fr[2:]))
poi_names.close()

## addition method to find file length. print poi_names.read()
num_lines = sum(1 for line in open(poi_text))
print("file length:",num_lines)

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print("file length:",file_len('/Users/yechenhua/version-control/ud120-projects/final_project/poi_names.txt'))

## Check if values exist in any string in the list
matching = [s for s in enron_data.keys() if "PRENTICE" in s]
print(matching)

#What is the total value of the stock belonging to James Prentice?
print("What is the total value of the stock belonging to James Prentice?",
        enron_data['PRENTICE JAMES']['total_stock_value'])

#How many email messages do we have from Wesley Colwell to persons of interest?
print("How many email messages do we have from Wesley Colwell to persons of interest?",
        enron_data['COLWELL WESLEY']['from_this_person_to_poi'])

#What’s the value of stock options exercised by Jeffrey Skilling?
print("What’s the value of stock options exercised by Jeffrey Skilling?",
        enron_data['SKILLING JEFFREY K']['exercised_stock_options'])

# Sort values
sorted(enron_data.keys())

# How much money did that person get?
print("How much money did that person get?",enron_data['SKILLING JEFFREY K']['total_payments'])
print("How much money did that person get?",enron_data['FASTOW ANDREW S']['total_payments'])
print("How much money did that person get?",enron_data['LAY KENNETH L']['total_payments'])

# How is an unfilled feature denoted?
print("How is an unfilled feature denoted?",enron_data['FASTOW ANDREW S']['deferral_payments'])

#How many folks in this dataset have a quantified salary? What about a known email address?
salary = 0
for i in enron_data:
	if enron_data[i]["salary"] != 'NaN' :
		salary += 1
print("How many folks in this dataset have a quantified salary?",salary)

email = 0
for i in enron_data:
	if enron_data[i]["email_address"] != 'NaN' :
		email += 1
print("How many folks in this dataset have a quantified salary?",email)

#from feature_format import featureFormat
#from feature_format import targetFeatureSplit

# How many people in the E+F dataset (as it currently exists) have “NaN” for their total payments?
# What percentage of people in the dataset as a whole is this?
count_NaN_tp = 0
for key in enron_data.keys():
    if enron_data[key]['total_payments'] == 'NaN':
        count_NaN_tp+=1
print("How many people in the E+F dataset (as it currently exists) have “NaN” for their total payments?",count_NaN_tp)
print("What percentage of people in the dataset as a whole is this?",float(count_NaN_tp)/len(enron_data.keys()))

# How many POIs in the E+F dataset have “NaN” for their total payments?
# What percentage of POI’s as a whole is this?
count_NaN_tp = 0
for key in enron_data.keys():
    if enron_data[key]['total_payments'] == 'NaN' and enron_data[key]['poi'] == True :
        print
        count_NaN_tp+=1
print("How many POIs in the E+F dataset have “NaN” for their total payments? ",count_NaN_tp)
print("What percentage of POI’s as a whole is this?",float(count_NaN_tp)/len(enron_data.keys()))


from collections import deque

v,e = map(int,input().split())

indegree = [0] * (v+1)

g = [[] for _ in range(v+1)]

for _ in range(e):
    a,b = map(int,input().split())
    g[a].append(b)
    indegree[b] += 1

def topology_sort():
    result = []
    q = deque()
    for i in range(1,v+1):
        if indegree[i] == 0:
            q.append(i)

    while q:
        now = q.popleft()
        result.append(result)

        for i in g[now]:
            indegree[i] -=1
            if indegree[i] == 0:
                q.append(i)

        for i in result:
            print(i)


string = input('Enter string: ')
new = ' '
b = 0

while b < len(string):
    s = string[b]
    if s.isupper():
        new +=  s+' '
    elif s.isdigit():
        new += s + str(int(s)*2 )
    else:
        new += s
    b += 1
print(new)


from src.manager.module_notice.constants import CUSTOM
from src.manager.handler.api.bk_chat import BkChatFeature
from src.manager.module_biz.handlers.biz_cache import get_biz_info
from src.manager.module_notice.handler.notice_cache import get_notice_group_data

class Notice:
    def __init__(self, im_type, msg_type, msg_content, receiver, headers, **kwargs):
        self.im_type = im_type.upper()
        self.msg_type = msg_type
        self.msg_content = msg_content
        self.receiver = receiver
        self.headers = headers
        self.kwargs = kwargs

    def send_origin_msg(self, msg_param):
        params = {
            "im": self.im_type,
            "msg_type": self.msg_type,
            "msg_param": msg_param,
            "receiver": self.receiver,
            "headers": self.headers,
        }
        biz_id = self.kwargs.get("biz_id")
        biz_info = get_biz_info(biz_id)
        send_data = {
            "biz_name": biz_info.get("bk_biz_name"),
            "biz_id": biz_id,
            "msg_source": self.kwargs.get("msg_source"),
            "msg_data": params,
            "msg_type": self.msg_type,
            "msg_context": self.msg_content,
            "im_platform": self.kwargs.get("im_platform"),
            "group_name": self.kwargs.get("group_name"),
            "raw_data": {},
        }
        _, send_result = BkChatFeature.send_msg_and_report(send_data)
        if send_result["code"] != 0:
            return {"result": False, "message": send_result["message"]}

        return {"result": True, "message": "OK"}

    def send(self):
        params = {
            "im": self.im_type,
            "msg_type": self.msg_type,
            "msg_param": {"content": self.msg_content},
            "receiver": self.receiver,
            "headers": self.headers,
            **self._extra_params,
        }
        biz_id = self.kwargs.get("biz_id")
        biz_info = get_biz_info(biz_id)
        send_data = {
            "biz_name": biz_info.get("bk_biz_name"),
            "biz_id": biz_id,
            "msg_source": self.kwargs.get("msg_source"),
            "msg_data": params,
            "msg_type": self.msg_type,
            "msg_context": self.msg_content,
            "im_platform": self.kwargs.get("im_platform"),
            "group_name": self.kwargs.get("group_name"),
            "raw_data": {},
        }
        _, send_result = BkChatFeature.send_msg_and_report(send_data)
        if send_result["code"] != 0:
            return {"result": False, "message": send_result["message"]}

        return {"result": True, "message": "OK"}

    @property
    def _extra_params(self):
        params = {}
        if self.im_type in ["SLACK", "SLACK_WEBHOOK"]:
            params = {
                "msg_type": "text",
                "msg_param": {"text": self.msg_content},
            }

        # 支持QQ的告警类型
        if self.im_type in ["QQ"]:
            params = {
                "msg_type": "0",
                "msg_param": {
                    "content": [{"data": self.msg_content}],
                },
            }

        # 支持飞书
        if self.im_type in ["LARK_WEBHOOK"]:
            params = {
                "msg_type": "post",
                "msg_param": {
                    "post": {
                        "zh-CN": {
                            "title": "",
                            "content": [[{"tag": "text", "text": self.msg_content}]],
                        }
                    }
                },
            }

        # 支持钉钉
        if self.im_type in ["DING_WEBHOOK"]:
            params = {
                "msg_type": "text",
                "msg_param": {"content": self.msg_content},
            }

        # 支持微信公众号
        if self.im_type in ["MINI_PROGRAM"]:
            params = {
                "msg_type": "mini",
                "msg_param": {
                    "first": {"value": self.msg_content},
                    "keynote1": {"value": "     -"},
                    "keynote2": {"value": "     -"},
                },
            }

        # 支持邮件
        if self.im_type in ["EMAIL"]:
            params = {
                "msg_param": {"title": self.kwargs.get("group_name", "BkChat消息通知"), "content": self.msg_content},
            }

        return params

def send_msg_to_notice_group(group_id_list, msg_type, msg_content, msg_param={}, custom_headers={}):
    notice_groups = get_notice_group_data(group_id_list)
    send_success = True
    fail_message_list = []
    fail_notice_group_id_list = []
    for notice_group in notice_groups:
        kwargs = {
            "im_platform": notice_group.get("im_platform"),
            "biz_id": notice_group.get("biz_id"),
            "msg_source": CUSTOM,
            "group_name": notice_group.get("notice_group_name"),
        }
        headers = notice_group.get("headers")
        headers.update(custom_headers)
        notice = Notice(
            notice_group.get("im"),
            msg_type,
            msg_content,
            notice_group.get("receiver"),
            headers,
            **kwargs,
        )
        if msg_param:
            send_result = notice.send_origin_msg(msg_param)
        else:
            send_result = notice.send()
        if not send_result["result"]:
            send_success = False
            fail_notice_group_id_list.append(notice_group["notice_group"])
            fail_message_list.append(
                f"[NoticeGroup-{notice_group['notice_group']}] send msg failed,error is {send_result['message']}"
            )

    return {
        "result": send_success,
        "message": "\n".join(fail_message_list),
        "fail_notice_group_id_list": fail_notice_group_id_list,
    }


from random import randint
from gettext import find

questao = int(input("Número da questão: "))

if questao == 1:
    ls = []
    while True:
        num = int(input("Insira seu número aqui: "))
        ls.append(num)
        if num == 0:
            ls.sort()
            print(ls)
            break
        else:
            ls.append(num)
            continue

elif questao == 2:
    ls = []
    while True:
        num = int(input("Insira seu número aqui: "))

        if num == 0:
            ls.sort()
            ls.reverse()
            print(ls)
            break
        else:
            ls.append(num)
            continue

elif questao == 3:

    ls = []

    while True:
        num = int(input("Insira seu número aqui: "))

        if num == 0:
            ls.sort()
            ls.pop(0)
            ls.reverse()
            ls.pop(0)
            ls.reverse()
            print(ls)
            break
        else:
            ls.append(num)
            continue

elif questao == 4:

    ls = []

    while True:
        text = input("Insira seu número aqui: ")

        if text == "":
            ls = list(dict.fromkeys(ls))
            print(ls)
            break
        else:
            ls.append(text)
            continue

elif questao == 5:

    ls = []
    ls1 = []
    ls2 = []
    ls3 = []
    while True:
        num = input("Insira seu número aqui: ")

        if num == "":

            ls = ls1 + ls2

            print(ls)
            break

        else:
            number = int(num)
            if number < 0:
                ls1.append(number)

                continue

            elif number > 0:
                ls2.append(number)

                continue

            continue

elif questao == 6:
    def divisores(div):
        htot = []

        for n in range(1, div + 1):
            if div % n == 0:
                h = [n]
                htot = htot + h

        return htot

    def main():
        exes = int(input("Número: "))
        print(divisores(exes))

    if __name__ == "__main__":
        main()

elif questao == 7:
    def divisores(div):
        htot = 0

        for n in range(1, div):
            if div % n == 0:
                h = n
                htot = htot + h
        if htot == div:
            return "É um numero perfeito"
        else:
            return "Não é um número perfeito"

    def main():
        exes = int(input("Número: "))
        print(divisores(exes))

    if __name__ == "__main__":
        main()

elif questao == 8:

    def textoooo(elton):

        eder = elton.replace(" ", "$$")
        eder = eder.replace("!", "$$")
        eder = eder.replace("?", "$$")
        eder = eder.replace(".", "$$")
        eder = eder.replace(",", "$$")
        eder = eder.replace("/", "$$")
        eder = eder.replace(":", "$$")
        eder = eder.replace(";", "$$")
        eder = eder.replace("-", "$$")
        eder = eder.split("$$")
        return eder

    def main():
        exes = input("Text: ")
        print(textoooo(exes))

    if __name__ == "__main__":
        main()

elif questao == 9:

    def order(ls, media):
        out = 0
        lslen = len(ls)
        alta = []
        abajo = []
        mediaaa = []

        while out != lslen:
            out = out + 1
            thingy = ls[0]
            thingy = int(thingy)

            if thingy < media:
                thingy = [thingy]
                abajo = abajo + thingy

            elif thingy == media:
                thingy = [thingy]
                mediaaa = mediaaa + thingy

            elif thingy > media:
                thingy = [thingy]
                alta = alta + thingy

            ls.pop(0)

        return f"notas abaixo da média: {abajo} \nnotas na média:{mediaaa} \nnotas acima da média: {alta}"

    def main():
        ls = []
        m = 0
        n = 0

        while True:
            num = input('Número (enter para sair): ')

            if num == '':
                print(order(ls, media))

                break

            else:

                num = int(num)

                y = num

                m = m + y

                n = n + 1
                media = m / n

                x = [num]
                ls = ls + x

    if __name__ == "__main__":
        main()

elif questao == 10:

    ls = []
    lse = ['e']
    lsr = []
    ls1 = []
    string = " "

    while True:
        item = [input("Texto: ")]

        if item[0] == "":

            if len(ls) > 2:
                ls.reverse()
                ls1 = [ls[0]]
                ls.pop(0)
                ls.reverse()
                ls = ls + lse + ls1
                x = string.join(ls)
                x = x.replace(" ", ", ")
                x = x.replace("e, ", "e ")
                if x.find(", e ") >= 1:
                    x = x.replace(", e ", " e ")
                print(x)
                break
            elif len(ls) == 2:
                ls1 = [ls[1]]
                ls.pop(1)
                ls = ls + lse + ls1
                x = string.join(ls)
                print(x)
                break
            elif len(ls) == 1:
                print(ls[0])
                break
            else:
                print("Insira um texto")

        else:
            ls = ls + item
            continue

elif questao == 11:

    sorteio = []
    for numeiro in range(6):
        rand = [randint(1, 60)]
        sorteio = sorteio + rand
        sorteio.sort()

    print(sorteio)

elif questao == 12:

    def main():
        ls =[]
        while True:
            term = input("Termo: ")

            if term == "":
                aaa = ls
                aaa = aaa.sort()

                if aaa == ls:
                    print("True")
                    break

                else:
                    print("False")
                    break

            else:
                term = int(term)
                term = [term]
                ls = ls + term
                continue

    if __name__ == "__main__":
        main()

elif questao == 13:
    def countRange(ls, mini, maxi):

        values = []
        ls.sort()
        lente = len(ls)
        for x in range(lente):
            if ls[0] >= mini and ls[0] < maxi:
                ls1 = [ls[0]]
                values = values + ls1
                ls.pop(0)

            else:
                ls.pop(0)
        return values

    def main():

        ls = []
        while True:
            term = input("Número(Enter para continuar): ")
            if term == "":
                break

            else:
                term = int(term)
                term = [term]
                ls = ls + term
                continue

        termmax = int(input("Valor máximo: "))
        termmin = int(input("Valor mínimo: "))

        print(countRange(ls, termmin, termmax))

    if __name__ == "__main__":
        main()

elif questao == 14:

    def precedencia(x):
        if x.find('-') >= 0 or x.find("+") >= 0:
            return 1

        elif x.find("*") >= 0 or x.find("/") >= 0:
            return 2

        elif x.find("^") >= 0:
            return 3

        else:
            return -1, "não é uma precedência"

    def main():
        x = input("Precedência: ")
        print(precedencia(x))

    if __name__ == "__main__":
        main()

elif questao == 15:

    def main():
        expres = input("Expressão matemática: ")

        if expres.find("+ ") >= 0:

            expres = expres.replace("+ ", ", + , ")

        if expres.find("- ") >= 0:
            expres = expres.replace("- ", ", - , ")

        if expres.find("/") >= 0:
            expres = expres.replace("/", ", / , ")

        if expres.find("*") >= 0:
            expres = expres.replace("*", ", * , ")

        if expres.find("^") >= 0:
            expres = expres.replace("^", "^ , ")

        expres = expres.split(",")

        print(f"tokens: {expres}")

    if __name__  == "__ main__":
        main()


from .can import CAN
from .pgn import PGN
from .amp import AMP
from .denet import DENet

key2arch = {
    'CAN': CAN,
    'PGN': PGN,
    'AMP': AMP,
    'DENet': DENet,
}

def get_architecture(arch_name=None):
    if arch_name is None:
        print("Using default DENet model")
        return DENet

    else:
        if arch_name not in key2arch:
            raise NotImplementedError('Model {} not implemented'.format(arch_name))

        print('Using model: {}'.format(arch_name))
        return key2arch[arch_name]


import requests as rq
import pandas as pd
import numpy as np
import time

def get_apy(apr):
    """APY assuming compounding daily"""
    return ((1+(apr/365))**(365))-1

def get_cost(price, set):
    """Get cost from current price and amount needed to get in the set"""
    return price*set

def get_monthly_income(p, apy):
    """calc month income from current price and the apy"""
    return (p*apy)/12

def fetch():
    juno_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=juno-network&vs_currencies=usd").json()['juno-network']['usd']
    osmo_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=osmosis&vs_currencies=usd").json()['osmosis']['usd']
    cosmos_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=cosmos&vs_currencies=usd").json()['cosmos']['usd']
    evmos_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=evmos&vs_currencies=usd").json()['evmos']['usd']
    akash_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=akash-network&vs_currencies=usd").json()['akash-network']['usd']
    stargaze_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=stargaze&vs_currencies=usd").json()['stargaze']['usd']
    umee_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=umee&vs_currencies=usd").json()['umee']['usd']
    secret_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=secret&vs_currencies=usd").json()['secret']['usd']
    terra_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=terra-luna-2&vs_currencies=usd").json()['terra-luna-2']['usd']
    injective_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=injective-protocol&vs_currencies=usd").json()['injective-protocol']['usd']
    sifchain_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=sifchain&vs_currencies=usd").json()['sifchain']['usd']
    kava_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=kava&vs_currencies=usd").json()['kava']['usd']
    comdex_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=comdex&vs_currencies=usd").json()['comdex']['usd']
    cryptoorgchain_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=crypto-com-chain&vs_currencies=usd").json()['crypto-com-chain']['usd']
    persistence_price = rq.get(f"https://api.coingecko.com/api/v3/simple/price?ids=persistence&vs_currencies=usd").json()['persistence']['usd']

    #minimum amount needed to get in active set https://www.mintscan.io/
    # assets = ['juno', 'osmosis', 'cosmoshub', 'evmos','akash', 'stargaze','umee', 'secretnetwork', 'terra']
    juno_val_set = rq.get("https://validators.cosmos.directory/chains/juno").json()
    juno_val_set_df = pd.DataFrame(juno_val_set['validators'])
    juno_actv_val_set_df = juno_val_set_df[juno_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    juno_set = float(juno_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    osmosis_val_set = rq.get("https://validators.cosmos.directory/chains/osmosis").json()
    osmosis_val_set_df = pd.DataFrame(osmosis_val_set['validators'])
    osmosis_actv_val_set_df = osmosis_val_set_df[osmosis_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    osmosis_set = float(osmosis_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    cosmoshub_val_set = rq.get("https://validators.cosmos.directory/chains/cosmoshub").json()
    cosmoshub_val_set_df = pd.DataFrame(cosmoshub_val_set['validators'])
    cosmoshub_actv_val_set_df = cosmoshub_val_set_df[cosmoshub_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    cosmoshub_set = float(cosmoshub_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    evmos_val_set = rq.get("https://validators.cosmos.directory/chains/evmos").json()
    evmos_val_set_df = pd.DataFrame(evmos_val_set['validators'])
    evmos_actv_val_set_df = evmos_val_set_df[evmos_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    evmos_set = float(evmos_actv_val_set_df.tail(1)['delegator_shares'])/1000000000000000000

    akash_val_set = rq.get("https://validators.cosmos.directory/chains/akash").json()
    akash_val_set_df = pd.DataFrame(akash_val_set['validators'])
    akash_actv_val_set_df = akash_val_set_df[akash_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    akash_set = float(akash_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    stargaze_val_set = rq.get("https://validators.cosmos.directory/chains/stargaze").json()
    stargaze_val_set_df = pd.DataFrame(stargaze_val_set['validators'])
    stargaze_actv_val_set_df = stargaze_val_set_df[stargaze_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    stargaze_set = float(stargaze_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    umee_val_set = rq.get("https://validators.cosmos.directory/chains/umee").json()
    umee_val_set_df = pd.DataFrame(umee_val_set['validators'])
    umee_actv_val_set_df = umee_val_set_df[umee_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    umee_set = float(umee_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    secretnetwork_val_set = rq.get("https://validators.cosmos.directory/chains/secretnetwork").json()
    secretnetwork_val_set_df = pd.DataFrame(secretnetwork_val_set['validators'])
    secretnetwork_actv_val_set_df = secretnetwork_val_set_df[secretnetwork_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    secretnetwork_set = float(secretnetwork_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    sifchain_val_set = rq.get("https://validators.cosmos.directory/chains/sifchain").json()
    sifchain_val_set_df = pd.DataFrame(sifchain_val_set['validators'])
    sifchain_actv_val_set_df = sifchain_val_set_df[sifchain_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    sifchain_set = float(sifchain_actv_val_set_df.tail(1)['delegator_shares'])/1000000000000000000

    kava_val_set = rq.get("https://validators.cosmos.directory/chains/kava").json()
    kava_val_set_df = pd.DataFrame(kava_val_set['validators'])
    kava_actv_val_set_df = kava_val_set_df[kava_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    kava_set = float(kava_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    comdex_val_set = rq.get("https://validators.cosmos.directory/chains/comdex").json()
    comdex_val_set_df = pd.DataFrame(comdex_val_set['validators'])
    comdex_actv_val_set_df = comdex_val_set_df[comdex_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    comdex_set = float(comdex_actv_val_set_df.tail(1)['delegator_shares'])/1000000

    cryptoorgchain_val_set = rq.get("https://validators.cosmos.directory/chains/cryptoorgchain").json()
    cryptoorgchain_val_set_df = pd.DataFrame(cryptoorgchain_val_set['validators'])
    cryptoorgchain_actv_val_set_df = cryptoorgchain_val_set_df[cryptoorgchain_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    cryptoorgchain_set = float(cryptoorgchain_actv_val_set_df.iloc[-1]['delegator_shares'])/100000000

    persistence_val_set = rq.get("https://validators.cosmos.directory/chains/persistence").json()
    persistence_val_set_df = pd.DataFrame(persistence_val_set['validators'])
    persistence_actv_val_set_df = persistence_val_set_df[persistence_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    persistence_set = float(persistence_actv_val_set_df.iloc[-1]['delegator_shares'])/1000000

    # terra_val_set = rq.get("https://validators.cosmos.directory/chains/terra").json()
    # terra_val_set_df = pd.DataFrame(terra_val_set['validators'])
    # terra_actv_val_set_df = terra_val_set_df[terra_val_set_df['status']=='BOND_STATUS_BONDED'].sort_values(by=['rank'], ascending=True)
    # terra_set = float(terra_actv_val_set_df.tail(1)['delegator_shares'])/1000000
    terra_set = 292900
    injective_set = 10009

    #inflation/bonded rate
    #query infaltion rate
    #bonded rate is total supply / sum balance of all validators
    #staking aprs https://www.mintscan.io/
    juno_apr = .8009
    osmo_apr = .3401
    evmos_apr = 6.2943
    cosmos_apr = .1884
    akash_apr = .2157
    stargaze_apr = .6038
    umee_apr = .5157
    secret_apr = .2337
    terra_apr = .1431
    injective_apr = .1297
    sifchain_apr = 1.2937
    kava_apr = .2634
    comdex_apr = .4037
    cryptoorgchain_apr = .1453
    persistence_apr = .3393

    data = {
        "juno":{"price":juno_price, "set":juno_set, "apr":juno_apr},
        "osmo":{"price":osmo_price, "set":osmosis_set, "apr":osmo_apr},
        "evmos":{"price":evmos_price, "set":evmos_set, "apr":evmos_apr},
        "cosmos":{"price":cosmos_price, "set":cosmoshub_set, "apr":cosmos_apr},
        "akash":{"price":akash_price, "set":akash_set, "apr":akash_apr},
        "stargaze":{"price":stargaze_price, "set":stargaze_set, "apr":stargaze_apr},
        "umee":{"price":umee_price, "set":umee_set, "apr":umee_apr},
        "secret":{"price":secret_price, "set":secretnetwork_set, "apr":secret_apr},
        "terra":{"price":terra_price, "set":terra_set, "apr":terra_apr},
        "injective":{"price":injective_price, "set":injective_set, "apr":injective_apr},
        "sifchain":{"price":sifchain_price, "set":sifchain_set, "apr":sifchain_apr},
        "kava":{"price":kava_price, "set":kava_set, "apr":kava_apr},
        "comdex":{"price":comdex_price, "set":comdex_set, "apr":comdex_apr},
        "cryptoorgchain":{"price":cryptoorgchain_price, "set":cryptoorgchain_set, "apr":cryptoorgchain_apr},
        "persistence":{"price":persistence_price, "set":persistence_set, "apr":persistence_apr},
    }
    for i in data.keys():
        apy = get_apy(data[i]['apr'])
        p = get_cost(data[i]['price'], data[i]['set'])
        monthly_income = get_monthly_income(p,apy)

        data[i]['apy'] = apy
        data[i]['cost_to_enter_set'] = p
        data[i]['est_monthly_revenue'] = monthly_income
        data[i]['est_monthly_income_to_validator'] = monthly_income *.1
    return data

# v_data = pd.DataFrame(data)
# v_data.to_csv("data/validator_data")
    # print(f"""{i}
    # price: ${round(data[i]['price'],2)}
    # apy: {round(apy*100,2)}%
    # cost to get in the set: ${round(p,2)}
    # monthly income: ${round(monthly_income,2)}""")


import os
import sys
from MyModule import foo, bar, foobar

def my_function(one,two,
                three,four,
                five,six):
    print("hello world")

def second_function():
    print("second funcrion")

my_list = [1,2,
           3,4,
           5,6]

print("Hello World", "Hi Everyone")

check = True
if check is True:
    print("Check id True")

#Dont do this
func_one(); func_two; func_three;


from typing import List

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        #It's only based on very simple repetition, can't handle pattern like
        #1.414, because 4 appears more than once.
        if numerator * denominator < 0:
            sign = '-'
            numerator, denominator = abs(numerator), abs(denominator)
        else:
            sign = ''
        q, r = divmod(numerator, denominator)
        if r == 0:
            return sign + str(q)
        s = str(q) + '.'
        remainDict = dict()
        frac = ''
        while r:
            #already seen remains, break; else, continue
            if r in remainDict:
                l = remainDict[r]
                frac = frac[:l] +'(' + frac[l:] + ')'
                break
            remainDict[r] = len(frac)
            r *= 10
            q, r = divmod(r, denominator)
            frac += str(q)
        return sign + s + frac


#import csv module
import csv
#get the csv file and the xml file
txt_file = open("etudiants.txt","r")
xml_file = open("students.xml","w")

csv_reader = csv.reader(txt_file,delimiter=',')

#head of the xml file
xml_t = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE students SYSTEM "students.dtd">
<?xml-stylesheet type="text/css" href="students.css"?>
    <students>"""
#add xml_t to the xml file

xml_file.write(xml_t)

#start read the csv file and append the items to lists

students_list_def = []
students_list_body = []

line_in = 0
item_in = 0

for item in csv_reader:
    if line_in == 0:
        while item_in < len(item):
            students_list_def.append(item[item_in])
            item_in+=1
        line_in+=1
    else:
        students_list_body.append(item)
        line_in += 1
line_o = 0
item_in = 0
nmbr_admis = 0
nmbr_ajournne = 0
nmbr_admis_a_dette = 0
for itemD in students_list_body:
    xml_file.write("""
        <student>
        """)
    if line_o != len(students_list_body):
        while item_in != len(students_list_def):
            for item_h in students_list_def:
                xml_file.write("""\t<"""+item_h+""">"""+itemD[item_in]+"""</"""+item_h+""">\n\t\t""")
                item_in += 1
            line_o += 1
        item_in = 0
        xml_file.write("""\t<moyenne>%s</moyenne>\n"""%((float(itemD[3])+float(itemD[4]))/2))
        if float(itemD[3]) >= 10 and float(itemD[4]) >= 10:
            nmbr_admis += 1
            xml_file.write("""\t\t\t<observation> Admis </observation>\n""")
        elif float(itemD[3]) < 10 or float(itemD[4]) < 10:
            if int(itemD[5]) > 45:
                nmbr_admis_a_dette += 1
                xml_file.write("""\t\t\t<observation> Admis ave detts </observation>\n""")
            else:
                nmbr_ajournne += 1
                xml_file.write("""\t\t\t<observation> Ajournee </observation>\n""")

    xml_file.write("""\t\t</student>""")
xml_file.write("""
    </students>""")


# Case #3 "Investment report".

# The program displays information for each month on capital investments for several years
# with a monthly capitalization.

# Developers:   Zemtseva A. (40%),
#               Zaitseva A. (35%),
#               Daniel A.   (45%).

# The program offers the user to select the language.
language = str(input('Выберите язык: / Choose language: / Choisissez votre langue: '))
if language.lower() == 'русский':
    import local_rus as lc
elif language.lower() == 'english':
    import local_eng as lc
elif language.lower() == 'francais':
    import local_fr as lc

# Input information.
years = int(input(lc.TХT_PERIOD_OF_INVESTMENT))
initial_capital = float(input(lc.TXT_INITIAL_CAPITAL))
percent = float(input(lc.TXT_INTEREST_RATE))
investment_infusion = float(input(lc.TXT_INVESTMENT_INFUSION))

# Cycle to calculate compound interest.
for year in range(1, years + 1):
    print(year, lc.TXT_YEAR)
    print("-" * 57)                                                                      # Starting tabulation.
    print(lc.TXT_TABLE_1)
    print(lc.TXT_TABLE_2)
    print("-" * 57)
    for month in range(1, 13):
        capital = initial_capital * (1 + (percent/100))                                  # Calculating.
        print("|{:^7}|{:^15.2f}|{:^15.2f}|{:^15.2f}|".format(month, initial_capital,     # Tabulation.
                                              (capital - initial_capital), capital))
        initial_capital = capital + investment_infusion
    print("-" * 57)


N = int(input())
s = input()

q = []
ans = 0
for x in s:
    if x == 'f':
        q.append(1)
    elif x == 'o' and q and q[-1] == 1:
        q[-1] = 2
    elif x == 'x' and q and q[-1] == 2:
        q.pop()
    else:
        ans += 1
        q.append(0)

print(ans+sum(q))


import requests
from bs4 import BeautifulSoup

class pesos_automation():

    def start_script(self):
        print("start pesos script")
        try:
            URL = 'https://wise.com/es/currency-converter/usd-to-cop-rate'
            page = requests.get(URL)
            soup = BeautifulSoup(page.content, 'html.parser')
            dollarContainer = soup.find("span", {"class": "text-success"})
            print("pesos value",dollarContainer.text.split(',')[0])
            return dollarContainer.text.split(',')[0]
        except Exception as e:
            print("Could not load site: "+str(e))
            return None


#Start
from tkinter import *

#Color
color={'black':'#32373e', 'blac':'#006400','white':'#d3d3d3' }

#Window
menu_window=Tk()
menu_window.geometry('400x250')
menu_window.title('Avestack 2.0')
menu_window.config(bg=color['black'])

#Menu_Funcion

#Converçao_alimentar_menu
def converção_alimentar_funcion(Converção_alimentar):
    converção=Tk()
    converção.geometry('400x200')
    converção.title('Avestack 2.0')
    converção.config(bg=color['black'])
    menu_text_1=Label(converção, width='20', text='converção alimentar', font='Arial 20 bold')
    menu_text_1.place(x=60,y=5)
    menu_text_1.config(bg=color['black'])
    def converção_button1(cb):
        n1=int(c1.get())
        n2=int(c2.get())
        n3=int(c3.get())
        n4=int(c4.get())
        Ps=n1-n2
        Ps1=n3/Ps
        Convercao=Ps1/n4
        L=Label(converção, width='40', text='A converção alimentar dos frangos é %s'%(Convercao))
        L.place(x=1,y=40)
        L.config(bg=color['black'])
    converção_button=Button(converção, width='10', text='Calcular', command=lambda:converção_button1('cb'))
    converção_button.place(x=5,y=10)
    converção_button.config(bg=color['blac'])
    c1=Entry(converção, width=10)
    c1.place(x=40, y=150)
    c1.config(bg=color['blac'])
    c2=Entry(converção, width=10)
    c2.place(x=260, y=150)
    c2.config(bg=color['blac'])
    c3=Entry(converção, width=10)
    c3.place(x=40, y=90)
    c3.config(bg=color['blac'])
    c4=Entry(converção, width=10)
    c4.place(x=260, y=90)
    c4.config(bg=color['blac'])
    L1=Label(converção, width='30', text='Diga o numero de ave alojadas',font='arial 8')
    L1.place(x=15, y=130)
    L1.config(bg=color['black'])
    L2=Label(converção, width='30', text='Diga o numero de aves mortas',font='arial 8')
    L2.place(x=190, y=130)
    L2.config(bg=color['black'])
    L3=Label(converção, width='30', text='Diga quanta ração foi consumida(Kg)',font='arial 8')
    L3.place(x=15, y=70)
    L3.config(bg=color['black'])
    L4=Label(converção, width='25', text='Diga o peso medio(Kg)',font='arial 8')
    L4.place(x=210, y=70)
    L4.config(bg=color['black'])
    converção.mainloop()

#Peso_medio_menu
def Peso_medio_funcion(Peso_medio):
    converção=Tk()
    converção.config(bg=color['black'])
    converção.geometry('290x300')
    converção.title('Avestack 2.0')
    def Peso_button(peso):
        n1=float(e1.get())
        n2=float(e2.get())
        n3=float(e3.get())
        n4=float(e4.get())
        n5=float(e5.get())
        n6=float(e6.get())
        n7=float(e7.get())
        n8=float(e8.get())
        nm1=(n1+n2+n3+n4)/4
        nm2=(n5+n6+n7+n8)/4
        res1=(nm1+nm2)/2
        l=Label(converção, width='25',text='O peso medio foi de %s'%(res1), font='arial 10 bold')
        l.place(x=95,y=25)
        l.config(bg=color['black'])
    converção_button=Button(converção, width='10', text='Calcular', command=lambda:Peso_button('peso'))
    converção_button.place(x=5,y=10)
    converção_button.config(bg=color['blac'])
    l=Label(converção, width='20', text='Diga os Pesos:', font='arial 15 bold')
    l.place(x=85,y=20)
    l.config(bg=color['black'])
    e1=Entry(converção, width='20')
    e1.place(x=10,y=100)
    e1.config(bg=color['blac'])
    e2=Entry(converção, width='20')
    e2.place(x=150,y=100)
    e2.config(bg=color['blac'])
    e3=Entry(converção, width='20')
    e3.place(x=10,y=150)
    e3.config(bg=color['blac'])
    e4=Entry(converção, width='20')
    e4.place(x=150,y=150)
    e4.config(bg=color['blac'])
    e5=Entry(converção, width='20')
    e5.place(x=10,y=200)
    e5.config(bg=color['blac'])
    e6=Entry(converção, width='20')
    e6.place(x=150,y=200)
    e6.config(bg=color['blac'])
    e7=Entry(converção, width='20')
    e7.place(x=10,y=250)
    e7.config(bg=color['blac'])
    e8=Entry(converção, width='20')
    e8.place(x=150,y=250)
    e8.config(bg=color['blac'])
    converção.mainloop()

#IEP_menu
def IEP_funcion(IEP):
    converção=Tk()
    converção.config(bg=color['black'])
    converção.geometry('400x600')
    converção.title('Avestack 2.0')
    converção.mainloop()

#Consumo_de_raçao_menu
def Consumo_de_raçao_funcion(Consumo_de_raçao):
    converção=Tk()
    converção.config(bg=color['black'])
    converção.geometry('400x600')
    converção.title('Avestack 2.0')
    converção.mainloop()

#Metas_de_CA_menu
def Metas_de_CA_funcion(Metas_de_CA):
    converção=Tk()
    converção.config(bg=color['black'])
    converção.geometry('400x600')
    converção.title('Avestack 2.0')
    converção.mainloop()

#Metas_de_peso_menu
def Metas_de_peso_funcion(Metas_de_peso):
    converção=Tk()
    converção.config(bg=color['black'])
    converção.geometry('290x480')
    converção.title('Avestack')
    List_raças=["Macho","Femea","Misto"]
    w=StringVar()
    w.set(List_raças[0])
    op_raças=OptionMenu(converção,w,*List_raças)
    op_raças.place(x=190,y=10)
    op_raças.config(bg=color['white'])
    def Listas(listas):
        W1=w.get()
        if W1=='Macho':
            l1=Label(converção, width=20, text='Dia 1: 53 g', font='arial 10')
            l1.place(x=50,y=120)
            l1.config(bg=color['blac'])
            l2=Label(converção, width=20, text='Dia 7: 179 g', font='arial 10')
            l2.place(x=50,y=160)
            l2.config(bg=color['blac'])
            l3=Label(converção, width=20, text='Dia 14: 475 g', font='arial 10')
            l3.place(x=50,y=200)
            l3.config(bg=color['blac'])
            l4=Label(converção, width=20, text='Dia 21: 938 g', font='arial 10')
            l4.place(x=50,y=240)
            l4.config(bg=color['blac'])
            l5=Label(converção, width=20, text='Dia 28: 1531 g', font='arial 10')
            l5.place(x=50,y=280)
            l5.config(bg=color['blac'])
            l6=Label(converção, width=20, text='Dia 35: 2217 g', font='arial 10')
            l6.place(x=50,y=320)
            l6.config(bg=color['blac'])
            l7=Label(converção, width=20, text='Dia 42: 2953 g', font='arial 10')
            l7.place(x=50,y=360)
            l7.config(bg=color['blac'])
            l8=Label(converção, width=20, text='Dia 49: 3660 g', font='arial 10')
            l8.place(x=50,y=400)
            l8.config(bg=color['blac'])
        if W1=='Femea':
            l1=Label(converção, width=20, text='Dia 1: 51 g', font='arial 10')
            l1.place(x=50,y=120)
            l1.config(bg=color['blac'])
            l2=Label(converção, width=20, text='Dia 7: 175 g', font='arial 10')
            l2.place(x=50,y=160)
            l2.config(bg=color['blac'])
            l3=Label(converção, width=20, text='Dia 14: 473 g', font='arial 10')
            l3.place(x=50,y=200)
            l3.config(bg=color['blac'])
            l4=Label(converção, width=20, text='Dia 21: 844 g', font='arial 10')
            l4.place(x=50,y=240)
            l4.config(bg=color['blac'])
            l5=Label(converção, width=20, text='Dia 28: 1341 g', font='arial 10')
            l5.place(x=50,y=280)
            l5.config(bg=color['blac'])
            l6=Label(converção, width=20, text='Dia 35: 1914 g', font='arial 10')
            l6.place(x=50,y=320)
            l6.config(bg=color['blac'])
            l7=Label(converção, width=20, text='Dia 42: 2511 g', font='arial 10')
            l7.place(x=50,y=360)
            l7.config(bg=color['blac'])
            l8=Label(converção, width=20, text='Dia 49: 3084 g', font='arial 10')
            l8.place(x=50,y=400)
            l8.config(bg=color['blac'])
        if W1=='Misto':
            l1=Label(converção, width=20, text='Dia 1: 52 g', font='arial 10')
            l1.place(x=50,y=120)
            l1.config(bg=color['blac'])
            l2=Label(converção, width=20, text='Dia 7: 177 g', font='arial 10')
            l2.place(x=50,y=160)
            l2.config(bg=color['blac'])
            l3=Label(converção, width=20, text='Dia 14: 459 g', font='arial 10')
            l3.place(x=50,y=200)
            l3.config(bg=color['blac'])
            l4=Label(converção, width=20, text='Dia 21: 891 g', font='arial 10')
            l4.place(x=50,y=240)
            l4.config(bg=color['blac'])
            l5=Label(converção, width=20, text='Dia 28: 1436 g', font='arial 10')
            l5.place(x=50,y=280)
            l5.config(bg=color['blac'])
            l6=Label(converção, width=20, text='Dia 35: 2067 g', font='arial 10')
            l6.place(x=50,y=320)
            l6.config(bg=color['blac'])
            l7=Label(converção, width=20, text='Dia 42: 2732 g', font='arial 10')
            l7.place(x=50,y=360)
            l7.config(bg=color['blac'])
            l8=Label(converção, width=20, text='Dia 49: 3369 g', font='arial 10')
            l8.place(x=50,y=400)
            l8.config(bg=color['blac'])
    Metas_de_peso=Button(converção, width='20', text='Metas de peso',font='Arial 10', command=lambda:Listas('listas'))
    Metas_de_peso.place(x=5,y=10)
    Metas_de_peso.config(bg=color['blac'])
    converção.mainloop()

#Menu_Button
converção_alimentar=Button(menu_window, width='20',text='Converção alimentar',font='Arial 10', command=lambda:converção_alimentar_funcion('Converção_alimentar'))
converção_alimentar.place(x=15,y=70)
converção_alimentar.config(bg=color['blac'])

Peso_medio=Button(menu_window, width='20', text='Peso medio',font='Arial 10', command=lambda:Peso_medio_funcion('Peso_medio'))
Peso_medio.place(x=195,y=70)
Peso_medio.config(bg=color['blac'])

IEP=Button(menu_window, width='20', text='IEP',font='Arial 10', command=lambda:IEP_funcion('IEP'))
IEP.place(x=15,y=130)
IEP.config(bg=color['blac'])

Consumo_de_raçao=Button(menu_window, width='20', text='Consumo de ração',font='Arial 10', command=lambda:Consumo_de_raçao_funcion('Consumo_de_raçao'))
Consumo_de_raçao.place(x=195,y=130)
Consumo_de_raçao.config(bg=color['blac'])

Metas_de_CA=Button(menu_window, width='20', text='Metas de CA',font='Arial 10', command=lambda:Metas_de_CA_funcion('Metas_de_CA'))
Metas_de_CA.place(x=15,y=190)
Metas_de_CA.config(bg=color['blac'])

Metas_de_peso=Button(menu_window, width='20', text='Metas de peso',font='Arial 10', command=lambda:Metas_de_peso_funcion('Metas_de_peso'))
Metas_de_peso.place(x=195,y=190)
Metas_de_peso.config(bg=color['blac'])

#Menu_Text
menu_text_1=Label(menu_window, width='20', text='Menu', font='Arial 30 bold')
menu_text_1.place(x=-55,y=20)
menu_text_1.config(bg=color['black'], fg=color['white'])

#End
menu_window.mainloop()


# Note: you need to be using OpenAI Python v0.27.0 for the code below to work

import os
import openai
openai.organization = "org-DZn6MOgACWIbxxYLzuk2MdHz" #填你自己的OpenAI-Organization，这里获得：https://platform.openai.com/account/org-settings
openai.api_key = os.getenv("OPENAI_API_KEY") #填你自己的api_key，这里获得：https://platform.openai.com/account/api-keys
openai.Model.list()

map=[]
user = {"role": "user", "content": ""}
system = {"role": "system", "content": ""}
user["content"] = input('请问您想了解什么？\n')

while True:
    map.append(user)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages = map
    )

    re = response['choices'][0]['message']['content']

    re.encode('unicode_escape').decode('utf-8')

    print(re + "\n")

    system["content"] = re

    map.append(system)

    user = {"role": "user", "content": ""}
    system = {"role": "system", "content": ""}

    user["content"] = input()


from pymongo import MongoClient
from pymongo import cursor
from Stock import Stock
from flask_login import UserMixin
import re
import os

class User(UserMixin):
    def __init__(self, name):
        self.name = name
    def get_id(self):
        return self.name
    @staticmethod
    def users_collection():
        myclient = MongoClient(f"mongodb+srv://{os.getenv('DB_NAME')}:{os.getenv('PASS')}@cluster0-twyu7.mongodb.net/test?retryWrites=true&w=majority")
        db = myclient["users_stats"]
        users_collection = db["users_collection"]
        return users_collection
    def stats_database(self):
        myclient = MongoClient(f"mongodb+srv://{os.getenv('DB_NAME')}:{os.getenv('PASS')}@cluster0-twyu7.mongodb.net/test?retryWrites=true&w=majority")
        db = myclient["users_stats"]
        user_stats = db[self.name]
        return user_stats

    def buy(self, company_name, quantity):
        if (quantity):
            quantity = int(quantity)
        else:
            quantity = 1
        stock_list = Stock.stock_list()
        user_stats = self.stats_database()
        users_collection = self.users_collection()
        cursor=users_collection.find_one({"user_name": self.name})
        current_balance = float(cursor.get("balance"))
        cost = quantity * float(stock_list.get(company_name))
        if current_balance < cost:
            return False
        current_balance = current_balance - cost
        users_collection.update_one({"user_name": self.name}, {"$set": {"balance": current_balance}})
        current_quantity = 0
        for cursor in user_stats.find({}):
            if company_name in cursor:
                current_quantity = cursor[company_name]
                break
        user_stats.update_one({company_name: current_quantity},
                              {"$set": {company_name: current_quantity + quantity}}, upsert=True)

        return True

    def get_balance(self):
        users_collection = self.users_collection()
        cursor=users_collection.find_one({"user_name": self.name})
        return cursor.get("balance")

    def sell(self, company_name, quantity):
        if quantity:
            quantity = int(quantity)
        else:
            quantity = 1

        stock_list = Stock.stock_list()
        user_stats = self.stats_database()
        for cursor in user_stats.find({}):
            if company_name in cursor:
                current_quantity = cursor[company_name]
                break
        if current_quantity < quantity:
            return False
        if current_quantity - quantity == 0:
            user_stats.delete_one({company_name: current_quantity})
        else:
            user_stats.update({company_name: current_quantity}, {company_name: current_quantity - quantity})

        users_collection = self.users_collection()
        cursor = users_collection.find_one({"user_name": self.name})
        current_balance = cursor.get("balance")

        prise = quantity * float(stock_list.get(company_name))
        current_balance = current_balance + prise
        users_collection.update_one({"user_name": self.name}, {"$set": {"balance": current_balance}})
        return True

    def get_stats(self):
        user_stats = self.stats_database()
        stats = {}
        for stat in user_stats.find({}):
            x = re.split(':|\,', (str(stat)))
            company_name = (x[2][2:-1])
            quantity = (x[3][1:-1])
            stats[company_name] = quantity
        return stats

    def get_share_value(self):
        stock_list = Stock.stock_list()
        stats = self.get_stats()
        return sum((float(stock_list.get(k, 0)) * int(v)) for k, v in zip(stats, stats.values()))


import chainer
import chainer.links as L
from chainer import functions as F
from gen_models.sngan_resblocks import Block
from source.miscs.random_samples import sample_categorical, sample_continuous

class SNGAN(chainer.Chain):
    # all bn parameters are initialized to 1 and 0
    def __init__(self, ch=64, dim_z=128, bottom_width=4, activation=F.relu, n_classes=0, distribution="normal",
                 normalize_stat=False):
        super(SNGAN, self).__init__()
        initializer = chainer.initializers.GlorotUniform()
        self.bottom_width = bottom_width
        self.activation = activation
        self.distribution = distribution
        self.dim_z = dim_z
        self.n_classes = n_classes
        self.ch = ch
        self.normalize_stat = normalize_stat
        with self.init_scope():
            self.l1 = L.Linear(dim_z, (bottom_width ** 2) * ch * 16, initialW=initializer)
            self.block2 = Block(ch * 16, ch * 16, activation=activation, upsample=True, n_classes=n_classes)
            self.block3 = Block(ch * 16, ch * 8, activation=activation, upsample=True, n_classes=n_classes)
            self.block4 = Block(ch * 8, ch * 4, activation=activation, upsample=True, n_classes=n_classes)
            self.block5 = Block(ch * 4, ch * 2, activation=activation, upsample=True, n_classes=n_classes)
            self.block6 = Block(ch * 2, ch, activation=activation, upsample=True, n_classes=n_classes)
            self.b7 = L.BatchNormalization(ch)
            self.l7 = L.Convolution2D(ch, 3, ksize=3, stride=1, pad=1, initialW=initializer)

    def __call__(self, batchsize=64, z=None, gamma=None, beta=None, **kwargs):
        if z is None:
            z = sample_continuous(self.dim_z, batchsize, distribution=self.distribution, xp=self.xp)
        if gamma is None:
            gamma = [None] * 12
            beta = [None] * 12
        y = self.xp.zeros((1, self.n_classes), dtype="float32")
        if self.n_classes > 0:
            y[0, 0] = 1
        h = z
        h = self.l1(h)
        h = F.reshape(h, (batchsize, -1, self.bottom_width, self.bottom_width))
        if self.normalize_stat:
            gamma = [self.normalize(g) * 0.2 + 1 for g in gamma]
            beta = [self.normalize(b) * 0.15 for b in beta]

        h = self.shift(h, gamma[0], beta[0])
        h = self.block2(h, y, None, gamma[1:3], beta[1:3], **kwargs)
        h = self.block3(h, y, None, gamma[3:5], beta[3:5], **kwargs)
        h = self.block4(h, y, None, gamma[5:7], beta[5:7], **kwargs)
        h = self.block5(h, y, None, gamma[7:9], beta[7:9], **kwargs)
        h = self.block6(h, y, None, gamma[9:11], beta[9:11], **kwargs)
        h = self.b7(h)
        h = self.activation(h)
        h = F.tanh(self.l7(h))
        return h

    def normalize(self, g):
        mu = F.mean(g)
        sigma = F.sqrt(F.mean(g ** 2) - mu ** 2 + 1e-5)
        return (g - mu) / (sigma + 1e-5)

    def shift(self, x, gamma, beta):
        if gamma is None:
            return x
        batchsize = x.shape[0]
        if gamma.ndim == 1 and beta.ndim == 1:
            x = x * F.tile(gamma[None, :, None, None], (batchsize, 1, self.bottom_width, self.bottom_width)) + \
                F.tile(beta[None, :, None, None], (batchsize, 1, self.bottom_width, self.bottom_width))
        elif gamma.ndim == 2 and beta.ndim == 2:
            x = x * F.tile(gamma[:, :, None, None], (1, self.bottom_width, self.bottom_width)) + \
                F.tile(beta[:, :, None, None], (1, self.bottom_width, self.bottom_width))
        return x

    def get_gamma(self):
        xp = self.xp
        gamma = [L.Parameter(xp.ones(self.ch * i, dtype="float32")) for i in [16, 16, 16, 16, 8, 8, 4, 4, 2, 2, 1]]
        return gamma

    def get_beta(self):
        xp = self.xp
        beta = [L.Parameter(xp.zeros(self.ch * i, dtype="float32")) for i in [16, 16, 16, 16, 8, 8, 4, 4, 2, 2, 1]]
        return beta

    def initialize_params(self, gamma=True, beta=True):
        self.block2.initialize_params(gamma, beta)
        self.block3.initialize_params(gamma, beta)
        self.block4.initialize_params(gamma, beta)
        self.block5.initialize_params(gamma, beta)
        self.block6.initialize_params(gamma, beta)

    def start_finetuning(self):
        self.block2.start_finetuning()
        self.block3.start_finetuning()
        self.block4.start_finetuning()
        self.block5.start_finetuning()
        self.block6.start_finetuning()
        self.b7.start_finetuning()


"""
Optimized State
^^^^^^^^^^^^^^^

..contents:: Table of Contents
    :backlinks: none
    :local:

Introduction
------------

This module contains functions can be monkey patched into
`ethereum.frontier.state` to make it use the optimized trie.
"""

from dataclasses import dataclass, field
from typing import Dict, cast

import ethereum.frontier.state
from ethereum.base_types import U256, Bytes
from ethereum.frontier.eth_types import EMPTY_ACCOUNT, Account, Address
from ethereum.frontier.state import state_root

from .trie import Trie, get_internal_key, trie_get, trie_set

@dataclass
class State:
    """
    Contains all information that is preserved between transactions.
    """

    _main_trie: Trie[Account] = field(
        default_factory=lambda: Trie(secured=True, default=EMPTY_ACCOUNT)
    )
    _storage_tries: Dict[Address, Trie[U256]] = field(default_factory=dict)

    def __eq__(self, other: object) -> bool:
        """
        Test for equality by comparing state roots.
        """
        if type(self) != type(other):
            return NotImplemented
        return state_root(
            cast(ethereum.frontier.state.State, self)
        ) == state_root(cast(ethereum.frontier.state.State, other))

def set_storage(
    state: State, address: Address, key: Bytes, value: U256
) -> None:
    """
    Set a value at a storage key on an account. Setting to `U256(0)` deletes
    the key.

    Parameters
    ----------
    state: `State`
        The state
    address : `Address`
        Address of the account.
    key : `Bytes`
        Key to set.
    value : `U256`
        Value to set at the key.
    """
    internal_address = get_internal_key(state._main_trie, address)
    trie = state._storage_tries.get(internal_address)
    if trie is None:
        trie = Trie(secured=True, default=U256(0))
        state._storage_tries[internal_address] = trie
    trie_set(trie, key, value)
    state._main_trie._dirty_set.add(internal_address)
    if trie._data == {}:
        del state._storage_tries[internal_address]

def get_storage(state: State, address: Address, key: Bytes) -> U256:
    """
    Get a value at a storage key on an account. Returns `U256(0)` if the
    storage key has not been set previously.

    Parameters
    ----------
    state: `State`
        The state
    address : `Address`
        Address of the account.
    key : `Bytes`
        Key to lookup.

    Returns
    -------
    value : `U256`
        Value at the key.
    """
    internal_address = get_internal_key(state._main_trie, address)
    trie = state._storage_tries.get(internal_address)
    if trie is None:
        return U256(0)

    value = trie_get(trie, key)

    assert isinstance(value, U256)
    return value