#
# QBot is greedy but careful about playing a Q if it
# doesn't gain a lot of points from the move
#

__author__ = 'John Bohannon'

from ScrabbleBot import ScrabbleAI
from ScrabbleBot import ScrabbleBoard
from ScrabbleBot import ScrabbleUtils

class QBot(ScrabbleAI.ScrabbleAI):
    def make_move(self, board: ScrabbleBoard, letters: list, solutions: list) -> ScrabbleUtils.ScrabbleMove:
        if len(solutions) > 0:
            solutions.sort(reverse=True)
            for i in solutions:
                if ('Q' in i.letters) and i.score < 20:
                    continue
                else:
                    return i
        else:
            return None


ComparePlayers = True # If you would like to compare two players set to True and fill in both player details, If only one player set to False and Fill in only the first player details

PlayerName = "Nkunku" # Enter Player folder name e.g. Lukaku
Season = "2019-2020" # Enter season e.g. 2018-2019
FullPlayerName = "Christopher Nkunku" # Enter players full name for display on graph e.g. Romelu Lukaku

PlayerName2 = "Hazard" # Enter Player folder name e.g. Lukaku
Season2 = "2018-2019" # Enter season e.g. 2018-2019
FullPlayerName2 = "Jadon Sancho" # Enter players full name for display on graph e.g. Romel

if not ComparePlayers:
	import Radar
else: import Radar2


# NOTE to run this in REPL
# import examples
# examples.<function-name()>

import os

# OAuth stuff
import random
import socket
import sys

# NOTE: This app uses PRAW:https://praw.readthedocs.io/en/stable/
import praw

# config parser
# https://docs.python.org/3/library/configparser.html#configparser.ConfigParser
import configparser

# respect rate limit of 1 request/ sec
# see: https://www.reddit.com/r/redditdev/comments/13wsiks/api_update_enterprise_level_tier_for_large_scale/
import time

print(f"[{os.path.basename(__file__)}] Hello world!")

# GENERAL SETTINGS
# Set this to true if you want to use an authorized reddit instance
is_authorized=True
# turn on debug for printing
is_debug=True

# NETWORK SETTINGS
PORT=7777 # NOTE: 7777 is the default port for a Terraria server, change this if you happen to be playing Terraria online

# RATE LIMITS
# With oauth, 100 queries / 60 sec, or wait 0.6 sec/ query
# with no oauth, 10 queries/ 60 sec or wait 6 sec/ query
sec=60
queries=100
OPTIMAL_SLEEP_TIME=sec/queries
BUFFERED_OPTIMAL_SLEEP_TIME=sec/queries * 1.5
SLEEP_TIME=1

# praw.ini data
READ_ONLY='Read-Only'
AUTHORIZED='Authorized'

#OAUTH2
TEMPORARY="temporary"
# indicate you need permanent access for an account
PERMANENT="permanent"

# INIT
praw_example_ini='praw_example.ini'
praw_ini='praw.ini'
# change this when you want to change to production
selected_ini=praw_example_ini
# set up configparser to read .ini
config = configparser.ConfigParser()
print(f'Configuring settings using: {selected_ini}')
config.read(selected_ini)

# get info for Read-Only Instance
client_id     = config.get('Read-Only', 'client_id')
client_secret = config.get('Read-Only', 'client_secret')
user_agent    = config.get('Read-Only', 'user_agent')
# get info for Authorized Instance
username     = config.get('Authorized', 'username')
password     = config.get('Authorized', 'password')
redirect_uri = config.get('Authorized', 'redirect_uri')
# END_INIT

def handle_connection():
    """
    Wait for and then return a connected socket..

    Opens a TCP connection on port 7777, and waits for a single client.

    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
    # check NETWORK_SETTINGS to see what ports we're using
    print(f"Server binding to http://127.0.0.1:{PORT}")
    server.bind(("127.0.0.1", PORT))

    client = server.accept()[0]
    server.close()

    return client
#fin

def send_message(client, message):
    """Send message to client and close the connection."""
    print(message)
    client.send(f"HTTP/1.1 200 OK\r\n\r\n{message}".encode("utf-8"))
    client.close()
#fin

def get_refresh_token_example():
    scope_input = input(
        "Enter a comma separated list of scopes, or '*' for all scopes: "
    )
    scopes = [scope.strip() for scope in scope_input.strip().split(",")]
    reddit = praw.Reddit(
        user_agent="I'm a Bot by /u/BotMaster5000",
        redirect_url="http://127.0.0.1:7777"
    )

    # unique possibly random string for each auth request
    state = str(random.randint(0,65000))
    url = reddit.auth.url(duration=PERMANENT, scopes=scopes, state=state)
    print(f"Open this url in your browser: {url}")
    client = handle_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split("", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value for (key,value) in [token.split("=") for token in param_tokens]
    }

    # state mismatch
    if state != params["state"]:
        send_message(
            client,
            f"[ERROR]: State mismatch. Expected: {state}, Received {params['state']}",
        )
        return 1
    elif "error" in params:
        send_message(
            client,
            params["error"]
        )
        return 1
    #fi

    refresh_token = reddit.auth.authorize(params["code"])
    send_message(
        client,
        f"Refresh token: {refresh_token}"
    )
    return refresh_token
#fin

def submit_link_post():

    title = "PRAW documentation"
    url = "https://praw.readthedocs.io"
    reddit.subreddit("test").submit(title, url=url)
#fin

def show_base64encoding_note():
    print(
    """
    see: https://en.wikipedia.org/wiki/Basic_access_authentication
    When the user agent wants to send authentication credentials to the server, it may use the Authorization header field.

    The Authorization header field is constructed as follows:[9]

    The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
    The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.[9]
    The resulting string is encoded using a variant of Base64 (+/ and with padding).
    The authorization method and a space character (e.g. "Basic ") is then prepended to the encoded string.

    For example, if the browser uses Aladdin as the username and open sesame as the password, then the field's value is the Base64 encoding of Aladdin:open sesame, or QWxhZGRpbjpvcGVuIHNlc2FtZQ==. Then the Authorization header field will appear as:

    Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

    Base64(client_id:client_secret)
    """
    )
#fin


import os
import re
from math import pow

import yaml
import json

from LocationList import vanilla_locations

with open('byte_values/loc_text.yaml', 'r') as yamlfile:
    bl_text_firstplay = (yaml.safe_load(yamlfile)).get('text_firstplay')

with open('byte_values/val_text_characters.yaml', 'r') as yamlfile:
    byte_text_characters = yaml.safe_load(yamlfile)

with open ('byte_values/val_items.yaml', 'r') as yamlfile:
    byte_items = (yaml.safe_load(yamlfile))

with open ('byte_values/val_additem_functions.yaml', 'r') as yamlfile:
    additem_functions = (yaml.safe_load(yamlfile))

with open('byte_values/loc_maps.yaml', 'r') as yamlfile:
    bl_starting_location = (yaml.safe_load(yamlfile)).get('initial_map')

with open('byte_values/val_maps.yaml', 'r') as yamlfile:
    byte_maps = (yaml.safe_load(yamlfile))

def conv_chars_to_bytes(charstring):
    hexval = 0
    for i in reversed(range(0, len(charstring))):
        hexval += byte_text_characters.get(charstring[i]) * pow(256, (len(charstring) - 1 - i))
    return(int(hexval).to_bytes(len(charstring),'big'))

def patch_rom(infile, outfile, general_settings, randomized_locations):

    # Write to new ROM
    os.system('copy "%s" "%s"' % (infile, outfile))
    f=open(outfile,'rb+')

    ## Always apply following modifications regardless of settings
    # Overwrite "First Play" text on new savefile with "Randomized"
    f.seek(bl_text_firstplay)
    f.write(conv_chars_to_bytes('Rand'))
    f.write(conv_chars_to_bytes('omiz'))
    f.write(conv_chars_to_bytes('ed'))

    ##

    # Disable developer logos
    if 'skip_devlogos' in general_settings:
        f.seek(0xF298)
        f.write((0x00000000).to_bytes(4, 'big'))
        f.write((0x24040700).to_bytes(4, 'big'))
        f.write((0xA44400AC).to_bytes(4, 'big'))

    # Disable intro video
    if 'skip_intro' in general_settings:
        f.seek(0x11c84)
        f.write((0x34051000).to_bytes(4, 'big'))

    # Disable demo reel
    if 'disable_demo' in general_settings:
        f.seek(0x12644)
        f.write((0x1000).to_bytes(2, 'big'))

    # Change initial map (StarRod style) ?? doesnt really work
    # f.seek(0x2811720)
    # f.write((0x24010001).to_bytes(4, 'big'))
    # f.seek(0x2811728)
    # f.write((0x24010001).to_bytes(4, 'big'))

    # Load vanilla locations
    item_locations = vanilla_locations

    for modified_check in randomized_locations.keys():
        new_location_tuple = (item_locations[modified_check][0],
                              item_locations[modified_check][1],
                              item_locations[modified_check][2],
                              item_locations[modified_check][3],
                              randomized_locations.get(modified_check))
        item_locations[modified_check] = new_location_tuple

    # Iterate over all item check locations
    for location in item_locations.items():
        # Write different addObject function if necessary (mostly used in Scripts)
        cur_locationtype = location[1][0]
        cur_itemname = location[1][4]
        if cur_locationtype == 'Script':
            if byte_items.get(cur_itemname).get('isKeyItem'):
                cur_additem_function_val = additem_functions.get('addKeyItem')
            elif byte_items.get(cur_itemname).get('isBadge'):
                cur_additem_function_val = additem_functions.get('addBadge')
            elif cur_itemname.startswith('Star Piece'):
                cur_additem_function_val = additem_functions.get('addStarPieces')
            else:
                cur_additem_function_val = additem_functions.get('addItem')
            for func_adress in location[1][2]:
                f.seek(func_adress)
                f.write(cur_additem_function_val.to_bytes(4,'big'))

        # Iterate over all item byte locations of that item check
        for item_adress in location[1][1]:
            # Write byte value of item to item byte location
            if (cur_itemname.startswith('Star Piece') and
                cur_locationtype == 'Script' and
                (item_adress == location[1][1][-1] or # hacky solution for Goombaria's Dolly
                 item_adress == location[1][1][1])):
                # Find # of Star Pieces to set
                reg_pattern_sp_count = re.compile(r'(?<=\()(\d+)(?=\))')
                reg_match_sp_count = reg_pattern_sp_count.search(cur_itemname)
                item_value = int(reg_match_sp_count.group())
            else:
                item_value = byte_items.get(cur_itemname).get('bytes')
            f.seek(item_adress)
            f.write(item_value.to_bytes(4,'big'))

    # testing
    # f.seek(0x8c7a20)
    # f.write((0x00000100).to_bytes(4, 'big'))

# write itemvalue into dgb_14
# f.seek(0xC4F4D0)
# f.write((0x0000015E).to_bytes(4,'big'))

# start of black magic
    # Don't start the game from Mario's house
    # f.seek(bl_starting_location)
    # f.write(byte_maps.get('kmr').get('kmr_10').get('bytes').to_bytes(4,'big'))
#    f.write((0x23000000).to_bytes(4,'big'))
#    f.seek(0x168083)
#    f.write((0x00A3).to_bytes(2, 'big'))

    #code patch: start with goombario out
    # f.seek(0x808A8)
    # f.write((0xA0820012).to_bytes(4,'big'))
    # f.write((0xA082000A).to_bytes(4,'big')) # enable action command
    # f.write((0x2402FFFF).to_bytes(4,'big'))
    # f.seek(0x808E4)
    # f.write((0xA0800000).to_bytes(4,'big'))
    # #have every party member
    # f.write((0xA0A20014).to_bytes(4,'big'))
    # #enable menus
    # f.seek(0x168074)
    # f.write((0x2406FF81).to_bytes(4,'big'))
# end of black magic

# for i in range(302,303):
#     f.seek(0x6B450 + i*0x20)
#     nameptr = int.from_bytes(f.read(4), 'big') - 0x80024C00
#     f.seek(nameptr)
#     name = f.read(8).decode().strip('\0')
#     print(f'{i}: {name}')

# with open('E:/Downloads/_Git/MrCheeze_paper-mario-randomizer/roomdata.json', 'r') as jsonfile:
#     roomdata = json.load(jsonfile)

# # invert byte_items
# items_byte = {}
# for i in byte_items.keys():
#     items_byte[byte_items.get(i).get('bytes')] = i

# for i in range(421):
#     f.seek(0x6B450 + i*0x20)
#     nameptr = int.from_bytes(f.read(4), 'big') - 0x80024C00
#     f.seek(4, os.SEEK_CUR)
#     roomptr = int.from_bytes(f.read(4), 'big')
#     f.seek(nameptr)
#     name = f.read(8).decode().strip('\0')
#     print(f'{name}')
#     count_item = 0
#     for itemptr in roomdata[name]['items']:
#         item_location = roomptr + itemptr - 0x80240000
#         f.seek(item_location)
#         item = int.from_bytes(f.read(4), 'big')
#         if 0 < item < 0x200:
#             print(f'    {hex(item_location)}: {items_byte.get(item)}')
#         else:
#             print(f'    {hex(item_location)}: {item}')
#         count_item += 1

    # Save patched file
    f.close()

    # Fix bootcode
    try:
        assert(os.path.isfile('rn64crc2\\rn64crc.exe'))
        os.system('rn64crc2\\rn64crc.exe "%s" -u' % outfile)
    except AssertionError:
        print('')
        exit(1)

    # Output spoiler log if necessary
    trimmed_locations = {}
    for location in item_locations.items():
        trimmed_locations[location[0]] = location[1][4]
    spoiler_log = json.dumps(trimmed_locations, indent=4)
    try:
        jsonSpoiler = open("spoiler_log.json", "w")
        jsonSpoiler.write(spoiler_log)
        jsonSpoiler.close()
    except OSError:
        print('Error: Spoiler log could not be written!')


from __future__ import annotations

import re
from typing import NamedTuple

import discord
from redbot.core import commands

from .helpers import embed_from_msg, find_messages

CHANNEL_RE = re.compile(r"^<#(\d{15,21})>$|^(\d{15,21})$")

class GlobalTextChannel(NamedTuple):
    matched_channel: discord.TextChannel

    @classmethod
    async def convert(cls, ctx: commands.Context, argument: str):

        bot = ctx.bot

        match = CHANNEL_RE.match(argument)
        channel = None
        if match:
            idx = next(filter(None, match.groups()), None)

            if idx:
                channel_id = int(idx)
                channel = bot.get_channel(channel_id)

        if not channel or not isinstance(channel, discord.TextChannel):
            raise commands.BadArgument('Channel "{}" not found.'.format(argument))

        return cls(channel)

class QuoteTools(commands.Cog):
    """
    Cog for quoting messages by ID
    """

    __author__ = "mikeshardmind(Sinbad)"
    __version__ = "2021.03"

    async def red_delete_data_for_user(self, **kwargs):
        """ Nothing to delete """
        return

    def format_help_for_context(self, ctx):
        pre_processed = super().format_help_for_context(ctx)
        return f"{pre_processed}\nCog Version: {self.__version__}"

    def __init__(self, bot, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bot = bot

    @commands.command()
    async def quote(
        self, ctx, channels: commands.Greedy[GlobalTextChannel] = None, *messageids: int
    ):
        """
        gets (a) message(s) by ID(s)

        User must be able to see the message(s)

        You need to specify specific channels to search (by ID or mention only!)
        """

        if not messageids or not channels:
            return await ctx.send_help()

        chans = [c.matched_channel for c in channels]

        msgs = await find_messages(ctx, messageids, chans)
        if not msgs:
            return await ctx.maybe_send_embed("No matching message found.")

        for m in msgs:
            if await ctx.embed_requested():
                em = embed_from_msg(m)
                await ctx.send(embed=em)
            else:
                msg1 = "\n".join(
                    [
                        f"Author: {m.author}({m.author.id})",
                        f"Channel: <#{m.channel.id}>",
                        f"Time(UTC): {m.created_at.isoformat()}",
                    ]
                )
                if len(msg1) + len(m.clean_content) < 2000:
                    await ctx.send(msg1 + m.clean_content)
                else:
                    await ctx.send(msg1)
                    await ctx.send(m.clean_content)


from rest_framework import serializers
from organizations.models import Organization
from donations.serializers import DonationSerializer

class OrganizationSerializer(serializers.ModelSerializer):
    krs = serializers.CharField(source='get_zero_krs')

    class Meta:
        model = Organization
        fields = (
            'pk', 'name', 'krs', 'street', 'zip_code',
            'wojewodztwo', 'powiat', 'gmina',
            'city', 'latitude', 'longitude',
        )

class OrganizationDetailSerializer(OrganizationSerializer):
    donations = DonationSerializer(many=True)
    class Meta(OrganizationSerializer.Meta):
        fields = OrganizationSerializer.Meta.fields + ('donations',)


from testing.tests import run_all_tests
from business.expense_service import business_start_console

f = open('ART.txt', 'r')
art = f.read()
print(art)
f.close()

run_all_tests()
business_start_console()


import glob
import os
from PIL import Image
import xmltodict
import json

def get_bboxs(my_dict):
    objects = my_dict['annotation']['object']

    if isinstance(objects, dict):
        objects = [objects]

    bboxs = []
    category = []

    for o in objects:

        bndbox = o['bndbox']
        bbox = [   (int(bndbox['xmin']), int(bndbox['ymin'])),
                    (int(bndbox['xmax']), int(bndbox['ymax']))
                ]
        bboxs.append(bbox)
        category.append(o['name'])

    return bboxs, category

def resize(img, my_dict, img_id, annotations, categories):
    w = img.size[0]
    h = img.size[1]

    ratio = min(800/w, 450/h)
    new_w = int(w*ratio)
    new_h = int(h*ratio)
    img = img.resize((new_w, new_h), Image.ANTIALIAS)

    bboxs, category = get_bboxs(my_dict)
    new_bboxs = []

    for i in range(len(bboxs)):
        bbox = bboxs[i]
        xmin = int(bbox[0][0] * ratio)
        ymin = int(bbox[0][1] * ratio)
        xmax = int(bbox[1][0] * ratio)
        ymax = int(bbox[1][1] * ratio)

        new_bbox = [(xmin, ymin), (xmax, ymax)]
        new_bboxs.append(new_bbox)

        ann_id = 0 if not annotations else max(x['id'] for x in annotations) +1

        annotations.append({
            "id": ann_id,
            "image_id": img_id,
            "category_id": next(x for x in categories if x["name"] == category[i])["id"],
            "bbox": [xmin, ymin, img.size[0], img.size[1]]
        })

    return img, annotations

def get_category(my_dict, categories):
    objects = my_dict['annotation']['object']

    if isinstance(objects, dict):
        objects = [objects]

    for o in objects:
        category = o["name"]

        if not any(c['name'] == category for c in categories):
            if category == "cat" or category == "dog":
                supercategory = "animal"
            elif category == "bike" or category == "car":
                supercategory = "vehicle"
            elif category == "person":
                supercategory = "person"
            elif category == "ball":
                supercategory = "sports"

            cat_id = 0 if not categories else max(x['id'] for x in categories) +1

            categories.append({
                "id": cat_id,
                "name": category,
                "supercategory": supercategory
            })

    return categories

def execute_file(imgfile, xmlfile, outputdir, categories, images, annotations):
    img = Image.open(imgfile)

    with open(xmlfile, 'r', encoding='utf-8') as file:
        my_xml = file.read()
        my_dict = xmltodict.parse(my_xml)

        categories = get_category(my_dict, categories)
        img_id = 0 if not images else max(x['id'] for x in images) +1

        img, annotations = resize(img, my_dict, img_id, annotations, categories)

        images.append({
            "id": img_id,
            "width": img.size[0],
            "height": img.size[1],
            "file_name": my_dict["annotation"]["path"]
        })

        path =  f"{outputdir}/{img_id}.jpg"
        img.save(path)

    return categories, images, annotations

def main(imagedir, xmldir, outputdir):
    imgs_list = glob.glob(os.path.join(imagedir, "*.jpg"))
    xmls_list = glob.glob(os.path.join(xmldir, "*.xml"))

    categories = []
    images = []
    annotations = []

    for i in range(len(imgs_list)):
        categories, images, annotations = execute_file(imgs_list[i], xmls_list[i], outputdir, categories, images, annotations)

    res = {
        "categories": categories,
        "images": images,
        "annotations": annotations
    }

    path = outputdir + "/res.json"
    with open(path, "w") as  outpath:
        json.dump(res, outpath)

if __name__=='__main__':
    imagedir = "./images"
    xmldir = "./xmldata"
    outputdir = "./output"

    main(imagedir, xmldir, outputdir)


#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time    : 2019-06-18 17:57
@Author  : Xincheng.Zhao
@Desc    : 获取每天新增企业
@Email   : zhaoboy9692@163.com
@File    : getnewdata.py
"""
import threading
from multiprocessing import Process
from time import sleep

import requests
from apscheduler.schedulers.blocking import BlockingScheduler

from common.utils import connect_redis, get_yesterday, read_data, more_get_token, write_data

device_id, tim, sign, header = more_get_token()

is_break = False

def new_enterprise_main():
    """
    获取新增企业数据
    :return:
    """
    global device_id, tim, sign, header
    device_id, tim, sign, header = more_get_token()
    r = connect_redis(0, 110)
    for url, city, province in creat_url():
        handle_page(url, city, province, r)
        sleep(1.5)

def handle_page(url, city, province, r):
    """
    处理每一个页面的url以及数据
    :param url:
    :param city:
    :param province:
    :param r:
    :return:
    """
    global device_id, tim, sign, header, is_break
    res = requests.get(url, headers=header)
    res_data = dict(eval(res.text.replace('false', 'False').replace('true', 'True').replace('null', 'None')))
    if '200' not in str(res_data):
        while '200' not in str(res_data):
            sleep(10)
            sign_tmp = sign
            tim_tmp = tim
            print('handle_page', res.text)
            print('权限不足或者accessToken失效，sign失败')
            device_id, tim, sign, header = more_get_token()
            url = url.replace(sign_tmp, sign).replace().replace(tim_tmp, tim)
            res = requests.get(url, headers=header, timeout=10)
            res_data = dict(eval(res.text.replace('false', 'False').replace('true', 'True').replace('null', 'None')))
    res.close()
    try:
        qiye_data = res_data.get('result').get('Result')
    except Exception as e:
        print(e)
        return
    if not qiye_data:
        is_break = True
        return
    write_list = []
    for qiye in qiye_data:
        if qiye.get('StartDate') != get_yesterday():
            is_break = True
            continue
        qiye['City'] = city
        qiye['Province'] = province
        del qiye['ImageUrl']
        del qiye['HitReason']
        write_list.append(qiye)
        r.set(province + ":" + city + ':' + qiye.get('KeyNo'), str(qiye))
    threading.Thread(target=write_data, args=(get_yesterday() + "-data.txt", write_list)).start()

def creat_url():
    """
    生产url
    :return:
    """
    global is_break
    for city_data in read_data('other/city_code.txt'):
        page_index = 0
        city_data = eval(city_data)
        while True:
            if is_break:
                is_break = False
                break
            page_index += 1
            url = 'https://appv3.qichacha.net/app/v1/base/getNewCompanys?province=' + str(
                city_data['provinceCode']) + '&cityCode=' + str(
                city_data['Value']) + '&pageIndex=' + str(
                page_index) + '&timestamp=' + str(tim) + '&sign=' + sign + '&platform=other&app_channel=qq'
            yield url, city_data['Desc'], city_data['provinceName']

def main():
    print(get_yesterday(), 'start')
    Process(target=new_enterprise_main).start()

if __name__ == '__main__':
    main()
    scheduler = BlockingScheduler()
    # 每天凌晨1点执行脚本
    scheduler.add_job(main, 'cron', hour='01', minute='01')
    scheduler.start()


#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
This file is designed to be a subprocess to copy files from one location to USB's file structure

"""

import sys, getopt
import argparse
import os, shutil
import logging
import shutil

def main():
        inputdir = ""
        outputdir = ""
        error = []
        parser = argparse.ArgumentParser()
        parser.add_argument( '--i', type=str, required=True, help = "Input Directory for Copy")
        parser.add_argument( '--o', type=str, required=True, help = "Output Directory for copy")
        arguments = (parser.parse_args())
        print("arguments", arguments)
        logging.info("Starting the copy function")
#        if not ("--i" in aruments and '--o" in  arguments):
#               print("startup of USBCopyUtil with unknown arguments")
#               sys.exit(2)
        if len(arguments.i) <= 4:
                print('USBCopyUtil.py -i <inputdir> missing')
                sys.exit()
        elif len(arguments.o) <=4:
                print("USBCopyUtil.py -o <outputdir> missing")                                                # we have a valid output directory
                outputdir = val[1]
        if  arguments.i == arguments.o:
                print("cannot copy from the same source to same destination")
                print("Closed USBCopyUtil.py due to lack of valid variabales")
                sys.exit(2)                                                                                # we didn't get valid paramaters
        if  not os.path.isdir(arguments.o):                                                                     #Check output that its a valid directory
                print("Closed USBCopyUtil.py due to output path not being a direcotry")
                sys.exit(2)
        print("Starting USBCopyUtil with "+arguments.i+" copying to "+arguments.o)
        try:
            if os.path.isdir(arguments.i):                                                                     # We check that we have a valid direcotry on input
                print("Copying tree: "+arguments.i+" to: "+arguments.o)
                shutil.rmtree( arguments.o, ignore_errors=True)							#Remove the directory where were copying to.
                logging.info("Copying: "+arguments.i+" to "+arguments.o)
                shutil.copytree(arguments.i, arguments.o, symlinks=False, copy_function=shutil.copy2, ignore_dangling_symlinks=True)
            else:
                print("Copying: "+arguments.i+" to: "+arguments.o)	                                           # We may just try a copy if the input directory is only a file.
                logging.info("USBcopyUtil copy: "+arguments.i+" to: "+arguments.o)
                shutil.copy2(arguments.i, arguments.o)
#        except (OSError):
#            errors.append((arguments.i, arguments.o, str(OSError), str(shutil.Error))                            # We encountered an error so we stop.
        except shutil.Error:
            errors.extend(arguments.i, arguments.o, str(Baseexeption), str(shutil.Error))
        try:
            shutil.copystat(arguments.i, arguments.o)                          	                                   # wE WANT TO MOVE THE STATISTICAL INFO TO THE FILES AS WELL
        except OSError:
            if err.winerror is None:
                errors.extend((arguments.i, arguments.o, str(err), str(shutil.Error)))                              # We had an error in the statistics.
            else:
                logging.info("USBcopyUtil copystat errors",errors)
                print("USBopyUtil copystat errors ", errors)
                sys.exit()                                                                                #No error so we just exit clean

if __name__ == "__main__":
    main()


from gevent.pywsgi import WSGIServer
from flask import Flask, request, abort, Response, jsonify, send_file,redirect,url_for
from flaskext.mysql import MySQL

import warnings
import json
import logging
from validators.url import url as check
import re

logger= logging.getLogger(__name__)
class ShortenerServer(object):
    """Class For URL Shortcut Maker"""
    app=Flask(__name__)
    agent=None
    users_inProcess={}
    premium=False
    mysql=MySQL()
    app.config["MYSQL_DATABASE_USER"]="iyunusp"
    app.config["MYSQL_DATABASE_PASSWORD"]="waspeper"
    app.config["MYSQL_DATABASE_DB"]="aea"
    app.config["MYSQL_DATABASE_HOST"]="0.0.0.0"
    mysql.init_app(app)
    """
    --store procedure for check and create rather the shotcut is already used or not
    DROP PROCEDURE IF EXISTS proc_shortener;
    DELIMITER //
    CREATE PROCEDURE proc_shortener(
        IN p_shortcut VARCHAR(15),
        IN p_url TEXT
    )
    BEGIN
            IF( SELECT EXISTS( SELECT 1 FROM shortener WHERE shortcut = p_shortcut)) THEN
                IF(p_url = '-') THEN
                    UPDATE shortener SET hit = hit +1 WHERE shortcut = p_shortcut ;
                    SELECT url FROM shortener WHERE shortcut = p_shortcut ;
                ELSE
                    SELECT 'Failed';
                END IF ;
            ELSE
                IF(p_url != '-') THEN
                    INSERT INTO shortener(shortcut, url) VALUES(p_shortcut, p_url) ;
                END IF ;
            END IF ;
    END
    //
    DELIMITER ;

    """
    def __init__(self):
        import os
        dir=os.path.dirname(os.path.realpath(__file__))
        @self.app.route("/", methods=['GET', 'OPTIONS'])
        def UI():
            """Web Interface for sCreating new URL Shortcut"""
            return send_file("indexs.html")

        @self.app.route("/<shortcut>", methods=['GET', 'OPTIONS'])
        def shortcut(shortcut):
            """Chatt"""
            try:
                conn=self.mysql.connect()
                data=()
                with conn.cursor() as cursor:
                    cursor.callproc("proc_shortener",(shortcut,'-'))
                    data=cursor.fetchall()
                url=data[0][0]
                conn.commit()
                return redirect(url,code=302)
            except:
                return redirect(url_for('UI'),code=302)

        @self.app.route("/make/<shortcut>", methods=['POST', 'OPTIONS'])
        def make(shortcut):
            """API for creating new URL Shortcut"""
            body = request_parameters()
            url=body.pop("url")
            status=self.valid(shortcut,url)
            if not status["success"]:
                return jsonify(status)
            try:
                conn=self.mysql.connect()
                cursor=conn.cursor()
                cursor.callproc("proc_shortener",(shortcut,url))
                data=cursor.fetchall()
                if len(data) == 0:
                    conn.commit()
                    status["status"]="shortcut created succesfully"
                else:
                    status["status"]="shortcut already in used"
                    status["success"]=False
            except:
                status["status"]="Connection Failed"
                status["success"]=False
            return jsonify(status)

        @self.app.route("/image/<path>", methods=['GET', 'OPTIONS'])
        def image(path):
            """Image API for getting Image that stored in image folder"""
            return send_file(dir+"/image/"+path,mimetype="image/*")

        def request_parameters():
            availableMethod=['POST','GET']
            if request.method in availableMethod:
                return request.args.to_dict()
            else:
                try:
                    return request.get_json(force=True)
                except ValueError as e:
                    pass
    def valid(self,shortcut,url):
        "form validator"
        reg=re.compile(r'^[a-zA-Z0-9]{1,14}$')
        status={"status":"","success":False}
        if len(shortcut) == 0 or len(url)==0:
            status["status"]="all field must be filled"
        elif len(shortcut) > 15:
            status["status"]="shortcut must be less than 15 character"
        elif len(url) > 2000:
            status["status"]="url must be less than 2000 character"
        elif re.match(reg,shortcut) is None:
            status["status"]="shortcut must be alphanumeric"
        elif shortcut == "make":
            status["status"]="shortcut already in used"
        elif check(url) is not True:
            status["status"]="url is invalid"
        else:
            status["success"]=True
        return status

    def startApp(self):
        """Start the Server using WSGI"""
        http_server = WSGIServer(('0.0.0.0', 5005), self.app)
        logger.info("Up and running")
        try:
            http_server.serve_forever()
        except Exception as exc:
            logger.exception(exc)

server= ShortenerServer()
server.startApp()


import numpy as np
import h5py
import matplotlib.pyplot as plt

def calc_activity(spikes, ensemble):

    activity = np.zeros(spikes.shape[1])

    for i_frame in range(spikes.shape[1]):
        for i_lag in range(ensemble.shape[1]):
            if i_frame+i_lag >= spikes.shape[1]:
                continue

            frame1 = spikes[:,i_frame+i_lag]
            frame2 = ensemble[:,i_lag]
            activity[i_frame] += np.dot(frame1, frame2)

    return activity

def activity(dataset,dataset_name,ensemblefile,output,figurename, swap_axes):

    """
    Activity plotter

    Parameters
    -----------

    dataset      : the original h5 file containing the spike matrix (Note: add -dn dataset_name if the sheet is not named "spikes")

    dataset_name : sheet of matrix (Default: "spikes")

    ensemblefile : name of the .h5 file containing the identified motifs

    output       : name of the output file containing the calculated activities

    figurename   : name of the file containing the plot, for each ensemble a saparate file is created

    swap_axes    : transposes the input matrix

    """

    fin1 = h5py.File(dataset,'r')
    X = fin1[dataset_name][...]
    X = X.astype(float)
    # X contains the spikes
    if swap_axes:
        X = X.T

    fin2 = h5py.File(ensemblefile,'r')
    ensembles = fin2['final_motifs'][...]

    fin1.close()
    fin2.close()

    fout = h5py.File(output,'w')

    for i in range(ensembles.shape[0]):

        activity = calc_activity(X, ensembles[i])
        fout.create_dataset('activity_ensemble_'+str(i),data=activity)
        # calc done for ensemble i

        params = {
        'axes.labelsize': 50,
        'font.size': 50,
        'legend.fontsize': 50,
        'xtick.labelsize': 30,
        'ytick.labelsize': 30,
        "text.usetex": False
        }
        plt.rcParams.update(params)

        if np.max(activity) > 0:
            f = plt.figure()
            a = f.add_axes((.03,.2,.7,.35))
            a.plot(activity)
            a.set_xlim(0,X.shape[1])
            numb = i+1
            a.set_title("motif %d" % numb)
            a.set_xlabel("frame")
            a.set_ylabel("activity")
            f.savefig(figurename+str(i)+'.png', bbox_inches='tight')

    fout.close()


import pygame
from random import randrange

class Line:
    def __init__(self, x1, y1, x2, y2):
        self.X1, self.Y1 = x1, y1
        self.X2, self.Y2 = x2, y2

def get_random_color():
    return pygame.Color(randrange(100,256), randrange(100,256),randrange(100,256))

def draw_line(screen, color, x1, y1, x2, y2):
    if x1 == x2 and y1 == y2:
        screen.set_at((x1, y1), color)
        return
    if abs(x2 - x1) > abs(y2 - y1):
        if x2 < x1:
            x1, x2, y1, y2 = x2, x1, y2, y1
        i = x1
        k = (y2 - y1) / (x2 - x1)
        while i <= x2:
            screen.set_at((i, int((i - x1) * k + y1)), color)
            i += 1
    else:
        if y2 < y1:
            x1, x2, y1, y2 = x2, x1, y2, y1
        i = y1
        k = (x2 - x1) / (y2 - y1)
        while i <= y2:
            screen.set_at((int((i - y1) * k + x1), i), color)
            i += 1

pygame.init()
screen = pygame.display.set_mode((800, 600))

SZ = 100, 80

objects, nobj = [], 0

drag, start_pos, cur_pos = False, (0, 0), (0, 0)

timeout = 1500
pygame.time.set_timer(pygame.USEREVENT, timeout)

while True:
    e = pygame.event.wait()
    if e.type is pygame.QUIT:
        print("QUIT")
        break
    if e.type is pygame.MOUSEBUTTONDOWN:
        if e.button == 3:
            color = get_random_color()
            objects.append((nobj, color, pygame.Rect(e.pos, SZ)))
            nobj += 1
        if e.button == 1:
            drag = True
            start_pos, cur_pos = e.pos, e.pos
            line_color = get_random_color()
    if e.type is pygame.MOUSEBUTTONUP:
        if e.button == 1 and drag:
            drag = False
            objects.append((nobj, line_color, Line(*start_pos, *e.pos)))
            nobj += 1
    if e.type is pygame.MOUSEMOTION:
        if drag:
            cur_pos = e.pos
            if e.pos[0] <= 0 or e.pos[1] <= 0 or e.pos[0] >= screen.get_size()[0] or e.pos[1] >= screen.get_size()[1]:
                grag = False
    if e.type is pygame.ACTIVEEVENT:
        if e.gain == 0 and drag == True:
            drag = False
    else:
        for (i, color, obj) in reversed(objects):
            if type(obj) == pygame.Rect and hasattr(e, "pos") and obj.collidepoint(e.pos):
                print(f"{e} to {i}")
                break
        else:
            print(e)

    screen.fill(0)
    for i, color, obj in objects:
        if type(obj) == pygame.Rect:
            screen.fill(color, obj)
        if type(obj) == Line:
            draw_line(screen, color, obj.X1, obj.Y1, obj.X2, obj.Y2)

    if drag:
        draw_line(screen, line_color, *start_pos, *cur_pos)

    pygame.display.flip()


import os
import configure as c
import csv

def get_warning_info(path):
    warnings = []
    with open(path, 'r') as f:
        reader = csv.reader(f)
        index = 0
        for line in reader:
            if index == 0:
                index += 1
                continue
            path = line[c.index_map['path']]
            start = line[c.index_map['start']]
            end = line[c.index_map['end']]
            method = line[c.index_map['method']]
            field = line[c.index_map['field']]
            warnings.append({'index': index, 'path': path, 'start': start, 'end': end, 'method': method, 'field': field})
            index += 1
    f.close()

    return warnings

def location_warning(warnings: list, feature_list: list):
    location_list = []
    for warning in warnings:
        start = int(warning['start'])
        end = int(warning['end'])
        path = warning['path']
        method = warning['method']
        location_count = 0
        for i in warnings:
            if i['path'] == path and i['method'] == method:
                start_i = int(i['start'])
                end_i = int(i['end'])
                if start_i >= (start - c.offset) and end_i <= (end + c.offset):
                    location_count += 1
        location_list.append(location_count)

    for i in range(len(warnings)):
        feature_list[i]['location_count'] = location_list[i] - 1

def method_warning(warnings: list, feature_list: list):
    method_list = []
    for warning in warnings:
        method = warning['method']
        path = warning['path']
        method_count = 0
        for i in warnings:
            if i['path'] == path and i['method'] == method:
                method_count += 1
        method_list.append(method_count)

    for i in range(len(warnings)):
        feature_list[i]['method_count'] = method_list[i] - 1

def file_warning(warnings: list, feature_list: list):
    file_list = []
    for warning in warnings:
        path = warning['path']
        file_count = 0
        for i in warnings:
            if i['path'] == path:
                file_count += 1
        file_list.append(file_count)

    for i in range(len(warnings)):
        feature_list[i]['file_count'] = file_list[i] - 1

if __name__ == '__main__':
    pro_dirs = os.listdir(c.data_dir)
    for pro in pro_dirs:
        pro_path = os.path.join(c.data_dir, pro)
        if os.path.isdir(pro_path):
            path = os.path.join(pro_path, c.warning_file_name)
            warnings = get_warning_info(path)
            feature_list = []
            for i in range(len(warnings)):
                feature_list.append({})
            location_warning(warnings, feature_list)
            method_warning(warnings, feature_list)
            file_warning(warnings, feature_list)
            print(feature_list)
            with open(pro + '_new_feature.csv', 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['location_count', 'method_count', 'file_count'])
                for i in feature_list:
                    writer.writerow([i['location_count'], i['method_count'], i['file_count']])
            f.close()


# 7kyu
def main():
    def counting_valleys(s):
        level = total_enter = total_exit = 0
        in_valley = False

        for c in s:
            level += 1 if c == 'U' else -1 if c == 'D' else 0
            if level < 0 and not in_valley:
                total_enter += 1
                in_valley = True

            elif level >= 0 and in_valley:
                total_exit += 1
                in_valley = False

        return (total_enter + total_exit) // 2

    print(counting_valleys('DFFFU'))

if __name__ == '__main__':
    main()


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

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from pymongo import MongoClient
import re

collectionName = input("Enter collection name: ")

#connect mongodb
client = MongoClient()
db = client.myProject
#set collection
collection = db[collectionName]

text = ""
for tweet in collection.find():
    text += tweet["text"]
text = re.sub("(https\S*|RT)","",text)
#print(text)

wordcloud = WordCloud(font_path="angsana.ttc",
                      relative_scaling = 1.0,
                      min_font_size=1,
                      background_color="white",
                      width=800,
                      height=800,
                      scale=1,
                      #mask=mask,
                      font_step=1,
                      regexp=r"[\u0E00-\u0E7Fa-zA-Z']+",
                      collocations=False,
                      margin=4,
                      max_words=1000
                      ).generate(text)

plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()


import os
from typing import Iterable, Tuple, Union

from megengine.core._imperative_rt.core2 import apply
from megengine.core.ops.builtin import LAMBUpdate

from .. import Parameter, tensor
from ..functional import sum
from ..functional.inplace import _inplace_add_
from .optimizer import Optimizer

class LAMB(Optimizer):
    r"""Implements LAMB algorithm.

    LAMB is proposed in `"Large Batch Optimization for Deep Learning: Training BERT in 76 minutes"
    <https://arxiv.org/abs/1904.00962>`_.

    Args:
        params: iterable of parameters to optimize or dicts defining parameter groups.
        lr: learning rate.
        betas: coefficients used for computing running averages of gradient and its square.
            Default: ``(0.9, 0.999)``
        eps: term added to the denominator to improve numerical stability. Default: ``1e-8``
        bias_correction: enables bias correction by ``1 - beta ** step``. Default: ``True``
        weight_decay: weight decay (L2 penalty). Default: ``0.0``
        always_adapt: apply adaptive lr to ``0.0`` weight decay parameter. Default: ``False``
    """

    def __init__(
        self,
        params: Union[Iterable[Parameter], dict],
        lr: float,
        betas: Tuple[float, float] = (0.9, 0.999),
        eps: float = 1e-8,
        bias_correction: bool = True,
        weight_decay: float = 0.0,
        always_adapt: bool = False,
    ):
        if lr < 0.0:
            raise ValueError("Invalid learning rate: {}".format(lr))
        if weight_decay < 0.0:
            raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
        if not 0.0 <= betas[0] < 1.0:
            raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
        if not 0.0 <= betas[1] < 1.0:
            raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))

        defaults = dict(lr=lr, weight_decay=weight_decay, betas=betas, eps=eps)
        super().__init__(params, defaults)
        self.bias_correction = bias_correction
        self.always_adapt = always_adapt
        self._disable_type_convert = True

    def _create_state(self, param_group):
        for param in param_group["params"]:
            self._add_state(param, "exp_avg")
            self._add_state(param, "exp_avg_sq")
            self._add_state(param, "step", initializer=0.0, dtype="float32")

    def _updates(self, param_group):
        lr = param_group["lr"]
        weight_decay = param_group["weight_decay"]
        eps = param_group["eps"]
        beta0, beta1 = param_group["betas"]

        # since `conver_inputs` is disabled for param updates,
        # scalar should be explicitly tansforred to tensor
        c1 = tensor(1.0)

        for param in param_group["params"]:

            if param.grad is None:
                continue

            grad = param.grad

            states = self._state[param]

            step, exp_avg, exp_avg_sq = (
                states["step"],
                states["exp_avg"],
                states["exp_avg_sq"],
            )
            step += c1

            op = LAMBUpdate(
                beta0,
                beta1,
                int(step),
                lr,
                weight_decay,
                eps,
                self.bias_correction,
                self.always_adapt,
            )

            new_exp_avg, new_exp_avg_sq, new_param = apply(
                op, exp_avg, exp_avg_sq, param, grad
            )
            param._reset(new_param)
            exp_avg._reset(new_exp_avg)
            exp_avg_sq._reset(new_exp_avg_sq)

class LAMBFp16(LAMB):
    def _create_state(self, param_group):
        for param in param_group["params"]:
            self._add_state(param, "exp_avg", dtype="float32")
            self._add_state(param, "exp_avg_sq", dtype="float32")
            self._add_state(param, "step", initializer=0.0, dtype="float32")
            self._state[param]["param_fp32"] = param.astype("float32")

    def _updates(self, param_group):
        lr = param_group["lr"]
        weight_decay = param_group["weight_decay"]
        eps = param_group["eps"]
        beta0, beta1 = param_group["betas"]
        c1 = tensor(1.0)
        for param in param_group["params"]:

            if param.grad is None:
                continue

            grad = param.grad

            states = self._state[param]

            step, exp_avg, exp_avg_sq = (
                states["step"],
                states["exp_avg"],
                states["exp_avg_sq"],
            )
            step += c1
            fp32_param = states["param_fp32"]
            op = LAMBUpdate(
                beta0,
                beta1,
                step,
                lr,
                weight_decay,
                eps,
                self.bias_correction,
                self.always_adapt,
            )

            new_exp_avg, new_exp_avg_sq, new_param = apply(
                op, exp_avg, exp_avg_sq, fp32_param, grad
            )
            fp32_param._reset(new_param)
            param._reset(new_param.astype("float16"))
            exp_avg._reset(new_exp_avg)
            exp_avg_sq._reset(new_exp_avg_sq)


"""
surface tension coefficient model featuring surface-partitioning
 as in [Ruehl et al. (2016)](https://doi.org/10.1126/science.aad4889)
"""
import numba
import numpy as np

from PySDM.backends.impl_numba.conf import JIT_FLAGS as jit_flags
from PySDM.backends.impl_numba.toms748 import toms748_solve
from PySDM.physics.trivia import Trivia

# pylint: disable=too-many-arguments
@numba.njit(**{**jit_flags, "parallel": False})
def minfun(f_surf, Cb_iso, RUEHL_C0, RUEHL_A0, A_iso, c):
    lhs = Cb_iso * (1 - f_surf) / RUEHL_C0
    rhs = np.exp(c * (RUEHL_A0**2 - (A_iso / f_surf) ** 2))
    return lhs - rhs

within_tolerance = numba.njit(
    Trivia.within_tolerance, **{**jit_flags, "parallel": False}
)

class CompressedFilmRuehl:  # pylint: disable=too-few-public-methods
    """
    Compressed film model of surface-partitioning of organics from Ruehl et al. (2016).
    Described in supplementary materials equations (13) and (15).

    Allows for more realistic thermodynamic partitioning of some organic to the surface,
    while some remains dissolved in the bulk phase. The surface concentration is solved
    implicitly from the isotherm equation that relates the bulk organic concentration
    `C_bulk` to the surface average molecular area `A`. The equation of state relates
    the surface concentration to the surface tension. For the compressed film model it
    is linear, with slope `m_sigma`.
    """

    def __init__(self, const):
        assert np.isfinite(const.RUEHL_nu_org)
        assert np.isfinite(const.RUEHL_A0)
        assert np.isfinite(const.RUEHL_C0)
        assert np.isfinite(const.RUEHL_m_sigma)
        assert np.isfinite(const.RUEHL_sgm_min)

    @staticmethod
    def sigma(const, T, v_wet, v_dry, f_org):  # pylint: disable=too-many-locals
        # wet radius (m)
        r_wet = ((3 * v_wet) / (4 * const.PI)) ** (1 / 3)

        if f_org == 0:
            sgm = const.sgm_w
        elif f_org == 1:
            sgm = const.RUEHL_sgm_min
        else:
            # C_bulk is the concentration of the organic in the bulk phase
            # Cb_iso = C_bulk / (1-f_surf)
            Cb_iso = (f_org * v_dry / const.RUEHL_nu_org) / (v_wet / const.nu_w)

            # A is the area one molecule of organic occupies at the droplet surface
            # A_iso = A*f_surf (m^2)
            A_iso = (4 * const.PI * r_wet**2) / (
                f_org * v_dry * const.N_A / const.RUEHL_nu_org
            )

            # solve implicitly for fraction of organic at surface
            c = (const.RUEHL_m_sigma * const.N_A) / (2 * const.R_str * T)

            args = (Cb_iso, const.RUEHL_C0, const.RUEHL_A0, A_iso, c)
            rtol = 1e-6
            max_iters = 1e2
            bracket = (1e-16, 1)
            f_surf, iters = toms748_solve(
                minfun,
                args,
                *bracket,
                minfun(bracket[0], *args),
                minfun(bracket[1], *args),
                rtol,
                max_iters,
                within_tolerance
            )
            assert iters != max_iters

            # calculate surface tension
            sgm = const.sgm_w - (const.RUEHL_A0 - A_iso / f_surf) * const.RUEHL_m_sigma

        # surface tension bounded between sgm_min and sgm_w
        sgm = np.minimum(np.maximum(sgm, const.RUEHL_sgm_min), const.sgm_w)
        return sgm

CompressedFilmRuehl.sigma.__extras = {
    "toms748_solve": toms748_solve,
    "minfun": minfun,
    "within_tolerance": within_tolerance,
}
CompressedFilmRuehl.sigma.__vectorize = True


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split

def count_null_data(data):
    missing_counts = (data == 0).sum()
    sorted_columns = missing_counts.sort_values(ascending=False)
    no_missing_data = True
    for column, count in sorted_columns.items():
        if pd.api.types.is_numeric_dtype(data[column]):
            nan_count = data[column].isna().sum()
            count += nan_count
        if count != 0:
            print(f"Column '{column}': {count} values 0")
            no_missing_data = False
    if no_missing_data:
        print("There are no 0 value anymore!")

def delete_columns_with_zero_data(data, threshold):
    for column in data.columns:
        zero_count = (data[column] == 0).sum()
        if zero_count > threshold:
            data = data.drop(column, axis=1)
    return data

def separate_categorical_numerical(data):
    categorical_cols = []
    numerical_cols = []
    for column in data.columns:
        if data[column].dtype == 'object' or pd.api.types.\
                            is_categorical_dtype(data[column].dtype):
            categorical_cols.append(column)
        else:
            numerical_cols.append(column)
    return categorical_cols, numerical_cols

def drop_columns_with_zero_threshold(data, threshold):
    zero_counts = (data == 0).sum()
    columns_to_drop = zero_counts[zero_counts > threshold].index
    data = data.drop(columns=columns_to_drop)
    print(zero_counts)
    return data

def plot_categorical_columns(data):
    num_cols = len(data.columns)
    num_rows = (num_cols - 1) // 6 + 1
    fig, axes = plt.subplots(nrows=num_rows, ncols=6,
                             figsize=(20, num_rows * 4))
    for i, column in enumerate(data.columns):
        row = i // 6
        col = i % 6
        value_counts = data[column].value_counts()
        sns.barplot(x=value_counts.index, y=value_counts.values,
                    ax=axes[row, col])
        axes[row, col].set_title(f'Value Counts - {column}')
        axes[row, col].set_xlabel('Categories')
        axes[row, col].set_ylabel('Count')
        axes[row, col].tick_params(axis='x', rotation=45)
    plt.tight_layout()
    plt.show()

def apply_1_plus_log_transformation(data, columns_to_transform):
    transformed_data = data.copy()
    for column in columns_to_transform:
        transformed_data[column] = np.log1p(transformed_data[column])
    return transformed_data

def model_evaluation(name, model, data, output_file):
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import mean_squared_error, r2_score

    X = data.iloc[:, :-1].values
    y = data.iloc[:, -1].values
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
                                                        random_state=42)
    model = model()
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    mse = mean_squared_error(y_test, y_pred)
    r2 = r2_score(y_test, y_pred)
    metrics_dict = {
        'Model': name,
        'MSE': mse,
        'R2-Score': r2
    }
    result = np.concatenate((y_pred.reshape(len(y_pred), 1),
                             y_test.reshape(len(y_test), 1)), 1)
    with open(output_file, "w") as file:
        np.savetxt(file, result, fmt="%.2f", delimiter=",")
    return metrics_dict

def plot_boxplot(df, x_column, y_column):
    data = df[[x_column, y_column]]
    fig, ax = plt.subplots(figsize=(14, 9))
    sns.boxplot(x=x_column, y=y_column, data=data, ax=ax)
    ax.set_ylim(0, 800000)
    plt.xticks(rotation=90)
    plt.title(f'Boxplot of {y_column} by {x_column}')
    plt.xlabel(x_column)
    plt.ylabel(y_column)
    name = f"Boxplot of {y_column} by {x_column}.png"
    plt.savefig(f"results/plot_preprocessing/{name}.png")
    plt.show()

def plot_heatmaps(df):
    corrmat = df.corr()
    f, ax = plt.subplots(1, 2, figsize=(20, 10))
    sns.heatmap(corrmat, vmax=0.8, square=True, cmap="RdBu", ax=ax[0])
    ax[0].set_title('Correlation Matrix Heatmap')
    k = 10
    cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index
    cm = np.corrcoef(df[cols].values.T)
    sns.set(font_scale=1.25)
    sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f',
                annot_kws={'size': 10}, yticklabels=cols.values,
                xticklabels=cols.values, cmap="RdBu", ax=ax[1])
    ax[1].set_title('Top 10 most correlated variables with sale price')
    plt.savefig("results/plot_preprocessing/Correlation Matrix Heatmap.png")
    plt.show()


class Solution:
    """
    @param n: An integer
    @return: An integer
    """

    def climbStairs(self, n):
        # write your code here
        result = [1, 1]

        if n == 0:
            return 0

        for i in range(2, n + 1):
            result.append(result[i - 1] + result[i - 2])

        return result[n]


# импорт библиотек
import json
import logging
from random import choice
from table_of_results import add_information

# импорт для яндекс карт
from geocoder import get_ll_span

# телеграм бот
from telegram.ext import CommandHandler, MessageHandler, filters

# логгирование
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG
)

logger = logging.getLogger(__name__)

# приветсвие и старт игры
async def cities(update, context):
    await update.message.reply_text("Поиграем в города! Я начну")
    context.user_data['list_of_cities'] = ["Москва"]
    # показать Москву
    ll, spn = await get_ll_span("Москва")
    if ll and spn:
        point = "{ll},pm2vvl".format(ll=ll)
        static_api_request = f"http://static-maps.yandex.ru/1.x/?ll={ll}&spn={spn}&l=map&pt={point}"
        await context.bot.sendPhoto(update.message.chat.id, static_api_request,
                                    caption="Москва")
    await update.message.reply_text("Напишите 'заново', чтобы начать игру сначала.")
    await update.message.reply_text("Напишите 'помощь', чтобы я сделал ещё один ход.")

# ход игры
async def geocoder(update, context):
    try:
        # выгружаем словарь городов
        with open('list_of_cities.json') as file:
            dictionary_of_cities = json.load(file)
        # сообщение пользователя
        mes = update.message
        new_city = mes.text.capitalize()
        # проверка на начало заново
        if "заново" in new_city.lower():
            context.user_data['list_of_cities'] = ["Москва"]
        # помощь бота
        elif "помощь" in new_city.lower():

            # поиск последней подходящей буквы
            last_possible_letter = -1
            while context.user_data['list_of_cities'][-1][last_possible_letter:][0] in 'ъьыё':
                last_possible_letter -= 1
            last_possible_letter = context.user_data['list_of_cities'][-1][last_possible_letter:][0].upper()

            # список возможных новых городов
            set_of_possible_cities = set(dictionary_of_cities[last_possible_letter]) - set(
                context.user_data['list_of_cities'])

            # окончание игры
            if len(set_of_possible_cities) == 0:
                await update.message.reply_text("Не могу придумать город, начните игру заново.")

            else:
                # выбор города
                new_city = choice(list(set_of_possible_cities))
                help_list = context.user_data.get('list_of_cities', [])
                # добавление города в список, чтобы избежать повторений
                help_list.append(new_city)
                context.user_data['list_of_cities'] = help_list

                # показ карты города
                ll, spn = await get_ll_span(new_city)
                if ll and spn:
                    point = "{ll},pm2vvl".format(ll=ll)
                    static_api_request = f"http://static-maps.yandex.ru/1.x/?ll={ll}&spn={spn}&l=map&pt={point}"
                    await context.bot.sendPhoto(update.message.chat.id, static_api_request,
                                                caption=new_city)
                else:
                    # без карты
                    await update.message.reply_text(f"Увы, но в этот раз без карты. Город:{new_city}")
        elif new_city not in dictionary_of_cities[new_city[0].upper()]:
            # ложный город (введён бред)
            await update.message.reply_text("Такого города не существует.")
        else:

            # проверка последней буквы
            last_city = context.user_data['list_of_cities'][-1]
            letter_for_user = -1
            while last_city[letter_for_user:][0] in 'ъьыё':
                letter_for_user -= 1
            letter_for_user = last_city[letter_for_user:][0].upper()
            if letter_for_user != new_city[0]:
                await update.message.reply_text("Не та первая буква.")
                await update.message.reply_text(f"Вам нужна: {letter_for_user.capitalize()}.")

            else:
                help_list = context.user_data.get('list_of_cities', [])
                # проверка повтора города
                if new_city in help_list:
                    await update.message.reply_text("Такой город уже был.")
                else:
                    # добавление города
                    help_list.append(new_city)
                    context.user_data['list_of_cities'] = help_list
                    add_information(mes.from_user.username, add_city=True)

                    # карта города
                    ll, spn = await get_ll_span(new_city)
                    if ll and spn:
                        point = "{ll},pm2vvl".format(ll=ll)
                        static_api_request = f"http://static-maps.yandex.ru/1.x/?ll={ll}&spn={spn}&l=map&pt={point}"
                        await context.bot.sendPhoto(update.message.chat.id, static_api_request,
                                                    caption=update.message.text.capitalize())
                    else:
                        await update.message.reply_text(
                            f"Увы, но в этот раз без карты. Город:{update.message.text.capitalize()}")

                    # ответ бота
                    # последняя возможная буква
                    last_possible_letter = -1
                    while new_city[last_possible_letter:][0] in 'ъьыё':
                        last_possible_letter -= 1
                    last_possible_letter = new_city[last_possible_letter:][0].upper()
                    set_of_possible_cities = set(dictionary_of_cities[last_possible_letter]) - set(
                        context.user_data['list_of_cities'])

                    # начать заново
                    if len(set_of_possible_cities) == 0:
                        await update.message.reply_text("Не могу придумать город, начните игру заново.")
                    else:

                        # добавление города
                        new_city = choice(list(set_of_possible_cities))
                        help_list = context.user_data.get('list_of_cities', [])
                        help_list.append(new_city)
                        context.user_data['list_of_cities'] = help_list

                        #показ карты
                        ll, spn = await get_ll_span(new_city)
                        if ll and spn:
                            point = "{ll},pm2vvl".format(ll=ll)
                            static_api_request = f"http://static-maps.yandex.ru/1.x/?ll={ll}&spn={spn}&l=map&pt={point}"
                            await context.bot.sendPhoto(update.message.chat.id, static_api_request,
                                                        caption=new_city)
                        else:
                            await update.message.reply_text(
                                f"Увы, но в этот раз без карты. Город:{new_city}")
    except RuntimeError as ex:
        await update.message.reply_text(str(ex))

# подключение городов
def main_cities(application):
    application.add_handler(CommandHandler("cities", cities))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, geocoder))


"""Helper script to extract the slack user_id from an email and a name.

Usage:
    python3 get_slack_user.py --name="William Chu" --email=test@uptickhq.com

Uses the jaccard similarity of pairwise characters of email/name/real_name to determine
the most similar user.

This script is written for python 3.8 compatibility (usage in github actions.)
"""
import argparse
import dataclasses
import json
import os
import subprocess
import urllib.request
from typing import Iterable, List, Tuple

@dataclasses.dataclass
class SlackUser:
    name: str
    email: str
    real_name: str
    id: str

def jaccard_similarity(x: Iterable, y: Iterable) -> float:
    """returns the jaccard similarity between two lists or strings"""
    intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
    union_cardinality = len(set.union(*[set(x), set(y)]))
    return intersection_cardinality / float(union_cardinality)

def pairwise_tuples(x: str) -> List[Tuple[str, str]]:
    """Given William returns [(W,i), (i,l), (l,l), (l,i), (i,a), (a, m)]"""
    if not x or len(x) < 2:
        return [("", "")]
    else:
        return [(letter, x[i + 1]) for i, letter in enumerate(x[:-1])]

def search(name: str, email: str, users: List[SlackUser]) -> SlackUser:
    def scoring_fn(user: SlackUser) -> float:
        return (
            jaccard_similarity(pairwise_tuples(user.email), pairwise_tuples(email))
            + jaccard_similarity(pairwise_tuples(name), pairwise_tuples(user.name))
            + jaccard_similarity(pairwise_tuples(name), pairwise_tuples(user.real_name))
        )

    match = max(users, key=scoring_fn)
    return match

def main(name: str, email: str, token: str) -> SlackUser:

    with urllib.request.urlopen(
        urllib.request.Request(
            "https://slack.com/api/users.list?limit=300&pretty=1",
            headers={"Authorization": f"Bearer {token}"},
        )
    ) as response:
        data = json.loads(response.read())

    if not data["ok"]:
        raise Exception(data["error"])
    users = [
        SlackUser(
            m["name"].lower(),
            m["profile"].get("email", "").lower(),
            m.get("real_name", "").lower(),
            m["id"],
        )
        for m in data["members"]
        if not m["is_bot"]
    ]

    matched_user = search(name, email, users)
    print(matched_user.id)
    return matched_user

default_user = subprocess.check_output(
    "git log -n 1 --pretty=format:%an".split()
).decode("utf-8")
default_email = subprocess.check_output(
    "git log -n 1 --pretty=format:%ae".split()
).decode("utf-8")
parser = argparse.ArgumentParser(
    description=(
        "Extracts the slack user id the latest commit via text similarity against slack"
        " profiles"
    )
)
parser.add_argument(
    "--name",
    type=str,
    default=default_user,
    help="Full name of the user. Defaults to latest commit name.",
)
parser.add_argument(
    "--email",
    type=str,
    default=default_email,
    help="Email address of the user. Defaults to latest commit email.",
)
parser.add_argument(
    "--slack-token",
    type=str,
    default=os.environ.get("SLACK_TOKEN", ""),
    help="OAuth slack token. Defaults to environ SLACK_TOKEN",
)

if __name__ == "__main__":
    args = parser.parse_args()
    print("token=", os.environ.get("SLACK_TOKEN"))
    main(args.name, args.email, args.slack_token)


n = int(input())

ugly = [0] * n  # 못생긴 수 리스트
ugly[0] = 1  # 1은 못생긴 수로 가정

# 2, 3, 5배 인덱스
i2 = i3 = i5 = 0
# 2, 3, 5 곱셈값
next2, next3, next5 = 2, 3, 5

# n번째까지의 못생긴 수 찾기
for i in range(1, n):
    ugly[i] = min(next2, next3, next5)
    # 인덱스에 따라서 곱셈값 증가
    if ugly[i] == next2:
        i2 += 1
        next2 = ugly[i2] * 2
    if ugly[i] == next3:
        i3 += 1
        next3 = ugly[i3] * 3
    if ugly[i] == next5:
        i5 += 1
        next5 = ugly[i5] * 5

print(ugly[n - 1])


import pygame
import random

# Initialize Pygame
pygame.init()

# Constants
width, height = 400, 400
gridSize = 4
gridCellSize = width // gridSize
gridColor = (187, 173, 160)
fontSize = 36
backgroundColor = (205, 193, 180)

# Fonts
font = pygame.font.Font(None, fontSize)

# Initialize the grid
grid = [[0 for _ in range(gridSize)] for _ in range(gridSize)]

# Number colors and box colors
numberColors = {
    0: (205, 193, 180),  # Empty cell
    2: (238, 228, 218),
    4: (237, 224, 200),
    8: (242, 177, 121),
    16: (245, 149, 99),
    32: (246, 124, 95),
    64: (246, 94, 59),
    128: (237, 207, 114),
    256: (237, 204, 97),
    512: (237, 200, 80),
    1024: (237, 197, 63),
    2048: (237, 194, 46)
}

boxColor = (172, 156, 141)

# Function to draw the grid
def draw_grid(screen):
    screen.fill(backgroundColor)
    for row in range(gridSize):
        for col in range(gridSize):
            pygame.draw.rect(screen, gridColor, (col * gridCellSize, row * gridCellSize, gridCellSize, gridCellSize), 0)
            number = grid[row][col]
            if number > 0:
                pygame.draw.rect(screen, numberColors[number], (col * gridCellSize, row * gridCellSize, gridCellSize, gridCellSize), 0)
                text = font.render(str(number), True, (0, 0, 0))
                text_rect = text.get_rect(center=(col * gridCellSize + gridCellSize // 2, row * gridCellSize + gridCellSize // 2))
                pygame.draw.rect(screen, boxColor, (col * gridCellSize, row * gridCellSize, gridCellSize, gridCellSize), 3)
                screen.blit(text, text_rect)

# Function to add a random tile (2 or 4) to the grid
def add_random_tile():
    emptyCells = [(row, col) for row in range(gridSize) for col in range(gridSize) if grid[row][col] == 0]
    if emptyCells:
        row, col = random.choice(emptyCells)
        grid[row][col] = random.choice([2, 4])

# Function to check for a win (2048 in any cell)
def check_win():
    for row in range(gridSize):
        for col in range(gridSize):
            if grid[row][col] == 2048:
                return True
    return False

# Function to check for a loss (no empty cells) (hard mode)
def check_loss_hard():
    for row in range(gridSize):
        for col in range(gridSize):
            if grid[row][col] == 0:
                return False  # There is an empty cell, game can continue
    return True  # No empty cells, you lost

# Function to check for a loss (no empty cells and no available moves) (easy mode)
def check_loss_easy():
    for row in range(gridSize):
        for col in range(gridSize):
            if grid[row][col] == 0:
                return False  # There is an empty cell, game can continue

            if col < gridSize - 1 and (grid[row][col] == grid[row][col + 1] or grid[row][col] == 0):
                return False  # Tiles can merge horizontally or there is an empty cell

            if row < gridSize - 1 and (grid[row][col] == grid[row + 1][col] or grid[row][col] == 0):
                return False  # Tiles can merge vertically or there is an empty cell

    return True  # No empty cells and no available moves

# Function to display the menu and select game mode
def show_menu():
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("2048 Game - Select Mode")

    menu_running = True
    selected_mode = None

    while menu_running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if 100 <= event.pos[0] <= 300 and 200 <= event.pos[1] <= 250:
                    selected_mode = "easy"
                    menu_running = False
                elif 100 <= event.pos[0] <= 300 and 300 <= event.pos[1] <= 350:
                    selected_mode = "hard"
                    menu_running = False

        # Draw the menu
        screen.fill(backgroundColor)
        title_font = pygame.font.Font(None, 48)
        title_text = title_font.render("2048 Game", True, (0, 0, 0))
        title_rect = title_text.get_rect(center=(width // 2, height // 4))

        easy_button = pygame.Rect(100, 200, 200, 50)
        easy_font = pygame.font.Font(None, 36)
        easy_text = easy_font.render("Easy Mode", True, (0, 0, 0))
        easy_text_rect = easy_text.get_rect(center=easy_button.center)

        hard_button = pygame.Rect(100, 300, 200, 50)
        hard_font = pygame.font.Font(None, 36)
        hard_text = hard_font.render("Hard Mode", True, (0, 0, 0))
        hard_text_rect = hard_text.get_rect(center=hard_button.center)

        pygame.draw.rect(screen, (0, 0, 0), easy_button, 2)
        pygame.draw.rect(screen, (0, 0, 0), hard_button, 2)

        screen.blit(title_text, title_rect)
        screen.blit(easy_text, easy_text_rect)
        screen.blit(hard_text, hard_text_rect)

        pygame.display.flip()

    return selected_mode

# Display the menu and select game mode
game_mode = show_menu()

# Create a window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("2048 Game")

# Initialize the game
add_random_tile()
add_random_tile()

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                # Implement left movement logic
                for row in range(gridSize):
                    # Merge tiles
                    for col in range(1, gridSize):
                        if grid[row][col] != 0:
                            for move_col in range(col, 0, -1):
                                if grid[row][move_col - 1] == 0:
                                    grid[row][move_col - 1] = grid[row][move_col]
                                    grid[row][move_col] = 0
                                elif grid[row][move_col - 1] == grid[row][move_col]:
                                    grid[row][move_col - 1] *= 2
                                    grid[row][move_col] = 0
                                    # Update score here if needed
                                    break

            elif event.key == pygame.K_RIGHT:
                # Implement right movement logic
                for row in range(gridSize):
                    # Merge tiles
                    for col in range(gridSize - 2, -1, -1):
                        if grid[row][col] != 0:
                            for move_col in range(col, gridSize - 1):
                                if grid[row][move_col + 1] == 0:
                                    grid[row][move_col + 1] = grid[row][move_col]
                                    grid[row][move_col] = 0
                                elif grid[row][move_col + 1] == grid[row][move_col]:
                                    grid[row][move_col + 1] *= 2
                                    grid[row][move_col] = 0
                                    # Update score here if needed
                                    break

            elif event.key == pygame.K_UP:
                # Implement up movement logic
                for col in range(gridSize):
                    # Merge tiles (if able to)
                    for row in range(1, gridSize):
                        if grid[row][col] != 0:
                            for move_row in range(row, 0, -1):
                                if grid[move_row - 1][col] == 0:
                                    grid[move_row - 1][col] = grid[move_row][col]
                                    grid[move_row][col] = 0
                                elif grid[move_row - 1][col] == grid[move_row][col]:
                                    grid[move_row - 1][col] *= 2
                                    grid[move_row][col] = 0
                                    # Update score here if needed
                                    break

            elif event.key == pygame.K_DOWN:
                # Implement down movement logic
                for col in range(gridSize):
                    # Merge tiles (if able to)
                    for row in range(gridSize - 2, -1, -1):
                        if grid[row][col] != 0:
                            for move_row in range(row, gridSize - 1):
                                if grid[move_row + 1][col] == 0:
                                    grid[move_row + 1][col] = grid[move_row][col]
                                    grid[move_row][col] = 0
                                elif grid[move_row + 1][col] == grid[move_row][col]:
                                    grid[move_row + 1][col] *= 2
                                    grid[move_row][col] = 0
                                    # Update score here if needed
                                    break

            # After each move, add a random tile and update the display
            add_random_tile()
            draw_grid(screen)
            pygame.display.flip()

            # Check for win or loss based on the selected game mode
            if game_mode == "easy" and check_loss_easy():
                print("You lose!")
                running = False
            elif game_mode == "hard" and check_loss_hard():
                print("You lose!")
                running = False
            elif check_win():
                print("You win!")
                running = False

# Quit Pygame
pygame.quit()


"""
https://leetcode.com/problems/distinct-subsequences/description/

https://www.youtube.com/watch?v=nVG7eTiD2bY
"""
class Solution:

    def dfs(self, s, t, i, j, dp):
        if (i, j) in dp:
            return dp[(i, j)]
        if j < 0:
            return 1
        if i < 0:
            return 0
        if s[i] == t[j]:
            dp[(i, j)] = self.dfs(s, t, i-1, j-1, dp) + self.dfs(s, t, i-1, j, dp)
        else:
            dp[(i, j)] = self.dfs(s, t, i-1, j, dp)
        return dp[(i, j)]

    def tabular(self, s, t):
        n = len(s)
        m = len(t)
        dp = [[0]*(m+1) for _ in range(n+1)]

        for i in range(n+1):
            dp[i][0] = 1

        for i in range(1, n+1):
            for j in range(1, m+1):
                if s[i-1] == t[j-1]:
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
                else:
                    dp[i][j] = dp[i-1][j]
        return dp[n][m]

    def numDistinct(self, s: str, t: str) -> int:
        # dp = {}
        # return self.dfs(s, t, len(s)-1, len(t)-1, dp)
        return self.tabular(s, t)

solve = Solution()
print(solve.numDistinct(s='rabbbit', t='rabbit'))
print(solve.numDistinct(s='babgbag', t='bag'))


import cv2
import numpy as np
from pynput.mouse import Button, Controller
import tkinter as tk
# Kamera ve maskeleme
cam = cv2.VideoCapture(0) #webcam'i yakalama
# Font
font = cv2.FONT_HERSHEY_SIMPLEX
# Renk araligi secimi
lowerb = np.array([110,80,155])
upperb = np.array([200,120,255])
# Fareyi tanimla
mouse = Controller()
# Arayüz yakalama
root = tk.Tk()
sx = root.winfo_screenwidth()
sy = root.winfo_screenheight()
(camx, camy) = (640, 480)
grainAcik = np.ones((5,5)) # Buna Kernelde denir bosluklari doldurma islemidir
grainKapali = np.ones((20,20))
pinchFlag = 0
while True:
    ret, img = cam.read()
    img = cv2.resize(img,(camx,camy))

    # Hue, Saturation dönümü
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # Maskeleme
    mask = cv2.inRange(imgHSV, lowerb, upperb)
    maskeAcik = cv2.morphologyEx(mask, cv2.MORPH_OPEN, grainAcik)  # Morphology yani eritme yöntemi
    maskeKapali = cv2.morphologyEx(maskeAcik, cv2.MORPH_CLOSE, grainKapali)
    maskSecim = maskeKapali
    kontur, h = cv2.findContours(maskSecim.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if(len(kontur)==2):
        #if (pinchFlag == 1):
        #    pinchFlag = 0
        #    mouse.release(Button.left)
        # Parmaklar acik
        x1, y1, w1, h1 = cv2.boundingRect(kontur[0])
        x2, y2, w2, h2 = cv2.boundingRect(kontur[1])
        # Obje Cercevesi olusturma
        cv2.rectangle(img, (x1, y1), (x1+w1, y1+h1), (255, 0, 0), 2)
        cv2.rectangle(img, (x2, y2), (x2+w2, y2+h2), (255, 0, 0), 2)
        # Objelerin orta noktasi
        cx1 = x1+w1/2
        cy1 = y1+h1/2
        cx2 = x2 + w2 / 2
        cy2 = y2 + h2 / 2
        cx = (cx2+cx1)/2
        cy = (cy1+cy2)/2
        cv2.line(img, (int(cx1), int(cy1)), (int(cx2), int(cy2)), (255, 0, 0), 2)
        cv2.circle(img, (int(cx), int(cy)), 2, (0, 0, 255), 2)
        # Fare tiklama islemleri parmaklar acikken
        '''mouse.release(Button.left)

        mouseLoc = (sx-(cx*sx/camx), cy*sy/camy)
        mouse.position = mouseLoc
        while mouse.position != mouseLoc:
            pass'''

    elif(len(kontur)==1):
        x, y, w, h = cv2.boundingRect(kontur[0])
        #if (pinchFlag == 0):
        #    pinchFlag = 1
        #    mouse.press(Button.left)
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
        cx = x+w/2
        cy = y+h/2
        cv2.circle(img, (int(cx), int(cy)), int((w+h)/4), (0, 0, 255), 2)
        # Fare tiklama islemleri parmaklar kapaliyken
        '''mouse.press(Button.left)

        mouseLoc = (sx-(cx*sx/camx), cy*sy/camy)
        mouse.position = mouseLoc
        while mouse.position != mouseLoc:
            pass'''
    cv2.imshow("Kamera", img)
    cv2.waitKey(5)


import os
import pickle
import pandas as pd
import numpy as np
from Params import args
import scipy.sparse as sp

# Load data
path = 'dataset/' + args.dataset
rating_path = path + '/rating_data.txt'
trust_path = path + '/trust_data.txt'
save_path = path + '/' + args.model_name
if not os.path.exists(save_path):
    os.makedirs(save_path)

if args.dataset == 'Epinions':
    rating_df = pd.read_csv(rating_path, sep=' ', header=None, error_bad_lines=False )
    rating_df = rating_df.astype(int)
    list=[1, 2, 3, 4, 5]
    rating_df = rating_df[rating_df[2].isin(list)]        # make sure the rating is in [1,2,3,4,5]
    rating_df.columns = ['uid', 'iid', 'rating']

    trust_df = pd.read_csv(trust_path, sep=' ', header=None, error_bad_lines=False )
    trust_df = trust_df[trust_df[3] == 1]
    trust_df = trust_df.iloc[:, [1,2]]
    trust_df = trust_df.astype(int)
    trust_df.columns = ['source_uid', 'target_uid']
    print("Epinions: Successfully load the rating data and trust data......")

elif args.dataset == 'Ciao':
    rating_df = pd.read_csv(rating_path, sep='  ', header=None, error_bad_lines=False )
    rating_df = rating_df.iloc[:, [0,1,3]]
    rating_df = rating_df.astype(int)
    list=[1, 2, 3, 4, 5]
    rating_df = rating_df[rating_df[3].isin(list)]        # make sure the rating is in [1,2,3,4,5]
    rating_df.columns = ['uid', 'iid', 'rating']

    trust_df = pd.read_csv(trust_path, sep='  ', header=None, error_bad_lines=False )
    trust_df = trust_df.iloc[:, [0,1]]
    trust_df = trust_df.astype(int)
    trust_df.columns = ['source_uid', 'target_uid']
    print("Ciao: Successfully load the rating data and trust data......")

else:
    print("Dataset {} is not supported!".format(args.dataset))

def loadDataSet():
    global rating_df, trust_df
    # Collect data characteristics
    rating_uid_list = np.sum(np.array(rating_df.iloc[:, [0]]).tolist(), axis=1)
    rating_iid_list = np.sum(np.array(rating_df.iloc[:, [1]]).tolist(), axis=1)
    rating_list = np.sum(np.array(rating_df.iloc[:, [2]]).tolist(), axis=1)
    trust_list_1 = max(np.sum(np.array(trust_df.iloc[:, [0]]).tolist(), axis=1)) + 1
    trust_list_2 = max(np.sum(np.array(trust_df.iloc[:, [1]]).tolist(), axis=1)) + 1
    rating_uid_0 = max(rating_uid_list) + 1
    user_count = int(max(trust_list_1, trust_list_2, rating_uid_0))   # the number of users
    item_count = int(max(rating_iid_list) + 1)                        # the number of items
    rating_count = int(max(rating_list) + 1)                          # the number of ratings

    # Generate negative item for each user
    rating_matrix = sp.coo_matrix((rating_list, (rating_uid_list, rating_iid_list)), shape=(user_count, item_count))
    rating_matrix = rating_matrix.toarray()
    pos_iids = []
    for i in range(user_count):
        pos_iids.append(np.where(rating_matrix[i]!=0)[0])
    print("Successfully generate positive items for each user.")

    with open(save_path+ '/pos_items.pkl', 'wb') as f:
        pickle.dump(pos_iids, f, pickle.HIGHEST_PROTOCOL)

    # Generate user-user trust graph
    source_list = np.sum(np.array(trust_df.iloc[:, [0]]).tolist(), axis=1)
    target_list = np.sum(np.array(trust_df.iloc[:, [1]]).tolist(), axis=1)
    assert len(source_list) == len(target_list)
    with open(save_path + '/social_relation.pkl', 'wb') as f:
        pickle.dump(source_list, f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(target_list, f, pickle.HIGHEST_PROTOCOL)

    # Generate the train, valid, test set
    rating_df = rating_df.sample(frac=1).reset_index(drop=True)      # disorder the dataset
    test_count = int(len(rating_list) * float(args.test_rate))
    convert_dict = {'uid': int, 'iid': int, 'rating': float}
    rating_df = rating_df.astype(convert_dict)
    test_df = rating_df[0:test_count]
    valid_df = rating_df[test_count:2*test_count]
    train_df = rating_df[2*test_count:]
    print("The size of train, valid, test set is ", len(train_df), ", ", len(valid_df), ", ", len(test_df))

    # Generate single-behavior data
    train_set_b0, train_set_b1, train_set_b2 = [], [], []
    train_set = np.array(train_df).tolist()
    valid_set = np.array(valid_df).tolist()
    test_set = np.array(test_df).tolist()
    for train_data in train_set:
        if train_data[2]>0 and train_data[2]<3:
            train_set_b0.append(train_data)
        if train_data[2]==3:
            train_set_b1.append(train_data)
        if train_data[2]>3 and train_data[2]<=5:
            train_set_b2.append(train_data)
    print("Successfully single-behavior interaction data.")
    with open(save_path + '/behavior_train_set.pkl', 'wb') as f:
        pickle.dump(train_set_b0, f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(train_set_b1, f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(train_set_b2, f, pickle.HIGHEST_PROTOCOL)

    return user_count, item_count, rating_count, train_set, valid_set, test_set

if __name__ == '__main__':
    user_count, item_count, rating_count, train_set, valid_set, test_set = loadDataSet()
    with open(save_path + '/all_data.pkl', 'wb') as f:
        pickle.dump((user_count, item_count, rating_count), f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(train_set, f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(valid_set, f, pickle.HIGHEST_PROTOCOL)
        pickle.dump(test_set, f, pickle.HIGHEST_PROTOCOL)
    print("Load Over!!")


import logging
from pathlib import Path
from typing import List, Optional

from pydantic import Field

from demisto_sdk.commands.common.constants import (
    NATIVE_IMAGE_FILE_NAME,
    MarketplaceVersions,
)
from demisto_sdk.commands.common.handlers import YAML_Handler
from demisto_sdk.commands.common.native_image import (
    ScriptIntegrationSupportedNativeImages,
    file_to_native_image_config,
)
from demisto_sdk.commands.content_graph.objects.content_item import ContentItem
from demisto_sdk.commands.prepare_content.integration_script_unifier import (
    IntegrationScriptUnifier,
)

yaml = YAML_Handler()

logger = logging.getLogger("demisto-sdk")

class IntegrationScript(ContentItem):
    type: str
    docker_image: Optional[str]
    description: Optional[str]
    is_unified: bool = Field(False, exclude=True)

    def prepare_for_upload(
        self, marketplace: MarketplaceVersions = MarketplaceVersions.XSOAR, **kwargs
    ) -> dict:
        if not kwargs.get("unify_only"):
            data = super().prepare_for_upload(marketplace)
        else:
            data = self.data

        data = IntegrationScriptUnifier.unify(self.path, data, marketplace, **kwargs)
        return data

    def get_supported_native_images(
        self, marketplace: MarketplaceVersions, ignore_native_image: bool = False
    ) -> List[str]:
        if marketplace == MarketplaceVersions.XSOAR and not ignore_native_image:
            if not Path(f"Tests/{NATIVE_IMAGE_FILE_NAME}").exists():
                logger.debug(f"The {NATIVE_IMAGE_FILE_NAME} file could not be found.")
                return []
            return ScriptIntegrationSupportedNativeImages(
                _id=self.object_id,
                docker_image=self.docker_image,
                native_image_config=file_to_native_image_config(),
            ).get_supported_native_image_versions(get_raw_version=True)
        return []


import torch
import torch.nn as nn
import torch.nn.functional as F

import crystallographic_graph

from .min_distance_loss import MinDistanceLoss

class PeriodicRelativeLoss(nn.Module):
    def __init__(self, knn: int = 4):
        super().__init__()

        self.min_distance = MinDistanceLoss()
        self.knn = knn

    def forward(
        self,
        cell: torch.FloatTensor,
        x: torch.FloatTensor,
        x_tilde: torch.FloatTensor,
        num_atoms: torch.FloatTensor,
    ) -> torch.FloatTensor:
        edges = crystallographic_graph.make_graph(cell, x, num_atoms, knn=self.knn)
        e_ij = x[edges.dst] + edges.cell - x[edges.src]
        e_tilde_ij = x_tilde[edges.dst] + edges.cell - x_tilde[edges.src]

        struct_idx = torch.arange(cell.shape[0], device=cell.device)
        batch = struct_idx.repeat_interleave(num_atoms)
        batch_edges = batch[edges.src]

        _, num_edges = torch.unique_consecutive(batch_edges, return_counts=True)

        return self.min_distance(cell, e_tilde_ij, e_ij, num_edges)


import subprocess
import shutil
from pathlib import Path
import sys
import tempfile

INCLUDE_DIRS = [
    'cache',
    'core',
    'custom',
    'dev',
    'modules',
    'uploads',
    'vendor',
]

INCLUDE_FILES = [
    '.htaccess',
    '403.php',
    '404.php',
    'index.php',
    'install.php',
    'LICENSE.txt',
    'rewrite_test.php',
]

def generate_checksums(cwd):
    subprocess.check_call(['php', 'dev/scripts/generate_checksums.php'],
                          shell=False,
                          cwd=cwd)

def create_archive_dir(archive_source: str = '.') -> str:
    # Copy all files that should be included to a temporary directory
    archive_temp = tempfile.mkdtemp(prefix='nameless')

    for include_file in INCLUDE_FILES:
        include_path = Path(archive_source, include_file)
        if include_path.exists():
            shutil.copy(include_path, archive_temp)

    for include_dir in INCLUDE_DIRS:
        include_path = Path(archive_source, include_dir)
        if include_path.exists():
            shutil.copytree(include_path, Path(archive_temp, include_dir))

    return archive_temp

def create_archives(archive_name, cwd):
    archive_path: str = Path('release', archive_name).absolute().as_posix()

    print('Archive: Creating .zip file')
    zip_command = [
        'zip',
        '-r',  # Recursive
        '-q',  # Quiet
        f'{archive_path}.zip',
        '.',
    ]
    subprocess.check_call(zip_command, shell=False, cwd=cwd)

    print('Archive: Creating .tar.xz file')

    tar_command = [
        'tar',
        '-c',  # Compress
        '-J',  # Use xzip
        '--owner=0',  # Set owner inside archive to root
        '--group=0',
        '-f', f'{archive_path}.tar.xz',
        '.',
    ]

    subprocess.check_call(tar_command, shell=False, cwd=cwd,
                          env={'XZ_DEFAULTS': '-T 0'})  # Enable multithreading

def regenerate_vendor_files():
    print('Re-generating vendor files')
    shutil.rmtree('core/assets/vendor', ignore_errors=True)
    subprocess.check_call(['npm', 'ci', '-q', '--cache', '.node_cache'])
    subprocess.check_call(['composer', 'update'])
    subprocess.check_call(['composer', 'install', '--no-dev', '--no-interaction'])

def create_deps_dist_archive():
    print('Creating nameless-deps-dist archive')
    # Copy the required files to a new temporary directory
    deps_dist_temp = create_archive_dir()
    # Generate checksums
    generate_checksums(deps_dist_temp)
    # Create .zip and .tar.xz archives
    create_archives('nameless-deps-dist', deps_dist_temp)
    # Temporary directory can now be deleted
    shutil.rmtree(deps_dist_temp)

def always_in_update_package(relative_path: str) -> bool:
    return relative_path == 'checksums.json' or relative_path.startswith('vendor/') or relative_path.startswith('core/assets/vendor')

def create_upgrade_archive():
    print('Creating update archive')

    # Copy the required files to a new temporary directory
    upgrade_temp = create_archive_dir()
    # Generate checksums
    generate_checksums(upgrade_temp)

    # Find previous tag
    previous_tag_command = ['git', 'describe', '--abbrev=0', '--tags']
    previous_tag = subprocess.check_output(previous_tag_command, shell=False)[:-1].decode()

    print('Creating files for upgrade from', previous_tag)

    # Find all files changed between previous tag and HEAD (current state)
    changed_command = ['git', 'diff', previous_tag, 'HEAD', '--name-only', '--diff-filter=d']
    changed_files_output = subprocess.check_output(changed_command, shell=False)[:-1]
    changed_files = set(changed_files_output.decode().split('\n'))

    # Delete any files that have not been changed
    for path in Path(upgrade_temp).rglob("*"):
        relative_path = path.as_posix()[len(upgrade_temp)+1:]
        if (
            not always_in_update_package(relative_path) and
            relative_path not in changed_files and
            path.is_file()
        ):
            path.unlink()

    # Delete empty directoryes
    subprocess.check_call(['find', '.', '-type', 'd', '-empty', '-delete'], cwd=upgrade_temp)

    # Create .zip and .tar.xz archives
    create_archives('upgrade-from-' + previous_tag, upgrade_temp)

def create_deps_dev_archive():
    print('Creating nameless-deps-dev archive')
    # Copy the required files to a new temporary directory
    deps_dev_temp = create_archive_dir()
    # Generate checksums
    generate_checksums(deps_dev_temp)
    # Create .zip and .tar.xz archives
    create_archives('nameless-deps-dev', deps_dev_temp)
    # Temporary directory can now be deleted
    shutil.rmtree(deps_dev_temp)

if __name__ == '__main__':
    if not Path('.git').exists():
        print('.git does not exist')
        sys.exit(1)

    # Re-generate vendor files (without development dependencies)
    regenerate_vendor_files()

    # Create nameless-deps-dist archive with production dependencies only
    create_deps_dist_archive()

    # Create update archive (files changed since last tag)
    create_upgrade_archive()

    # Run composer again, to install development dependencies
    subprocess.check_call(['composer', 'install', '--no-interaction'])
    # Create nameless-deps-dev archive with development dependencies
    create_deps_dev_archive()