import socket
import threading
import uuid
import cv2
import argparse
from back_propagation import Back_Propagation
from querys import consulta

def main(args):
    HEADER=64
    PORT=args.x
    DISCONNECT_MESSAGE=args.y
    FORMAT=args.z

    fotos=['P1-1.jpg',
        'P2-1.jpg',
        'P1-2.jpg',
        'P2-2.jpg'
        ]

    salidas=[1,0,1,0]

    pixeles_fotos=[]
    # -----------------Imagenes
    for foto in fotos:
        image = cv2.imread(foto)
        auxiliar=[]
        for alto in image:
            for ancho in alto:
                auxiliar.append(ancho[0])
        auxiliar.append(1)
        pixeles_fotos.append(auxiliar)

    # -----------------

    back=Back_Propagation(pixeles_fotos,salidas)
    neuronas=back.main()

    semaphore=threading.BoundedSemaphore(2)

    ADDR2 = ("", PORT)
    server_ipv6 = socket.create_server(ADDR2, family=socket.AF_INET6, dualstack_ipv6=True)

    SERVER=socket.gethostbyname(socket.gethostname())
    ADDR=(SERVER,5051)

    server_ipv4=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    server_ipv4.bind(ADDR)
    def handle_client(conn,addr,access):

        connected=True
        id_con=uuid.uuid1().int
        id_con=id_con/1000000

        consulta(id_con)

        while connected:

            msg_length=conn.recv(HEADER).decode(FORMAT)

            if msg_length:

                msg_length=int(msg_length)
                msg=conn.recv(msg_length).decode(FORMAT)

                if msg==DISCONNECT_MESSAGE:
                    conn.send(f"Disconnect".encode(FORMAT))
                    conn.close()
                    semaphore.release()
                    connected=False
                    break

                if access==False:
                    conn.send(f"Disconnect capacity".encode(FORMAT))
                    conn.close()
                    break

                print(f"Usuario {addr} dice {msg}")

                resultado=back.foto(msg,neuronas,pixeles_fotos=[])

                conn.send(f"(SERVER MESSAGE). Usted dijo {msg}. El resultado es: {resultado}".encode(FORMAT))

    def start_server():
        print("Servidor escuchando...")
        server_ipv4.setblocking(0)
        server_ipv6.setblocking(0)
        server_ipv4.listen()
        server_ipv6.listen()

        while True:
            try:
                conn_ipv4, addr_ipv4 = server_ipv4.accept()
                print(f"Nuevo cliente IPv4 conectado. Direccion {addr_ipv4}")
                access = semaphore.acquire(blocking=False)
                threading.Thread(target=handle_client, args=(conn_ipv4, addr_ipv4, access)).start()
            except:

                pass

            try:
                conn_ipv6, addr_ipv6 = server_ipv6.accept()
                print(f"Nuevo cliente IPv6 conectado. Direccion {addr_ipv6}")
                access = semaphore.acquire(blocking=False)
                threading.Thread(target=handle_client, args=(conn_ipv6, addr_ipv6, access)).start()

            except:
                pass

    start_server()

parser=argparse.ArgumentParser()
parser.add_argument('--x',type=int,default=8080,help='Numero de puerto')
parser.add_argument('--y',type=str,default='quit',help='Mensaje de desconexion')
parser.add_argument('--z',type=str,default='utf-8',help='Formato de codificacion')
args=parser.parse_args()
main(args)


#coding=utf-8
'''
Created on 2018年3月19日

@author: gjb
'''

import os
from uiautomator import Device
import time
import random
from simu_common import *

#切换频道
def simu_eastfirst_channel(aDeviceID):
    out_log("enter simu_eastfirst_channel")
    chanle_list=EASTFIRST_CHANNEL_NAME_LIST[random.randint(0,len(EASTFIRST_CHANNEL_NAME_LIST)-1)]
    out_log("channel count=%d"%len(chanle_list))
    for i in range(0,len(chanle_list)):
        go_eastfirst_apphome(aDeviceID)
        #进入频道编辑页
        if aDeviceID(resourceId='com.songheng.eastnews:id/age').wait.exists(timeout=COMMON_WAIT_TIME):
            out_log("find channel more button ,click it")
            aDeviceID(resourceId='com.songheng.eastnews:id/age').click()
        else:
            out_error("channel more button not found,continue")
            continue
        #点击频道并进入
        if aDeviceID(resourceId='com.songheng.eastnews:id/aem').wait.exists(timeout=COMMON_WAIT_TIME):#等待进入频道编辑
            aDeviceID(text=chanle_list[i]).click()
            out_log("enter channel:%s"%chanle_list[i])
            channel_eastfirst_readartical(aDeviceID)
        else:
            out_error("channel:%s not found"%chanle_list[i])
            continue
    out_log("exit simu_channel")

#频道观看
def channel_eastfirst_readartical(aDeviceID):
    #点击随机数量文章
    random_read_article_maxnum=random.randint(1,3)
    out_log("need to read %d number of articles"%random_read_article_maxnum)
    for j in range (0,random_read_article_maxnum):
        #滑动随机几屏寻找文章
        for k in range(0,random.randint(1,2)):
            aDeviceID(scrollable=True).swipe.up(steps=80)

        #点击该页内随机第几篇文章并阅读
        random_read_articl_index=random.randint(0,3)
        out_log("read article index=%d"%random_read_articl_index)
        try:
            #检查是否是广告
            article_list=aDeviceID(resourceId='com.songheng.eastnews:id/kr',className='android.widget.ListView')
            article_selected=article_list.child_by_instance(random_read_articl_index)
            if article_selected.child(text='广告',className='android.widget.TextView').exists:
                out_error("the article is ad ,igonore it")
                continue
            else:
                out_log("the articel is not ad,read it")
                #aDeviceID(resourceId='com.songheng.eastnews:id/ou')[random_read_articl_index].wait.exists(timeout=5000):
                #aDeviceID(resourceId='com.songheng.eastnews:id/ou')[random_read_articl_index].click()
                article_selected.click()
                read_eastfirst_article(aDeviceID)
                out_log("finish read article")
                global SHARE_WEIXIN_COUNT
                if SHARE_WEIXIN_COUNT > 0:
                    share_weixin(aDeviceID)
                    SHARE_WEIXIN_COUNT=SHARE_WEIXIN_COUNT-1
                aDeviceID.press.back()
        except:
            out_error("exception happend")
            continue
        else:
            out_log("exception not happened")

#回到首页
def go_eastfirst_apphome(aDeviceID):
    for i in range(0,3):
        aDeviceID.press.back()
        if aDeviceID(resourceId='com.songheng.eastnews:id/k0').wait.exists(timeout=COMMON_WAIT_TIME):
            aDeviceID(resourceId='com.songheng.eastnews:id/k0').click()
            break

#阅读文章
def read_eastfirst_article(aDeviceID):
    #停留在文章开始处几秒钟，模仿用户看文章
    time.sleep(READ_ARTICAL_BEGIN_WAIT_TIME)
    #随机滑动次数
    random_read_article_swipe_num=random.randint(7,15)
    for i in range(0,random_read_article_swipe_num):
        if aDeviceID(className='android.webkit.WebView').wait.exists(timeout=COMMON_WAIT_TIME):
            aDeviceID(className='android.webkit.WebView')\
              .swipe.up(steps=80)
        else:
            out_error("article body not found")
            return
        if aDeviceID(descriptionContains='展开全文').exists:
            out_log("find:expand all")
            aDeviceID(descriptionContains='展开全文').click()

def eastfirst_simu(aDeviceID):
#    aDeviceID.watcher("EastFirst_Push_News").when(text="头条新闻").when(text="查看") \
#                             .press.back()

    launch_eastfirst_app(aDeviceID)
    action_list=EASTFIRST_ACTION_LIST[random.randint(0,1)]
    for i in range(0,len(action_list)):
        if action_list[i]=='channel':
            simu_eastfirst_channel(aDeviceID)
        else:
            out_error('invalid action:%s'%action_list[i])
    execCmd(CMD_CLEAN_EASTFIRST)

def share_weixin(aDeviceID,aGroupName='阳光100'):
    out_log("begin share to weixin")
    #点击页面上的分享按钮
    if aDeviceID(className='android.widget.ImageView',resourceId='com.songheng.eastnews:id/a9f').wait.exists(timeout=COMMON_WAIT_TIME):
        out_log("find share button,will share to weixin")
        aDeviceID(className='android.widget.ImageView',resourceId='com.songheng.eastnews:id/a9f').click()
    else:
        out_error("can not find share button,cancel")
        return
    #点击微信分享按钮
    if aDeviceID(className='android.widget.LinearLayout',resourceId='com.songheng.eastnews:id/ahj').wait.exists(timeout=30000):
        out_log("find weixin button,will share to weixin")
        aDeviceID(className='android.widget.LinearLayout',resourceId='com.songheng.eastnews:id/ahj').click()
    else:
        out_error("can not find share weixin button,cancel")
        return
    #点击群组
    if aDeviceID(text=aGroupName).wait.exists(timeout=COMMON_WAIT_TIME):
        out_log("find the weixin group %s"%aGroupName)
        aDeviceID(text=aGroupName).click()
    else:
        out_error("not found weixin group %s"%aGroupName)
        return

    #分享
    if aDeviceID(text='分享').wait.exists(timeout=COMMON_WAIT_TIME):
        out_log("share to weixin")
        aDeviceID(text='分享').click()
    else:
        out_error("share failed")
        return

    #返回东方头条
    if aDeviceID(text='返回东方头条').wait.exists(timeout=COMMON_WAIT_TIME):
        out_log("return to eastfirst")
        aDeviceID(text='返回东方头条').click()
    else:
        out_error("fail to return eastfirst")
        return

def launch_eastfirst_app(aDeviceID):
    aDeviceID.screen.on()
    aDeviceID.wakeup()
    #启动app
    execCmd(CMD_CLEAN_EASTFIRST)
    time.sleep(1)
    execCmd(CMD_LAUNCH_EASTFIRST)
    if aDeviceID(resourceId='com.songheng.eastnews:id/aga').wait.exists(timeout=COMMON_WAIT_TIME):
        out_log("Launch eastfirst app finished")
    else:
        out_log("ERROR:Launch eastfirst app fail")

#d=Device('410bd4f4')
#eastfirst_simu(d)
#channel_eastfirst_readartical(d)
#dab= d(resourceId="com.songheng.eastnews:id/ou", instance=1)
#ddd=d(resourceId='com.songheng.eastnews:id/kr',className='android.widget.ListView')
#print ddd.info
#line_tmp=ddd.child_by_instance(0)
#if line_tmp.child(text='广告',className='android.widget.TextView').exists:
#    print "ad"
#    line_tmp.click()
#else:
#    print "not ad"


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

import os
import re
import uuid
import sys
import json
import shutil
import subprocess
import plistlib
import errno

def run_cmd(cmd):
    print("run cmd: " + " ".join(cmd))
    print("")
    print("")
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    output = ""
    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break

        sys.stdout.write(nextline)
        sys.stdout.flush()
        output = output + nextline

    xoutput, err = process.communicate()
    exitCode = process.returncode

    if (exitCode != 0):
        if err is not None:
            print(err)

    print("")
    print("")
    return output

def self_install(file, des):
    file_path = os.path.realpath(file)

    filename = file_path

    pos = filename.rfind("/")
    if pos:
        filename = filename[pos + 1:]

    pos = filename.find(".")
    if pos:
        filename = filename[:pos]

    to_path = os.path.join(des, filename)

    print("installing [" + file_path + "] \n\tto [" + to_path + "]")
    if os.path.isfile(to_path):
        os.remove(to_path)

    shutil.copy(file_path, to_path)

    os.system('/bin/chmod a+x ' + to_path)

def regex_replace(path, rgstr, rpstr):

    print("regex_replace " + path + " " + rgstr + " " + rpstr)

    result = regex_find(path, rgstr)

    if len(result) > 0:
        print("regex found strings:")
        print(result)
        print("replacing to [" + rpstr + "] ...")

        # open the file
        f = open(path, "r")
        content = f.read()
        f.close()

        # replace
        new_content = re.sub(rgstr, rpstr, content)

        # save to file
        f = open(path, "w")
        f.write(new_content)
        f.close()

    else:
        print("regex found nothing, exit")

def mkdir_p(path):
    # print("mkdir_p: " + path)
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def regex_find(path, rgstr):
    # open the file
    f = open(path, "r")
    content = f.read()
    f.close()

    # replace
    pattern = re.compile(rgstr)
    results = pattern.findall(content)
    return results

def dir_content(folder):
    fList = os.listdir(folder)
    dirs = []
    files = []
    for f in fList:
        fPath = os.path.join(folder, f)
        if os.path.isfile(fPath):
            files.append(f)
        elif os.path.isdir(fPath):
            dirs.append(f)

    return dirs, files

def read_cmd(tip_str, cmds=["q"]):

    cmd = ""
    success = False
    while not success:

        cmd = raw_input(tip_str)
        cmd = cmd.strip()
        cmd = cmd.lower()

        if cmd in cmds:
            success = True

    return cmd, success

def __main__():

    # self_install
    if len(sys.argv) > 1 and sys.argv[1] == 'install':
        self_install("xcmk.py", "/usr/local/bin")
        return

    param = ""
    autoMode = False
    args = []

    if len(sys.argv) > 1:
        idx = 1
        while idx < len(sys.argv) - 1:
            a = str(sys.argv[idx])
            if (a.startswith('-')):
                args.append(a)
            idx += 1

        param = sys.argv[len(sys.argv) - 1]

    if ("-a" in args) or ("-A" in args):
        autoMode = True

    if not str(param).startswith("/"):
        param = os.path.join(os.getcwd(), param)

    if not str(param).endswith("project.pbxproj"):
        param = os.path.join(param, "project.pbxproj")

    if os.path.isfile(param):
        XCODE_PRJ_PATH = param
    else:
        print("using xcmk [xcode-project-path] [-a: auto mode] to auto build ipa")
        return

    regex_replace(XCODE_PRJ_PATH, "CODE_SIGN_RESOURCE_RULES_PATH[ ]*=.*\n", "CODE_SIGN_RESOURCE_RULES_PATH = \"\";\n")

    if not autoMode:
        # find bundle id
        bundle_id = ""
        results = regex_find(XCODE_PRJ_PATH, "PRODUCT_BUNDLE_IDENTIFIER ?= ?\"?.+\"?;")
        if len(results) > 0:
            tmp = results[0]
            tmp = tmp[len("PRODUCT_BUNDLE_IDENTIFIER"):]
            bundle_id = tmp.strip("=; \t\n\"")

        print("get bundle id: [" + bundle_id + "]\n")

        # profiles path
        home = os.path.expanduser("~")
        profiles_path = os.path.join(home, "Library/MobileDevice/Provisioning Profiles/")

        file_duplicate_detector = {}
        profile_list_name_match = []
        profile_list = []

        dirs, files = dir_content(profiles_path)
        for fpath in files:
            if fpath.split(".")[-1].lower() != "mobileprovision":
                continue

            path = os.path.join(profiles_path, fpath)
            f = open(path, "r")
            content = f.read()
            f.close()

            # print("walking through: " + fpath)
            start = content.find("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
            end = content.find("</plist>")

            content = content[:(end + len("</plist>"))][start:]

            plist_obj = plistlib.readPlistFromString(content)

            Entitlements = plist_obj["Entitlements"]

            app_id = Entitlements["application-identifier"]
            team_id = Entitlements["com.apple.developer.team-identifier"]

            e_bundle_id = "-"
            if app_id.startswith(team_id):
                e_bundle_id = app_id[len(team_id):]
                e_bundle_id = e_bundle_id.strip(".")
                if e_bundle_id == "":
                    e_bundle_id = "*"

            if e_bundle_id != bundle_id and e_bundle_id != "*":
                continue

            # print("found bundleid [" + bundle_id + "] in [" + fpath + "]\n")

            ProvisionedDevices = plist_obj.get("ProvisionedDevices", [])
            # print("get ProvisionedDevices: [" + ProvisionedDevices + "]")

            if len(ProvisionedDevices) != 0:
                profile_mode = "contains devices"
            else:
                profile_mode = "no device list"

            UUID = plist_obj["UUID"]
            # print("get UUID: [" + UUID + "]\n")

            TeamName = plist_obj["TeamName"]
            # print("get TeamName: [" + TeamName + "]\n")

            Name = plist_obj["Name"]
            # print("get Name: [" + Name + "]\n")

            ExpirationDate = plist_obj["ExpirationDate"]

            TeamIdentifier = plist_obj["TeamIdentifier"][0]

            obj = {}
            obj["path"] = fpath
            obj["Name"] = Name
            obj["mode"] = profile_mode
            obj["UUID"] = UUID
            obj["TeamName"] = TeamName
            obj["TeamIdentifier"] = TeamIdentifier
            obj["ExpirationDate"] = ExpirationDate

            key = "[" + Name + "]-[" + TeamName + "]-[" + profile_mode + "]"
            saved_obj = file_duplicate_detector.get(key, {})
            if saved_obj == {}:
                file_duplicate_detector[key] = obj
                if bundle_id == e_bundle_id:
                    profile_list_name_match.append(obj)
                else:
                    profile_list.append(obj)
            else:
                if obj["ExpirationDate"] > saved_obj["ExpirationDate"]:
                    # print("remove " + saved_obj["path"])
                    # os.remove(os.path.join(profiles_path, saved_obj["path"]))

                    if bundle_id == e_bundle_id:
                        new_list = []
                        for one_obj in profile_list_name_match:
                            if one_obj["Name"] == obj["Name"] and one_obj["mode"] == obj["mode"] and one_obj["TeamName"] == obj["TeamName"]:
                                continue
                            else:
                                new_list.append(one_obj)

                        profile_list_name_match = new_list
                        profile_list_name_match.append(obj)
                    else:
                        new_list = []
                        for one_obj in profile_list:
                            if one_obj["Name"] == obj["Name"] and one_obj["mode"] == obj["mode"] and one_obj["TeamName"] == obj["TeamName"]:
                                continue
                            else:
                                new_list.append(one_obj)

                        profile_list = new_list
                        profile_list.append(obj)

        print("found profiles could sign this bundle id:")

        if len(profile_list_name_match) > 0:

            profile_list_name_match = sorted(profile_list_name_match, key=lambda obj: obj["TeamName"])

            cmds = ["q"]
            idx = 0
            while idx < len(profile_list_name_match):
                cmds.append(str(idx))
                # cmds.append("s" + str(idx))
                obj = profile_list_name_match[idx]
                print(str(idx) + "\t[" + obj["Name"] \
                + "]\n\t[" + obj["mode"] \
                + "]\n\t[" + obj["TeamName"] \
                + "]\n\t[" + obj["TeamIdentifier"] \
                + "]\n\t[" + obj["UUID"] \
                + "]\n\t[" + str(obj["ExpirationDate"]) \
                + "]\n\t[" + os.path.join(profiles_path, obj["UUID"] + ".mobileprovision]\n"))
                idx = idx + 1

            cmd, success = read_cmd("input number to use profile, \"q\" to exit: ", cmds) # \"sx\" to use x whitout change,
            if success:
                if cmd.strip() == "q":
                    return 0
                else:
                    if cmd.startswith("s"):
                        cmd = cmd[1:]
                        obj = profile_list_name_match[int(cmd)]
                    else:
                        obj = profile_list_name_match[int(cmd)]
                        regex_replace(XCODE_PRJ_PATH, "CODE_SIGN_IDENTITY[ ]+=[ ]+[\",a-z,A-Z,0-9,.,\\-,_,;, ]*", "CODE_SIGN_IDENTITY = \"\";")
                        regex_replace(XCODE_PRJ_PATH, "\"CODE_SIGN_IDENTITY\\[sdk=iphoneos\\*\\]\"[ ]*=[ ,\"]*[a-z,A-Z,0-9,\\-,_,;, ,\"]*", "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"\";")
                        regex_replace(XCODE_PRJ_PATH, "PROVISIONING_PROFILE[ ]+=[ ]+[\",a-z,A-Z,0-9,.,\\-,_,;]*", "PROVISIONING_PROFILE = \"" + obj["UUID"] + "\";")

        else:

            profile_list = sorted(profile_list, key=lambda obj: obj["TeamName"])

            cmds = ["q"]
            idx = 0
            while idx < len(profile_list):
                cmds.append(str(idx))
                # cmds.append("s" + str(idx))
                obj = profile_list[idx]
                print(str(idx) + "\t[" + obj["Name"] \
                + "]\n\t[" + obj["mode"] \
                + "]\n\t[" + obj["TeamName"] \
                + "]\n\t[" + obj["TeamIdentifier"] \
                + "]\n\t[" + obj["UUID"] \
                + "]\n\t[" + str(obj["ExpirationDate"]) \
                + "]\n\t[" + os.path.join(profiles_path, obj["UUID"] + ".mobileprovision]\n"))
                idx = idx + 1

            cmd, success = read_cmd("input number to use profile, \"q\" to exit: ", cmds) # \"sx\" to use x whitout change,
            if success:
                if cmd.strip() == "q":
                    return 0
                else:
                    if cmd.startswith("s"):
                        cmd = cmd[1:]
                        obj = profile_list[int(cmd)]
                    else:
                        obj = profile_list[int(cmd)]
                        regex_replace(XCODE_PRJ_PATH, "CODE_SIGN_IDENTITY[ ]+=[ ]+[\",a-z,A-Z,0-9,.,\\-,_,;, ]*", "CODE_SIGN_IDENTITY = \"\";")
                        regex_replace(XCODE_PRJ_PATH, "\"CODE_SIGN_IDENTITY\\[sdk=iphoneos\\*\\]\"[ ]*=[ ,\"]*[a-z,A-Z,0-9,\\-,_,;, ,\"]*", "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"\";")
                        regex_replace(XCODE_PRJ_PATH, "PROVISIONING_PROFILE[ ]+=[ ]+[\",a-z,A-Z,0-9,.,\\-,_,;]*", "PROVISIONING_PROFILE = \"" + obj["UUID"] + "\";")

    xcpaths = os.path.split(XCODE_PRJ_PATH)
    if len(xcpaths) > 1:
        tmp = xcpaths[0]
        xcpaths = os.path.split(tmp)
        if len(xcpaths) > 1:
            prj_path = xcpaths[0]

    build_path = os.path.join(prj_path, "build")
    if os.path.isdir(build_path):
        shutil.rmtree(build_path)
    mkdir_p(build_path)

    arc_path = os.path.join(build_path, "build.xcarchive")

    print("reading schemes ... \n");
    print (prj_path)
    os.chdir(prj_path)
    schemes = run_cmd(["/usr/bin/xcodebuild", "-list"]);
    start = False
    tmp_schemes_lines = schemes.split("\n")
    schemes_lines = []
    for l in tmp_schemes_lines:
        l = l.strip()
        if start and len(l) > 0:
            schemes_lines.append(l)

        if l == "Schemes:":
            start = True

    tmp = os.path.basename(XCODE_PRJ_PATH)
    prj_name, ext = os.path.split(tmp)

    filted_schemes = []
    for l in schemes_lines:
        if str(l).find(prj_name) != -1:
            filted_schemes.append(l)

    if len(filted_schemes) > 0:
        cmds = ["q"]
        idx = 0
        while idx < len(filted_schemes):
            cmds.append(str(idx))
            l = filted_schemes[idx]
            print(str(idx) + "\t[" + l + "]")
            idx = idx + 1

        cmd, success = read_cmd("input number to use scheme, \"q\" to exit: ", cmds)
        if success:
            if cmd.strip() == "q":
                return 0
            else:
                SchemeName = filted_schemes[int(cmd)]
                print("select scheme: [" + SchemeName + "]")
    else:
        cmds = ["q"]
        idx = 0
        while idx < len(schemes_lines):
            cmds.append(str(idx))
            l = schemes_lines[idx]
            print(str(idx) + "\t[" + l + "]")
            idx = idx + 1

        cmd, success = read_cmd("input number to use scheme, \"q\" to exit: ", cmds)
        if success:
            if cmd.strip() == "q":
                return 0
            else:
                SchemeName = schemes_lines[int(cmd)]
                print("select scheme: [" + SchemeName + "]")

    print("building archive ...")

    os.chdir(prj_path)

    build_result = run_cmd(["/usr/bin/xcodebuild", "-scheme", SchemeName, "clean", "archive", "-archivePath", arc_path])

    if "** ARCHIVE SUCCEEDED **" not in build_result:
        print("build failed");
        return 0

    print("build success, exporting ipa ... \n")

    # ipa_method = ["app-store", "ad-hoc", "package", "enterprise", "development", "developer-id"]
    # cmds = ["q"]
    # idx = 0
    # while idx < len(ipa_method):
    #     cmds.append(str(idx))
    #     print(str(idx) + "\t[" + ipa_method[idx] + "]")
    #     idx = idx + 1
    # cmd, success = read_cmd("input number to select ipa method, \"q\" to exit: ", cmds)
    # if success:
    #     if cmd.strip() == "q":
    #         return 0
    #     else:
    #         s_method = ipa_method[int(cmd)]
    # ipa_plist_path = ipa_plist()

    ipa_path = os.path.join(build_path, "build.ipa")

    # export_result = run_cmd(["/usr/bin/xcodebuild", "-exportArchive", "-exportFormat", "ipa", "-archivePath", arc_path, "-exportPath", ipa_path, "-exportProvisioningProfile", '"' + obj["Name"] + '"'])
    export_result = run_cmd(["/usr/bin/xcodebuild", "-exportArchive", "-archivePath", arc_path, "-exportPath", ipa_path])

    if "** EXPORT SUCCEEDED **" not in export_result:
        print("export failed")
        return 0

    print ("ipa May Exported At [" + ipa_path + "]")

    print("Done")

__main__()


"""
topological.py
Compute topological ordering of a DAG or edge-weighted DAG.
 *  Runs in O(E + V) time.

 The Topological class represents a data type for
 *  determining a topological order of a directed acyclic graph (DAG).
 *  A digraph has a topological order if and only if it is a DAG.
 *  The has_order operation determines whether the digraph has
 *  a topological order, and if so, the order operation
 *  returns one.
 *
 *  This implementation uses depth-first search.
 *  The constructor takes Theta(V + E) time in the
 *  worst case, where V is the number of vertices and E
 *  is the number of edges.
 *  Each instance method takes Theta(1) time.
 *  It uses Theta(V) extra space (not including the digraph).
"""
from graphs.digraph import Digraph
from graphs.edge_weighted_digraph import EdgeWeightedDigraph
from graphs.edge_weighted_directed_cycle import EdgeWeightedDirectedCycle
from graphs.depth_first_order import DepthFirstOrder
from graphs.directed_cycle import DirectedCycle
from graphs.symbol_digraph import SymbolDigraph

class Topological:

    _order = None
    _rank = None

    def __init__(self, g):
        if isinstance(g, Digraph):
            print('g is a Digraph')
            finder = DirectedCycle(g)
            if not finder.has_cycle():
                dfs = DepthFirstOrder(g)
                self._order = dfs.reverse_post()
                self._rank = [0 for _ in range(g.get_V())]
                i = 0
                for v in self._order:
                    i += 1
                    self._rank[v] = i
        if isinstance(g, EdgeWeightedDigraph):
            print('g is an EdgeWeightedDigraph')
            finder = EdgeWeightedDirectedCycle(g)
            print(finder)
            if not finder.has_cycle():
                dfs = DepthFirstOrder(g)
                self._order = dfs.reverse_post()

    def order(self):
        return self._order

    def has_order(self):
        return self._order is not None

    def rank(self, v):
        self.__validate_vertex(v)
        if self.has_order():
            return self._rank[v]
        else:
            return -1

    def __validate_vertex(self, v):
        n = len(self._rank)
        if v < 0 or v >= n:
            raise ValueError(f'vertex {v} is not between 0 and {n - 1}')

    def __repr__(self):
        return f'<{self.__class__.__name__}(_order={self.order()}, _rank={self._rank})>'

def main():
    sg = SymbolDigraph('jobs', '/')
    print(sg)
    topological = Topological(sg.digraph())
    print(topological)
    for v in topological.order():
        print(sg.name_of(v))

if __name__ == '__main__':
    main()


import sys

def lower_dict(d):
   new_dict = dict((str(k).lower(), str(v).lower()) for k, v in d.items())
   return new_dict

def get_stock_price(s):
    COMPANIES = {
        'Apple': 'AAPL',
        'Microsoft': 'MSFT',
        'Netflix': 'NFLX',
        'Tesla': 'TSLA',
        'Nokia': 'NOK'
    }
    STOCKS = {
        'AAPL': 287.73,
        'MSFT': 173.79,
        'NFLX': 416.90,
        'TSLA': 724.88,
        'NOK': 3.37
    }

    COMPANIES = lower_dict(COMPANIES)
    STOCKS = lower_dict(STOCKS)
    s = s.lower()

    res = STOCKS.get(COMPANIES.get(s))
    if (res is None):
        print("Unknown company")
    else:
        print(res)

if __name__ == "__main__":
    if (len(sys.argv) == 2):
        get_stock_price(sys.argv[1])


# -*- coding: utf-8 -*-
# @Author: Nianko <nianko>
# @Date:   2018-03-07T11:46:32+08:00
# @Last modified by:   nianko
# @Last modified time: 2018-03-15T12:26:19+08:00

import os
import uuid
from flask_restful import  Resource, Api
from flask import Blueprint, request, jsonify, url_for, send_file
from werkzeug import SharedDataMiddleware

from app import app

up_bp= Blueprint('upload', __name__)
up_api = Api(up_bp)

UPLOAD_FOLDER = 'uploads/'

app.add_url_rule('/uploads/<filename>', 'uploaded_file', build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/uploads':  UPLOAD_FOLDER
})

class GetFile(Resource):
    def get(self, filename):
        path = os.path.abspath(os.path.join(UPLOAD_FOLDER, filename))
        return send_file(path)

class Uploads(Resource):
    def post(self):
        file = request.files.get('img')

        if file:
            filename = str(uuid.uuid1())
            try:
                os.makedirs(UPLOAD_FOLDER)
            except OSError:
                if not os.path.isdir(UPLOAD_FOLDER):
                    return jsonify({"code": -1, "message": "上传失败"})
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            path = url_for('uploaded_file', filename=filename)
            return jsonify({"code": 0, "data": {"image_url":path}})

        return jsonify({"code": -1, "message": "上传失败"})


# This file trained the neural network that we used for our Behavioral Cloning agent. It reads in the data
# saved from the BCNetDataGenerator file, modifies it as needed, then trains on all of it.

import os
import keras.backend
import tensorflow as tf
from tensorflow import keras
from keras import layers
from keras import backend as k
from keras.layers import Dense
import sys
import numpy
from sklearn.model_selection import train_test_split
from tqdm import tqdm

load_directory = "D:\\smashdataset\\parseddata\\"

# Loop over every file in the directory where we saved all our data.
for directory, subdirectory, data_files in os.walk(load_directory):
    # This will contain all of the gamestate data for the games in a directory.
    x_games = []
    # This will contain all of the controller data for the player that the NN is playing as.
    y_games = []
    # This line was only used once, hence it being commented out, but this is used to normalize stage
    # data because I forgot to do that in gathering the data.
    #enclosing_folder = ""

    # We train per stage directory rather than loading in all the files at once. It turns out that even with
    # memory mapped arrays, we didn't have enough memory to do everything at once.
    for file in tqdm(data_files):
        # Again, this is used for normalization.
        #enclosing_folder = os.path.basename(directory)

        # There were three crashes throughout the course of the data writing process.
        # That may mean incomplete data. Accidentally having some arrays a few entries
        # off from others would defeat the purpose of this exercise, hence all of this code.
        #
        # Split components of the filenames:
        file_breakdown = file.split("-")
        # Start with the gamestate data files:
        if file_breakdown[3] == "x.npy":
            # Ensure that the X file has a matching y0 and y1 file:
            if (
                    f"{file_breakdown[0]}-{file_breakdown[1]}-{file_breakdown[2]}-y0.npy" in data_files
                    and
                    f"{file_breakdown[0]}-{file_breakdown[1]}-{file_breakdown[2]}-y1.npy" in data_files
            ):
                # If p1 is a Fox player, load in the X data and the Y0 data. The data proved to be far more Fox heavy
                # than Jigglypuff heavy, so we chose to disregard any files that didn't have Fox in them.
                if file_breakdown[1] == "1":
                    path = os.path.join(directory, file)
                    # Note that we're loading these in memory mapped. This is because there is not enough memory to load the entire
                    # set in in most cases. We have >100GB of data.
                    x_games.append(numpy.load(path, mmap_mode='r+'))
                    y_games.append(numpy.load(f"{path[:-5]}y0.npy", mmap_mode='r+'))
                # If p1 is not a Fox player but p2 is, load in the X data and the Y1 data.
                elif file_breakdown[2] == "1":
                    path = os.path.join(directory, file)
                    x_games.append(numpy.load(path, mmap_mode='r+'))
                    y_games.append(numpy.load(f"{path[:-5]}y1.npy", mmap_mode='r+'))

    # This is the part that actually normalizes the stage data in each of these arrays. Once this was done once, it was
    # saved to disk, so we didn't have to do it all again. Note that we divide by 26 rather than 29 because the stage represented
    # by 29 had zero replays, so we divided by the next highest value.
    # for x in tqdm(x_games):
    #     new_x = int(enclosing_folder)/26
    #     x[:, 0] = new_x

    # If there's nothing in one of the subdirectories, go to the next one.
    if len(x_games) == 0:
        continue

    # Now that we've loaded in all of the game data and we know that input frames map to output frames, we don't care about which
    # games they came from. This code will flatten out the arrays such that they are treated as one continuous set of
    # input data/output data pairs.
    x_games = numpy.concatenate(x_games, axis=0)
    y_games = numpy.concatenate(y_games, axis=0)
    print("Concatenated.")

    # Convert to dtype=float32 to speed up training. These are stored as float64, and since things took awhile as-is I can only imagine how bad
    # it would've been had we not done this.
    x_games = x_games.astype(numpy.float32, copy=False)
    y_games = y_games.astype(numpy.float32, copy=False)
    print("Casted.")

    # Ensure that things were done right with the pruning up above. Want to make sure that every gamestate has a matching controller input.
    num_entries = tf.shape(x_games)[0]
    if num_entries != tf.shape(y_games)[0]:
        print("ERROR, Y entries not match X entries.")
        sys.exit(1)

    # Divide into training/testing sets using scikitlearn, 20% test and 80% train.
    x_train, x_test, y_train, y_test = train_test_split(x_games, y_games, test_size=0.2, random_state=20)

    # If this isn't the first loop, load in the model, otherwise we'll create it.
    if os.path.isdir(f"saved_symmetric_melee_model"):
        bc_model = keras.models.load_model(f"saved_symmetric_melee_model")
        print("Loaded model.")

    else:
        # Define model. The details of our various parameter changes and experiments are outlined in our writeup doc, but we tried several different
        # configurations here. Generally, though, this was patterned off of the model in an "Intro to TensorFlow" video tutorial series we found on
        # YouTube. The particular video that helped us out the most can be found here: https://youtu.be/pAhPiF3yiXI
        bc_model = keras.Sequential([
            # Input layer.
            keras.Input(shape=23),
            # This is one of our symmetric models, with the extra hidden layer.
            layers.Dense(115, activation='relu'),
            layers.Dense(115, activation='relu'),
            layers.Dense(115, activation='relu'),
            # We also tried making this layer a sigmoid activation instead of ReLU, thinking it might give better output results.
            layers.Dense(9, activation='relu'),

        ])

        bc_model.compile(
            # The loss function used in the example video didn't work with our data set, so we dug around and decided MSE was the best option.
            # Evidently it's the default for a reason and you really shouldn't mess with it unless you're sure you need to. Here's one source
            # that explained this to us: https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/
            loss='mean_squared_error',
            # Again, just what was in the video. We would've experimented with more possible values/optimizers had we had the time.
            optimizer=keras.optimizers.Adam(learning_rate=0.001),
            # Our goal is to be as close as possible to human inputs at any given state, which is why we use accuracy.
            metrics=["accuracy"]
        )

    # Train the network. The batch size was settled on because we wanted frequent updates but we also wanted the process to not take far too long.
    # Ultimately, we probably could've afforded to increase this a bit, but likely to even worse results. We probably would've toyed with things like batch
    # size and number of epochs more had we had more time to spend training.
    bc_model.fit(x_train, y_train, batch_size=512, epochs = 50, verbose = 2, shuffle=True)
    # Show test results at the end of each training step.
    bc_model.evaluate(x_test, y_test, batch_size=512, verbose=2)
    # Save the network so that the next loop can pick up here.
    bc_model.save(f"saved_symmetric_melee_model/")

    # Delete arrays to make space for next loop.
    del(x_games)
    del(y_games)

    # Free VRAM
    keras.backend.clear_session()#


from django.core.management.base import BaseCommand
from telegram.utils.request import Request
from telegram import Bot
from django.conf import settings
from telegram import Update, ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, CallbackContext, ConversationHandler, MessageHandler, Filters, \
    CallbackQueryHandler

from bot.views import *

class Command(BaseCommand):
    help = 'Telegram-bot'

    def handle(self, *args, **options):
        request = Request(
            connect_timeout=None,
            read_timeout=None
        )
        bot = Bot(
            request=request,
            token=settings.TOKEN,
        )

        updater = Updater(
            bot=bot,
            use_context=True
        )
        conv_hand = ConversationHandler(
            entry_points=[
                MessageHandler(Filters.text, start)
            ],
            states={
                state_user_name: [
                    MessageHandler(Filters.text, command_user_name)
                ],
                state_user_contact: [
                    MessageHandler(Filters.contact, command_user_contact)
                ],
                state_user_main: [
                    MessageHandler(Filters.regex('^(' + addorder + ')$'), command_user_addorder),
                    MessageHandler(Filters.regex('^(' + savatcha + ')$'), command_user_savatcha),
                    MessageHandler(Filters.regex('^(' + orderhistory + ')$'), command_user_orderhistory),
                    MessageHandler(Filters.regex('^(' + hisobkitob + ')$'), command_hisobkitob),
                    MessageHandler(Filters.regex('^(' + info + ')$'), command_info),
                    CallbackQueryHandler(command_user_product)
                ],
                state_user_savatcha: [
                    CallbackQueryHandler(command_user_savatcha_conf)
                ],
                state_user_muddat:[
                    CallbackQueryHandler(command_user_muddat)
                ]
            },
            fallbacks=[
                CommandHandler('start', start)
            ]

        )
        updater.dispatcher.add_handler(conv_hand)

        updater.start_polling()
        updater.idle()


# coding: utf-8
#-------------------------------------------------------------------------------
#
# This file contains the application definition for the Alexa bas skill (for Aseag Aachen)
# The application definition is specified as python file in global variables
# rather than as JSON object to
# - ensure fast loading for individual user utterances when run on the server
# -avoid parsing issued in the online system
# - allow import of custom slot types from external files (e.g. station names)
#-------------------------------------------------------------------------------

import aseag_data

APPNAME = "aseag"
#APPID   = "amzn1.ask.skill.a5cea9e0-a824-45e6-830f-5e048085f85d" # andi
APPID   = "amzn1.ask.skill.f83ddc70-f70f-40de-aa46-8d966907d8f3" # mankei
INTENTS = {
            "GetDeparturesFromFavorite":  ["Direction", "Busline", "Next", "Transport"],
            "GetDeparturesFromOther":     ["Origin", "Direction", "Busline", "Next", "Transport"],
#            "GetFavConnecionDepartures" : ["FavConnection"],
            "FindConnectionFromFavorite": ["Destination", "Next", "Transport"],
            "FindConnectionFromOther":    ["Origin", "Destination", "Next", "Transport"],
            "ChangeDefaultStation":       ["Origin"],
            "AMAZON.YesIntent" : [],
            "AMAZON.NoIntent" : [],
            "AMAZON.HelpIntent"  : [],
            "AMAZON.CancelIntent" : [],
            "AMAZON.StopIntent" : []
           }

SLOTS = {
            "Direction" :       "LIST_OF_DIRECTIONS",
            "Busline" :         "LIST_OF_ASEAG_LINES",
            "Next" :            "MODIFIER_NEXT",
            "Transport" :       "LIST_OF_TRANSPORT",
            "Origin" :          "LIST_OF_STATIONS",
            "Destination" :     "LIST_OF_STATIONS",
            "FavConnection" :   "LIST_OF_FAVORITE_CONNECTIONS"
         }

SLOTTYPES = {
            "LIST_OF_DIRECTIONS":[
                ["DIR_INWARD", [u"stadteinwärts", u"richtung stadt", u"richtung innenstadt", u"in die stadt", u"richtung aachen", u"richtung zentrum"]],
                ["DIR_OUTWARD", [u"stadtauswärts"]]
            ],
            "LIST_OF_TRANSPORT" :[
                ["DEPARTURE", [u"abfahrt", u"abfahrten"]],
                ["BUS", [u"bus", u"busabfahrt", u"busabfahrten", u"busverbindung", u"busverbindungen"]],
                ["ZUG", [u"zug", u"bahn", u"bahnverbindungen", u"zugverbindungen"]],
                ["SCHNELLBUS", [u"schnellbus"]],
                ["DIRECT", [u"direktverbindung"]],
                ["ANY", [u"verbindung"]]
            ],
            "MODIFIER_NEXT" :[
                ["ANY",   [u"der", u"die", u"ein", u"eine", u"irgendein", u"irgendeine"]],
                ["NEXT",  [u"der nächste", u"die nächste"]],
                ["NEXT5", [u"die nächsten fünf"]]
            ],
            "LIST_OF_FAVORITE_CONNECTIONS" : [
                ["SCHOOL", [u"der schulbus",
                            u"mein schulbus", u"mein bus in die schule", u"mein bus zur schule"]],
                ["WORK", [u"mein bus in die arbeit", u"mein bus zur arbeit", u"mein bus in die firma"]],
            ],
            "LIST_OF_ASEAG_LINES" : aseag_data.BUSLINES, # import from external file
            "LIST_OF_STATIONS" : aseag_data.STATIONLIST # import from external file
   }


n = int(input())
matrix = []
for _ in range(n):
    matrix.append(input().split())

b_r = 0
b_c = 0
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] == 'B':
            b_r = i
            b_c = j
best = {}
moves = ['left', 'right', 'up', 'down']

for move in moves:
    result = 0
    if move == 'left':
        x = b_r
        y = b_c - 1
        while 0 <= x < n and 0 <= y < n:
            if matrix[x][y] == 'X':
                break
            number = int(matrix[x][y])
            result += number
            y -= 1
        best[move] = result
    elif move == 'right':
        x = b_r
        y = b_c + 1
        while 0 <= x < n and 0 <= y < n:
            if matrix[x][y] == 'X':
                break
            number = int(matrix[x][y])
            result += number
            y += 1
        best[move] = result
    elif move == 'up':
        x = b_r - 1
        y = b_c
        while 0 <= x < n and 0 <= y < n:
            if matrix[x][y] == 'X':
                break
            number = int(matrix[x][y])
            result += number
            x -= 1
        best[move] = result
    elif move == 'down':
        x = b_r + 1
        y = b_c
        while 0 <= x < n and 0 <= y < n:
            if matrix[x][y] == 'X':
                break
            number = int(matrix[x][y])
            result += number
            x += 1
        best[move] = result
res = dict(sorted(best.items(), key= lambda x: -x[1]))
best_direction = ''
best_value = 0
for k, v in res.items():
    best_direction = k
    best_value = v
    break
print(best_direction)
dirs = {'left': [0, -1], 'right': [0, 1], 'up': [-1, 0], 'down': [1, 0]}
x = b_r + dirs[best_direction][0]
y = b_c + dirs[best_direction][1]
while 0 <= x < n and 0 <= y < n:
    if matrix[x][y] == 'X':
        break
    print([x, y])
    b_r = x
    b_c = y
    x = b_r + dirs[best_direction][0]
    y = b_c + dirs[best_direction][1]
print(best_value)


#!/usr/bin/python3
"""
Square Class: Prints a square with # and coordinates
"""

class Square:
    """ clas square that defines a square """
    def __init__(self, size=0, position=(0, 0)):
        """ Initializes the attributes"""
        self.size = size
        self.position = position

    @property
    def size(self):
        """ get size """
        return self.__size

    @size.setter
    def size(self, value):
        """ sets the size with safe Assignment """
        if type(value) is not int:
            raise TypeError("size must be an integer")
        if (value < 0):
            raise ValueError("size must be >= 0")
        self.__size = value

    @property
    def position(self):
        """ retrieve the initial position """
        return self.__position

    @position.setter
    def position(self, value):
        """ sets the new position """
        s = "position must be a tuple of 2 positive integers"
        if type(value) is not tuple:
            raise TypeError(s)
        elif (len(value) != 2):
            raise TypeError(s)
        else:
            for t in value:
                if (t < 0):
                    raise TypeError(s)
                elif (type(t) is not int):
                    raise TypeError(s)
        self.__position = value

    def area(self):
        """ Return the area of the square """
        return (self.__size * self.__size)

    def my_print(self):
        """ prints in stdout with # """
        if (self.size != 0):
             print("\n" * self.__position[1], end="")
             print("\n".join([" " * self.__position[0] + "#" * self.__size
                 for rows in range(self.__size)]))
        else:
            print("")


from double_linked_list import *

class DoubleLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def append(self, data, previous=None, next=None):

        if self.head == None:
            self.head = TwoWayNode(data)
            self.tail = self.head
        else:
            tail = self.tail
            while tail.next:
                tail = tail.next
            tail.next = TwoWayNode(data, previous, next)

        self.size += 1

    def size(self):
        return str(self.size)

    def iter(self):
        probe = self.tail
        while probe.previous:
            print(probe.data)
            probe = probe.previous


"""Test the elements of complete plots based on ensemble COSMO-2 data."""
# Local
from .shared import _TestBase
from .shared import _TestCreatePlot  # noqa:F401
from .shared import _TestCreateReference  # noqa:F401
from .shared import datadir  # noqa  # required by _TestBase.test

INFILE_1 = "flexpart_cosmo-2e_2021030503_{ens_member:03d}_MUE.nc"
ENS_MEMBER_IDS = [0, 5, 10, 15, 20]

# Uncomment to create plots for all tests
# _TestBase = _TestCreatePlot

# Uncomment to references for all tests
# _TestBase = _TestCreateReference

class Test_EnsMin_AffectedArea(_TestBase):
    reference = "ref_cosmo-e_ens_min_affected_area"
    setup_dct = {
        "files": {
            "input": INFILE_1,
            "output": f"{reference}.png",
        },
        "model": {
            "name": "COSMO-2E",
            "ens_member_id": ENS_MEMBER_IDS,
        },
        "panels": [
            {
                "plot_variable": "affected_area",
                "ens_variable": "minimum",
                "integrate": True,
                "lang": "de",
                "domain": "full",
                "dimensions": {
                    "time": -1,
                    "level": 0,
                },
            }
        ],
    }

class Test_CloudArrivalTime(_TestBase):
    reference = "ref_cosmo-2e_ens_cloud_arrival_time"
    setup_dct = {
        "files": {
            "input": INFILE_1,
            "output": f"{reference}.png",
        },
        "model": {
            "name": "COSMO-2E",
            "ens_member_id": ENS_MEMBER_IDS,
        },
        "panels": [
            {
                "ens_variable": "cloud_arrival_time",
                "plot_variable": "concentration",
                "integrate": True,
                "ens_params": {
                    "mem_min": 1,
                    "thr": 1e-6,
                },
                "lang": "en",
                "domain": "full",
                "dimensions": {
                    "time": 0,
                    "level": 0,
                },
            }
        ],
    }

class Test_CloudDepartureTime(_TestBase):
    reference = "ref_cosmo-2e_ens_cloud_departure_time"
    setup_dct = {
        "files": {
            "input": INFILE_1,
            "output": f"{reference}.png",
        },
        "model": {
            "name": "COSMO-2E",
            "ens_member_id": ENS_MEMBER_IDS,
        },
        "panels": [
            {
                "ens_variable": "cloud_departure_time",
                "plot_variable": "concentration",
                "integrate": True,
                "combine_levels": True,
                "ens_params": {
                    "mem_min": 1,
                    "thr": 0,
                },
                "lang": "de",
                "domain": "ch",
                "dimensions": {
                    "time": 3,
                    "level": 0,
                },
            }
        ],
    }

class Test_MultipanelEnsStats_Concentration(_TestBase):
    reference = "ref_cosmo-2e_multipanel_ens_stats_integr_concentration"
    setup_dct = {
        "files": {
            "input": INFILE_1,
            "output": f"{reference}.png",
        },
        "layout": {
            "plot_type": "multipanel",
            "multipanel_param": "ens_variable",
        },
        "model": {
            "name": "COSMO-2E",
            "ens_member_id": ENS_MEMBER_IDS,
        },
        "panels": {
            "plot_variable": "concentration",
            "ens_variable": ["minimum", "maximum", "median", "mean"],
            "integrate": True,
            "lang": "de",
            "domain": "ch",
            "dimensions": {
                "time": -1,
                "level": 0,
            },
        },
    }


from setuptools import setup, find_packages

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setup(
    name="LigPrepper",
    version="0.4.3",
    author="Abhishek Kognole",
    author_email="aakognole@gmail.com",
    description="Simple program to quickly prepare ligand 3d SDF/MOL2/PDBQT from smiles",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/aakognole/ligprepper",
    project_urls={
        "Bug Tracker": "https://github.com/aakognole/ligprepper/issues",
    },
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    packages=find_packages(),
    install_requires=['rdkit-pypi'],
    python_requires=">=3.6",
    zip_safe=False
)


#!/usr/bin/env.python
# -*- coding:utf-8 -*-
n = int(input())
l = sorted(map(int, input().split()))

def find_max(s, e, x):
    head, tail = s, e
    while s <= head <= tail <= e:
        mid = (head + tail) // 2
        if l[mid] <= x:
            head = mid + 1
        else:
            tail = mid - 1
    return tail

id = n - 1
for e in range(min(l[-1],n), -1, -1):
    id = find_max(0, id, e)  # 有num个比e大的
    num = n - 1 - id
    if e <= num:  # 比e大的个数刚好够着e的大小，e不能再小了
        break

print(e)


"""
Frequently Used request handlers.
By : Mahmoud Elshobaky (mahmoud.elshobaky@gmail.com).
"""

# import app engine frameworks
import webapp2, jinja2
# import app settings
from settings import *
# importing libs and modules for Intenationalization
from webapp2_extras import i18n
from webapp2_extras.i18n import gettext as _
# user login
from google.appengine.api import users
from user.data_models import LocalUser
# importing modules for handling file uploads
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
# session handler for flash messages
from webapp2_extras.sessions import SessionDict

from assets.misc import *
# get text for translations and internationalization
def t(text):
    return _(text)
# initialize jinja template envionment
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(TEMPLATE_DIR),
                               extensions=['jinja2.ext.i18n'],
                               autoescape = True)
jinja_env.install_gettext_translations(i18n)

# function used to prepare the template file
def render_str(template, **params):
    t = jinja_env.get_template(template)
    return t.render(params)

# main class used for handling requests
class MainHandler(webapp2.RequestHandler, SessionDict):
    """
    used for handlig requests and building responses
    using basic webapp2 requesthandler plus some helper functions:
     -- sending response options:
      - plain text response:
        self.write(text_response)
      - HTML response:
        self.render("path_to _html _file",**optional_kw_args_to_use_with_jinj2_templates)
      - JSON response:
        self.write_json(dict_or_json_object)
     -- dealing with cookies:
       - self.set_secure_cookie(name,value,remember=False)
       - self.read_secure_cookie(name)

    ready to use with user app
    """
    def write(self, *a, **kw):
        "function for sending string response to user"
        self.response.out.write(*a, **kw)

    # functions for building a response using template file
    def render_str(self, template, **params):
        params['user'] = self.local_user
        params['admin'] = self.admin
        params['author'] = self.author
        params['google_user'] = self.google_user
        params['locale'] = self.locale
        params['flashes'] = self.get_flashes()
        return render_str(template, **params)

    def render(self, template, **kw):
        "used to send a response using a template file"
        self.write(self.render_str(template, **kw))

    def write_json(self, data):
        "used to respond with json for ajax requests"
        self.response.headers['Content-Type'] = 'application/json'
        if type(data) is dict: data = json.dumps(data, default=date_handler)
        if is_json(data): self.write(data)

    def set_secure_cookie(self, name, val,remember=False):
        cookie_val = make_secure_val(val)
        if remember :
            expires = cookies_expiry_date()
            self.response.headers.add_header(
                'Set-Cookie',
                '%s=%s; Path=/; expires=%s' % (name, cookie_val,expires))
        else :
            self.response.headers.add_header(
                'Set-Cookie',
                '%s=%s; Path=/' % (name, cookie_val))

    def read_secure_cookie(self, name):
        cookie_val = self.request.cookies.get(name)
        return cookie_val and check_secure_val(cookie_val)

    def switch_locale(self, locale, remember=True):
        try:
            locale = str(locale)
            self.set_secure_cookie('locale', locale,remember=remember)
            return True
        except:
            return False

    def login(self, user, remember=False):
        self.set_secure_cookie('user_id', str(user.key.id()),remember=remember)

    def logout(self):
        self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')

    def signup(self):
        role = 'u'
        if self.admin: role='admin'
        u = LocalUser.register(self.google_user.user_id(), self.google_user.email(), self.google_user.nickname(), role=role)
        u.put()
        self.login(u)
        self.add_flash(t('thanks! for signing up please, go to ') +\
                         '%s'% t('your profile') +\
                         t(' to update your info'),'success')
        return u

    def initialize(self, *a, **kw):
        webapp2.RequestHandler.initialize(self, *a, **kw)
        self.locale = self.read_secure_cookie('locale')
        if self.locale is None :
            self.locale = LOCALE
        self.local_user = None; self.admin = None; self.author = None
        # check if user logged in from cookies and grapping user entity from database
        uid = self.read_secure_cookie('user_id')
        if uid:
            self.local_user = LocalUser.by_id(int(uid))
        # check if user logged in with google account
        self.google_user = users.get_current_user()
        if self.google_user and self.local_user:
            # check if google_user matches the local_user
            if self.local_user.user_id != self.google_user.user_id():
                self.local_user.user_id = self.google_user.user_id()
                self.local_user.put()
            elif users.is_current_user_admin():
                if self.local_user.role != 'admin':
                    self.local_user.role = 'admin'
                    self.local_user.put()
                self.admin = self.author = self.local_user
        elif self.google_user:
            u = LocalUser.by_google_id(self.google_user.user_id())
            if u :
                self.login(u)
                self.local_user = u
                if u.role == 'admin':
                    self.admin = self.author = self.local_user
                if u.role == 'author':
                    self.author = self.local_user
            else:
                u = LocalUser.by_email(self.google_user.email())
                if u :
                    u.user_id = self.google_user.user_id()
                    u.put()
                else:
                    u = self.signup()
                    self.local_user = u
        if self.local_user:
            if self.locale != self.local_user.locale:
                self.switch_locale(self.local_user.locale)
                self.locale = self.local_user.locale
        self.user = self.local_user
        #self.locale = str(self.locale)
        i18n.get_i18n().set_locale(self.locale)

# handlers for file upload and download
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler, MainHandler):
    """UploadHandler containg main function to upload and download files"""
    def create_upload_url(self,url):
        return blobstore.create_upload_url(url)

    def get_info(self,value):
        return blobstore.BlobInfo.get(value)

class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler, MainHandler):
    def get_file(self,file_key):
        if blobstore.get(file_key):
            return True
        else:
            return False

    def send_file(self, file_key):
        if not self.get_file(file_key):
            self.error(404)
            self.write('file not found')
        else:
            self.send_blob(file_key)


"""
Author: Dheeraj Alimchandani

Date : 13-11-2019

File : WalkSAT.py

Usage : WalkSAT Algorithm
"""

import random
from time import time
import queue
from preprocessing import CnfPreprocess
from utils import Utils as ut

random.seed(2)

class WalkSAT:

    def __init__(self):
        self.sat_variables = []

    def zero_negative_gain(self,negative_gain,unsat_clause_selection):

        zero_negative_gain = [index for index, zero in enumerate(negative_gain) if zero == 0]

        if len(zero_negative_gain) > 1:  # If more than one -ve gain with 0
            flipped_value_var = random.choices(zero_negative_gain)
            flipped_value_index = abs(unsat_clause_selection[flipped_value_var[0]]) - 1
        else:
            flipped_value_index = abs(unsat_clause_selection[zero_negative_gain[0]]) - 1

        return flipped_value_index

    def min_negative_gain(self, negative_gain, unsat_clause_selection):

        min_value = min(negative_gain)
        min_negative_gain = [index for index, min in enumerate(negative_gain) if min == min_value]
        if len(min_negative_gain) > 1:  # If more than one min. -ve gain (breaking tie)
            flipped_value_var = random.choices(min_negative_gain)
            flipped_value_index = abs(unsat_clause_selection[flipped_value_var[0]]) - 1
        else:
            flipped_value_index = abs(unsat_clause_selection[min_negative_gain[0]]) - 1

        return flipped_value_index

    def walksat_solution(self, cnf_formula, max_tries, max_flips, wp, tl, preprocess):

        for try_sol in range(0, max_tries):
            tabu = queue.Queue(maxsize=tl)  # Initializing the tabu queue
            # Here we will generate the random solution in the form of Booleans
            initial_solution = ut.generate_solution(preprocess)

            for flip in range(0, max_flips):
                # Here we will be returned with the and of all clauses
                if ut.clause_satisfation(initial_solution, cnf_formula, satcheck=True):
                    ''' Generating the solution by changing the booleans to actual variable '''
                    final_sol_list = ut.final_solution(initial_solution, preprocess, try_sol, flip)
                    self.sat_variables = final_sol_list
                    return f'Solution is {final_sol_list} generated in {try_sol + 1} tries and {flip + 1} flips'

                else:
                    # sol_list_init = []
                    index_selected_unsat_clause = []

                    '''Generating the variable solution list from the boolean list'''
                    sol_list_init = ut().variable_sol_list(initial_solution)

                    # List of all the clauses after performing OR operation on each
                    all_clauses = ut.clause_satisfation(initial_solution, cnf_formula, satcheck=False)

                    cnf_formula_unsat = ut().unsat_clauses(all_clauses, cnf_formula) # All unsat clauses
                    cnf_formula_sat = ut().sat_clauses(all_clauses, cnf_formula)    # All SAT clauses

                    # Selecting UNSAT clause randomly
                    unsat_clause_selection = random.choice(cnf_formula_unsat)

                    '''CHECKING THE TABU LIST, if all the variables in selected unsat clauses are on the tabu list'''
                    tabu_list = list(tabu.queue)

                    # Creating the selected usat clause variable list (not literal)
                    abs_unsat_clause_selection = [abs(var) for var in unsat_clause_selection]

                    # if all the variables are in tabu list then
                    if set(abs_unsat_clause_selection).issubset(set(tabu_list)):
                        continue

                    '''We will check for each variale if that variable in UNSAT clause exists in tabu list
                        If yes : The remove that variable from tabu list.
                        It is a preprocessed step to reduce operation cost of checking tabu list after the var
                        selection
                    '''
                    for index,var in enumerate(abs_unsat_clause_selection):
                        if var in tabu.queue:
                            index_selected_unsat_clause.append(index)

                    # Now lets remove the variables from selected unsat clause which are in tabu list
                    unsat_clause_selection = [i for j,i in enumerate(unsat_clause_selection) if j not in index_selected_unsat_clause]

                    # If only single variable is present in the unsat clause after tabu check, then just flip that
                    if len(unsat_clause_selection) == 1:
                        flipped_value_index = abs(unsat_clause_selection[0]) - 1

                    else:
                        # Computing negative gain of the variables in selected unsat clauses
                        negative_gain = ut.negative_gain(sol_list_init, cnf_formula_sat, unsat_clause_selection)

                        if 0 in negative_gain:
                            '''Checking for the variables with negative gain of 0'''
                            flipped_value_index = self.zero_negative_gain(negative_gain, unsat_clause_selection)

                        else:
                            r = random.random()
                            if r < wp:
                                '''getting a random variable in the selected unsat clauses'''
                                flipped_value_var = random.choice(unsat_clause_selection)
                                flipped_value_index = abs(flipped_value_var) - 1

                            else:
                                '''Selecting the variable with minimum negative gain'''
                                flipped_value_index = self.min_negative_gain(negative_gain, unsat_clause_selection)

                    '''Manipulating the tabu list'''
                    if tabu.full():
                        tabu.get()
                    tabu.put(flipped_value_index+1)

                    '''Flipping the initial_solution variable'''
                    initial_solution[flipped_value_index] = not (initial_solution[flipped_value_index])

        return 'No Solution'

    def solution_txt(self):
        with open('sol_gwsat.txt', 'w') as sat_sol:
            sat_sol.write('c Solution generated using GWSAT \n')
            sat_sol.write('v')
            for variables in self.sat_variables:
                if variables % 11 == 0:
                    sat_sol.write('\n')
                    sat_sol.write('v')
                sat_sol.write(f' {str(variables)} ')

if __name__ == '__main__':
    max_tries = 10
    max_flips = 100
    wp = 0.4
    tl = 5
    cnf_instance = 'Lab-data/Lab-data/Inst/uf20-06.cnf'
    preprocess = CnfPreprocess(cnf_instance)
    cnf_formula = preprocess.filter_cnf_instance()
    walksat = WalkSAT()
    start = time()
    result = walksat.walksat_solution(cnf_formula, max_tries, max_flips, wp, tl, preprocess)
    print(f'The execution took {round(time() - start, 3)} seconds')
    print(result)
    walksat.solution_txt()


# 给出方程式 A / B = k, 其中 A 和 B 均为用字符串表示的变量， k 是一个浮点型数字。根据已知方程式求解问题，并返回计算结果。如果结果不存在，
# 则返回 -1.0。
#
#  示例 :
# 给定 a / b = 2.0, b / c = 3.0
# 问题: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
# 返回 [6.0, 0.5, -1.0, 1.0, -1.0 ]
#
#  输入为: vector<pair<string, string>> equations, vector<double>& values, vector<p
# air<string, string>> queries(方程式，方程式结果，问题方程式)， 其中 equations.size() == values.siz
# e()，即方程式的长度与方程式结果长度相等（程式与结果一一对应），并且结果值均为正数。以上为方程式的描述。 返回vector<double>类型。
#
#  基于上述例子，输入如下：
#
#  equations(方程式) = [ ["a", "b"], ["b", "c"] ],
# values(方程式结果) = [2.0, 3.0],
# queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]
# ].
#
#
#  输入总是有效的。你可以假设除法运算中不会出现除数为0的情况，且不存在任何矛盾的结果。
#  Related Topics 并查集 图

from typing import List
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        node_dict = {}
        for i in range(len(equations)):
            node_dict[equations[i][0]] = (equations[i][0], 1)
            node_dict[equations[i][1]] = (equations[i][1], 1)

        def find(x):
            if x == node_dict[x][0]:
                return node_dict[x]
            root, sub_val = find(node_dict[x][0])
            node_dict[x] = root, sub_val * node_dict[x][1]
            return node_dict[x]

        def union(a, b, value):
            root_a, val_a = find(a)
            root_b, val_b = find(b)
            if root_a != root_b:
                node_dict[root_a] = (root_b, value * val_b / val_a)
                find(a)

        for i in range(len(equations)):
            union(equations[i][0], equations[i][1], values[i])

        res = []
        for q in queries:
            if q[0] not in node_dict or q[1] not in node_dict:
                res.append(-1.0)
            else:
                root_0, val_0 = find(q[0])
                root_1, val_1 = find(q[1])
                if root_0 == root_1:
                    res.append(val_0 / val_1)
                else:
                    res.append(-1.0)
        return res

# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
    equations = [["a", "b"], ["b", "c"]]
    values = [2.0, 3.0]
    queries = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]
    print(Solution().calcEquation(equations, values, queries))


#!/usr/bin/env python3 -tt
"""A module to help students visualize their path through the maze

@parthsarin 11-21-2019 created
"""
import tkinter
from tkinter import messagebox
import time
import exploremaze
import threading
import os

class MazeViz:
    def __init__(self, parent, maze_width, maze_height, scale=20):
        """Initializes the GUI and draws a grid on it.

        Keyword arguments:
        parent -- the parent Tk object
        maze_width -- the width of the maze
        maze_height -- the height of the maze
        scale -- 1 maze unit = `scale` many pixels
        """
        self.parent = parent
        self.parent.title("Maze Exploration Visualization")

        self.maze_width = maze_width
        self.maze_height = maze_height
        self.scale = scale

        # Compute actual width and height
        self.width = maze_width * scale
        self.height = maze_height * scale

        # Store tkinter object
        self.frame = tkinter.Frame(self.parent,
                                   width=self.width,
                                   height=self.height,
                                   highlightthickness=1,
                                   highlightbackground="black")
        self.canvas = tkinter.Canvas(self.frame,
                                     width=self.width,
                                     height=self.height)
        self.canvas.pack(expand=False)
        self.frame.pack(expand=False)

        # Initialize look of grid
        self.draw_gray_grid()

        self.person = None
        self.draw_person(self.maze_width // 2, self.maze_height // 2)

    def draw_gray_grid(self):
        """Draws a grayed out grid on the canvas."""
        gray = "#D3D3D3"
        # Draw the vertical lines
        for x in range(0, self.width, self.scale):
            self.canvas.create_line(x, 0, x, self.height, fill=gray)

        # Draw the horizontal lines
        for y in range(0, self.height, self.scale):
            self.canvas.create_line(0, y, self.width, y, fill=gray)

    def draw_visited(self, x, y):
        """Highlights (x,y) as light green"""
        # Compute pixel coords
        upper_left = (y * self.scale, x * self.scale)
        lower_right = tuple(i + self.scale for i in upper_left)

        color = '#90ee90'
        self.canvas.create_rectangle(*upper_left, *lower_right, fill=color, outline='')

    def draw_person(self, x, y, color="blue"):
        """Draws a person at the location specified."""
        # Delete the old person
        if self.person is not None:
            self.canvas.delete(self.person)

        # Compute pixel coords
        upper_left = (y * self.scale, x * self.scale)
        lower_right = tuple(i + self.scale for i in upper_left)

        # Add some padding
        upper_left = tuple(i + self.scale / 10 for i in upper_left)
        lower_right = tuple(i - self.scale / 10 for i in lower_right)

        self.person = self.canvas.create_oval(*upper_left, *lower_right,
                                              fill=color)
        self.person_location = (x, y)

    def draw_lines(self, x, y,
                   north=False, south=False, east=False, west=False,
                   color="black"):
        """Draws lines on the canvas around the area where the
        student is currently standing based on the boolean parameters."""
        upper_left = (y * self.scale, x * self.scale)
        upper_right = (upper_left[0] + self.scale, upper_left[1])
        lower_left = (upper_left[0], upper_left[1] + self.scale)
        lower_right = (upper_left[0] + self.scale, upper_left[1] + self.scale)

        if north:
            self.canvas.create_line(*upper_left, *upper_right, fill=color)

        if south:
            self.canvas.create_line(*lower_left, *lower_right, fill=color)

        if east:
            self.canvas.create_line(*upper_right, *lower_right, fill=color)

        if west:
            self.canvas.create_line(*upper_left, *lower_left, fill=color)

    def draw_unicorn_hit(self, x, y, color="yellow"):
        """Draws a unicorn marker at the location specified.
        TODO: decompose this and draw_person
        """
        # Compute pixel coords
        upper_left = (y * self.scale, x * self.scale)
        lower_right = tuple(i + self.scale for i in upper_left)

        # Add some padding
        upper_left = tuple(i + self.scale / 10 for i in upper_left)
        lower_right = tuple(i - self.scale / 10 for i in lower_right)

        self.canvas.create_oval(*upper_left, *lower_right,
                                fill=color)

    def refresh(self):
        """Redraws the canvas.
        TODO: find a safer way to do this (race cond'n warning)
        """
        self.parent.update()

def overwrite_student(old_fn, app):
    """Overwrites the student's function by updating the
    canvas and sleeping between function calls."""

    def new_fn(x, y, url):
        result = old_fn(x, y, url)

        # Draw the output
        if "neighbors" in result:
            all_directions = {"north", "south", "east", "west"}
            valid_directions = set(result["neighbors"].keys())
            blocked_directions = all_directions - valid_directions

            # Build a dict to use to draw the lines
            draw_kwargs = {d: (d in blocked_directions)
                           for d in all_directions}

            # Signal that x, y was visited
            app.draw_visited(x, y)

            # Draw the lines, move the person and refresh
            app.draw_lines(x, y, **draw_kwargs)

        if "unicorn_cry" in result:
            app.draw_unicorn_hit(x, y)

        app.draw_person(x, y)
        app.refresh()

        return result

    return new_fn

def full_app():
    """Call the student's exploremaze function (once it's
    been overwritten) and then prompt for saving the data
    collected."""
    unicorn_data = exploremaze.search_maze()
    save = messagebox.askyesno("Save?",
                               "Do you want to save the unicorn data by calling save_data?",
                               icon='question')

    if save:
        try:
            os.remove(exploremaze.OUTPUT_FILENAME)
        except OSError:
            pass

        exploremaze.save_data(unicorn_data, exploremaze.OUTPUT_FILENAME)
        messagebox.showinfo("Save", "Data saved.", icon='info')

def main():
    """Initialize the GUI and start exploring!"""
    # Initialize GUI
    master = tkinter.Tk()
    app = MazeViz(master, exploremaze.MAZE_WIDTH, exploremaze.MAZE_HEIGHT)

    # Overwrite get_url_data
    old = exploremaze.get_url_data
    exploremaze.get_url_data = overwrite_student(old, app)

    # Call search_maze and explore
    t = threading.Thread(target=full_app)
    t.start()

    # Open app
    tkinter.mainloop()

    # End the function call
    t.join()

if __name__ == '__main__':
    main()


import os
import time as tt
import math as m
import random as rd
import numpy as np
from numpy.lib import scimath

tmp_file = "/tmp/.tmp_file"
img = ""

def get_ecr_size():
    tmp_file = "/tmp/."+ str(rd.randint(0, 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)) + ""
    cmd = "rm -rf " + tmp_file + "; touch " + tmp_file + "; tput cols > " + tmp_file + "; tput lines >> " + tmp_file + ";"
    os.system(cmd)
    f = open(tmp_file, "r")
    size = [int(f.readline()), int(f.readline())]
    f.close
    cmd = "rm -rf " + tmp_file + ";"
    os.system(cmd)
    return (size)

def get_ecr_size_vec():
    size = get_ecr_size()
    return (np.array(size))

def get_ecr_size2():
    size = get_ecr_size()
    return ({'x':size[0], 'y':size[1]})

def get_col(val):
    val = val if ((val >= 0.0) and (val <= 1.1)) else (0.0 if (val < 0.0) else 1.0)
    color = [' ', '.', '-', ':', '*', '0', '@', '#']
    id = int(val * (len(color) - 1))
    return (color[id])

#def print_line(img2, size, p1, p2, c1, c2):
#    global img
#
#    diff = [(p2[0] - p1[0]), (p2[1] - p1[1])]
#    col_dif = [(c2[0] - c1[0]), (c2[1] - c1[1]), (c2[2] - c1[2])]
#   # len_line = m.sqrt(diff[0]**2 + diff[1]**2)
#    id_max = 0 if (abs(diff[0]) >= abs(diff[1])) else 1
#    id_min = 1 - id_max
#    ratio = diff[id_min] / diff[id_max]
#    nb_pix = diff[id_max]
#    pos = [0, 0]
#    print("id_min:", id_min, "id_max:", id_max)
#    for i in range(nb_pix):
#    pos[id_max] = 0#float(p1[id_max] + i)
#    pos[id_min] = p1[id_min] + float(i * ratio) / (nb_pix)
#    img[int(pos[0] + pos[1] * size[0])] = "9"#get_col(c1)

#################################################

###### DATA ######
# {position + axe} camera
# liste des position des point
# liste des liens des point
# ==> liste des segment

class Vector:

    def __init__(self, x = 0.0, y = 0.0, z = 0.0):
        self.x = x
        self.y = y
        self.z = z

    def sub(a, b):
        return (Vector(a.x - b.x, a.y - b.y, a.z - b.z))

    def add(a, b):
        return (Vector(a.x + b.x, a.y + b.y, a.z + b.z))
    def scalar_product(vec, coef):
        return (Vector(vec.x * coef, vec.y * coef. vec.z * coef))
    def dot_product(v1, v2):
        return (v1.x * v2.x, v1.y * v2.y, v1.z * v2.z)
    def normalize(vec):
        return (scalar_product(vec, 1.0 / m.sqrt(dot_product(vec, vec))))

class Segment:

    def __init__(self, pt1 = Vector(0., 0., 0.), pt2 = Vector(1., 1., 1.)):
        self.pt1 = pt1
        self.pt2 = pt2
        self.normal = Vector.normalize(Vector.sub(pt2, pt1))
        self.thick = 5.0

    def get_dist_xy(pt):
        return (abs(Vector.dot_product(Vector.sub(pt, self.pt1), self.normal)))

    def get_dist_z():
        # a terme on s'en servira pour avoir un z_buffer
        return (0.0)

    def is_inside(pt):
        return (self.get_dist_xy(pt) <= self.thick)

class Object:

    def __init__(self):
        self.pts = [] # liste de point
        self.conexion = [] #liste des connexiont
        self.nb_point = len(self.pts)

###### DATA ######
# {position + axe} camera
# liste des position des point
# liste des liens des point
# ==> liste des segment

###### ALGO ######
# le point en 3d
# changement de repere camera
# projection conique
# tracer une ligne a l'ecran

def get_seg_dist_2d(seg, pt):
	# diff  scalaire normale < largeur
	print("la on fait de la magie")

def get_color_pix(x, y, size, time):
	cx = (float(x) / size[0])
	cy = (float(y) / size[1])
	value = (m.sin(m.sin(cy * 7.0 + time * 1.01)) + \
		m.cos((cx * 12.0) + 1.0 * time) + \
		m.cos(cx * 37.0 + 1.4 * time) * 0.3 +\
		m.sin(cx * 80.0 + 1.4 * time) * 0.1 +\
		2.4 ) / 4.8

	#(m.sin((15.0 * (x + -time)) / size[0]) + m.cos(((7.0 * (y + time))/size[1])) + m.cos(float(x) / size[0] + 1.01 * -time) * 0.1 + 2.5) / 5.0
	return get_col(value)

def print_all_screen(tab_line, size_ecr):
    os.system("clear;")
    img = ""
    t = tt.clock()
    print("\n")
    for y in range(size_ecr[1]):
        line = ""
        for x in range(size_ecr[0] - 1):
        	line += str(get_color_pix(x, y, size_ecr, t * 10))
        img += line + "\n"
    os.system("echo \""+ img + "\"")

#################################################

def test_palette():
    print("nb lines:", size[0], "nb cols:", size[1])
    for a in range(-2, 10):
        help(a)
        b = a
        print("=====================================>", b)
        val = float((float(b) + 0.0) / 7.0)

def test_termshader():
    ecr = get_ecr_size()
    print("screen:{x:"+str(ecr[0])+", y:"+str(ecr[1])+"}")
    tab_line = [{'x1':0, 'x2':ecr[0] , 'y1':0 , 'y2':ecr[1], 'col':0.9}]

    while True :
        print_all_screen(tab_line, get_ecr_size())
        tt.sleep(0.05)
###################################################################################
###################################################################################
###################################################################################
###################################################################################

#lst1 # la premiere liste de point
#lst2 # la deusieme liste de point
#len1 # la premiere taille
#len2 # la deusieme taille

def get_number_face(nb):
    if (nb == 4):
        lst_pt = np.array([[[0.1, 0.1, 0.3],[0.9, 0.1, 0.3],[1.2, 0.5, 0.3],[0.9, 0.9, 0.3],[0.1, 0.1, 0.3]],[[0.1, 0.1, -0.3],[0.9, 0.1, -0.3],[1.2, 0.5, -0.3],[0.9, 0.9, -0.3],[0.1, 0.1, -0.3]]])
    elif (nb == 2):
      lst_nb = np.array([[[0.3, 0.3, 0.3],[0.6, 0.3, 0.3],[1.2, 0.5, 0.3],[0.6, 0.6, 0.3],[0.3, 0.6, 0.3],[0.3, 0.3, 0.3]],[[0.3, 0.3, -0.3],[0.6, 0.3, -0.3],[1.2, 0.5, -0.3],[0.6, 0.6, -0.3],[0.3, 0.6, -0.3],[0.3, 0.3, -0.3]]])
    return (lst_pt)

def get_rotation_matrice(rot):
    rot_all = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
    c = np.cos(rot.data[0])
    s = np.sin(rot.data[0])
    rotx = np.array([[1., 0., 0.], [0., c, -s], [0., s, c]])
    c = np.cos(rot.data[1])
    s = np.sin(rot.data[1])
    roty = np.array([[c, 0., s], [0., 1., 0.], [-s, 0., c]])
    c = np.cos(rot.data[2])
    s = np.sin(rot.data[2])
    rotz = np.array([[0., c, -s], [0., s, c], [0., 0., 1.]])
    rot_all = rot_all.dot(rotx)
    rot_all = rot_all.dot(roty)
    rot_all = rot_all.dot(rotz)
    return (rot_all)

def landmark_change(obj_seg, nb_seg, center, rot):
    for i in range(nb_seg):
        tmp = (obj_seg[0][i].sub(center))
        new_seg[0][i] = tmp.mult(rot)

        tmp = (obj_seg[1][i].sub(center))
        new_seg[1][i] = tmp.mult(rot)
    return (new_seg)

def landmark_change_proj(size, obj_seg, nb_seg, center, rot):
    for i in range(nb_seg):
        tmp = np.add(obj_seg[0][i], center * -1)
        rot_mat = get_rotation_matrice(rot)
        print("rot:", rot_mat)
        tmp = rot_mat.dot(tmp)
        print("tmp", tmp)
        tt.sleep(10000)
        print("tmp.data[0][0]", tmp.data[0][0])
        print("\ttmp.data[0][2]", tmp.data[0][2],)
        print("\tsize.data[0][0]", size.data[0][0])
        tmp.data[0][0] = (tmp.data[0][0] / tmp.data[0][2]) * size.data[0][0]
        tmp.data[0][1] = tmp.data[0][1] / tmp.data[0][2]  * size.data[0][1]
        new_seg[0][i] = tmp

        tmp = np.sub(obj_seg[1][i], center)
        tmp = rot.dot(tmp)
        tmp.data[1][0] = (tmp.data[1][0] / tmp.data[1][2]) * size.data[1][0]
        tmp.data[1][1] = tmp.data[1][1] / tmp.data[1][2]  * size.data[1][1]
        new_seg[1][i] = tmp
    return (new_seg)

def is_in_line(size, pos_ecr, pt_beg, pt_end, width):
    # il faut la projection du point dans le repere de la ligne
    # du coup on peut determiner la normal et donc la distance
    print("yolo\n")

# on retourne eventuelement un nombre entre [0., 1.]
#    ou directement le charactere
def is_in_lst(size, lst, nb_pt, pos_ecr):
    for i in range(nb_pt):
        id_prev = ((i - 1 + nb_pt) % nb_pt)
        id_next = ((i + 1) % nb_pt)
        # lst.data[0][i] -> lst.data[0][id_prev]
        # lst.data[0][i] -> lst.data[0][id_next]
        # lst.data[1][i] -> lst.data[1][id_prev]
        # lst.data[1][i] -> lst.data[1][id_next]
        # lst.data[0][i] -> lst.data[1][i]

# Il faut encore

def vector_test_print():
    #
    vmat = [[1., 2.], [3., 4.]]
    vtest = np.array([42.1337, 1.3, .5])
 #   help(vtest)
    print("coucou\n", get_ecr_size())
    print("x=>", vtest.data[0])
    for j in range(2):
        for i in range(2):
            print("-->[", j, "],[", i, "]<--\n")

def vector_test():
   # obj_2 = get_number_face(2)
    size = get_ecr_size_vec()
    nb = 4
    obj_4 = get_number_face(nb)
    cam_pos = np.array([0., 0.,-5])
    len_4 = 4 if (nb == 4) else 2
    rot = np.array([0., 0., 0.])

    obj_tmp = landmark_change_proj(size, obj_4, len_4, cam_pos, rot)
    img_txt = ""
    # pour toute les pixel
    for y in range(size.data[1]):
        img_txt += "\n"
        for x in range(size.data[0]):
            val = is_in_lst(size, obj_tmp, len_4, cam_pos, rot)
            img_txt += get_col(val)
        os.system(("echo " + img_txt))
    #time.sleep(0.025)

# on va renvoyer une liste des point d'une des face sous forme de liste
# on va la copier et la deplacer selon la normale de la face.
# pour chaque point serra relier a 3 autre point: ses deux voisin et son equivalent de l'autre face

if __name__ == "__main__":
#    test_termshader()
    vector_test()

#	word = ""
#	help("")
#	test_line(size)


from sysinfo_lib import parseCharDelimitedTable, tableToDict

def parser(stdout, stderr):
    output = {}
    columns = ['installtime', 'buildtime', 'name', 'version', 'release', 'arch', 'vendor', 'packager', 'distribution', 'disttag']
    if stdout:
        output = parseCharDelimitedTable(stdout, '|', columns)
        output = tableToDict(output, 'name')

    return {'output': output}

def register(main):
    main['rpm'] = {
        'cmd': 'rpm -q -a --queryformat "%{INSTALLTIME}|%{BUILDTIME}|%{NAME}|%{VERSION}|%{RELEASE}|%{arch}|%{VENDOR}|%{PACKAGER}|%{DISTRIBUTION}|%{DISTTAG}\n"',
        'description': 'Querying all RPM packages',
        'parser': parser
    }


import random
import sys
import time

class TicTacToe(object):

    CHARACTER_X_SYMBOL = "X"
    CHARACTER_O_SYMBOL = "O"

    # All the probability of winner's move.
    DATA_SET = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],

        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],

        [0, 4, 8],
        [2, 4, 6]
    ]

    def __init__(self, debugMode=False):
        self.__is_debug_mode = debugMode
        self.__log("Initializing the TicTacToe class...")

        self.__log("Allocating new spaces for board and player moves...")
        # Initialize the board with empty value.
        # Board size: 3x3
        self.board = [[None] for i in range(0, 9)]

        # Records the moves of player x.
        self.__xMoves = []
        # Records the moves of player o.
        self.__oMoves = []

        # Winner
        self.__winner = ""

        self.__log("Game is now ready to use!")

    def is_cell_taken(self, index: int) -> bool:
        """Checking the cell availability.

        Arguments:
            index {int} -- Cell's index.

        Returns:
            bool
        """

        return self.board[index][0] != None

    def get_winner(self) -> str:
        """Get the winner.

        Returns:
            str -- The winner's character.
        """

        return self.__winner

    def set_winner(self, character: str) -> None:
        """Set a new winner.

        Arguments:
            character {str} -- The winner's character.
        """

        self.__winner = character

    def get_player_moves_record(self, character: str) -> list:
        """[summary]

        Arguments:
            character {str} -- [description]

        Returns:
            list -- [description]
        """

        if character == TicTacToe.CHARACTER_X_SYMBOL:
            return self.__xMoves
        else:
            return self.__oMoves

    def get_board_diagonal(self, cr: int) -> list:
        """Get board's cross value in a list. It only has two valid value for `cr` wich is `1` and `2`.
        Otherwise will raise a RuntimeError.

        1 is the cross side from `Top-left` to `Bottom-right`,

        2 is the cross side from `Bottom-left` to `Top-right`.

        Arguments:
            cr {int} -- The cross side.

        Raises:
            RuntimeError

        Returns:
            list -- The value of cross side.
        """

        self.__log("get_board_diagonal(cr: %d)" % cr)

        if (cr != 1) or (cr != 2):
            raise RuntimeError("Invalid cross side was given: %d" % cr)

        if cr == 1:  # Top-Left -> Bottom-right
            return [self.board[n] for n in range(0, 9, 4)]
        else: # Top-right -> Bottom-left
            return [self.board[n] for n in range(2, 8, 2)]

    def get_board_column(self, col: int) -> list:
        """Get board's column value in a list.

        Arguments:
            col {int} -- Column index (1, 2, 3).

        Raises:
            RuntimeError

        Returns:
            list -- The value of column.
        """

        self.__log("get_board_column(col: %d)" % col)

        if (col < 1) or (col > 3):
            raise RuntimeError("Invalid column index was given: %d" % d)

        if col == 1:
            return [self.board[n] for n in range(0, 9, 3)]
        elif col == 2:
            return [self.board[n] for n in range(1, 9, 3)]
        else:
            return [self.board[n] for n in range(2, 9, 3)]

    def get_board_row(self, row: int) -> list:
        """Get board's row value in a list.

        Arguments:
            row {int} -- Row index (1, 2, 3).

        Raises:
            RuntimeError

        Returns:
            list -- The value of row.
        """

        self.__log("get_board_row(row: %d)" % row)

        if (row < 1) or (row > 3):
            raise RuntimeError("Invalid row index was given: %d" % row)

        if row == 1:
            return [self.board[n] for n in range(0, 3)]
        elif row == 2:
            return [self.board[n] for n in range(3, 6)]
        else:
            return [self.board[n] for n in range(6, 9)]

    def insert_cell_value(self, index: int, character: str) -> None:
        """Insert new value into specific cell.

        Arguments:
            index {int} -- Cell's index.
            character {str} -- Fill value.

        Raises:
            RuntimeError
        """

        self.__log("insert_cell_value(index: %d, character: %s)" % (index, character))

        if (index < 0) or (index > 8):
            raise RuntimeError("Given index exceed the limits: %d" % index)

        if (character != TicTacToe.CHARACTER_X_SYMBOL) and (character != TicTacToe.CHARACTER_O_SYMBOL):
            raise RuntimeError("Given value is not a valid character: %c" % character)

        if self.board[index][0] != None:
            raise RuntimeError("The index is already filled with value: %c" % self.board[index][0])

        self.board[index][0] = character

    def save_moves_record(self, index: int, character: str) -> None:
        """Save each moves record into a list. The record would be used to get the winner.

        Arguments:
            index {int} -- Destination cell's index.
            character {str} -- Character type.

        Raises:
            RuntimeError
        """

        self.__log("save_moves_record(character: %s, index: %d)" % (character, index))

        if (character != TicTacToe.CHARACTER_X_SYMBOL) and (character != TicTacToe.CHARACTER_O_SYMBOL):
            raise RuntimeError("Given value is not a valid character: %c" % character)

        if character == TicTacToe.CHARACTER_X_SYMBOL:
            self.__xMoves.append(index)
        else:
            self.__oMoves.append(index)

    def check_moves(self, records: list) -> bool:
        """Check player moves from the given `records`.

        Arguments:
            records {list} -- Player's move records.

        Returns:
            bool -- True if there is matches move from the data set (Found the winner).
        """

        self.__log("check_moves(records: 0x%x)" % id(records))

        for data in TicTacToe.DATA_SET:
            if all(element in records for element in data):
                return True
        return False

    def __log(self, message: str) -> None:
        """Log any important message. Enable `debugMode` to activate this function.

        Arguments:
            message {str} -- Log messages.
        """

        if not self.__is_debug_mode:
            return

        now = time.localtime(time.time())
        sys.stdout.write("[TicTacToe] %d:%d:%d -> %s\n" % (now.tm_hour, now.tm_min, now.tm_sec, message))

    @property
    def is_debug_mode(self) -> bool:
        return self.__is_debug_mode

if __name__ == "__main__":
    print("[Error] This module is the backend class. Please use `play.py` instead to start the game!")
    exit(code=1)


# coding: utf-8

from setuptools import setup, Extension

from Cython.Build import cythonize

extensions = cythonize([
    Extension('graphql_parser.{}'.format(cls_name),
              ['graphql_parser/{}.pyx'.format(cls_name)],
              libraries=['graphqlparser'],
              include_dirs=['.'])
    for cls_name in ['GraphQLParser', 'GraphQLAstVisitor',
                     'GraphQLAst', 'GraphQLAstNode']
])

setup(
    name='graphqlparser',
    version='0.0.4',
    author='Marco Paolini',
    author_email='markopaolini@gmail.com',
    description='Python bindings for libgraphqlparser (Cython-based)',
    long_description='\n\n'.join([open('README.rst', 'r').read(),
                                  '-----',
                                  open('NEWS.rst', 'r').read()]),
    url='https://github.com/elastic-coders/py-graphqlparser',
    packages=['graphql_parser'],
    install_requires=['cython'],
    package_data={'graphql_parser': ['*.pxd', '*.pyx']},
    include_package_data=True,
    ext_modules=extensions,
    license='BSD',
    keywords=['graphql', 'parser', 'libgraphql'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: CPython',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


from math import *

def HaversineDistance (lat1, lon1, lat2, lon2):
	# Radius of the Earth, in km
	R = 6371

	lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

	dlon = lon2 - lon1
	dlat = lat2 - lat1
	a = sin (dlat/2)**2 + cos (lat1) * cos (lat2) * sin (dlon/2)**2
	c = 2 * atan2 (sqrt (a), sqrt (1-a))
	d = R * c

	return d


#!/usr/bin/python
import time

def main():
    combinaciones = ["2L: 1"]
    for monedas1L in range(0,3):
        restante = 200

        combinacion={"1L":monedas1L}
        restante -= monedas1L * 100

        for monedas50p in range((restante//50)+1):
            combinacion["50p"]=monedas50p
            restante -= monedas50p * 50

            for monedas20p in range((restante//20)+1):
                combinacion["20p"]=monedas20p
                restante -= monedas20p * 20

                for monedas10p in range((restante//10)+1):
                    combinacion["10p"]=monedas10p
                    restante -= monedas10p * 10

                    for monedas5p in range((restante//5)+1):
                        combinacion["5p"]=monedas5p
                        restante -= monedas5p * 5

                        for monedas2p in range((restante//2)+1):
                            combinacion["2p"]=monedas2p
                            restante -= monedas2p * 2

                            monedas1p = restante
                            combinacion["1p"]=monedas1p

                            combinaciones.append(list(combinacion.values()))

                            restante += monedas2p * 2
                        restante += monedas5p * 5
                    restante += monedas10p * 10
                restante += monedas20p * 20
            restante += monedas50p * 50
        restante += monedas1L * 100

##    for elem in combinaciones:
##        print(elem)
    print(str(len(combinaciones)),"combinaciones")

if __name__ == "__main__":
    start_time = time.time()
    main()
    print("--- %s seconds ---" % (time.time() - start_time))