import telebot
import random
viclist = ['Молодец','Поздраляю','Умничка','Везунчик','Вы стеклодув','Любитель стекла','Каратель викторин']
funlist = ['Почему стекольные заводы всегда заняты? Потому что им всегда есть что гранить!',
           'Что скажет стеколомойщик, когда его спросят, как дела на заводе? Нам все в руки!',
           'Почему стекольные заводы никогда не скучают? Потому что у них всегда есть окна к похвале!',
           'Какой стекольный завод самый занятой? Тот, где люди в очереди стоят, чтобы разбить окно!',
           'Почему на стекольных заводах всегда тихо? Потому что стеклографии не звучат громко!',
           'Как называют завод, где производят бутылки? Стекловкусообразие!',
           'Что произойдет, если стекольщик на заводе долго не спит? Он начнет видеть окна возле каждого предмета!',
           'Как стекольные заводы поднимают настройку своих работников? Им показывают прозрачные слайды!',
           'Зачем стекольным заводам экстрасенсы? Чтобы заранее видеть, сколько окон им нужно производить!',
           'Когда на стекольных заводах наступает новый год, они празднуют разбитием бутылок и украшением окон!',
           "Почему стекольный завод всегда приносит прибыль? Потому что они всегда имеют чашку успеха!",
            "Какой самый популярный подарок на свадьбу стекольщикам? Очевидно, стеклянные сюрпризы!",
            "Зачем стеклоход ходит вокруг стекольного завода? Он ищет свою прозрачную любовь!",
            "Почему стеклодувы такие хорошие рассказчики? Потому что они всегда говорят правду в глаза!",
            "Как называют танцы на стекле? Стеклянные шары!",
            "Какой фильм любят смотреть на стекольных заводах? Стекло (Glass)!",
            "Почему стекло всегда спокойное? Потому что оно никогда не теряет своего хладнокровия!"
]

from telebot import types
qvestmode = False
bot = telebot.TeleBot('6478889497:AAGb_tVDuN3Y5dlMGsTwXqdXykAU1JnsW8I')
def SetOff(bool):
    bool = False
def SetOn(bool):
    bool = True
@bot.message_handler(commands=['start','s'])
def main(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("👋 Поздороваться")
    btn2 = types.KeyboardButton("❓ Задать вопрос")
    markup.add(btn1, btn2)
    bot.send_message(message.chat.id,f'Привет, {message.from_user.first_name}, Я чат бот ажур стиль, ты можешь увидеть снизу экрана,кнопки, нажимайте на них чтобы задавать вопросы и многое другое)',reply_markup=markup)
@bot.message_handler(content_types=['text'])
def func(message):
    if message.text == "👋 Поздороваться":
        bot.send_message(message.chat.id, text="Привет! Я чат бот ажур стиль, ты можешь увидеть снизу экрана кнопки, нажимайте на них чтобы задавать вопросы и многое другое)")
    elif message.text == "❓ Задать вопрос":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("Викторина 💎")
        btn2 = types.KeyboardButton("Что я могу 🤖")
        btn3 = types.KeyboardButton("Обо Всем 🌃")
        btn4 = types.KeyboardButton("Шутки про стеклозавод 🤡")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(btn1, btn2, btn3,btn4, back)
        bot.send_message(message.chat.id, text="Задай мне вопрос", reply_markup=markup)

    elif message.text == "Шутки про стеклозавод 🤡":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Еще Одну Шутку!")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, back)
        bot.send_message(message.chat.id, "Окей вот и шутка:\n" + ''+funlist[random.randrange(0,16)]+"", reply_markup=markup,parse_mode='html')

    elif message.text == "Еще Одну Шутку!":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Еще Одну Шутку!")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, back)
        bot.send_message(message.chat.id, "Окей вот и шутка:\n" + '' + funlist[random.randrange(0, 16)] + "",
                         reply_markup=markup, parse_mode='html')

    elif message.text == "Викторина 💎":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Бутылки стеклянные")
        button2 = types.KeyboardButton("Банки стеклянные")
        button3 = types.KeyboardButton("Любые")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id,"Привет , {0.first_name}! \nРад видеть тебя в викторине!\nИтак, не будем же ждать, к первому вопросу.".format(message.from_user, bot.get_me()))
        bot.send_message(message.chat.id, "Вопрос №1:\nЧто принимаем?",reply_markup=markup)
    elif message.text == "Любые" :
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Банки стеклянные":
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Бутылки стеклянные":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Хрусталь целая")
        button2 = types.KeyboardButton("Хрусталь битая")
        button3 = types.KeyboardButton("Любые из предложенных")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)] + ', следующий вопрос №2!')
        bot.send_message(message.chat.id, 'Что из этого мы также принимаем!',reply_markup=markup)
    elif message.text == "Любые из предложенных" :
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Хрусталь битая":
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Хрусталь целая":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Синие и прозрачные стеклянные")
        button2 = types.KeyboardButton("Пластиковые,стеклянные")
        button3 = types.KeyboardButton("Железные и стеклянные")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №3!')
        bot.send_message(message.chat.id, 'какие бутылки принимаем?', reply_markup=markup)
    elif message.text == "Железные и стеклянные":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "Пластиковые,стеклянные":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "Синие и прозрачные стеклянные":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Нисколько, даром")
        button2 = types.KeyboardButton("мало")
        button3 = types.KeyboardButton("много всего")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №4!')
        bot.send_message(message.chat.id, 'Сколько платят за сдачу стекла?', reply_markup=markup)
    elif message.text == "мало":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "много всего":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "Что я могу 🤖":
        bot.send_message(message.chat.id, text="Я - чат бот Ажур Стиль могу все что вы попросите!\nНапример если хотите я могу вам рассказать про стекло и когда были первые очки, если интересно тогда переходи в вопросы и выбери пункт обо всем! И узнай много вестей")

    elif message.text == "Нисколько, даром":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("мячи")
        button2 = types.KeyboardButton("деревянные игрушки")
        button3 = types.KeyboardButton("елочные игрушки")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №5!')
        bot.send_message(message.chat.id, 'Что изготавливают из бутылочного стекла?', reply_markup=markup)

    elif message.text == "мячи":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "деревянные игрушки":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "елочные игрушки":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("785")
        button2 = types.KeyboardButton("1088")
        button3 = types.KeyboardButton("2137")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)] + ', следующий вопрос №6!')
        bot.send_message(message.chat.id, 'При какой температуре плавится жидкое стекло?', reply_markup=markup)

    elif message.text == "785":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "2137":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1088":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("красный")
        button2 = types.KeyboardButton("голубой")
        button3 = types.KeyboardButton("синий")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №7!')
        bot.send_message(message.chat.id, 'Какой цвет самого дорогого стекла?', reply_markup=markup)

    elif message.text == "голубой":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "синий":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "красный":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("1451г")
        button2 = types.KeyboardButton("1673г")
        button3 = types.KeyboardButton("1342г")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №8!')
        bot.send_message(message.chat.id, 'Когда изобрели очки для коррекции зрения?', reply_markup=markup)

    elif message.text == "1673г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "1342г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1451г":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("1876г")
        button2 = types.KeyboardButton("2004г")
        button3 = types.KeyboardButton("1903г")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №9!')
        bot.send_message(message.chat.id, 'когда было изобретено Небьющееся стекло?', reply_markup=markup)
    elif message.text == "2004г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "1876г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1903г":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("металлы")
        button2 = types.KeyboardButton("краски")
        button3 = types.KeyboardButton("красители")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, 'Итак! Это последний вопрос викторины')
        bot.send_message(message.chat.id, 'что используют для окраски стекла?', reply_markup=markup)
    elif message.text == "краски":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "красители":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "металлы":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+'! Вы прошли эту викторину о стекле !', reply_markup=markup)

    elif message.text == "Обо Всем 🌃":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        back = types.KeyboardButton("Вернуться в главное меню")
        btn1 = types.KeyboardButton("Что принимают стекольные фабрики?")
        btn2 = types.KeyboardButton("Что изготавливают стекольные фабрики?")
        btn3 = types.KeyboardButton("Когда изобрели?")
        markup.add(btn1,btn2,btn3,back)
        bot.send_message(message.chat.id, text="Здесь вы можете узнать все и ответы на викторину в том числе!",parse_mode='html',reply_markup=markup)

    elif message.text == "Когда изобрели?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="О первых очках коррекции зрения: В 1451 году в Германии Nikolaus Kuzanski наладил производство вогнутых линз"
                                               ", которые имели тонкий центр линзы и толстый край и использовались для коррекции близорукости. "
                                               "Первые оправы для очков Первые оправы для очков изготавливались из дерева, свинца или меди.\n\nНебьющееся стекло "
                                               "было изобретено случайно. В 1903 году французский химик Эдуард Бенедиктус нечаянно уронил колбу, заполненную"
                                               "нитроцеллюлозой. Стекло треснуло, но не разлетелось на мелкие кусочки.\n\nТак как ученые считают эти находки древнейшими, "
                                               "то на вопрос, когда появилось стекло, они отвечают – около 12 тысяч лет назад. Именно столько лет насчитывает существование "
                                               "голубых и зеленых украшений из числа египетских археологических находок.\nОтвечая на вопрос, откуда появилось стекло, ученые сделали вывод, что это "
                                               "произошло примерно 55 веков назад, на территории Древнего Египта и Месопотамии. Первыми предметами из стекла были небольшие шарики правильной формы", reply_markup=markup)
    elif message.text == "Что изготавливают стекольные фабрики?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="\nОснову стекольной промышленности в России представляют пять крупных заводов, специализирующихся "
                                               "на производстве листового стекла. На их долю приходится более 90% всего выпускаемого в стране объема. \n\n"
                                               "Листовое стекло производится из кварцевого песка, кальцинированной соды, доломита и различных примесей. \n\n"
                                               "Продукция заводов востребована в строительстве, машиностроении, производстве мебели, торгового и медицинского"
                                               "оборудования, бытовой техники. Статистика отрасли показывает ежегодный рост производства в пределах 15%. \n\nНовым "
                                               "перспективным направлением стекольной промышленности, в котором занято свыше 50 профильных предприятий, называют "
                                               "промышленную переработку, включающую в себя изготовление стеклопакетов, закаливание и армирование стекла, производство "
                                               "триплекса. \n\nСтекольные заводы реализуют готовую продукцию следующих типов: стекло листовое, закаленное, матовое, цветное, "
                                               "узорчатое, армированное, многослойное, огнеупорное, а также стеклопакеты и стеклянные блоки "
                                               "\n\nСтекольные фабрики изготавливают елочные игрушки, многие украшение, посуду, дверные стекла и очень большое количество "
                                               "товаров на заказ!", reply_markup=markup)
    elif message.text == "Что принимают стекольные фабрики?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id,
                         text="\n\nПереработкой стекла занимаются стеклоперерабатывающие заводы. В отличие от переработки пластика, эта система налажена и успешно работает уже долгие годы. \n\nВ стране работают десятки предприятий, которые перерабатывают стекло и превращают его в новые изделия. Поэтому дело за каждым – сдавать стекло на переработку довольно просто. \n\nНайти ближайший пункт приёма стеклотары в своём городе можно здесь."
"\n\nВ контейнеры для вторсырья или пункты приёма стеклотары можно отнести бутылки от напитков, банки из-под консервов или детского питания, а также различные пузырьки. Тара может быть прозрачная, зелёная или коричневая."
"\n\nНа переработку можно сдать и листовое стекло, которое осталось при замене окон. Однако его принимают только в компании «Стеклобой»: листовое стекло надо оставить у контейнера."
"\n\nПрежде чем сдать стекло, его надо ополоснуть от остатков содержимого и снять с тары крышку. Этикетку отрывать не нужно.Так-же можно сдавать целую хрусталь в наши Стеклозаводы!"
"\n\nПри этом вместе со стеклом нельзя сдавать на переработку:"
"\n\nкерамическую и стеклянную посуду (бокалы, стаканы, кружки, тарелки);\nочки или линзы;\nавтомобильное стекло;\nкрышки от сковородок и кастрюль;\nлампочки;\nзеркала;"
"\nхрусталь.", reply_markup=markup)

    elif message.text == "Вернуться в главное меню":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("👋 Поздороваться")
        button2 = types.KeyboardButton("❓ Задать вопрос")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="Вы вернулись в главное меню", reply_markup=markup)
    else:
        bot.send_message(message.chat.id, text="На такую комманду я не запрограммирован..")

bot.polling(none_stop=True)


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pydataset import data

'''
iris = sns.load_dataset('iris')

# 1. to 6.9 length range
print(iris.describe())

#saves plot locally, use open command to view
#petal divides well
sns.relplot(x='petal_length', y='petal_width', hue='species',
	data=iris).savefig('petal.png')
#sepal can't divide versicolor and virginica
sns.relplot(x='sepal_length', y='sepal_width', hue='species',
	data=iris).savefig('sepal.png')

Using the lesson as an example, use seaborn's load_dataset function to load the anscombe data set. Use pandas to group the data by the dataset column, and calculate summary statistics for each dataset. What do you notice?
Plot the x and y values from the anscombe data. Each dataset should be in a separate column. ?? plots have columns ??
Load the InsectSprays dataset and read it's documentation. Create a boxplot that shows the effectiveness of the different insect sprays.
Load the swiss dataset and read it's documentation. Create visualizations to answer the following questions:
Create an attribute named is_catholic that holds a boolean value of whether or not the province is Catholic. (Choose a cutoff point for what constitutes catholic)
Does whether or not a province is Catholic influence fertility?
What measure correlates most strongly with fertility?
Using the chipotle dataset from the previous exercise, create a bar chart that shows the 4 most popular items and the revenue produced by each.
Load the sleepstudy data and read it's documentation. Use seaborn to create a line chart of all the individual subject's reaction times and a more prominant line showing the average change in reaction time.
'''

ansc = sns.load_dataset('anscombe')
#same means & variances for x and y, diffent ranges
print(ansc.groupby('dataset').agg(['mean','var','max','median','min']).T)
sns.relplot(x='x', y='y', hue='dataset', kind='line',
	data=ansc).savefig('anscombe.png')

bug = data('InsectSprays') #, show_doc=True)
print(bug.head())
plt.title("Bug Lethality")
sns.boxplot(data=bug, x='spray', y='count').figure.savefig('spray.png')
plt.clf() #clear figure

swiss = data('swiss')
print(swiss.head())
plt.title("Where are all the Catholics?")
sns.histplot(swiss.Catholic).figure.savefig("catholics.png")
swiss["is_catholic"] = swiss.Catholic > 50
plt.title("Catholics Don't Use Condoms")
sns.boxplot(data=swiss, x="is_catholic", y="Fertility").figure.savefig('catholicbabies.png')
sns.pairplot(swiss, hue="is_catholic").savefig("fertility.png")
print(swiss.corr().Fertility)

plt.clf()
plt.figure(figsize=(16,9))
sleep = data('sleepstudy')
sleep['Subject'] = 'Subject_' + sleep.Subject.astype(str)
sns.lineplot(data=sleep, x='Days', y='Reaction', hue='Subject')
sns.lineplot(data=sleep, x='Days', y='Reaction',
	color='black', estimator='mean').figure.savefig('sleep.png')


import logging
import shutil
import sys
from pathlib import Path

from invoke import task

logging.getLogger().level = logging.DEBUG

@task
def cleanup_build_artifacts(c):
    for path in [
        *Path('.').glob('build'),
        *Path('.').glob('dist'),
        *Path('src').glob('*.egg-info'),
    ]:
        _rm_rf(path)

def _rm_rf(path):
    logging.info('removing %s', path)
    try:
        shutil.rmtree(path)
    except Exception:
        logging.exception('unexpected error')
        sys.exit(1)


import sys
import pandas as pd

import db as db
from queries import (
    CREATE_AGENT_OUTPOSTS_TABLE,
    DROP_AGENT_OUTPOSTS_TABLE,
    INSERT_AGENT_OUTPOST,
)

conn = None

def main():
    df = pd.read_excel("data/Postos de Guarda Vidas.xls", 0)
    for name, latitude, longitude in zip(
        df["IDENTIFICAÇÃO"], df["LATITUDE"], df["LONGITUDE"]
    ):
        insert_outpost_into_db(name, latitude, longitude)

def insert_outpost_into_db(name, latitude, longitude):
    cursor = conn.cursor()
    cursor.execute(
        INSERT_AGENT_OUTPOST,
        (name, latitude, longitude, f"POINT({longitude} {latitude})"),
    )
    conn.commit()

def create_table_if_not_exists():
    cur = conn.cursor()
    cur.execute(CREATE_AGENT_OUTPOSTS_TABLE)
    conn.commit()
    conn.close()

def drop_table():
    cur = conn.cursor()
    cur.execute(DROP_AGENT_OUTPOSTS_TABLE)
    conn.commit()
    conn.close()

if __name__ == "__main__":
    conn = db.connect()

    migration = None
    if len(sys.argv) > 1:
        migration = sys.argv[1]

    if migration == "up":
        create_table_if_not_exists()
    elif migration == "down":
        drop_table()
    elif migration is None:
        main()


#Ejercicio 1
#Escriba un programa que permita que el usuario ingrese el
#nombre de un archivo el programa lee el contenido y lo imprime por
#pantalla.

loop = True
while(loop):
    try:
        print("Ingrese la ruta del archivo que desee leer por pantalla: ")
        archivo = open(str(input()))
        contenido = archivo.read()
        print(contenido)
        archivo.close()
        loop = False
    except ValueError:
        print("Se ingreso una ruta incorrecta, vuelva a intentarlo!")
    except FileNotFoundError:
        print("La ruta del archivo ingresada no coincide con ningun archivo existente, vuelva a intentarlo!")

Unidad 5/5.1 Archivos/Actividades de afianzamiento/Ejercicio1.py


#!/usr/bin/env python
# coding: utf-8

# **Inlämningsuppgift - Del 1 (Johan)**
#
# Data: E-commerce Transaction Data (fil: Sales Transaction v.4a)

# In[1]:

import pandas as pd
import matplotlib.pyplot as plt

# In[2]:

ecom_df = pd.read_csv('Sales_Transaction.csv')
#ecom_df.head(-5)

# In[3]:

ecom_df = ecom_df.sample(frac = 0.10, random_state=0)

# In[4]:

ecom_df.info()

# In[5]:

ecom_df.describe()

# In[6]:

ecom_df.corr()

# In[7]:

ecom_df['Date'].sort_values()

# In[8]:

#Vi tar fram en boxplot för att få en överblick över outliers
data = ecom_df['Quantity']

fig1, ax1 = plt.subplots()
ax1.set_title('Boxplot innan data cleaning')
ax1.boxplot(data)

# In[9]:

mask1 = ecom_df['Quantity'] >= 1

# In[10]:

ecom_df = ecom_df[mask1]

ecom_df

# In[11]:

#filtrera ut värden i den översta kvantilen och skapar en ny DataFrame utan dessa "outliers"
q_limit  = ecom_df["Quantity"].quantile(0.99)

ecom_df = ecom_df.loc[(ecom_df["Quantity"] < q_limit),]
print("q_limit = ", q_limit)

# In[12]:

data = ecom_df['Quantity']

fig1, ax1 = plt.subplots()
ax1.set_title('Boxplot efter data cleaning')
ax1.boxplot(data)

# In[13]:

#ecom_df.loc['Real_date'] = pd.to_datetime(ecom_df["Date"]) #LOOK INTO THIS !!!
ecom_df['Real_date'] = pd.to_datetime(ecom_df["Date"])

# In[14]:

#skapa day
#skapa week
ecom_df['Day'] = pd.DatetimeIndex(ecom_df['Date']).day
ecom_df['Week'] = pd.DatetimeIndex(ecom_df['Date']).week
ecom_df['Month'] = pd.DatetimeIndex(ecom_df['Date']).month

#ecom_df['Day'] = ecom_df['Real_date'].dt.day
#ecom_df['Week'] = ecom_df['Real_date'].dt.week
#ecom_df['Month'] = ecom_df['Real_date'].dt.month

# In[15]:

ecom_df['Week_cat'] = pd.Categorical(ecom_df['Week'], ordered=True)
ecom_df['Month_cat'] = pd.Categorical(ecom_df['Month'], ordered=True)

# In[16]:

#Tar bort onödiga kolumner

ecom_df.drop(["TransactionNo", "Date", "ProductNo", "CustomerNo"], axis=1, inplace=True)

# In[17]:

ecom_df

# **Måste "one-hot-encoda" kategorivariabler för att kunna använda kategorivariabler**

# In[18]:

ecom_df = pd.get_dummies(ecom_df, columns=["ProductName", "Country"])

# In[19]:

ecom_df.info()

# In[20]:

clean_df = ecom_df

# In[21]:

#Nu har vi en korrekt DataFrame som heter clean_df som innehåller endast transaktioner med positiv Quantity, korrekta datumkolumner och one-hot-encodade kolumner.
clean_df

# In[22]:

data = clean_df['Quantity']

fig1, ax1 = plt.subplots()
ax1.set_title('Boxplot efter data cleaning')
ax1.boxplot(data)

# Nu är vi klara med vår dataformatering och datatvätt. Nu är det dags för linjär regression!

# In[23]:

#X = clean_df.loc[:, ~clean_df.columns.isin(['Quantity', 'Real_date'])]
X = clean_df.loc[:,['Price','Day','Week_cat','Month_cat']]
y = clean_df.Quantity

# In[24]:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# **OBS, kör de nedanstående cellerna en gång innan RFECV cellerna körs**

# In[33]:

#RFECV för LINJÄR REGRESSION (LinearRegression)
from sklearn.feature_selection import RFECV

selector = RFECV(LinearRegression(), step=1, cv=5, scoring='r2', verbose=3)

selector.fit(X_train, y_train)

selector.get_feature_names_out()
selector.cv_results_

# In[34]:

#RFECV för DECISION TREE (DecisionTreeRegressor)
from sklearn.feature_selection import RFECV

selector = RFECV(DecisionTreeRegressor(), step=1, cv=5, scoring='r2', verbose=3)

selector.fit(X_train, y_train)

print(selector.get_feature_names_out())
print(selector.cv_results_)

# In[27]:

from sklearn.linear_model import LinearRegression
linreg_model = LinearRegression()

linreg_model = linreg_model.fit(X = X_train, y = y_train)
print('Coefficients: \n', linreg_model.coef_)

# In[28]:

#kolla intercept
linreg_model.intercept_

# In[29]:

#genomsnitt för kvantitet
clean_df['Quantity'].mean()

# In[30]:

y_test_pred = linreg_model.predict(X_test)

# In[31]:

#Hur väl fungerar vår modell?

from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt

#mean squared error
mse = mean_squared_error(y_test, y_test_pred)
print('Mean squared error:', round(mse, 2))

#root mean squared error
rmse = sqrt(mse)
print('Root mean squared error:', round(rmse, 2))

#coefficient of determination: 1 is perfect regression
r2 = r2_score(y_test, y_test_pred)
print('Coefficient of determination:', round(r2, 2))

# **Testar att använda ett beslutsträd istället**

# In[36]:

from sklearn.tree import DecisionTreeRegressor
tree_reg_model = DecisionTreeRegressor()

#För att bara testa 'Price' sätt in detta efter X_train och X_test: ['Price'].values.reshape(-1, 1)

tree_reg_model = tree_reg_model.fit(X=X_train['Price'].values.reshape(-1, 1), y=y_train)
print('Modellens djup:', tree_reg_model.get_depth())

y_test_pred_tree = tree_reg_model.predict(X_test['Price'].values.reshape(-1, 1))

# Dags att utvärdera vår modell!!!

from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt

#mean squared error
mse = mean_squared_error(y_test, y_test_pred_tree)
print('Mean squared error:', round(mse, 2))

#root mean squared error
rmse = sqrt(mse)
print('Root mean squared error:', round(rmse, 2))

#coefficient of determination: 1 is perfect regression
r2_tree = r2_score(y_test, y_test_pred_tree)
print('Coefficient of determination:', round(r2_tree, 2))

# In[ ]:


'''
for 选择 in 选择列表：
    # 做选择
    将该选择从选择列表移除
    路径.add(选择)
    backtrack(路径，选择列表)
    # 撤销选择
    路径.remove(选择)
    将该选择在加入选择列表
'''
import copy
res = []
def solveNQueens(n:int):
    board = [[0 for _ in range(n)] for _ in range(n)]
    backtrack(board,0)
    return res

def backtrack(board,row:int):
    if row == len(board):
        res.append(copy.deepcopy(board))
        return
    for col in range(len(board[row])):
        if not isVaild(board,row,col):
            continue
        board[row][col] = 1
        backtrack(board,row+1)
        board[row][col] = 0

def isVaild(board,row,col):
    i,j = 0,0
    # 检查上面
    while i < row:
        if board[i][col] == 1:
            return False
        i+=1

    # 检查下面

    # 检查左上
    i,j = row - 1,col-1
    while i >= 0 and j >= 0:
        if board[i][j] == 1:
            return False
        i -= 1
        j -= 1

    # 检查右上
    i ,j = row -1 , col+1
    while i >= 0 and j < len(board):
        if board[i][j] == 1:
            return False
        i -= 1
        j += 1

    return True

solveNQueens(8)
for index,arr in enumerate(res):
    print(f"第{index+1}种解法:")
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if arr[i][j] == 0:
                print("*",end=" ")
            elif arr[i][j] == 1:
                print("♛",end=" ")
        print()
    print()

自己实现代码/[开篇词]回溯算法解题套路-N皇后问题.py

[开篇词]回溯算法解题套路-N皇后问题.py


src = '/home/jelen/jelen_dta/projekty/qgis_islh/sample_dta/kbo.geojson'

lyr = QgsVectorLayer(src, 'pokus','ogr')

svgStyle = {}

svgStyle['fill'] = '#0000ff'
svgStyle['name'] = 'landmark/tourism-museum.svg'
svgStyle['outline'] = '#000000'
svgStyle['outline-width'] = '6.8'
svgStyle['size'] = '6'

symLyr1 = QgsSvgMarkerSymbolLayerV2.create(svgStyle)
#symLyr1 = QgsSVGFillSymbolLayer.create(props)

lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr1)

QgsMapLayerRegistry.instance().addMapLayer(lyr)


import logging
from io import BytesIO
import zipfile
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

LOG = logging.getLogger(__name__)

class ElectionsClient(object):
    """
    Client for retrieving elections data from systems using Clarity.
    """

    # TODO make electionid/statepostal constructor args and/or add caching of retrieved version and so on

    def __init__(
            self,
            base_url,
            timeout=5,
            session=None,
            retry_params={},
            # faking a user-agent because Clarity is giving us forbidden errors otherwise
            user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
            **kwargs):

        if session is None:
            session = requests.Session()
            session.headers.update({'Accept-Encoding': 'gzip'})
            session.headers.update({"User-Agent": user_agent})

        retry_params = {"total": 3, "status_forcelist": (502, 504, 429, 499), "backoff_factor": 0.2, **retry_params}
        adapter = HTTPAdapter(max_retries=Retry(**retry_params))
        session.mount("http://", adapter)
        session.mount("https://", adapter)

        self.base_url = base_url
        self.session = session
        self.timeout = timeout

    def make_request(self, route, **kwargs):
        """
        Makes a request relative to ``self.base_url``.

        :param route: the route to request (relative to the base ``api_url``)
        :type route: str
        :param kwargs: keyword args passed to underlying requests call
        :return: the response xml
        :rtype: str

        """
        url = f'{self.base_url}/{route}'
        LOG.debug("Making request at %s", url)

        response = self.session.get(url, params=kwargs, timeout=self.timeout)
        response.raise_for_status()
        return response

    def _get_url_subdirectories(self, electionid, statepostal, county_name):
        url_subdirectory = f"{statepostal}/"
        if county_name:
            url_subdirectory += f"{county_name}/{electionid}"
        else:
            url_subdirectory += str(electionid)
        return url_subdirectory

    def get_current_version(self, electionid, statepostal, county_name, **kwargs):
        url_subdirectory = self._get_url_subdirectories(electionid, statepostal, county_name)
        current_ver_url = f"{url_subdirectory}/current_ver.txt"
        current_ver_response = self.make_request(current_ver_url)
        return current_ver_response.text

    def get_summary(self, electionid, statepostal, county_name, **kwargs):
        current_ver = self.get_current_version(electionid, statepostal, county_name)
        url_subdirectory = self._get_url_subdirectories(electionid, statepostal, county_name)
        summary_url = f"{url_subdirectory}/{current_ver}/json/en/summary.json"
        resp = self.make_request(summary_url, **kwargs)
        return resp.json()

    def get_detail_xml(self, route):
        resp = self.make_request(f"{route}/reports/detailxml.zip")
        filebytes = BytesIO(resp.content)
        _zipfile = zipfile.ZipFile(filebytes)
        for name in _zipfile.namelist():
            with _zipfile.open(name) as myfile:
                return myfile.read()

    def get_settings(self, electionid, statepostal, county_name, **kwargs):
        """
        :param electionid: the election ID
        :type electionid: str
        :keyword statepostal: the state(s) to query
        :type statepostal: str or tuple(str)

        :param kwargs: other keyword args passed to underlying requests call
        :return: the response json
        :rtype: str

        """
        current_ver = self.get_current_version(electionid, statepostal, county_name)
        url_subdirectory = self._get_url_subdirectories(electionid, statepostal, county_name)
        settings_url = f"{url_subdirectory}/{current_ver}/json/en/electionsettings.json"
        resp = self.make_request(settings_url, **kwargs)
        return resp.json()

    # https://results.enr.clarityelections.com//GA//105369/270988/reports/detailxml.zip
    def get_county_results(self, statepostal, county_name, county_id, county_version, **kwargs):
        return self.get_detail_xml(f"{statepostal}/{county_name}/{county_id}/{county_version}")

    def get_state_results(self, electionid, statepostal, county_name, version, **kwargs):
        url_subdirectory = self._get_url_subdirectories(electionid, statepostal, county_name)
        results_url = f"{url_subdirectory}/{version}"
        return self.get_detail_xml(results_url)

    def get_results(self, electionid, statepostal, county_name, level, **kwargs):
        if level == "precinct" and not county_name:
            results = []
            # Bad bad bad; do not use in production! This will request _many_ files
            election_settings = self.get_settings(electionid, statepostal, county_name)
            raw_counties = election_settings.get("settings", {}).get("electiondetails", {}).get("participatingcounties")
            success = 0
            failure = 0
            for raw_county in raw_counties:
                name, clarity_id, _, _ = raw_county.split("|")[0:4]
                try:
                    current_ver = self.get_current_version(clarity_id, statepostal, name)
                    results.append(self.get_county_results(statepostal, name, clarity_id, current_ver, **kwargs))
                    success += 1
                except requests.exceptions.HTTPError:
                    try:
                        name, clarity_id, version, _ = raw_county.split("|")[0:4]
                        results.append(self.get_county_results(statepostal, name, clarity_id, version, **kwargs))
                        success += 1
                    except requests.exceptions.HTTPError:
                        failure += 1
                        LOG.info(f"Failed to get results for {name}")
                except:
                    failure += 1
                    LOG.info(f"Failed to get results for {name}")
            LOG.info("Number of successes: ", success)
            LOG.info("Number of failures: ", failure)
            return results
        elif (level == "state" or level == "county") and not county_name:
            current_ver = self.get_current_version(electionid, statepostal, county_name)
            return self.get_state_results(electionid, statepostal, county_name, current_ver, **kwargs)
        elif level == "precinct" and county_name:
            current_ver = self.get_current_version(electionid, statepostal, county_name)
            return self.get_state_results(electionid, statepostal, county_name, current_ver, **kwargs)
        return None


# -*- coding: utf-8 -*-
# !@time: 2020/12/8 下午9:30
# !@author: superMC @email: 18758266469@163.com
# !@fileName: se.py

from abc import ABC

import torch
from torch import nn

class CSEModule(nn.Module, ABC):
    def __init__(self, in_planes, hidden_ratio=16):
        hidden_state = in_planes // hidden_ratio
        super().__init__()
        self.global_average_pool = nn.AdaptiveAvgPool2d(1)
        self.in_planes = in_planes
        self.fc = nn.Sequential(
            nn.Linear(in_planes, hidden_state, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(hidden_state, in_planes, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        batch_size, channel_num, height, width = x.size()
        y = self.global_average_pool(x).view(batch_size, channel_num)
        y = self.fc(y).view(batch_size, channel_num, 1, 1)
        return y

if __name__ == '__main__':
    cse = CSEModule(128)
    x = torch.ones((1, 128, 10, 10))
    ret = cse(x)
    print(ret.size())


from data_structures.trees import Tree, Node, ChanceNode

def build_kuhn_tree(num_players, rank):
    """
    Build a tree for the game of Kuhn with a given number of players and a given number of ranks in the deck (i.e. how
    many cards).
    """

    root = ChanceNode(0)

    tree = Tree(num_players, 0, root)

    hands = build_all_possible_hands(num_players, list(range(rank)))
    hand_probability = 1 / len(hands)
    for hand in hands:
        n = tree.addNode(0, parent = root, probability = hand_probability, actionName = str(hand))
        build_kuhn_hand_tree(hand, ['n'] * num_players, 0, n, tree)

    for i in range(len(hands)):
        for j in range(i+1, len(hands)):
            players_to_merge = []
            for p in range(num_players):
                if(hands[i][p] == hands[j][p]):
                    players_to_merge.append(p)
            create_information_sets(root.children[i], root.children[j], players_to_merge)

    return tree

def create_information_sets(node1, node2, players_to_merge):
    """
    Takes two identically shaped trees (rooted at node1 and node2) and put all the nodes
    belonging to players in players_to_merge in pairwise information sets.
    """

    if(node1.isLeaf()):
        return

    if(node1.player in players_to_merge):
        iset_id = min(node1.information_set, node2.information_set)
        node1.information_set = iset_id
        node2.information_set = iset_id

    for i in range(len(node1.children)):
        create_information_sets(node1.children[i], node2.children[i], players_to_merge)

def build_kuhn_hand_tree(hand, previous_moves, current_player, current_node, tree):
    """
    Recursively build the subtree for the Kuhn game where the hand is fixed.
    """

    actionPrefix = 'p' + str(current_player)
    num_players = len(hand)

    next_player = (current_player + 1) % num_players
    while(previous_moves[next_player] in ['b', 'f']):
        next_player = (next_player + 1) % num_players

    # There was a bet, so I can only call or fold
    if('b' in previous_moves):
        # If the current and the next player are the same, we are at the last decision node of the game
        if(current_player == next_player):
            previous_moves[current_player] = 'b'
            tree.addLeaf(current_node, kuhn_utility(hand, previous_moves), actionName = actionPrefix + 'b')

            previous_moves[current_player] = 'f'
            tree.addLeaf(current_node, kuhn_utility(hand, previous_moves), actionName = actionPrefix + 'f')

            return

        callNode = tree.addNode(next_player, parent = current_node, actionName = actionPrefix + 'b')
        previous_moves[current_player] = 'b'
        build_kuhn_hand_tree(hand, previous_moves.copy(), next_player, callNode, tree)

        foldNode = tree.addNode(next_player, parent = current_node, actionName = actionPrefix + 'f')
        previous_moves[current_player] = 'f'
        build_kuhn_hand_tree(hand, previous_moves.copy(), next_player, foldNode, tree)

    else: # No bet yet, so I can check or bet
        previous_moves[current_player] = 'c'
        if(len(list(filter(lambda el: el == 'c', previous_moves))) == num_players):
            tree.addLeaf(current_node, kuhn_utility(hand, previous_moves), actionName = actionPrefix + 'c')
        else:
            checkNode = tree.addNode(next_player, parent = current_node, actionName = actionPrefix + 'c')
            build_kuhn_hand_tree(hand, previous_moves.copy(), next_player, checkNode, tree)

        betNode = tree.addNode(next_player, parent = current_node, actionName = actionPrefix + 'b')
        previous_moves[current_player] = 'b'
        build_kuhn_hand_tree(hand, previous_moves.copy(), next_player, betNode, tree)

def kuhn_utility(hand, moves):
    """
    Get the utility of a Kuhn game given the hand and how the players have played.
    """

    num_players = len(hand)

    pot = num_players + len(list(filter(lambda el: el == 'b', moves)))
    showdown_participants = [p for p in range(num_players) if moves[p] != 'f']
    winner = max(showdown_participants, key = lambda el: hand[el])

    utility = [-1] * num_players
    for p in range(num_players):
        if(p == winner):
            utility[p] += pot
        if(moves[p] == 'b'):
            utility[p] -= 1

    return utility

def build_all_possible_hands(num_players, ranks):
    """
    Build all the possible hands for the game of Kuhn with a given number of players and a given set of cards.
    """

    if(num_players <= 0):
        return [[]]

    smaller_hands = build_all_possible_hands(num_players-1, ranks)
    hands = []

    for hand in smaller_hands:
        remaining_ranks = list(filter(lambda el: el not in hand, ranks))
        for r in remaining_ranks:
            hands.append(hand + [r])

    return hands


class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert(root, temp_node):
    if root is None:
        root = temp_node
    elif root.data > temp_node.data:
        if root.left is None:
            root.left = temp_node
        else:
            insert(root.left, temp_node)
    else:
        if root.right is None:
            root.right = temp_node
        else:
            insert(root.right, temp_node)

def inorder(root):
    if root:
        inorder(root.left)
        print(root.data, end=" ")
        inorder(root.right)

def preorder(root):
    if root:
        print(root.data, end=" ")
        preorder(root.left)
        preorder(root.right)

def postorder(root):
    if root:
        postorder(root.left)
        postorder(root.right)
        print(root.data, end=" ")

list_arr = []
n = int(input("enter the no of nodes"))
print("enter the key values for nodes")
for i in range(n):
    x = int(input())
    if(i == 0):
        root = node(x)
    else:
        insert(root, node(x))
print("in_order traversal :", end=" ")
inorder(root)
print()
print("pre_order traversal :", end=" ")
preorder(root)
print()
print("post_order traversal :", end=" ")
postorder(root)


# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 10:21:02 2021

@author: Grant Isaacs
"""

#IMPORT LIBRARIES------------------------------------------------------------->
import pandas as pd

#LOAD DATA-------------------------------------------------------------------->
"""The data can be located at:
    http://tiny.cc/studcsv
"""
students = pd.read_csv("students.csv")
teachers = pd.read_csv("teachers.csv")
grades_01 = pd.read_csv("grades1.csv")
grades_02 = pd.read_csv("grades2.csv")
contacts = pd.read_csv("contact.csv")

#MERGING DATAFRAME ROWS------------------------------------------------------->
grades_01["Semester"] = 1
grades_02["Semester"] = 2

"""To merge the rows of the two dataframes we can use either concat or append."""
grades_03 = pd.concat([grades_01, grades_02])
grades_03 = grades_03.reset_index(drop=True)

grades_04 = grades_01.append(grades_02)
grades_04 = grades_04.reset_index(drop=True)

#MERGING DATAFRAME COLUMNS---------------------------------------------------->
student_grades = pd.merge(students, grades_04, left_on="id", right_on="student_id")
print(students.shape, grades_04.shape, student_grades.shape)

students_02 = students.rename({"id": "student_id"}, axis=1)
students_full = students_02.merge(contacts, on='student_id')
student_grades = pd.merge(students_full, grades_04, on='student_id')
student_grades = pd.merge(student_grades, teachers, on='course')

#JOINING---------------------------------------------------------------------->
"""Joining is done on the index of the dataframes."""
students_03 = students.copy()
students_03 = students_03.set_index("id")
contacts_01 = contacts.copy()
contacts_01 = contacts_01.set_index("student_id")
students_03 = students_03.join(contacts_01)


import faiss
import numpy as np
from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import torchvision.transforms as transforms
import torch
import matplotlib.pyplot as plt
from datasets import load_dataset
from IPython.display import display
from IPython.display import Image as IPyImage

# 加载数据集
dataset = load_dataset("rajuptvs/ecommerce_products_clip")
training_split = dataset["train"]

# 定义显示图像的函数

def display_images(images):
    fig, axes = plt.subplots(2, 5, figsize=(15, 6))
    axes = axes.ravel()

    for idx, img in enumerate(images):
        axes[idx].imshow(img)
        axes[idx].axis('off')

    plt.subplots_adjust(wspace=0.2, hspace=0.2)
    plt.show()

# 校验数据集， 获取数据集中的前10张图像并显示
images = [example["image"] for example in training_split.select(range(10))]
# display_images(images)

# 初始化 CLIP 模型
device = "cuda" if torch.cuda.is_available() else "cpu"
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

# 获取图像的特征向量

def get_image_features(image):
    with torch.no_grad():
        inputs = processor(images=[image], return_tensors="pt", padding=True)
        inputs.to(device)
        features = model.get_image_features(**inputs)
    return features.cpu().numpy()

# 为数据集中的每个示例添加图像特征向量

def add_image_features(example):
    example["features"] = get_image_features(example["image"])
    return example

# 对数据集应用函数以添加图像特征向量
training_split = training_split.map(add_image_features)

# 构建特征矩阵并创建 Faiss 索引
features = [example["features"] for example in training_split]
features_matrix = np.vstack(features)
dimension = features_matrix.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(features_matrix.astype('float32'))

# 获取文本的特征向量

def get_text_features(text):
    with torch.no_grad():
        inputs = processor(text=[text], return_tensors="pt", padding=True)
        inputs.to(device)
        features = model.get_text_features(**inputs)
    return features.cpu().numpy()

# 显示搜索结果
def display_search_results(results):
    fig, axes = plt.subplots(1, len(results), figsize=(15, 5))
    axes = axes.ravel()

    for idx, result in enumerate(results):
        axes[idx].imshow(result["image"])
        axes[idx].set_title(f"Distance: {result['distance']:.2f}")
        axes[idx].axis('off')

    plt.subplots_adjust(wspace=0.2, hspace=0.2)
    plt.show()

# 图片搜索
def search_image(image_path, top_k=5):
    # Load the image from the file
    image = Image.open(image_path).convert("RGB")

    # Get the image feature vector for the input image
    image_features = get_image_features(image)

    # Perform a search using the FAISS index
    distances, indices = index.search(image_features.astype("float32"), top_k)

    # Get the corresponding images and distances
    results = [
        {"image": training_split[i.item()]["image"],
         "distance": distances[0][j]}
        for j, i in enumerate(indices[0])
    ]

    return results

# 文字搜索

def search_text(query_text, top_k=5):
    # 获取输入查询文本的特征向量
    text_features = get_text_features(query_text)

    # 使用 Faiss 索引进行搜索
    distances, indices = index.search(text_features.astype("float32"), top_k)

    # 获取相应的图像和距离
    results = [
        {"image": training_split[i.item()]["image"],
         "distance": distances[0][j]}
        for j, i in enumerate(indices[0])
    ]

    return results

image_path = "./data/shirt.png"
query_text = "A red dress"

# 搜索示例
# results = search_image(image_path)
# display(IPyImage(filename=image_path, width=300, height=200))
# display_search_results(results)

results = search_text(query_text)
display_search_results(results)


from PyQt5 import QtGui
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog
from PyQt5.uic import loadUi
from SearchEngine import textSearch, imageSearch, Freeman, DCT, os, Image, np
import glob, shutil

from tools import is_grayScale

class widget(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        loadUi("assets/Search Engine.ui",self)
        self.setWindowTitle("Search Engine")
        self.startSearch.clicked.connect(self.deleteFiles)
        self.startSearch.clicked.connect(self.search)
        self.imgUpload.clicked.connect(self.deleteFiles)
        self.imgUpload.clicked.connect(self.UploadImage)

        self.path = os.getcwd()+'\\Download'
        self.searchPath = os.getcwd()+'\\Images'
        self.DBPath = os.getcwd()+'\\assets\\SearchEngine.db'
        self.pixel = None
        self.DCT = None
        self.Chains = None

    def UploadImage(self):
        try:
            imageFile = QFileDialog.getOpenFileName(None, "Open image", self.searchPath, "Image Files (*.png *.jpg *.bmp *.jpeg *.png *.jfif)")
            self.imagename = str(imageFile[0])
            self.pixel = np.array(Image.open(self.imagename).convert('RGB'))
            GrayScale = is_grayScale(self.pixel)
            if GrayScale:
                print('Method: Freeman')
                self.Chains = Freeman(self.pixel)
            else:
                print('Method: DCT')
                self.DCT = DCT(self.pixel)

            imageSearch(self.searchPath, self.path, self.DBPath, self.DCT, self.Chains)
            self.showImage()
            self.DCT = None
            self.Chains = None

        except: pass

    def showImage(self):
        os.chdir(self.path)
        row, column = 0, -1
        for file in glob.glob("*"):
            column += 1
            if column >= 4:
                row += 1
                column = 0
            pixmap = QtGui.QPixmap(self.path+"/"+file)
            pixmap = pixmap.scaled(270, 270)
            label = QLabel()
            label.setPixmap(pixmap)
            self.gridL.addWidget(label, row, column)

    def search(self):
        textSearch(self.path, self.DBPath, self.searchBar.text())
        self.showImage()

    def deleteFiles(self):
        for filename in os.listdir(self.path):
            file_path = os.path.join(self.path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print('Failed to delete %s. Reason: %s' % (file_path, e))

        for i in reversed(range(self.gridL.count())):
            self.gridL.itemAt(i).widget().setParent(None)

app = QApplication([])
window = widget()
window.show()
app.exec_()


# -*- coding: utf-8 -*-
"""
Created on Mon Apr  1 21:45:13 2019

@author: hsieh
"""
a=0
for j in range(5):
    print('-'*j,end='')
    a=j
    for i in range(5):
        a +=1
        print(a,end='')
    print('-'*(5-1-j))


#for is more like an iterator method than a classical for
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

for x in "banana":
  print(x)

#break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

for x in fruits:
  if x == "banana":
    break
  print(x)

#continue
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

#range() function
for x in range(6):#values 0 to 5
  print(x)

for x in range(2, 6):#values 2 to 5
  print(x)

for x in range(2, 30, 3):#values 2 to 29 with increments of 3
  print(x)

#else
for x in range(6):
  print(x)
else: #executes after loop is finished, but not if a break is applied
  print("Finally finished!")

#nested
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
  for y in fruits:
    print(x, y)

#pass statement
for x in [0, 1, 2]:
  pass


import sys
'''
taller + shorter == N-1 임을 이용해서 풀었다.
'''
read =sys.stdin.readline

def tDfs(cur) :
    global T
    visited[cur] = 1
    for nx in taller[cur] :
        if visited[nx] != 0 : continue
        T += 1
        tDfs(nx)

def sDfs(cur) :
    global S
    visited[cur] = 1
    for nx in shorter[cur] :
        if visited[nx] != 0 : continue
        S += 1
        sDfs(nx)

N,M = map(int,read().split())
taller = [[] for _ in range(N+1)]
shorter = [[] for _ in range(N+1)]
for _ in range(M) :
    x,y = map(int,read().split())
    taller[x].append(y)
    shorter[y].append(x)

ans = 0
for i in range(1,N+1) :
    T = S = 0

    visited = [0 for _ in range(N+1)]
    tDfs(i)

    visited = [0 for _ in range(N+1)]
    sDfs(i)

    if T + S == N-1 :
        ans += 1

print(ans)


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 18:32:15 2019

@author: aleah cute
"""

import string

def getAvailableLetters(lettersGuessed) :
    alphabet = string.ascii_lowercase
    for char in lettersGuessed :
        if char in alphabet :
            alphabet = alphabet.translate({ord(char): None})
    return alphabet


from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

import torch
import torch.optim as optim
from torchvision import transforms, models

# get 'features' portion of VGG19
vgg = models.vgg19(pretrained=True).features

# freeze all VGG parameters since we're only optimizing the target image
for param in vgg.parameters():
    param.requires_grad_(False)

# move the model to GPU, if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
vgg.to(device)

def load_image(img_path, max_size=400, shape=None):
    '''
    Load in and transform an image, making sure image is <= 400 pixels in the
    x-y dims
    '''
    image = Image.open(img_path).convert('RGB')
    if max(image.size) > max_size:
        size = max_size
    else:
        size = max(image.size)

    if shape is not None:
        size = shape

    in_transform = transforms.Compose([transforms.Resize(size),
                                       transforms.ToTensor(),
                                       transforms.Normalize((0.485, 0.456, 0.406),
                                                            (0.229, 0.224, 0.225))])
    image = in_transform(image)[:3, :, :].unsqueeze(0)
    return image

# load in content and image design
content_image = load_image('images/content.jpg').to(device)
style_image = load_image('images/style.jpeg', shape=content_image.shape[-2:]).to(device)

def im_convert(tensor):
    '''
    Helper function for un-normalizing an image
    and converting it from Tensor to numpy for display that image
    '''
    image = tensor.to('cpu').clone().detach()
    image = image.numpy().squeeze()
    image = image.transpose(1, 2, 0)
    image = image * np.array((0.229, 0.224, 0.225))\
           + np.array((0.485, 0.456, 0.406))
    image = image.clip(0, 1)
    return image

#display the images
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
ax1.imshow(im_convert(content_image))
ax2.imshow(im_convert(style_image))
print('Draw successfully')
# plt.show()

def get_features(image, model, layers=None):
    '''Run an image through a model and get the features for a set of layer.
    Default layers are for VGG net matching Gatys
    '''
    if layers is None:
        layers = {
            '0': 'conv1_1',
            '5': 'conv2_1',
            '10': 'conv3_1',
            '19': 'conv4_1',
            '21': 'conv4_2',
            '28': 'conv5_1'
        }
    features = {}
    tmp_image = image
    for name, layer in model._modules.items():
        tmp_image = layer(tmp_image)
        if name in layers:
            features[layers[name]] = tmp_image

    return features

def gram_matrix(tensor):
    '''
    Calculate gram matrix for a given tensor
    '''
    _, d, h, w = tensor.size()
    tensor = tensor.view(d, h*w)
    gram = torch.mm(tensor, tensor.t())

    return gram

content_features = get_features(content_image, vgg)
style_features = get_features(style_image, vgg)
style_grams = {layer: gram_matrix(style_features[layer])
              for layer in style_features}

# create a target by copying content image
target = content_image.clone().requires_grad_(True).to(device)

show_every = 100
optimizer = optim.Adam([target], lr=0.003)
steps = 2000

style_weights = {
    'conv1_1': 0.1,
    'conv2_1': 0.2,
    'conv3_1': 0.4,
    'conv4_1': 0.6,
    'conv4_2': 0.6,
    'conv5_1': 0.7
}

content_weight = 1
style_weight = 0.6

for i in range(1, steps + 1):
    print('Running Epoch', i)
    target_features = get_features(target, vgg)

    # content loss
    content_loss = torch.mean((target_features['conv4_2']
                               - content_features['conv4_2']) ** 2)

    # style loss
    style_loss = 0
    for layer in style_weights:
        target_feature = target_features[layer]
        target_gram = gram_matrix(target_feature)
        _, d, h, w = target_feature.shape
        style_gram = style_grams[layer]
        layer_style_loss = style_weights[layer] \
                           * torch.mean((target_gram - style_gram) ** 2)
        style_loss += layer_style_loss / (d * h * w)

    # total loss
    total_loss = content_weight * content_loss + style_weight * style_loss

    optimizer.zero_grad()
    total_loss.backward()
    optimizer.step()

    if i % show_every == 0:
        print('Total loss', total_loss.item())
        numpy_image = im_convert(target)
        plt.imshow(numpy_image)
        plt.savefig(f'image{i}.jpg')
        # plt.show()
        # im = Image.fromarray(numpy_image)
        # im.save(f'image{i}.jpg')


class Node:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None

    def print_tree(self):
        if self.left:
            self.left.print_tree()
        print(self.data)
        if self.right:
            self.right.print_tree()

def mirror(root):
    if root is None:
        return
    mirror(root.left)
    mirror(root.right)
    temp = root.left
    root.left = root.right
    root.right = temp

def main():
    root = Node(1)
    root.left = Node(3)
    root.right = Node(2)
    root.right.left = Node(5)
    root.right.right = Node(4)

    root.print_tree()
    mirror(root)
    print("--------------------------------")
    root.print_tree()

main()

Amazon_interview/Binary Tree/Convert a Binary Tree into its Mirror Tree.py


from decimal import Decimal

import pytest

from abusor.events.requirement_plugins import (
    ScoreIsAbove,
    ScoreIsBelow,
    SubjectContains,
)
from abusor.rules.plugins import RequirementPluginError

pytestmark = pytest.mark.django_db

@pytest.mark.parametrize(
    "value, required_value, expected",
    [
        ("0", "0", False),
        ("0", "5", False),
        ("5", "0", True),
        ("5", "5", False),
        ("10", "5", True),
    ],
)
def test_events_requirement_score_is_above(
    event_factory, value, required_value, expected
):
    event = event_factory(score=Decimal(value))
    req = ScoreIsAbove()
    outcome = req(event, Decimal(required_value))
    assert outcome == expected

def test_events_requirement_score_is_above_invalid_object():
    obj = object()
    req = ScoreIsAbove()
    with pytest.raises(RequirementPluginError) as excinfo:
        req(obj, Decimal("5"))
    assert "Object with type <class 'object'> has no attribute 'score'." in str(
        excinfo.value
    )

@pytest.mark.parametrize(
    "value, required_value, expected",
    [
        ("0", "0", False),
        ("0", "5", True),
        ("5", "0", False),
        ("5", "5", False),
        ("10", "5", False),
    ],
)
def test_events_requirement_score_is_below(
    event_factory, value, required_value, expected
):
    event = event_factory(score=Decimal(value))
    req = ScoreIsBelow()
    outcome = req(event, Decimal(required_value))
    assert outcome == expected

def test_events_requirement_score_is_below_invalid_object():
    obj = object()
    req = ScoreIsBelow()
    with pytest.raises(RequirementPluginError) as excinfo:
        req(obj, Decimal("5"))
    assert "Object with type <class 'object'> has no attribute 'score'." in str(
        excinfo.value
    )

@pytest.mark.parametrize(
    "value, required_value, expected",
    [("foo", "foo", True), ("bar", "foo", False), ("FOO", "foo", True)],
)
def test_events_requirement_subject_contains(
    event_factory, value, required_value, expected
):
    event = event_factory(subject=value)
    req = SubjectContains()
    outcome = req(event, required_value)
    assert outcome == expected

def test_events_requirement_subject_contains_invalid_object():
    obj = object()
    req = SubjectContains()
    with pytest.raises(RequirementPluginError) as excinfo:
        req(obj, "foo")
    assert "Object with type <class 'object'> has no attribute 'subject'." in str(
        excinfo.value
    )


# -*- coding: utf-8 -*-
import urllib.request
url = "http://www.baidu.com"
data = urllib.request.urlopen(url).read()
data = data.decode()
f = open('data.html','w',encoding='utf-8')

f.write(data)
#print(d)


import sys
import time
id=0              # first token of each row is a an object id
prevId=0          # variable used to determine when id changes
index={}          # id:[startLine,endLine]
offset=0          # number of bytes from beginning of file
line_offset=[]    # ordered list of start of each line, in bytes from start
numOfObj=0        # many lines can have the same object id

class Names:
    startByte=3;
    numBytes=4;
    pass;

def idToOffset(id=13, indexfile="index.csv"):
  """Returns a tuple of offset and len in bytes."""
  with open(indexfile, 'r') as f:
    labels=f.readline().split(',');
    for i,line in enumerate(f):
      tokens=line.split(',')     # each line of comma separated file  id,start,end,byteoffset,bytelen
      if int(tokens[0])==id:
        f.close()
        return (int(tokens[Names.startByte]), int(tokens[Names.numBytes]))
  f.close()

def offsetToText(posAndLen):
    """Takes a tuple of position and length in bytes."""
    with open("./test_set.csv", 'r') as f:
        f.seek(posAndLen[0])
        data = f.read(posAndLen[1])
    f.close()
    return data

def textToList(data):
    """Takes csv data with newlines and returns array of strings via split."""
    samples=data.split('\n');
    return samples;

# example getting first object
obj14=textToList(offsetToText(idToOffset(14)))
# example getting last object
start=time.time()
lastObj=textToList(offsetToText(idToOffset(104853738)))
print(lastObj)
end=time.time()
print("Took {0: .2f}s to extract last object samples.".format(end-start))


### standard
import streamlit as st
from core.Page import Page
### custom
import core.stInfrastructure as infra
### Standard
import os
import base64
import numpy as np
import pandas as pd
import altair as alt

#####################
### main part
#####################

class Page1(Page):
    def __init__(self):
        super().__init__("Readings", "Zeroth Page", ['In mathematics, an automorphic number (sometimes referred to as a circular number) is a natural number in a given number base b whose square "ends" in the same digits as the number itself.','(see)["https://en.wikipedia.org/wiki/Automorphic_number"]'])

    def main(self):
        super().main()

        ### getting attribute
        pageDict=st.session_state[self.name]

        power=st.multiselect("Pick a power:",[x for x in range(1,10,1)])
        upto=st.radio("Pick range to check (up to):",[1000,10000,100000,1000000])
        plsmns=st.selectbox("Neighbours (+/-):",[x for x in range(0,10,1)])
        tallyList=[]
        if st.button("Get results!"):
            st.write("power ==",power)
            st.write("up to ==",upto)
            #tallyDict[power]={}
            for p in power:
                for y in range(plsmns*-1,plsmns+1,1):
                    #st.write("this is neighbour",y)
                    for x in range(0,upto,1):
                        if str(np.power(x,p))[-1*len(str(x))::]==str(x+y):
                            #st.write(x," : ",np.power(x,power),"...",y)
                            tallyList.append({'power':int(p),'neighbour':int(y),'n':int(x)})
                            #st.write(tallyList[-1])
        if len(tallyList)<1:
            st.stop()
        #st.write(tallyList)
        df_tally=pd.DataFrame(tallyList)
        df_tally_g=df_tally.groupby(["power","neighbour"]).count().reset_index()
        st.dataframe(df_tally_g)
        #df_tally_g=df_tally.groupby(["power","neighbour"]).count().reset_index()
        #st.dataframe(df_tally_g)
        myChart=alt.Chart(df_tally_g).mark_bar(size=20).encode(
                    x=alt.X('power:N'),
                    y=alt.Y('n'),
                    color='power:N',
                    column='neighbour:N',
                    tooltip=['power', 'neighbour', 'n']
        ).configure_legend(labelLimit= 0, symbolLimit=0)#.properties(width=800)
        st.altair_chart(myChart)


"""
Unofficial implementation of Copy-Paste for semantic segmentation
"""

#conda activate mmdet
from PIL import Image
#import imgviz
#pip install imgviz
import cv2
#conda install opencv
import argparse
import os
import numpy as np
#import tqdm
#conda install tqdm

import tensorflow.compat.v1 as tf
from third_party.deeplab.core import feature_extractor
from core import preprocess_utils

def random_flip_horizontal(mask, img, p=0.5):
    if np.random.random() < p:
        img = img[:, ::-1, :]
        mask = mask[:, ::-1]
    return mask, img

def img_add(img_src, img_main, mask_src):
    if len(img_main.shape) == 3:
        h, w, c = img_main.shape
    elif len(img_main.shape) == 2:
        h, w = img_main.shape
    mask = np.asarray(mask_src[:,:,0], dtype=np.uint8)
    sub_img01 = cv2.add(img_src, np.zeros(np.shape(img_src), dtype=np.uint8), mask=mask)
    mask_02 = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
    #size of output in cv2.resize() is defined as (w,h)
    mask_02 = np.asarray(mask_02, dtype=np.uint8)
    sub_img02 = cv2.add(img_main, np.zeros(np.shape(img_main), dtype=np.uint8),
                        mask=mask_02)

    if len(sub_img01.shape) == 2:
        sub_img01 = np.expand_dims(sub_img01, axis=2)
    if len(sub_img02.shape) == 2:
        sub_img02 = np.expand_dims(sub_img02, axis=2)

    sub_img01 = cv2.resize(sub_img01, (img_main.shape[1], img_main.shape[0]),
               interpolation=cv2.INTER_NEAREST)
    if len(sub_img01.shape) == 2:
        sub_img01 = np.expand_dims(sub_img01, axis=2)

    img_main = img_main - sub_img02 + sub_img01
    #img_main = img_main - sub_img02 + cv2.resize(sub_img01, (img_main.shape[1], img_main.shape[0]),
    #                                             interpolation=cv2.INTER_NEAREST)
    return img_main

def rescale_src(mask_src, img_src, h, w):
    #rescale and paste randomly
    if len(mask_src.shape) == 3:
        h_src, w_src, c = mask_src.shape
    elif len(mask_src.shape) == 2:
        h_src, w_src = mask_src.shape
    max_reshape_ratio = min(h / h_src, w / w_src)
    rescale_ratio = np.random.uniform(0.2, max_reshape_ratio)

    # reshape src img and mask
    rescale_h, rescale_w = int(h_src * rescale_ratio), int(w_src * rescale_ratio)
    mask_src = cv2.resize(mask_src, (rescale_w, rescale_h),
                          interpolation=cv2.INTER_NEAREST)
    mask_src = np.expand_dims(mask_src, axis=2)
    # mask_src = mask_src.resize((rescale_w, rescale_h), Image.NEAREST)
    img_src = cv2.resize(img_src, (rescale_w, rescale_h),
                         interpolation=cv2.INTER_LINEAR)

    # set paste coord
    py = int(np.random.random() * (h - rescale_h))
    px = int(np.random.random() * (w - rescale_w))

    # paste src img and mask to a zeros background
    img_pad = np.zeros((h, w, 3), dtype=np.uint8)
    mask_pad = np.zeros((h, w, 1), dtype=np.uint8)
    img_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio), :] = img_src
    mask_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio)] = mask_src

    return mask_pad, img_pad

def Large_Scale_Jittering(mask, img, min_scale=0.1, max_scale=2.0):
    rescale_ratio = np.random.uniform(min_scale, max_scale)
    h, w, _ = img.shape

    #h = int(h)
    #w = int(w)
    # rescale
    h_new, w_new = int(h * rescale_ratio), int(w * rescale_ratio)

    #img, mask = preprocess_utils.randomly_scale_image_and_label(img, mask, rescale_ratio)
    img = cv2.resize(img, (w_new, h_new), interpolation=cv2.INTER_LINEAR)
    mask = cv2.resize(mask, (w_new, h_new), interpolation=cv2.INTER_NEAREST)
    mask = np.expand_dims(mask, axis=2)
    # mask = mask.resize((w_new, h_new), Image.NEAREST)
    # crop or padding
    x, y = int(np.random.uniform(0, abs(w_new - w))), int(np.random.uniform(0, abs(h_new - h)))

    ##mask: Label with shape [height, width, 1].
    if rescale_ratio <= 1.0:  # padding
        img_pad = np.ones((h, w, 3), dtype=np.uint8) * 168
        #RGB(168,168,168) is grey
        mask_pad = np.zeros((h, w, 1), dtype=np.uint8)
        #
        #img_pad = np.ones((h, w, 3), dtype=np.float32) * 168
        #mask_pad = np.zeros((h, w, 1), dtype=np.int32)
        #img_pad = tf.cast(img_pad, tf.float32)
        #mask_pad = tf.cast(mask_pad, tf.int32)

        #print(h_new, w_new)

        img_pad[y:y+h_new, x:x+w_new, :] = img
        mask_pad[y:y+h_new, x:x+w_new, :] = mask

        return mask_pad, img_pad
    else:  # crop
        img_crop = img[y:y+h, x:x+w, :]
        mask_crop = mask[y:y+h, x:x+w, :]
        #print(img_crop.dtype)
        #print(mask_crop.dtype)
        return mask_crop, img_crop

def copy_paste(mask_src, img_src, mask_main, img_main, lsj=True):

    mask_src, img_src = random_flip_horizontal(mask_src, img_src)
    mask_main, img_main = random_flip_horizontal(mask_main, img_main)

    # LSJ， Large_Scale_Jittering
    if lsj:
        mask_src, img_src = Large_Scale_Jittering(mask_src, img_src)
        mask_main, img_main = Large_Scale_Jittering(mask_main, img_main)
    else:
        # rescale mask_src/img_src to less than mask_main/img_main's size
        h, w, _ = img_main.shape
        mask_src, img_src = rescale_src(mask_src, img_src, h, w)

    img = img_add(img_src, img_main, mask_src)
    mask = img_add(mask_src, mask_main, mask_src)

    return mask, img


import numpy as np
import tensorflow as tf

import tensorflow_docs as tfdocs
import tensorflow_docs.modeling
import tensorflow_docs.plots
import matplotlib.pyplot as plt

def nn_tf_model(input_data):
  num_classes, num_features, train_data, train_labels, validation_data, validation_labels, test_data, test_labels = input_data
  model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(num_features,)),
    tf.keras.layers.Dense(62, activation=None),
    tf.keras.layers.LayerNormalization(),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.Dense(62, activation=None),
    tf.keras.layers.LayerNormalization(),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.Dense(62, activation=None),
    tf.keras.layers.LayerNormalization(),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(32, activation=None),
    tf.keras.layers.LayerNormalization(),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(num_classes)
  ])
  model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

  # print model summary
  model.summary()

  # train
  batch_size=400
  history = model.fit(train_data, train_labels, epochs=8, verbose=1, shuffle=True, batch_size=batch_size,
    callbacks=[tfdocs.modeling.EpochDots()], validation_data=(validation_data, validation_labels))

  # test
  __, test_acc = model.evaluate(test_data,  test_labels, verbose=2)
  print('\nTest accuracy:', test_acc)

  probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
  predictions = probability_model.predict(test_data)
  return (test_acc, predictions, history)


# Topic: Count the number of words in the dictionary
# Coded by Hemanta Ingle
if False:
    book_title =  ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
    word_counter={}
    for word in book_title:
        if word not in word_counter:
            word_counter[word] = 1
        else:
            word_counter[word] += 1

    print(word_counter)
    # Thanks for watching

#Topic:Accessing the values as well as the keys in a for loop
cast = {
           "Jerry Seinfeld": "Jerry Seinfeld",
           "Julia Louis-Dreyfus": "Elaine Benes",
           "Jason Alexander": "George Costanza",
           "Michael Richards": "Cosmo Kramer"
       }
if False:
    for actors in cast:
        print(actors)
    for actors, value in cast.items():# here we use .items method to access the values of the keys
        print("Actor: {}    Role: {}".format(actors, value))# here actors is the key and value is the value Ie. role in this case
    #Thanks for watching

# You would like to count the number of fruits in your basket.
# In order to do this, you have the following dictionary and list of
# fruits.  Use the dictionary and list to count the total number
# of fruits, but you do not want to count the other items in your basket.

type = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for items, value in basket_items.items():
    if items in fruits:
        type += value
    # Iterate through the dictionary

    print("items:{} value:{}".format(items, value))

# if the key is in the list of fruits, add the value (number of fruits) to result

print(type)
# Now we will try for different examples and see if our logic still works
#Example 1

result = 0
basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for items, value in basket_items.items():
    if items in fruits:
        type += value
    # Iterate through the dictionary

    print("items:{} value:{}".format(items, value))

# if the key is in the list of fruits, add the value (number of fruits) to result

print(type)

#Example 2

result = 0
basket_items = {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for items, value in basket_items.items():
    if items in fruits:
        type += value
    # Iterate through the dictionary

    print("items:{} value:{}".format(items, value))

# if the key is in the list of fruits, add the value (number of fruits) to result

print(type)

#Example 3

result = 0
basket_items = {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']

for items, value in basket_items.items():
    if items in fruits:
        type += value
    # Iterate through the dictionary

    print("items:{} value:{}".format(items, value))

# if the key is in the list of fruits, add the value (number of fruits) to result

print(type)

#Thanks for watching


#!/usr/bin/env python3
"""
Module for function Montecarlo
"""
import numpy as np

def game(env, S, policy, max_steps):
    """_summary_

    Args:
        env (gym): AI gym environment.
        S (gym): initial state of the environment.
        policy (function): takes in state and returns action.
        max_steps (int): max number of steps per episode.
    """
    lista = []
    for _ in range(max_steps):
        A = policy(S)
        S_t1, R, done, _ = env.step(A)
        lista.append((S, A, R))
        if done:
            break
        S = S_t1
    return np.array(lista, dtype=int)

def monte_carlo(env, V, policy, episodes=5000,
                max_steps=100, alpha=0.1, gamma=0.99):
    """_summary_

    Args:
        env (gym): AI gym environment.
        V (np.ndarray): value estimate.
        policy (function): takes in state and returns action.
        episodes (int, optional): total number of episodes. Defaults to 5000.
        max_steps (int, optional): max number of steps per
                                episode. Defaults to 100.
        alpha (float, optional): learning rate. Defaults to 0.1.
        gamma (float, optional): discount rate. Defaults to 0.99.

    Returns:
        (np.ndarray): updated value estimate.
    """
    for i in range(episodes):
        S = env.reset()

        G = 0
        episode = game(env, S, policy, max_steps)

        for steps in episode[::-1]:
            S, _, R = steps
            G = gamma * G + R
            if not (S in episode[:i, 0]):
                V[S] = V[S] + alpha * (G - V[S])

    return V


from ash import *
import os
import glob

numcores=5

xyzfiles_dir="/Users/bjornsson/ownCloud/ASH-tests/testsuite/fragfiles_5"

#Creating list of fragmentfiles
fragmentfiles=[]
for file in glob.glob(xyzfiles_dir+"/*"):
    label=file.split('/')[-1].split('.')[0]
    print(file)
    frag=Fragment(xyzfile=file, label=label)
    frag.print_system(filename=label+'.ygg')
    #frag=Fragment(xyzfile=file)
    fragmentfiles.append(label+'.ygg')

print(fragmentfiles)

#xtbcalc=xTBTheory(charge=0,mult=1, xtbmethod='GFN2-xTB', numcores=1)
orcacalc=ORCATheory(charge=0,mult=1, orcasimpleinput="! HF def2-SVP")
result = Singlepoint_parallel(theories=[orcacalc], fragmentfiles=fragmentfiles, numcores=numcores)

print("Results object:", result)
print("Final energydict:", result.energies_dict)


# Import all the required modules/packages
from flask import request, url_for, redirect
import requests
from urllib.parse import parse_qsl
from config import getEnvConfig
from models import User, db
from flask_jwt_extended import create_access_token

#Load the env config
config = getEnvConfig()

'''
Index page of application
to route you to login page
'''
def index():
    return redirect(url_for('routeApp.login'))

'''
Login page of application
route you to gihub login
'''
def login():
    return redirect(config.GITHUB_AUTH_URI)

'''
Call back url from github provider
'''
def callback():
    try:
        #updating code from github to the github access token header
        config.GITHUB_ACCESS_TOKEN_HEADER.update({"code" : request.args.get("code")})
        #requesting access token from github using the code received
        response = requests.get('https://github.com/login/oauth/access_token',\
                                config.GITHUB_ACCESS_TOKEN_HEADER)

        #if success, use the access token to get the user details from github
        if response.status_code == 200:
            queryDict =  dict(parse_qsl(response.text))
            userResponse = requests.get(url = 'https://api.github.com/user',\
                                    headers = {"Authorization": "token {}".format(queryDict.get('access_token'))})

            #if user response is success, use the details to create user in our application
            if userResponse.status_code == 200:
                userData = userResponse.json()
                userObj = User.query.filter_by(github_id = userData.get('id')).first()
                if not userObj:
                    userObj = User(username = userData.get('login'), github_id = userData.get('id'),\
                                    is_active = True
                    )
                    db.session.add(userObj)
                    db.session.commit()
                '''generating jwt access token for the application and redirect to the client application
                with the access token'''
                access_token = create_access_token(identity = userObj.id)
                return redirect(config.LOGIN_SUCCESS_REDIRECT_URI+access_token)
            else:
                return {"message": "Error in fetching user form github!"}
        else:
            return {"message": "Error in github login!"}
    except Exception as e:
        return {"message":str(e)}


'''
题目描述:
给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
'''

from typing import List
from Tree.TreeNode import TreeNode

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []

        ans = []
        queue = [root]

        while queue:
            cur_level_len = len(queue)
            cur_val = []
            for _ in range(cur_level_len):
                root = queue.pop(0)
                cur_val.append(root.val)

                if root.left:
                    queue.append(root.left)
                if root.right:
                    queue.append(root.right)
            ans.append(cur_val)

        return ans

102_二叉树的层序遍历.py


from sys import stdin

graph = [True] * 10001

for i in range(1, 10001):
    num_len = len(str(i))
    new_num = i

    for j in range(num_len - 1, -1, -1):
        new_num += i // pow(10, j)
        i = i % pow(10, j)

    if new_num < 10001:
        graph[new_num] = False

for i in range(1, 10001):
    if graph[i]:
        print(i)