import sys, struct, os, time, types, re, math, random, operator, hashlib, pdb
import logging, settings
logging.basicConfig(filename=settings.LOG_FILENAME, level=logging.DEBUG)

from lsh.shingles.shingles import _get_list_of_shingles
from lsh.utils.similarity import compute_positive_hash

DbType = settings.DATABASES['default']['ENGINE']
if DbType == 'cassandra':
    from db_cassandra import DbInt, Table
elif DbType == 'datastore':
    from db_datastore import DbInt, Table
else:
    from db_in_memory import DbInt, Table

class UnknownException(Exception):
    pass

class Matrix(object):
    __metaclass__ = Table
    attrs = [
             'ds_key text',
             'source text',
             'filename text',
             'file_key text',
             'lsh_output text',
             'eval_output text',
             'count_output text',
             'random_seeds list<bigint>',
             'buckets list<int>',
             'rows int',
             'bands int',
             'shingle_type ascii',
             'minhash_modulo int',
             ]
    p_keys = ['ds_key']

    def __init__(self):
        return

    @classmethod
    def get(cls, ds_key):
        cls._initialize()
        if ds_key:
            ds = cls.select_row(ds_key = ds_key)
            if ds:
                for attr in ds:
                    if attr in ('random_seeds', 'buckets'):
                        if ds[attr]:
                            logging.info('retrieved dataset[%s][0] type %s, value %s', attr, type(ds[attr][0]), settings.max_mask & ds[attr][0])
                    else:
                        logging.info('retrieved dataset[%s] type %s, value %s', attr, type(ds[attr]), ds[attr])
                return ds
        return None

    @classmethod
    def find(cls, ds_key):
        cls._initialize()
        matrix = Matrix.select_row(ds_key = ds_key)
        if not matrix:
            logging.warning('Matrix.find failed to find matrix with ds_key %s', ds_key)
        return matrix

    def find_child_rows(self):
        MatrixRow._initialize()
        return MatrixRow.select_all(parent = self)

    @classmethod
    def _initialize(cls):
        matrix = Matrix(name = cls.__name__, attrs = cls.attrs, p_keys = cls.p_keys)
        return matrix

    @classmethod
    def make_new_id(cls, source, filename):
        cls._initialize()
        max_iters = 4
        for iter_count in xrange(max_iters):
            ds_key = 'k%04d' % (int(hashlib.md5(source + filename + ' ' * iter_count).hexdigest(), 16) % 10000)
            try:
                # Does a dataset with this ID already exist?
                this_ds = Matrix.select_row(ds_key = ds_key)
                if not this_ds:
                    break
                if this_ds.filename == filename:
                    logging.debug("A dataset with %s already exists, reusing", filename)
                    return ds_key
            except ValueError:
                raise Exception('WTF?')
        if iter_count == max_iters - 1:
            raise Exception("Unable to create Dataset ID")
        return ds_key

    @classmethod
    def create(cls, source, filename, file_key = '',
               rows = settings.rows,
               bands = settings.bands,
               shingle_type = settings.shingle_type,
               minhash_modulo = settings.minhash_modulo):

#         logging.debug('Matrix.create cls = %s, vars = %s', cls, vars(cls))
        Matrix._initialize()

#         logging.debug('Matrix.create inputs %s, %s, %s', source, filename, file_key)
        ds_key = cls.make_new_id(source, filename)
#         logging.debug('Matrix.create ds_key %s', ds_key)

        max_hashes = rows * bands
        data = {
                'ds_key': '%s' % ds_key,
                'source': '%s' % source,
                'filename': '%s' % filename,
                'file_key': '%s' % file_key,
                'random_seeds': [(settings.max_mask & random.getrandbits(settings.max_bits)) for _ in xrange(max_hashes)],
                'rows': rows,
                'bands': bands,
                'shingle_type': '%s' % shingle_type,
                'minhash_modulo': minhash_modulo,
                }
        Matrix.insert_row(data = data)
        matrix = Matrix.find(ds_key)
#         logging.debug('Matrix.create returning %s', matrix)
        return matrix

    def str(self):
        txt = '<Matrix ds_key={ds_key} />'.format(ds_key = self.ds_key)
        return txt

    def get_else_create_doc(self, doc_id):
        try:
            doc = MatrixRow.select_row(ds_key = self.ds_key, doc_id = doc_id)
            if doc:
                return True, doc
        except:
            pass
        doc = MatrixRow(name = 'MatrixRow', attrs = MatrixRow.attrs, p_keys = MatrixRow.p_keys)
        doc.ds_key = self.ds_key
        doc.doc_id = doc_id
        return False, doc

    def get_doc(self, doc_id):
        try:
            doc = MatrixRow.select_row(ds_key = self.ds_key, doc_id = doc_id)
            if doc:
                doc.ds_key = self.ds_key
                doc.doc_id = doc_id
                return doc
        except:
            pass
        return None

    def docs_iterator(self):
        return MatrixRow.select_all(ds_key = self.ds_key)

    def purge(self):
        MatrixRow._initialize()
        MatrixRow.delete_all(parent = self)
        Matrix.delete_row(ds_key = self.ds_key)

    def get_nns(self, doc_id):
        doc = self.get_doc(doc_id)
        if not doc:
            return []
        bkts = [DbInt.fm_db(bkt) for bkt in doc.buckets]
        mhs = {}
        for bkt in bkts:
            bkt_docs = session.execute(self.nns_select, [self.ds_key, DbInt.to_db(bkt)])
            for bkt_doc in bkt_docs:
                mhs[bkt_doc['doc_id']] = bkt_doc['minhashes']
        del mhs[doc_id]
        jac = {}
        for doc_id2 in mhs.keys():
            jac_min = reduce(lambda x, y: x+y, map(lambda a,b: a == b, doc.minhashes,mhs[doc_id2])) / float(len(doc.minhashes))
            jac[doc_id2] = 1.0 - jac_min
            if 0 == int(1000*time.time()) % 100:
                logging.info('Sampling (1%%) Jaccard distance %s | %s: %6.2f', doc_id, doc_id2, jac[doc_id2])
        return jac

    def create_doc(self, _id, text, stats):
        (found, doc) = self.get_else_create_doc(_id)
        stats['found'] = found
        if found:
            # if 0 == int(1000*time.time()) % 20:
            #     # print 5% of the documents on average
            #     logging.info('%s %s',doc['ds_key'], doc['doc_id'])
            return doc

        ### Parse
        t0 = time.time()
        doc.text = text
        tParse = time.time() - t0
        stats['parse'] = tParse
        doc.dataset = self
        doc.rows = self.rows
        doc.hashes = doc.rows * self.bands
        doc.seeds = list(self.random_seeds)
        doc.modulo = self.minhash_modulo
        doc.sh_type = self.shingle_type

        max_hashes = self.rows * self.bands
        doc.minhashes = doc.calc_minhashes()
        tMinhash = time.time() - t0 - tParse
        stats['minhash'] = tMinhash

        doc.buckets = doc.bucketize(doc.minhashes)
        tBucketize = time.time() - t0 - tParse - tMinhash
        stats['bucketize'] = tBucketize

        # if 0 == int(1000*time.time()) % 20:
        #     # print 5% of the documents on average
        #     logging.info('%s %s %s', doc.ds_key, doc.doc_id, doc.buckets)
        data = {
                'ds_key': '%s' % doc.ds_key,
                'doc_id': '%s' % doc.doc_id,
                # Don't need to store minhashes
                # 'minhashes': doc.minhashes,
                'buckets': doc.buckets,
                }
        MatrixRow.insert_row(data = data)
        tDbWrite = time.time() - t0 - tParse - tMinhash - tBucketize
        stats['database'] = tDbWrite
        return doc

class MatrixRow(object):
    __metaclass__ = Table
    attrs = [
             'ds_key text',
             'doc_id text',
             'buckets list<int>',
             # Don't need to store minhashes
             # 'minhashes list<int>',
             ]
    p_keys = ['doc_id', 'ds_key']
    indexes = [('doc_buckets', 'buckets',)]

    @classmethod
    def _initialize(cls):
        # Make sure the underlying tables or data structures exist
        matrix_row = MatrixRow(name = cls.__name__, attrs = cls.attrs, p_keys = cls.p_keys, indexes = cls.indexes)
        return matrix_row

    @classmethod
    def create(cls):
        return cls._initialize()

    def calc_minhashes(self):
        def minhashes_for_shingles(shingles):
            def calc_onehash(shingle, seed):
                def c4_hash(shingle):
                    try:
                        h = struct.unpack('<i',shingle)[0]
                    except struct.error:
                        # We land here when the shingle has non-ascii characters in it.
                        size = 4
                        encoded = shingle.encode('utf-8')
                        int_hashes = [int(encoded[i:i + size].encode('hex'), 16) for i in range(len(encoded)/size)]
                        h = reduce(operator.xor, int_hashes)
                    hash_val = h & settings.max_mask
                    return hash_val

                if self.sh_type == 'c4':
                    return operator.xor(c4_hash(shingle), long(seed)) % self.modulo
                else:
                    return operator.xor(compute_positive_hash(shingle), long(seed)) % self.modulo

            minhashes = [settings.max_mask for _ in xrange(self.hashes)]
            for shingle in shingles:
                for hno in xrange(self.hashes):
                    h_value = calc_onehash(shingle, self.seeds[hno])
                    minhashes[hno] = min(h_value, minhashes[hno])
            return minhashes
        ##########################################
        shingles = self.shingles()
        minhashes = minhashes_for_shingles(shingles)
        return minhashes

    def shingles(self):
        return MatrixRow.shingle_text(self.text, self.sh_type)

    @staticmethod
    def shingle_text(text, sh_type):
        retval = set(text.split()) if sh_type=='w' else set(_get_list_of_shingles(text))
        return retval

    def bucketize(self, minhashes):
        buckets = []
        try:
            band_bits = self.dataset.band_bits
        except AttributeError:
            matrix = self.dataset
            band_bits = int(math.ceil(math.log(matrix.bands, 2)))
            band_mask = (2**band_bits - 1)
            setattr(matrix, 'band_bits', band_bits)
            setattr(matrix, 'band_mask', band_mask)
            setattr(matrix, 'hash_mask', 2**(settings.max_bits - band_bits)-1)

        band_mask = self.dataset.band_mask
        hash_mask = self.dataset.hash_mask
        for band in xrange(self.dataset.bands):
            band_hash = (band_mask & band) * (hash_mask + 1)
            minhashes_in_band = [minhashes[band*self.rows + row] for row in xrange(self.rows)]
            minhashes_into_a_string = '-'.join([str(mh) for mh in minhashes_in_band])
            bucket = band_hash | (hash_mask & int(hashlib.md5(minhashes_into_a_string).hexdigest(), 16))
            buckets.append(DbInt.to_db(bucket))
        return buckets


# coding: utf-8

import asyncio
from typing import cast

from aiogram import Bot, F, Router
from aiogram.filters import (ADMINISTRATOR, CREATOR, JOIN_TRANSITION, KICKED,
                             LEAVE_TRANSITION, MEMBER, RESTRICTED,
                             ChatMemberUpdatedFilter, Text)
from aiogram.types import (CallbackQuery, ChatMemberUpdated,
                           InlineKeyboardButton, InlineKeyboardMarkup, Message)
from loguru import logger

import utils
from api import TelehooperAPI
from DB import get_db, get_default_group, get_group
from telegram.handlers.this import group_convert_message

_supergroup_converts = []

router = Router()

async def _supergroup_convert_check(chat_id: int) -> bool:
	"""
	Метод, который проверяет что группа с ID `chat_id` не была недавно конвертирована в supergroup'у.

	Если данный метод вернул True, то нужно пропустить обработку данного события (сделать `return`).
	"""

	# Что бы убедиться, что бот точно получил обновление с конвертацией группы в супергруппу необходимо чуть-чуть поспать.
	await asyncio.sleep(1)

	return chat_id in _supergroup_converts

@router.my_chat_member(ChatMemberUpdatedFilter(member_status_changed=JOIN_TRANSITION))
async def on_telehooper_added_in_chat_handler(event: ChatMemberUpdated, bot: Bot) -> None:
	"""
	Handler для события добавления бота в группу.

	Отправляет информацию о преобразовании группы в группу-диалог и прочую полезную информацию.
	"""

	if event.chat.type == "channel":
		await bot.send_message(
			chat_id=event.chat.id,
			text=(
				"⚠ Ошибка добавления бота в канал.\n"
				"\n"
				"Упс! Вы добавили бота Telehooper в канал. Telehooper не умеет работать в каналах. 🙈\n"
				"Создайте вместо этого группу и добавьте этого бота в неё.\n"
				"\n"
				"ℹ Telehooper автоматически удалит самого себя из данного канала."
			)
		)

		try:
			await bot.leave_chat(chat_id=event.chat.id)
		except:
			pass

		return

	if await _supergroup_convert_check(event.chat.id):
		return

	# Проверяем, что в группу добавили именно Telehooper.
	if event.new_chat_member.user.id != bot.id:
		return

	status_message = None
	try:
		status_message = await bot.send_message(
			chat_id=event.chat.id,
			text=(
				"🫂 Группа-диалог.\n"
				"\n"
				"Что бы продолжить, Вам необходимо выдать мне права администратора. Выдав права администратора мы сможем продолжить выбор диалога.\n"
				"\n"
				"ℹ Трудности с выдачей прав администратора? Нажмите на кнопку ниже, чтобы узнать, как это сделать для Вашей платформы.\n"
				"\n"
				"⏳ Данное сообщение отредактируется после получения прав администратора в беседе..."
			),
			reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="👋 Инструкция по выдаче прав администратора", callback_data="/this showAdminTips")]])
		)
	except:
		# Мы не смогли отправить сообщение по какой-то причине, например,
		# у бота нет прав админа либо в группе выключена возможность отправлять сообщения.
		#
		# В таком случае, просто информируем пользователя что бот так работать не может,
		# и удаляемся.

		await bot.send_message(
			chat_id=event.from_user.id,
			text=(
				"⚠ Ошибка добавления бота в группу.\n"
				"\n"
				f"По какой-то причине, Telehooper не смог заработать в группе «{event.chat.title}».\n"
				"Возможные на это причины:\n"
				" • У бота нет прав администратора в группе.\n"
				" • В группе отключена возможность отправлять сообщения.\n"
				"\n"
				"Пожалуйста, попробуйте выдать боту права администратора, а так же убедиться, что в группе включена возможность отправлять сообщения, и попробуйте снова.\n"
				"Telehooper автоматически покинет группу без Вашей помощи.\n"
				"\n"
				f"ℹ Возникают проблемы? Попросите помощи либо создайте баг-репорт (Github Issue), по ссылке в команде /help."
			)
		)

		# Удаляем бота из группы.
		try:
			await bot.leave_chat(chat_id=event.chat.id)
		except:
			pass

		return

	db = await get_db()

	data = get_default_group(
		chat=event.chat,
		creator=event.from_user,
		status_message=status_message,
		topics_enabled=status_message.is_topic_message or False,
		admin_rights=False # TODO: Проверка на наличие прав администратора?
	)

	# Небольшой костыль на случай, если группа уже сохранена в БД бота.
	group_db = await db.create(
		f"group_{event.chat.id}",
		exists_ok=True,
		data=data
	)
	group_db.update(data=data)

	await group_db.save()

@router.chat_member(ChatMemberUpdatedFilter(member_status_changed=JOIN_TRANSITION))
async def on_other_member_add_handler(event: ChatMemberUpdated, bot: Bot) -> None:
	"""
	Handler для случая, если в группу (в котором находится Telehooper) был добавлен какой-то сторонний пользователь.
	"""

	if await _supergroup_convert_check(event.chat.id):
		return

	# Добавили иного пользователя в группу.
	if event.new_chat_member.user.is_bot:
		return

	# Проверяем, что это уведомление показано лишь один раз.
	group = await get_group(event.chat)

	# В некоторых edge-case'ах группа может быть не найдена в БД.
	if not group:
		return

	if group["UserJoinedWarning"]:
		return

	await bot.send_message(
		chat_id=event.chat.id,
		text=(
			"🫂 Группа-диалог\n"
			"\n"
			"Вы добавили иного пользователя в данную группу!\n"
			"Это не запрещено ботом, однако так делать не рекомендуется, поскольку другой пользователь может читать Ваши сообщения, а так же бот может нестабильно работать в случаях присутствия «чужих» пользователей в группе.\n"
			"\n"
			f"ℹ Вы можете настроить бота так, что бы сообщения от других пользователей отправлялись от Вашего, либо от их собственного имени, либо что бы их сообщения полностью игнорировались. Зайдите в настройки сервисов и найдите соответствующую настройку для изменения поведения в таких случаях."
		)
	)

	# Сохраняем то, что мы предупредили пользователя.
	group["UserJoinedWarning"] = True

	await group.save()

@router.callback_query(Text("/this showAdminTips"), F.message.as_("msg"))
async def show_platform_admin_steps_inline_handler(query: CallbackQuery, msg: Message) -> None:
	"""
	Handler, вызываемый, если пользователь в welcome-сообщении нажал на кнопку с инструкцией по выдаче прав администратора.
	"""

	await TelehooperAPI.edit_or_resend_message(
		(
			"🫂 Группа-диалог.\n"
			"\n"
			"Отлично! Добавив меня в группу, Вы сможете выбрать нужный Вам диалог из подключённого сервиса.\n"
			"\n"
			"Что бы продолжить, Вам необходимо выдать мне права администратора. Выдав права администратора мы сможем продолжить выбор диалога.\n"
			"Инструкции по выдаче прав администратора для разных платформ описаны ниже.\n"
			"\n"
			"Telegram Desktop:\n"
			" • Нажмите на кнопку «Управление группой».\n"
			" • Выберите пункт «Администраторы».\n"
			" • Нажмите на кнопку «Добавить администратора».\n"
			f" • Найдите бота @{utils.get_bot_username()}.\n"
			" • Разрешите всё, кроме пункта «Анонимность».\n"
			"\n"
			"Android:\n"
			" • Откройте список участников группы.\n"
			" • Зажмите палец над этим ботом.\n"
			" • Разрешите всё, кроме пункта «Анонимность».\n"
			"\n"
			"⏳ Данное сообщение отредактируется после получения прав администратора в беседе..."
		),
		message_to_edit=msg,
		chat_id=msg.chat.id,
		query=query
	)

@router.my_chat_member(ChatMemberUpdatedFilter(member_status_changed=(RESTRICTED | MEMBER | KICKED) >> (ADMINISTRATOR | CREATOR)))
async def on_user_promoted_handler(event: ChatMemberUpdated, bot: Bot):
	"""
	Handler, вызываемый, если пользователя повысили в группе.
	"""

	# Проверяем, что повысили именно бота.
	if event.new_chat_member.user.id != bot.id:
		return

	await asyncio.sleep(1)

	group = await get_group(event.chat)

	# В некоторых edge-case'ах группа может быть не найдена в БД.
	if not group:
		return

	# Пытаемся отредактировать сообщение.
	#
	# Если группа была конвертирована в супергруппу, то бот не сможет его отредактировать, поэтому мы его просто отправим.
	try:
		await group_convert_message(event.chat.id, event.from_user, group["StatusMessageID"], called_from_command=False)
	except:
		await group_convert_message(event.chat.id, event.from_user, None, called_from_command=False)

@router.chat_member(ChatMemberUpdatedFilter(member_status_changed=(ADMINISTRATOR | CREATOR) >> (RESTRICTED | MEMBER)))
async def on_user_demotion_handler(event: ChatMemberUpdated, bot: Bot):
	"""
	Handler, вызываемый, если пользователя в группе понизили.
	"""

	# Проверяем, что понизили именно бота.
	if event.new_chat_member.user.id != bot.id:
		return

	await asyncio.sleep(1)

	group = await get_group(event.chat)

	# В некоторых edge-case'ах группа может быть не найдена в БД.
	if not group:
		return

	# Проверяем, что у бота ранее были права администратора.
	if not group["AdminRights"]:
		return

	# Запоминаем, что у бота теперь нет прав админа.
	group["AdminRights"] = False
	await group.save()

	await bot.send_message(
		event.chat.id,
		(
			"⚠ Предупреждение о работе бота в этой группе.\n"
			"\n"
			"Похоже, что Вы понизили бота Telehooper в этой группе. Бот продолжит работу, однако его стабильность может быть нарушена.\n"
			"\n"
			"Рекомендуется выдать боту права администратора, что бы он мог работать стабильно."
		)
	)

@router.chat_member(ChatMemberUpdatedFilter(member_status_changed=LEAVE_TRANSITION))
async def on_user_chat_kick_handler(event: ChatMemberUpdated, bot: Bot):
	"""
	Handler, вызываемый, если пользователя удалили из группы.
	"""

	# Проверяем, что понизили именно бота.
	# TODO: Если из группы вышел именно владелец, то написать ему в ЛС об этом, и предложить вернуться, в ином случае - удалить группу.
	if event.new_chat_member.user.id != bot.id:
		return

	await asyncio.sleep(1)

	# Если группа не была сохранена в БД, то значит что удалять нечего.
	if not get_group(event.chat):
		return

	# Удаляем группу из БД.
	await TelehooperAPI.delete_group_data(event.chat.id, fully_delete=True, bot=bot)

@router.message(F.migrate_to_chat_id)
async def group_to_supergroup_convert_handler(message: Message, bot: Bot):
	"""
	Handler для события конвертации Telegram-группы в супергруппу.

	При конвертации в супергруппу Telegram меняет ID группы.
	"""

	old_chat_id = message.chat.id
	new_chat_id = cast(int, message.migrate_to_chat_id)

	logger.debug(f"Telegram-группа с ID {old_chat_id} конвертировалась в supergroup'у с ID {new_chat_id}")

	new_chat = await bot.get_chat(new_chat_id)

	_supergroup_converts.append(old_chat_id)
	_supergroup_converts.append(new_chat_id)

	db = await get_db()

	# Пытаемся получить ассоциированного с данной группой пользователем.
	group_owner = None
	async for user in db.docs(prefix="user_"):
		if old_chat_id not in user["Groups"]:
			continue

		group_owner = user

	if not group_owner:
		logger.debug(f"Владелец группы, которая была конвертирована в супергруппу не был найден. Старый ID: {old_chat_id}, новый: {new_chat_id}")

	# Редактируем старую группу, и создаём новую с новым ID и прочими параметрами.
	group_old = await get_group(message.chat)
	if not group_old:
		return

	old_group_data = group_old._data.copy()

	del old_group_data["_id"]
	del old_group_data["_rev"]

	old_group_data["ID"] = new_chat_id
	old_group_data["LastActivityAt"] = utils.get_timestamp()

	# Создаём новый объект группы из БД.
	group_new = await db.create(f"group_{new_chat_id}", exists_ok=False, data=old_group_data)

	# Сохраняем новую группу.
	await group_new.save()

	# Удаляем старый объект группы из БД.
	await group_old.delete()

	# Редактируем информацию у владельца группы.
	if group_owner:
		group_owner["Groups"].remove(old_chat_id)
		group_owner["Groups"].append(new_chat_id)

		if "VK" in group_owner["Connections"]:
			for group in group_owner["Connections"]["VK"]["OwnedGroups"].values():
				if group["GroupID"] != old_chat_id:
					continue

				group["GroupID"] = new_chat_id

		# Сохраняем изменения у владельца группы.
		await group_owner.save()

	# Фиксим все subgroup'ы, что бы в них был новый ID.
	for subgroup in TelehooperAPI.get_all_subgroups():
		if subgroup.parent.chat.id != old_chat_id:
			continue

		subgroup.parent.chat = new_chat


# coding=gbk
# @file:07-Tteacher_new.py
# @data:2021/7/6 18:26
# Editor:clown
class Potato(object):
    def __init__(self):
        self.status='生瓜'
        self.total_time=0
        self.namelist=[]  #调料方法

    def cook(self,time):
       # 计算烧烤总时间
        self.total_time+=time
       # 修改地瓜状态
        if (self.total_time>= 0) and (self.total_time< 3):
            self.status='生瓜'
            # print("生瓜")

        elif (self.total_time >= 3) and (self.total_time < 6):
            # print("半熟")
            self.status='半熟'

        elif (self.total_time >= 6) and (self.total_time < 8):
            # print("熟透了")
            self.status='熟'
        else:
            self.status='烤糊了'

        if self.status=='生瓜'or self.status=='半熟':
            cook_time=6-self.total_time
            return cook_time
        else:
            print("此瓜已经熟了")

    def __str__(self):
        # buf_list=str(self.namelist)
        # buf_list=buf_list.replace('[','')
        # buf_list=buf_list.replace(']','')  #将字符串进行替换
        #字符串.join(列表)，可以将字符串添加到列表每一个元素之间组成信字符串
        if self.namelist:
            return f"此瓜从生的变{self.status},总烧烤时间{self.total_time}," \
                   f"此地瓜的调料为{self.namelist}"
        else:
            return f"此瓜从生的变{self.status},总烧烤时间{self.namelist},"

            #调料包
    #属性：name_list=[]
    #方法：添加调料 add()
    def tiaoliao(self,name):
        self.namelist.append(name)

po=Potato()
po.tiaoliao('油')
print(po)
print("&&&&&&&&&&&&&&&&&")
po.cook(4)
po.tiaoliao('辣椒面')
print(po)
print("^^^^^^^^^^^^^^^^^^^^^^^^")
po.cook(5)
po.tiaoliao('孜然')
print(po)


#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals

from setuptools import setup, find_packages

requirements = [
    'django>=1.8',
    'django-image-cropping',
    'django-sekizai>=0.8.2',
    'easy-thumbnails',
    'markdown',
]

setup(
    name="content",
    version="0.3",
    author="Webkom",
    description="A common functionality app for django.",
    keywords="django content",
    packages=find_packages(exclude=["testproject", "testproject.*"]),
    zip_safe=False,
    install_requires=requirements,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.4',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
    ],
    include_package_data=True,
)


"""
1. 아이디어
    - 치킨거리 구하기
        - 집좌표
        - 치킨 좌표
        comination으로 m개의 치킨집 뽑고 집과의 최단거리

    - 도시의 치킨거리 구하기
"""
import sys; input = sys.stdin.readline
from itertools import combinations

def chickenRoad(house, chicken):
    hx, hy = house
    cx, cy = chicken
    return abs(hx-cx) + abs(hy-cy)

houses = []
chickenShops = []

n, m = map(int, input().split())
for i in range(n):
    town = input().split()
    for j in range(n):
        if town[j] == '1': houses.append((i+1,j+1))
        elif town[j] == '2': chickenShops.append((i+1,j+1))

answer = float('inf')
for c in combinations(chickenShops,m):
    combiRoad = 0
    for h in houses:
        streetPerHouse = float('inf')
        for i in range(m):
            streetPerHouse = min(streetPerHouse, chickenRoad(h,c[i]))
        combiRoad += streetPerHouse
    answer = min(answer,combiRoad)

print(answer)


import random

class SuffixArrayInterface(object):
    def __init__(self, namestr, value=None):
        if namestr:
            self.breakchar = namestr[-1]
        else:
            self.breakchar = u'$'
            namestr=u'$'
        self.namestr = namestr

        strptr = []
        idxtable = []
        key = []
        idx = 0
        for i in xrange(len(namestr)):
            if namestr[i]!=self.breakchar:
                strptr.append(i)
                idxtable.append(idx)
            else:
                idxtable.append(-1)
                key.append(idx);
                idx=i+1
        self.strptr = strptr
        self.idxtable = idxtable
        self.sorted = False
        if value is not None:
            assert(len(value)==len(key))
            self.table = dict(zip(key, value))
        else:
            self.table = None

    def _strcomp(self, i, j):
        """
        return 0: equal
        1: str_j is lexicographically bigger than str_i
        -1: str_j is lexicographically smaller than str_i
        """
        while self.namestr[i]!=self.breakchar and self.namestr[j]!=self.breakchar:
            if self.namestr[i]==self.namestr[j]:
                i+=1
                j+=1
            elif self.namestr[i]<self.namestr[j]:
                return 1
            else:
                return -1

        if self.namestr[i]==self.breakchar and self.namestr[i]==self.namestr[j]:
            return 0
        elif self.namestr[j]==self.breakchar:
            return -1
        elif self.namestr[i]==self.breakchar:
            return 1
        else:
            raise

    def _externalstrcmp(self, i, s):
        """
        s must be ended with self.breakchar
        return 0: equal
        1: s is lexicographically bigger than str_i
        -1: s is lexicographically smaller than str_i
        """
        j=0
        while self.namestr[i]!=self.breakchar and s[j]!=self.breakchar:
            if self.namestr[i]==s[j]:
                i+=1
                j+=1
            elif self.namestr[i]<s[j]:
                return 1
            else:
                return -1

        if s[j]==self.breakchar:
            return 0
        else:
            return 1

    def _qsort(self, x):
        if len(x)<=1: return
        # choose a pivit
        i = random.choice(xrange(len(x)))
        x[0], x[i] = x[i], x[0]

        q = len(x)
        r = len(x)
        p = len(x)-1
        while p>=0:
            rst = self._strcomp(x[0], x[p])
            if rst>0:
                r-=1;
                q-=1
                x[q], x[p] = x[p], x[q]
                x[q], x[r] = x[r], x[q]
            elif rst==0:
                q-=1
                x[q], x[p] = x[p], x[q]
            p-=1
        t1=x[:q]
        t2=x[r:]
        self._qsort(t1)
        self._qsort(t2)
        x[:q]=t1
        x[r:]=t2

    def _lower_bound(self, q):
        "return the left most position that no less than query"
        b = 0
        e = len(self.strptr)
        while e-b>1:
            m = b+(e-b)/2
            if self._externalstrcmp(self.strptr[m], q)==1:
                b=m
            else:
                e=m
        return e

    def _upper_bound(self, q):
        "Returns first element in the range which compares greater than q."
        b = 0
        e = len(self.strptr)
        while e-b>1:
            m = b+(e-b)/2
            if self._externalstrcmp(self.strptr[m], q)>=0:
                b=m
            else:
                e=m
        return e

    def query(self, q):
        if self.sorted == False:
            raise Exception("Suffix array not sorted first. Please call build before this.")
        b = self._lower_bound(q+self.breakchar)
        e = self._upper_bound(q+self.breakchar)
        if e<=b:
            if self.table is not None:
                return [],[]
            return []

        rtn = [self.idxtable[self.strptr[i]] for i in xrange(b, e)]
        rtn = list(set(rtn))
        if self.table is not None:
            return rtn, [self.table[itm] for itm in rtn]
        return rtn

    def build(self):
        x = self.strptr
        self._qsort(x)
        self.strptr = x
        self.sorted = True


import unittest

from dashboard.pinpoint.models import change

class ChangeTest(unittest.TestCase):

  def testChange(self):
    base_commit = change.Dep('chromium/src', 'aaa7336c')
    dep = change.Dep('external/github.com/catapult-project/catapult', 'e0a2efb')
    patch = 'patch/rietveld/codereview.chromium.org/2565263002/20001'

    c = change.Change(base_commit, [dep], patch)

    self.assertEqual(c.base_commit, base_commit)
    self.assertEqual(c.deps, (dep,))
    self.assertEqual(c.patch, patch)

  def testDep(self):
    dep = change.Dep('chromium/src', 'aaa7336c')

    self.assertEqual(dep.repository, 'chromium/src')
    self.assertEqual(dep.git_hash, 'aaa7336c')


# Please note, requests needs to be installed using: pip install requests
import requests
import os

uri = f"https://api-us.cloud.com/cctrustoauth2/{os.environ['Citrix_Customer_Id']}/tokens/clients"

body = {
    "grant_type" : "client_credentials",
    "client_id" : os.environ['Citrix_Client_Id'],
    "client_secret" : os.environ['Citrix_Client_Secret']
}

try:
    request = requests.post(uri, data=body)
except requests.exceptions as e:
    print(f"Error: {e.RequestException}")

token = request.json()
print(f"Token: {token['access_token']}")


import argparse
import sys
import re
import tensorflow as tf
import numpy as np

NUM_INTENSITY_VALUES = 50
MAX_INTENSITY_VALUE = 255

parser = argparse.ArgumentParser(
    description="Run a Keras model to identify layer boundaries based on a "
                "vector of intensities.",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
parser.add_argument("--model", default="model.h5",
        help="Model file to use in Keras HDF5 format")
parser.add_argument("--delimiter", default=";",
        help="Field delimiter used in the program's input and output")
parser.add_argument("--output-file", default=None,
        help="Output file name. Default is INPUTNAME_ObBmIb_bounds.txt, "
             "where INPUTNAME is the input file name without extension.")
parser.add_argument("INPUTS", nargs="+",
        help="Any number of input files containing the intensity values.")

args = parser.parse_args()

def load_input_and_orient(input_file):
    data = np.loadtxt(input_file, delimiter=args.delimiter)
    is_transposed = False
    if data.shape[1] != NUM_INTENSITY_VALUES:
        if data.shape[0] == NUM_INTENSITY_VALUES:
            data = np.transpose(data)
            is_transposed = True
        else:
            print("Error: The input data has dimensions {}, but expected to have {}"
                    " intensity values per observation.".format(data.shape,
                        NUM_INTENSITY_VALUES)
                    )
            sys.exit(1)
    return data, is_transposed

def main():
    model = tf.keras.models.load_model(args.model)

    if len(args.INPUTS) > 1 and args.output_file:
        print("Error: output file cannot be specified when there are multiple inputs.")
        sys.exit(1)

    for input_filename in args.INPUTS:
        data, is_transposed = load_input_and_orient(input_filename)

        norm_inputs = data / MAX_INTENSITY_VALUE
        predictions = model.predict(norm_inputs)
        predictions *= NUM_INTENSITY_VALUES
        predictions = np.clip(predictions, a_min=1, a_max=NUM_INTENSITY_VALUES,
                                out=predictions)
        num_predictions = len(predictions)
        if is_transposed:
            predictions = np.transpose(predictions)
        if args.output_file:
            output_file = args.output_file
        else:
            output_file = re.sub(r"\.\w+$", "", input_filename)
            output_file += "_ObBmIb_bounds.txt"
        np.savetxt(output_file, predictions, fmt="%1.0f", delimiter=args.delimiter)
        print("{} results written to file {}.".format(num_predictions, output_file))

if __name__ == "__main__":
    main()


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
import pandas as pd
import json
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras import activations

from get_features.tokenizer.tokenizer import create_numerate_array
from get_features.image_character.image_feature import show

tf.config.run_functions_eagerly(True)
tf.get_logger().setLevel('ERROR')

id_size = 1
features_size = 7
vocab_size = 458
max_scenes_size = 396
embedding_dim = 458
rnn_units = 512

class ScenesModel(tf.keras.Model):
    def __init__(self, rnn_units):
        super().__init__(self)
        self.normalization = tf.keras.layers.BatchNormalization()
        self.gru = tf.keras.layers.GRU(rnn_units, return_state=True)
        self.dense = tf.keras.layers.Dense(rnn_units)

    def call(self, _input, states=None, return_state=True, training=False):
        norm = self.normalization(_input)
        if states is None:
            states = self.gru.get_initial_state(norm)
        x, final_state = self.gru(norm, initial_state=states, training=training)
        result = self.dense(final_state)

        return result

class HRNNModel(tf.keras.Model):
    def __init__(self, max_scenes_size, vocab_size, rnn_units, scenes_model):
        super().__init__(self)
        self.scenes_model = scenes_model
        self.embedding = tf.keras.layers.Embedding(vocab_size, max_scenes_size)
        self.time_distr = tf.keras.layers.TimeDistributed(self.scenes_model)
        self.gru_sess = tf.keras.layers.GRU(rnn_units, return_sequences=True)
        self.concat = tf.keras.layers.Concatenate()
        self.dense = tf.keras.layers.Dense(vocab_size, activation=activations.softmax)

    def call(self, _input, states=None, return_state=False, training=False):
        features = self.time_distr(_input[1])
        ids = self.embedding(_input[0])
        x = self.concat([ids, features, _input[2]])
        id_x = self.gru_sess(x, training=training)

        result = self.dense(id_x)

        return result

    def predict(self, x, history, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
                workers=1, use_multiprocessing=False, ):
        predictions = super().predict(x, batch_size, verbose, steps, callbacks, max_queue_size, workers,
                                      use_multiprocessing)
        predicted_values = []
        for i in range(len(predictions)):
            output = predictions[-1][0]
            mask = []
            for i in range(vocab_size):
                if i + 1 in history:
                    mask.append(1)
                else:
                    mask.append(0)
            masked_prediction = np.ma.array(output, mask=mask)
            predicted_values.append(np.argmax(masked_prediction) + 1)

        return predicted_values

def toNumber(_str, bias):
    return len(_str) + bias

def getVideoInfo(info_df, mean=False):
    scenes_array = [
        info_df['brightness'].to_numpy(),
        info_df['colorfulness'].to_numpy(),
        info_df['energy'].to_numpy(),
        info_df['tempo'].to_numpy(),
        info_df['amplitude'].to_numpy(),
        info_df['mfcc'].to_numpy(),
        create_numerate_array(info_df['hue'].to_numpy())
    ]
    scenes_array = np.nan_to_num(scenes_array, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
    scaler = MinMaxScaler((-1, 1))
    scenes_array = scaler.fit_transform(scenes_array)

    if mean:
        new_scenes_array = []
        for i in range(len(scenes_array)):
            new_scenes_array.append(np.around(np.mean(scenes_array[i]), 3))
        scenes_array = new_scenes_array

    return scenes_array

def getMovieInfo(trailers_row):
    key = trailers_row['Place of act'].keys()[0]
    emotions = json.loads(trailers_row['emotions'][key].replace("\'", "\""))

    return [
        np.nan_to_num([trailers_row['imdb_rating'][key]], copy=False, nan=0.0, posinf=0.0, neginf=0.0)[0],
        np.around(emotions["negative"], 3),
        np.around(emotions["neutral"], 3),
        np.around(emotions["positive"], 3),
    ]

def getScenesArray(movies_id, trailers_df):
    info = {}
    scenes_array = []
    movieinfo_array = []
    info_folder = "/Volumes/Seagate/natasha-diploma/videoinfo"
    for i in range(0, len(movies_id)):
        info_csv = info_folder + '/' + movies_id[i] + '.csv'
        info_df = pd.read_csv(info_csv, index_col=None, header=0)
        info[movies_id[i]] = getVideoInfo(info_df.iloc[:, 4:])
        scenes_array.append(info[movies_id[i]])
        movieinfo_array.append(getMovieInfo(trailers_df.loc[trailers_df['trailers_name'] == movies_id[i]]))

    return scenes_array, movieinfo_array

def pad_nested_arrays(seq, maxlen_sent):
    new_seq = []
    for i in range(len(seq)):
        size = len(seq[i])
        if maxlen_sent == size:
            new_seq.append(np.pad(seq[i], 0, 'mean'))
        else:
            size_beg = (maxlen_sent - size) // 2
            size_end = size_beg + 1
            new_seq.append(np.pad(seq[i], (size_beg, size_end), 'mean')[:396])

    return new_seq

def setup_model():
    trailers_csv = "/Users/nutochkina/Desktop/VKR/trailers.csv"
    trailers_df = pd.read_csv(trailers_csv, index_col=None, header=0)
    trailers_df.drop(trailers_df.columns[trailers_df.columns.str.contains('Unnamed', case=False)], axis=1, inplace=True)

    sessions_csv = "/Users/nutochkina/Desktop/VKR/sessions1.csv"
    sessions_df = pd.read_csv(sessions_csv, index_col=None, header=0)
    sessions_df.drop(sessions_df.columns[sessions_df.columns.str.contains('Unnamed', case=False)], axis=1, inplace=True)

    movies_id = sessions_df.to_numpy()
    copy = movies_id
    np.random.shuffle(copy)
    movies_id = np.concatenate((np.array(movies_id).flatten(), copy.flatten()))

    vocab = np.unique(movies_id)
    vocab_len = len(vocab)

    tokenized = create_numerate_array(movies_id)
    scenes_array, movieinfo_array = getScenesArray(movies_id, trailers_df)
    padded = np.stack([pad_nested_arrays(r, max_scenes_size) for r in scenes_array], axis=0)

    train_tokenized = tokenized[:4500]
    test_tokenized = tokenized[4500:7460]

    train_scenes = padded[:4500]
    test_scenes = padded[4500:7460]

    train_movinfo = movieinfo_array[:4500]
    test_movinfo = movieinfo_array[4500:7460]

    ids_ds = tf.data.Dataset.from_tensor_slices(train_tokenized)
    features_ds = tf.data.Dataset.from_tensor_slices(train_scenes)
    movie_ds = tf.data.Dataset.from_tensor_slices(train_movinfo)

    ids_ds_test = tf.data.Dataset.from_tensor_slices(test_tokenized)
    features_ds_test = tf.data.Dataset.from_tensor_slices(test_scenes)
    movie_ds_test = tf.data.Dataset.from_tensor_slices(test_movinfo)

    ds_test = tf.data.Dataset.zip((ids_ds_test, features_ds_test, movie_ds_test))
    ds = tf.data.Dataset.zip((ids_ds, features_ds, movie_ds))

    seq_length = 10

    sequences = ds.batch(seq_length + 1, drop_remainder=True)
    sequences_test = ds_test.batch(seq_length + 1, drop_remainder=True)

    def full_split_input_target(id_sequence, feature_sequence, movie_sequence):
        input_text = (id_sequence[:-1], feature_sequence[:-1], movie_sequence[:-1])
        target_text = (id_sequence[1:])
        return input_text, target_text

    ds = sequences.map(full_split_input_target)
    ds_test = sequences_test.map(full_split_input_target)

    BATCH_SIZE = 8
    TEST_BATCH_SIZE = 1
    BUFFER_SIZE = 10000

    ds = (
        ds
            .shuffle(BUFFER_SIZE)
            .batch(TEST_BATCH_SIZE, drop_remainder=True)
            .prefetch(tf.data.experimental.AUTOTUNE))

    ds_test = (
        ds_test
            .shuffle(BUFFER_SIZE)
            .batch(TEST_BATCH_SIZE, drop_remainder=True)
            .prefetch(tf.data.experimental.AUTOTUNE))

    scenes_model = ScenesModel(rnn_units=16)
    scenes_model.build(input_shape=(seq_length, features_size, max_scenes_size))
    scenes_model.summary()

    model = HRNNModel(
        max_scenes_size=max_scenes_size,
        vocab_size=vocab_size,
        rnn_units=rnn_units,
        scenes_model=scenes_model
    )

    for _input, _output in ds.take(1):
        model(_input)

    model.summary()

    return model, ds, ds_test, vocab

def train_model():
    log_file = "/Users/nutochkina/Desktop/VKR/hrnn_model/history.ckpt"
    model, ds, ds_test, _ = setup_model()

    cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=log_file, save_weights_only=True, verbose=1)
    loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)
    model.compile(optimizer=tf.keras.optimizers.Adam(), loss=loss, metrics=[tf.keras.metrics.SparseCategoricalAccuracy(
        name='sparse_categorical_accuracy', dtype=None
    )])

    EPOCHS = 15
    model.fit(ds, validation_data=ds_test, epochs=EPOCHS, callbacks=[cp_callback])

def evaluate_and_predict():
    log_dir = "/Users/nutochkina/Desktop/VKR/hrnn_model/"
    model, ds, ds_test, vocab = setup_model()
    model.compile(optimizer='adam',
                  loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name='sparse_categorical_accuracy', dtype=None)])

    latest = tf.train.latest_checkpoint(log_dir)
    model.load_weights(latest)
    model.evaluate(ds_test, batch_size=1, return_dict=True)

    for _input, _output in ds_test.take(1):
        values = model.predict(_input, _input[0].numpy())
        show(vocab[_input[0].numpy()[0][-1] - 1])
        show(vocab[values[0] - 1])


# Canadian Computing Competition: 2012 Stage 1, Junior #1
#
# Many communities now have "radar" signs that tell drivers what their speed is, in the hope that they will slow down.
#
# You will output a message for a "radar" sign.
# The message will display information to a driver based on his/her speed according to the following table:

# km/h over the limit 	Fine
# 1 to 20 	            $100
# 21 to 30           	$270
# 31 or above       	$500

# Input Specification
# The user will be prompted to enter two integers.
# First, the user will be prompted to enter the speed limit.
# Second, the user will be prompted to enter the recorded speed of the car.

# Output Specification
# If the driver is not speeding, the output should be: Congratulations, you are within the speed limit!
# If the driver is speeding, the output should be: You are speeding and your fine is $F,
# where F is the amount of the fine as described in the table above.

speedLimit = int(input())
speedOfCar = int(input())
difference = speedOfCar - speedLimit
fine = 0

if difference <= 0:
    print("Congratulations, you are within the speed limit!")
elif difference < 21:
    fine = 100
elif difference < 31:
    fine = 270
else:
    fine = 500

if fine != 0:
    print("You are speeding and your fine is $%d." % fine)

J1/CCC '12 J1 - Speed fines are not fine!.py


import unittest

from rclpy.clock import ClockType
from rclpy.duration import Duration
from rclpy.time import Time

from tilde_vis.latency_viewer import (
    calc_one_hot,
    update_stat,
    )
from tilde_vis.message_tracking_tag import MessageTrackingTag, MessageTrackingTags
from tilde_vis.message_tracking_tag_traverse import (
    InputSensorStampSolver,
    TopicGraph,
    )

def get_scenario1():
    """
    Get the following scenario.

    topic1 --> topic2 --> topic3

    topic1 is published in 10Hz.
    topic2 takes 10ms to execute callback.

    """
    def get_topic2_times(start_time, start_time_steady):
        sub_time = start_time + nw_dur
        pub_time = sub_time + cb_dur

        sub_time_steady = start_time_steady + nw_dur
        pub_time_steady = sub_time_steady + cb_dur

        return {'sub': sub_time,
                'pub': pub_time,
                'sub_steady': sub_time_steady,
                'pub_steady': pub_time_steady}

    def get_topic3_times(start_time, start_time_steady):
        sub_time = start_time + nw_dur + cb_dur + nw_dur
        pub_time = sub_time + cb_dur

        sub_time_steady = start_time_steady + nw_dur + cb_dur + nw_dur
        pub_time_steady = sub_time_steady + cb_dur

        return {'sub': sub_time,
                'pub': pub_time,
                'sub_steady': sub_time_steady,
                'pub_steady': pub_time_steady}

    t1 = Time(seconds=10, nanoseconds=0)
    t1_steady = Time(seconds=0, nanoseconds=1,
                     clock_type=ClockType.STEADY_TIME)
    nw_dur = Duration(nanoseconds=1 * 10**6)  # 1 [ms]
    cb_dur = Duration(nanoseconds=10 * 10**6)  # 10 [ms]

    message_tracking_tag_topic1_t1 = \
        MessageTrackingTag(
            'topic1',
            t1.to_msg(),
            t1_steady.to_msg(),
            True,
            t1.to_msg())

    topic2_t1_times = get_topic2_times(t1, t1_steady)
    message_tracking_tag_topic2_t1 = \
        MessageTrackingTag(
            'topic2',
            topic2_t1_times['pub'].to_msg(),
            topic2_t1_times['pub_steady'].to_msg(),
            True,
            t1.to_msg())
    message_tracking_tag_topic2_t1.add_input_info(
        'topic1',
        topic2_t1_times['sub'],
        topic2_t1_times['sub_steady'],
        True,
        t1.to_msg())

    topic3_t1_times = get_topic3_times(t1, t1_steady)
    message_tracking_tag_topic3_t1 = \
        MessageTrackingTag(
            'topic3',
            topic3_t1_times['pub'].to_msg(),
            topic3_t1_times['pub_steady'].to_msg(),
            True,
            t1.to_msg())
    message_tracking_tag_topic3_t1.add_input_info(
        'topic2',
        topic3_t1_times['sub'],
        topic3_t1_times['sub_steady'],
        True,
        t1.to_msg())

    return [message_tracking_tag_topic1_t1,
            message_tracking_tag_topic2_t1,
            message_tracking_tag_topic3_t1]

def dur_plus(lhs, rhs):
    """Plus of Duration."""
    return Duration(nanoseconds=lhs.nanoseconds + rhs.nanoseconds)

def gen_scenario2(
        st, st_steady,
        nw_dur, cb_dur):
    """
    Get the following scenario.

    topic1 --> topic3 --> topic4
    topic2 ---/

    Args:
      st: Time
      st_steady: Time
      nw_dur: Duration
      cb_dur: Duration

    Returns
    -------
    list of MessageTrackingTags such as
    (message_tracking_tag of topic1, message_tracking_tag of topic2, ...)

    """
    message_tracking_tag_topic1 = \
        MessageTrackingTag(
            'topic1',
            st.to_msg(),
            st_steady.to_msg(),
            True,
            st.to_msg())

    topic2_stamp = st + nw_dur
    message_tracking_tag_topic2 = \
        MessageTrackingTag(
            'topic2',
            st.to_msg(),
            st_steady.to_msg(),
            True,
            topic2_stamp.to_msg())

    sub_dur3 = nw_dur
    pub_dur3 = dur_plus(sub_dur3, cb_dur)
    topic3_stamp = st + pub_dur3
    message_tracking_tag_topic3 = \
        MessageTrackingTag(
            'topic3',
            (st + pub_dur3).to_msg(),
            (st_steady + pub_dur3).to_msg(),
            True,
            topic3_stamp.to_msg())
    message_tracking_tag_topic3.add_input_info(
        'topic1',
        (st + sub_dur3).to_msg(),
        (st_steady + sub_dur3).to_msg(),
        True,
        st.to_msg()
        )
    message_tracking_tag_topic3.add_input_info(
        'topic2',
        (st + sub_dur3).to_msg(),
        (st_steady + sub_dur3).to_msg(),
        True,
        topic2_stamp.to_msg())

    sub_dur4 = dur_plus(pub_dur3, nw_dur)
    pub_dur4 = dur_plus(sub_dur4, cb_dur)
    topic4_stamp = st + pub_dur4
    message_tracking_tag_topic4 = \
        MessageTrackingTag(
            'topic4',
            (st + pub_dur4).to_msg(),
            (st_steady + pub_dur4).to_msg(),
            True,
            topic4_stamp.to_msg())
    message_tracking_tag_topic4.add_input_info(
        'topic3',
        (st + sub_dur4).to_msg(),
        (st_steady + sub_dur4).to_msg(),
        True,
        topic3_stamp.to_msg())

    return [
        message_tracking_tag_topic1,
        message_tracking_tag_topic2,
        message_tracking_tag_topic3,
        message_tracking_tag_topic4,
        ]

class TestTopicGraph(unittest.TestCase):

    def test_straight(self):
        infos = get_scenario1()
        message_tracking_tags = MessageTrackingTags()
        for info in infos:
            message_tracking_tags.add(info)

        graph = TopicGraph(message_tracking_tags, skips={})

        self.assertEqual(graph.topics[0], 'topic1')
        self.assertEqual(graph.topics[1], 'topic2')
        self.assertEqual(graph.topics[2], 'topic3')

        edges = graph.topic_edges
        self.assertEqual(edges[0], {1})
        self.assertEqual(edges[1], {2})
        self.assertEqual(edges[2], set())

        rev_edges = graph.rev_edges
        self.assertEqual(rev_edges[0], set())
        self.assertEqual(rev_edges[1], {0})
        self.assertEqual(rev_edges[2], {1})

    def test_scenario2(self):
        t0 = Time(seconds=10, nanoseconds=0)
        t0_steady = Time(seconds=0, nanoseconds=1,
                         clock_type=ClockType.STEADY_TIME)
        nw_dur = Duration(nanoseconds=1 * 10**6)  # 1 [ms]
        cb_dur = Duration(nanoseconds=10 * 10**6)  # 10 [ms]

        infos = gen_scenario2(t0, t0_steady, nw_dur, cb_dur)
        message_tracking_tags = MessageTrackingTags()
        for info in infos:
            message_tracking_tags.add(info)

        graph = TopicGraph(message_tracking_tags, skips={})

        self.assertEqual(graph.topics[0], 'topic1')
        self.assertEqual(graph.topics[1], 'topic2')
        self.assertEqual(graph.topics[2], 'topic3')
        self.assertEqual(graph.topics[3], 'topic4')

        edges = graph.topic_edges
        self.assertEqual(edges[0], {2})
        self.assertEqual(edges[1], {2})
        self.assertEqual(edges[2], {3})
        self.assertEqual(edges[3], set())

        rev_edges = graph.rev_edges
        self.assertEqual(rev_edges[0], set())
        self.assertEqual(rev_edges[1], set())
        self.assertEqual(rev_edges[2], {0, 1})
        self.assertEqual(rev_edges[3], {2})

    def test_scenario2_with_loss(self):
        """
        Graph creation with lossy MessageTrackingTags.

        t0: message_tracking_tag only topic1 and topic3
        t1: only topic2
        t2: only topic4
        """
        t0 = Time(seconds=10, nanoseconds=0)
        t0_steady = Time(seconds=0, nanoseconds=1,
                         clock_type=ClockType.STEADY_TIME)
        nw_dur = Duration(nanoseconds=1 * 10**6)  # 1 [ms]
        cb_dur = Duration(nanoseconds=10 * 10**6)  # 10 [ms]
        period = Duration(seconds=1)
        t1, t1_steady = t0 + period, t0_steady + period
        t2, t2_steady = t1 + period, t1_steady + period

        infos_t0 = gen_scenario2(t0, t0_steady, nw_dur, cb_dur)
        infos_t1 = gen_scenario2(t1, t1_steady, nw_dur, cb_dur)
        infos_t2 = gen_scenario2(t2, t2_steady, nw_dur, cb_dur)
        message_tracking_tags = MessageTrackingTags()

        message_tracking_tags.add(infos_t0[0])
        message_tracking_tags.add(infos_t0[2])
        message_tracking_tags.add(infos_t1[1])
        message_tracking_tags.add(infos_t2[3])

        graph = TopicGraph(message_tracking_tags, skips={})

        self.assertEqual(graph.topics[0], 'topic1')
        self.assertEqual(graph.topics[1], 'topic2')
        self.assertEqual(graph.topics[2], 'topic3')
        self.assertEqual(graph.topics[3], 'topic4')

        edges = graph.topic_edges
        self.assertEqual(edges[0], {2})
        self.assertEqual(edges[1], {2})
        self.assertEqual(edges[2], {3})
        self.assertEqual(edges[3], set())

        rev_edges = graph.rev_edges
        self.assertEqual(rev_edges[0], set())
        self.assertEqual(rev_edges[1], set())
        self.assertEqual(rev_edges[2], {0, 1})
        self.assertEqual(rev_edges[3], {2})

class TestTreeNode(unittest.TestCase):

    def test_solve2_straight(self):
        infos = get_scenario1()
        message_tracking_tags = MessageTrackingTags()
        for info in infos:
            message_tracking_tags.add(info)
        graph = TopicGraph(message_tracking_tags, skips={})
        solver = InputSensorStampSolver(graph)

        tgt_stamp = sorted(message_tracking_tags.stamps('topic3'))[0]
        results = solver.solve2(
            message_tracking_tags,
            'topic3',
            tgt_stamp
        )

        r3 = results
        self.assertEqual(r3.name, 'topic3')
        self.assertEqual(len(r3.data), 1)
        self.assertEqual(len(r3.data[0].in_infos['topic2']), 1)
        self.assertEqual(r3.data[0].in_infos['topic2'][0].stamp.sec, 10)

        r2 = r3.name2child['topic2']
        self.assertEqual(r2.name, 'topic2')
        self.assertEqual(len(r2.data), 1)
        self.assertEqual(len(r2.data[0].in_infos['topic1']), 1)
        self.assertEqual(r2.data[0].in_infos['topic1'][0].stamp.sec, 10)

        r1 = r2.name2child['topic1']
        self.assertEqual(r1.name, 'topic1')
        self.assertEqual(len(r1.data), 1)
        self.assertEqual(len(r1.data[0].in_infos.keys()), 0)

    def test_solve2_branched(self):
        t0 = Time(seconds=10, nanoseconds=0)
        t0_steady = Time(seconds=0, nanoseconds=1,
                         clock_type=ClockType.STEADY_TIME)
        period = Duration(nanoseconds=100 * 10**6)
        nw_dur = Duration(nanoseconds=1 * 10**6)  # 1 [ms]
        cb_dur = Duration(nanoseconds=10 * 10**6)  # 10 [ms]

        message_tracking_tags = MessageTrackingTags()
        st = t0
        st_steady = t0_steady

        # st: 10.0, 10.1, 10.2, ...

        for i in range(100):
            if i == 75:
                test_st = Time.from_msg(st.to_msg())

            infos = gen_scenario2(st, st_steady, nw_dur, cb_dur)
            for info in infos:
                message_tracking_tags.add(info)
            st += period
            st_steady += period

        graph = TopicGraph(message_tracking_tags, skips={})
        solver = InputSensorStampSolver(graph)

        sorted_stamps = sorted(message_tracking_tags.stamps('topic4'))

        tgt_stamp = sorted_stamps[75]
        results = solver.solve2(
            message_tracking_tags,
            'topic4',
            tgt_stamp)

        test_stamp1 = test_st
        test_stamp2 = test_st + nw_dur
        test_stamp3 = test_st + nw_dur + cb_dur
        test_stamp4 = test_stamp3 + nw_dur + cb_dur

        r4 = results
        self.assertEqual(r4.name, 'topic4')
        self.assertEqual(r4.data[0].out_info.stamp,
                         test_stamp4.to_msg())
        self.assertEqual(len(r4.data), 1)
        self.assertEqual(len(r4.data[0].in_infos['topic3']), 1)
        self.assertEqual(r4.data[0].in_infos['topic3'][0].stamp,
                         test_stamp3.to_msg())

        r3 = r4.name2child['topic3']
        self.assertEqual(r3.name, 'topic3')
        self.assertEqual(len(r3.data), 1)
        self.assertEqual(len(r3.data[0].in_infos['topic2']), 1)
        self.assertEqual(r3.data[0].in_infos['topic2'][0].stamp,
                         test_stamp2.to_msg())
        self.assertEqual(len(r3.data[0].in_infos['topic1']), 1)
        self.assertEqual(r3.data[0].in_infos['topic1'][0].stamp,
                         test_stamp1.to_msg())

        one_hot_durations = calc_one_hot(results)
        self.assertEqual(len(one_hot_durations), 4)
        dur4 = one_hot_durations[0]
        self.assertEqual(dur4[1], 'topic4')
        self.assertEqual(dur4[3], 0)

        dur3 = one_hot_durations[1]
        self.assertEqual(dur3[1], 'topic3')
        self.assertEqual(dur3[3], 11)

        dur2 = one_hot_durations[3]
        self.assertEqual(dur2[1], 'topic2')
        self.assertEqual(dur2[3], 22)

        dur1 = one_hot_durations[2]
        self.assertEqual(dur1[1], 'topic1')
        self.assertEqual(dur1[3], 22)

    def setup_only_topic4_scenario(self):
        """Test lossy scenario."""
        t0 = Time(seconds=10, nanoseconds=0)
        t0_steady = Time(seconds=0, nanoseconds=1,
                         clock_type=ClockType.STEADY_TIME)
        nw_dur = Duration(nanoseconds=1 * 10**6)  # 1 [ms]
        cb_dur = Duration(nanoseconds=10 * 10**6)  # 10 [ms]
        period = Duration(seconds=1)

        def init_solver():
            infos = gen_scenario2(t0, t0_steady, nw_dur, cb_dur)
            message_tracking_tags = MessageTrackingTags()
            for info in infos:
                message_tracking_tags.add(info)
            graph = TopicGraph(message_tracking_tags, skips={})
            solver = InputSensorStampSolver(graph)
            return solver

        def get_message_tracking_tags_with_only_topic4():
            t1 = t0 + period
            t1_steady = t0_steady + period
            infos = gen_scenario2(t1, t1_steady, nw_dur, cb_dur)
            message_tracking_tags = MessageTrackingTags()
            message_tracking_tags.add(infos[-1])
            return message_tracking_tags

        solver = init_solver()
        tgt_message_tracking_tags = get_message_tracking_tags_with_only_topic4()

        return (solver, tgt_message_tracking_tags)

    def test_solve_empty(self):
        # setup
        solver, _ = self.setup_only_topic4_scenario()
        tgt_topic = 'topic4'

        results = solver._solve_empty(tgt_topic)

        result_topic4 = results
        self.assertEqual(result_topic4.name, 'topic4')
        self.assertEqual(len(result_topic4.data), 0)

        result_topic3 = result_topic4.name2child['topic3']
        self.assertEqual(result_topic3.name, 'topic3')
        self.assertEqual(len(result_topic3.data), 0)

        result_topic2 = result_topic3 .name2child['topic2']
        self.assertEqual(result_topic2.name, 'topic2')
        self.assertEqual(len(result_topic2.data), 0)

        result_topic1 = result_topic3.name2child['topic1']
        self.assertEqual(result_topic1.name, 'topic1')
        self.assertEqual(len(result_topic1.data), 0)

    def test_solve2_with_loss(self):
        """Solve with lossy MessageTrackingTags."""
        solver, tgt_message_tracking_tags = self.setup_only_topic4_scenario()

        tgt_topic = 'topic4'
        tgt_stamps = tgt_message_tracking_tags.stamps(tgt_topic)

        self.assertEqual(len(tgt_stamps), 1)
        results = solver.solve2(tgt_message_tracking_tags, tgt_topic, tgt_stamps[0])

        # is there full graph?
        result_topic4 = results
        self.assertEqual(result_topic4.name, 'topic4')
        self.assertEqual(len(result_topic4.data), 1)
        self.assertTrue(isinstance(result_topic4.data[0], MessageTrackingTag))

        result_topic3 = result_topic4.name2child['topic3']
        self.assertEqual(result_topic3.name, 'topic3')
        self.assertEqual(len(result_topic3.data), 0)

        result_topic2 = result_topic3.name2child['topic2']
        self.assertEqual(result_topic2.name, 'topic2')
        self.assertEqual(len(result_topic2.data), 0)

        result_topic1 = result_topic3.name2child['topic1']
        self.assertEqual(result_topic1.name, 'topic1')
        self.assertEqual(len(result_topic1.data), 0)

    def test_update_stat(self):
        t = []
        ts = []
        nw_dur = []
        cb_dur = []

        t.append(Time(seconds=10, nanoseconds=0))
        ts.append(Time(seconds=0, nanoseconds=1,
                       clock_type=ClockType.STEADY_TIME))
        nw_dur.append(Duration(nanoseconds=10 * 10**6))
        cb_dur.append(Duration(nanoseconds=1 * 10**6))

        period1 = Duration(nanoseconds=100 * 10**6)
        t.append(t[-1] + period1)
        ts.append(ts[-1] + period1)
        nw_dur.append(Duration(nanoseconds=20 * 10**6))
        cb_dur.append(Duration(nanoseconds=2 * 10**6))

        period2 = Duration(nanoseconds=100 * 10**6)
        t.append(t[-1] + period2)
        ts.append(ts[-1] + period2)
        nw_dur.append(Duration(nanoseconds=30 * 10**6))
        cb_dur.append(Duration(nanoseconds=3 * 10**6))

        message_tracking_tags = MessageTrackingTags()

        for i in range(len(t)):
            infos = gen_scenario2(t[i], ts[i],
                                  nw_dur[i], cb_dur[i])
            for info in infos:
                message_tracking_tags.add(info)

        graph = TopicGraph(message_tracking_tags, skips={})
        solver = InputSensorStampSolver(graph)

        tgt_stamp = sorted(message_tracking_tags.stamps('topic4'))[-1]
        results = solver.solve2(
            message_tracking_tags,
            'topic4',
            tgt_stamp)
        results = update_stat(results)

        self.assertEqual(results.data, [(0, 0)])
        topic3 = results.get_child('topic3')
        self.assertEqual(topic3.data, [(33, 33)])

        topic2 = topic3.get_child('topic2')
        self.assertEqual(topic2.data, [(66, 66)])

        topic1 = topic3.get_child('topic1')
        self.assertEqual(topic1.data, [(66, 66)])

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


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:

            return head

        count = 0

        fast = head

        while fast != None:

            fast = fast.next

            count += 1

        mid = count // 2 + 1

        slow = head

        for i in range(1, mid):

            slow = slow.next

        return slow


import sys
input = sys.stdin.readline
dict = {}
ans = []
while True:
    arr = input().split()
    if len(arr)>0:
        if arr[0] == '0':
            break
        elif arr[0] == '1':
            dict[arr[1]] = True
        elif arr[0] == '2':
            if arr[1] in dict and dict[arr[1]] == True:
                ans.append(1)
            else:
                ans.append(0)
        elif arr[0] == '3' and arr[1] in dict:
                dict[arr[1]] = False
for i in ans:
    print(i)

WeCode Assignments/Tuan 2.1 - Chu y thoi gian chay/GameOnline2.py


from torch.utils import model_zoo

from model.library.base import InvertModel, ModelLibrary
from datasets import image_net
from torch import nn
from torchvision.models import resnet50

def robust_resnet50():
    model = nn.DataParallel(resnet50())
    checkpoint = model_zoo.load_url('https://github.com/AminJun/PublicModels/releases/download/main/free.pt',
                                    map_location='cpu')
    model.load_state_dict(checkpoint['state_dict'])
    return model.module

class RobustResNet50(InvertModel):
    def __init__(self, constructor, batch_size: int):
        normalizer = image_net.normalizer
        image_size = 224
        constructor_args = {}
        name = f'{self.__class__.__name__}'

        super().__init__(name, constructor, constructor_args, image_size, batch_size, normalizer)

robust_models = ModelLibrary([
    RobustResNet50(robust_resnet50, 21),
])


import numpy as np
from typing import Dict, List, Tuple
from boolcryptogp.nsgp.structure.FullBinaryDomain import FullBinaryDomain

class WalshTransform:
    def __init__(self,
                 n_bits: int
                 ) -> None:
        self.__domain: FullBinaryDomain = FullBinaryDomain(n_bits)
        # self.__pairwise_scalar_prod: np.ndarray = WalshTransform.linear_function_xor_of_bitwise_and(self.__domain.data())
        self.__number_of_ones_for_each_number: np.ndarray = np.array([bin(i)[2:].count('1') for i in range(self.__domain.space_cardinality())])
        self.__boolean_mask_number_of_ones_for_each_number: Dict[int, np.ndarray] = {t: self.__number_of_ones_for_each_number <= t for t in range(self.__domain.number_of_bits() + 1)}

    def domain(self) -> FullBinaryDomain:
        return self.__domain

    def number_of_ones_for_each_number(self) -> np.ndarray:
        return self.__number_of_ones_for_each_number

    def boolean_mask_number_of_ones_for_each_number(self, t: int) -> np.ndarray:
        return self.__boolean_mask_number_of_ones_for_each_number[t]

    def resiliency(self, spectrum: np.ndarray) -> int:
        max_resiliency_found_so_far: int = -1
        t: int = 0
        if spectrum[0] == 0:
            max_resiliency_found_so_far = 0
            for iii in range(self.__domain.number_of_bits()):
                t += 1
                m: np.ndarray = self.boolean_mask_number_of_ones_for_each_number(t)
                if np.any(spectrum[m]):
                    return max_resiliency_found_so_far
                else:
                    max_resiliency_found_so_far += 1
                    if iii == self.__domain.number_of_bits() - 1:
                        return max_resiliency_found_so_far
        else:
            return max_resiliency_found_so_far

    def non_linearity(self, spectrum: np.ndarray) -> float:
        x: np.ndarray = np.absolute(spectrum)
        m: float = float(np.max(x))
        return (2 ** (self.__domain.number_of_bits() - 1)) - 0.5 * m

    def apply(self, result: np.ndarray) -> Tuple[np.ndarray, int]:
        #res: np.ndarray = np.tile(result, (self.__domain.space_cardinality(), 1))
        #res = np.logical_xor(res, self.__pairwise_scalar_prod)
        #res = np.power(-1, res)
        #return np.sum(res, axis=1)
        return self.__fast_walsh_transform_init(result)

    def invert(self, spectrum: np.ndarray, directly_go_to_truth_table: bool = False) -> Tuple[np.ndarray, int]:
        return self.__inverse_fast_walsh_transform_init(spectrum, directly_go_to_truth_table)

    def __fast_walsh_transform_init(self, result: np.ndarray) -> Tuple[np.ndarray, int]:
        polar_form: np.ndarray = FullBinaryDomain.convert_truth_table_to_polar_form(result)
        l: List[int] = polar_form.tolist()
        spectral_radius: int = self.__fast_walsh_transform(l, 0, len(l))
        return np.array(l), spectral_radius

    def __fast_walsh_transform(self, v: List[int], start: int, length: int) -> int:
        half: int = length // 2
        for i in range(start, start + half):
            temp: int = v[i]
            v[i] += v[i + half]
            v[i + half] = temp - v[i + half]

        if half > 1:
            val1: int = self.__fast_walsh_transform(v, start, half)
            val2: int = self.__fast_walsh_transform(v, start + half, half)
            return max(val1, val2)
        else:
            if abs(v[start]) > abs(v[start + half]):
                return abs(v[start])
            else:
                return abs(v[start + half])

    def __inverse_fast_walsh_transform_init(self, result: np.ndarray, directly_go_to_truth_table: bool = False) -> Tuple[np.ndarray, int]:
        l: List[int] = result.tolist()
        max_auto_correlation_coefficient: int = self.__inverse_fast_walsh_transform(l, 0, len(l))
        r: np.ndarray = np.array(l, dtype=np.int64)
        if not directly_go_to_truth_table:
            return r, max_auto_correlation_coefficient
        return FullBinaryDomain.convert_polar_form_to_truth_table(r), max_auto_correlation_coefficient

    def __inverse_fast_walsh_transform(self, v: List[int], start: int, length: int) -> int:
        half: int = length // 2
        for i in range(start, start + half):
            temp: int = v[i]
            v[i] = int( (v[i] + v[i + half]) / 2.0 )
            v[i + half] = int( (temp - v[i + half]) / 2.0 )

        if half > 1:
            val1: int = self.__inverse_fast_walsh_transform(v, start, half)
            val2: int = self.__inverse_fast_walsh_transform(v, start + half, half)
            return max(val1, val2)
        else:
            if start == 0:
                return abs(v[1])
            else:
                if abs(v[start]) > abs(v[start + half]):
                    return abs(v[start])
                else:
                    return abs(v[start + half])

    @staticmethod
    def linear_function_xor_of_bitwise_and(data: np.ndarray) -> np.ndarray:
        res: np.ndarray = np.empty((data.shape[0], data.shape[0]))
        for i in range(res.shape[0]):
            for j in range(res.shape[1]):
                first: np.ndarray = data[i]
                second: np.ndarray = data[j]
                and_res: np.ndarray = np.logical_and(first, second)
                final_res: int = and_res[0]
                for iii in range(1, len(and_res)):
                    final_res = final_res ^ and_res[iii]
                res[i][j] = final_res
        return res


secret = "alana"
digitations = []

while True:
    letter = input('Digite uma letra:\n')

    if len(letter) > 1:
        print("Digite apenas uma letra.")
        continue

    digitations.append(letter)

    if letter in secret:
        print(f'A letra que você digitou contem na palavra secreta!')
    else:
        print(f'A letra que você digitou não contem na palavra secreta :(')
        digitations.pop()

    temporarySecret = ''
    for secretLetter in secret:
        if secretLetter in digitations:
            temporarySecret += secretLetter
        else:
            temporarySecret += '*'

    if temporarySecret == secret:
        print(f"Você ganhou!!! A palavra era {temporarySecret}.")
        break
    else:
        print(f'A palavra secreta está assim: {temporarySecret}')


import math
import numpy as np
import matplotlib
matplotlib.use('SVG')

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

N = 5
M = 6
h = 1. / M

grid = [(h * i, h * j) for i in range(0, M + 1) for j in range(0, N + 1)]

sx, sy = zip(*grid)
ax.scatter(sx, sy, marker='+')

xi, ti = h * 2, h * 2

stencil = [(xi, ti), (xi - h, ti - h), (xi, ti - h), (xi + h, ti - h)]
stx, sty = zip(*stencil)
ax.scatter(stx, sty, marker='o')

boundary = [(0, h * j) for j in range(1, N + 1)] + [(1., h * j) for j in range(1, N + 1)]
ax.scatter(*zip(*boundary), marker='s')

initial = [(h * i, 0) for i in range(0, M + 1)]
ax.scatter(*zip(*initial), marker='D')

stencil_labels = ['$(x_k, t_{i+1})$', '$(x_{k -1}, t_{i})$', '$(x_{k}, t_{i})$', '$(x_{k + 1}, t_{i})$']
for i in range(len(stencil)):
    x, y = stencil[i]
    ax.annotate(stencil_labels[i], xy=stencil[i], xytext=(x + 0.01, y + (- 0.05 if (i > 0) else 0.03)))

for i in range(1, len(stencil)):
    x, y = stencil[i]
    xx, yy = stencil[0]
    dx = xx - x
    dy = yy - y
    ax.annotate("", xy=(xx - dx * 0.1, yy - dy * 0.1), xytext=(x + dx * 0.1, y + dy * 0.1),
                arrowprops=dict(arrowstyle="-|>", color='black'))

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')

ax.set_xticks([h * i for i in range(0, M + 1)])
ax.set_xticklabels(["$x_{}$".format(i + 1) for i in range(M+1)])
ax.set_yticks([h * i for i in range(0, N + 1)])
ax.set_yticklabels(["$t_{}$".format(i) for i in range(N+1)])

ax.spines['bottom'].set_bounds(-0.01, 1.01)
ax.spines['left'].set_bounds(-0.01, N * h + 0.01)
ax.set_xlim((0 - 0.05, 1 + 0.05))
ax.set_ylim((0 - 0.05, N * h + 0.05))
ax.set_xlabel('$x$', rotation=0)
ax.xaxis.set_label_coords(1.0, -0.025)
ax.set_ylabel('$t$', rotation=0)
ax.yaxis.set_label_coords(-0.025, 1.0)

plt.savefig('../img/fdm.svg')


import faust
from taxi_rides_model import TaxiRide

app = faust.App('faust.stream', broker='kafka://localhost:9092')
topic = app.topic('yellow_taxi_ride.json', value_type=TaxiRide)

@app.agent(topic)
async def start_reading(records):
    async for record in records:
        print(record)

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


import os
import sys
import json
import spotipy
import webbrowser
import spotipy.util as util
from json.decoder import JSONDecodeError
from json.decoder import JSONDecodeError
from collections import Counter
from dotenv import load_dotenv

load_dotenv()

# Get username from terminal
username = sys.argv[1]
scope = 'user-top-read'

def get_top_genres(timeline, tracks=True):
    time_range, time_description = timeline
    top_genres = get_top_tracks(time_range) if tracks else get_top_artists(time_range)
    based = "Songs" if tracks else "Artists"
    print(f"Top Genres from the past {time_description} Based on {based} Listened to")
    for i, item in enumerate(top_genres.most_common(10)):
        print(i+1, item[0])
    print()

def get_top_tracks(time_range):
    top_tracks = Counter()
    results = sp.current_user_top_tracks(time_range=time_range, limit=50)
    for item in results['items']:
        artist_id = item['artists'][0]['id']
        artist = sp.artist(artist_id)
        top_tracks.update(artist['genres'])
    return top_tracks

def get_top_artists(time_range):
    top_artists = Counter()
    results = sp.current_user_top_artists(time_range=time_range, limit=50)
    for artist in results['items']:
        top_artists.update(artist['genres'])
    return top_artists

# Erase cache and prompt for user permission
try:
    token = util.prompt_for_user_token(username, scope) # add scope
except (AttributeError, JSONDecodeError):
    os.remove(f".cache-{username}")
    token = util.prompt_for_user_token(username, scope) # add scope

# Create our spotify object with permissions
sp = spotipy.Spotify(auth=token)
ranges = [('short_term', '4 Weeks'), ('medium_term', '6 Months'), ('long_term', 'Several Years')]
for rng in ranges:
    get_top_genres(rng)


import json
import re

import requests
from bs4 import BeautifulSoup

url = 'https://s.search.bilibili110.com/cate/search?main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=183&page=1&pagesize=20&jsonp=jsonp&time_from=20180602&time_to=20180609&_=1528510256558'
url = 'http://news.163.com/rank/'
url = 'http://list.iqiyi.com/www/1/-------------11-7-1-iqiyi--.html'
url = 'http://www.iqiyi.com/v_19rrh4moi8.html'
# ip = getRandomOneIP()
# proxies = {"http": "http://198.15.135.26:8090", "https": "https://198.15.135.26:8090", }
html = requests.get(url).text
# soup = BeautifulSoup(html, "html.parser")
# print(soup.prettify())
msgStr = re.search(":page-info='(.*?)'", html).group(1)
msgStr2 = re.search(":video-info='(.*?)'", html).group(1)
jsonObj = json.loads(msgStr)
jsonObj2 = json.loads(msgStr2)
print(jsonObj2)


from django.contrib import admin
from django.urls import path, include

admin.site.site_header = 'ProjectTracker Admin'
admin.site.site_title = 'ProjectTracker admin'
admin.site.index_title = 'ProjectTracker Administration'
admin.site.site_title = 'ProjectTracker Administration'
admin.site.site_header = 'ProjectTracker Admin Login'

urlpatterns = [
    path('admin/docs/', include('django.contrib.admindocs.urls')),
    path('admin/', admin.site.urls),
    path('', include('app.urls')),
]


#!/usr/bin/env python3
from botocore.exceptions import ClientError

import argparse
import os
import json

module_info = {
    # Name of the module (should be the same as the filename)
    'name': 'ecs__enum_task_def',

    # Name and any other notes about the author
    'author': 'Nicholas Spagnola of Rhino Security Labs',

    # Category of the module. Make sure the name matches an existing category.
    'category': 'ENUM',

    # One liner description of the module functionality. This shows up when a user searches for modules.
    'one_liner': 'Parses task definitions from ECS tasks',

    # Description about what the module does and how it works
    'description': 'This module will pull task definitions for ECS clusters.',

    # A list of AWS services that the module utilizes during its execution
    'services': ['ECS'],

    # For prerequisite modules, try and see if any existing modules return the data that is required for your module before writing that code yourself, that way, session data can stay separated and modular.
    'prerequisite_modules': ['ecs__enum'],

    # Module arguments to autocomplete when the user hits tab
    'arguments_to_autocomplete': ['--task_definitions'],
}

parser = argparse.ArgumentParser(add_help=False, description=module_info['description'])
parser.add_argument('--task_definitions',required=False,default=None,help='A comma separated list of ECS task defintion ARNs (arn:aws:ecs:us-east-1:273486424706:task-definition/first-run-task-definition:latest)')

def main(args, pacu_main):
    session = session = pacu_main.get_active_session()

    ###### Don't modify these. They can be removed if you are not using the function.
    args = parser.parse_args(args)
    print = pacu_main.print
    fetch_data = pacu_main.fetch_data
    ######

    task_definitions = []
    summary_data = {"task_definitions": 0}

    if args.task_definitions is not None:
        for task_def in args.task_definitions.split(','):
            task_definitions.append({
                'Task Defintion ID': task_def
            })
    else:
        if fetch_data(['ECS', 'TaskDefinitions'], module_info['prerequisite_modules'][0], '--taskdef') is False:
            print('Pre-req module not run successfully. Exiting...')
            return None
        task_definitions = session.ECS['TaskDefinitions']

    if not os.path.exists('sessions/{}/downloads/ecs_task_def_data/'.format(session.name)):
        os.makedirs('sessions/{}/downloads/ecs_task_def_data/'.format(session.name))

    if task_definitions:
        print("Targeting {} task definition(s)...".format(len(task_definitions)))

        for task_def in task_definitions:
            region = task_def.split(':')[3]
            client = pacu_main.get_boto3_client('ecs', region)

            try:
                task_def_data = client.describe_task_definition(
                    taskDefinition=task_def,
                )
            except ClientError as error:
                code = error.response['Error']['Code']
                print('FAILURE: ')
                if code == 'AccessDenied':
                    print('  Access denied to DescribeTaskDefinition.')
                    print('Skipping the rest of the task definitions...')
                    break
                else:
                    print('  ' + code)

            formatted_data = "{}@{}\n{}\n\n".format(
                task_def,
                region,
                json.dumps(task_def_data['taskDefinition'], indent=4)
            )

            with open('sessions/{}/downloads/ecs_task_def_data/all_task_def.txt'.format(session.name), 'a+') as data_file:
                data_file.write(formatted_data)
            with open('sessions/{}/downloads/ecs_task_def_data/{}.txt'.format(session.name, task_def.split('/')[1].split(':')[0]), 'w+') as data_file:
                data_file.write(formatted_data.replace('\\t', '\t').replace('\\n', '\n').rstrip())
            summary_data['task_definitions'] += 1

    return summary_data

def summary(data, pacu_main):
    session = pacu_main.get_active_session()

    output = '  ECS Task Definition Data for {} task definition(s) was written to ./sessions/{}/downloads/ecs_task_def_data/'.format(data['task_definitions'],session.name)
    return output


# Escribe una función llamada palindromoRecursivo. Esta función recibe como parámetro
# un string. La función se encarga de retornar True si el string es un palindromo
# False de lo contrario.

def palindromoRecursivo( texto ):
    if len( texto ) <= 1:
        return True
    else:
        if texto[0] != texto[ len(texto) - 1 ]:
            return False
        else:
            return palindromoRecursivo( texto[1:-1] )

print( palindromoRecursivo( "radar" ) )


import json

CAMINHO = "Python/Aulas/Udemy 2/Introdução à Programação Orientada a Objetos em Python - POO (Classes)/"

class Pessoa:

    def __init__(self, nome, idade):
        self.nome = nome
        self.idade = idade

p1 = Pessoa('João', 33)
p2 = Pessoa('Helena', 21)
p3 = Pessoa('Joana', 11)

def fazer_dump():
    with open(CAMINHO + "classe.json", "w") as arquivo:

        bd = [p1.__dict__, vars(p2), p3.__dict__]
        json.dump(bd, arquivo, ensure_ascii=False, indent=2)

if __name__ == "__main__":              # O módulo for o main na execução:
    fazer_dump()

Aulas/Udemy 2/Introdução à Programação Orientada a Objetos em Python - POO (Classes)/06 - Salvar classe em JSON - a.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec  7 16:08:29 2020

@author: pi
"""
import numpy as np
import matplotlib.pyplot as plt
import math
#from matplotlib.figure import Figure

data = np.loadtxt('dats_test.txt')
#plt.plot(data)
#plt.show

data_norm=data/max(data)

data_norm_list = np.ndarray.tolist(data_norm)
data_norm_list = data_norm_list[:math.floor(len(data_norm_list)/2)]# taking every second point in data, due to ADC sampling nature
data1=np.asarray(data_norm_list,dtype=float)
# constants
c = 3E8 #(m/s) speed of light
FS = 44100 #needs to be matched with ADC sampling rate

#radar parameters
Tp = 0.250 #(s) observation time
N = Tp*FS # number of of samples per observation
fc = 2437E6 #(Hz) Center frequency (fixed)

#invertion due to HW
s=data1#[i * 1 for i in data1]

#doppler vs. time data creation
X=round(len(s)/N)-1
sif =np.zeros(X)
for ii in range(1,X):
    idx1=1+(ii-1)*N
    idx2=ii*N
    sif = np.array([sif, s[idx1:idx2]])

##subtract the average DC term here and zeropad
#sif=np.array(sif)-np.mean(s)
#zpad= 8*N/2

###create doppler vs. time plot:
#v = np.fft.ifft(sif,int(zpad),1)
#v = 20 * np.log10(abs(v)); #calculate v in dB
#v = v[0:141,:]
##data=v
#
###plot
#plt.imshow(v, aspect='auto')
#plt.colorbar()


from flask import request
from database.db import db
from bson import ObjectId
from functions.crypto import decrypt
from datetime import datetime

def history():
    id = request.args.get('id')
    if not id:
        return returnAll()
    item = db['history'].find_one({'_id': ObjectId(id)}, {"_id": 0})
    return item

def returnAll():
    token = request.headers.get('token')
    if not token:
        return {"status": 400, "message": "Token not provided"}, 400
    id = decrypt(token, str(request.remote_addr))
    # print(id)
    items = db['history'].find({'user_id': id}, {"_id": 0})
    return sorted(list(items), key=sort_key, reverse=True)

def sort_key(sublist):
    date_str, time_str = sublist['date'], sublist['time']
    return datetime.strptime(date_str, '%d-%m-%Y'), datetime.strptime(time_str, '%H:%M:%S')


from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
import keras
from scipy.stats import wasserstein_distance
import joblib

class CustomSaver(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        self.model.save("model_CNN_{}".format(epoch))

dataset = read_csv('TEST_25_01_2020_OIL_GAS_WITH_EUA.csv', delimiter=",", engine='python')
dataset = dataset.drop_duplicates()
values = dataset.values

n_steps = len(dataset.columns)-1

scaler = MinMaxScaler(feature_range=(0, 1))
values = scaler.fit_transform(values)

# --------

n_train_hours = int(len(dataset)*0.8)
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]

X, y = train[:, :-1], train[:, -1]
X_test, y_test = test[:, :-1], test[:, -1]

# --------

# reshape from [samples, timesteps] into [samples, timesteps, features]
n_features = 1
X = X.reshape((X.shape[0], X.shape[1], n_features))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], n_features))

saver = CustomSaver()

# define model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(n_steps, n_features)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(1))

joblib.dump(scaler, 'Scaler.pkl')

model.compile(optimizer='Adam', loss='mae')
# fit model
history = model.fit(X, y, callbacks=[saver], epochs=500, batch_size=64, validation_data=(X_test, y_test), verbose=2)

pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

# Prediction

yhat = model.predict(X_test)
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1]))

inv_yhat = concatenate((yhat, X_test[:, :]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:, 0]

y_test = y_test.reshape((len(y_test), 1))
inv_y = concatenate((y_test, X_test[:, :]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:, 0]

print(inv_y)

pyplot.plot(inv_yhat)
pyplot.plot(inv_y)
pyplot.legend(['Forecast', 'Actual Values'])
pyplot.show()

rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.10f' % rmse)
print(str(history.history['val_loss'][-1]))
print("")
print("DISTANCE: ", wasserstein_distance(inv_yhat, inv_y))


from .handler import JupytexprHandler
from notebook.utils import url_path_join

def _load_jupyter_server_extension(serverapp):
    """
    This function is called when the extension is loaded.
    """

    web_app = serverapp.web_app
    host_pattern = '.*$'
    route_pattern = url_path_join(web_app.settings['base_url'], '/jupytexpr/(.*)')
    web_app.add_handlers(host_pattern, [(route_pattern, JupytexprHandler)])

def _jupyter_server_extension_paths():
    """
    Returns a list of dictionaries with metadata describing
    where to find the `_load_jupyter_server_extension` function.
    """
    return [
        {
            "module": "jupytexpr"
        }
    ]


from bs4 import BeautifulSoup, Comment
import os
SOURCE="/Users/john/Documents/诡秘之主/"
DEST="tmp/gm/"

def process_html(filename):
	soup=BeautifulSoup(open(SOURCE+filename,encoding="gbk"))
	content=soup.select("#content")
	title=soup.select("title")
	print(len(s))
	if len(s) != 1:
		print(s)

process_html('1000039.html')
#for root, dirs, files in os.walk(SOURCE):
#    for filename in files:
#        print(filename)