"""
Pollard rho based hash mining algorithm.
"""
from random import randint
from typing import Optional
import time
from blockchain.block import Block
from crypto.pollard_rho import func_g, func_h
from mining.pollard_rho_solution import PRSolution

class SimplePRMiner:
    """A pollard rho miner uses textbook mapping functions to search private key."""
    def __init__(self, block: Block, block_time=0):
        self.block = block
        self.block_time = block_time

    def header_hash(self, nonce: int) -> int:
        self.block.nonce = nonce
        # if the block is restored from database or json, the full Tx info may missing
        # WARNING: this part of code is insecure and it is not based on original design but only for
        # simplification of code.
        header_hash = self.block.current_block_hash if self.block.current_block_hash else self.block.hash_header()
        hash_val = int.from_bytes(header_hash, byteorder='little', signed=True) % self.block.public_key.p
        return hash_val

    def func_f(self, hash_i, y_i):
        """x_(i+1) = func_f(hash(x_i))"""
        base = self.block.public_key.g
        h = self.block.public_key.h
        p = self.block.public_key.p
        if hash_i % 3 == 2:
            return (h * y_i) % p
        elif hash_i % 3 == 0:
            return pow(y_i, 2, p)
        elif hash_i % 3 == 1:
            return base * y_i % p
        else:
            raise ValueError("Input value has error!")

    def func_g(self, a, n, hash_i):
        """Wrapper of classic mapping function for a."""
        p = self.block.public_key.p
        return func_g(a, n, p, hash_i)

    def func_h(self, b, n, hash_i):
        """Wrapper of classic mapping function for b."""
        p = self.block.public_key.p
        return func_h(b, n, p, hash_i)

    @staticmethod
    def _calculate_y(a, b, g, h, p):
        return (pow(g, a, p) * pow(h, b, p)) % p

    def mining(self) -> tuple[int, Optional[PRSolution]]:
        """
        Refer to section 3.6.3 of Handbook of Applied Cryptography
        Computes `x` = a mod n for the DLP base**x % p == y
        in the Group G = {0, 1, 2, ..., n}
        given that order `n` is a prime number.

        Returns:
            nonce and paired private key
        """
        pubkey = self.block.public_key
        n = (pubkey.p - 1) // 2

        a_i = randint(0, n)
        b_i = randint(0, n)
        a_2i = a_i
        b_2i = b_i

        y_i = self._calculate_y(a_i, b_i, pubkey.g, pubkey.h, pubkey.p)
        y_2i = y_i

        i = 1
        init_time = time.time()
        while i <= n and (time.time() - init_time) < self.block_time:
            # Single Step calculations
            hash_1i = self.header_hash(y_i)
            a_i = self.func_g(a_i, n, hash_1i)
            b_i = self.func_h(b_i, n, hash_1i)
            y_i = self.func_f(hash_1i, y_i)
            # print(f"y: {y_i}, a: {a_i}, b: {b_i}")
            # assert(y_i == self._calculate_y(a_i, b_i, pubkey.g, pubkey.h, pubkey.p))

            # Double Step calculations
            hash_2mi = self.header_hash(y_2i)
            a_2i = self.func_g(a_2i, n, hash_2mi)
            b_2i = self.func_h(b_2i, n, hash_2mi)
            y_2mi = self.func_f(hash_2mi, y_2i)
            hash_2i = self.header_hash(y_2mi)
            a_2i = self.func_g(a_2i, n, hash_2i)
            b_2i = self.func_h(b_2i, n, hash_2i)
            y_2i = self.func_f(hash_2i, y_2mi)
            # assert (y_2i == self._calculate_y(a_2i, b_2i, pubkey.g, pubkey.h, pubkey.p))

            if y_i == y_2i:
                # print("left side = ", (pow(pubkey.g, a_i, pubkey.p) * pow(pubkey.h, b_i, pubkey.p)) % pubkey.p)
                # print("right side = ", (pow(pubkey.g, a_2i, pubkey.p) * pow(pubkey.h, b_2i, pubkey.p)) % pubkey.p)
                solution = PRSolution(a_i, a_2i, b_i, b_2i, n)
                solution.pubkey = pubkey
                return y_2mi, solution
            else:
                i += 1
                continue
        # failed to find the solution and nonce, return none
        print("Cannot seal a new block within block time! Try again")
        return 0, None

class PRMiner(SimplePRMiner):
    """The pollard rho miner with a mapping function which is hard to compute reversely."""
    def func_f(self, hash_i, y_i):
        base = self.block.public_key.g
        h = self.block.public_key.h
        p = self.block.public_key.p
        if hash_i % 3 == 2:
            return (pow(h, hash_i, p) * y_i) % p
        elif hash_i % 3 == 0:
            return pow(y_i, hash_i, p)
        elif hash_i % 3 == 1:
            return (pow(base, hash_i, p) * y_i) % p
        else:
            raise ValueError("Input value has error!")

    def func_g(self, a, n, hash_i):
        p = self.block.public_key.p
        if hash_i % 3 == 2:
            return a
        elif hash_i % 3 == 0:
            return a * hash_i % (p-1)
        elif hash_i % 3 == 1:
            return (a + hash_i) % (p-1)
        else:
            raise ValueError("Input value has error!")

    def func_h(self, b, n, hash_i):
        p = self.block.public_key.p
        if hash_i % 3 == 2:
            return (b + hash_i) % (p-1)
        elif hash_i % 3 == 0:
            return b * hash_i % (p-1)
        elif hash_i % 3 == 1:
            return b
        else:
            raise ValueError("Input value has error!")


import logging
import urllib
import yaml
from simplejson import JSONDecodeError
import simplejson as json
from twisted.internet import defer

from synapse.api.constants import Membership
from synapse.appservice import ApplicationService, AppServiceTransaction
from synapse.storage.roommember import RoomsForUser
from synapse.types import UserID
from ._base import SQLBaseStore

logger = logging.getLogger(__name__)

class ApplicationServiceStore(SQLBaseStore):

    def __init__(self, hs):
        super(ApplicationServiceStore, self).__init__(hs)
        self.hostname = hs.hostname
        self.services_cache = []
        self._populate_appservice_cache(
            hs.config.app_service_config_files
        )

    def get_app_services(self):
        return defer.succeed(self.services_cache)

    def get_app_service_by_user_id(self, user_id):
        """Retrieve an application service from their user ID.

        All application services have associated with them a particular user ID.
        There is no distinguishing feature on the user ID which indicates it
        represents an application service. This function allows you to map from
        a user ID to an application service.

        Args:
            user_id(str): The user ID to see if it is an application service.
        Returns:
            synapse.appservice.ApplicationService or None.
        """
        for service in self.services_cache:
            if service.sender == user_id:
                return defer.succeed(service)
        return defer.succeed(None)

    def get_app_service_by_token(self, token):
        """Get the application service with the given appservice token.

        Args:
            token (str): The application service token.
        Returns:
            synapse.appservice.ApplicationService or None.
        """
        for service in self.services_cache:
            if service.token == token:
                return defer.succeed(service)
        return defer.succeed(None)

    def get_app_service_rooms(self, service):
        """Get a list of RoomsForUser for this application service.

        Application services may be "interested" in lots of rooms depending on
        the room ID, the room aliases, or the members in the room. This function
        takes all of these into account and returns a list of RoomsForUser which
        represent the entire list of room IDs that this application service
        wants to know about.

        Args:
            service: The application service to get a room list for.
        Returns:
            A list of RoomsForUser.
        """
        return self.runInteraction(
            "get_app_service_rooms",
            self._get_app_service_rooms_txn,
            service,
        )

    def _get_app_service_rooms_txn(self, txn, service):
        # get all rooms matching the room ID regex.
        room_entries = self._simple_select_list_txn(
            txn=txn, table="rooms", keyvalues=None, retcols=["room_id"]
        )
        matching_room_list = set([
            r["room_id"] for r in room_entries if
            service.is_interested_in_room(r["room_id"])
        ])

        # resolve room IDs for matching room alias regex.
        room_alias_mappings = self._simple_select_list_txn(
            txn=txn, table="room_aliases", keyvalues=None,
            retcols=["room_id", "room_alias"]
        )
        matching_room_list |= set([
            r["room_id"] for r in room_alias_mappings if
            service.is_interested_in_alias(r["room_alias"])
        ])

        # get all rooms for every user for this AS. This is scoped to users on
        # this HS only.
        user_list = self._simple_select_list_txn(
            txn=txn, table="users", keyvalues=None, retcols=["name"]
        )
        user_list = [
            u["name"] for u in user_list if
            service.is_interested_in_user(u["name"])
        ]
        rooms_for_user_matching_user_id = set()  # RoomsForUser list
        for user_id in user_list:
            # FIXME: This assumes this store is linked with RoomMemberStore :(
            rooms_for_user = self._get_rooms_for_user_where_membership_is_txn(
                txn=txn,
                user_id=user_id,
                membership_list=[Membership.JOIN]
            )
            rooms_for_user_matching_user_id |= set(rooms_for_user)

        # make RoomsForUser tuples for room ids and aliases which are not in the
        # main rooms_for_user_list - e.g. they are rooms which do not have AS
        # registered users in it.
        known_room_ids = [r.room_id for r in rooms_for_user_matching_user_id]
        missing_rooms_for_user = [
            RoomsForUser(r, service.sender, "join") for r in
            matching_room_list if r not in known_room_ids
        ]
        rooms_for_user_matching_user_id |= set(missing_rooms_for_user)

        return rooms_for_user_matching_user_id

    def _parse_services_dict(self, results):
        # SQL results in the form:
        # [
        #   {
        #     'regex': "something",
        #     'url': "something",
        #     'namespace': enum,
        #     'as_id': 0,
        #     'token': "something",
        #     'hs_token': "otherthing",
        #     'id': 0
        #   }
        # ]
        services = {}
        for res in results:
            as_token = res["token"]
            if as_token is None:
                continue
            if as_token not in services:
                # add the service
                services[as_token] = {
                    "id": res["id"],
                    "url": res["url"],
                    "token": as_token,
                    "hs_token": res["hs_token"],
                    "sender": res["sender"],
                    "namespaces": {
                        ApplicationService.NS_USERS: [],
                        ApplicationService.NS_ALIASES: [],
                        ApplicationService.NS_ROOMS: []
                    }
                }
            # add the namespace regex if one exists
            ns_int = res["namespace"]
            if ns_int is None:
                continue
            try:
                services[as_token]["namespaces"][
                    ApplicationService.NS_LIST[ns_int]].append(
                    json.loads(res["regex"])
                )
            except IndexError:
                logger.error("Bad namespace enum '%s'. %s", ns_int, res)
            except JSONDecodeError:
                logger.error("Bad regex object '%s'", res["regex"])

        service_list = []
        for service in services.values():
            service_list.append(ApplicationService(
                token=service["token"],
                url=service["url"],
                namespaces=service["namespaces"],
                hs_token=service["hs_token"],
                sender=service["sender"],
                id=service["id"]
            ))
        return service_list

    def _load_appservice(self, as_info):
        required_string_fields = [
            "url", "as_token", "hs_token", "sender_localpart"
        ]
        for field in required_string_fields:
            if not isinstance(as_info.get(field), basestring):
                raise KeyError("Required string field: '%s'", field)

        localpart = as_info["sender_localpart"]
        if urllib.quote(localpart) != localpart:
            raise ValueError(
                "sender_localpart needs characters which are not URL encoded."
            )
        user = UserID(localpart, self.hostname)
        user_id = user.to_string()

        # namespace checks
        if not isinstance(as_info.get("namespaces"), dict):
            raise KeyError("Requires 'namespaces' object.")
        for ns in ApplicationService.NS_LIST:
            # specific namespaces are optional
            if ns in as_info["namespaces"]:
                # expect a list of dicts with exclusive and regex keys
                for regex_obj in as_info["namespaces"][ns]:
                    if not isinstance(regex_obj, dict):
                        raise ValueError(
                            "Expected namespace entry in %s to be an object,"
                            " but got %s", ns, regex_obj
                        )
                    if not isinstance(regex_obj.get("regex"), basestring):
                        raise ValueError(
                            "Missing/bad type 'regex' key in %s", regex_obj
                        )
                    if not isinstance(regex_obj.get("exclusive"), bool):
                        raise ValueError(
                            "Missing/bad type 'exclusive' key in %s", regex_obj
                        )
        return ApplicationService(
            token=as_info["as_token"],
            url=as_info["url"],
            namespaces=as_info["namespaces"],
            hs_token=as_info["hs_token"],
            sender=user_id,
            id=as_info["as_token"]  # the token is the only unique thing here
        )

    def _populate_appservice_cache(self, config_files):
        """Populates a cache of Application Services from the config files."""
        if not isinstance(config_files, list):
            logger.warning(
                "Expected %s to be a list of AS config files.", config_files
            )
            return

        for config_file in config_files:
            try:
                with open(config_file, 'r') as f:
                    appservice = self._load_appservice(yaml.load(f))
                    logger.info("Loaded application service: %s", appservice)
                    self.services_cache.append(appservice)
            except Exception as e:
                logger.error("Failed to load appservice from '%s'", config_file)
                logger.exception(e)

class ApplicationServiceTransactionStore(SQLBaseStore):

    def __init__(self, hs):
        super(ApplicationServiceTransactionStore, self).__init__(hs)

    @defer.inlineCallbacks
    def get_appservices_by_state(self, state):
        """Get a list of application services based on their state.

        Args:
            state(ApplicationServiceState): The state to filter on.
        Returns:
            A Deferred which resolves to a list of ApplicationServices, which
            may be empty.
        """
        results = yield self._simple_select_list(
            "application_services_state",
            dict(state=state),
            ["as_id"]
        )
        # NB: This assumes this class is linked with ApplicationServiceStore
        as_list = yield self.get_app_services()
        services = []

        for res in results:
            for service in as_list:
                if service.id == res["as_id"]:
                    services.append(service)
        defer.returnValue(services)

    @defer.inlineCallbacks
    def get_appservice_state(self, service):
        """Get the application service state.

        Args:
            service(ApplicationService): The service whose state to set.
        Returns:
            A Deferred which resolves to ApplicationServiceState.
        """
        result = yield self._simple_select_one(
            "application_services_state",
            dict(as_id=service.id),
            ["state"],
            allow_none=True
        )
        if result:
            defer.returnValue(result.get("state"))
            return
        defer.returnValue(None)

    def set_appservice_state(self, service, state):
        """Set the application service state.

        Args:
            service(ApplicationService): The service whose state to set.
            state(ApplicationServiceState): The connectivity state to apply.
        Returns:
            A Deferred which resolves when the state was set successfully.
        """
        return self._simple_upsert(
            "application_services_state",
            dict(as_id=service.id),
            dict(state=state)
        )

    def create_appservice_txn(self, service, events):
        """Atomically creates a new transaction for this application service
        with the given list of events.

        Args:
            service(ApplicationService): The service who the transaction is for.
            events(list<Event>): A list of events to put in the transaction.
        Returns:
            AppServiceTransaction: A new transaction.
        """
        return self.runInteraction(
            "create_appservice_txn",
            self._create_appservice_txn,
            service, events
        )

    def _create_appservice_txn(self, txn, service, events):
        # work out new txn id (highest txn id for this service += 1)
        # The highest id may be the last one sent (in which case it is last_txn)
        # or it may be the highest in the txns list (which are waiting to be/are
        # being sent)
        last_txn_id = self._get_last_txn(txn, service.id)

        txn.execute(
            "SELECT MAX(txn_id) FROM application_services_txns WHERE as_id=?",
            (service.id,)
        )
        highest_txn_id = txn.fetchone()[0]
        if highest_txn_id is None:
            highest_txn_id = 0

        new_txn_id = max(highest_txn_id, last_txn_id) + 1

        # Insert new txn into txn table
        event_ids = json.dumps([e.event_id for e in events])
        txn.execute(
            "INSERT INTO application_services_txns(as_id, txn_id, event_ids) "
            "VALUES(?,?,?)",
            (service.id, new_txn_id, event_ids)
        )
        return AppServiceTransaction(
            service=service, id=new_txn_id, events=events
        )

    def complete_appservice_txn(self, txn_id, service):
        """Completes an application service transaction.

        Args:
            txn_id(str): The transaction ID being completed.
            service(ApplicationService): The application service which was sent
            this transaction.
        Returns:
            A Deferred which resolves if this transaction was stored
            successfully.
        """
        return self.runInteraction(
            "complete_appservice_txn",
            self._complete_appservice_txn,
            txn_id, service
        )

    def _complete_appservice_txn(self, txn, txn_id, service):
        txn_id = int(txn_id)

        # Debugging query: Make sure the txn being completed is EXACTLY +1 from
        # what was there before. If it isn't, we've got problems (e.g. the AS
        # has probably missed some events), so whine loudly but still continue,
        # since it shouldn't fail completion of the transaction.
        last_txn_id = self._get_last_txn(txn, service.id)
        if (last_txn_id + 1) != txn_id:
            logger.error(
                "appservice: Completing a transaction which has an ID > 1 from "
                "the last ID sent to this AS. We've either dropped events or "
                "sent it to the AS out of order. FIX ME. last_txn=%s "
                "completing_txn=%s service_id=%s", last_txn_id, txn_id,
                service.id
            )

        # Set current txn_id for AS to 'txn_id'
        self._simple_upsert_txn(
            txn, "application_services_state", dict(as_id=service.id),
            dict(last_txn=txn_id)
        )

        # Delete txn
        self._simple_delete_txn(
            txn, "application_services_txns",
            dict(txn_id=txn_id, as_id=service.id)
        )

    def get_oldest_unsent_txn(self, service):
        """Get the oldest transaction which has not been sent for this
        service.

        Args:
            service(ApplicationService): The app service to get the oldest txn.
        Returns:
            A Deferred which resolves to an AppServiceTransaction or
            None.
        """
        return self.runInteraction(
            "get_oldest_unsent_appservice_txn",
            self._get_oldest_unsent_txn,
            service
        )

    def _get_oldest_unsent_txn(self, txn, service):
        # Monotonically increasing txn ids, so just select the smallest
        # one in the txns table (we delete them when they are sent)
        txn.execute(
            "SELECT * FROM application_services_txns WHERE as_id=?"
            " ORDER BY txn_id ASC LIMIT 1",
            (service.id,)
        )
        rows = self.cursor_to_dict(txn)
        if not rows:
            return None

        entry = rows[0]

        event_ids = json.loads(entry["event_ids"])
        events = self._get_events_txn(txn, event_ids)

        return AppServiceTransaction(
            service=service, id=entry["txn_id"], events=events
        )

    def _get_last_txn(self, txn, service_id):
        txn.execute(
            "SELECT last_txn FROM application_services_state WHERE as_id=?",
            (service_id,)
        )
        last_txn_id = txn.fetchone()
        if last_txn_id is None or last_txn_id[0] is None:  # no row exists
            return 0
        else:
            return int(last_txn_id[0])  # select 'last_txn' col


from flask import Flask, render_template, request, jsonify
import yaml
from src.models.predict_model import predict_value

def retrieve_params(config):
    with open(config) as yaml_file:
        params = yaml.safe_load(yaml_file)
    return params

params = retrieve_params(config="params.yaml")

app = Flask(
    __name__,
    static_folder=params["webapp"]["static_folder"],
    template_folder=params["webapp"]["template_folder"],
)

@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == "GET":
        return render_template("home.html")
    else:
        if request.form:
            response_ = predict_value(request.form)
            return render_template("home.html", response_=response_)
        elif request.json:
            response_ = predict_value(request.json)
            return jsonify(response_)

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


ten = list(range(1, 11))
print(ten)
evens = list(filter(lambda i: i % 2 == 0, ten))
evens2 = list(map(lambda i: i ** 2, evens))

def func(lst: list):
    while True:
        try:
            index = input("Введите индекс: ").lower()

            if index == "exit" or index == "выход":
                print("Программа завершается: ")
                break
            print(lst[int(index)])
        except:
            print(f"Вводите только числа от 0 до {len(ten) - 1}")

func(ten)


import sqlite3

from config import CONF
from tools.log import *

# 实例化日志对象
logger = setLogger('databases')

def db(sql=None):
    """
    数据库操作
    :param sql:
    :return:
    """
    # 挂载链接
    connect = connect_database()
    logger.info(connect)
    # 传入查询时
    if sql:
        # 执行SQL
        result = do_query(connect, sql)
        connect.close()
        return result
    # 关闭链接
    connect.close()

def connect_database():
    """
    挂载数据库
    :return: sqlite3.Connection
    """
    # 挂载链接
    connect = sqlite3.connect(CONF.DB_PATH)

    # 强制启动外键约束
    if CONF.USE_FOREIGN:
        connect.execute("PRAGMA foreign_keys=1;")

    if CONF.CACHE_SIZE:
        sql = "PRAGMA cache_size=" + str(CONF.CACHE_SIZE) + ";"
        connect.execute(sql)

    return connect

def do_query(connect, sql):
    """
    执行SQL
    :type connect: sqlite3.Connection
    :type sql: string
    """
    sql = sql.strip()

    if sql.lstrip().upper().startswith("SELECT"):
        # 创建游标
        cursor = connect.cursor()
        # 查询
        result = select(cursor, sql)
        # 关闭游标
        cursor.close()
        return result
    elif sql.lstrip().upper().startswith("INSERT"):
        result = insert(connect, sql)
        return result
    elif sql.lstrip().upper().startswith("UPDATE"):
        result = update(connect, sql)
        return result
    elif sql.lstrip().upper().startswith("DELETE"):
        result = delete(connect, sql)
        return result
    else:
        return 0

def select(cursor, sql):
    """
    SELECT语句
    :param sql:
    :param cursor:
    :return:
    """
    # 执行SQL
    cursor.execute(sql)
    # 获取结果
    result = cursor.fetchall()

    return result

def insert(connect, sql):
    """
    INSERT语句
    :param sql:
    :param connect:
    :type connect: sqlite3.Connection
    :return:
    """
    # 执行SQL
    try:
        connect.execute(sql)
        connect.commit()
        result = 1
    except sqlite3.DatabaseError:
        result = 0
        logger.error(sqlite3.DatabaseError)
        print(sqlite3.DatabaseError)
    except sqlite3.Error:
        result = 0
        logger.error(sqlite3.Error)
        print(sqlite3.Error)

    return result

def update(connect, sql):
    """
    UPDATE语句
    :param connect:
    :param sql:
    :type connect: sqlite3.Connection
    :return:
    """
    # 执行SQL
    try:
        connect.execute(sql)
        connect.commit()
        result = 1
    except sqlite3.DatabaseError:
        result = 0
        logger.error(sqlite3.DatabaseError)
        print(sqlite3.DatabaseError)
    except sqlite3.Error:
        result = 0
        logger.error(sqlite3.Error)
        print(sqlite3.Error)

    return result

def delete(connect, sql):
    """
    DELETE语句
    :param connect:
    :param sql:
    :type connect: sqlite3.Connection
    :return:
    """
    # 执行SQL
    try:
        connect.execute(sql)
        connect.commit()
        result = 1
    except sqlite3.DatabaseError:
        result = 0
        logger.error(sqlite3.DatabaseError)
        print(sqlite3.DatabaseError)
    except sqlite3.Error:
        result = 0
        logger.error(sqlite3.Error)
        print(sqlite3.Error)

    return result

# if __name__ == '__main__':
#     # pass
#     sql = """
#     UPDATE bug SET tester_id=1, developer_id=1, phase_id=1, bug_type=1, category=8, title='作品展示页翻页后点击进入作品详情页后，点击退回上个页面保持页面筛选状态，即维持在进入此作品详情页的作品类表页数',
#     model='前端-作品展示区', create_time=1611147000, close_time=0, is_finished='False', is_closed='False', is_online='False' WHERE kb_id=71892;
#     """
#     db(sql)


import pygame
from lib.AnimatedSprite import AnimatedSprite
from lib.AutoMovingAnimatedSprite import AutoMovingAnimatedSprite
from lib import invaderutils
from lib.GameObjectKeeper import GameObjectKeeper

class Hero(AnimatedSprite):
    MIS_STEPS = 0  # Number of waits before we trigger another missile
    mis_steps = 0
    MOVE_STEPS = 0 # Number of waits before we allow another move
    move_steps = 0

    def __init__(self, ix, iy, filenames, steps=1, move_steps=1, mis_steps=50):
        """What is steps, and msteps?? """

        super().__init__(ix, iy, filenames, steps)
        Hero.MIS_STEPS = mis_steps
        Hero.MOVE_STEPS = move_steps

        self.effect = pygame.mixer.Sound('sounds/thump.wav')
        self.effect.set_volume(0.03)

        self.count = len(filenames)-1

    def process_events(self, evt):
        if (self.mis_steps >= Hero.MIS_STEPS):
            if evt.type == pygame.KEYDOWN and evt.key == pygame.K_SPACE:
                self.fire_missile()

    def process_keys(self, pressed):
        """constantly being called"""

        self.mis_steps += 1
        self.move_steps += 1

        if (self.mis_steps >= Hero.MIS_STEPS):
            if pressed[pygame.K_UP]:
                self.fire_missile()

        if (self.move_steps >= Hero.MOVE_STEPS):
            self.move_steps = 0
            if pressed[pygame.K_LEFT]:
                self.x -= self.STEPS
            if pressed[pygame.K_RIGHT]:
                self.x += self.STEPS

        self.myclipx()

    def myclipx(self):
        """ Keeps the ship from hanging out at the edge where aliens can't
        shoot it. """
        if (self.x < 40):
            self.x = 0+40

        if (self.x+self.get_width() + 40 > invaderutils.get_game_width()):
            self.x = invaderutils.get_game_width() - self.get_width()-40

    def fire_missile(self):
        self.mis_steps = 0

        newx = int(self.x + self.get_width()/2)
        newy = self.y

        missile = AutoMovingAnimatedSprite(
            newx, newy,
            invaderutils.missile_png(), movex=0, movey=-4,
            msteps=1)
        GameObjectKeeper.setupfriendly(missile, 45)

    def draw(self, screen):
        image = self.images[self.count]
        screen.blit(image, (self.x, self.y))

        # self.steps += 1
        # if (self.steps >= self.STEPS):
        #     self.count = self.count + 1
        #     self.count = self.count % len(self.images)
        #     self.steps = 0

    def terminate(self):

        if self.count > 0:
            self.count -= 1
        else:
            super().terminate()


# bot.py
import os
import random
from time import sleep
import asyncio
import time
import youtube_dl

import discord
from discord.ext import commands
from discord.utils import get

TOKEN = "[input token here]"
justUsed = ""
connected = False
playGachi = True
optoutusers = []

bot = commands.Bot(command_prefix='pog, ')
def openThing(fileName):
    global justUsed
    notGood = True
    with open('.\\media\\' + fileName) as Links:
        words = Links.read().split(",")
        while notGood:
            response = random.choice(words)
            if response != justUsed:
                notGood = False
        print(response)
    justUsed = response
    return response

async def mp3Player(fileName, message, length, directory):
    try:
	    global vc
	    global connected
	    global playGachi
	    user = message.author
	    print(user)
	    voice_channel = user.voice.channel
	    print(voice_channel)
	    channel = None
	    if voice_channel != None:
	        channel = voice_channel.name
	        if not connected:
	            vc = await voice_channel.connect()
	            connected = True
	        if directory == 0:
	            vc.play(discord.FFmpegPCMAudio(".\\mp3\\"+fileName))
	        elif directory == 1:
	            vc.play(discord.FFmpegPCMAudio("M:\\Gachi\\"+fileName))
	        elif directory == 2:
	        	vc.play(discord.FFmpegPCMAudio(".\\minecraft\\"+fileName))
	        elif directory == 3:
	        	vc.play(discord.FFmpegPCMAudio(".\\mp3\\yt\\"+fileName))

	        if (directory != 0 or directory != 3) and length == 0:
	            while vc.is_playing():
	                await asyncio.sleep(1)
	            vc.stop()
	        elif directory != 0 or directory != 3:
	            await asyncio.sleep(length)
	            vc.stop()
	        elif length == 0:
	            while vc.is_playing():
	                await asyncio.sleep(1)
	            await vc.disconnect()
	            connected = False
	        else:
	            await asyncio.sleep(length)
	            await vc.disconnect()
	            connected = False
    except:
        try:
            vc.stop()
            await vc.disconnect()
            connected = False
            playGachi = False
            pass
        except:
        	await vc.disconnect()
        	connected = False
        	pass
        print("whoop exception at mp3Player")
    await vc.disconnect()
    connected = False

def checkifplaying():
	return vc.is_playing()

with open('optout.txt') as optoutList:
	optoutusers = optoutList.read().split(",")

@bot.event
async def on_ready():
    print('Bot is now working!')
    await bot.change_presence(activity=discord.Game('with your dad ;)'))

@bot.event
async def on_message(message):
    with open('optout.txt') as optoutList:
       optoutusers = optoutList.read().split(",")
    global messagem
    if message.author == bot.user or ('.com' in message.content and not 'play' in message.content.lower()):
        return
    if message.author == 327606483741179914 and random.randint(0, 2) == 1:
        print("thompson denied")
        return
    if str(message.author) in optoutusers and not "pog, " in message.content.lower():
    	print(str(message.author), "is opted out")
    	return

    messagem = message

    #==============================poggers

    if 'poggers' in message.content.lower():

        response = openThing('poggers.tenor')

        unpoggers = ["https://tenor.com/view/poggers-deku-bakugo-my-hero-academia-my-hero-gif-18930451",
                     "https://tenor.com/view/unpoggers-pog-gif-19224204",
                     "https://tenor.com/view/anime-poggers-anime-poggers-anime-gif-18290524"]

        await message.channel.send(response)

        if response in unpoggers:
            await message.channel.send("whoa!")
            await message.channel.send("unpoggers...")

        else:
            await mp3Player("poggers.mp3", message, 1.2, 0)
            chance = random.randint(1, 50)
            print(chance)
            if chance == 24:
                await message.channel.send("poggers", tts=True)

        #==============================amogus

    elif 'amogus' in message.content.lower():

        a = random.choice(["amoguss", "aamogus", "sus", "amogus"])

        await mp3Player(a + ".mp3", message, 0, 0)

        await message.channel.send("ඞ")

    await bot.process_commands(message)

@bot.command(help='tells (un)funny joke')
async def funny(ctx):
    await mp3Player(random.choice(["eel.mp3", "congrats.mp3", "ahhhh.mp3"]), messagem, 0, 0)

@bot.command(help="play command, plays mp3's from playlist, opt. seconds")
async def playmp3(ctx, fileName: str, seconds: float = 0):
	fileName.replace(".mp3", "")
	fileName = fileName + ".mp3"
	print(fileName)
	await mp3Player(fileName, messagem, seconds, 0)

@bot.command(help="youtube play command, only accepts url")
async def play(ctx, url: str):
	if "list" in url:
		url = url[:url.index("list")-1]
	songDownloaded = os.path.isfile("ytsong.mp3")
	try:
		if songDownloaded:
			os.remove("ytsong.mp3")
	except PermissionError:
		await ctx.send("oop gotta wait for this one to end. or like use stop command idk")
	ytdl_opts = {
	'format': 'bestaudio/best',
	'outtmpl': '.\\mp3\\yt\\ytsong.%(ext)s',
	'postprocessors': [{
	'key': 'FFmpegExtractAudio',
	'preferredcodec': 'mp3',
	'preferredquality': '192'
		}]
	}
	print("downloading", url)
	with youtube_dl.YoutubeDL(ytdl_opts) as ydl:
		ydl.download([url])
	await mp3Player('ytsong.mp3', messagem, 0, 3)

@bot.command(help='audio files you can play')
async def playlist(ctx):
    files = os.listdir(".\\mp3\\")
    await messagem.channel.send(files)

@bot.command(help='stop playing')
async def stop(ctx):
    global playGachi
    global playMinecraft
    global connected
    playGachi = False
    playMinecraft = False
    vc.stop()
    await vc.disconnect()
    connected = False

@bot.command(help='triggers list')
async def triggers(ctx):
    with open("triggers.txt") as triggers:
        response = triggers.read().split(",")
    await messagem.channel.send("this is the simple version of this bot, so most of these wont work")
    await messagem.channel.send(response)

''' Check bot-og.py for why this is commented out
@bot.command(help='gachi')
async def gachi(ctx):
    global playGachi
    global connected
    global vc
    m = messagem
    playGachi = True
    while playGachi:
        toPlay = random.choice(os.listdir("M:\\Gachi"))
        await m.channel.send(toPlay)
        await mp3Player(toPlay, messagem, 0, 1)
'''

@bot.command(help='minecraft')
async def minecraft(ctx):
	global playMinecraft
	global connected
	global vc
	m = messagem
	playMinecraft = True
	listofsongs = os.listdir(".\\minecraft")
	if listofsongs == []:
		playMinecraft = False
	while playMinecraft:
		toPlay = random.choice(listofsongs)
		listofsongs.remove(toPlay)
		await m.channel.send(toPlay)
		await mp3Player(toPlay, messagem, 0, 2)

@bot.command(help='opt out using this')
async def optout(ctx):
	with open('optout.txt') as optoutList:
		optoutusers = optoutList.read().split(",")
	print(optoutusers)
	if not str(messagem.author) in optoutusers:
		with open('optout.txt', 'a') as optoutList:
			optoutList.write(str(messagem.author) + ',')
	await messagem.channel.send('opt back in using "pog, optin"')

@bot.command(help='opt back in')
async def optin(ctx):
	with open('optout.txt') as optoutList:
		optoutusers = optoutList.read().split(",")
	print(optoutusers)
	new = ''
	if str(messagem.author) in optoutusers:
		optoutusers.remove(str(messagem.author))
	for i in optoutusers:
		if i != '':
			new += i + ','
	with open('optout.txt', 'w') as optoutList:
		optoutList.write(new)
	await messagem.channel.send("welcome back!")

@bot.command(help='random screenshot')
async def randomsc(ctx, n: int = 1):
	letters = "qwertyuiopasdfghjklzxcvbnm"
	for i in range(n):
		await ctx.send("https://prnt.sc/" + random.choice(letters) + random.choice(letters) + str(random.randint(1000, 9999)))

bot.run(TOKEN)


"""
Project Name: CSCI 570 Final Project
Author: Luke Nelson, Peter Argo
"""

import sys

delta = 30
alphas = {('A', 'A'): 0,
         ('A', 'C'): 110,
         ('A', 'G'): 48,
         ('A', 'T'): 94,
         ('C', 'A'): 110,
         ('C', 'C'): 0,
         ('C', 'G'): 118,
         ('C', 'T'): 48,
         ('G', 'A'): 48,
         ('G', 'C'): 118,
         ('G', 'G'): 0,
         ('G', 'T'): 110,
         ('T', 'A'): 94,
         ('T', 'C'): 48,
         ('T', 'G'): 110,
         ('T', 'T'): 0}

def read_file(input_file):
    # Open input file and determine base_string_X with its indices and base_string_Y with its indices
    txt = open(input_file, "r")

    first_line = True
    X_switch = True

    base_string_X = None
    base_string_Y = None
    X_indices = []
    Y_indices = []

    for line in txt:
        line = line.rstrip()

        if first_line == True:
            base_string_X = line
            first_line = False

        elif X_switch == True:
            try:
                line = int(line)
                X_indices.append(line)
            except:
                base_string_Y = line
                X_switch = False
        else:
            try:
                Y_indices.append(int(line))
            except:
                break

    txt.close()

    return {'base_string_X': base_string_X,
           'base_string_Y': base_string_Y,
           'X_indices': X_indices,
           'Y_indices': Y_indices}

def string_generator(string: str, jk: list):
    """
    Gererate the stings from the input files
    :param string: input string
    :param jk: list of multipliers
    :return:
    """
    if len(jk) == 1:
        return string[0:jk[0]+1] + string + string[jk[0]+1::]

    new_string = string[0:jk[0]+1] + string + string[jk[0]+1::]
    return string_generator(new_string, jk[1::])

def str_length_validation(base_string, full_string, indices):
    full_str_length = len(full_string)
    base_str_length = len(base_string)
    j = len(indices)

    validation_length = (2 ** j) * base_str_length

    if full_str_length == validation_length:
        print('TRUE')
        print('Full String Length: ', full_str_length)
        print('Validation Length: ', validation_length)

    else:
        print('FALSE')
        print('Full String Length: ', full_str_length)
        print('Validation Length: ', validation_length)

def alignment(X, Y):

    global delta
    global alphas

    # size of matrix n x m
    # Y -> has length 1, 2, ...j..., n   ----> Rows
    # X -> has length 1, 2, ...i..., m   ----> Cols
    n = len(Y)    # Rows
    m = len(X)    # Cols
    print("length of Y string: (n) ", n)
    print("length of X string: (m) ", m)
    A = [ [ 0 for i in range(m + 1) ] for j in range(n + 1) ]    # Create empty array
    T = [[0 for i in range(m + 1)] for j in range(n + 1)]
    # Initialize A[i, 0] and A[0, j]
    # Matrix access looks like A[row][column] = A[j][i]
    for i in range(m + 1):
        A[0][i] = i * delta

    for j in range(n + 1):
        A[j][0] = j * delta

    # Run recurrence
    for j in range(n + 1)[1:]:
        for i in range(m + 1)[1:]:

            diag = alphas[(X[i - 1], Y[j - 1])] + A[j - 1][i - 1]
            left = delta + A[j][i - 1]
            up = delta + A[j - 1][i]

            A[j][i] = min(alphas[(X[i - 1], Y[j - 1])] + A[j - 1][i - 1],
                         delta + A[j][i - 1],
                         delta + A[j - 1][i])

            best_choice = min(diag, left, up)

            if best_choice == diag:
                # T[j][i] = str(i-1) + " " + str(j-1)
                T[j][i] = str(j - 1) + " " + str(i - 1)
            elif best_choice == left:
                # T[j][i] = str(i - 1) + " " + str(j)
                T[j][i] = str(j - 1) + " " + str(i)
            elif best_choice == up:
                # T[j][i] = str(i) + " " + str(j-1)
                T[j][i] = str(j) + " " + str(i - 1)

            new_T = [row[1::] for row in T][1::]

    return (new_T, A)

def reconstruct_soln(matrix, m, n, xstring, ystring):
    """

    :param matrix: The alignment matrix
    :param m:
    :param n:
    :param xstring:
    :param ystring:
    :return:
    """
    global solution
    global solution_stringx
    global solution_stringy
    global x_prev
    global y_prev
    global delta
    global alphas

    if m == 0 and n == 0:
        return

    left = matrix[n][m-1]
    up = matrix[n-1][m]
    diag = matrix[n-1][m-1]

    if matrix[n][m] == diag + alphas[(xstring[m-1], ystring[n-1])]:
        solution_stringx = xstring[m-1] + solution_stringx
        solution_stringy = ystring[n - 1] + solution_stringy
        return reconstruct_soln(matrix=matrix, m=m-1, n=n-1, xstring=xstring, ystring=ystring)

    elif matrix[n][m] == left + delta:
        solution_stringx = xstring[m-1] + solution_stringx
        solution_stringy = "_" + solution_stringy
        return reconstruct_soln(matrix, m-1, n, xstring, ystring)

    elif matrix[n][m] == up + delta:
        solution_stringx = "_" + solution_stringx
        solution_stringy = ystring[n - 1] + solution_stringy
        return reconstruct_soln(matrix, m, n-1, xstring, ystring)

if __name__ == '__main__':
    # input_file = sys.argv[1]
    input_file = "input1.txt"
    output_file = 'output.txt'
    solution = list()
    solution_stringx = ""
    solution_stringy = ""

    file_data = read_file(input_file)
    base_string_X = file_data['base_string_X']
    base_string_Y = file_data['base_string_Y']
    X_indices = file_data['X_indices']
    Y_indices = file_data['Y_indices']

    s1 = "ACTG"
    j = [3,6,1,1]
    s2 = "TACG"
    k = [1, 2, 9, 2]
    # x_prev = len(s1)
    # y_prev = len(s2)

    new_s1 = string_generator(string=s1, jk=j)
    new_s2 = string_generator(string=s2, jk=k)
    print("string 1: ", new_s1)
    print("string 2: ", new_s2)

    x_prev = len(new_s1)
    y_prev = len(new_s2)

    mm = alignment(new_s1, new_s2)
    # mm = alignment(s1, s2)

    reconstruct_soln(matrix=mm[1], m=len(new_s1), n=len(new_s2), xstring=new_s1, ystring=new_s2)
    # reconstruct_soln(matrix=mm[1], m=len(s1), n=len(s2), xstring=s1, ystring=s2)

    print(solution[::-1])
    print("our solution for string 1(x): ", solution_stringx[0:50], solution_stringx[len(solution_stringx)-50::])
    print("our solution for string 1(y): ", solution_stringy[0:50], solution_stringy[len(solution_stringy)-50::])

    print("output1.txt for string 1(x):  ", "_A_CA_CACT__G__A_C_TAC_TGACTG_GTGA__C_TACTGACTGGAC", "GTGA__C_TACTGACTGGACTGACTACTGACTGGTGACTACT_GACTG_G")
    print("output1.txt for string 1(y):  ", "TATTATTA_TACGCTATTATACGCGAC_GCG_GACGCGTA_T_AC__G_C", "G_GACGCGTA_T_AC__G_CT_ATTA_T_AC__GCGAC_GC_GGAC_GCG")


# -*- coding: utf-8 -*-
# __author__ = 'zhouxuan'

from biocluster.api.database.base import Base, report_check
import re
import datetime
from bson import ObjectId, SON
from bson.objectid import ObjectId
from types import StringTypes
# from biocluster.config import Config

class MetaSourcetracker(Base):
    """
    微生物来源组成比例分析
    """
    def __init__(self, bind_object):
        super(MetaSourcetracker, self).__init__(bind_object) #
        self._project_type = 'meta'
        # self._db_name = Config().MONGODB
        self.task_id = ""

    @report_check
    def add_sg_sourcetracker_detail(self, id=None, file_path=None, stdev_file_path=None, name_1=None, name_2=None):
        insert_data = list()
        d_dict = dict()
        def addtwodimdict(thedict, key_a, key_b, val):
            if key_a in thedict:
                thedict[key_a].update({key_b: val})
            else:
                thedict.update({key_a: {key_b: val}})
        with open(stdev_file_path, "rb") as s:
            head_s = s.next().strip('\r\n')
            head_s = re.split('\t', head_s)
            source_name = head_s[1:]
            for line in s:
                line = line.rstrip("\r\n")
                line = re.split('\t', line)
                stdev_number = line[1:]
                for i in range(0, len(source_name)):
                    addtwodimdict(d_dict, line[0], source_name[i], float(stdev_number[i]))
        print(d_dict)
        with open(file_path, 'rb') as r:
            head = r.next().strip('\r\n')  # windows换行符
            head = re.split('\t', head)
            new_head = head[1:]
            for line in r:
                line = line.rstrip("\r\n")
                line = re.split('\t', line)
                group_num = line[1:]
                detail = dict()
                detail['sourcetracker_id'] = ObjectId(id)
                detail['file_name_1'] = name_1
                detail['file_name_2'] = name_2
                detail['sample_name'] = line[0]
                for i in range(0, len(group_num)):
                    # detail[new_head[i]] = float(group_num[i])
                    detail[new_head[i] + "_mean"] = float(group_num[i])
                    detail[new_head[i] + "_stdev"] = float(d_dict[line[0]][new_head[i]])
                    detail[new_head[i] + "_h"] = float(group_num[i]) + (d_dict[line[0]][new_head[i]])
                    detail[new_head[i] + "_l"] = float(group_num[i]) - (d_dict[line[0]][new_head[i]])
                    # detail[new_head[i] + "_stdev_plot"] = float(d_dict[line[0]][new_head[i]]*d_dict[line[0]][new_head[i]])
                    # detail[new_head[i] + "_h"] = float(group_num[i]) + (d_dict[line[0]][new_head[i]]*d_dict[line[0]][new_head[i]])
                    # detail[new_head[i] + "_l"] = float(group_num[i]) - (d_dict[line[0]][new_head[i]]*d_dict[line[0]][new_head[i]])
                insert_data.append(detail)
        try:
            collection = self.db['sg_sourcetracker_detail']
            collection.insert_many(insert_data)
        except Exception as e:
            self.bind_object.logger.error("导入sg_sourcetracker_detail表格信息出错:{}".format(e))
            self.bind_object.set_error("导入sg_sourcetracker_detail表格信息出错", code="51003801")
        else:
            self.bind_object.logger.info("导入sg_sourcetracker_detail表格成功")


import logging
from enum import Enum

from cmdb.framework.cmdb_location import CmdbLocation

LOGGER = logging.getLogger(__name__)

class CheckRoutine:
    """
    This class holds checks for the database check routines
    """

    class CheckStatus(Enum):
        """
        Enumeration of the status options for checks
        """
        NOT = 0
        RUNNING = 1
        HAS_UPDATES = 2
        FINISHED = 3

    def __init__(self, dbm):
        self.status: int = CheckRoutine.CheckStatus.NOT
        self.setup_database_manager = dbm

    def get_check_status(self) -> int:
        """
        Returns the CheckStatus of the current CheckRoutine

        Returns:
            (int): Current CheckStatus
        """
        return self.status

    def checker(self):
        LOGGER.info('CHECK ROUTINE: STARTED...')
        self.status = CheckRoutine.CheckStatus.FINISHED

        # check database
        if not self.__is_database_empty():
            if not (self.__check_database_collection_valid() and self.has_updates()):
                LOGGER.warning(
                    'The current database version does not match the valid database version.'
                )
                self.status = CheckRoutine.CheckStatus.HAS_UPDATES
        LOGGER.info('CHECK ROUTINE: FINISHED!')
        return self.status

    def __is_database_empty(self) -> bool:
        """
        Checks if there are any collections in the initialised database

        Returns:
            (bool): Returns bool if there are any collection in the initialised database
        """
        return not self.setup_database_manager.connector.database.list_collection_names()

    def __check_database_collection_valid(self) -> bool:
        LOGGER.info('CHECK ROUTINE: Checking database collection validation')
        from cmdb.framework import __COLLECTIONS__ as FRAMEWORK_CLASSES
        from cmdb.user_management import __COLLECTIONS__ as USER_MANAGEMENT_COLLECTION
        from cmdb.exportd import __COLLECTIONS__ as JOB_MANAGEMENT_COLLECTION
        detected_database = self.setup_database_manager.connector.database
        collection_test = True

        try:
            # framework collections
            for collection in FRAMEWORK_CLASSES:
                collection_test = detected_database.validate_collection(collection.COLLECTION, scandata=True)['valid']

                # setup locations if valid test
                if collection == CmdbLocation and collection_test:
                    root_location: CmdbLocation = self.setup_database_manager.find_one(collection.COLLECTION, 1)

                    if root_location:
                        if self.setup_database_manager.validate_root_location(CmdbLocation.to_data(root_location)):
                            LOGGER.info("CHECK ROUTINE: Root Location valid")
                        else:
                            LOGGER.info("CHECK ROUTINE: Root Location invalalid => Fixing the Issue!")
                            self.setup_database_manager.set_root_location(collection.COLLECTION, create=False)

                    else:
                        LOGGER.info("CHECK ROUTINE: No Root Location => Creating a new Root Location!")
                        self.setup_database_manager.set_root_location(collection.COLLECTION, create=True)

            # user management collections
            for collection in USER_MANAGEMENT_COLLECTION:
                collection_test = detected_database.validate_collection(collection.COLLECTION, scandata=True)['valid']
            # exportdJob management collections
            for collection in JOB_MANAGEMENT_COLLECTION:
                collection_test = detected_database.validate_collection(collection.COLLECTION, scandata=True)[
                    'valid']
        except Exception as ex:
            LOGGER.info(f'CHECK ROUTINE: Database collection validation for "{collection.COLLECTION}" failed. '
                        f'msgerror: {ex}')
            collection_test = False

        LOGGER.info(f'CHECK ROUTINE: Database collection validation status {collection_test}')
        return collection_test

    def has_updates(self) -> bool:
        """
        Check if updates are available

        Returns:
            (bool): True if updates are available else raises an error
        """
        from cmdb.updater import UpdaterModule
        from cmdb.utils.system_reader import SystemSettingsReader, SectionError

        try:
            ssr = SystemSettingsReader(self.setup_database_manager)
            ssr.get_all_values_from_section('updater')

            upd_module = UpdaterModule(ssr)
            new_version = upd_module.get_last_version()['version']
            current_version = upd_module.settings.version

            if new_version > current_version:
                LOGGER.error(
                    f'Please run an update. There are new updates available.'
                    f'Current Updater Version: {current_version} '
                    f'Newest Update Version: {new_version}'
                )
                return False

        except SectionError as err:
            LOGGER.error(err.message)
            return False

        return True


def add(x, y=3): #x is a required parameter now, but y is an optional parameter, y=3 is called a default parameter. These must go after the non-default parameters
    print(x + y)

add(5)  # 8
add(5, 8)  # 13
add(y=3)  # Error, missing x

# -- Order of default parameters --

# def add(x=5, y):  # Not OK, default parameters must go after non-default
#     print(x + y)

# -- Usually don't use variables as default value --

default_y = 3

def add(x, y=default_y):
    sum = x + y
    print(sum)

add(2)  # 5

default_y = 4
print(default_y)  # 4

add(2)  # 5, even though we re-defined default_y


import json
import re
import sys
import xmltodict
from functools import reduce

def parse_text(text):
    obj = {}
    for m in re.findall(r'(\{\{pagebanner|\n\=\=(\w+)\=\=\n)(((.|\n)(?!\n\=\=))*)', text):
        label = m[1].lower()
        group = m[2]
        if len(label) < 1:
            if "summary" in obj: continue
            label = "summary"
            group = m[0] + group
        paragraphs = []

        for g in re.findall(r'([^\{]+|\{\{[^\}]+\}\})', group):
            if len(g) < 5: continue

            if '{' in g:
                p = g[2:-2].split('|')
                pk = p[0].strip()
                new_obj = {}

                for s in p[1:]:
                    s = s.split('=')
                    k = s[0].strip()
                    if pk == 'pagebanner' and len(s) == 1:
                        v = k
                        k = 'image'
                    else:
                        v = s[1].strip() if len(s) > 1 else None
                    if v and len(v) > 2:
                        new_obj[k] = v

                if len(new_obj.keys()) > 0:
                    paragraphs.append({pk: new_obj})
            else:
                paragraphs.append(g.strip())

        obj[label] = paragraphs

    return obj

def main(filename):
    file_data = open(filename).read()
    xml_obj = xmltodict.parse(file_data)
    pages = []

    for page in xml_obj['mediawiki']['page']:
        try:
            text = page['revision']['text']['#text']
        except Exception:
            continue
        id = page['id']
        title = page['title']
        text_obj = parse_text(text)

        data_len = len(set([k for k in text_obj.keys() if k not in ['summary']]))
        has_image = False
        has_detailed_summary = False
        if 'summary' in text_obj:
            for s in text_obj['summary']:
                if isinstance(s, str):
                    if len(s) > 150 and len(s.split('.')) > 1:
                        has_detailed_summary = True
                elif 'pagebanner' in s:
                    if 'image' in s['pagebanner']:
                        img = s['pagebanner']['image']
                        if img and 'default' not in img:
                            has_image = True

        if data_len > 0 and has_image and has_detailed_summary:
            pages.append({
                'id': id,
                'title': title,
                'sections': text_obj
            })

    with open('wikivoyage.json', 'w') as f:
        f.write(json.dumps(pages, indent=2))

if __name__ == '__main__':
    """
        data gathered from the latest Wikivoyage data dump
        https://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles.xml.bz2
    """
    main(sys.argv[-1])


import sys
from os.path import dirname, realpath
import argparse

sys.path.insert(1, dirname(dirname(realpath(__file__))))
from src.utils.SQLUtils import CalibrationDB
from src.evaluation.Calibrator import Calibrator

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("cal1", help="cal path 1")
    parser.add_argument("cal2", help="cal path 2")
    parser.add_argument("calname", help="cal path 2")
    args = parser.parse_args()
    cal1 = CalibrationDB(args.cal1, args.calname)
    cal2 = CalibrationDB(args.cal2, args.calname)
    cal1 = Calibrator(cal1)
    cal2 = Calibrator(cal2)
    max_diff = 0
    max_det = 0
    for i in range(14):
        for j in range(11):
            for k in range(2):
                diff = (cal1.gains[i,j,k] - cal2.gains[i,j,k]) / cal1.gains[i,j,k]
                if(abs(diff) > max_diff):
                    max_det = 2*(14*j + i) + k
                    max_diff = abs(diff)
                print("det {0} gain diff {1}".format((2*(14*j + i) + k), diff))
    print("max diff is det {0} diff {1}".format(max_det, max_diff))
    #print((cal1.gains - cal2.gains) / cal1.gains)

if __name__=="__main__":
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''sunsitive word views'''

__author__ = "wenxiaoning(371032668@qq.com)"
__copyright__ = "Copyright of hopapapa (2017)."

from src.common import http_util
from src.config import BaseConfig
from src.api.sensitive_word.models import SensitiveWord
from src.common.http_util import return_model
from src.common.web.flask_snippets import crossdomain
from src.common.web.flask_snippets import jsonp

from flask import request
from flask import Blueprint

admin_sensitive_word_bp = Blueprint('admin_sensitive_word', __name__)

@admin_sensitive_word_bp.route('/sensitive_word/list.json', methods=['GET'])
@jsonp
def list():
    '''文章列表'''

    args = request.args

    page = http_util.get_param_int(args, 'page', BaseConfig.DEFAULT_PAGE)
    per_page = http_util.get_param_int(args, 'per_page',
                                       BaseConfig.DEFAULT_PER_PAGE)

    paginate = SensitiveWord.query_paginate(
        page=page,
        per_page=per_page
    )

    items = []
    for item in paginate.items:
        detail = item.to_json()
        # detail['id'] = "{}".format(detail['id'])
        items.append(detail)

    res = http_util.make_page_response(items, paginate.total, page,
                                       per_page)

    return return_model(
        data=res
    )

@admin_sensitive_word_bp.route('/sensitive_word/edit.json', methods=['POST'])
@crossdomain(origin='*', methods=['POST'], headers='Origin, Content-Type')
def edit():
    '''创建文章'''
    args = request.form
    id = args.get('id', None)

    if id:
        SensitiveWord.update_by_id(**args)
    else:
        SensitiveWord.create(**args)

    return return_model()

@admin_sensitive_word_bp.route('/sensitive_word/delete.json', methods=['POST'])
@crossdomain(origin='*', methods=['POST'], headers='Origin, Content-Type')
def delete():
    '''删除敏感词'''
    args = request.form
    id = args.get('id', None)

    SensitiveWord.update_by_id(
        id=id,
        is_del=1
    )

    return return_model()


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

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read().replace('.. :changelog:', '')

requirements = [
    'requests',
]

test_requirements = [
    'requests-mock'
]

setup(
    name='pyactiviti',
    version='0.1.0',
    description="An SDK that helps with interacting with Activiti.",
    long_description=readme + '\n\n' + history,
    author="Stephane Wirtel",
    author_email='stephane@wirtel.be',
    url='https://github.com/matrixise/pyactiviti',
    packages=[
        'pyactiviti',
    ],
    package_dir={'pyactiviti':
                 'pyactiviti'},
    include_package_data=True,
    install_requires=requirements,
    license="BSD",
    zip_safe=False,
    keywords='pyactiviti',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


# Given the root of a binary tree, return the postorder traversal of its nodes' values.
# https://leetcode.com/problems/binary-tree-postorder-traversal/

# 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 postorderTraversal(self, root) -> list[int]:
        # Recursive solution
        treeList = []
        def postOrder(root):
            if not root:
                return
            postOrder(root.left)
            postOrder(root.right)
            treeList.append(root.val)
        postOrder(root)
        return treeList

        # iterative solution
        # if not root: return []
        # treeList= []
        # stack = [root]

        # while stack:
        #     curr = stack.pop()
        #     treeList.append(curr.val)
        #     if curr.left:
        #         stack.append(curr.left)
        #     if curr.right:
        #         stack.append(curr.right)

        # return treeList[ : : -1]


"""An implementation of the Intersection over Union (IoU) metric for Keras."""
from tensorflow.keras import backend as K
import tensorflow as tf
# Jarracrd : https://gist.github.com/wassname/f1452b748efcbeb4cb9b1d059dce6f96
# DICE : https://gist.github.com/wassname/7793e2058c5c9dacb5212c0ac0b18a8a
# IOU : https://www.kaggle.com/vbookshelf/keras-iou-metric-implemented-without-tensor-drama
# F1 : 2*((precision*recall)/(precision+recall+K.epsilon()))

def dice_loss(y_true, y_pred):
    numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2))
    denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2))

    return tf.reshape(1 - numerator / denominator, (-1, 1, 1))

def F1(y_true, y_pred):
    def recall(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
        recall = true_positives / (possible_positives + K.epsilon())
        return recall

    def precision(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
        precision = true_positives / (predicted_positives + K.epsilon())
        return precision

    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    return 2*((p*r)/(p+r+K.epsilon()))

def weightedBCE(y_true, y_pred):
    y_pred = tf.clip_by_value(y_pred, 10e-8, 1. - 10e-8)
    beta1 = 1.0
    beta2 = 1.2
    beta3 = 1.0
    loss1 = -(beta1 * y_true[:, :, :, 0] * tf.math.log(y_pred[:, :, :, 0]) + (1-y_true[:, :, :, 0]) * tf.math.log(1- y_pred[:, :, :, 0]))
    loss2 = -(beta2 * y_true[:, :, :, 1] * tf.math.log(y_pred[:, :, :, 1]) + (1-y_true[:, :, :, 1]) * tf.math.log(1- y_pred[:, :, :, 1]))
    loss3 = -(beta3 * y_true[:, :, :, 2] * tf.math.log(y_pred[:, :, :, 2]) + (1-y_true[:, :, :, 2]) * tf.math.log(1- y_pred[:, :, :, 2]))

    alpha1 = 0.7
    alpha2 = 0.7
    alpha3 = 0.7
    loss1 = alpha1*loss1 + (1-alpha1)*(dice_loss(y_true[:, :, :, 0], y_pred[:, :, :, 0]))
    loss2 = alpha2*loss2 + (1-alpha2)*(dice_loss(y_true[:, :, :, 1], y_pred[:, :, :, 1]))
    loss3 = alpha3*loss3 + (1-alpha3)*(dice_loss(y_true[:, :, :, 2], y_pred[:, :, :, 2]))

    t = (loss1*0.2 + loss2*0.7 + loss3*0.1)
    return t

def recall(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

def precision(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

def iou(y_true, y_pred, label: int):
    """
    Return the Intersection over Union (IoU) for a given label.
    Args:
        y_true: the expected y values as a one-hot
        y_pred: the predicted y values as a one-hot or softmax output
        label: the label to return the IoU for
    Returns:
        the IoU for the given label
    """
    # extract the label values using the argmax operator then
    # calculate equality of the predictions and truths to the label
    y_true = K.cast(K.equal(K.argmax(y_true), label), K.floatx())
    y_pred = K.cast(K.equal(K.argmax(y_pred), label), K.floatx())
    # calculate the |intersection| (AND) of the labels
    intersection = K.sum(y_true * y_pred)
    # calculate the |union| (OR) of the labels
    union = K.sum(y_true) + K.sum(y_pred) - intersection
    # avoid divide by zero - if the union is zero, return 1
    # otherwise, return the intersection over union
    return K.switch(K.equal(union, 0), 1.0, intersection / union)

def build_iou_for(label: int, name: str=None):
    """
    Build an Intersection over Union (IoU) metric for a label.
    Args:
        label: the label to build the IoU metric for
        name: an optional name for debugging the built method
    Returns:
        a keras metric to evaluate IoU for the given label

    Note:
        label and name support list inputs for multiple labels
    """
    # handle recursive inputs (e.g. a list of labels and names)
    if isinstance(label, list):
        if isinstance(name, list):
            return [build_iou_for(l, n) for (l, n) in zip(label, name)]
        return [build_iou_for(l) for l in label]

    # build the method for returning the IoU of the given label
    def label_iou(y_true, y_pred):
        """
        Return the Intersection over Union (IoU) score for {0}.
        Args:
            y_true: the expected y values as a one-hot
            y_pred: the predicted y values as a one-hot or softmax output
        Returns:
            the scalar IoU value for the given label ({0})
        """.format(label)
        return iou(y_true, y_pred, label)

    # if no name is provided, us the label
    if name is None:
        name = label
    # change the name of the method for debugging
    label_iou.__name__ = 'iou_{}'.format(name)

    return label_iou

def mean_iou(y_true, y_pred):
    """
    Return the Intersection over Union (IoU) score.
    Args:
        y_true: the expected y values as a one-hot
        y_pred: the predicted y values as a one-hot or softmax output
    Returns:
        the scalar IoU value (mean over all labels)
    """
    # get number of labels to calculate IoU for
    num_labels = K.int_shape(y_pred)[-1]
    # initialize a variable to store total IoU in
    total_iou = K.variable(0)
    # iterate over labels to calculate IoU for
    for label in range(num_labels):
        total_iou = total_iou + iou(y_true, y_pred, label)
    # divide total IoU by number of labels to get mean IoU
    return total_iou / num_labels


#Script for The Real Reversal
#Look at the bits of the given file
reversed = open('reversed.txt', 'rb')
reversedBits = reversed.read()
#Reverse the bits of the given file and write a new one
bits = reversedBits[::-1]
outputText = open('fix_attempt_one.txt','wb')
outputText.write(bits)
reversed.close()
outputText.close()
print("Fixed the bits")

#This gives us Latin characters in fixed_attempt_one.txt, but the characters are reversed. We can tell by the strange punctuation. The challenge also says that someone reversed the file twice.
#After looking through the text I determined that "}niw_eht_rof_8ftu{ftcsh" is likely the flag reversed

#For some strange reason, no matter what I did the file wouldn't be read as ascii characters with the line below, so I made a workaround using input() and retyping the reversed flag. This may have something to do with the fact that the written text appears like its in a strange font of some kind. }niw_eht_rof_8ftu{ftcsh
#flipped = open('fix_attempt_one.txt','r')

reversedCharacters = str(input("What characters need to be reversed?\n(the text from fix_attempt_one in quotes) \n"))
#Reverse the characters from the new file
characters = reversedCharacters[::-1]
print("Fixed the characters")
print("The Flag is: " +  str(characters))

#The flag is hsctf{utf8_for_the_win}


from flask import Flask, request

app = Flask(__name__)

@app.route('/upload', methods = ['POST'])
def upload():
    if request.method == 'POST':
        raw_data = request.data
        print(raw_data)
        return "Data received successfully!"
    return "Data not received successfully"

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


import os
import traceback
from typing import Optional, Union

from Config import experiment_config as cnfg

TEXT_EXTENSION = 'txt'
IMAGE_EXTENSION = 'png'
VIDEO_EXTENSION = 'mp4'
PICKLE_EXTENSION = 'pkl'

def create_subject_output_directory(subject_id: Union[int, str], output_dir: Optional[str] = cnfg.OUTPUT_DIR) -> str:
    """
    Create subject output directory with a unique name with the following format: PATH/TO/OUTPUT_DIR/SXXX
    If argument `output_dir` is not provided, the default output directory from `experiment_config` is used.
    """
    if output_dir is None:
        output_dir = cnfg.OUTPUT_DIR
    if isinstance(subject_id, int):
        subject_id = f"{subject_id:03d}"
    return create_directory(dirname=f"S{subject_id}", parent_dir=output_dir)

def create_directory(dirname: str, parent_dir: str) -> str:
    if not os.path.exists(parent_dir):
        os.makedirs(parent_dir)
    full_path = os.path.join(parent_dir, dirname)
    if not os.path.exists(full_path):
        os.makedirs(full_path)
    return full_path

def get_filename(name: str, extension: Optional[str] = None) -> str:
    split_name = name.split('.')
    if len(split_name) > 2:
        raise ValueError(f'Invalid filename: {name}')
    if len(split_name) == 2:
        if extension is not None:
            raise ValueError(f'File already has an extension: {extension[1]}')
        name, extension = split_name
    if extension is None:
        raise ValueError(f'No extension provided for filename: {name}')
    return f"{name}.{extension}"

def log_and_print(msg: str, log_file: Optional[str] = None) -> None:
    print(msg)
    try:
        if log_file is not None:
            if not log_file.endswith(TEXT_EXTENSION):
                log_file = get_filename(name=log_file, extension=TEXT_EXTENSION)
            with open(log_file, 'a') as f:
                f.write(msg + '\n')
    except Exception as e:
        trace = traceback.format_exc()
        print(f"\tFailed to write to log file: {e}\n\t{trace}\n")


import arcade
import asyncio
import os
import pyglet
import time
import timeit
from car import *
from map import *
from cube import *
from FPS_Counter import *
from timeit import default_timer as timer

USE_SPATIAL_HASHING = True
if USE_SPATIAL_HASHING:
    RESULTS_FILE = "stress_test_collision_arcade_spatial.csv"
else:
    RESULTS_FILE = "stress_test_collision_arcade.csv"

class window(arcade.Window):

    def __init__(self):
        super().__init__(width=1920, height=1080, title="Traffic Simulator", fullscreen=False)
        self.cube_list = []
        self.car_list = None
        self.change = 0
        self.current_status = 1
        self.frame_count = 0
        self.yellow_start = False
        self.yellow_count = 0
        self.yellow_time = 60
        self.red_time = 240
        self.global_spawn = 0
        self.hour = 20
        self.timer_start = None
        self.timer_now = None
        self.timer_result = None
        self.timer_second = 0
        self.timer_second_sup = 0
        self.timer_minute = 0
        self.timer_string_min = "00"
        self.timer_string_sec = "00"
        self.total_car = 0
        self.total_car_min = 0
        self.spawn_rate = 0
        self.incidenti_min = 0

        self.background_music_list = []
        self.current_background_song = 0
        self.music = None
        self.BACKGROUND_MUSIC_VOLUME = 0.01

        self.results_file = open(RESULTS_FILE, "w")

    def play_background_song(self):
        self.background_music = arcade.Sound(self.background_music_list[self.current_background_song], streaming=True)
        self.background_music.play(self.BACKGROUND_MUSIC_VOLUME)

    def setup(self):
        self.background_music_list = ["../Sound/traffic.wav"]
        self.current_background_song = 0
        self.play_background_song()

        y = 1050
        for j in map:
            x = 30
            for i in j:
                self.cube_list.append(cube(x-30, y-30, x, y, i))
                x = x + 60
            y = y - 60

        self.car_list = arcade.SpriteList()

        auto = car()
        auto.setup(self.cube_list, self.car_list)
        auto.time_service(self.hour, self.timer_minute, self.timer_second)
        self.car_list.append(auto)
        self.total_car += 1
        self.total_car_min += 1

        self.timer_start = datetime.datetime.now().replace(microsecond=0)

    def on_draw(self):
        arcade.start_render()
        img_map = arcade.load_texture("../Sprites/Road_blocks/map.png")
        img_map.draw_scaled(960, 540)
        for car in self.car_list:
            car.fov.sprite.draw()
            car.fov.stop_sprite.draw()

        self.car_list.draw()
        try:
            self.incidenti = self.car_list[0].get_incidenti()
            self.incidenti_min = self.incidenti
        except:
            self.incidenti = self.incidenti

        height = 990
        val = 0
        for i in self.car_list:
            val = val + 1
        #    height = height - 30
        #    if(i.collision == False):
        #        output_draw_time = f"Velocita veicoli: {i.probability_change}"
        #        arcade.draw_text(output_draw_time, 300, height, arcade.color.BLACK, 25)

        output_draw_time = f"Numero Veicoli Totali: {self.total_car}"
        arcade.draw_text(output_draw_time, 300, 1020, arcade.color.BLACK, 25)

        output_draw_time = f"Numero Veicoli Nell'Incrocio: {val}"
        arcade.draw_text(output_draw_time, 300, 990, arcade.color.BLACK, 25)

        output_draw_time = f"Frame Count: {self.global_spawn}"
        arcade.draw_text(output_draw_time, 300, 960, arcade.color.BLACK, 25)

        output_draw_time = f"Incidenti: {self.incidenti}"
        arcade.draw_text(output_draw_time, 300, 930, arcade.color.BLACK, 25)

        output_draw_time = f"Cronometro: {self.hour}:{self.timer_string_min}:{self.timer_string_sec}"
        arcade.draw_text(output_draw_time, 300, 900, arcade.color.BLACK, 25)

        if(self.current_status == 1 and self.yellow_start == False):
            cube = arcade.load_texture("../Sprites/Lights/Green.png")
            cube.draw_scaled(810, 750, angle=180)
        elif(self.current_status == 1 and self.yellow_start == True):
            cube = arcade.load_texture("../Sprites/Lights/Yellow.png")
            cube.draw_scaled(810, 750, angle=180)
        else:
            cube = arcade.load_texture("../Sprites/Lights/Red.png")
            cube.draw_scaled(810, 750, angle=180)

        if(self.current_status == 2 and self.yellow_start == False):
            cube = arcade.load_texture("../Sprites/Lights/Green.png")
            cube.draw_scaled(1170, 690, angle=90)
        elif(self.current_status == 2 and self.yellow_start == True):
            cube = arcade.load_texture("../Sprites/Lights/Yellow.png")
            cube.draw_scaled(1170, 690, angle=90)
        else:
            cube = arcade.load_texture("../Sprites/Lights/Red.png")
            cube.draw_scaled(1170, 690, angle=90)

        if(self.current_status == 3 and self.yellow_start == False):
            cube = arcade.load_texture("../Sprites/Lights/Green.png")
            cube.draw_scaled(1110, 330)
        elif(self.current_status == 3 and self.yellow_start == True):
            cube = arcade.load_texture("../Sprites/Lights/Yellow.png")
            cube.draw_scaled(1110, 330)
        else:
            cube = arcade.load_texture("../Sprites/Lights/Red.png")
            cube.draw_scaled(1110, 330)

        if(self.current_status == 4 and self.yellow_start == False):
            cube = arcade.load_texture("../Sprites/Lights/Green.png")
            cube.draw_scaled(750, 390, angle=270)
        elif(self.current_status == 4 and self.yellow_start == True):
            cube = arcade.load_texture("../Sprites/Lights/Yellow.png")
            cube.draw_scaled(750, 390, angle=270)
        else:
            cube = arcade.load_texture("../Sprites/Lights/Red.png")
            cube.draw_scaled(750, 390, angle=270)

    def advance_song(self):
        self.current_background_song += 1
        if self.current_background_song >= len(self.background_music_list):
            self.current_background_song = 0

    def query_5_min(self):
        self.cursor = cursor
        self.cursor.execute("INSERT INTO dbo.ClockTable (NVehicle, Hours, Collision) VALUES (?, ?, ?)", (self.total_car_min, self.hour, self.incidenti_min))
        cursor.commit()
        cursor.cancel()
        self.incidenti_min = 0
        self.total_car_min = 0

    def on_update(self, delta_time=0.50):

        self.timer_now = datetime.datetime.now().replace(microsecond=0)
        self.timer_result =  self.timer_now - self.timer_start

        if(self.timer_result.seconds != self.timer_second_sup):
            self.timer_second_sup = self.timer_result.seconds
            self.timer_second = self.timer_second + 1
            if(self.timer_second <= 9):
                self.timer_string_sec = "0" + str(self.timer_second)
            else:
                self.timer_string_sec = str(self.timer_second)
        if(self.timer_second == 59):
            self.timer_second = 0
            self.timer_minute = self.timer_minute + 1
            if(self.timer_minute % 5 == 0):
                self.query_5_min()
            if(self.timer_minute <= 9):
                self.timer_string_min = "0" + str(self.timer_minute)
            else:
                self.timer_string_min = str(self.timer_minute)

        self.global_spawn += 1
        background_music_looper = self.background_music.get_stream_position()
        if background_music_looper == 0.0:
            self.advance_song()
            self.play_background_song()

        if(self.frame_count % self.red_time == 0 and self.frame_count != 0):
            self.yellow_start = True
            if(self.yellow_count == 0):
                for cube in self.cube_list:
                    if(cube.val == 4):
                        if(cube.stop_status == True):
                            cube.stop_status = False
            if(self.yellow_count % self.yellow_time == 0 and self.yellow_count != 0):
                self.yellow_start = False
                self.yellow_count = 0
                if(self.current_status < 4):
                    self.current_status += 1
                else:
                    self.current_status = 1
                for cube in self.cube_list:
                    if(cube.val == 4 or cube.val == 6):
                        cube.change_status(self.current_status)
            else:
                self.yellow_count += 1
        if(self.yellow_start != True):
            self.frame_count += 1

        for car in self.car_list:
            car.set_car_list(self.car_list)

        self.car_list.update()
        for car in self.car_list:
            car.fov.sprite.update()
            car.fov.stop_sprite.update()

        if(self.hour == 1 or self.hour == 2 or self.hour == 3 or self.hour == 4):
            self.spawn_rate = 1500
        elif(self.hour == 5 or self.hour == 0):
            self.spawn_rate = 750
        elif(self.hour == 6 or self.hour == 23):
            self.spawn_rate = 500
        elif(self.hour == 7 or self.hour == 11 or self.hour == 22):
            self.spawn_rate = 300
        elif(self.hour == 8 or self.hour == 10 or self.hour == 16 or self.hour == 21):
            self.spawn_rate = 200
        elif(self.hour == 9 or self.hour == 20):
            self.spawn_rate = 150
        elif(self.hour == 15 or self.hour == 17 or self.hour == 19):
            self.spawn_rate = 125
        elif(self.hour == 12 or self.hour == 14 or self.hour == 18):
            self.spawn_rate = 100
        elif(self.hour == 13):
            self.spawn_rate = 75

        if(self.global_spawn % self.spawn_rate == 0):
            self.spawn_car()

    def spawn_car(self):
        auto = car()
        auto.setup(self.cube_list, self.car_list)
        auto.time_service(self.hour, self.timer_minute, self.timer_second)
        self.car_list.append(auto)
        self.total_car += 1
        self.total_car_min += 1

    def on_key_press(self, key, modifiers):
        if key == arcade.key.F:
            self.set_fullscreen(not self.fullscreen)

            width, height = self.get_size()
            self.set_viewport(0, width, 0, height)

        if key == arcade.key.C:
            if(self.change == 1):
                for auto in self.car_list:
                    if(auto.fov.sprite.alpha != 0):
                        auto.fov.sprite.alpha = 0
                        auto.fov.stop_sprite.alpha = 0
                self.change = 0
            else:
                for auto in self.car_list:
                    if(auto.fov.sprite.alpha == 0):
                        auto.fov.sprite.alpha = 255
                        auto.fov.stop_sprite.alpha = 255
                self.change = 1

        if key == arcade.key.KEY_1:
            auto = car()
            auto.setup(self.cube_list, self.car_list)
            auto.time_service(self.hour, self.timer_minute, self.timer_second)
            self.car_list.append(auto)
            self.total_car += 1
            self.total_car_min += 1

        if key == arcade.key.P:
            auto = car()
            auto.ignore = True
            auto.speed = 500
            auto.setup(self.cube_list, self.car_list)
            auto.time_service(self.hour, self.timer_minute, self.timer_second)
            self.car_list.append(auto)
            self.total_car += 1
            self.total_car_min += 1

        if key == arcade.key.UP:
            if(self.hour < 23):
                self.hour = self.hour + 1
                self.timer_start = datetime.datetime.now().replace(microsecond=0)
                self.timer_second = 0
                self.timer_minute = 0
                self.timer_string_min = "00"
                self.timer_string_sec = "00"
                self.incidenti_min = 0
                self.total_car_min = 0

        if key == arcade.key.DOWN:
            if(self.hour > 0):
                self.hour = self.hour - 1
                self.timer_start = datetime.datetime.now().replace(microsecond=0)
                self.timer_second = 0
                self.timer_minute = 0
                self.timer_string_min = "00"
                self.timer_string_sec = "00"
                self.incidenti_min = 0
                self.total_car_min = 0

    def set_update_rate(self, rate: float):

        pyglet.clock.unschedule(self.update)
        pyglet.clock.schedule_interval(self.update, rate)
        pyglet.clock.unschedule(self.on_update)
        pyglet.clock.schedule_interval(self.on_update, rate)


import torch
from torch import autocast
from diffusers import StableDiffusionPipeline,StableDiffusionImg2ImgPipeline
from djl_python import Input, Output
import io
from PIL import Image
from io import BytesIO
import requests

textPipe = StableDiffusionPipeline.from_pretrained("/opt/ml/model/stable-diffusion-v1-4",revision="fp16", torch_dtype=torch.float16).to("cuda")
imgPipe = StableDiffusionImg2ImgPipeline.from_pretrained("/opt/ml/model/stable-diffusion-v1-4",revision="fp16", torch_dtype=torch.float16).to("cuda")
#url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
#response = requests.get(url)
def handle(inputs: Input) -> Output:
    global textPipe
    global imgPipe
    if inputs.is_empty():
        return None
    content_type = inputs.get_property("content-type")
    if content_type == "application/json":
        param = inputs.get_as_json()
        prompt =param.get('prompt')
        height =param.get('height')
        width =param.get('width')
        steps =param.get('steps')
        scale =param.get('scale')
        with torch.autocast("cuda"):
            image = textPipe(prompt,guidance_scale=scale, num_inference_steps=steps,height=height, width=width)["sample"][0]
            buf = io.BytesIO()
            image.save(buf, format='PNG')
            byte_im = buf.getvalue()
            return Output().add(byte_im).add_property("content-type","image/png")
    elif content_type is not None and content_type.startswith("text/"):
        prompt =inputs.get_as_string()
        with torch.autocast("cuda"):
            image = textPipe(prompt)["sample"][0]
            buf = io.BytesIO()
            image.save(buf, format='PNG')
            byte_im = buf.getvalue()
            return Output().add(byte_im).add_property("content-type","image/png")
    else:
        init_image = Image.open(BytesIO(inputs.get_as_bytes())).convert("RGB")
        #init_image = Image.open(BytesIO(response.content)).convert("RGB")
        init_image = init_image.resize((768, 512))
        prompt =inputs.get_as_string(key="prompt")
        #prompt = "A fantasy landscape, trending on artstation"
        with torch.autocast("cuda"):
            image = imgPipe(prompt=prompt, init_image=init_image, strength=0.75, guidance_scale=7.5).images[0]
            buf = io.BytesIO()
            image.save(buf, format='PNG')
            byte_im = buf.getvalue()
            return Output().add(byte_im).add_property("content-type","image/png")


'''
2023-05-03
김근호
반복문 1~10 출력하기, 1~10 까지의 합계 구하기
'''

#while 반복문
i = 1 # 반복 횟수 초기화
sum = 0 # 합계
while i <= 10 : # 반복 조건
    sum = sum + i # 합계 저장
    i = i + 1 # i 1증가
print("1~10까지의 합계:{}".format(sum))

#i = 1 for은 i 초기화할 필요가 없다. # 반복 횟수 초기화
sum1 = 0 # sum으로 할, 시 합계 초기화
#for 반복문
for j in range (1, 11) : # 반복 조건
    sum1 = sum1 + j # 합계 구하기
print("1~10까지의 합계:{}".format(sum1))


class convIntoASCII:
    def convert(self,name):

        ascii = ''
        posi1 = ''
        for i in range(33, 126):
            ascii += chr(i)

        for x in name:
            pos = ascii.find(x)
            pos += 33
            posi = str(pos)
            posi1 += posi
        return posi1
    #print(posi1)

name = input('enter your name to convert it to ASCII num\n')
nam = convIntoASCII()
e = nam.convert(name)
print(e)


from jax import random
import jax.numpy as jnp

def uniform_prior_particles(key, minimums, maximums, N):
    """Produces an array of N particles sampled unformly within a
    multidimensional box defined by minimums and maximums for each parameter.

    Parameters
    ----------
    key : jax.random.PRNGKey
        The pseudo-random number generator key used to seed all
        jax random functions.
    minimums : Vector
        A vector of minimum parameter values
    maximums : Vector
        A vector of maximum parameter values
    N : Int
        The number of particles

    Returns
    -------
    Array
        A set of particles from the desired distribution.
    """
    n_params = len(minimums)
    return random.uniform(key,(n_params,N),
                          minval=jnp.asarray(minimums).reshape(n_params,1),
                          maxval=jnp.asarray(maximums).reshape(n_params,1))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import click
from pypiup.requirement import Requirement

class Requirements(object):

    def __init__(self, requirements_file):
        self.file = self.read_file(requirements_file)
        self.requirements = []

    def should_ignore_requirement(self, requirement):
        if requirement.startswith("#") or requirement == "":
            return True
        return False

    def read_file(self, requirements_filename):
        click.secho("\nAttempting to read %s ...\n" % requirements_filename, fg='magenta')

        try:
            requirements_file = open(requirements_filename)
            requirements_file_lines = requirements_file.read().splitlines()
            with click.progressbar(
                    iterable=requirements_file_lines,
                    label='Getting requirements details',
                    bar_template='%(label)s %(bar)s | %(info)s',
                    fill_char=click.style(u'█', fg='cyan'),
                    empty_char=' ') as bar:
                requirements = []
                for line in bar:
                    if not self.should_ignore_requirement(line):
                        requirement = Requirement(line)
                        requirements.append(requirement)
                self.requirements = requirements
                self.show_details()
                self.show_stats()
                requirements_file.close()
        except IOError:
            return click.secho("Could not find %s. No such file or directory.\n" % (requirements_filename), fg='red')

    def show_details(self):
        click.echo()
        for requirement in self.requirements:
            requirement.output_details()

    def show_stats(self):
        stat_total = len(self.requirements)
        stat_uptodate = 0
        stat_needs_update = 0
        stat_invalid_semver = 0
        stat_invalid = 0

        for requirement in self.requirements:
            if requirement.valid:
                if requirement.status == "UPTODATE":
                    stat_uptodate += 1
                elif requirement.status == "NEEDS_UPDATE":
                    stat_needs_update += 1
                elif requirement.status == "INVALID_SEMVER":
                    stat_invalid_semver += 1
            else:
                stat_invalid += 1

        click.echo(click.style("\nStatistics", bold=True, underline=True, fg='yellow'))
        click.echo("  Total Requirements: %s" % stat_total)
        click.echo("  Up to date: %s" % stat_uptodate)
        click.echo("  Update available: %s" % stat_needs_update)
        click.echo("  Invalid Semver: %s" % stat_invalid_semver)
        click.echo("  Non PyPI Requirements: %s" % stat_invalid)


from __future__ import unicode_literals
import frappe

from frappe.utils import flt

def execute(filters=None):
	return get_columns(), get_data(filters)

def get_columns():
	return [
		"Factura:Link/Sales Invoice:90",
		"Fecha:Date:90",
		"Paciente:Link/Customer:200",
		"Medico:Link/Customer:180",
		"Servicio:Link/Item Group:90",
		"Grupo:Data:90",
		"Total:Currency:90",
		"Porcentaje:Percent:80",
		"Comision:Currency:100",
	]

def get_data(filters):

	return frappe.db.sql("""
		SELECT
			p.name AS invoice,
			p.posting_date,
			p.customer,
			p.medico,
			c.item_name,
			c.item_group,
			c.amount,
			m.referido,
			c.amount * (m.referido/100.00) AS comision
		FROM
			`tabSales Invoice` AS p
		JOIN
			`tabSales Invoice Item` AS c
		ON
			p.name = c.parent
		JOIN
			`tabMedico` AS m
		ON
			p.medico = m.name
		WHERE
			%(filters)s
		ORDER BY
			p.posting_date
	""" % { "filters": get_filters(filters) }, filters)

def get_filters(filters):
	query = ['p.docstatus = 1']

	if filters.get('from_date'):
		query.append('p.posting_date >= %(from_date)s')

	if filters.get('to_date'):
		query.append('p.posting_date <= %(to_date)s')

	if filters.get('medico'):
		query.append('p.medico = %(medico)s')

	if filters.get('item_group'):
		query.append('c.item_group = %(item_group)s')

	return " AND ".join(query)


#!/usr/bin/env python
#-*- coding:utf8-*-

'''
输入三个整数x,y,z，请把这三个数由小到大输出。
'''

L=[]
for i in range(3):
	num=int(input("please input num\n"))
	L.append(num)
L.sort()
print(L)


# https://leetcode.com/problems/sort-array-by-parity/

# find even and odd separately [even] [odd]
# merge it together +
def Solution(A=list):
    even = []
    odd = []
    for i in A:
        if i % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    return even + odd

print(Solution(A=[3, 1, 2, 4] * 250))


# -*- coding: utf-8 -*-
import scrapy
from time import sleep

class DoubanSpider(scrapy.Spider):
    name = 'DouBan'
    allowed_domains = ['douban.com']
    start_urls = ['https://book.douban.com/top250?start=0']

    def parse(self, response):
        sleep(3)
        book_stars = response.xpath('//span[@class="rating_nums"]').xpath('string(.)').extract()
        book_names = []
        for name in response.xpath('//div[@class="pl2"]/a').xpath('string(.)').extract():
            book_names.append(name.replace('\n','').replace(' ',''))
        next_url = response.xpath('//span[@class="next"]/a/@href').extract_first()
        for n,s in zip(book_names,book_stars):
            yield {
                'book_name':n,
                'book_star':s
            }
        yield scrapy.Request(next_url,callback=self.parse)


# -*- coding: utf-8 -*-
from osv import osv, fields
from tools.translate import _
from datetime import timedelta, datetime
from osv.osv import TransactionExecute

class WizardFraccionarViaExtralines(osv.osv_memory):

    _name = "wizard.fraccionar.via.extralines"
    _inherit = "wizard.fraccionar.via.extralines"

    def action_fraccionar_via_extralines(self, cursor, uid, ids, context=None):
        if context is None:
            context = {}

        wiz = self.browse(cursor, uid, ids)[0]

        if not wiz.first_term_payment:
            return super(WizardFraccionarViaExtralines, self).action_fraccionar_via_extralines(
                cursor, uid, ids, context
            )

        factura_ids = context.get("active_ids")
        factura_o = self.pool.get("giscedata.facturacio.factura")
        user_o = self.pool.get("res.users")
        data_final = (
            datetime.strptime(wiz.data_inici, "%Y-%m-%d") + timedelta(days=365 * 10)
        ).strftime("%Y-%m-%d")

        msgs = []
        has_errors = False
        for info in factura_o.read(cursor, uid, factura_ids, ["number"]):
            base_res = _(u"Resultat '{0}' (ID {1}):\n").format(info["number"], info["id"])
            try:
                factura_teo = TransactionExecute(cursor.dbname, uid, "giscedata.facturacio.factura")
                factura = factura_o.browse(cursor, uid, info["id"])
                ntermes = wiz.ntermes - 1
                amount = (factura.residual / wiz.ntermes) * ntermes
                factura_teo.fraccionar_via_extralines(
                    info["id"],
                    ntermes,
                    wiz.data_inici,
                    data_final,
                    journal_id=wiz.journal_id.id,
                    amount=amount,
                    context=context,
                )
                comment_head = "{} ({}): Fraccionament extralines en {} quotes.\n".format(
                    datetime.now().strftime("%Y-%m-%d"),
                    "".join(
                        [
                            word[0]
                            for word in user_o.read(cursor, uid, uid, ["name"])["name"].split(" ")
                        ]
                    ),
                    wiz.ntermes,
                )
                old_comment = factura.comment or ""
                new_comment = comment_head + old_comment
                factura_teo.write(info["id"], {"comment": new_comment})

            except Exception as e:
                has_errors = True
                if hasattr(e, "value"):
                    res = e.value
                else:
                    res = str(e)
                msgs.append(base_res + res)

        if has_errors:
            msgs = [
                _(u"Hi ha hagut problemes al processar {0} factures: ").format(len(msgs))
            ] + msgs
            msg = "\n\n".join(msgs)
        else:
            msg = _(u"S'han processat totes les factures correctament.")

        msg = _(u"Número de factures processades: {0}.\n\n").format(len(factura_ids)) + msg

        final_state = "end" if not has_errors else "error"
        wiz.write({"info": msg, "state": final_state})
        return True

    _columns = {
        "first_term_payment": fields.boolean(
            "Carregar primer termini a la factura actual", required=True
        ),
    }

    _defaults = {
        "first_term_payment": lambda *a: True,
        "data_inici": lambda *a: (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"),
    }

WizardFraccionarViaExtralines()


import numpy as np
from openslide import open_slide
from openslide.deepzoom import DeepZoomGenerator
import os
import sys

# to remove leading and trailing whitespace
image_path = sys.argv[1]
# split the line into words
words = image_path.split("/")
svs_file = words[len(words)-1]#"23-168-001-004.svs"
slide = open_slide(f"{image_path}")
current_svs_file_nm = svs_file.split(".")[0]
print(current_svs_file_nm)
tiles = DeepZoomGenerator(slide, tile_size=1024, overlap=0, limit_bounds=False)
level = tiles.level_count - 1
cols, rows = tiles.level_tiles[level]
#os.system(f'mkdir processing/tiles/{current_svs_file_nm}_{level}')
# we are looping over the words array and printing the word
# with the count of 1 to the STDOUT
for col in range(cols):
    for row in range(rows):
    # write the results to STDOUT (standard output);
    # what we output here will be the input for the
    # Reduce step, i.e. the input for reducer.py
        img = tiles.get_tile(level, (0, 0))
        img_d = list(img.getdata())
        #dt=np.dtype
        np_img = np.asarray(img)
        data = np_img.tobytes()
        print(f"{level}_{str(col)}_{str(row)}_{current_svs_file_nm}\t{data}")


# Write a program that takes as input a sorted list and updates it
# so that all duplicates have been removed and the remaining elements have been shifted left
# to fill the emptied indices.
#
# Fill the remaining indices with zeros.
# Return the number of valid elements.
# You cant use sets for this coding challenge.

def delete_duplicates(list):
    write_index = 1                                 # Q: Why not zero? is it because we check duplication with prev? 0?

    for i in range(1, len(list)):                   # start from 1 and go till the end of list
        print(f'\nIteration # {i}')
        print(list)
        print(write_index)
        if list[write_index - 1] != list[i]:        # Q: 1:32:17 ??  checking if current element is the same as previous element: 1 != 4
            list[write_index] = list[i]             # after != HE SKIPS THIS PART at video. overwrite index write_index and set it to current element
            write_index += 1                        # increment the right index
                                                    # Q: i = i+1 is this simply adding to list?
    for i in range(write_index, len(list)):
        list[i] = 0                                  # Q: ?

    print(list,'<-- elements have shifted left')

test_list = [1, 4, 6, 6, 8, 9, 11, 11, 12]
delete_duplicates(test_list)

ALGO/AL4/Delete duplicates from sorted list.py