# Samujjwaal Dey
# Python Script to implement vector space model

# load dependency libraries
import math
import os
import copy
import re
from nltk.corpus import stopwords
from collections import Counter
from nltk.stem import PorterStemmer
import pickle

# number of webpages indexed
N = 6001

# extracting english stop words
stop_words = stopwords.words("english")

# Initializing Porter Stemmer object
st = PorterStemmer()

# folder to store pickle files
pickle_folder = "./PickleFiles/"
os.makedirs(pickle_folder, exist_ok=True)

webpages_idf = {}
max_freq = {}
webpages_tf_idf = {}

# unloading all the pickle files
with open(pickle_folder + "6000_inverted_index.pickle", "rb") as f:
    inverted_index = pickle.load(f)

with open(pickle_folder + "6000_webpages_tokens.pickle", "rb") as f:
    webpages_tokens = pickle.load(f)

with open(pickle_folder + "6000_pages_crawled.pickle", "rb") as f:
    urls = pickle.load(f)

# function for computing idf of each token in the collection of webpages
def calc_idf(inverted_index):
    idf = {}
    for key in inverted_index.keys():
        df = len(inverted_index[key].keys())
        # calculating IDF for a token
        idf[key] = math.log2(N / df)
    return idf

# function to compute tf-idf of each token
def calc_tfidf(inverted_index):
    # making a temporary copy of the inverted index
    tf_idf = copy.deepcopy(inverted_index)
    for token in tf_idf:
        for page in tf_idf[token]:
            # calculating TF for the webpage
            tf = tf_idf[token][page] / max_freq[page]
            # calculating TF-IDF for token
            tf_idf[token][page] = tf * webpages_idf[token]
    return tf_idf

# function to calculate document vector length for a particular webpage
def calc_doc_len(doc, doc_tokens):
    doc_len = 0
    for token in set(doc_tokens):
        # adding square of weight of token to document vector length
        doc_len += webpages_tf_idf[token][doc] ** 2
    doc_len = math.sqrt(doc_len)
    return doc_len

# calculate document vector lengths for all fetched webpages
def doc_len_pages(list_of_tokens):
    doc_lens = {}
    for page in list_of_tokens:
        doc_lens[page] = calc_doc_len(page, list_of_tokens[page])
    return doc_lens

# Function to compute cosine similarity
def calc_cos_sim_scores(query, doc_lens):
    similarity_scores = {}
    query_len = 0
    query_weights = {}
    # create count dictionary of the query
    query_dict = Counter(query)

    for token in query_dict.keys():
        # calculate query token TF
        token_tf = query_dict[token] / query_dict.most_common(1)[0][1]
        # calculate query token TF-IDF of token
        query_weights[token] = token_tf * webpages_idf.get(token, 0)
        # add square of token weight to query vector length
        query_len += query_weights[token] ** 2

    query_len = math.sqrt(query_len)

    for token in query:
        token_weight = query_weights.get(token)

        if token_weight:
            # calculating inner product between query and webpages
            for page in webpages_tf_idf[token].keys():
                similarity_scores[page] = similarity_scores.get(page, 0) + (
                    webpages_tf_idf[token][page] * token_weight
                )

    # dividing inner product by product of doc lens of query and webpage
    for page in similarity_scores:
        similarity_scores[page] = similarity_scores[page] / (doc_lens[page] * query_len)

    return similarity_scores

# function to tokenize query text
def tokenize_query(query_text):
    text = query_text.lower()
    text = re.sub("[^a-z]+", " ", text)
    tokens = text.split()
    clean_stem_tokens = [
        st.stem(token)
        for token in tokens
        if (token not in stop_words and st.stem(token) not in stop_words)
        and len(st.stem(token)) > 2
    ]
    return clean_stem_tokens

def show_relevant_pages(count, webpages):
    for i in range(count, count + 10):
        try:
            url_no = int(webpages[i][0])

        # executed when their are no more relevant pages to display
        except Exception as e:
            print("\nNo more results found !!")
            break

        if urls.get(url_no, None):
            print(i + 1, urls.get(url_no))

# calculating IDF for all tokens
webpages_idf = calc_idf(inverted_index)

# finding the frequency of most frequent token in each webpage
for page in webpages_tokens:
    max_freq[page] = Counter(webpages_tokens[page]).most_common(1)[0][1]

# calculating TF-IDF for all tokens
webpages_tf_idf = calc_tfidf(inverted_index)

# calculating document vector length for all webpages
webpages_lens = doc_len_pages(webpages_tokens)

print("\n                     ---UIC Web Search Engine---\n")
# take input query from user
query = str(input("Enter a search query: "))
print("\n")
# tokenize input query
query_tokens = tokenize_query(query)

# calculate cosine similarity scores
query_sim_pages = calc_cos_sim_scores(query_tokens, webpages_lens)

# sort cosine similarities in descending order
most_relevant_pages = sorted(query_sim_pages.items(), key=lambda x: x[1], reverse=True)

yes = {"y", "yes"}
# to implement do-while loop
first_pass = True
count = 0

while first_pass or choice.lower() in yes:
    first_pass = False
    show_relevant_pages(count, most_relevant_pages)
    choice = str(input("\nDo you want to more web page results? "))
    count += 10


"""
Solução do Desafio 03 por Junior Vieira
"""
def palindromo(start=1, end=10000):
    """
    Função para procurar por algarismos palíndromos
    """
    while start <= end:
        valor = str(start)
        if valor == valor[::-1]:
            print(f'[{valor}]', end='')
        start += 1
    print()
palindromo()


"""DRFsite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from myQuize.views import *
from rest_framework import routers
from rest_framework_simplejwt.views import TokenVerifyView,TokenObtainPairView,TokenRefreshView
from django.views.generic import TemplateView,RedirectView

app_name = 'myQuize'

urlpatterns = [
    path('admin/', admin.site.urls),
    path ('api/v1/Myquize/', MyquizeAPIList.as_view ()),
    path('api/v1/Myquize/<int:pk>/', MyquizeAPIUpdate.as_view()),
    path ('api/v1/Myquizedelete/<int:pk>/', MyquizeAPIDestroy.as_view()),
    path('api/v1/Myquize-auth/',include('rest_framework.urls')),
    path ('api/v1/auth/', include ('djoser.urls')),
    re_path (r'^auth/', include ('djoser.urls.authtoken')),
    path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    # path('accounts/profile/', RedirectView.as_view(url='http://127.0.0.1:8000')),
    path('', TemplateView.as_view(template_name='index.html'), name='index'),
    path('accounts/profile/', RedirectView.as_view(url='/')),
    path('users/', UserCreate.as_view(), name='user-create'),
#
#
#
#
#
# class MyCustomRouter (routers. SimpleRouter):
#     routes = [
#         routers.Route(url=r'^{prefix}$',
#                      mapping={'get': 'list'},
#                      name='{basename}-list',
#                      detail=False,
# #                      initkwargs={'suffix': 'List'}),
#         routers.Route(url=r'^{prefix}/{lookup}$',
#                      mapping={'get': 'retrieve'},
#                      name='{basename}-detail',
#                      detail=True,
#                      initkwargs={'suffix': 'Detail'})]

# router = MyCustomRouter()
# router.register (r"Myquize",MyquizeViewSet,basename='Myquize')

    # path('api/v1/', include(router.urls)),
    # path('api/v1/Myquize/', MyquizeViewSet.as_view({'get': 'list'})),
    # path('api/v1/Myquize/<int:pk>/', MyquizeViewSet.as_view({"put":"update"})),

]


class Corral:
    # class that represent the corral
    def __init__(self, number, area, kind):
        self.number = number            # coral number at the zoo
        self.area = area                # total area of the corral
        self.free_area = area           # free area left at the corral
        self.kind = kind                # type of animals that can live in the corral (predator or herbivore)
        self.animals_at_corral = {}     # list of the all animals that live in the corral

    def __repr__(self):
        # magic method that represent corral. In this case it show's all available information about the corral
        corral_overview = f'Corral number: {self.number}\n' \
                          f'Total area taken by corral: {self.area} sq.m.\n' \
                          f'Free area left at the corral: {self.free_area} sq.m.\n' \
                          f'This corral is intended for: {self.kind}.\n' \
                          f'Animals in corral:'
        if len(self.animals_at_corral) > 0:
            for key, item in self.animals_at_corral.items():
                corral_overview += f'\n{key}: {item};'
        else:
            corral_overview += f'\nThere are no animals at this corral\n'
        return corral_overview

    def add_animal(self, kind, species, area, quantity):
        # the method that is responsible for adding animals to the corral
        if kind != self.kind:
            print(f"You can't house {kind} with {self.kind}\n")
        else:
            area_needed = area * quantity
            if area_needed > self.free_area:
                print(f"There is not enough space for {quantity} {species}\n")
            else:
                if species in self.animals_at_corral:
                    self.animals_at_corral[species] += quantity
                else:
                    self.animals_at_corral[species] = quantity
                self.free_area -= area_needed
                print(
                    f'You have successfully added {quantity} {species} to the corral №{self.number}.\n'
                    f'There are {self.free_area} sq.m. of the free space left at the corral\n'
                )


import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
from time import sleep
from selenium import webdriver

url = 'https://www.usquidditch.org/teams'

#open selenium - use your own info for PATH
PATH = (r"C:\\Users\\Gustavo\\Desktop\\scoutfy\\Team USA\\chromedriver.exe")

driver = webdriver.Chrome(PATH)
driver.get(url)
driver.implicitly_wait(3)

#wait for page loading
sleep(2)
#html got with selenium
selenium_get = driver.page_source

soup = bs(selenium_get, 'html.parser')

link=[]

#close selenium
driver.close()

for a in soup.findAll('a'):
    link.append(a['href'])

#get every team website
link=link[115:346]
#get every team's info from the main page
info = soup.find('tbody').findAll('tr')

def find_acronym(s):
    #return only letters between ()
    return s[s.find("(")+1:s.find(")")]

def find_class(soup):
    list =[]
    for el in range(230):
        element = (soup.find("table", attrs = {"class" : "teams-display"}))
        list.append(element.find("tr", attrs ={"id" : "t"+str(el)}).find_all("td")[2].get_text())
# find_class(soup)

def find_socialmedia(soup):
    refs = []
    listsocial = []
    acuts = (soup.find_all("a"))
    for el in acuts:
        refs.append(el.get("href"))
    listsocial.append(refs)
    return listsocial
# find_socialmedia(soup)

def main():
    # this list will store every dictionary of each club
    my_list = []

    for i in range(len(info)):
       # This dict will store the information of each club
        my_dict = {}

        my_dict['Name'] = info[i].findAll('td')[0].text
        my_dict['City'] = info[i].findAll('td')[1].text.split(',')[0].strip()
        my_dict['State'] = info[i].findAll('td')[1].text.split(',')[1].strip()

        #here it's oppened every team's new page with another info

        url = 'https://www.usquidditch.org' + str(link[i])

        agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
        req = requests.get(url, headers=agent)
        soup = bs(req.content, features="lxml")

        my_dict['Acronym'] = find_acronym(soup.find('h2').text)
        my_dict['social_media'] = find_socialmedia(soup.find("ul", attrs ={"class" : "team-social-media-links"}))

        #this are all the constants that must be added
        my_dict['Category'] = 'Non Recognized'
        my_dict['Sport'] = 'Quidditch'
        my_dict['Country'] = 'United States of America'
        my_dict['Affilated'] = 'US Quidditch'
        my_dict['Recorded By'] = 'Gustavo Florindo Oliveira'
        my_dict['Recorded Date'] = '27/02/2022'

        my_list.append(my_dict)

    return my_list

res = main()

df = pd.DataFrame(data=res)
df.to_excel('US_Quidditch.xlsx', index=False)


from django.shortcuts import render, redirect
from .models import Book, Author

def index(request):

    context = {
        "books_table" : Book.objects.all()
    }

    return render(request, 'books_authors_app/addbook.html', context)

def add_book(request):
    if request.method == 'POST':

        Book.objects.create(title = request.POST['title'], description = request.POST['description'])

    return redirect("/")

def delete_book(request, id):
        book_id = int(id)

        delete_book = Book.objects.get(id= book_id )
        delete_book.delete()

        return redirect ("/")

def view_book(request, id):
    book_id = int(id)

    view_book = Book.objects.get(id=book_id)
    not_author = Author.objects.exclude(books = book_id)

    context = {
        'book': view_book,
        'not_author' : not_author,
    }
    print("$"*80)
    print(not_author)

    return render(request, 'books_authors_app/view_book.html', context)

def add_author_to_book(request, id):
    book_id = int(id)

    book = Book.objects.get(id = book_id)
    request = request.POST['add_author']
    first_name, last_name = request.split(" ")
    author = Author.objects.get(first_name = first_name, last_name = last_name)

    book.authors.add(author)

    return redirect(f"/view_book/{book_id}")

def show_authors(request):
    authors = Author.objects.all()
    print("*"*80)
    print(authors)

    context = {
        'authors': authors
    }

    return render(request,'books_authors_app/addauthor.html', context)

def add_author(request):
    if request.method == 'POST':
        Author.objects.create(first_name = request.POST['auth_first_name'], last_name = request.POST['auth_last_name'], notes = request.POST['notes'])
        return redirect('/show_authors')

    return redirect('/show_authors')

def delete_author(request, id):
    auth_id = int(id)
    author = Author.objects.get(id=auth_id)
    author.delete()

    return redirect('/show_authors')

def view_author(request, id):
    auth_id = int(id)
    author = Author.objects.get(id=auth_id)
    not_book = Book.objects.exclude(authors=auth_id)

    context = {
        'author': author,
        'not_book': not_book,
    }

    return render(request, 'books_authors_app/view_author.html', context)

def add_book_to_author(request, id):
    if request.method == 'POST':
        auth_id = int(id)

        author = Author.objects.get(id=auth_id)
        book = Book.objects.get(title = request.POST['add_author'])

        author.books.add(book)
        print(author)

        return redirect(f"/view_author/{auth_id}")
    return redirect(f"/view_author/{auth_id}")


#
#  File:
#    clmdiv1.py
#
#  Synopsis:
#    Draws U.S. geographic climate divisions as polygonal areas.
#
#  Categories:
#    maps only
#    polygons
#
#  Author:
#    Fred Clare (based on an NCL script of Mark Stevens, CGD, NCAR)
#
#  Date of initial publication:
#    September, 2004
#
#  Description:
#    This example reads polygon data defining the U.S. geographic
#    climate divisions and produces a visualization of those divisions
#    colored randomly.
#
#  Effects illustrated:
#      o  Using a Lambert conformal map projection.
#      o  How to select a map database resolution.
#      o  How to color only specified map areas.
#      o  How to draw color-filled polygons.
#      o  Usage of the the Python "random" module.
#
#  Output:
#     A single visualization is produced showing the
#     U.S. climate divisions.
#

#
#  Import numpy and random.
#
from __future__ import print_function
import numpy
import random
import os

#
#  Import Nio for reading netCDF files.
#
import Nio

#
#  Import Ngl support functions.
#
import Ngl

#
#  Open the netCDF file containing the climate divisions polygons.
#
dirc = Ngl.pynglpath("data")
ncdf = Nio.open_file(os.path.join(dirc,"cdf","climdiv_polygons.nc"))

#
#  State names for the contiguous U.S. states.
#
statenames = ["AL","AR","AZ","CA","CO","CT","DE","FL","GA","IA","ID","IL", \
              "IN","KS","KY","LA","MA","MD","ME","MI","MN","MO","MS","MT", \
              "NC","ND","NE","NH","NJ","NM","NV","NY","OH","OK","OR","PA", \
              "RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY"]

#
#  Climate divisions in each state.
#
ncds = [8,9,7,7,5,3,2,6,9,9,10,9,9,9,4,9,3,8,3,10,9,6,10,7, \
        8,9,8,2,3,8,4,10,10,9,9,10,1,7,9,4,10,7,7,3,10,9,6,10]

#
#  Number of polygons to draw.
#
npoly = len(ncds)

#
#  Define a color map and open a workstation.
#
cmap = numpy.array([[1.00,1.00,1.00],[0.00,0.00,0.00],[1.00,0.00,0.00],\
                      [0.00,1.00,0.00],[0.00,0.00,1.00],[1.00,1.00,0.00],\
                      [0.00,1.00,1.00],[1.00,0.00,1.00],[0.70,0.30,0.30],\
                      [0.50,1.00,1.00],[0.80,0.80,0.20],[1.00,1.00,0.50],\
                      [0.50,0.00,0.80],[1.00,0.50,0.00],[0.30,0.30,0.80],\
                      [0.50,1.00,0.00],[0.40,0.00,0.40],[0.50,1.00,0.50],\
                      [0.80,0.20,0.80],[0.00,0.60,0.00],[0.50,0.50,1.00],\
                      [1.00,0.00,0.50],[0.50,0.50,0.00],[0.00,0.50,0.50],\
                      [1.00,0.50,0.50],[0.00,1.00,0.50],[0.80,0.80,0.80],\
                      [0.20,0.80,0.00],[0.55,0.55,0.00],[0.00,0.70,0.00],\
                      [0.62,0.62,0.00],[0.25,0.25,0.25]],
                      'f')
wks_type = "png"
wks = Ngl.open_wks (wks_type,"clmdiv1")

#
#  Create the plot.
#

#
#  Map resources.
#
res = Ngl.Resources()
res.mpLambertParallel1F = 33.0         # two parallels
res.mpLambertParallel2F = 45.0
res.mpLambertMeridianF  = -95.0        # central meridian

res.mpLimitMode         = "LatLon"     # limit map via lat/lon
res.mpMinLatF           = 24.0         # map area
res.mpMaxLatF           = 50.0         # latitudes
res.mpMinLonF           = -125.0       # and
res.mpMaxLonF           = -65.0        # longitudes

res.mpDataBaseVersion   = "Ncarg4_1"   # change database
res.mpFillOn            = True         # fill continents
res.mpPerimOn           = False        # no box around map

res.mpAreaMaskingOn        = True                 # draw only parts of map
res.mpFillAreaSpecifiers   = ["Water","Land"]     # what parts to fill
res.mpSpecifiedFillColors  = ["white","white"]   # fill with white
res.mpOutlineBoundarySets  = "USStates"           # what outlines to use
res.mpMaskAreaSpecifiers   = ["Conterminous US"]  # don't fill here
res.mpGridAndLimbOn        = False                # no lat/lon lines

#
#  Increase the viewport size (make the map bigger).
#
res.vpWidthF  = 0.93
res.vpHeightF = 0.93
res.vpXF      = 0.05
res.vpYF      = 0.99

res.nglDraw  = False       # don't draw the plots now
res.nglFrame = False       # or advance the frame

res.mpProjection = "LambertConformal"
plot = Ngl.map(wks,res) # create the map plot

#
#  Polygon resources.
#
res_poly             = Ngl.Resources()
res_poly.gsEdgesOn   = True       # draw border around polygons.
res_poly.gsEdgeColor = "black"

#
# Prepare to draw the polygons.
#
random.seed(10)   # set a seed for the random number generator

#
#  Get the polygon data and fill polygons with random colors in
#  the range of our color table (2-31).
#
for st in range(npoly):
  for cd in range(ncds[st]):
    rand_num = int(29.*random.random()+2.)
    if (st == 42 and cd == 0):          # save value
      va1_rn = rand_num                 # VA clim div 1
    if (st == 42 and cd == 6):          # use value for
      res_poly.gsFillColor = cmap[va1_rn,:]     # VA clim div 1
    else:
      res_poly.gsFillColor = cmap[rand_num,:]
    varstr = "{}_CD{}".format(statenames[st], cd + 1)
    x = ncdf.variables[varstr].lon
    y = ncdf.variables[varstr].lat
    Ngl.polygon (wks,plot,x,y,res_poly)
    del(varstr)
    del(x)
    del(y)

#
# Add a title.
#
res_txt               = Ngl.Resources()         # text resources
res_txt.txFontHeightF = 0.03                    # select font size
res_txt.txFont        = "helvetica-bold"        # font
Ngl.text_ndc (wks, "Climate Division Polygons", 0.5, 0.78, res_txt)

Ngl.frame(wks)

Ngl.end()


#
# @lc app=leetcode.cn id=873 lang=python3
#
# [873] 最长的斐波那契子序列的长度
#
# https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence/description/
#
# algorithms
# Medium (50.92%)
# Likes:    189
# Dislikes: 0
# Total Accepted:    14.7K
# Total Submissions: 28.8K
# Testcase Example:  '[1,2,3,4,5,6,7,8]'
#
# 如果序列 X_1, X_2, ..., X_n 满足下列条件，就说它是 斐波那契式 的：
#
#
# n >= 3
# 对于所有 i + 2 ，都有 X_i + X_{i+1} = X_{i+2}
#
#
# 给定一个严格递增的正整数数组形成序列 arr ，找到 arr 中最长的斐波那契式的子序列的长度。如果一个不存在，返回  0 。
#
# （回想一下，子序列是从原序列 arr 中派生出来的，它从 arr 中删掉任意数量的元素（也可以不删），而不改变其余元素的顺序。例如， [3, 5, 8]
# 是 [3, 4, 5, 6, 7, 8] 的一个子序列）
#
#
#
#
#
#
# 示例 1：
#
#
# 输入: arr = [1,2,3,4,5,6,7,8]
# 输出: 5
# 解释: 最长的斐波那契式子序列为 [1,2,3,5,8] 。
#
#
# 示例 2：
#
#
# 输入: arr = [1,3,7,11,12,14,18]
# 输出: 3
# 解释: 最长的斐波那契式子序列有 [1,11,12]、[3,11,14] 以及 [7,11,18] 。
#
#
#
#
# 提示：
#
#
# 3
#
# 1
#
#
#
#

# @lc code=start
class Solution:
    def lenLongestFibSubseq(self, arr: List[int]) -> int:
        index = {x: i for i, x in enumerate(arr)}
        longest = collections.defaultdict(lambda: 2)

        ans = 0
        for k, z in enumerate(arr):
            for j in range(k):
                i = index.get(z - arr[j], None)
                if i is not None and i < j:
                    cand = longest[j, k] = longest[i, j] + 1
                    ans = max(ans, cand)

        return ans if ans >= 3 else 0
# @lc code=end

code/873.最长的斐波那契子序列的长度.py

873.最长的斐波那契子序列的长度.py


import sys

sys.path.append("E:\PythonGUI-ManageEmployee\Pyqt5")
from PyQt5.QtWebEngineWidgets import QWebEngineView
from Algorithm.Cluster.Brute_Force import Brute_Force_Cluster
from Algorithm.Cluster.Randomized_Tour import Randomized_Tour_Cluster
from Process_Data.PyQT5_ProcessData import Process_Data_Small
from Process_Data.PyQT5_distanceMatrix import distance_Matrix
from decimal import Decimal, ROUND_DOWN
from Compare_Algorithm.PyQT5_Compare import Compare
import Map_.css_Map_Route as css
from dotenv import load_dotenv
import numpy as np
import os

class Show_Map_Cluster:
    def __init__(
        self,
        dataCenters,
        dataPoints,
        dataLayout,
        layout_Function,
        cb_TSP,
        on,
        off,
        data_Matrix,
        cb_cluster,
        cb_Start,
        data_Map,
    ):
        load_dotenv()
        self.api_Key = os.getenv("API_KEY")
        self.web_view = QWebEngineView()
        self.show_All_Compare = ""
        self.on_Compare = False
        self.values_Title = []
        self.distance = []
        self.all_Points = []
        self.data_Point_Clean = []
        self.distance_Matrix = []
        self.click_count = 0
        # self.change_Compare(layout_Function, dataCenters)
        self.show_Map_HTML(
            dataCenters, dataPoints, dataLayout, cb_TSP, on, off, data_Matrix, data_Map
        )

    def show_Map_HTML(
        self,
        dataCenters,
        dataPoints,
        dataLayout,
        cb_TSP,
        on,
        off,
        data_Matrix,
        data_Map,
    ):
        self.show_valueAllPoint(dataPoints)
        data_Center = [list(point) for point in dataCenters]
        data_Kg = self.show_DataKgM(dataPoints, data_Matrix)
        data_Points_ = np.array(self.data_Point_Clean, dtype=object)
        data_Kg_M3_Drops = np.array(data_Kg, dtype=object)
        data_Radius = self.show_radius_Cluster(data_Points_, dataCenters)
        distances_html = self.calculator_Distance_Trip(data_Points_)
        nearest_Neighbor = Process_Data_Small().use_NearestNeighbor(
            distances_html, data_Points_
        )
        self.show_HTMLContent(
            data_Center,
            data_Radius,
            data_Kg_M3_Drops,
            nearest_Neighbor,
            dataCenters,
            dataLayout,
            data_Map,
        )

        def show_Data_():
            self.web_view.hide()
            Compare(
                data_Points_,
                data_Center,
                cb_TSP,
                dataCenters,
                data_Kg_M3_Drops,
                dataLayout,
            )

        def show_Data_Cluster_Main():
            remove_layout()
            if dataLayout.count() == 1:
                self.web_view.show()

        def remove_layout():
            item = dataLayout.itemAt(1)
            if item:
                widget_to_delete = item.widget()
                if widget_to_delete:
                    dataLayout.removeWidget(widget_to_delete)
                    widget_to_delete.deleteLater()

        def on_Change_LayOut():
            self.click_count += 1
            if self.click_count % 2 == 1:
                show_Data_()
            else:
                show_Data_Cluster_Main()

    def show_DataKgM(self, dataPoints, data_Matrix):
        data_Kg = []
        array_Matrix = np.array(
            [
                [
                    item[2],
                    item[3],
                    float(item[5]),
                    float(item[6]),
                ]
                for item in data_Matrix
            ]
        )
        for items in dataPoints:
            data = []
            for value in items:
                lat = value[0]
                lon = value[1]
                for data_ in array_Matrix:
                    if lat == data_[2] and lon == data_[3]:
                        data.append(data_)
            data_Kg.append(data)
        self.data_Point_Clean = dataPoints
        return data_Kg

    def show_valueAllPoint(self, dataPoints):
        for data in dataPoints:
            for value in data:
                self.all_Points.append([value[0], value[1]])
        return self.all_Points

    def haversine_distance(self, coord1, coord2):
        R = 6371  # Bán kính của Trái Đất trong kilômét
        lat1, lon1 = np.radians(list(coord1))
        lat2, lon2 = np.radians(list(coord2))

        dlat = lat2 - lat1
        dlon = lon2 - lon1

        a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2
        c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))

        distance = R * c
        return distance

    def show_radius_Cluster(self, data_point, data_center):
        radius = []
        for i, group in enumerate(data_point):
            max_distance = 0
            for point in group:
                distance = self.haversine_distance(point, data_center[i])
                if distance > max_distance:
                    max_distance = distance
            radius.append(max_distance)
        radius = np.array(radius) * 1000
        return radius

    def calculator_Distance_Trip(self, data_point):
        try:
            for value in data_point:
                distance_matrix = distance_Matrix.calculate_distances(value)
                self.distance_Matrix.append(distance_matrix)
        except ValueError as e:
            print("Check Log Error Distance", e)
        return self.distance_Matrix

    def show_Tree_Trip(self, data_point, distances, data_Center):
        list_Option = ""
        for index, value in enumerate(data_point):
            sum_kg = 0
            sum_m3 = 0
            for item in value:
                volume = item[0]
                weight = item[1]
                sum_kg += volume
                sum_m3 += weight
            list_Option += f"""

Trip {index+1}:

            KM:{distances[index]} - KG:{sum_kg.quantize(Decimal("1.000"), rounding=ROUND_DOWN)}
            - M3:{sum_m3.quantize(Decimal("1.000"), rounding=ROUND_DOWN)} -
            Drops:{len(self.calculator_Drops(value))} - Orders:{len(value)}

            """
        return list_Option

    def calculator_Drops(self, drops):
        data_Clean = []
        seen_coordinates = set()

        for item in drops:
            volume, weight, latitude, longitude = item
            coordinates = (latitude, longitude)

            if coordinates not in seen_coordinates:
                data_Clean.append(item)
                seen_coordinates.add(coordinates)
        return data_Clean

    def remove_layout(self, dataLayout):
        item = dataLayout.itemAt(0)
        if item:
            widget_to_delete = item.widget()
            if widget_to_delete:
                dataLayout.removeWidget(widget_to_delete)
                widget_to_delete.deleteLater()

    def show_HTMLContent(
        self,
        data_Center,
        data_Radius,
        data_Kg_M3_Drops,
        distances_html,
        dataCenters,
        dataLayout,
        data_Map,
    ):
        html_content = f"""
        <!DOCTYPE html>

                <title>Google Maps</title>
                {css.type_cs()}

                                    Nearest Neighbor

Trip: {len(data_Center)}

                                                    {self.show_Tree_Trip(data_Kg_M3_Drops,distances_html,dataCenters)}

            """
        if len(data_Map) > 4:
            self.web_view.setHtml(data_Map)
            self.remove_layout(dataLayout)
        else:
            self.web_view.setHtml(html_content)
        dataLayout.addWidget(self.web_view)


# print中有变长参数，因此可以使用*args的方式进行参数传递
import math

def isprime(x):
    if x == 1:
        return False
    if x % 2 == 0:
        return x == 2
    for i in range(2, int(math.sqrt(x))+1):
        if x % i == 0:
            return False
    return True

def findPrime(n):
    res = []
    x = 2
    while len(res) < n:
        if isprime(x) and isprime(2**x-1):
            res.append((x, 2**x-1))
        x += 1 if x == 2 else 2
    return res

res = findPrime(int(input()))
for p, m in res:
    print(p, m)


from units.unit import Unit

class Colony(Unit):
    def __init__(self,player,unit_index,p_index,init_coords,turn_bought,tech,home_colony=False):
        super().__init__(player,unit_index,p_index,init_coords,turn_bought)
        self.can_move=False
        self.attack = 0
        self.defense = 1
        self.tactics = 0
        self.movement = 0
        self.armor = 4
        self.name = 'Colony'
        self.combat_ready = True
        self.home_colony=home_colony
        self.assets=[]
        self.ship_yard_capacity=0

    def destroy_colony(self):
        for unit in self.assets:
          unit.exists=False

    def destroy(self):
        if self.home_colony:
          self.player.game.choose_winner(loser=self.player_index)
        self.exists=False
        self.player.board.remove_from_board(self)
        self.destroy_colony()

    def calc_shipyards(self):
      spyd_count=0
      for unit in self.assets:
        if unit.name=="Shipyard":
          spyd_count+=unit.spyd_tech
      return spyd_count

    def state(self):
      return {"type": self.name,
            "num":self.unit_index,
            "coords":self.coords,
            "technology":{"defense": self.defense,"attack": self.attack,"movement": self.movement},
            "hits_left":self.armor,
            'turn_created':self.turn_made,
            "shipyard_capacity":self.calc_shipyards(),
            'exists':self.exists,
            'tactics':self.tactics
            }


# # # -*- encoding = utf-8 -*- #
import turtle as t

# # for i in range(4):
# #     t.fd(100)
# #     t.left(90)
# t.penup()
# t.goto(-100,-30)
# t.pendown()
t.pencolor('black')
t.pensize(1)
t.title('turtle one')
# # for j in range(100):
# #     t.speed(10)
# #     t.fd(j*5)
# #     t.left(360/3)
# #
# # t.done()
colorlist = ['red', 'blue', 'yellow', 'brown', 'purple', 'orange', 'green',
             'light green', 'dark blue', 'dark blue', 'grey5']

t.penup()
t.speed(10)
t.goto(0, 0)
t.pendown()
for vs in range(11):
	for i in range(4):
		t.pencolor(colorlist[vs])
		t.fd((vs + 1) * 12)
		t.left(360 / 4)
	t.penup()
	t.goto(-(vs + 1) * 4, -(vs + 1) * 4)
	t.pendown()
t.done()


from collections import deque

def getEnergy(e, result):
    global M
    if len(e) == 2:
        # print(result)
        if M < result:
            M = result
        return 0
    for i in range(1, len(e)-1):
        c = e.copy()
        result += c[i-1]*c[i+1]
        del c[i]
        # print(c)
        # print(result)
        getEnergy(c, result)
        result -= c[i-1]*c[i]

input()
e = deque([int(x) for x in input().split()])
M = -999999999
for i in range(1, len(e)-1):
    c = e.copy()
    result = c[i-1]*c[i+1]
    del c[i]
    # print(c)
    # print(result)
    getEnergy(c, result)
    result -= c[i-1]*c[i]

# print(e)
print(M)


import argparse

import numpy as np

def add_bool_arg(parser, name, default=False, **kwargs):
    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument(
        "--" + name,
        dest=name,
        action="store_true",
        help="Default: " + ("Enabled" if default else "Disabled"),
    )
    group.add_argument("--no-" + name, dest=name, action="store_false", **kwargs)
    parser.set_defaults(**{name: default})

def arg_conversion(args):
    """ Conversions from time arguments to data size """

    # Detected sampling freq different from imu freq
    imu_freq = args.imu_freq
    if args.sampling_freq > 0.0:
        if not (imu_freq / args.sampling_freq).is_integer():
            raise ValueError("sampling_freq must be divisible by imu_freq.")
        else:
            sampling_factor = int(imu_freq / args.sampling_freq)
            sampling_freq = args.sampling_freq
    else:
        sampling_factor = 1
        sampling_freq = imu_freq

    window_size = int((args.window_time * imu_freq) / sampling_factor)
    if window_size < 1:
        raise ValueError("window_size less than 1. Try to increase sampling_freq.")

    window_shift_size = args.window_shift_size
    window_shift_time = 1. / imu_freq * sampling_factor

    data_window_config = dict(
        [("sampling_factor", sampling_factor),
        ("sampling_freq", sampling_freq),
        ("imu_freq", imu_freq),
        ("window_size", window_size),
        ("window_shift_size", window_shift_size),
        ("window_shift_time", window_shift_time)]
    )
    net_config = {
        "net_type": 'model',
        "weight_vel_err": args.weight_vel_err,
        "weight_pos_err": args.weight_pos_err,
        "loss_type": args.loss_type,
        "huber_vel_loss_delta": args.huber_vel_loss_delta * args.weight_vel_err,
        "huber_pos_loss_delta": args.huber_pos_loss_delta * args.weight_pos_err
    }

    return data_window_config, net_config


# Создайте программу для игры с конфетами человек против человека

import random

sweet_count = 100
take_count = 28

def do_step(player_type, step_count, cur_player, sweet_count, take_count, can_take):
    if player_type == 1: # Игрок
        return int(input(f'Ход {step_count}. Игрок {cur_player}. Количество конфет: {sweet_count}. Можно взять: {can_take}: '))
    elif player_type == 2: # Бот
        auto_take = random.randint(1, can_take)
        print(f'Ход {step_count}. Игрок {cur_player}. Количество конфет: {sweet_count}. Можно взять: {can_take}. Взято: {auto_take}')
        return auto_take
    else: # Бот с интеллектом
        if can_take == sweet_count:
            auto_take = can_take
        elif sweet_count % (take_count + 1) != 0:
            auto_take = sweet_count % (take_count + 1)
        else:
            auto_take = 1
        print(f'Ход {step_count}. Игрок {cur_player}. Количество конфет: {sweet_count}. Можно взять: {can_take}. Взято: {auto_take}')
        return auto_take

def Game(game_type, sweet_count, take_count, first_player, second_player, who_first):
    first_player_step = True
    step_count = 1
    while sweet_count > 0:
        can_take = take_count if take_count < sweet_count else sweet_count
        cur_player = first_player if first_player_step else second_player

        if game_type == 1 or who_first == 1 and first_player_step or who_first == 2 and not first_player_step:
            player_type = 1 # Игрок
        elif game_type == 2:
            player_type = 2 # Бот
        else:
            player_type = 3 # Бот с интеллектом

        take = do_step(player_type, step_count, cur_player, sweet_count, take_count, can_take)
        if take > can_take or take <= 0:
            print(f'Можно взять только: {can_take}')
            continue
        sweet_count -= take
        step_count += 1
        first_player_step = not first_player_step
    return cur_player

game_type = int(input('Выберите тип игры: 1 - два игрока, 2 - игра с ботом, 3 - игра с ителлектуальным ботом: '))
if 1 <= game_type <= 3:
    if game_type == 1:
        first_player = input('Введите имя первого игрока: ')
        second_player = input('Введите имя второго игрока: ')
        print(f'Выиграл игрок {Game(game_type, sweet_count, take_count, first_player, second_player, 0)}!')
    else:
        who_first = int(input('Кто будет ходиться первым 1 - Игрок, 2 - Бот: '))
        if who_first == 1:
            first_player = input('Введите имя игрока: ')
            second_player = 'Бот' if game_type == 2 else 'Бот с интеллектом'
        elif who_first == 2:
            first_player = 'Бот' if game_type == 2 else 'Бот с интеллектом'
            second_player = input('Введите имя игрока: ')
        else:
            print('Неправильно выбрана очередность ходов')
            exit()
        print(f'Выиграл игрок {Game(game_type, sweet_count, take_count, first_player, second_player, who_first)}!')
else:
    print('Неправильно выбран тип игры')


import math
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt

def plot_image_examples(images : tf.Tensor, n=9):
    rows = int(math.sqrt(n))
    fig, axs = plt.subplots(rows, math.ceil(n / rows))
    for i in range(n):
        axs[i // rows, i % rows].imshow(images[i], cmap="gray")
    fig.show()
    plt.show()

def plot_changed_images(images : tf.Tensor, noised_image : tf.Tensor, changed_images : tf.Tensor, n=8):
    fig, axs = plt.subplots(3, n)
    for i in range(n):
        axs[0, i].imshow(images[i], cmap="gray")
        axs[1, i].imshow(noised_image[i], cmap="gray")
        axs[2, i].imshow(changed_images[i], cmap="gray")
    fig.show()
    plt.show()


import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://exame.com/brasil/as-50-melhores-escolas-de-cada-estado-do-brasil-no-enem/'
response = requests.get(url)

soup = BeautifulSoup(response.content, 'html.parser')

table = soup.find('table')

data = []
for row in table.find_all('tr')[1:6]:
    cells = row.find_all('td')
    posicao = cells[0].get_text().strip()
    nome_escola = cells[1].get_text().strip()
    nota_media = cells[2].get_text().strip()
    uf = cells[3].get_text().strip()
    data.append([posicao, nome_escola, nota_media, uf])

df = pd.DataFrame(data, columns=['Posicao', 'Nome da escola', 'Nota media', 'UF'])

print(df)

Raspagem das 5 melhores escolas do país.py


# Project 3 - Tic-Tac-Toe Simulator
#
# Name: Ajay Patel
# Instructor: S. Einakian
# Section: 1
# Functions definitions comes here

def Welcome():
   #Display welcome message, rules, and ask user for how many players
   #str int ---> int
   print("Welcome to this Tic-Tac-Toe Simulator.")
   print("Your goal is to line up 3 of your tics in either a line or a diagonol.")
   print("You will pick either X or O. X will go first")
   #num = int(input("Do you wish to play against a (1) computer, or with (2)Players? "))
   #while num < 1 or num > 2:
      #print("ERROR: You must either play against (1) computer, or with (2)Players")
      #num = int(input("Do you wish to play against (1) computer, or with (2)Players? "))
      #if num == 1:
         #return 1
      #elif num == 2:
         #return 2

def createBoard():
   #Create a function that creates a list for X and O
   #none ----> list
   board = ['','','','','','','','','']

   print("The board postions are as follows:")

   return board

def printBoard(board):
   #Display the empty board so users can play
   #none ----> none
   print("  " + board[0] + " | " + board[1] + "  | " + board[2])
   print("------------")
   print("  " + board[3] + " | " + board[4] + "  | " + board[5])
   print("------------")
   print("  " + board[6] + " | " + board[7] + "  | " + board[8])

def pickLetter():
   #Create a function that asks user to pick X or O
   #int ----> str
   letter = str(input("Choose X or O: "))
   while not(letter == "X" or letter == "O"):
     print("ERROR: Invalid letter please use X or O")
     letter = str(input("Choose X or O: "))
   if letter == "X":
     return letter
   elif letter  == "O":
     return letter

def getInput(letter, board):
   #Ask user where they want to place letter
   #int ----> str (in spot that correlates with int)
   spot = int(input("Where do you like to place your letter (pick in range of 1-9): "))
   while spot < 1 or spot > 9:
      print("Invalid move! Location does not exist. Please try again.")
      spot = int(input("Where do you like to place your letter (pick in range of 1-9): "))
   if spot >= 1 and spot <= 9:
      while board[spot-1] != "":
         print("Invalid move! Location is already taken. Please try again.")
         spot = int(input("Where do you like to place your letter (pick in range of 1-9): "))
      board[spot-1] = letter
      return board

def checkRows(board):
   #To check if there are any winning combinations in rows
   #board ----> true and letter if there is a winning combination
   if "X" in board[0] and "X" in board[1] and "X" in board[2]:
     print("")
     print("Winner is X!")
     return (True, "X")
   elif "X" in board[3] and "X" in board[4] and "X" in board[5]:
     print("")
     print("Winner is X!")
     return (True, "X")
   elif "X" in board[6] and "X" in board[7] and "X" in board[8]:
     print("")
     print("Winner is X!")
     return (True, "X")
   elif "O" in board[0] and "O" in board[1] and "O" in board[2]:
     print("")
     print("Winner is O!")
     return (True, "O")
   elif "O" in board[3] and "O" in board[4] and "O" in board[5]:
     print("")
     print("Winner is O!")
     return (True, "O")
   elif "O" in board[6] and "O" in board[7] and "O" in board[8]:
     print("")
     print("Winner is O!")
     return (True, "O")
   else:
     return False

def checkCols(board):
   #to check if there are any winnig combinatiosn in columns
   #board -----> true and letter if there is a winning combination
   if "X" in board[0] and "X" in board[3] and "X" in board[6]:
      print("")
      print("Winner is X!")
      return (True, "X")
   elif "X" in board[1] and "X" in board[4] and "X" in board[7]:
      print("")
      print("Winner is X!")
      return (True, "X")
   elif "X" in board[2] and "X" in board[5] and "X" in board[8]:
      print("")
      print("Winner is X!")
      return (True, "X")
   elif "O" in board[0] and "O" in board[3] and "O" in board[6]:
      print("")
      print("Winner is O!")
      return (True, "O")
   elif "O" in board[1] and "O" in board[4] and "O" in board[7]:
      print("")
      print("Winner is O!")
      return (True, "O")
   elif "O" in board[2] and "O" in board[5] and "O" in board[8]:
      print("")
      print("Winner is O!")
      return (True, "O")
   else:
      return False

def checkDiags(board):
   #To check ic there are any winning combinations in diagonols
   #board ---> true and letter if there is a winning combination
   if "X" in board[0] and "X" in board[4] and "X" in board[8]:
      print("")
      print("Winner is X!")
      return (True, "X")
   elif "X" in board[2] and "X" in board[4] and "X" in board[6]:
      print("")
      print("Winner is X!")
      return (True, "X")
   elif "O" in board[0] and "O" in board[4] and "O" in board[8]:
      print("")
      print("Winner is O!")
      return (True, "O")
   elif "O" in board[2] and "O" in board[4] and "O" in board[6]:
      print("")
      print("Winner is O!")
      return (True, "O")
   else:
      return False

def boardFull(board):
    for i in range(len(board)):
        if board[i] == ' ':
           return False
    return True

def checkWin(rows, cols, diags):
     if rows:
        return True
     elif cols:
        return True
     elif diags:
        return True
     else:
        return False

def checkTurn(count):
   while count < 9:
     count += 1
     return count


def Factorial(n, algorithm='simple'):
    """
    Computes factorial.

    Parameters
    ----------
    n : int
        n value to compute n!
    algorithm : str, optional
        Algorithm to compute factorial: {simple , recursion}
    """
    if n==0 or n==1:
        return 1
    if algorithm=='simple':
        res=1
        for i in range(1,n+1):
            res=res*i
        return res
    if algorithm=='recursion':
        if n == 1:
            return 1
        else:
            return n * Factorial(n - 1)

def Comb(n,k,algorithm='recursion'):
    """
    Computes factorial.

    Parameters
    ----------
    n : int
        n
    k : int
        k
    algorithm : str, optional
        Algorithm to compute factorial: {fast , recursion}
    """
    if k==n:
        return 1
    if k==1:
        return n
    if k==0:
        return 1

    if algorithm=='recursion':
        res=0
        for i in range(k-1,n):
            res=res+Comb(i,k-1)
        return res
    if algorithm == 'fast':
        return Comb(n-1,k)+Comb(n-1,k-1)


import numpy as np

"""
I'm not aware of many pairwise weighting schemes that exist for tree taxa. One could imagine calculating
the weights of each member of a pair by methods described in "weighting_methods.py" and combining them.

Thus, this file currently contains a method that I made up and that is all.

Possible to do list:
    1. Write method to calculate pairwise weights from dictionary of single terminal weights
    2. Figure out how to code the ACL pairwise method
"""

def get_weight_matrices(my_tree):
    """
    This is code that implements a method I developed to get weights for pairwise comparisons
    that is similar in ideology to the GSC (Gerstein, Sonnhammer, Chothia) algorithm for weighting
    individual nodes in a tree. I wouldn't be surprised if someone else came up with this idea at
    some point but I've yet to see it. At the end of the GSC method, the weights for all terminals
    is equivalent to the total branch length. Which is to say the branch length of the tree gets
    pushed/pulled to the terminals in a weighted fashion. A similar process occurs here where one
    can envision laying out all pairwise lineages and performing calculations on this set of lines
    where each individual segment of any given line contributes a weight inversely proportional to
    how many lines that the segment appears in. A line of branch length 5 that appears in 100 pairs
    contributes 5/100 of a weight to each pair. A line of branch length 5 that apperas in 20 pairs
    contributes 5/20 to each of the pairs, etc. At the end each gets added up to give a weight for
    the overall pairwise comparison.

    Note that this calculation may alter the original tree by first setting the root node to have a
    length of zero and then making it equal to None at the end.

    Input(s):
    my_tree - a Bio.Phylo tree object. No root required!

    Output(s):
    ending_weight_matrix - the matrix of weights for all terminal-terminal pairs (rows and columns)
    ending_weight_matrix_normalized - ending_weight_matrix divided by the ending_matrix_raw. Sort of
            a %-uniqueness score for each pairwise comparison
    ending_matrix_raw - the matrix of distances between all terminal-terminal pairs
    my_tree.get_terminals() - list of terminals that are critical for knowing row/col entries in
            the matrices. This should be obvious but am returning it to be super sure everyone knows

    """
    #Instantiate the matrices that I'll use throughout
    term_count = len(my_tree.get_terminals())
    starting_weight_matrix = np.zeros((term_count, term_count))
    starting_matrix_raw = np.zeros((term_count, term_count))

    #Set root branch length to zero
    my_tree.root.branch_length = 0.
    term_pairs = enumerate(my_tree.get_terminals())
    term_pairs = [(pair[1], pair[0]) for pair in term_pairs]
    term_dict = dict(term_pairs)

    ending_weight_matrix, ending_matrix_raw, finished\
            = pairwise_distances_recursive(my_tree.root, my_tree,\
                                           starting_weight_matrix,\
                                           starting_matrix_raw,\
                                           term_dict, [])
    ending_weight_matrix_normalized = np.divide(ending_weight_matrix, ending_matrix_raw,\
                                     out=np.zeros_like(ending_weight_matrix), where=ending_matrix_raw!=0)
    #Reset the root branch length
    my_tree.root.branch_length = None
    return ending_weight_matrix, ending_weight_matrix_normalized, ending_matrix_raw, my_tree.get_terminals()

def pairwise_distances_recursive(putative_root, my_tree, weight_matrix, matrix_raw, term_map_dict, finished):
    """
    Side note, this took weeks, WEEKS, to get working and I'm very proud of it's overall simplicity despite the
    handful of notes and the obvious copy/pasting that shouldn't be there.

    Input(s):
    putative_root - a Bio.Phylo clade object, should probably be my_tree.root to start the process
    my_tree - the Bio.Phylo tree
    weight_matrix and matrix_raw - start as n x n np.zeros matrices where n is the number of terminals
            in the tree. These matrices get values added to them throughout the recursion
    term_map_dict - a dictionary that speeds things up by indexing key:val pairs
            as: "terminal object":"index in matrices"
    finished - an empty list to start and tracks progress of the recursive algorithm

    Output(s):
    weight_matrix - the matrix of weights for all terminal-terminal pairs (rows and columns)
    matrix_raw - the matrix of distances between all terminal-terminal pairs
    finished - a list of visited nodes for record keeping

    """
    ###Speeding things up by passing ds_terms and us_terms around a bit
    ds_terms = [term_map_dict[i] for i in putative_root.get_terminals()]
    us_terms = [term_map_dict[i] for i in my_tree.get_terminals() if term_map_dict[i] not in ds_terms]

    #This initial "if" really just skips the root which should have no upstream terms and the branch length
    #along the root node is contained in Bio.Phylo trees by the branch_length of the two descendants
    if min([len(ds_terms), len(us_terms)]) > 0:
        ###################
        ###For the weights matrix
        ###################
        val = putative_root.branch_length/(len(ds_terms)*len(us_terms))
        #Start at zero
        to_add = np.zeros(weight_matrix.shape)
        #Add rows and column values
        to_add[len(finished):len(ds_terms)+len(finished), :] = val
        to_add[:, len(finished):len(ds_terms)+len(finished)] = val
        #Subtract center square
        to_add[len(finished):len(ds_terms)+len(finished), len(finished):len(ds_terms)+len(finished)] = 0
        #Add to matrix
        weight_matrix += to_add

        #####################
        ###For the raw matrix
        #####################
        #Which is  to say, partitioning the branch_length to all straddling terminals
        #without dividing it by the number of straddling terminals
        val = putative_root.branch_length
        #Start at zero
        to_add = np.zeros(matrix_raw.shape)
        #Add rows and column values
        to_add[len(finished):len(ds_terms)+len(finished), :] = val
        to_add[:, len(finished):len(ds_terms)+len(finished)] = val
        #Subtract center square
        to_add[len(finished):len(ds_terms)+len(finished), len(finished):len(ds_terms)+len(finished)] = 0
        #Add to matrix
        matrix_raw += to_add

    if len(putative_root.clades) == 2:
        weight_matrix, matrix_raw, finished = pairwise_distances_recursive(putative_root.clades[0],\
                                                                      my_tree, weight_matrix, matrix_raw,\
                                                                      term_map_dict, finished)
        weight_matrix, matrix_raw, finished = pairwise_distances_recursive(putative_root.clades[1],\
                                                                      my_tree, weight_matrix, matrix_raw,\
                                                                      term_map_dict, finished)
    elif len(putative_root.clades) == 0:
        finished.append(putative_root)
    return weight_matrix, matrix_raw, finished


"""
https://leetcode.com/problems/cousins-in-binary-tree/

"""

from typing import Optional
from utils import TreeNode

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        level = [root]
        while True:
            newLevel = []
            vals = set()
            for node in level:
                if node:
                    vals.add(node.val)
                    newLevel.append(node.left)
                    newLevel.append(node.right)

            xIn = x in vals
            yIn = y in vals
            if xIn ^ yIn:
                return False
            if xIn & yIn:
                return True
            level = newLevel

"""
okay.. siblings vs cousins
"""

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        encodings = {}

        def encode(root, pEncoding, left):
            if not root:
                return

            if left:
                thisNode = pEncoding+"0"
            else:
                thisNode = pEncoding+"1"

            encodings[root.val] = thisNode
            encode(root.left, thisNode, True)
            encode(root.right, thisNode, False)
        encode(root, "", False)
        return len(encodings[x]) == len(encodings[y]) and encodings[x][:-1] != encodings[y][:-1]

if __name__ == '__main__':
    s = Solution()

    print(s.isCousins(TreeNode(1,
                               TreeNode(2,
                                        None,
                                        TreeNode(4)),
                               TreeNode(3)), 2, 3))


from django import template
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.contrib.staticfiles.storage import staticfiles_storage

register = template.Library()

@register.simple_tag
def vertical_bar(value, max_value, display=None):
    if not max_value:
        return ""

    if display == "ratio":
        value_str = "%d/%d" % (value, max_value)
    else:
        value_str = str(value)

    # handle value == None
    value = value or 0

    try:
        ratio = min(float(value) / float(max_value), 1) * 100
    except ValueError:
        return ""

    if ratio > 40:
        left = format_html("{}", value_str)
        right = ""
    else:
        left = format_html(" ")
        right = format_html("{}", value_str)

    return format_html(
        '

{}
{}
',
        ratio,
        left,
        right,
    )

@register.filter()
def timeline(data):
    s = '\n'
    s += '\n"

    return mark_safe(s)


from project.player import Player

class Guild:
    def __init__(self, name: str):
        self.name = name
        self.players = []

    def assign_player(self, player: Player) -> str:
        if player.guild != "Unaffiliated":
            if self.name == player.guild:
                return f"Player {player.name} is already in the guild."

            else:
                return f"Player {player.name} is in another guild."

        else:
            player.guild = self.name
            self.players.append(player)
            return f"Welcome player {player.name} to the guild {self.name}"

    def kick_player(self, player_name: str) -> str:
        for pl in self.players:
            if pl.name == player_name:
                self.players.remove(pl)
                pl.guild = "Unaffiliated"
                return f"Player {player_name} has been removed from the guild."

        else:
            return f"Player {player_name} is not in the guild."

    def guild_info(self) -> str:
        current_players = []
        for pl in self.players:
            current_players.append(pl.player_info())
        current_players = "\n".join(current_players)
        return f"Guild: {self.name}\n" \
               f"{current_players}"

player = Player("George", 50, 100)
print(player.add_skill("Shield Break", 20))
print(player.player_info())

guild = Guild("UGT")
print(guild.assign_player(player))
print(guild.guild_info())


# Learner: Nguyen Truong Thinh
# Contact me: nguyentruongthinhvn2020@gmail.com || +84393280504
#
# Topic: Mathematical Thinking in Computer Science
# Proofs: Convincing Arguments section

from random import randint, seed

# Number theory: a / b = k, if a = kb
print(237 % 3, "\t", 237 % 7)
# Is there a positive integer that is divisible by 13 and ends with 15?
for i in range(10 ** 4):
    if i % 13 == 0 and i % 100 == 15:
        print(i)
# Find a two-digit (positive) integer that becomes 7 times smaller when its first
# (=leftmost) digit is removed.
for i in range(10, 100):
    if i == 7 * int(str(i)[1:]):
        print(i)
# Non-constructive Proofs (probabilistic method) / Irrational numbers: x = a / b (a > 0, b > 0)
# 2^n + 3^n <= 10^1000
for i in range(4000):
    if 2 ** i + 3 ** i > 10 ** 1000:
        print(i - 1)
        break
# Finding a constructive proof: generate 30 seven-digit numbers.
seed(10)
for i in range(30):
    print(randint(10 ** 6, 10 ** 7 - 1), end=' ')
    if i % 6 == 5:
        print()


import os

def run(path):
    for doc in os.listdir(path):
        docPath = os.path.join(path, doc)
        if os.path.isdir(doc):
            for sDoc in os.listdir(doc):
                sDocPath = os.path.join(docPath, sDoc)
                if not os.path.isdir(sDoc):
                    renamePath = os.path.join(docPath, sDoc.upper())
                    # print(renamePath)
                    os.rename(sDocPath, sDocPath.upper())

if __name__ == '__main__':
    run(r"D:\PythonProjects\SA_IntersectionSimulation\Data\Images")


#!/broad/software/free/Linux/redhat_5_x86_64/pkgs/python_2.7.1-sqlite3-rtrees/bin/python

# cptoigv.py
# Given a list of BAMs and loci, make for IGV_plotter
# a samples.txt and sample_locus.txt file corresponding
# to the cartesian product of all BAMs at all loci.

import sys
import re
import argparse
import os

parser = argparse.ArgumentParser(description='Produce sample and sample locus files.')
parser.add_argument('--bams', dest='bams', nargs='+',
    type=str, help='BAMs (full paths, space separated)' )
parser.add_argument('--loci', dest='loci', nargs='+',
    type=str, help='Loci (chr:pos+buffer, space separated)' )

args = parser.parse_args()

sfile = open('samples.txt',mode='wb')
slfile = open('sample_locus.txt',mode='wb')

for bam in args.bams:
    samplename = os.path.basename(bam)[:-4] # remove directory and .bam extension
    sfile.write(samplename+"\t"+bam+"\n")
    for locus in args.loci:
        samplelocusid = samplename+locus
        slfile.write(samplelocusid+"\t"+locus+"\t"+samplename+"\n")

sfile.close()
slfile.close()


# -*- coding: utf-8 -*-

# pylint: disable=trailing-whitespace,bad-whitespace,invalid-name
# pylint: disable=anomalous-backslash-in-string,bad-continuation
# pylint: disable=multiple-statements,redefined-outer-name,global-statement

"""
FILE:  pyThreeD.py
DATE:  06 DEC 2023
AUTH:  G. E. Deschaines
DESC:  Three dimensional (3D) drawing of objects defined as collections
       of polygons.
REFS:

  [1] This Python script was refactored from threeD.c available at:
      https://github.com/gedeschaines/threeD/blob/master/src/threeD.c

Disclaimer:  See DISCLAIMER file.

"""

import sys
import warnings

warnings.simplefilter(action='ignore', category=FutureWarning)

try:
    import matplotlib.pyplot as plt
except ImportError:
    print("* Error: Matplotlib package required.")
    print("         Suggest installing the SciPy stack.")
    sys.exit()

from draw3D import Draw3D

global fig       # Instantiated matplotlib pyplot figure
global draw3D    # Instantiated Draw3D object
global started   # Draw3D.MainLoop method started flag

started = False

def onClick(event):
    """
    Mouse button pressed handler
    """
    global fig
    global draw3D
    global started

    #b = event.button
    #x = event.xdata
    #y = event.ydata
    if not started:
        started = True
        draw3D.MainLoop()
        if draw3D.doneflag:
            fig.clear()
            plt.close(fig)
            sys.exit()
        started = False

if __name__ == "__main__":

    global fig
    global draw3D

    # Set image save flag and rate (FPS).

    img_Save = False  # Save rendered images as PNG files
    img_FPS = 50;     # (semi-colon is hold over from threeD.c)

    # Process command line arguments.

    CaseId = None  # TXYZ.OUT.CaseId

    if len(sys.argv) > 2:
        CaseId   = sys.argv[1]
        img_Save = False if sys.argv[2] == "0" else True
    else:
        print("usage:  python3 pyThreeD.py CaseId [0|1]")
        print("where:  CaseId - read trajectory data from ./out/TXYZ.OUT.CaseId")
        print("        [0|1]  - save rendered image flag (0=False, 1=True)")
        sys.exit()

    File  = "./out/TXYZ.OUT." + CaseId
    title = "pyThreeD - " + File

    # Instantiate a matplotlib pyplot figure.

    #fig = plt.figure(figsize=(6.0,6.0), dpi=100.0)     # 465x462 viewport
    fig = plt.figure(figsize=(8.0,6.0), dpi=100.0)     # 620x462 viewport
    #fig = plt.figure(figsize=(8.0,8.0), dpi=100.0)     # 620x616 viewport
    #fig = plt.figure(figsize=(7.74,7.78), dpi=100.0)   # 600x599 viewport
    #fig = plt.figure(figsize=(10.0,8.0), dpi=100.0)    # 775x616 viewport
    #fig = plt.figure(figsize=(10.32,7.80), dpi=100.0)  # 800x601 viewport

    try:
        fig.set_tight_layout(True)
    except:
        fig.set_layout_engine('tight')

    # Specify plotting layout and parameters.

    ax = fig.add_subplot(111, autoscale_on=False, animated=False)
    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect('equal')
    bbox = ax.bbox.get_points()
    w = round(bbox[1,0] - bbox[0,0])
    h = round(bbox[1,1] - bbox[0,1])
    #print("w= %d, h= %d" % (w, h))
    ax.set_xlim(0.0, w)
    ax.set_ylim(h, 0.0)
    ax.set_facecolor('#d8dcd6')  # light gray
    fig.canvas.draw()

    # Instantiate a Draw3D object.

    draw3D = Draw3D(txyzFile=File, w=w, h=h, fig=fig, ax=ax,
                    imgSave=img_Save, imgFPS=img_FPS)

    # Load object shape polygon data.

    draw3D.ReadPolyData()

    # Assign mouse button press handler.

    cidbtn = fig.canvas.mpl_connect('button_press_event', onClick)

    # Assign key press event handler.

    cidkey = fig.canvas.mpl_connect('key_press_event', draw3D.onPress)

    # Present instructions, then display figure window for rendering.

    print("With cursor in the displayed Figure, press a mouse button")
    print("to initiate threeD animation. If animation is exited or has")
    print("completed, close figure to terminate this program or press")
    print("a mouse button to restart animation. During threeD program")
    print("animation the following key presses are recognized:\n")

    print("Press T key to toggle field-of-view towards target.")
    print("Press M key to toggle field-of-view towards missile.")
    print("Press H key to toggle field-of-view along missile heading.")
    print("Press Z key to reset zoom to one.")
    print("Press Up Arrow key to increase zoom.")
    print("Press Down Arrow key to decrease zoom.")
    print("Press 0 (zero) key to reset animation step delay to zero.")
    print("Press Left Arrow key to slow animation down by 50 msec increments.")
    print("Press Right Arrow key to speed animation up by 50 msec increments.")
    print("Press Space key to toggle pause/unpause.")
    print("Press X key to exit animation (press a mouse button to restart).")
    print("Press Esc key to exit program.")

    plt.show(block=True)

    # Execution terminated, delete draw3D object and exit.

    del draw3D


import re
input_string = input("Enter a number :")
pattern = re.compile(r'(\d{3})(\d{10})')
country_code = pattern.search(input_string)
code = country_code.group(1)
code = int(code)
if code == 977:
    print("Your number belong to Nepal")
    print(f" And your phone number is {country_code.group(2)} ")
else:
    print("Your number does not belong to Nepal")

Some stuffs with python/python part  2/FindingCountryCode.py


import string

def most_common(hist):
    t = []
    for key, value in hist.items():
        t.append((value, key))
    t.sort(reverse=True)
    return t

def process_file(filename):
    hist = {}
    fin = open(filename)
    for line in fin:
        process_line(line, hist)
    return hist

def process_line(line, hist):
    line = line.replace('-', ' ')
    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()
        hist[word] = hist.get(word, 0) + 1

hist = process_file('emma.txt')
t = most_common(hist)
print('The most common words are: ')
for freq, word in t[:40]:
    print(word, freq, sep='\t') #deixa a segunda coluna alinhada verticalmente

Capítulo 13 Seleção de estrutura de dados/palavras mais comuns.py


episodes_count = 5
MOVE_PENALTY = 1
DEAD_END_PENALTY = 300
DESTINATION_REWARD = 25
epsilon = 0.9
epsilon_decay = 0.9998
show_game_every = 2

start_q_table = None # None or Filename

LEARNING_RATE = 0.1
DISCOUNT = 0.95

SIZE = 10


#twitter mentioning network Matrix
#goal is to make it up-to-date everytime
#this code is run by a user

#!/usr/bin/env python
# encoding: utf-8
import time
from selenium import webdriver #solve scroll problem????
from selenium.webdriver.common.keys import Keys
#from selenium.webdriver.support.ui import WebDriverWait
#import selenium.webdriver.support.expected_conditions as EC
#from selenium.webdriver.common.by import By
import csv
driver = webdriver.Chrome() # edit to webdriver.PhantomJS("phantomjs")
                            # to utilize phantomjs instead

#take command line argument of file name
'''
try:
    filename = sys.argv[1]
except IndexError:
    filename = "edges.csv"
'''
fd = open('new_edges.csv', 'wb')
#mentioner is from whome the mention, and mentiong is the person
#being mentioned
def get_total_mention(mentioner, mentioning):
    url = u'https://twitter.com/search?f=tweets&q=from%3A'+mentioner+'%20%40'+mentioning+'&src=typd'
    driver.get(url)
    time.sleep(2)
    body = driver.find_element_by_tag_name('body')

    for _ in range(400):
        body.send_keys(Keys.PAGE_DOWN)

    #    if driver.find_elements_by_class_name('stream-end-inner'):
    #        next
    #    time.sleep(0.2)
        #if driver.find_elements_by_class_name('stream-end-inner')
        #continue
    tweets = driver.find_elements_by_class_name('tweet-text')

    counter = 0
    for tweet in tweets:
        if not tweet:
            continue
        counter += 1
    results = '%s,%s,%s\n' % (mentioner,mentioning,counter)#outputformat gephi edges
    fd.write(results)
with open(var, 'r') as file1:
    l = []
    for usern in file1:
        usern = usern.rstrip()
        l.append(usern)
    for mentioner in l:
        time.sleep(2) #find best time sleep for twitter
        for mentioning in l: #what's newer way to do nested loop?find
            get_total_mention(mentioner, mentioning)
fd.close()


# coding=utf-8
from __future__ import print_function
import numpy as np
import sys
import os
import pandas as pd

def print_log(*s, **kwargs):
    log_handle = kwargs.get("log_handle", sys.stderr)
    print(*s, file=log_handle)
    log_handle.flush()

def make_kwargs(args):
    kwargs = {}
    for kv in args:
        arr = kv.split("=")
        if len(arr) == 2:
            key, val = arr
        else:
            key = arr[0]
            val = None
        kwargs[key] = val
    return kwargs

def count_lines(fpath):
    line_count = 0
    with open(fpath, "r") as fin:
        for line_count, _ in enumerate(fin, 1):
            pass
    return line_count

PLINK_BED_MAGIC_NUMBERS = [0b01101100, 0b00011011]
PLINK_SNP_MAJOR_MODE = 1

def read_bed_file(bed_file_path, missing=255):
    """read genotypes in plink bed file format with sample size n and number of SNPs p
        missing genotypes are set to missing
    """
    bed_file_dirname, bed_file_basename = os.path.split(bed_file_path)
    arr = bed_file_basename.split(".")
    if len(arr) >= 2:
        bed_file_prefix = ".".join(arr[:-1])
    else:
        bed_file_prefix = ".".join(arr)
    n = count_lines(os.path.join(bed_file_dirname, bed_file_prefix + ".fam"))
    p = count_lines(os.path.join(bed_file_dirname, bed_file_prefix + ".bim"))
    print_log("Reading bed file {0} with n = {1}, p = {2}".format(bed_file_path, n, p))
    return read_bed_file_dims(bed_file_path, n, p, missing)

def read_bed_file_dims(bed_file_path, n, p, missing=255):
    """read genotypes in plink bed file format with sample size n and number of SNPs p
        missing genotypes are output as 255 by default
    """
    # reads bed file format described at http://pngu.mgh.harvard.edu/~purcell/plink/binary.shtml
    tmp_X = np.fromfile(bed_file_path, dtype=np.uint8)

    assert all(tmp_X[0:2] == PLINK_BED_MAGIC_NUMBERS), "magic numbers in bed file don't match expected values"
    assert tmp_X[2] == PLINK_SNP_MAJOR_MODE, "bed file needs to be in SNP-major mode"
    assert 4*(tmp_X.shape[0] - 3) % p == 0, "mismatch in bed file dimensions"

    n_tilde = int((tmp_X.shape[0] - 3) * 4 / p)     # n_tilde = 4 * ceil (n / 4)

    X = np.zeros(n_tilde * p, dtype=np.uint8)

    X[0::4] = (tmp_X[3:] & 0b11      )
    X[1::4] = (tmp_X[3:] & 0b1100    ) >> 2
    X[2::4] = (tmp_X[3:] & 0b110000  ) >> 4
    X[3::4] = (tmp_X[3:] & 0b11000000) >> 6

    # 00  Homozygote "1"/"1"
    # 01  Heterozygote
    # 11  Homozygote "2"/"2"
    # 10  Missing genotype
    X[X == 2] = missing   # missing value
    X[X == 3] = 2

    X = np.reshape(X, (p, n_tilde))

    return X[:, 0:n].T

def write_bed_file_dims(X, file_path, n, p):
    X = np.array(X, dtype=np.uint8)
    n_tilde = 4 * int((n + 3) / 4)
    X = np.vstack([X, np.zeros((n_tilde - n, p), dtype=np.uint8)])
    X = X.T.flatten()
    X[X == 2] = 3
    tmp_X = np.zeros((n_tilde * p) / 4 + 3, dtype=np.uint8)
    # print tmp_
    tmp_X[0:2] = PLINK_BED_MAGIC_NUMBERS
    tmp_X[2] = PLINK_SNP_MAJOR_MODE
    tmp_X[3:] = X[0::4] | (X[1::4] << 2) | (X[2::4] << 4) | (X[3::4] << 6)
    tmp_X.tofile(file_path)

def read_bim_file(bim_file_path):
    snp_df = pd.read_table(bim_file_path, delim_whitespace=True, header=None, names=["chr", "snp", "dist", "pos", "allele1", "allele2"])
    return snp_df


# coding=utf-8
import random
import numpy as np
from collections import defaultdict
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator

class LearningAgent(Agent):
    """ An agent that learns to drive in the smart-cab world

    *** Q-learning agent pseudo-code ***

    1. Initialize Q(s, a) arbitrarily
    2. For each trial t:
        3. Repeat for until deadline or goal is reached:
            4. Update the state s
            5. Choose action a from s using a policy derived from Q (e.g. epsilon-greedy)
            6. Take action a and observe the reward and outcome state s'
            7. Update Q(s, a) := Q(s,a) + α [r + γ max_a′ Q(s′,a′) − Q(s,a)]
    """

    def __init__(self, env):
        """ Initialize the learning agent"""

        super(LearningAgent, self).__init__(env)  # Run constructor of base class
        self.color = 'red'  # Set agent color to red, overriding the default value
        self.planner = RoutePlanner(self.env, self)  # Route planner to get next_waypoint
        self.actions = Environment.valid_actions  # Store all possible actions (improved code readability)

        self.Q = defaultdict(lambda: random.uniform(-.25, .25))  # arbitrary values for all state, action pairs
        self.gamma = 0.35  # Discount factor of max(Qs', a')
        self.epsilon = 0.9  # Probability of doing a random move
        self.alpha = 0.2  # Learning rate
        self.trial = 0  # Trial counter (epsilon decay)
        self.selection = "random"
        self.filter = False

        self.total_reward = 0  # Keep track of total reward for the current trial
        self.mistake_counter = 0  # Keep track of the number of moves with a negative reward
        self.rewards = []  # Historical rewards
        self.mistakes = []  # Historical mistakes
        self.results = []  # Non-successful trials
        self.success = 1

    def set_parameters(self, alpha, epsilon, gamma, selection, f):
        """ Overwrite the parameters with static settings hack """

        self.gamma = gamma  # Discount factor of max(Qs', a')
        self.epsilon = epsilon  # Probability of doing a random move
        self.alpha = alpha
        self.selection = selection
        self.filter = f

    def reset(self, destination=None):
        """ Reset the agent between trails """

        self.planner.route_to(destination)  # Initialize new destination

        self.trial += 1  # For every trial, increment trial counter
        self.rewards.append(self.total_reward)  # Keep track of rewards for each trial
        self.mistakes.append(self.mistake_counter)  # Keep track of mistakes for each trial
        self.total_reward = 0  # Reset reward counter
        self.mistake_counter = 0  # Reset mistake counter
        self.results.append(self.success)
        self.success = 1

    def get_state(self):
        """ Return the current state s of the agent """

        inputs = self.env.sense(self)
        return inputs['light'], inputs['oncoming'], inputs['left'], self.next_waypoint

    def select_action(self, s):

        if self.selection == "random":
            return random.choice(self.actions)

        if self.selection == "epsilon-greedy":
            # select a random move with probability ε
            if random.random() < self.epsilon:
                return random.choice(self.actions)
            else:
                # Shuffle deals with the cases when a draw is returned from np.argmax
                random.shuffle(self.actions)
                # Evaluate all action and pick the one with the highest estimated reward
                return self.actions[np.argmax([self.Q[(s, a_i)] for a_i in self.actions])]

        elif self.selection == "epsilon-decay":
            # select a random move with probability ε controlled by an epsilon-decay function
            if random.random() < np.exp(-self.epsilon * self.trial):
                return random.choice(self.actions)
            # otherwise action = max Q(s', a')
            else:
                # Shuffle deals with the cases when a draw is returned from np.argmax
                random.shuffle(self.actions)
                # Evaluate all action and pick the one with the highest estimated reward
                return self.actions[np.argmax([self.Q[(s, a_i)] for a_i in self.actions])]

    def update(self, t):
        """ Implements the q-learning algorithm """

        # Get next waypoint from the route planner
        self.next_waypoint = self.planner.next_waypoint()

        # Filter out unwanted actions
        if self.filter:
            self.actions = [self.next_waypoint, None]

        # Observe the current state
        s = self.get_state()
        # Select action a according to policy
        a = self.select_action(s)
        # Take action a, observe reward and s'
        reward, s_i = self.env.act(self, a), self.get_state()
        # Calculate maximum attainable reward in the next state (s_i)
        max_a = max([self.Q[(s_i, a_i)] for a_i in self.actions])
        # Update state, action value
        self.Q[(s, a)] += self.alpha * (reward + self.gamma * (max_a - self.Q[(s, a)]))

        # Update total reward
        self.total_reward += reward
        # If remaining time is 0, store as failed attempt
        if self.env.get_deadline(self) == 0:
            self.success = 0
        # Update total mistakes
        if reward < 0:
            self.mistake_counter += 1

        # DEBUG
        # print "deadline = {}, inputs = {}, action = {}, reward = {}".format(
            # self.env.sense(self), self.env.get_deadline(self), a, reward)

    def get_run_data(self):
        return self.results, self.mistakes, self.rewards

def run(alpha, epsilon, gamma, selection, t, f):
    """Run the agent for a finite number of trials."""

    # create environment, add dummy agents
    e = Environment()

    # Create our agent
    a = e.create_agent(LearningAgent)
    # Initialize agent settings
    a.set_parameters(alpha, epsilon, gamma, selection, f)
    # Configure the environment, set agent a as primary agent to track
    e.set_primary_agent(a, enforce_deadline=True)

    # Simulator settings, reduce delay to speed up simulations
    sim = Simulator(e, update_delay=0.00001)
    # Set the number of trials
    sim.run(n_trials=t)

    # Return data on agents performance
    return a.get_run_data()

if __name__ == '__main__':
    run(.2, .5, .1, "epsilon-decay", 100)


import random

def kilobases():

    err = True
    while err == True:
        try:
            cantidad_kb= int(input("Digite una cantidad de kilobases de ADN: "))
            err = False
        except ValueError:
            err = True

    try:
        GC = float(input("Digite un porcentaje de pares GC en decimales (0 - 1): "))
        if GC < 0 or GC > 1:
              GC = 0.5

    except ValueError:
        GC = 0.5

    A,T,G,C = "A","T","G","C"

    total_GC = round(cantidad_kb*GC)

    G = G * random.randint(0,round(total_GC))
    C = C * (total_GC - len(G))

    total_AT = cantidad_kb - total_GC

    A = A * random.randint(0,round(total_AT))
    T = T * (total_AT - len(A))

    lista = list(A+T+G+C)

    random.shuffle(lista)

    secuencia = ''.join(lista)

    print(secuencia)

kilobases()


import turtle

turtle.getscreen().setworldcoordinates(-50, -130, 130, 50)
turtle.speed(0)
turtle.hideturtle()

def draw(itrn):
  sqr = 'FRFRFRFR'
  for j in range(itrn):
    sqr = sqr.replace('F', 'FLFRFRFLF')

  for s in sqr:
    if s == 'F':
      turtle.forward(3 ** (4 - itrn))
    elif s == 'L':
      turtle.left(90)
    elif s == 'R':
      turtle.right(90)

for j in range(5):
  draw(j)

#open('sqr.ps', 'w').write(turtle.getscreen().getcanvas().postscript())

import time
time.sleep(100)


N = input("")
N = int(N)

counter = 0

for i in range(N):
	newinput = input()
	for i in newinput:
		if i in newinput:
			counter[i] += 1
			print(counter, newinput[i])
		else:
			counter[i] = 1


#!/usr/bin/python

# -*- coding: utf-8 -*-

# For better print formatting
from __future__ import print_function

# Imports
from enum import Enum

from data_utils import DataRegister
from data_utils import MainDataAccessRegister
from task_utils import TaskRegister
from task_utils import ApplicationRegister
from action_utils import JobRegister
from resource_utils import ResourceRegister
from connection_utils import ConnectionRegister
from ce_utils import CoreElementRegister

import sys

class ExecutionState:
    """
    Class representing the current state of the execution
    """
    def __init__(self):
        self.core_elements = CoreElementRegister()
        self.apps = ApplicationRegister()
        self.tasks = TaskRegister()
        self.resources = ResourceRegister()
        self.jobs = JobRegister()
        self.data = DataRegister()
        self.connections = ConnectionRegister()
        self.main_accesses = MainDataAccessRegister()

    def clear(self):
        self.tasks = TaskRegister()
        self.resources = ResourceRegister()
        self.jobs = JobRegister()
        self.main_accesses = MainDataAccessRegister()

    def query_resource(self, query):
        if len(query) > 0:
            resource_name = query[0]
            resource = self.resources.get_resource(resource_name)
            if resource is None:
                print("Runtime has no information regarding resource " + resource_name + ".", file=sys.stderr)
            else:
                print("-------- Resource ------")
                print("Name: " + resource.name)
                print("Currently hosting :")
                for a in resource.hosts:
                    print("\t " + str(a))
                print("Task History:")
                for entry in resource.history:
                    print("\t " + entry[0] + " -> " + entry[1])
        else:
            print("-------- Resources ------")
            resources = self.resources.get_resources()
            resource_names = self.resources.get_resource_names()
            max_length = 4
            for name in resource_names:
                if len(name) > max_length:
                    max_length = len(name)
            print("Name" + (((max_length - 4) + 3) * " ") + "#Hosting actions")
            for resource in sorted(resources, key=lambda resource: resource.name):
                name = resource.name
                print(name + (((max_length - len(name)) + 3) * " ") + str(len(resource.hosts)))

    def _short_signature(self, signature):
        if len(signature) > 50 :
            method_name = signature.split(".")[-1]
            prev_len = 47 - len(method_name)
            return signature[0:prev_len]+".."+method_name
        else:
            return signature.ljust(50)

    def query_core_elements(self, query):
        """

        :param query:
        """
        if len(query) > 0:
            core_element = None
            if all(char.isdigit() for char in query[0]):
                core_id = int(query[0])
                core_element = self.core_elements.get_core_element_by_id(core_id)
            else:
                core_signature = query[0]
                core_element = self.core_elements.get_core_element_by_signature(core_signature)
            if core_element is None:
                print("Runtime has no information regarding such core element.", file=sys.stderr)
            else:
                print("------- Core Element ------")
                print("Id: " + str(core_element.core_id))
                print("Signature: " + core_element.signature)
                print("Implementations:")
                for impl in core_element.get_implementations():
                    print("\t* Signature:"+impl.signature)
                    print("\t  Constraints:"+impl.constraints)
                print("History:")
                for entry in core_element.get_history():
                    print("\t "+entry[0]+" -> "+entry[1])

        else:
            print("------ Core Elements ------")
            print("ID\tSignature\t\t\t\t\t\tCPUs\tMem")
            cores = self.core_elements.get_core_elements()
            for core in sorted(cores, key=lambda core: int(core.core_id)):
                print(str(core.core_id)+"\t"+self._short_signature(str(core.signature)))
                impls = core.get_implementations()
                impl_count=len(impls)
                idx = 0
                for impl in impls:
                    impl_desc=""
                    if impl_count == idx+1:
                        impl_desc = b'\xc0'.decode("cp437") # |_
                    else:
                        impl_desc = b'\xc3'.decode("cp437") # |-
                    impl_desc = impl_desc + (b'\xc4'.decode("cp437") * 7 ) # -
                    print(impl_desc+" "+self._short_signature(str(impl.signature))+"\t"+impl.get_constraints_cores()+"\t"+impl.get_constraints_memory())

    def query_connection(self, query):
        """

        :param query:
        """
        if len(query) > 0:
            if all(char.isdigit() for char in query[0]):
                connection_id = query[0]
                connection = self.connections.get_connection(connection_id)
                if connection is None:
                    print("Runtime has no information regarding connection " + connection_id + ".", file=sys.stderr)
                else:
                    print("-------- Connection ------")
                    print("Id: " + connection.connection_id)
                    print("Socket Id: " + str(connection.socket_id))
                    print("Current Stage: "+str(connection.current_stage.name))

                    print("Enqueued Stages: ")
                    for stage in connection.get_stages():
                        print("\t "+stage.name)
                    print("Connection History:")
                    for entry in connection.get_history():
                        print("\t "+entry[0]+" -> "+entry[1])
            else:
                print("Unknown job sub-command "+query[0], file=sys.stderr)
        else:
            print("------- Connections -------")
            print("Connection ID\tStatus")
            connections = self.connections.get_connections()
            for connection in sorted(connections, key=lambda connection: int(connection.connection_id)):
                print(connection.connection_id+"\t"+str(connection.status))

    def query_job(self, query):
        """

        :param query:
        """
        if len(query) > 0:
            if all(char.isdigit() for char in query[0]):
                job_id = query[0]
                job = self.jobs.get_job(job_id)
                if job is None:
                    print("Runtime has no information regarding job " + job_id + ".", file=sys.stderr)
                else:
                    print("-------- Job ------")
                    print("Id: " + job.job_id)
                    print("Job Status " + str(job.status))
                    print("Resource: " + str(job.resource.name))
                    print("Action: " + str(job.action))
                    print("Job History:")
                    for entry in job.get_history():
                        print("\t "+entry[0]+" -> "+entry[1])
            else:
                print("Unknown job sub-command "+query[0], file=sys.stderr)
        else:
            print("-------- Jobs ------")
            print("Job ID\tStatus\t\tAction\t\t\t\tResource\tExecution Period")
            jobs = self.jobs.get_jobs()
            for job in sorted(jobs, key=lambda job: int(job.job_id)):
                job_status_label = "{:<15}".format(str(job.status).split(".")[1])
                job_action_label= "{:<31}".format(str(job.action))
                job_resource_label = "{:<15}".format(str(job.resource.name))

                job_creation_label="?"
                job_submission_label="?"
                job_completion_label="?"
                for entry in job.get_history():
                    if "created" in entry[1]:
                        job_creation_label=entry[0]
                    elif "submitted" in entry[1]:
                        job_submission_label=entry[0]
                    elif "completed" in entry[1]:
                        job_completion_label=entry[0]

                print(job.job_id+"\t"+job_status_label+"\t"+job_action_label+"\t"+job_resource_label+"\t"+job_submission_label+"-"+job_completion_label)

    def query_task(self, query):
        if len(query) > 0:
            if all(char.isdigit() for char in query[0]):
                task_id = query[0]
                task = self.tasks.get_task(task_id)
                if task is None:
                    print("Runtime has no information regarding job " + task_id + ".", file=sys.stderr)
                else:
                    print("-------- Task ------")
                    print("Id: " + task.task_id)
                    print("Method Name: " + task.method_name)
                    print("Parameters:")
                    for p in task.parameters:
                        direction = str(p.get_direction())
                        data = p.get_data()
                        data_id = str(data.get_id())
                        predecessor = p.get_detected_dependency()
                        confirmed_predecessor = p.get_confirmed_dependency()

                        producer = ""
                        if predecessor is not None:
                            predecessor_state = predecessor.state
                            if confirmed_predecessor is not None:
                                if predecessor == confirmed_predecessor:
                                    producer = " depends on task "+str(predecessor.task_id) +\
                                               " (detected with state " + str(predecessor_state)+")"
                                else:
                                    producer = " expected a dependency on task " + str(predecessor.task_id) + \
                                               " and dependency with " + str(confirmed_predecessor.task_id)
                            else:
                                producer = " depends on task "+str(predecessor.task_id) +\
                                               " (not detected with state " + str(predecessor_state)+")"
                        else:
                            if confirmed_predecessor is not None:
                                producer = "unexpected dependency with task " + str(confirmed_predecessor.task_id)
                            else:
                                producer == ""
                        print(" * " + direction + " data " + data_id + producer)

                    print("Status: " + str(task.state))
                    print("Actions: ")
                    for a in task.action:
                        print("\t "+str(a))
                    print("Task History:")
                    for entry in task.get_history():
                        print("\t "+entry[0]+" -> "+entry[1])
            else:
                print("Unknown job sub-command "+query[0], file=sys.stderr)
        else:
            print("-------- Tasks ------")
            name_max_length = 0
            for name in self.tasks.get_method_names():
                if len(name) > name_max_length:
                    name_max_length = len(name)
            print("Task ID" + "    " +
                  "Method name" + ((name_max_length - 11 + 4) * " ") +
                  "Status")
            tasks = self.tasks.get_tasks()
            for task in sorted(tasks, key=lambda task: int(task.task_id)):
                print(task.task_id+((11-len(task.task_id))*" ") +
                      task.method_name + (( name_max_length - len(task.method_name) + 4) * " ") +
                      str(task.state))

    def query_data(self, query):
        if len(query) > 0:
            if all(char.isdigit() for char in query[0]):
                data_id = query[0]
                data = self.data.get_datum(data_id)
                if data is None:
                    print("Runtime has no information regarding data " + data_id + ".", file=sys.stderr)
                else:
                    print("-------- Data ------")
                    print("Id: " + data.get_id())
                    last_writer = data.get_last_writer()
                    if last_writer is None:
                        last_writer = "Main Code"
                    else:
                        last_writer = last_writer.task.task_id
                    print("Last writer: " + last_writer)
                    print("Data history:")
                    for entry in data.get_history():
                        print("\t " + entry[0] + " -> " + entry[1])
            else:
                print("Unknown job sub-command " + query[0], file=sys.stderr)
        else:
            print("-------- Data ------")
            print("Data ID     Num Versions    Last Writer")
            data = self.data.get_data()
            for d in sorted(data, key=lambda d: int(d.get_id())):
                last_writer = d.get_last_writer()
                if last_writer is None:
                    last_writer = "Main Code"
                else:
                    last_writer = last_writer.task.task_id
                versions_count = str(len(d.get_all_versions()))
                print(d.get_id() + ((12 - len(d.get_id())) * " ") + versions_count + ((28 - 12 - len(versions_count)) * " ") + last_writer)


def SearchCV(X, Y, estimator, param, crossval, nb_coeur, etape, random_search = False, iteration = None):
    import Librairies
    import Constant

    global search
    param_dist = param
    #NAME_ALGO = Constant.NAME_ALGORITHM
    #RANDOM_SEARCH = Constant.RANDOMIZED_SEARCH

    if random_search:
        search = Librairies.RandomizedSearchCV(estimator, param_distributions=param_dist, cv = crossval,
                                       n_iter=iteration, n_jobs = nb_coeur, verbose = etape)
    else:
        search = Librairies.GridSearchCV(estimator, param_distributions=param_dist, cv = crossval,
                                       n_jobs = nb_coeur, verbose = etape)

    start = Librairies.time.time()
    search.fit(X, Y)

    with open(Constant.REP_DATA_IN + Constant.M_NAME_OUTPUT, 'a', encoding='utf-8') as f:
        for i in range(1, 4):
            candidates = Librairies.np.flatnonzero(search.cv_results_['rank_test_score'] == i)
            for candidate in candidates:
                f.write("Algorithm: %s \r\n" % Constant.M_NAME_ALGORITHM)
                f.write("Model with rank: %d \r\n" % i)
                f.write("Mean validation score: %f (std: %f) \r\n" % (search.cv_results_['mean_test_score'][candidate],search.cv_results_['std_test_score'][candidate]))
                f.write("Parameters: %s \r\n" % search.cv_results_['params'][candidate])
                f.write("\r\n")
    f.close()

    return search