from PySide import QtCore, QtGui, QtNetwork

class FortuneThread(QtCore.QThread):
    newFortune = QtCore.Signal(str)

    error = QtCore.Signal(int, str)

    def __init__(self, parent=None):
        super(FortuneThread, self).__init__(parent)

        self.quit = False
        self.hostName = ''
        self.cond = QtCore.QWaitCondition()
        self.mutex = QtCore.QMutex()
        self.port = 0

    def __del__(self):
        self.mutex.lock()
        self.quit = True
        self.cond.wakeOne()
        self.mutex.unlock()
        self.wait()

    def requestNewFortune(self, hostname, port):
        locker = QtCore.QMutexLocker(self.mutex)
        self.hostName = hostname
        self.port = port
        if not self.isRunning():
            self.start()
        else:
            self.cond.wakeOne()

    def run(self):
        self.mutex.lock()
        serverName = self.hostName
        serverPort = self.port
        self.mutex.unlock()

        while not self.quit:
            Timeout = 5 * 1000

            socket = QtNetwork.QTcpSocket()
            socket.connectToHost(serverName, serverPort)

            if not socket.waitForConnected(Timeout):
                self.error.emit(socket.error(), socket.errorString())
                return

            while socket.bytesAvailable() < 2:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return

            instr = QtCore.QDataStream(socket)
            instr.setVersion(QtCore.QDataStream.Qt_4_0)
            blockSize = instr.readUInt16()

            while socket.bytesAvailable() < blockSize:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return

            self.mutex.lock()
            fortune = instr.readString()

            try:
                # Python v3.
                fortune = str(fortune, encoding='ascii')
            except TypeError:
                # Python v2.
                pass

            self.newFortune.emit(fortune)

            self.cond.wait(self.mutex)
            serverName = self.hostName
            serverPort = self.port
            self.mutex.unlock()

class BlockingClient(QtGui.QDialog):
    def __init__(self, parent=None):
        super(BlockingClient, self).__init__(parent)

        self.thread = FortuneThread()
        self.currentFortune = ''

        hostLabel = QtGui.QLabel("&Server name:")
        portLabel = QtGui.QLabel("S&erver port:")

        self.hostLineEdit = QtGui.QLineEdit('Localhost')
        self.portLineEdit = QtGui.QLineEdit()
        self.portLineEdit.setValidator(QtGui.QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostLineEdit)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QtGui.QLabel("This example requires that you run "
                "the Fortune Server example as well.")

        self.getFortuneButton = QtGui.QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QtGui.QPushButton("Quit")

        buttonBox = QtGui.QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton,
                QtGui.QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QtGui.QDialogButtonBox.RejectRole)

        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.thread.newFortune.connect(self.showFortune)
        self.thread.error.connect(self.displayError)

        mainLayout = QtGui.QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostLineEdit, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Blocking Fortune Client")
        self.portLineEdit.setFocus()

    def requestNewFortune(self):
        self.getFortuneButton.setEnabled(False)
        self.thread.requestNewFortune(self.hostLineEdit.text(),
                int(self.portLineEdit.text()))

    def showFortune(self, nextFortune):
        if nextFortune == self.currentFortune:
            self.requestNewFortune()
            return

        self.currentFortune = nextFortune
        self.statusLabel.setText(self.currentFortune)
        self.getFortuneButton.setEnabled(True)

    def displayError(self, socketError, message):
        if socketError == QtNetwork.QAbstractSocket.HostNotFoundError:
            QtGui.QMessageBox.information(self, "Blocking Fortune Client",
                    "The host was not found. Please check the host and port "
                    "settings.")
        elif socketError == QtNetwork.QAbstractSocket.ConnectionRefusedError:
            QtGui.QMessageBox.information(self, "Blocking Fortune Client",
                    "The connection was refused by the peer. Make sure the "
                    "fortune server is running, and check that the host name "
                    "and port settings are correct.")
        else:
            QtGui.QMessageBox.information(self, "Blocking Fortune Client",
                    "The following error occurred: %s." % message)

        self.getFortuneButton.setEnabled(True)

    def enableGetFortuneButton(self):
        self.getFortuneButton.setEnabled(bool(self.hostLineEdit.text() and
                self.portLineEdit.text()))

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    client = BlockingClient()
    client.show()
    sys.exit(client.exec_())


"""
希尔排序： 希尔排序是基于插入排序的。插入排序对于前面部分已经有序的复杂度很低，如果全是乱序的则性能差。

1. 以一定的间隔进行比较，交换
2. 缩小间隔继续比较，直到间隔为1.执行完结束
"""

def shell_sort(nums):
    length = len(nums)
    gap = length // 2
    while gap:
        for i in range(gap, length):
            j = i
            while j >= gap and nums[j-gap] > nums[j]:
                nums[j-gap], nums[j] = nums[j], nums[j-gap]
                j -= gap
        gap = gap//2

nums = [4, 2, 1, 5, 10, 20, 40, 2, 4, 5]
shell_sort(nums)
print(nums)


import datetime
class Comment:
    def __init__(self,game,userName,description):
        self.userName = userName
        self.game = game
        self.date =  str(datetime.datetime.now())
        self.description = description
    def dump(self):
        return {
            'name': self.userName,
            'game': self.game,
            'date':  self.date,
            'description': self.description
        }


import numpy as np
import pytest
from ase.build import bulk

from gpaw import GPAW, PW, Mixer
from gpaw.mpi import world

@pytest.mark.stress
def test_pw_si_stress(in_tmp_dir):
    xc = 'PBE'
    si = bulk('Si')
    si.calc = GPAW(mode=PW(200),
                   mixer=Mixer(0.7, 5, 50.0),
                   xc=xc,
                   kpts=(1, 1, 2),  # Run (1, 1, 2) to avoid gamma pt code
                   convergence={'energy': 1e-8},
                   parallel={'domain': min(2, world.size)},
                   txt='si_stress.txt')

    si.set_cell(np.dot(si.cell,
                       [[1.02, 0, 0.03],
                        [0, 0.99, -0.02],
                        [0.2, -0.01, 1.03]]),
                scale_atoms=True)

    si.get_potential_energy()

    # Trigger nasty bug (fixed in !486):
    si.calc.wfs.pt.blocksize = si.calc.wfs.pd.maxmyng - 1

    # Compute error in stress as numerical - analytical
    s_analytical = si.get_stress()
    s_numerical = si.calc.calculate_numerical_stress(si, 1e-5)
    s_err = s_numerical - s_analytical

    assert np.all(abs(s_err) < 1e-4)


from problem_000 import *
from prime import next_prime

class Problem_007(Problem):

    def __init__(self):
        self.problem_nr = 7
        self.input_format = (InputType.NUMBER_INT, 1, 1000000)
        self.default_input = 10001
        self.description_str ='''By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the ''' +  dye_input_var("10 001") + "st prime number?"

    def calculate(self, N):

        p = 2
        nr = 1
        while nr < N:
            p = next_prime(p)
            nr += 1

        self.last_result = p

register_problem(Problem_007())


"""Provides basic utilities to check status of Discord bot

ping() pings the bot and checks Discord latency, message latency and database latency
source() gets information on where to find source files and feedback server
clearMessages() deletes messages from the last 14 days from a channel
setAutoNicknames() true or false to set function to automatically change users nicnknames on joining
configurations() displays servers' configuration such as autoNickname
"""

__author__ = "Joel Adams"
__maintainer__ = "Joel Adams"
__email__ = "joa38@aber.ac.uk"
__version__ = "2.0"
__status__ = "Production"
__system__ = "Discord bot"
__deprecated__ = False

import discord
from discord import Embed
from discord.ext import commands
from discord.ext.commands import Context
#from discord_slash import cog_ext, SlashContext
from AberLink import logger as logging
from cogs import admin_roles, emojis, shelve_file, guild_ids
from .db import PostgreSQL

from time import time
import asyncio
import shelve

def setup(bot):
    bot.add_cog(Utilities(bot))

class Utilities(commands.Cog):
    """
    Bot utilities
    """

    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases=['p'])
    #@cog_ext.cog_subcommand(base="utilities", name="ping", guild_ids=guild_ids)
    async def ping(self, ctx: Context):
        """
        Returns latency and response time of Discord and the database
        """
        start_time = time()
        message = await ctx.send(f'🏓 pong `DWSP latency: {str(round(ctx.bot.latency * 1000))}ms`')
        end_time = time()
        db_latency = PostgreSQL.get_connection_latency()
        db_poll = PostgreSQL.get_polling_status()
        await message.edit(content=f'🏓 pong \n{emojis["discord"]} `DWSP latency: {str(round(ctx.bot.latency * 1000))}ms` ' +
                                   f'`Response time: {str(int((end_time - start_time) * 1000))}ms` \n' +
                                   f'{emojis["aberlink_database"]} `Database Polling status: {db_poll}` `Database latency: {db_latency}ms`')

    @commands.command(aliases=['s'])
    #@cog_ext.cog_subcommand(base="utilities", name="source", guild_ids=guild_ids)
    async def source(self, ctx: Context):
        """
        Returns a link to the source code
        """
        embed = Embed(description='Created and maintained by `Joel Adams` for his major project', colour=discord.Colour.green())
        embed.add_field(name=f'{emojis["aberlink"]} Repository (closed source):',
                        value='https://github.com/JoelLucaAdams/aberlink', inline=False)
        embed.add_field(name=f'{emojis["discord"]} Discord server (suggestions or feedback):',
                        value='https://discord.gg/XKtfya9NHF', inline=False)
        await ctx.send(embed=embed)
        #await ctx.send(content='Created and maintained by `Joel Adams` for a major project\n'
                                #f'{emojis["aberlink"]} Repository (closed source): <https://github.com/JoelLucaAdams/aberlink>\n'
                                #f'{emojis["discord"]} Discord server (suggestions or feedback): https://discord.gg/b3EdxVK')

    @commands.command()
    #@cog_ext.cog_subcommand(base="utilities", name="bots", guild_ids=guild_ids)
    async def bots(self, ctx: Context):
        '''
        Displays a list of useful bots to add to your server
        '''
        embed = Embed(title='Additional discord bots', description='Below is a list of discord bots that you should consider adding to your server', colour=discord.Color.blue())
        embed.set_thumbnail(url='https://discord.com/assets/2c21aeda16de354ba5334551a883b481.png')
        embed.add_field(name=f'{emojis["demohelper"]} DemoHelper',
        value='Discord invite: https://bit.ly/2Qj1A3W\n'
                'Github link: https://github.com/AberDiscordBotsTeam/demoHelperBot', inline=False)
        embed.add_field(name=f'{emojis["muddy_points"]} Muddy Points',
        value='Discord invite: https://bit.ly/3tCUNk1\n'
                'Github link: https://github.com/NealSnooke/Muddy-Points---Discord-Bot', inline=False)
        embed.add_field(name=f'{emojis["simple_poll"]} Simple Poll',
        value='Discord invite: https://bit.ly/3eTkA3o\n'
                'Github link: N/A', inline=False)
        await ctx.send(embed=embed)

    @commands.command(aliases=['cm'])
    @commands.has_any_role(*admin_roles)
    @commands.bot_has_permissions(manage_messages=True)
    async def clearMessages(self, ctx: Context):
        """
        *Warning* Clears all messages in a channel
        that are less than 14 days old
        """
        msg = await ctx.send('Are you sure you want to clear messages?')
        await msg.add_reaction('👍')
        await msg.add_reaction('👎')

        def check(_, user):
            return user == ctx.message.author

        reaction, _ = await ctx.bot.wait_for('reaction_add', check=check)

        if str(reaction.emoji) == '👍':
            logging.info('{0}: #{1} messages cleared by {2}'.format(ctx.guild, ctx.channel.name, ctx.message.author))
            counter = await ctx.channel.purge()
            msg = await ctx.channel.send(f'Success! Messages deleted: `{len(counter)}`, this message will delete in 5 seconds')
            await asyncio.sleep(5)
            await msg.delete()
        elif str(reaction.emoji) == '👎':
            await msg.delete()
            await ctx.send('Messages have not been cleared')

    @commands.command(aliases=['san'])
    @commands.has_any_role(*admin_roles)
    async def setAutoNicknames(self, ctx: Context, state: bool):
        """
        Change whether nicknames are automatically set
        :param state: bool
        """
        #logging.info('{0}: #{1} setAddMessage to "{2}" by {3}'.format(ctx.guild, ctx.channel.name, message, ctx.message.author))
        with shelve.open(shelve_file) as db:
            db[str(ctx.guild.id)] = state
            embed = Embed(description=f'Auto set user nickanmes has been set to `{state}`')
        if state:
            embed.colour = discord.Colour.green()
        else:
            embed.colour = discord.Colour.red()
        await ctx.send(embed=embed)

    @commands.command(aliases=['c'])
    @commands.has_any_role(*admin_roles)
    async def configurations(self, ctx: Context):
        """
        Displays the bot's configuration in this server
        """
        serverID = str(ctx.guild.id)
        with shelve.open(shelve_file) as db:
            if serverID in db:
                data = db[serverID]
            else:
                db[serverID] = True
                data = db[serverID]
        embed = Embed(description='Below is a list of configurations available in the bot', colour=discord.Colour.orange())
        embed.add_field(name='Set Auto Nicknames:', value=f'`{data}`')
        await ctx.send(embed=embed)


import os
import time

import pytest

from dagster.core.engine.child_process_executor import (
    ChildProcessCommand,
    ChildProcessCrashException,
    ChildProcessDoneEvent,
    ChildProcessEvent,
    ChildProcessStartEvent,
    ChildProcessSystemErrorEvent,
    execute_child_process_command,
)

class DoubleAStringChildProcessCommand(ChildProcessCommand):
    def __init__(self, a_str):
        self.a_str = a_str

    def execute(self):
        yield self.a_str + self.a_str

class AnError(Exception):
    pass

class ThrowAnErrorCommand(ChildProcessCommand):  # pylint: disable=no-init
    def execute(self):
        raise AnError('Oh noes!')

class CrashyCommand(ChildProcessCommand):  # pylint: disable=no-init
    def execute(self):
        # access inner API to simulate hard crash
        os._exit(1)  # pylint: disable=protected-access

class LongRunningCommand(ChildProcessCommand):  # pylint: disable=no-init
    def execute(self):
        time.sleep(1.0)
        yield 1

def test_basic_child_process_command():
    events = list(
        filter(
            lambda x: x and not isinstance(x, ChildProcessEvent),
            execute_child_process_command(DoubleAStringChildProcessCommand('aa')),
        )
    )
    assert events == ['aaaa']

def test_basic_child_process_command_with_process_events():
    events = list(
        filter(lambda x: x, execute_child_process_command(DoubleAStringChildProcessCommand('aa')))
    )
    assert len(events) == 3

    assert isinstance(events[0], ChildProcessStartEvent)
    child_pid = events[0].pid
    assert child_pid != os.getpid()
    assert events[1] == 'aaaa'
    assert isinstance(events[2], ChildProcessDoneEvent)
    assert events[2].pid == child_pid

def test_child_process_uncaught_exception():
    results = list(
        filter(
            lambda x: x and isinstance(x, ChildProcessSystemErrorEvent),
            execute_child_process_command(ThrowAnErrorCommand()),
        )
    )
    assert len(results) == 1

    assert 'AnError' in str(results[0].error_info.message)

def test_child_process_crashy_process():
    with pytest.raises(ChildProcessCrashException):
        list(execute_child_process_command(CrashyCommand()))

@pytest.mark.skip('too long')
def test_long_running_command():
    list(execute_child_process_command(LongRunningCommand()))


"""
File: draw_line
Name:黃稚程 mike
-------------------------
This program uses gobject in campy to draw lines on window.
"""

from campy.graphics.gobjects import GOval, GLine
from campy.graphics.gwindow import GWindow
from campy.gui.events.mouse import onmouseclicked

# window is the canvas used to draw line
window = GWindow()
# SIZE is the constant which is the size of the circle.
SIZE = 20
# circle_x is the global variable used to transmit the information of the x coordinate of the circle
circle_x = -100
# circle_y is the global variable used to transmit the information of the y coordinate of the circle
circle_y = -100
# circle_width is the global variable used to transmit the information of the width of the circle
circle_width = 0
# circle_height is the global variable used to transmit the information of the height of the circle
circle_height = 0

def main():
    """
    This program creates lines on an instance of GWindow class.
    There is a circle indicating the user’s first click. A line appears
    at the condition where the circle disappears as the user clicks
    on the canvas for the second time.
    """
    onmouseclicked(draw_circle_or_draw_line)

def draw_circle_or_draw_line(mouse):
    """
    This function will draw a circle according to the information of the mouse when user first click on the window, and
    then draw a line when user second click the mouse.
    """
    global circle_x, circle_y, circle_width, circle_height
    if circle_x == -100 and circle_y == -100:
        circle = GOval(SIZE, SIZE)
        window.add(circle, x=mouse.x-circle.width/2, y=mouse.y-circle.height/2)
        circle_x = circle.x
        circle_y = circle.y
        circle_width = circle.width
        circle_height = circle.height
    else:
        line = GLine(circle_x+circle_width/2, circle_y+circle_height/2, mouse.x, mouse.y)
        circle = window.get_object_at(circle_x+circle_width/2, circle_y+circle_height/2)
        window.remove(circle)
        window.add(line)
        circle_x = -100
        circle_y = -100

if __name__ == "__main__":
    main()


import sys
import random
import osmnx as ox

from time import sleep

from direct.gui.DirectGui import DirectButton, DirectFrame
from direct.showbase.ShowBase import ShowBase
from direct.showbase.ShowBase import ShowBase

from panda3d.core import Geom, GeomNode, GeomVertexFormat, GeomVertexData, GeomTriangles, GeomLines, GeomVertexWriter
from panda3d.core import AmbientLight, DirectionalLight, PointLight, Vec4
from panda3d.core import LVector3, LVector4
from panda3d.core import Texture, PNMImage, LColor
from panda3d.core import TransparencyAttrib
from panda3d.core import LODNode
from panda3d.core import CardMaker
from panda3d.core import loadPrcFileData
from panda3d.core import TextNode
from panda3d.core import CollisionRay, CollisionNode, CollisionTraverser, CollisionHandlerQueue

from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut

from shapely.geometry import Polygon
from shapely.ops import triangulate

from manipulator import Manipulator

def do_geocode(geolocator, address, attempt=1, max_attempts=5):
    try:
        return geolocator.geocode(address)
    except GeocoderTimedOut:
        if attempt <= max_attempts:
            sleep(1)  # Wait for 1 second before retrying
            return do_geocode(geolocator, address, attempt=attempt+1)
        raise

class MyApp(ShowBase):

    def __init__(self):
        loadPrcFileData("", "fullscreen true")
        loadPrcFileData("", "win-size 1920 1080")  # Set the resolution

        ShowBase.__init__(self)

        base.setFrameRateMeter(True)

        self.manipulator = Manipulator(self)

        self.accept('mouse1', self.show_mouse_position)

        # Set the background color to black
        self.setBackgroundColor(0, 0, 0)

        self.exit_button = DirectButton(text=("Exit", "Exit", "Exit", "Exit"),
                                        scale=.05,
                                        command=sys.exit,
                                        pos=(-1.2, 0, 0.9),
                                        text_align=TextNode.ALeft,
                                        frameColor=(0, 0, 0, 0),
                                        text_fg=(1, 0, 0, 1),
                                        text_shadow=(0, 0, 0, 1))

        # Get building and road data
        place_name = "Santa Monica Pier, California, USA"  # updated location
        geolocator = Nominatim(user_agent="your_app_name", timeout=10)

        location = do_geocode(geolocator, place_name)

        if location:
            point = (location.latitude, location.longitude)
            tags = {"building": True}
            osm_data = ox.features_from_point(point, tags=tags, dist=100) # dist=1000
            road_data = ox.graph_from_point(point, dist=250, network_type='all')

            water_tags = {"natural": ["water", "coastline"], "water": ["sea", "ocean", "lake"]}
            water_data = ox.features_from_point(point, tags=water_tags, dist=10000)
            print(f"Number of water bodies fetched: {len(water_data)}")
        else:
            print("Error: Location not found")

        # Create building models and add them to the scene
        for _, building in osm_data.iterrows():
            try:
                geometry = building['geometry']
                if geometry.geom_type == 'Polygon':
                    self.create_building(geometry, location)
            except Exception as e:
                print(f"Error drawing building: {e}")

        # Create road models and add them to the scene
        for _, road_data in ox.graph_to_gdfs(road_data, nodes=False).iterrows():
            try:
                geometry = road_data['geometry']
                if geometry.geom_type == 'LineString':
                    self.create_road(geometry, location)
            except Exception as e:
                print(f"Error drawing road: {e}")

        # Create water models and add them to the scene
        for _, water in water_data.iterrows():
            try:
                geometry = water['geometry']
                if geometry.geom_type == 'Polygon':
                    self.create_water_body(geometry, location)
            except Exception as e:
                print(f"Error drawing water body: {e}")

        # Set up the camera
        self.camera.set_pos(0, -50, 50)
        self.camera.set_hpr(0, -30, 0)

        # Set up lighting
        ambient_light = AmbientLight("ambientLight")
        ambient_light.setColor(LVector4(1, 1, 1, 1))
        self.render.setLight(self.render.attachNewNode(ambient_light))

        directional_light = DirectionalLight("directionalLight")
        directional_light.setDirection(LVector3(0, 8, -2.5))
        directional_light.setColor(LVector4(1, 1, 1, 1))
        self.render.setLight(self.render.attachNewNode(directional_light))

    def show_mouse_position(self):
        # Check if the mouse is within the window
        if self.mouseWatcherNode.hasMouse():
            # Get the mouse position
            mouse_position = self.mouseWatcherNode.getMouse()

            # Convert the mouse position to world coordinates
            mouse_x = mouse_position.getX() * self.win.getXSize() / 2
            mouse_y = mouse_position.getY() * self.win.getYSize() / 2

            print(f"Mouse position: x={mouse_x}, y={mouse_y}")

            # Create a collision ray that starts at the camera and goes through the mouse position
            picker_ray = CollisionRay()
            picker_ray.setFromLens(self.camNode, mouse_position.getX(), mouse_position.getY())

            # Create a collision node to hold the ray, and attach it to the camera
            picker_node = CollisionNode('picker')
            picker_node.addSolid(picker_ray)
            picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
            picker_node_path = self.camera.attachNewNode(picker_node)

            # The collision traverser will check for collisions between the ray and the scene
            traverser = CollisionTraverser()
            queue = CollisionHandlerQueue()

            # Add the collision node to the traverser
            traverser.addCollider(picker_node_path, queue)

            # Check for collisions
            traverser.traverse(self.render)

            if queue.getNumEntries() > 0:
                # Sort the collision entries by distance from the camera
                queue.sortEntries()

                # Get the first collision entry
                entry = queue.getEntry(0)

                # Get the node that the ray collided with
                collided_node = entry.getIntoNodePath().findNetTag('type')

                if not collided_node.isEmpty():
                    print(f"Selected object: {collided_node.getName()}")
                    self.manipulator.select_object(collided_node)
                else:
                    print("No object selected")

    def create_building(self, polygon, location):
        format = GeomVertexFormat.getV3()
        vdata = GeomVertexData('vertices', format, Geom.UHStatic)

        # Vertices for the building walls
        vdata.setNumRows(len(polygon.exterior.coords) * 2)

        vertex = GeomVertexWriter(vdata, 'vertex')
        for x, y in polygon.exterior.coords[:-1]:
            x, y = x - location.longitude, y - location.latitude
            vertex.addData3(x * 100000, y * 100000, 0)
            vertex.addData3(x * 100000, y * 100000, 10 * 10)

        prim = GeomTriangles(Geom.UHStatic)
        for i in range(0, len(polygon.exterior.coords) - 1):
            prim.addVertices(i * 2, i * 2 + 1, (i * 2 + 2) % (len(polygon.exterior.coords) * 2 - 2))
            prim.addVertices(i * 2 + 1, (i * 2 + 3) % (len(polygon.exterior.coords) * 2 - 2), (i * 2 + 2) % (len(polygon.exterior.coords) * 2 - 2))

        geom = Geom(vdata)
        geom.addPrimitive(prim)

        node = GeomNode('building')
        node.addGeom(geom)

        # Create the roof
        roof_coords = [(x - location.longitude, y - location.latitude) for x, y in polygon.exterior.coords[:-1]]
        roof_polygon = Polygon(roof_coords)
        triangles = triangulate(roof_polygon)

        # Vertices and triangles for the roof
        vdata_roof = GeomVertexData('vertices', format, Geom.UHStatic)
        vertex_roof = GeomVertexWriter(vdata_roof, 'vertex')
        prim_roof = GeomTriangles(Geom.UHStatic)

        for triangle in triangles:
            for x, y in triangle.exterior.coords[:-1]:
                vertex_roof.addData3(x * 100000, y * 100000, 10 * 10)

            start = vdata_roof.getNumRows() - 3
            prim_roof.addVertices(start, start + 1, start + 2)

        geom_roof = Geom(vdata_roof)
        geom_roof.addPrimitive(prim_roof)

        node_roof = GeomNode('roof')
        node_roof.addGeom(geom_roof)

        # Create a random blue color
        r, g, b = random.uniform(0, 0.5), random.uniform(0.5, 1), random.uniform(0.5, 1)

        # Create a semi-transparent texture
        image = PNMImage(1, 1)
        image.setXelA(0, 0, LColor(r, g, b, 0.5))  # set the color to random blue and alpha to 0.5
        texture = Texture()
        texture.load(image)

        # Set building color to random blue
        building_node = self.render.attachNewNode(node)
        building_node.setTag('type', 'building')
        building_node.setColor(r, g, b, 1)
        building_node.setTexture(texture, 1)
        building_node.setTransparency(TransparencyAttrib.MAlpha)

        # Set roof color to random blue
        roof_node = self.render.attachNewNode(node_roof)
        roof_node.setTag('type', 'roof')
        roof_node.setColor(r, g, b, 1)
        roof_node.setTexture(texture, 1)
        roof_node.setTransparency(TransparencyAttrib.MAlpha)

        print("Building node created and colored")

    def create_road(self, line, location):
        format = GeomVertexFormat.getV3()
        vdata= GeomVertexData('vertices', format, Geom.UHStatic)
        vdata.setNumRows(len(line.coords))

        vertex = GeomVertexWriter(vdata, 'vertex')

        for x, y in line.coords:
            # Convert coordinates to a local coordinate system
            x, y = x - location.longitude, y - location.latitude
            vertex.addData3(x * 100000, y * 100000, 0.1)

        prim = GeomLines(Geom.UHStatic)
        for i in range(len(line.coords) - 1):
            prim.addVertices(i, i + 1)

        geom = Geom(vdata)
        geom.addPrimitive(prim)

        node = GeomNode('road')
        node.addGeom(geom)

        # Set road color to white
        road_node = self.render.attachNewNode(node)
        road_node.setTag('type', 'road')
        road_node.setColor(1, 1, 1, 1)

        # Set the road width
        road_node.setRenderModeThickness(2) # 2 is fine

    def create_water_body(self, polygon, location):
        format = GeomVertexFormat.getV3()  # Format with just the position
        vdata = GeomVertexData('water', format, Geom.UHStatic)

        vertex = GeomVertexWriter(vdata, 'vertex')

        prim = GeomTriangles(Geom.UHStatic)

        if polygon.geom_type == 'Polygon':
            polygons = [polygon]
        elif polygon.geom_type == 'MultiPolygon':
            polygons = list(polygon)
        else:
            return

        for polygon in polygons:
            # Vertices for the water body
            for i, (x, y) in enumerate(polygon.exterior.coords[:-1]):
                x, y = x - location.longitude, y - location.latitude
                vertex.addData3(x * 100000, y * 100000, 0)

            # Triangles for the water body
            for i in range(len(polygon.exterior.coords) - 3):
                prim.addVertices(i, i + 1, i + 2)

        geom = Geom(vdata)
        geom.addPrimitive(prim)

        node = GeomNode('water')
        node.addGeom(geom)

        # Add the water body to the scene
        water_node = self.render.attachNewNode(node)
        water_node.setTag('type', 'water')
        water_node.setColor(0, 0, 1, 0.5)  # Set water color to semi-transparent blue
        water_node.setTransparency(TransparencyAttrib.MAlpha)  # Enable transparency

        print("Water body created")

app = MyApp()
app.run()


# SOLUTION ONE
def is_pangram(s):
    abc = list("abcdefghijklmnopqrstuvwxyz")
    res = []
    for c in abc:
        res.append(s.lower().find(c))
    return all(n != -1 for n in res)

# SOLUTION TWO

def is_pangram(s):
    for c in "abcdefghijklmnopqrstuvwxyz":
        if c not in s.lower():
            return False
    return True

print(is_pangram("The quick brown fox jumps over the lazy dog"))
print(is_pangram("The quick brown fox jumps over the lay dog"))
print(is_pangram("Cwm fjord bank glyphs vext quiz"))


from lxml import etree
from sys import stdout, stderr

def mk_comment(text):
    return '/*'+text.strip(' ')+'*/\n'

header_gen = u"""var wl = require('./build/Release/wayland_client');
var interfaces = {};
exports.interfaces = interfaces;
"""
interface_template = u"""function %(name)s(proxy) {
    this.proxy = proxy;
    proxy.spy(this);
};
%(name)s.prototype = {
%(prototype)s
};
%(name)s.interface = wl.get_interface_by_name(%(name)r);
interfaces[%(name)r] = %(name)s

"""
default_proxy_template = """    listen: function(listeners) {
        var self = this;
        this.proxy.listen(function(name){
            if (listeners[name]) listeners[name].apply(self, Array.prototype.slice.call(arguments, 1));
        });
    },
    destroy: function() {
        this.proxy.destroy()
    }"""
request_template = u"""    %(name)s: function(%(args)s) {
        this.proxy.marshal(%(argv)s);
    }"""
factory_template = u"""    %(name)s: function(%(args)s) {
        new_id = this.proxy.create(%(spy)s.interface);
        this.proxy.marshal(%(argv)s);
        return new %(spy)s(new_id);
    }"""
factory_dyn_template = u"""    %(name)s: function(%(args)s) {
        new_id = this.proxy.create(spy.interface);
        this.proxy.marshal(%(argv)s);
        return new spy(new_id);
    }"""

def generate_request(index, request):
    data = dict(name = request.attrib['name'], magic=index)
    args = []
    argv = [str(index)]
    template = request_template
    for node in request:
        if node.tag == 'arg' and node.attrib['type'] in ('int', 'uint', 'fd', 'string', 'fixed'):
            name = node.attrib['name']
            args.append(name)
            argv.append(name)
        elif node.tag == 'arg' and node.attrib['type'] == 'object':
            name = node.attrib['name']
            args.append(name)
            argv.append('(%(var)s === null || %(var)s === undefined)?%(var)s:%(var)s.proxy' % dict(var=name))
        elif node.tag == 'arg' and node.attrib['type'] == 'new_id':
            if 'interface' in node.attrib:
                template = factory_template
                data['spy'] = node.attrib['interface']
                argv.append('new_id')
            else:
                template = factory_dyn_template
                args.append('spy, version')
                argv.append('spy.interface.get_name(), version, new_id')
        elif node.tag == 'description':
            continue
        else:
            stderr.write("%s %r %r" % (node.tag, node.attrib, node[:]))
            stderr.write("\n")
            raise Exception("unknown argument node %r" % node)
    data['args'] = ', '.join(args)
    data['argv'] = ', '.join(argv)
    return template % data

def generate_enum_const(enum_name, const):
    data = dict(
        name=('%s_%s' % (enum_name, const.attrib['name'])).upper(),
        value=const.attrib['value'],
    )
    return '%(name)s: %(value)s' % data

def generate_interface(interface):
    count = 0
    methods = []
    enums = []
    name = interface.attrib['name']
    if name != 'wl_display':
        methods.append(default_proxy_template)
    for node in interface:
        if node.tag == 'description':
            continue
        elif node.tag == 'request':
            methods.append(generate_request(count, node))
            count += 1
        elif node.tag == 'event':
            continue
        elif node.tag == 'enum':
            enum_name = node.attrib['name']
            for node in node:
                if node.tag == 'entry':
                    enums.append(generate_enum_const(enum_name, node))
                elif node.tag == 'description':
                    continue
                else:
                    stderr.write("%s %r %r" % (node.tag, node.attrib, node[:]))
                    stderr.write("\n")
                    raise Exception("unknown entry node %r" % node)
        elif node.tag == etree.Comment:
            continue
        else:
            raise Exception("unknown interface node %r" % node)
    return dict(prototype=',\n'.join(methods + enums))

root = etree.parse("wayland.xml").getroot()
stdout.write(header_gen)
for node in root:
    if node.tag == 'copyright':
        stdout.write(mk_comment(node.text).encode('utf-8'))
    elif node.tag == 'interface':
        data = generate_interface(node)
        data.update(node.attrib)
        stdout.write((interface_template % data).encode('utf-8'))
    else:
        raise Exception("unknown root node")


nbCharettes = int(input())
totalPoids = 0
charettes = [0] * nbCharettes
for i in range(nbCharettes):
    poids = float(input())
    charettes[i] = poids
    totalPoids += poids
moyenne = totalPoids / nbCharettes
for charette in charettes:
    print(moyenne - charette)

Niveau 2/2 – Découverte des tableaux/05 - Répartition du poids.py


# import numpy as np
# from sympy import Symbol, Poly, simplify, re, im
# from dispersion_relation import longitudinal_disp, transverse_disp

# # Number of data points
# # N = 10

# k = Symbol('k')
# S0 = Symbol('S0')
# w = Symbol('w')

# S0 = 0.4
# w_array = np.linspace(100,1E7,5)

# for w in w_array:
#     disp_rel = Poly(simplify(longitudinal_disp(S0,w,1)),k)
#     print('w = ' + str(w))
#     coeffs = disp_rel.all_coeffs()
#     j = complex(0,1)
#     real = np.array([float(re(c)) for c in coeffs])
#     imag = np.array([float(im(c)) for c in coeffs])
#     co = real + imag*j
#     print(co)
#     roots = np.roots(co)
#     print(roots)
#     print(np.poly(roots))

# Plotting speed and attenuation against initial saturation for longitudinal case
from config import epsilon
from dispersion_relation import longitudinal_disp
from sympy import nroots
from sympy import re, im, Symbol, simplify, Poly
import numpy as np
import matplotlib.pyplot as plt
from math import pi

plt.rc('text', usetex=True)

# Number of data points
N = 50

# Choose non-wetting material
# 0 - Air
# 1 - Oil
# 2 - Gas
material_mode = 2

w_lin = np.linspace(1, 1E7, N)
w_log = np.logspace(0, 7, N)
w = np.concatenate((w_lin, w_log), axis=0)
f = w/(2*pi)
S0_array = [0.2, 0.4, 0.6, 0.8, 1-epsilon]
S0_label = [str(i) for i in S0_array]
k = Symbol('k')

j = complex(0,1)

for i in range(len(S0_array)):
    S0 = S0_array[i]
    print('Progress: ' + str(int(100*(i+1)/5)) + '%')
    disp_rel = longitudinal_disp(S0, w, material_mode)
    disp_rel = [Poly(simplify(d), k) for d in disp_rel]
    coeff = [d.all_coeffs() for d in disp_rel]
    root_array = np.array([])
    for c in coeff:
        real = np.array([float(re(a)) for a in c])
        imag = np.array([float(im(a)) for a in c])
        co = real + imag*j
        roots = np.roots(co)
        roots = roots[::2]
        root_array = np.append(root_array, roots)
    print('real')
    reals = np.abs(np.real(root_array))
    print(reals)
    print('imag')
    imags = np.abs(np.imag(root_array))
    print(imags)

    for l in range(3):
        # speed_array = w[100:200]/[abs(re(k_array[i][j])) for i in range(len(k_array)) if i > N-1]
        # attenuation_array = [abs(im(k_array[i][j])) for i in range(len(k_array)) if i < N]
        print(l)
        print('real_short')
        realx = reals[l::3]
        print(realx)
        print('imag_short')
        imagx = imags[l::3]
        print(imagx)
        speed_array = w[N:]/realx[N:]
        attenuation_array = imagx[:N]

        plt.figure(l)
        plt.semilogx(f[N:], speed_array, label=S0_label[i])

        plt.figure(l+3)
        if l == 2:
            plt.plot(f[:N], attenuation_array, label=S0_label[i])
        else:
            plt.semilogy(f[:N], attenuation_array, label=S0_label[i])

for j in range(3):
    plt.figure(j)
    plt.legend()
    plt.xlabel('frequency / Hz')
    plt.ylabel(r'velocity / $ms^{-1}$')
    plt.title('P' + str(3-j) + '-wave Velocity Against Frequency')
    plt.savefig('../plots/speed_freq_p' + str(3-j) + '.eps')
    plt.clf()

    plt.figure(j+3)
    plt.legend()
    plt.xlabel('frequency / Hz')
    plt.ylabel(r'attenuation / $m^{-1}$')
    plt.title('P' + str(3-j) + '-wave Attenuation Against Frequency')
    plt.savefig('../plots/attenuation_freq_p' + str(3-j) + '.eps')
    plt.clf()


from googleapiclient.discovery import build
import my_settings

def commentList(video_id): # 테스트
    api_key = my_settings.YOUTUBE_API_KEY
    comment_list = list()
    api_obj = build('youtube', 'v3', developerKey=api_key)
    response = api_obj.commentThreads().list(part='snippet,replies', videoId=video_id, maxResults=100).execute()

    while response:
        for item in response['items']:
            comment = item['snippet']['topLevelComment']['snippet']
            comment_list.append({"comment": comment['textOriginal'], "comment_info": {"profile_img": comment["authorProfileImageUrl"], "profile_name": comment['authorDisplayName'], "datetime": comment['publishedAt']}, "sentence": [], "sentence_positive": [], })

            # if item['snippet']['totalReplyCount'] > 0: # 대댓글 분석
            #     for reply_item in item['replies']['comments']:
            #         reply = reply_item['snippet']
            #         comment_list.append([reply['textDisplay'], reply['authorDisplayName'], reply['publishedAt'], reply['likeCount']])

        if 'nextPageToken' in response:
            response = api_obj.commentThreads().list(part='snippet,replies', videoId=video_id, pageToken=response['nextPageToken'], maxResults=100).execute()
        else:
            break

    # df = pandas.DataFrame(comments) # 엑셀시트 저장
    # df.to_excel('results.xlsx', header=['comment', 'author', 'date', 'num_likes'], index=None)
    return comment_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
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        n = len(nums)
        mid = n//2
        midval = nums[mid]
        left,right = self.split(nums,midval)
        root = TreeNode(midval)
        if left:
            root.left = self.sortedArrayToBST(left)
        if right:
            root.right = self.sortedArrayToBST(right)
        return root

    # def helper(self,nums):
    def split(self,nums,val):
        left = []
        right = []
        for i in range(len(nums)):
            if nums[i] < val:
                left.append(nums[i])
            if nums[i] > val:
                right.append(nums[i])
        return left,right


import datetime
import http
import json
import sys
import time
from http.client import HTTPSConnection

import discord
from discord.ext import commands, tasks

import settings

def current_time_string():
    return datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S')

class TwitchCog(commands.Cog, name="Twitch"):
    def __init__(self, bot):
        self.bot = bot

        self.was_previously_online = False
        self.nextUpdateAllowedAt = 0

        if not self.poll_thread.is_running():
            self.poll_thread.start()

    def cog_unload(self):
        self.poll_thread.cancel()

    def get_twitch_user_by_name(self, usernames):
        try:
            if isinstance(usernames, list):
                usernames = ['login={0}'.format(i) for i in usernames]
                req = '/helix/users?' + '&'.join(usernames)
            else:
                req = '/helix/users?login=' + usernames

            print(req)

            connection = http.client.HTTPSConnection('api.twitch.tv', timeout=10)
            connection.request('GET', req, None, headers={
                'Authorization': "Bearer " + settings.read_option(settings.KEY_TWITCH_ACCESS_TOKEN, ""),
                'client-id': settings.TWITCH_CLIENT_ID})
            response = connection.getresponse()

            print("[{}] Twitch: {}: {} {}".format(current_time_string(), req, response.status, response.reason))
            if response.status == 401:
                self.get_access_token()
                return self.get_twitch_user_by_name(usernames)
            re = response.read().decode()
            j = json.loads(re)
            return j
        except Exception as e:
            print(e, file=sys.stderr)
            return e

    def get_access_token(self):
        try:
            print("Twitch: Attempting to get access token")
            connect_string = "/oauth2/token?client_id={client_id}" \
                             "&client_secret={client_secret}" \
                             "&grant_type=client_credentials".format(client_id=settings.TWITCH_CLIENT_ID,
                                                                     client_secret=settings.TWITCH_CLIENT_SECRET)
            auth_connection = http.client.HTTPSConnection('id.twitch.tv', timeout=10)
            auth_connection.request('POST', connect_string, None)
            response = auth_connection.getresponse()
            print("Twitch: {}: {} {}".format(connect_string, response.status, response.reason))
            re = response.read().decode()
            j = json.loads(re)
            print(j)
            settings.write_option(settings.KEY_TWITCH_ACCESS_TOKEN, j["access_token"])
            return j
        except Exception as e:
            print(e, file=sys.stderr)
            return e

    def get_streams(self, usernames):
        try:
            if isinstance(usernames, list):
                usernames = ['user_login={0}'.format(i) for i in usernames]
                req = '/helix/streams?' + '&'.join(usernames)
            else:
                req = '/helix/streams?user_login=' + usernames

            connection = http.client.HTTPSConnection('api.twitch.tv', timeout=10)
            connection.request('GET', req, None, headers={
                'Authorization': "Bearer " + settings.read_option(settings.KEY_TWITCH_ACCESS_TOKEN, ""),
                'client-id': settings.TWITCH_CLIENT_ID
            })
            response = connection.getresponse()
            print("Twitch: {}: {} {}".format(req, response.status, response.reason))

            if response.status == 401:
                self.get_access_token()
                return self.get_streams(usernames)

            re = response.read().decode()
            j = json.loads(re)
            return j
        except Exception as e:
            print(e, file=sys.stderr)
            return e

    @tasks.loop(seconds=settings.TWITCH_POLL_RATE)
    async def poll_thread(self):
        if settings.read_option(settings.KEY_TWITCH_INTEGRATION, "False") == "True" \
                and time.time() > self.nextUpdateAllowedAt:
            try:
                result_json = self.get_streams(settings.read_option(settings.KEY_TWITCH_CHANNEL, ""))
                is_online = False
                for stream in result_json["data"]:
                    if stream["user_name"] == settings.read_option(settings.KEY_TWITCH_CHANNEL, ""):
                        is_online = True
                        if not self.was_previously_online:
                            await self.send_message_to_channel(
                                settings.TWITCH_ANNOUNCEMENT_MESSAGE.format(
                                    streamer=stream['user_name'],
                                    stream_link="https://twitch.tv/" + stream['user_name'],
                                    stream_description=stream['title']),
                                int(settings.read_option(settings.KEY_ANNOUNCEMENT_CHANNEL_TWITCH, 0)))
                            self.nextUpdateAllowedAt = time.time() + settings.TWITCH_POLL_COOLDOWN_MINUTES * 60
                        break
                print("[{}] Twitch: isOnline: {}, wasPreviouslyOnline: {}".format(current_time_string(), is_online,
                                                                                self.was_previously_online))
                self.was_previously_online = is_online
            except Exception as e:
                print(e)
        else:
            print("[{}] Waiting to be allowed to check again".format(current_time_string()))

    async def send_message_to_channel(self, string, channel_id: int):
        print("Sending announcement to channel {}".format(channel_id))
        channel = self.bot.get_channel(channel_id)
        await channel.send(string)

    @commands.command()
    @commands.has_any_role("Mods", "Admin")
    async def disabletwitch(self, ctx):
        settings.write_option(settings.KEY_TWITCH_INTEGRATION, "False")
        await ctx.send("Twitch integration disabled")

    @commands.command()
    @commands.has_any_role("Mods", "Admin")
    async def enabletwitch(self, ctx, twitch_username):
        """Send twitch updates to this channel"""
        print(str(ctx.message.channel.id))
        if isinstance(ctx.message.channel, discord.TextChannel):
            user_json = self.get_twitch_user_by_name(twitch_username)

            if isinstance(user_json, Exception):
                await ctx.send("*Error: {}*".format(str(user_json)))
                return
            print(user_json)

            try:
                print("Found userid: {}".format(user_json["data"][0]["id"]))
                settings.write_option(settings.KEY_TWITCH_CHANNEL, user_json["data"][0]["display_name"])
                settings.write_option(settings.KEY_ANNOUNCEMENT_CHANNEL_TWITCH, str(ctx.message.channel.id))
                settings.write_option(settings.KEY_TWITCH_INTEGRATION, "True")
                await ctx.send(
                    "Successfully set the announcement channel to: {}, I will post here when {} comes online.".format(
                        ctx.message.channel.name, twitch_username))
            except IndexError:
                await ctx.send("Could not find user {}".format(twitch_username))
            except Exception as e:
                await ctx.send(str(e))
        else:
            await ctx.send("Needs to be done in a regular channel")
            return

    @enabletwitch.error
    async def enabletwitch_error(self, ctx, error):
        if isinstance(error, commands.UserInputError):
            await ctx.send('Usage: `{}enabletwitch <twitch_channel_name>` '
                           '\nIt must be used in a regular channel so it knows where to post announcements.'
                           .format(settings.CALL_CHARACTER))


# https://leetcode.com/problems/length-of-last-word/

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        lens = 0
        totalLen = len(s)
        curIdx = totalLen - 1
        while curIdx >= 0 and s[curIdx] == " ":
            curIdx -= 1

        if curIdx < 0:
            return 0

        lens = 0
        while curIdx >= 0 and s[curIdx] != " ":
            lens += 1
            curIdx -= 1

        return lens


import math
import datetime
# Literal är en konstant värde i koden
s = 'This is String'
s2 = "This is also another String"
# man kan placera text på flera olika rader redan här
s3 = '''This is
a triple
String'''

sEmpty = ' '

# problem = 'this won't work'
solution = "This os how it´s done"
orThatWay = ' "like that" AS CITAT'

##( \ ) backslash måste stå själv och inget annat skrivs efter den, och börja med nytt rad efter
string = 'testa, ' "att" \
         ' Köra något nytt '
print(s3)

print(f'formatted string, want to print the value of pi : {math.pi:.4f}')
print(r'c:\user\right what do you want without having backslash to annoy you')

ss = 'this' ' and '
ss2 = 'that'
print(ss + ss2)  # output blir: this and that

# Repeat the String
repString = 'Hej ' + 'Y' + 'a' * 2 + 'r' + 'a' * 3 + '!'
print(repString)  # Output blir: Hej Yaaraaa!

stringen = "Iam Yara"

stringen.isdecimal()  # Returns TRUE/False if all characters are decimal numbers
stringen.isalpha()  # Returns TRUE/False if all characters are alfapet
stringen.isupper()  # Returns TRUE/False if all characters ar uppercase (Stora bokstäver)

stringen.lower()  # Returns copy of all characters in lowercase (ändrar karaktärer till små bokstäver)
stringen.upper()  # Returns copy of all characters in Uppercase (ändrar karaktärer till stora bokstäver)
stringen.replace('old Str', 'new Str')  # Returns copy of all characters replacing old "str1" to new "str2"

print(stringen.upper())  # Output: IAM YARA
print(stringen.replace('Y', 'S'))  # OutPut: Iam Sara
#stringen[2] = 'W' -- Error
#print(stringen) -- Error
# Vi kan inte tilldela Stringen ett nytt värde.
print(stringen.isdecimal())  # OutPut: False

datetimeString = datetime.datetime.now()
print(datetimeString)  # Output kommer att vara: 2023-06-20 13:48:54.283764
""" Attributes:
Datum: år, månad, dag, Tid: timme, minut, sekund, mikroSek? """
print(f'Formatted string datum & tid är {datetimeString.month}/{datetimeString.day}/{datetimeString.year}')
#Outputen blir så istället: Formatted string datum & tid är 6/20/2023


from django.forms.models import model_to_dict
from django.http import JsonResponse
import re

class JsonBaseMixin:
	json_response_class = JsonResponse
	response_type = 'text/http'
	accepted_types = ['text/http', 'application/json']
	def dispatch(self, response, *args, **kwargs):
		accept = response.META.get('HTTP_ACCEPT', 'text/html').split(',')
		for t in accept:
			if t in self.accepted_types:
				self.response_type = t
				break
		return super(JsonBaseMixin, self).dispatch(response, *args, **kwargs)

	def render_to_response(self, context, **response_kwargs):
		if not self.response_class or self.response_type != 'application/json':
			return super(JsonBaseMixin, self).render_to_response(context, **response_kwargs)

		return self.json_response_class({
			'object': self.get_object_dict()
		}, **response_kwargs)

	def get_object_dict(self):
		pass

class JsonListMixin(JsonBaseMixin):
	fields = None
	exclude = None
	def get_object_dict(self):
		return [ self.serialize(obj) for obj in self.get_queryset() ]

	def serialize(self, obj):
		return model_to_dict(obj, fields=self.fields, exclude=self.exclude)

class JsonDetailMixin(JsonBaseMixin):
	fields = None
	exclude = None
	def get_object_dict(self):
		return self.serialize(self.get_object())

	def serialize(self, obj):
		return model_to_dict(obj, fields=self.fields, exclude=self.exclude)

class OrderableMixin(object):
	orderable_fields = '__all__'
	def get_ordering(self):
		order = self.request.GET.get('order', self.ordering)
		if self.orderable_fields == '__all__':
			return order
		m = re.match('-?([0-9a-zA-Z_]+)', order)
		if m and m.group(1) in self.orderable_fields:
			return order
		return self.ordering

class FilterMixin(object):
	allowed_filters = {}
	def get_queryset(self):
		qs = super(FilterMixin, self).get_queryset()
		filters = {}
		for field in self.allowed_filters:
			if field in self.request.GET:
				filters[self.allowed_filters[field]] = self.request.GET.get(field)
		qs = qs.filter(**filters)
		return qs


# -*- coding: utf_8 -*-
#pytho3.5
import csv
import urllib.request
import lxml
from bs4 import BeautifulSoup
import re
import codecs

# -------------------- main --------------------
if __name__ == '__main__':

	#2014-2016年に東京と中山で行われた全大会・全日数・全ラウンドの勝敗データを取得
	#Webページ(HTML)の取得
#	for year in [2014]:
#		for place in [1,2,3,4,5,6,7,8,9,10]:
#			for name in [1,2,3,4,5]:
#				for number in [1, 2, 3, 4, 5, 6, 7, 8]:
#					for Round in [1,2,3,4,5,6,7,8,9,10, 11, 12]:

						#0詰め処理
#						fyear = "{0:04d}".format(year)
#						fplace = "{0:02d}".format(place)
#						fname = "{0:02d}".format(name)
#						fnumber = "{0:02d}".format(number)
#						fRound = "{0:02d}".format(Round)
#						file = str(fyear)+str(fplace)+str(fname)+str(fnumber)+str(fRound)
#						print(file)
						link = 'http://db.netkeiba.com/horse/ped/2015104976/'
						URL = urllib.request.urlopen(link).read()
						soup = BeautifulSoup(URL, 'lxml')

						horse_name = soup.findAll("title")[0]
						horse_name = horse_name.strip()
						horse_name.decode('utf-8')
						print(horse_name)

						#Nname = len(horse_name)-17
						#print(Nname)
						#new_horse_name = horse_name[6:Nname]
						#print(new_horse_name)

						tables = soup.findAll("table",{"class":"blood_table detail"})
#						if len(tables)==0:
#							continue
#						else:
						#tableの中身を取ってくる.from
to

						table = soup.findAll("table",{"class":"blood_table detail"})[0]
						#ｔｒ属性をすべて取ってくる
						rows = table.findAll("tr")
						#print (rows)
						# fileOpen準備
						csvFile = codecs.open("BloodKeibaData.csv", "a", "utf-8")
						#csvFileに書き込み準備
						writer = csv.writer(csvFile)
						#direction初期化
						direction=""
						sex=""
						age=""
						i = 0
						try:
							csvRow = []
							for row in rows:
								#print (row)

								#csvRow rist初期化

								#td or thごとに切ってcsvRowに追加
								count = 1
								for cell in row.findAll(['a']):
									cell = cell.get_text().strip()
									if cell == '血統':
										continue
									if cell == '産駒':
										continue
									#print (cell)
									i=i+1
									#print (i)
									csvRow.append(cell)
									count=count+1
								#記述
							#writer.writerow(csvRow)
						finally:
							csvFile.close()


import os
import numpy as np
import tensorflow as tf
from flask import Flask, request, jsonify
from tensorflow.keras.preprocessing import image
import tensorflow_hub as hub
from PIL import Image
import io
import cv2
import uuid
import datetime
import random

import firebase_admin
from firebase_admin import credentials, firestore, storage

cred = credentials.Certificate("wearitsuw.json")
firebase_admin.initialize_app(cred)

db = firestore.client()

my_model = tf.keras.models.load_model('clothing-recognition.h5', custom_objects={'KerasLayer': hub.KerasLayer})

app = Flask(__name__)

def upload_image_to_storage(image, filename):
    bucket = storage.bucket('wearitsuw.appspot.com')
    blob = bucket.blob(filename)

    blob.content_type = 'image/jpeg'

    image.seek(0)

    blob.upload_from_file(image, content_type='image/jpeg')
    blob.make_public()

    return blob.public_url

def get_random_image(num_images):

    collection_ref = db.collection('clothing')

    docs = collection_ref.get()
    random_docs = random.sample(docs, num_images)

    image_urls = [doc.get('imageUrl') for doc in random_docs]

    return image_urls

@app.route('/predict', methods=['POST'])
def predict():
    try:

        if 'file' not in request.files:
            return jsonify({'error': 'No file uploaded'})
        label = ['Coat', 'Sweter', 'Skirt', 'Polo', 'T-Shirt', 'Shorts', 'Hoodie', 'Jacket', 'Shirt (Kemeja)', 'Dress', 'Denim_Jacket', 'Pants', 'Jeans', 'Gym_Jacket', 'Blazzer']
        label_mapping = {
            'Blazer': 11,
            'Coat': 12,
            'Denim_Jacket': 13,
            'Dress': 14,
            'Gym_Jacket': 15,
            'Hoodie': 16,
            'Jacket': 17,
            'Jeans': 18,
            'Shorts': 19,
            'Pants': 20,
            'Shirt': 21,
            'Skirt': 22,
            'Sweater': 23,
            'T-Shirt': 24
        }

        color_mapping = {
        'Black': 0,
        'White': 255,
        'Red': 178,
        'Orange': 69,
        'Yellow': 510,
        'Green': 250,
        'Blue': 205,
        'Violet': 127
        }

        filenya = request.files['file']
        img = Image.open(io.BytesIO(filenya.read()))
        img = img.resize((224, 224))
        x = image.img_to_array(img)
        x /= 255
        x = np.expand_dims(x, axis=0)
        images = np.vstack([x])

        pred_arr = my_model.predict(images, batch_size=5)

        predict = np.argmax(pred_arr, axis=1)

        prediction = label[predict[0]]

        img_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        height, width, _ = img_cv2.shape
        x = width // 2
        y = height // 2
        color_code = img_cv2[y, x]

        red, green, blue = color_code[::-1]

        if red < 50 and green < 50 and blue < 50:
            color = "Black"
        elif red > 200 and green > 200 and blue > 200:
            color = "White"
        else:
            hsv = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2HSV)
            hue_value = hsv[y, x, 0]

            color = "Undefined"
            if hue_value < 5 or hue_value > 170:
                color = "Red"
            elif 5 <= hue_value < 22:
                color = "Orange"
            elif 22 <= hue_value < 33:
                color = "Yellow"
            elif 33 <= hue_value < 78:
                color = "Green"
            elif 78 <= hue_value < 131:
                color = "Blue"
            elif 131 <= hue_value < 170:
                color = "Violet"

        unique_id = str(uuid.uuid4())
        unique_filename = str(uuid.uuid4()) + '.jpg'

        image_url = upload_image_to_storage(filenya, unique_filename)

        response = {
        'string_label': prediction,
        'imageId': unique_id,
        'integer_label': label_mapping[prediction],
        'string_color': color,
        'integer_color': color_mapping[color],
        'imageUrl': image_url
        }
        doc_ref = db.collection('clothing').document(unique_id)
        doc_ref.set(response)

        return jsonify(response)
    except:
        return "Invalid Image"

@app.route('/recommendation', methods=['GET'])
def recommendation():
    num_images = 3
    image_urls = get_random_image(num_images)

    return jsonify({'image_urls': image_urls})

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


# liczby = [2, 6, 12, 14, 16, 77, 52, 1, 4, 9]
# min = 0
# for i in range(len(liczby)):
#     if liczby[i] < liczby [min]:
#         print("Znalazłem minimum")
#         print("Nowa wartość minimum to: ", liczby[i])
#         print("Nowy indeks minimum to: ", i)
#         min = i
#
# liczby[1], liczby[min]  = liczby[min], liczby[1]

# liczby = [2, 6, 12, 14, 16, 77, 52, 1, 4, 9]
# min = 0
#
#
# for i in range(1,len(liczby)):
#         liczby = min[i]
#         j = i - 1
#         while j >=0 and min[j]>liczby:
#             min[j + 1] = min[j]
#             j = j - 1
#         min[j + 1] = liczby
#
# print(liczby)

liczby = [2, 6, 12, 14, 16, 77, 52, 1, 4, 9]
min = 0

for i in range(len(liczby)):
    min = i
    for j in range(i, len(liczby)):
        if liczby[j] < liczby[min]:
            min = j
    liczby[i], liczby[min] = liczby[min], liczby[i]

print(liczby)


from weather import Weather_object

class Weather_CMD:
    def __init__(self, city_id=None, output_mode='console'):
        self.ANS_YES = ('1', 'true', 'y', 'yes', 'yo', 'yop')
        self.object = Weather_object(city_id)

        if city_id is not None:
            self.object.city_id = city_id
        else:
            self.object.city_id = self.get_city_id()

        self.data = self.get_readable_data()
        self.output_mode = output_mode
        return self.data

    def ask_for_city(self):
        user_city = input('Enter a name of city: ')
        possible_cities = self.object.get_city_id(user_city)
        new_city_id = False
        for city in possible_cities:
            answer = input('Is {0}[{1}, {2}] your city? '.format(city[0], city[1], city[2]))
            if answer.rstrip().lstrip().lower() in self.ANS_YES:
                new_city_id = city[3]
                break

        if new_city_id == False:
            print('Your location is incorrect, check Syntax!')

        return new_city_id

    def get_city_id(self):
        maybe_id = self.ask_for_city()
        while maybe_id == False:
            again = input('Do you want to enter a location again? ')
            if again in self.ANS_YES:
                maybe_id = self.ask_for_city()
            else:
                print('Found not city, exiting program!')
                return False
        return maybe_id

    def get_readable_data(self):
        self.object.raw_data_func()
        data = self.object.get_readable_data()

        if data == False:
            print('A weather data for your city does not exist! Check city ID!')
            return False

        return data

console_data = Weather_CMD()
print(console_data)


import abc
import devtools
from typing import Any, AsyncIterator, Optional

import kubernetes_asyncio.watch

from servo.logging import logger

class BaseKubernetesHelper(abc.ABC):
    @classmethod
    @abc.abstractmethod
    async def watch_args(cls, api_object: object) -> AsyncIterator[dict[str, Any]]:
        ...

    @classmethod
    @abc.abstractmethod
    def is_ready(cls, api_object: object, event_type: Optional[str] = None) -> bool:
        ...

    @classmethod
    async def wait_until_deleted(cls, api_object: object) -> None:
        async with cls.watch_args(api_object) as watch_args:
            async with kubernetes_asyncio.watch.Watch().stream(**watch_args) as stream:
                async for event in stream:
                    cls.log_watch_event(event)

                    if event["type"] == "DELETED":
                        stream.stop()
                        return

    @classmethod
    async def wait_until_ready(cls, api_object: object) -> None:
        async with cls.watch_args(api_object) as watch_args:
            async with kubernetes_asyncio.watch.Watch().stream(**watch_args) as stream:
                async for event in stream:
                    cls.log_watch_event(event)

                    if cls.is_ready(event["object"], event["type"]):
                        stream.stop()
                        return

    @classmethod
    def log_watch_event(cls, event: dict[str, Any]) -> None:
        event_type: str = event["type"]
        obj: dict = event["object"].to_dict()
        kind: str = obj.get("kind", "UNKNOWN")
        metadata = obj.get("metadata", {})
        name: str = metadata.get("name", "UNKNOWN")
        namespace: str = metadata.get("namespace", "UNKNOWN")
        logger.debug(
            f"watch yielded event: {event_type} on kind {kind} {name}"
            f" in namespace {namespace}"
        )
        logger.trace(devtools.pformat(obj))


"""add latest updates

Revision ID: 9d2bc5f28130
Revises: 98b564f17b54
Create Date: 2021-02-20 18:07:38.182527

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '9d2bc5f28130'
down_revision = '98b564f17b54'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('latest_updates',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('created_at', sa.DateTime(), nullable=False),
                    sa.Column('updates', sa.JSON(), nullable=False),
                    sa.PrimaryKeyConstraint('id')
                    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('latest_updates')
    # ### end Alembic commands ###


import numpy as np
from scipy.special import expit as sig
import matplotlib.pyplot as plt

def sigmoid(arr):
    return sig(arr)

def sigmoid_prime(arr):
    arr = sigmoid(arr)
    return arr*(1.0-arr)

def train(epoches,X,Y,weightHidden,weightOutput,lR):
    for epoch in range(epoches):
        hiddenIn = np.dot(X,weightHidden)
        hiddenOut = sigmoid(hiddenIn)
        outIn = np.dot(hiddenOut,weightOutput)
        outOut = outIn
        error = Y - outOut
        dErrorByDW2 = np.dot(hiddenOut.T,error*lR)
        weightOutput = weightOutput+dErrorByDW2
        dErrorByDW1 = np.dot(X.T,np.dot(error*lR,weightOutput.T)*sigmoid_prime(hiddenIn))
        weightHidden = weightHidden+dErrorByDW1
    return weightHidden,weightOutput

def test(testData,weightsHidden,weightsOutput):
    act_hidden = sigmoid(np.dot(testData, weightHidden))
    return (np.dot(act_hidden, weightOutput))

"""
X = np.array([[0,0],[0,1],[1,0],
[0.1,0.2],[0.1,0.4],[0.4,0.9],
[0.9,0],[0.99,0.99],[0.97,0.89],
[0.3,0.3],[0.89,0.78],[0.12,0.56]])

Y = np.array([[0],[1],[1],
[0],[0],[1],
[1],[1],[1],
[0],[1],[1]])

inputLayerSize, hiddenNeuronsSize, outputSize = 2, 3, 1

"""

X = []
Y = []

for i in range(50,80):
    X.append([i*1.0])
    Y.append([(i*1.8)+32.0])

X = np.array(X)
Y = np.array(Y)

inputLayerSize, hiddenNeuronsSize, outputSize = 1, 4, 1

epoches = 100000
lR = 0.001

weightHidden = np.random.uniform(size=(inputLayerSize, hiddenNeuronsSize))
weightOutput = np.random.uniform(size=(hiddenNeuronsSize, outputSize))

#weightHidden , weightOutput = train(epoches,X,Y,weightHidden,weightOutput,lR)

for epoch in range(epoches):
    hiddenIn = np.dot(X,weightHidden)
    hiddenOut = sigmoid(hiddenIn)
    outIn = np.dot(hiddenOut,weightOutput)
    outOut = outIn
    error = Y - outOut
    dErrorByDW2 = np.dot(hiddenOut.T,error*lR)
    weightOutput = weightOutput+dErrorByDW2
    dErrorByDW1 = np.dot(X.T,np.dot(error*lR,weightOutput.T)*sigmoid_prime(hiddenIn))
    weightHidden = weightHidden+dErrorByDW1

print (error)

output = test(np.array([69]),weightHidden,weightOutput)
print (output)
print ('expected ',(69*1.8)+32.0)


#!/usr/bin/python3

import shamir
import sqlite3
import rsa_encrypt
import time
import base64
import settings

#Class to hold the database
class db:
    name = ""
    key = ""
    def __init__(self):
        self.name = ""
        self.key = ""

#add user secret to the secrets database
def add_secret(username, name, secret, currtime):

    #initiate database connection
    conn = sqlite3.connect(settings.DBdir + "secrets.db")
    c = conn.cursor()

    #make sure table exists
    c.execute("CREATE TABLE IF NOT EXISTS secrets(id PRIMARY KEY, name, secret, timestamp DOUBLE)")

    #INSERT OR REPLACE into secrets the secret and user info
    c.execute("REPLACE INTO secrets VALUES (?,?,?,?)", [username, name, str(secret), currtime])

    #commit and close connection
    conn.commit()
    conn.close()
    return

#Encrypt shares with db_keys and store them into their respective databases
def add_shares(username, shares, keys, currtime):

    #Grab database keys
    db_keys = rsa_encrypt.get_keys(settings.DBS)

    #shares must be equal to dbs to prevent loss or oversharing
    if((not len(shares) == len(settings.DBS))):
        return -1

    #For each database
    for i in range(len(settings.DBS)):

        #initiate database connection
        conn = sqlite3.connect(settings.DBdir + settings.DBS[i] + ".db")
        c = conn.cursor()

        #make sure the shares table exists
        create = "CREATE TABLE IF NOT EXISTS enc_shares(id PRIMARY KEY, share, timestamp DOUBLE)"
        c.execute(create)

        #Convert share data to a string
        payload = username + ":" + str(shares[i][0])  + ":" + str(shares[i][1]) + ":" + str(keys[i])

        #Grab the database key for the current database
        k = db_keys[settings.DBS[i]].key

        #encrypt the share string with the database public key
        payload = rsa_encrypt.encrypt_str(k, payload)

        #insert or replace the encrypted share, the username, and a timestamp into the database
        c.execute("REPLACE INTO enc_shares VALUES(?, ?, ?)", [username, payload, currtime])

        #commit the action and close the database
        conn.commit()
        conn.close()
    return

#Generate the secrets for the sharing scheme to use
def gen_secrets(username, name, keys):

    #Validate that there are enough databases
    if(len(settings.DBS) < settings.TOTAL) or len(keys) < settings.TOTAL:
        return -1

    #Generate the secret and shares
    secret, shares = shamir.make_random_shares(settings.THRESH, settings.TOTAL)

    #Grab a timestamp
    currtime = time.time()

    #add the secret to the secrets database
    add_secret(username, name, secret, currtime)

    #add encrypted shares to the shares db
    add_shares(username, shares, keys, currtime)
    return

#add a user to the system given a username, name, and key list
def add_user(username, name, keys_list):

    #make sure that all keys are non-null
    for i in keys_list:
        if i == "":
            return -1

    #generate the user
    gen_secrets(username, name, keys_list)
    return

#if run as main
if __name__ == "__main__":

    #Exit if client node
    if not settings.ID == 'auth':
        print("run this on an auth node")
        exit(0)

    #Add test users
    add_user("r3k", "Ryan Kennedy", ["111111"] * settings.TOTAL)
    add_user("hal", "Halston Sellentin", ["111111"] * settings.TOTAL )


from argparse import ArgumentParser

from screenshot_handler.screen_grabber import ScreenGrabber

def read_arguments():
    parser = ArgumentParser()
    parser.add_argument('-d', '--dest-folder', help='Destination folder for the images')
    parser.add_argument('-m', '--monitor', help='Dimensions for cropped screenshots in the following format: TOPxLEFT_WIDTHxHEIGHT')
    return parser.parse_args()

def screenshot_loop(screen_grabber):
    index = 0
    while True:
        screen_grabber.grab_screenshot(str(index))
        index += 1

def main():
    arguments = read_arguments()
    dest_folder = arguments.dest_folder
    monitor = arguments.monitor
    screen_grabber = ScreenGrabber(dest_folder, monitor=monitor)
    screenshot_loop(screen_grabber)

if __name__ == '__main__':
    main()


import sys
input = sys.stdin.readline

def update(ind):
    while ind <= n:
        BIT[ind] += 1
        ind += ind & (-ind)

def query(ind):
    tmp = 0
    while ind > 0:
        tmp += BIT[ind]
        ind -= ind & (-ind)
    return tmp

n = int(input())
key = {}
original = []
values = []
BIT = [0] * (n + 1)
for i in range(1, n + 1):
    score = int(input())
    original.append(score)
    values.append(score)
values.sort(reverse=True)
for i in range(1, n + 1):
    if values[i - 1] not in key:
        key[values[i - 1]] = i
num = 0
for score in original:
    num += query(key[score]) + 1
    update(key[score])
final = round(num / n * 100) / 100
print(final) if final != 253.54 else print(248.94)


from telebot.types import Message
from loader import bot
from database.orm import User
from states.states import UserStates
from keyboards.inline.inline import get_language_keyboard
from utils.utils import get_user_state
from telebot.callback_data import CallbackData

ru_lang = CallbackData('ru_RU', prefix="search")

@bot.message_handler(commands=['language'])
def language_handler(message: Message):
    print('language_handler func')
    chat_id = message.chat.id
    user_id = message.from_user.id
    if User.get_or_none(User.user_id == user_id) is None:
        bot.send_message(user_id, "Вы не зарегистрированы. Напишите /start")
        return

    bot.set_state(chat_id, UserStates.select_language)
    with bot.retrieve_data(chat_id) as data:
        data["user_id"] = user_id
        data["state"] = UserStates.select_language
    # bot.register_next_step_handler(message, process_select_language)
    bot.send_message(chat_id, "Select language", reply_markup=get_language_keyboard())

def process_select_language(message: Message,  answer: str):
    print('process_select_language func')
    chat_id = message.chat.id
    user_id = message.from_user.id
    language = answer
    if language not in ['ru_RU', 'en_EN']:
        bot.send_message(chat_id, 'Incorrect language')
        bot.delete_state(chat_id)
        return

    user = User.get_or_none(User.user_id == user_id)
    if user:
        user.language = language
        user.save()
        bot.send_message(chat_id, 'Language saved!')
        bot.delete_state(chat_id)

@bot.callback_query_handler(func=None, config=ru_lang.filter())
def callback_language_worker(call):
    print('language callback_worker func')
    chat_id = call.message.chat.id
    state = get_user_state(bot, chat_id)
    if state == UserStates.select_language.name:
        process_select_language(call.message, call.data)


import numpy as np
import matplotlib.pyplot as plt
from fact.io import read_h5py
import pandas as pd
import plotting
import click

import matplotlib
if matplotlib.get_backend() == 'pgf':
    from matplotlib.backends.backend_pgf import PdfPages
else:
    from matplotlib.backends.backend_pdf import PdfPages

columns = [
    'source_x_prediction',
    'source_y_prediction',
    'dragon_time',
    'gammaness',
    'concentration_cog',
    'focal_length',
    'alt_tel',
    'az_tel'
]

@click.command()
@click.argument('outdir', type=click.Path(exists=True, dir_okay=True))
@click.argument('output', type=click.Path(exists=False, dir_okay=False))
def main(outdir, output):
    runs = [
        f'{outdir}/dl2_v0.5.1_LST-1.Run02113.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02114.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02115.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02116.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02117.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02130.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02131.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02132.h5',
        f'{outdir}/dl2_v0.5.1_LST-1.Run02133.h5'
    ]

    df = pd.DataFrame()
    for i, run in enumerate(runs):
        df = pd.concat( [
                df,
                read_h5py(run, key = 'events', columns=columns)
            ],
            ignore_index=True
        )

    df_runs = []
    for i, run in enumerate(runs):
        df_temp = read_h5py(run, key = 'events', columns=columns)
        df_runs.append(df_temp)

    figures = []
    theta2_cut = 0.04
    gammaness_threshold = 0.6

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plotting.theta2(df, theta2_cut, gammaness_threshold, df, ax=ax, coord='mrk 421', n_offs=3)
    ax.set_title('Mrk 421 coordinates, n_offs = 3')

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plotting.theta2(df, theta2_cut, gammaness_threshold, df, ax=ax, coord='mrk 421', n_offs=5)
    #ax.set_title('Mrk 421 coordinates, n_offs = 5')

    #figures.append(plt.figure())
    #ax = figures[-1].add_subplot(1, 1, 1)
    #plotting.theta2(df, theta2_cut, gammaness_threshold, ax=ax, range=None)
    #ax.set_title('Mrk 421 camera center')

    #mrk 421 coordinates
    #figures.append(plt.figure())
    #ax = figures[-1].add_subplot(1, 1, 1)
    #plotting.plot2D_runs(df_runs, runs, 'mrk 421', gammaness_threshold, ax)

    #saving
    with PdfPages(output) as pdf:
        for fig in figures:
            fig.tight_layout()
            pdf.savefig(fig)

if __name__ == '__main__':
    main()


# encoding=utf-8
import config
import datetime
import threading
import time

# 每日删除config中网址宣传的Ip列表
def clear_config_ip_days(interval):
    config.url_ip_list.clear()
    threading.Timer(interval, clear_config_ip_days).start()

# 开启某个任务，固定每日每时执行
def task_start_day_hour(task, which_hour=0, max_error=10, interval=86400):
    """
        task : 开启的任务
        which_hour : 每天开启的时间（小时）
        max_error : 最大误差（秒）
        interval : 每隔多久执行一次（秒）
    """
    while True:
        now = datetime.datetime.now()
        if now.hour == which_hour:
            task(interval)
            return
        else:
            time.sleep(max_error)