### common 4.14.0-0.el7 ########################################################
from flags import *

def setup(exc):
    PID_T = 'unistd.h'
    SIZE_T = 'stddef.h'
    SA_FAMILY_T = "sys/socket.h"
    SOCKADDR = 'sys/socket.h'

    exc['asm-generic/ipcbuf.h'] = (['linux/posix_types.h'],
                                   OK, '__kernel_key_t')

    exc['asm-generic/msgbuf.h'] = (['linux/posix_types.h', 'asm-generic/ipcbuf.h'],
                                   OK, 'ipc64_perm __kernel_time_t')

    exc['asm-generic/sembuf.h'] = (['linux/posix_types.h', 'asm-generic/ipcbuf.h'],
                                   OK, 'ipc64_perm __kernel_time_t')

    exc['asm-generic/shmbuf.h'] = ([SIZE_T, 'linux/posix_types.h', 'asm-generic/ipcbuf.h'],
                                   OK, 'ipc64_perm __kernel_time_t size_t')

    exc['asm-generic/signal.h'] = ([SIZE_T],
                                   OK, 'size_t')

    exc['asm-generic/ucontext.h'] = ([SIZE_T, 'asm-generic/signal.h', 'asm/sigcontext.h'],
                                     OK, 'stack_t sigcontext')

    exc['asm/ipcbuf.h'] = (['linux/posix_types.h'],
                           OK, '__kernel_key_t')

    exc['asm/msgbuf.h'] = (['linux/posix_types.h', 'asm-generic/ipcbuf.h'],
                           OK, 'msg_perm, __kernel_time_t')

    exc['asm/sembuf.h'] = (['linux/sem.h'],
                           OK, '__kernel_time_t sem_perm')

    exc['asm/shmbuf.h'] = (['linux/shm.h'], OK, 'shm_perm')

    exc['asm/signal.h'] = ([SIZE_T], OK, 'size_t')

    exc['drm/drm.h'] = ([SIZE_T, 'stdint.h'],
                        OK, 'size_t uint32_t uint64_t')

    exc['drm/drm_mode.h'] = (['stdint.h'], OK, '__u32 __u64 uint32_t uint64_t')

    exc['drm/drm_sarea.h'] = ([SIZE_T, 'stdint.h'],
                              OK, 'size_t uint32_t uint64_t')

    exc['drm/exynos_drm.h'] = ([SIZE_T, 'stdint.h'],
                               OK, 'size_t uint32_t uint64_t')

    exc['drm/i810_drm.h'] = ([SIZE_T, 'stdint.h', 'drm/drm.h'],
                             OK, 'drm_clip_rect size_t uint32_t uint64_t')

    exc['drm/i915_drm.h'] = ([SIZE_T, 'stdint.h'],
                             OK, 'size_t uint32_t uint64_t')

    exc['drm/mga_drm.h'] = ([SIZE_T, 'stdint.h'],
                             OK, 'size_t uint32_t uint64_t')

    exc['drm/msm_drm.h'] = (['stdint.h'], OK, 'uint32_t uint64_t')

    exc['drm/nouveau_drm.h'] = (['stdint.h'], OK, 'uint32_t uint64_t')

    exc['drm/qxl_drm.h'] = (['stdint.h'], OK, 'uint32_t')

    exc['drm/r128_drm.h'] = exc['drm/i810_drm.h']

    exc['drm/radeon_drm.h'] = ([SIZE_T, 'stdint.h'], OK, 'size_t uint32_t uint64_t')

    exc['drm/savage_drm.h'] = exc['drm/i810_drm.h']

    exc['drm/sis_drm.h'] = ([], WARN | BLACKLIST,
                            'list_head not available')

    exc['drm/tegra_drm.h'] = ([SIZE_T, 'stdint.h'], OK, 'size_t uint32_t')

    exc['drm/via_drm.h'] = ([], WARN | BLACKLIST,
                            'nonexistent file in include: via_drmclient.h, blacklisted')

    exc['drm/vmwgfx_drm.h'] = ([SIZE_T, 'stdint.h'],
                             OK, 'size_t uint32_t uint64_t')

    exc['linux/agpgart.h'] = ([SIZE_T],
                              OK, 'size_t')

    exc['linux/android/binder.h'] = ([PID_T],
                                     OK, 'pid_t uid_t')

    exc['linux/atm_zatm.h'] = (['linux/time.h'],
                               OK, 'timeval')

    exc['linux/atmbr2684.h'] = ([SOCKADDR],
                                OK, 'sockaddr')

    exc['linux/auto_fs.h'] = (['linux/limits.h'],
                              OK, 'NAME_MAX')

    exc['linux/auto_fs4.h'] = exc['linux/auto_fs.h']

    exc['linux/btrfs.h'] = (['stddef.h'], OK, 'NULL')

    exc['linux/can/bcm.h'] = ([SA_FAMILY_T],
                              OK | INFO, 'timeval canid_t sa_family_t, linux/time.h conflicts with sys/time.h')

    exc['linux/coda.h'] = (['sys/types.h', '* #define _LINUX_TIME_H'],
                           OK | WARN, 'u_short pid_t ino_t caddr_t  u_short, sys/types conflicts with linux/time.h included by coda.h')

    exc['linux/coda_psdev.h'] = (['* struct list_head {};', '* typedef void* wait_queue_head_t;', 'sys/types.h'],
                                 OK | WARN, 'linux/coda_psdev.h - struct wait_queue_head_t not present anywhere')

    exc['linux/dlm_netlink.h'] = (['linux/dlmconstants.h'],
                                  OK, 'DLM_RESNAME_MAXLEN')

    exc['linux/dm-log-userspace.h'] = (['stdint.h'],
                                       OK, 'uint64_t')

    exc['linux/elfcore.h'] = ([
                               """* #include <stddef.h>
                                    #include <unistd.h>
                                    #define ELF_NGREG 1
                                    struct dummy {};
                                    typedef struct dummy elf_greg_t;
                                    typedef struct dummy elf_gregset_t;
                                    typedef struct dummy elf_fpregset_t;
                                    typedef struct dummy elf_fpxregset_t;"""
                               ], OK | WARN,
                              'user_regs_struct, size_t, pid_t, elf_greg_t, elf_gregset_t, elf_fpregset_t, elf_fpxregset_t')

    exc['linux/errqueue.h'] = (['linux/time.h'], OK, 'timespec')

    exc['linux/hdlc/ioctl.h'] = ([SOCKADDR, 'linux/if.h'],
                                 OK, 'IFNAMSIZ')

    exc['linux/hsi/hsi_char.h'] = (['stdint.h'], OK, 'uint32_t uint64_t')

    exc['linux/if.h'] = ([SOCKADDR],
                         OK, 'sockaddr')

    exc['linux/if_arp.h'] = ([SOCKADDR],
                             OK, 'sockaddr sa_family_t')

    exc['linux/if_bonding.h'] = ([SOCKADDR],
                                 OK, 'sockaddr')

    exc['linux/if_frad.h'] = ([SOCKADDR],
                              OK, 'sockaddr')

    exc['linux/if_pppol2tp.h'] = (['linux/in.h', 'linux/in6.h'],
                                  OK, 'sockaddr_in sockaddr_in6 sa_family_t')

    exc['linux/if_pppox.h'] = (['linux/in.h', 'linux/in6.h', SOCKADDR, 'linux/if.h'],
                               OK, 'sockaddr_in sockaddr_in6 sa_family_t ETH_ALEN IFNAMSIZ sockaddr')

    exc['linux/if_tunnel.h'] = ([SOCKADDR, 'linux/if.h', 'linux/ip.h', 'linux/in6.h'],
                                OK, 'IFNAMSIZ')

    exc['linux/ip6_tunnel.h'] = ([SOCKADDR, 'linux/if.h', 'linux/in6.h'],
                                 OK, 'IFNAMSIZ in6_addr')

    exc['linux/ipv6_route.h'] = (['linux/in6.h'],
                                 OK, 'in6_addr')

    exc['linux/kexec.h'] = ([SIZE_T],
                               OK, 'size_t')

    exc['linux/llc.h'] = ([SOCKADDR, 'linux/if.h'],
                          OK, 'sa_family_t IFHWADDRLEN')

    exc['linux/mroute.h'] = (['linux/in.h'],
                             OK, 'in_addr')

    exc['linux/mroute6.h'] = (['linux/in6.h'],
                              OK, 'sockaddr_in6 in6_addr')

    exc['linux/mqueue.h'] = (['linux/posix_types.h'], OK, '__kernel_long_t')

    exc['linux/ncp_fs.h'] = ([SIZE_T],
                             OK, 'sa_family_t, size_t')

    exc['linux/netdevice.h'] = ([SOCKADDR],
                                OK, 'sa_family_t sockaddr')

    exc['linux/netfilter.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                OK, 'in_addr in6_addr sa_family_t')

    exc['linux/netfilter/ipset/ip_set_bitmap.h'] = (['linux/netfilter/ipset/ip_set.h'],
                                                    OK, 'IPSET_ERR_TYPE_SPECIFIC')

    exc['linux/netfilter/ipset/ip_set_hash.h'] = exc['linux/netfilter/ipset/ip_set_bitmap.h']

    exc['linux/netfilter/ipset/ip_set_list.h'] = exc['linux/netfilter/ipset/ip_set_bitmap.h']

    exc['linux/netfilter/nf_conntrack_sctp.h'] = ([SIZE_T, 'linux/types.h'],
                                                  OK, '__be32 size_t')

    exc['linux/netfilter/nf_conntrack_tuple_common.h'] = ([SIZE_T, 'linux/types.h'],
                                                  OK, '__be16 size_t')

    exc['linux/netfilter/nf_nat.h'] = (['sys/types.h', 'linux/in.h', 'linux/in6.h'],
                                        OK, 'in in6 ')

    exc['linux/netfilter/xt_HMARK.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h', 'linux/netfilter.h'],
                                         OK, 'nf_inet_addr')

    exc['linux/netfilter/xt_RATEEST.h'] = ([SOCKADDR, 'linux/if.h'],
                                           OK, 'IFNAMSIZ')

    exc['linux/netfilter/xt_TEE.h'] = ([SOCKADDR, 'linux/in.h', 'linux/in6.h', 'linux/netfilter.h'],
                                       OK, 'IFNAMSIZ')

    exc['linux/netfilter/xt_TPROXY.h'] = exc['linux/netfilter/xt_TEE.h']

    exc['linux/netfilter/xt_connlimit.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                             OK, 'nf_inet_addr __be32')

    exc['linux/netfilter/xt_conntrack.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                             OK, 'nf_inet_addr')

    exc['linux/netfilter/xt_hashlimit.h'] = ([SOCKADDR, 'linux/if.h', 'linux/limits.h'],
                                             OK, 'IFNAMSIZ NAME_MAX')

    exc['linux/netfilter/xt_iprange.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                           OK, 'nf_inet_addr')

    exc['linux/netfilter/xt_ipvs.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h', 'linux/netfilter.h'],
                                           OK, 'nf_inet_addr')

    exc['linux/netfilter/xt_mac.h'] = (['linux/if_ether.h'],
                                       OK, 'ETH_ALEN')

    exc['linux/netfilter/xt_osf.h'] = (['linux/ip.h', 'linux/tcp.h'],
                                       OK, 'MAX_IPOPTLEN iphdr tcphdr')

    exc['linux/netfilter/xt_physdev.h'] = ([SOCKADDR, 'linux/if.h'],
                                           OK, 'IFNAMSIZ')

    exc['linux/netfilter/xt_policy.h'] = (['linux/in.h', 'linux/in6.h'],
                                          OK, 'in_addr in6_addr sa_family_t')

    exc['linux/netfilter/xt_rateest.h'] = ([SOCKADDR, 'linux/if.h'],
                                           OK, 'IFNAMSIZ')

    exc['linux/netfilter/xt_recent.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h', 'linux/netfilter.h'],
                                             OK, 'nf_inet_addr')

    exc['linux/netfilter/xt_sctp.h'] = (['* typedef int bool;', '* #define true 1;', '* #define false 0;'],
                                        OK | WARN, 'bool true false not defined')

    exc['linux/netfilter_arp.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                    OK, 'in_addr in6_addr')

    exc['linux/netfilter_arp/arp_tables.h'] = ([SOCKADDR, 'linux/if.h', 'linux/in.h', 'linux/in6.h'],
                                               OK, 'in_addr in6_addr u_int8_t u_int16_t IFNAMSIZ')

    exc['linux/netfilter_arp/arpt_mangle.h'] = ([SOCKADDR, 'linux/if.h', 'linux/in.h', 'linux/in6.h'],
                                               OK, 'in_addr in6_addr u_int8_t u_int16_t IFNAMSIZ')

    exc['linux/netfilter_bridge.h'] = ([SOCKADDR, 'linux/if.h', 'linux/in.h', 'linux/in6.h'],
                                       OK, 'in_addr in6_addr u_int8_t u_int16_t IFNAMSIZ')

    exc['linux/netfilter_bridge/ebt_arp.h'] = (['linux/if_ether.h'],
                                               OK, '__be16 ETH_ALEN uint8_t')

    exc['linux/netfilter_bridge/ebt_arpreply.h'] = (['linux/if_ether.h'],
                                                    OK, 'ETH_ALEN')

    exc['linux/netfilter_bridge/ebt_ip6.h'] = (['linux/in6.h'], OK, '__be32 uint8_t')

    exc['linux/netfilter_bridge/ebt_nat.h'] = (['linux/if_ether.h'],
                                               OK, 'ETH_ALEN')

    exc['linux/netfilter_bridge/ebt_ulog.h'] = ([SIZE_T, 'stdint.h', SOCKADDR, 'linux/if.h'],
                                                OK | WARN, 'uint32_t  IFNAMSIZ timeval size_t timeval')

    exc['linux/netfilter_bridge/ebtables.h'] = ([SOCKADDR, 'stdint.h',
                                                'linux/in.h', 'linux/in6.h', 'linux/if.h'],
                                                OK, 'sockaddr inaddr in6addr uint64_t')

    exc['linux/netfilter_decnet.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                       OK, 'INT_MIN')

    exc['linux/netfilter_ipv4.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                     OK, 'INT_MIN INT_MAX')

    exc['linux/netfilter_ipv4/ip_tables.h'] = ([SOCKADDR, 'linux/in.h', 'linux/in6.h', 'linux/if.h'],
                                               OK, 'in_addr in6_addr INT_MIN INT_MAX u_int16_t u_int8_t IFNAMSIZ')

    exc['linux/netfilter_ipv4/ipt_ULOG.h'] = ([SIZE_T, SOCKADDR, 'linux/if.h'],
                                              OK, 'size_t IFNAMSIZ')

    exc['linux/netfilter_ipv6.h'] = ([SA_FAMILY_T, 'linux/in.h', 'linux/in6.h'],
                                     OK, 'INT_MIN in_addr in6_addr')

    exc['linux/netfilter_ipv6/ip6_tables.h'] = ([SOCKADDR, 'linux/if.h', 'linux/in.h', 'linux/in6.h'],
                                                OK, 'INT_MIN in_addr in6_addr  u_int16_t u_int8_t IFNAMSIZ')

    exc['linux/netfilter_ipv6/ip6t_NPT.h'] = ([SIZE_T, 'linux/in.h', 'linux/in6.h'],
                                             OK, 'SIZE_T in in6')

    exc['linux/netfilter_ipv6/ip6t_rt.h'] = (['linux/in6.h'], OK, 'u_int32_t in6_addr')

    exc['linux/nfc.h'] = ([SA_FAMILY_T],
                                             OK, 'sa_family_t size_t')

    exc['linux/nfsd/cld.h'] = (['stdint.h'],
                             OK, 'uint8_t uint16_t uint32_t uint64_t')

    exc['linux/omapfb.h'] = ([SIZE_T],
                               OK, 'size_t')

    exc['linux/openvswitch.h'] = (['stdint.h'],
                                  OK, 'size_t uint32_t uint64_t')

    exc['linux/packet_diag.h'] = (['net/if_arp.h'], OK, 'MAX_ADDR_LEN')

    exc['linux/patchkey.h'] = ([SIZE_T],
                               WARN | BLACKLIST, 'error: #error "patchkey.h included directly"')

    exc['linux/phonet.h'] = ([SOCKADDR],
                             OK, 'sa_family_t sockaddr')

    exc['linux/rds.h'] = ([SOCKADDR, 'stdint.h'],
                             OK, 'sockaddr')

    exc['linux/reiserfs_xattr.h'] = ([SIZE_T],
                                     OK, 'size_t')

    exc['linux/route.h'] = ([SOCKADDR],
                            OK, 'sockaddr')

    exc['linux/scc.h'] = (['linux/sockios.h'],
                          OK, 'SIOCDEVPRIVATE')

    exc['linux/sctp.h'] = (['stdint.h', 'sys/socket.h'], OK, 'uint32_t')

    exc['linux/signal.h'] = ([SIZE_T],
                             OK, 'size_t')

    exc['linux/sysctl.h'] = ([SIZE_T],
                             OK, 'size_t')

    exc['linux/target_core_user.h'] = (['stdint.h'],
                                       OK, 'size_t uint32_t uint64_t')

    exc['linux/vm_sockets.h'] = ([SOCKADDR],
                                 OK, 'sockaddr sa_family_t')

    exc['linux/wireless.h'] = ([SOCKADDR],
                               OK, 'sockaddr')

    exc['rdma/rdma_user_cm.h'] = (['sys/socket.h'], OK, 'sockaddr_storage')

    exc['scsi/scsi_bsg_fc.h'] = (['stdint.h'], OK, 'uint32_t')

    exc['scsi/scsi_netlink.h'] = (['stdint.h'], OK, 'uint32_t')

    exc['scsi/scsi_netlink_fc.h'] = (['stdint.h'], OK, 'uint32_t')

    exc['sound/emu10k1.h'] = (['* #define DECLARE_BITMAP(name,bits) unsigned long name[bits/8];'],
                              OK | WARN, 'DECLARE_BITMAPS - missing')

    exc['xen/gntalloc.h'] = (['stdint.h'], OK, 'uint32_t uint64_t')

    exc['xen/privcmd.h'] = ([], BLACKLIST | WARN, 'no domid_t')

    exc['asm/ucontext.h'] = ([SIZE_T, 'asm/signal.h', 'asm/sigcontext.h'],
                                     OK, 'stack_t sigcontext')

    exc['linux/hsi/cs-protocol.h'] = (['linux/time.h'], OK, 'timespec')

    exc['linux/virtio_balloon.h'] = (['linux/virtio_types.h'], OK, '__virtio16 __virtio64')

    exc['linux/gsmmux.h'] = ([SOCKADDR, 'linux/if.h'],
                             OK, 'sockaddr')

    exc['drm/virtgpu_drm.h'] = (['stdint.h'], OK, 'uint32_t uint64_t')

    exc['linux/virtio_gpu.h'] = (['stdint.h'], OK, 'uint8_t')

    exc['xen/gntdev.h'] = ([], BLACKLIST | WARN, 'no domid_t')

    exc['asm/stat.h'] = (['sys/types.h'],
                         OK, 'ino_t nlink_t mode_t uid_t gid_t off_t')

    exc['rdma/rdma_user_rxe.h'] = ([SOCKADDR, 'linux/in.h', 'linux/in6.h'],
                                   OK, 'sockaddr sockaddr_in sockaddr_in6')

    exc['sound/asoc.h'] = ([], WARN | BLACKLIST,
                           'sound/asoc.h is blacklisted in kernel 4.8.0')

    exc['xen/evtchn.h'] = ([], BLACKLIST | WARN, 'no domid_t')

    exc['linux/bpf_perf_event.h'] = ([], WARN | BLACKLIST,
                                     'struct pt_regs is undefined in userspace kernel headers')

    exc['rdma/mlx5-abi.h'] = (['linux/if_ether.h'], OK, 'ETH_ALEN')

    exc['linux/fsmap.h'] = ([SIZE_T], OK, 'size_t')

    exc['linux/kfd_ioctl.h'] = ([SIZE_T, 'stdint.h'],
                                OK, 'uint8_t uint16_t uint32_t uint64_t')

    exc['linux/rxrpc.h'] = ([SA_FAMILY_T, SIZE_T, 'linux/types.h',
                            '* typedef __u16 u16;', '* typedef __u64 u64;'],
                            OK, 'sa_family_t size_t')


#!/usr/bin/env python

from cm import register_source, Base, getLogger
from neovim.api import Nvim

logger = getLogger(__name__)

register_source(name='ncm-emoji',
        abbreviation='emoji',
        word_pattern = r':[\w+\-]*',
        cm_refresh_length=2,
        priority=8)

class Source(Base):
    def __init__(self, nvim):
        super(Source, self).__init__(nvim)

    def cm_refresh(self,info,ctx):
        test = self.nvim.call('emoji#data#dict')
        logger.info("test: " + str(test['apple']))
        matches = []
        for name, code in test.items():
            if isinstance(code, list):
                emoji = "".join(map(chr, code))
            else:
                emoji = chr(code)
            matches += [dict(word=':'+name+':', menu=emoji)]
        self.complete(info, ctx, ctx['startcol'], matches)


# 将HTMLTestRunner.py 文件移到次目录下，导unittest包
import unittest

# 2.导入HTMLTestRunner
from HTMLTestRunner import HTMLTestRunner

# 3.定义一个测试报告文件
report_file = './test_report.html'

# 4.创建套件
suite = unittest.defaultTestLoader.discover(start_dir = '.', pattern="test*.py")

# 5.生成一个runner
with open(report_file,'wb') as f:
    runner = HTMLTestRunner(f, title='测试报告', description='v1.2版本的测试报告')
    runner.run(suite)


# https://leetcode.com/problems/validate-binary-search-tree/

# Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
# Example 1:
#     2
#    / \
#   1   3
# Binary tree [2,1,3], return true.
# Example 2:
#     1
#    / \
#   2   3
# Binary tree [1,2,3], return false.
import unittest
import sys

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

def is_valid_bst(root):

    def is_valid_bst_impl(root, minimum, maximum):
        if not root:
            return True
        if not minimum < root.val < maximum:
            return False

        left_valid = is_valid_bst_impl(root.left, minimum, root.val) if root.left else True
        right_valid = is_valid_bst_impl(root.right, root.val, maximum) if root.right else True

        return left_valid and right_valid

    return is_valid_bst_impl(root, -sys.maxint, sys.maxint)

class ValidateBstTest(unittest.TestCase):

    def test_positive(self):
        root = TreeNode(10)
        root.left = TreeNode(5)
        root.right = TreeNode(15)

        self.assertTrue(is_valid_bst(root))

    def test_negative(self):
        root = TreeNode(10)
        root.left = TreeNode(15)
        root.right = TreeNode(5)

        self.assertFalse(is_valid_bst(root))

    def test_negative_with_left_tree(self):
        #     15
        #    /
        #   10
        #  /  \
        #  5  12
        #     /
        #    3 <- illegal, less than 5
        root = TreeNode(15)
        root.left = TreeNode(10)
        root.left.left = TreeNode(5)
        root.left.right = TreeNode(12)
        root.left.right.left = TreeNode(3)

        self.assertFalse(is_valid_bst(root))

    def test_negative_with_right_tree(self):
        #     15
        #    /  \
        #   10  18
        #       / \
        #      9
        #       \
        #        19 <- illegal, greater than 18
        root = TreeNode(15)
        root.left = TreeNode(10)
        root.right = TreeNode(18)
        root.right.left = TreeNode(9)
        root.right.left.right = TreeNode(19)

        self.assertFalse(is_valid_bst(root))

if __name__ == '__main__':
    unittest.main()


n = int(input())
ans = 0

for _ in range(n):
  word = input()
  flag = 1
  for i in range(len(word) - 1):
    if word[i] != word[i + 1]:
      after = word[i + 1:]
      if after.count(word[i]) > 0:
        flag = 0
        break
  if flag:
    ans += 1

print(ans)


#### Nathan Hans
#### Python challenge

#Import the required libraries

import os
import csv
from pathlib import Path

csvpath = os.path.join('../PyPoll/Resources/election_data.csv')

# Read csv file and calculate necessary information from file

with open(csvpath) as csvfile:

    # CSV reader specifies delimiter and variable that holds contents
    csvreader = csv.reader(csvfile, delimiter=',')

    #print(csvreader)

    # Read the header row first (skip this step if there is no header)
    csv_header = next(csvreader)
    print(f"CSV Header: {csv_header}")

    Total_votes = 0
    Charles_votes = 0
    Diana_votes = 0
    Raymon_votes = 0
    Other_votes = 0
    # Read each row of data after the header
    for row in csvreader:
        #find total votes
        Total_votes = Total_votes+1
        #conditional to determine votes by candidate
        if row[2] == 'Charles Casper Stockham':
            Charles_votes = Charles_votes + 1
        elif row[2] == 'Diana DeGette':
            Diana_votes = Diana_votes + 1
        elif row[2] == 'Raymon Anthony Doane':
            Raymon_votes = Raymon_votes + 1
        else:
            Other_votes = Other_votes + 1

        #calculated percentages of total
        Charles_pct = Charles_votes/Total_votes
        Diana_pct = Diana_votes/Total_votes
        Raymon_pct = Raymon_votes/Total_votes

        if Charles_votes > Diana_votes and Charles_votes > Raymon_votes:
            winner = "Charles Casper Stockham"
        elif Diana_votes > Charles_votes and Diana_votes > Raymon_votes:
            winner = "Diana DeGette"
        else:
            winner = "Raymon Anthony Doane"

    #print requirements
    print("Election Results \n")
    print("---------------")
    print(f'Total Votes: {Total_votes}')
    print(f'Charles Casper Stockham: ' +  "{:.3%}".format(Charles_pct) + f' ({Charles_votes})')
    print(f'Diana DeGette: ' +  "{:.3%}".format(Diana_pct) + f' ({Diana_votes})')
    print(f'Raymon Anthony Doane: ' +  "{:.3%}".format(Raymon_pct) + f' ({Raymon_votes})')
    print("---------------")
    print(f'Winner: {winner}')

# Specify the file to write to
output_path = os.path.join('output', 'new.csv')

     # Open the file using "write" mode. Specify the variable to hold the contents.  Had to add newline = '' to avoid skipped rows
with open(output_path, 'w', newline = '') as csvfile:

    # Initialize csv.writer
    csvwriter = csv.writer(csvfile, delimiter=',')

    # Write the first row (column headers)
    csvwriter.writerow(['Total Votes', 'Charles Votes', 'Charles Percent','Diana Votes'
                        ,'Diana Percentage','Raymon Votes','Raymon Percentage','Winner'])

    # Write the second row
    csvwriter.writerow([Total_votes,Charles_votes,Charles_pct, Diana_votes, Diana_pct,Raymon_votes,Raymon_pct, winner])


from itertools import permutations

if __name__ == '__main__':
    S, k = input().split()
    S = str(S).upper()
    k = int(k)

# Create the list of permutations
perms = list(permutations(S, k))

# Extract the characters from the permutations into a string
perm_strings = []
for perm in perms:
    perm_string = ''
    for char in perm:
        perm_string = perm_string + char
    perm_strings.append(perm_string)

# Sort the list of strings and print each string
perm_strings.sort()
[print(string) for string in perm_strings]


from functools import singledispatchmethod

from abc import ABC

class Edu(ABC):
    ...

class Duduzinho(Edu):
    ...

class Pessoa:
    def __init__(self) -> None:
        self._status = "ok"

    @singledispatchmethod
    def chamei(self, p):
        raise NotImplementedError("Opa, caiu na genérica")

    @chamei.register
    def _(self, p: Edu):
        print(f"{self._status}: Caí na lógica do Edu")

p = Pessoa()


import sys
import itertools
from operator import itemgetter

input_test = """x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504"""

def parse_coord(c):
    name, range_ = c.split('=')
    range_ = tuple(map(int, range_.split('..')))

    return (name, range_)

def parse(input_):
    return [tuple(map(
        itemgetter(1),
        sorted(map(parse_coord, pair.split(', ')), key=itemgetter(0)),
    )) for pair in input_.rstrip('\n').split('\n')]

def test_parse():
    assert parse(input_test) == [
        ((495,), (2, 7)),
        ((495, 501), (7,)),
        ((501,), (3, 7)),
        ((498,), (2, 4)),
        ((506,), (1, 2)),
        ((498,), (10, 13)),
        ((504,), (10, 13)),
        ((498, 504), (13,)),
    ]

def print_map(x, y, X, Y, clay, water, rest):
    print()
    for j in range(min(y, 0), Y):
        for i in range(x, X):
            pos = (i, j)

            e = '.'

            if pos in clay:
                e = '#'
            elif pos in water:
                e = '+' if j == 0 else '|'
            elif pos in rest:
                e = '~'

            print(e, end='')
        print()

def flow(coordinates):
    x, y = sys.maxsize, sys.maxsize
    X, Y = 0, 0
    clay = set()
    water = set()
    rest = set()

    for rx, ry in coordinates:
        for i in range(rx[0], rx[-1] + 1):
            for j in range(ry[0], ry[-1] + 1):
                x = min(x, i - 1)
                X = max(X, i + 2)
                y = min(y, j)
                Y = max(Y, j + 1)
                clay.add((i, j))

    new_water = {(500, 0)}
    for iteration in itertools.count(1):
        # print('iteration:', iteration)
        # print_map(x, y, X, Y, clay, water, rest)

        new_coord = list(new_water)
        new_water = set()

        # print('will look into:', new_coord)

        # flow existing water
        for wx, wy in new_coord:
            if wy + 1 >= Y:
                continue

            below = (wx, wy + 1)
            left = (wx - 1, wy)
            right = (wx + 1, wy)

            if below in clay or below in rest:
                # propagate on the sides
                if left not in clay and left not in water and left not in rest:
                    new_water.add(left)

                if right not in clay and right not in water and right not in rest:
                    new_water.add(right)

                continue

            # else below should be water or sand
            if below in water:
                continue

            new_water.add(below)

        # print('new_water:', new_water)
        if new_water:
            water |= new_water
            # try to flow the water as much as we can
            continue

        # if no new water, try to see if we have rest water candidates
        new_rest = set()
        # look for existing flow that would turn into rest
        for pos in list(water):
            if pos in rest or pos in new_rest:
                # already transformed
                continue

            wx, wy = pos

            left = None
            for i in itertools.count(wx - 1, -1):
                if (i, wy) in water:
                    continue
                if (i, wy) in clay:
                    left = i + 1
                    break
                break

            if left is None:
                continue

            right = None
            for i in itertools.count(wx + 1, 1):
                if (i, wy) in water:
                    continue
                if (i, wy) in clay:
                    right = i
                    break
                break

            if right is None:
                continue

            new_rest |= {(i, wy) for i in range(left, right)}

            # reevaluate previous water points
            new_water |= {(i, j) for i, j in water if left <= i < right and j == wy - 1}

        if not new_rest:
            break

        rest |= new_rest
        water -= new_rest

    return (
        len(rest),
        len(rest) + sum(1 for _, j in water if y <= j < Y),
    )

def test_flow():
    assert flow(parse(input_test)) == (29, 57)

if __name__ == '__main__':
    input_ = parse(open('input.txt').read())
    part2, part1 = flow(input_)
    print('part1:', part1)
    print('part2:', part2)


from django.urls import path
from .views import *

urlpatterns = [
	path('',index,name='index'),
	path('contactus/',contact,name='contact'),
	path('stock/',stock,name='inventory'),
	path('stockdb/',dbstock,name='db stock'),
	path('home/',home,name='home'),
]


import sys

# checks for correctness of argument
if len(sys.argv) != 2:
    print("Usage: python " + sys.argv[0] + " <first integer>")
    sys.exit()

n = int(sys.argv[1])

if n <= 0:
    print("argument should be a positive integer")
    sys.exit()

# set the first number to 0 and second to 1
first = 0
second = 1
if n == 1:
    print(first)
elif n == 2:
    print(second)
else:
    for i in range(n-1):
        current_number = first + second # add the last two numbers
        # update the numbers
        first = second
        second = current_number
    print(current_number)


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

# In[1]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import re
import itertools
import threading
import time
import sys

# In[2]:

cities = ['Dublin','Amsterdam','Madrid','Paris','Berlin','Milan','London','Barcelona','Frankfurt','Lisbon']
roles_list =['Junior Data Analyst','Junior Web Developer']
#Glassdoor
da_table=pd.read_csv('glassdoor_role_table_unique2roles.csv')
#Numbeo
numbeo_summary_table = pd.read_csv('numbeo_table_summary.csv')
numbeo_item_table =  pd.read_csv('numbeo_table_priceitems.csv')
numbeo_item_table.rename(columns = {'Country':'City'}, inplace = True)
#Nomad list
nomad_list =pd.read_csv('df_nomad_list.csv')
#Columns adjugement
columnsok = []
for x in nomad_list.columns[1:]:
    b = re.findall(r'(?<=\s).*',x)
    columnsok.append(b)
columnsok
col = []

for x in range(0,80):
     col.append(columnsok[x][0])
col.insert(0,"City")
col
nomad_list.set_axis(col,axis=1,inplace=True)
#Functions
def city_validation(city_val):
    #validates city in list
    while  True:
        if city_val not in cities:
            print("Sorry, we dont have information for that city, try again:")
            city_val = input('Introduce city: ').strip().capitalize()
            True
        else:
            break
    return city_val
def role_validation(role_val):
    #validates city in list
    while  True:
        if role_val not in roles_list:
            print("Sorry, we dont have information for that role, try again:")
            role_val = input('Introduce the role exactly as listed above: ').strip()
            True
        else:
            break
    return role_val

# In[3]:

#MAin program

print('\033[1m','....................................Welcome to Choose&Move....................................''\033[0m')
#Scraping proccess simulation
#TBD
done = False
#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rScraping last updates     ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    print('\rDone:Last update:Updated 7 May 2022      ')

t = threading.Thread(target=animate)
t.start()

#long process here
time.sleep(1)
done = True
print("\n")

#long process here
time.sleep(2)
done = True
#program
print('    ')
print('\033[94m','Information available for:','\033[0m')
[print('\033[0;32m',city,'\033[0m') for city in cities]
print('    ')
#city_orig = input('Introduce current city: ').capitalize().strip()
#city_dest = input('Introduce city to compare: ').capitalize().strip()
city_orig = city_validation(input('Introduce current city: ').strip().capitalize())
city_dest = city_validation(input('Introduce city to compare: ').strip().capitalize())

print('    ')
print('\033[0;34m','Information available for:','\033[0m')
#print('\033[0;32m','Junior Data Analyst''\033[0m')
#print('\033[0;32m','Junior Web Developer''\033[0m')
print('    ')
[print('\033[0;32m',role,'\033[0m') for role in roles_list ]
print('    ')
#role= input('Role position to analyze: ',).strip()
role= role_validation(input('Role position to analyze: ',).strip())
print('    ')
#filter table by position and role
df_1 = da_table[(da_table['city'] == city_orig) | (da_table['city'] == city_dest)]
df_1= df_1[df_1.position.str.contains(f'{role}', flags = re.IGNORECASE, regex = True, na = False)].reset_index()

print('\033[0;34m' ,'Salary reference:','\033[0m')

#Avg salary origin  and to comparecity
avg_org_city = df_1["avgbasepay"][df_1['city'] == city_orig].reset_index()
avg_org_city = avg_org_city['avgbasepay'][0]
avg_org_city
avg_dest_city = df_1["avgbasepay"][df_1['city'] == city_dest].reset_index()
avg_dest_city =avg_dest_city['avgbasepay'][0]
avg_dest_city

print(f'Average salary in {city_orig} : {avg_org_city} | {city_dest} : {avg_dest_city}  ')
print('    ')
print('\033[0;34m' ,'Range Salaries:','\033[0m')
#Range Salaries table
df_1.rename(columns = {'city':'City', 'minpay':'Low','avgpay':'Average', 'maxpay':'High'}, inplace = True)
#Changing colum names
#Ldisplay(df_1[['City','Low','Average','High']])
print(df_1[['City','Low','Average','High']])
#Cost of life part
print('    ')
print('\033[0;34m' ,'Cost of Life:','\033[0m')

#Estimated monthly costs single person without rent
df_2 = numbeo_summary_table[(numbeo_summary_table['City'] == city_orig) | (numbeo_summary_table['City'] == city_dest)].reset_index()
cost_cityorig = df_2["A single person estimated monthly costs are without rent."][df_2['City'] == city_orig].reset_index()
cost_cityorig = cost_cityorig["A single person estimated monthly costs are without rent."][0]
cost_cityorig
#cost_cityorig
cost_citydest = df_2["A single person estimated monthly costs are without rent."][df_2['City'] == city_dest].reset_index()
cost_citydest = cost_citydest["A single person estimated monthly costs are without rent."][0]
cost_citydest
#cost_citydest

#Apartment (1 bedroom) in City Centre
df_3 = numbeo_item_table[(numbeo_item_table['City'] == city_orig) | (numbeo_item_table['City'] == city_dest)].reset_index()
apartment1bed_cityorig = df_3['Apartment (1 bedroom) in City Centre '][df_3['City'] == city_orig].reset_index()
apartment1bed_cityorig = apartment1bed_cityorig['Apartment (1 bedroom) in City Centre '][0]
apartment1bed_cityorig
#apartment1bed_cityorig
apartment1bed_citydest = df_3['Apartment (1 bedroom) in City Centre '][df_3['City'] == city_dest].reset_index()
apartment1bed_citydest =apartment1bed_citydest['Apartment (1 bedroom) in City Centre '][0]
apartment1bed_citydest
#apartment1bed_citydest

#Apartment (1 bedroom) in City Centre
df_4 = numbeo_item_table[(numbeo_item_table['City'] == city_orig) | (numbeo_item_table['City'] == city_dest)].reset_index()
sal_cityorig = df_4['Average Monthly Net Salary (After Tax) '][df_4['City'] == city_orig].reset_index()
sal_cityorig =sal_cityorig['Average Monthly Net Salary (After Tax) '][0]
#sal_cityorig
sal_citydest = df_4['Average Monthly Net Salary (After Tax) '][df_4['City'] == city_dest].reset_index()
sal_citydest = sal_citydest['Average Monthly Net Salary (After Tax) '][0]
sal_citydest
#sal_citydest

print(f'Average Monthly Net Salary (After Tax):  {city_orig}:','€', sal_cityorig,' | ',f'{city_dest}:','€',sal_citydest)
print(f'Estimated monthly costs single person without rent:  {city_orig}:','€', cost_cityorig,' | ',f'{city_dest}:','€',cost_citydest)
print(f'Apartment (1 bedroom) in City Centre:  {city_orig}:','€', apartment1bed_cityorig,' | ',f'{city_dest}:','€',apartment1bed_citydest)
print(' ')

print('\033[0;34m' ,'Quality of life:','\033[0m')

df_5 = nomad_list[(nomad_list['City'] == city_orig) | (nomad_list['City'] == city_dest)].reset_index()
#NightLife
nightlife_dest =df_5['Nightlife'][df_5['City'] == city_dest].reset_index()
nightlife_dest =nightlife_dest['Nightlife'][0]
nightlife_dest

nightlife_org= df_5['Nightlife'][df_5['City'] == city_orig].reset_index()
nightlife_org=nightlife_org['Nightlife'][0]
nightlife_org
#Fun
fun_dest = df_5['Fun'][df_5['City'] == city_dest].reset_index()
fun_dest =fun_dest['Fun'][0]
fun_dest
fun_org= df_5['Fun'][df_5['City'] == city_orig].reset_index()
fun_org=fun_org['Fun'][0]
fun_org

#Fender ratio
gender_dest = df_5['Gender ratio (overall)'][df_5['City'] == city_dest].reset_index()
gender_dest=gender_dest['Gender ratio (overall)'][0]
gender_dest
gender_org= df_5['Gender ratio (overall)'][df_5['City'] == city_orig].reset_index()
gender_org=gender_org['Gender ratio (overall)'][0]

print(f'Night Life in {city_orig}:',nightlife_org,f' in {city_dest}:',nightlife_dest)
print(f'Fun in {city_orig}:',fun_org,f' in {city_dest}:',fun_dest)
print(f'Gender Ratio in {city_orig}:',gender_org,f' in {city_dest}:',gender_dest)

# In[ ]:

# In[ ]:


from django.shortcuts import render

from django.shortcuts import render, redirect
from customer.forms import CustomerForm
from customer.models import Customer

def cust(request):
    if request.method == "POST":
        form = CustomerForm(request.POST)
        if form.is_valid():
            cid = form.cleaned_data['cid']
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            contact = form.cleaned_data['contact']
            form.save()
            return redirect('show')
    else:
        form = CustomerForm()
    return render(request,'index.html',{'form':form})
def show(request):
    customers = Customer.objects.all()
    return render(request,"show.html",{'customers':customers})
def edit(request, id):
    customer = Customer.objects.get(id=cid)
    return render(request,'edit.html', {'customer':customer})
def update(request, id):
    customer = Customer.objects.get(id=cid)
    form = CustomersForm(request.POST, instance = customer)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'customer': customer})
def destroy(request, id):
    try:
        customer = Customer.objects.get(id=cid)
    except Customer.DoesNotExist:
        return redirect('customer_list')

    customer.delete()
    return redirect('customer_list')


input = __import__('sys').stdin.readline
n,k = map(int,input().split())
bag = [[0,0]]+[list(map(int,input().split())) for _ in range(n)]
knapsack = [[0 for _ in range(k+1)] for _ in range(n+1)]
for i in range(1,n+1):
    for j in range(1,k+1):
        if bag[i][0]>j:
            knapsack[i][j] = knapsack[i-1][j]
        else:
            knapsack[i][j] = max(knapsack[i-1][j], knapsack[i-1][j-bag[i][0]] + bag[i][1])
print(knapsack[n][-1])


from flask import Flask
import datetime

app = Flask(__name__)

@app.route('/')
def today_datetime():
    now = datetime.datetime.now()
    #today = datetime.date.today()
    now = now.strftime("%Y年%m月%d日 %H時%M分%S秒")
    return f"Hello, 現在の日時は {now}です。 How are you?"

@app.route('/app')
def hoge_world():
    return 'Hello!! App'

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


# Exercício Python 44: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
# – à vista dinheiro/cheque: 10% de desconto
# – à vista no cartão: 5% de desconto
# – em até 2x no cartão: preço formal
# – 3x ou mais no cartão: 20% de juros

preco = float(input('Preço do produto R$:'))

print('''Forma de pagamento:
1 - à vista dinheiro/cheque: 10% de desconto
2 - à vista no cartão: 5% de desconto
3 - em até 2x no cartão: preço formal
4 - 3x ou mais no cartão: 20% de juros''')
escolha = str(input('Digite sua opção:')).strip()

if escolha == '1':
    desconto = preco - (preco * 10 / 100)
    print(f'Preço do produto com 10% de desconto R$:{desconto:.2f} reais.')
elif escolha == '2':
    desconto = preco - (preco * 5 / 100)
    print(f'Preço do produto com 5% de desconto R$:{desconto:.2f} reais,')
elif escolha == '3':
    print(f'2 parcelas de R${preco / 2:.2f} reais.')
elif escolha == '4':
    parcelas = int(input('Quantas parcelas?'))
    juros = preco + (preco * 20 / 100)
    print(f'{parcelas} parcelas de R${juros / parcelas:.2f} reais.')
else:
    print('Opção invalida!')

Mundo 2/1 - Condições em Python (if..elif)/Ex044.py


import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import imdb
from keras import models, layers
from keras import optimizers, losses, metrics

(train_data, train_labels),(test_data, test_labels) = imdb.load_data(num_words=10000) # 자주 나타나는 단어 1만개만 사용

# 정수 시퀀스를 이진 행렬로 인코딩하기
def vectorize_sequence(sequences, dimension=10000):
	results = np.zeros((len(sequences), dimension))

	for i, sequences in enumerate(sequences):
		results[i, sequences] = 1
	return results

# vector 변환
x_train = vectorize_sequence(train_data)
x_test = vectorize_sequence(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
#print(x_train[0])
#print(y_train[0])

# validation set
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]

# model define
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(16, activation='relu')) # layer 추가
model.add(layers.Dense(1, activation='sigmoid'))

# model compile
model.compile(optimizer='rmsprop',
			loss = 'mse',			# mean squared error
			metrics=['accuracy'])
# fit
model.fit(x_train, y_train, epochs=4, batch_size=512) # epochs을 4로 제한

# test set에 평가
results = model.evaluate(x_test, y_test)
print(results)	# [0.2945874176502228, 0.8832]

# predict
pred = model.predict(x_test)
#print(pred)


from binaryninja import *
from . import operations
from . import config
import logging

class MLILResults():

    def get_stack_trace(self):

        stack_trace  = "[PATH]"
        stack_trace += "".join(["->" + func for func in config.stack])
        return stack_trace

    def check_results(self, expr, ssa_var):

        for fields in MediumLevelILInstruction.ILOperations[expr.operation]:
            x, y = fields
            if y == "expr":
                self.check_results(getattr(expr, x), ssa_var)

        if expr in self.results:
            return

        instr = self.function_mlilssa[expr.instr_index]

        if expr.operation == MediumLevelILOperation.MLIL_STORE_SSA and ssa_var in expr.dest.vars_read:
            logging.info("Potential OOB write @ 0x%lx %s %s", expr.address, instr, self.get_stack_trace())
            self.results.append(expr)
            config.vuln = True

        elif expr.operation == MediumLevelILOperation.MLIL_LOAD_SSA and ssa_var in expr.vars_read and instr.operation not in operations.MLIL_CALLS:
            logging.info("Potential OOB read @ 0x%lx %s %s", expr.address, instr, self.get_stack_trace())
            self.results.append(expr)
            config.vuln = True

        elif expr.operation == MediumLevelILOperation.MLIL_IF and self.check_loop_operation(expr):
            if self.check_x86_reps(expr):
                asm = self.bv.get_disassembly(expr.address)
                logging.info("Potential controlled size in x86 reps @ 0x%lx %s [%s]", expr.address, asm, self.get_stack_trace())
            else:
                instr, hlil_address = self.loops[expr.address]
                logging.info("Potential controlled condition in loop @ 0x%lx %s %s", hlil_address, instr, self.get_stack_trace())

            self.results.append(expr)
            config.vuln = True

        elif expr.operation in operations.MLIL_CALLS:
            if expr.dest.operation == MediumLevelILOperation.MLIL_CONST_PTR:
                if expr in self.callee:
                    self.callee[expr].append(ssa_var)
                else:
                    self.callee[expr] = [ssa_var]
            elif expr.dest.operation == MediumLevelILOperation.MLIL_LOAD_SSA:
                if ssa_var in expr.dest.vars_read:
                    logging.info("Potential controlled indirect call @ 0x%lx %s %s", expr.address, instr, self.get_stack_trace())
                    self.results.append(expr)
                    config.vuln = True

    def log_untrusted_ptr(self, expr, dest):

        # Log tainted pointer loads if the destination var type confidence is MAX(255).
        if (dest.var.type.type_class == TypeClass.PointerTypeClass
            and dest.var.type.confidence == 255 and expr.src.operation == MediumLevelILOperation.MLIL_LOAD_SSA):

            instr = self.function_mlilssa[expr.instr_index]
            logging.info("Potential untrusted pointer load @ 0x%lx %s %s", expr.address, instr, self.get_stack_trace())
            config.vuln = True

    def get_var_for_arg(self, expr, arg):

        params = expr.params
        argno = lambda _arg: int(_arg.split("arg").pop())

        if argno(arg) < len(params):
            param = params[argno(arg)]
            if param.operation in operations.MLIL_GET_VARS:
                return param.vars_read[0]

    def visit_function_hooks(self, expr, func, tainted_vars):

        args = config.function_hooks[func]
        if not args:
            return

        for arg in args:
            ssa_var = self.get_var_for_arg(expr, arg)
            if ssa_var in tainted_vars:
                logging.info("Potential controlled args in call to %s @ 0x%lx %s %s", func, expr.address, expr, self.get_stack_trace())
                config.vuln = True
                break

    def get_args_to_pass(self, expr, tainted_vars):
        params = expr.params
        args = dict()

        if not params:
            return args

        arg_for_index = lambda x: "arg" + str(x + 1)

        for idx, param in enumerate(params):
            if param.operation in operations.MLIL_GET_VARS:
                param_var = param.vars_read[0]
                if param_var in tainted_vars:
                    args[arg_for_index(idx)] = self.tainted_vars[param_var]

        return args


import enum
from typing import *

from pydantic import BaseModel, Field

from normalize.utils.clean import clean_whitespace
from normalize.utils.clean import convert_ch_symbols_to_en

class DegreeName(enum.Enum):
    PRIMARY = '小学'
    JUNIOR_HIGH = '初中'
    HIGH = '高中'
    SECONDARY = '中专'
    COLLEGE = '大专'
    SPECIALIST = '专科'
    JUNIOR_COLLEGE = '专升本'
    BACHELOR = '本科'
    ONJOB_MASTER = '在职研究生'
    MASTER = '硕士'
    SPECIAL_MASTER = '专业学位硕士'
    ACADEMIC_MASTER = '学术型硕士'
    ONJOB_DOCTOR = '在职博士生'
    DOCTOR = '博士'
    SPECIAL_DOCTOR = '专业学位博士'
    ACADEMIC_DOCTOR = '学术型博士'
    POSTDOCTORAL = '博士后'
    MBA = 'MBA'
    EMBA = 'EMBA'

class Degree(BaseModel):
    name: str = Field(default=..., title='学历')
    rank: Optional[int] = Field(default=None, title='学历rank，越大学历越高')

class DegreeRange(BaseModel):
    gte: Optional[str] = Field(default=None, title='学历下限')
    lte: Optional[str] = Field(default=None, title='学历上限')

degree_to_score = {
    DegreeName.PRIMARY: -4,
    DegreeName.JUNIOR_HIGH: -2,
    DegreeName.HIGH: 0,
    DegreeName.SECONDARY: -1,
    DegreeName.COLLEGE: 8,
    DegreeName.SPECIALIST: 8,
    DegreeName.JUNIOR_COLLEGE: 10,
    DegreeName.BACHELOR: 16,
    DegreeName.ONJOB_MASTER: 20,
    DegreeName.MASTER: 24,
    DegreeName.SPECIAL_MASTER: 24,
    DegreeName.ACADEMIC_MASTER: 28,
    DegreeName.ONJOB_DOCTOR: 30,
    DegreeName.DOCTOR: 32,
    DegreeName.SPECIAL_DOCTOR: 32,
    DegreeName.ACADEMIC_DOCTOR: 36,
    DegreeName.POSTDOCTORAL: 40,
    DegreeName.MBA: 29,
    DegreeName.EMBA: 30
}

degree_to_keywords = [(DegreeName.PRIMARY, ['小学']),
                      (DegreeName.JUNIOR_HIGH, ['初中']),
                      (DegreeName.HIGH, ['高中']),
                      (DegreeName.SECONDARY, ['中专']),
                      (DegreeName.COLLEGE, ['大专']),
                      (DegreeName.SPECIALIST, ['专科']),
                      (DegreeName.JUNIOR_COLLEGE, ['专升本', '成人本科', '成人学士']),
                      (DegreeName.BACHELOR, ['本科', '学士', '大学']),
                      (DegreeName.ONJOB_MASTER, ['在职研究生', '在职硕士', '在职工程硕士']),
                      (DegreeName.MASTER, ['硕士', '研究生']),
                      (DegreeName.SPECIAL_MASTER, ['专业学位硕士', '专硕', '专业硕士', '专业型硕士']),
                      (DegreeName.ACADEMIC_MASTER, ['学术型硕士']),
                      (DegreeName.ONJOB_DOCTOR, ['在职博士']),
                      (DegreeName.DOCTOR, ['博士']),
                      (DegreeName.SPECIAL_DOCTOR, ['专业学位博士', '专业型博士']),
                      (DegreeName.ACADEMIC_DOCTOR, ['学术型博士']),
                      (DegreeName.POSTDOCTORAL, ['博士后']),
                      (DegreeName.MBA, ['mba']),
                      (DegreeName.EMBA, ['emba']),
                      ][::-1]

mapper = {
    '不限': -4,
    '初中': -2,
    '中专': -1,
    '高中': 0,
    '专科': 8,
    '大专': 8,
    '统招': 16,
    '本科': 16,
    '大学': 16,
    '硕士': 24,
    '专业学位硕士': 24,
    '学术型硕士': 28,
    'mba': 29,
    'emba': 30,
    '博士': 32,
    '专业学位博士': 32,
    '学术型博士': 36,
    '博士后': 40,
}

symbol_split_deg_range_most_possible = [
    "~", ",", "-", ".", "至", "到", "下限", "|", "/", "&", "#", "以上", "以下", "下限"
]

def normalize_value(deg_str: str) -> str:
    """
    分析学历字段，返回Degree，Degree.rank越大学历越高
    如果未解析出学历，返回None
    :param deg_str: 任意学历字符串
    :return: Optional[Degree]
    """
    cleaned_deg_str = clean_whitespace(deg_str).lower()
    for degree_name, keys in degree_to_keywords:
        for k in keys:
            if k in cleaned_deg_str:
                return degree_name.value
                # return Degree(name=degree_name.value, rank=degree_to_score[degree_name])
    return ''

def normalize(deg_range_str: str) -> dict:
    deg_range_str_converted = convert_ch_symbols_to_en(deg_range_str)
    if not deg_range_str_converted:
        return {}
    for possible_symbol in symbol_split_deg_range_most_possible:
        deg_range_str_converted_split = deg_range_str_converted.split(possible_symbol)
        if len(deg_range_str_converted_split) >= 2:
            if "以上" in deg_range_str_converted or "大于" in deg_range_str_converted or "高于" in deg_range_str_converted or \
                    "下限" in deg_range_str_converted:
                degree_lower_limit = normalize_value(deg_range_str_converted_split[0])
                return {'gte': degree_lower_limit}
            elif "以下" in deg_range_str_converted or "小于" in deg_range_str_converted or "低于" in deg_range_str_converted or \
                    "上限" in deg_range_str_converted:
                degree_upper_limit = normalize_value(deg_range_str_converted_split[0])
                return {'lte': degree_upper_limit}
            else:
                g, l = sorted(list(map(normalize_value, deg_range_str_converted_split)), key=lambda x: x.rank)
                return {'gte': g, 'lte': l}
    normalized_result = normalize_value(deg_range_str)
    if not normalized_result:
        return {}
    return {'value': normalized_result}

if __name__ == '__main__':
    print((normalize("本科")))


import sys
from collections import defaultdict
import re

def stripped_lines(filename):
    with open(filename) as f:
        for line in f.readlines():
            yield line.strip()

def parse_file(filename):
    lines = list(stripped_lines(filename))
    state = 0
    rules = defaultdict(list)
    messages = []
    for line in lines:
        if line == '':
            state += 1
        elif state == 0:
            kv = line.split(':')
            key = int(kv[0])
            values = kv[1]
            if '"' in values:
                start = values.find('"')
                end = values.rfind('"')
                rules[key].append(values[start + 1:end])
            else:
                for group in values.split('|'):
                    refs = [int(ref) for ref in group.split(' ') if ref != '']
                    rules[key].append(refs)
        elif state == 1:
            messages.append(line)
    return rules, messages

def build_regex(rules, key, part_num):
    groups = rules[key]
    if isinstance(groups[0], str):
        return groups[0]

    if part_num == 2 and (key == 8 or key == 11):
        r42 = build_regex(rules, 42, part_num)
        r31 = build_regex(rules, 31, part_num)
        if key == 8:
            return '(' + r42 + '+)'
        elif key == 11:
            return '(' + '|'.join([r42 + '{' + str(i) + '}' + r31 + '{' + str(i) + '}' for i in range(1, 5)]) + ')'

    result = []
    for group in groups:
        group_regex = ''.join((build_regex(rules, key, part_num) for key in group))
        result.append(group_regex)
    pre = '^' if key == 0 else '('
    post = '$' if key == 0 else ')'
    return pre + '|'.join(result) + post

def run(inputs, part_num):
    rules, messages = inputs
    rx_str = build_regex(rules, 0, part_num)
    rx = re.compile(rx_str)
    num_valid = 0
    for m in messages:
        matches = rx.match(m)
        if matches is not None:
            num_valid += 1
    return num_valid

def main(args):
    inputs = parse_file(args[1])
    p1_ans = run(inputs, 1)
    print(f'part one: {p1_ans}')
    p2_ans = run(inputs, 2)
    print(f'part two: {p2_ans}')
    # part one: 132
    # part two: 306

if __name__ == '__main__':
    main(sys.argv)


run0 = False
run1 = False
run2 = False
run3 = False
snakeAgentOn = False
bbAgentOn = False
run4 = True

while True:

    import pygame
    import sys
    import math
    import random
    import torch
    import torch.nn as nn
    import torch.optim as optim
    import torch.nn.functional as F
    import os
    import numpy as np
    import matplotlib.pyplot as plt
    from IPython import display

    ######################################
    # Section for any and all cited code:
    #           cited as per MIT style rules, cited inline as Cit01
    # Citation 01:
    #       https://youtu.be/L8ypSXwyBds retrieved 4/22/2023
    #
    #       Some of the functions: plot, QTrainerSnake, LinearQNet
    #       Some of the run==0 and run==2 While loops
    #
    #           Despite this citation, a fair bit of what is cited is standard as
    #           per pytorch library documentation, such as remember, the memory training and some
    #           other things not listed as cited inline.
    #
    #       End of Citation 01
    ######################################

    # initialize pygame
    pygame.init()

    # defining global variables
    SW, SH = 800, 800
    mainFont = pygame.font.SysFont("calibri", 40)
    snakeButtonText = mainFont.render("Snake!", True, "white")
    bbButtonText = mainFont.render("Brick Breaker", True, "white")
    snakeAIButtonText = mainFont.render("Snake AI", True, "white")
    bbAIButtonText = mainFont.render("Brick Breaker AI", True, "white")

    gameStatePause = False

    # creating window
    screen = pygame.display.set_mode((SW, SH))
    pygame.display.set_caption("Main Menu")

    # functions
    def menuText(text, font, color, x, y):
        img = font.render(text, True, color)
        screen.blit(img, (x, y))

    #classes
    class mainMenuButton:
        def __init__(self, buttonText, x, y):
            self.buttonText = buttonText
            self.rect = self.buttonText.get_rect(center=(x, y))

        def draw(self):
            global run0
            global run1
            global run2
            global run3
            global run4
            # get mouse position
            pos = pygame.mouse.get_pos()

            #check mouseover and click
            if self.rect.collidepoint(pos):
                if pygame.mouse.get_pressed()[0]:
                    if self.buttonText == snakeButtonText:
                        run0 = True
                    elif self.buttonText == bbButtonText:
                        run1 = True
                    elif self.buttonText == snakeAIButtonText:
                        run2 = True
                    elif self.buttonText == bbAIButtonText:
                        run3 = True

            screen.blit(self.buttonText, self.rect)

     #class pauseMenuButton():
     #   def __init__(self, buttonText, buttonFunction, x, y):
     #       self.buttonText = buttonText
     #       self.buttonFile = buttonFile
     #       self.rect =

     #objects

    snakeButton = mainMenuButton(snakeButtonText, 75, 450)
    bbButton = mainMenuButton(bbButtonText, 125, 500)
    snakeAIButton = mainMenuButton(snakeAIButtonText, 88, 550)
    bbAIButton = mainMenuButton(bbAIButtonText, 146, 600)

    plt.ion()

    def plot(scores, meanScores):
        display.clear_output(wait=True)
        display.display(plt.gcf())
        plt.clf()
        plt.title('Training...')  # Cit01
        plt.xlabel('Number of Games')  # Cit01
        plt.ylabel('Score')  # Cit01
        plt.plot(scores)
        plt.plot(meanScores)
        plt.ylim(ymin=0)
        plt.text(len(scores) - 1, scores[-1], str(scores[-1]))
        plt.text(len(meanScores) - 1, meanScores[-1], str(meanScores[-1]))
        plt.show(block=False)
        plt.pause(.1)

    class snakeLinearQNet(nn.Module):  # Cit01, but also largely standard documentation
        def __init__(self, inputSize, hiddenSize, outputSize):
            super().__init__()
            self.linear1 = nn.Linear(inputSize, hiddenSize)
            self.linear2 = nn.Linear(hiddenSize, outputSize)

        def forward(self, x):
            x = F.relu(self.linear1(x))
            x = self.linear2(x)
            return x

        def save(self, fileName="model.pth"):
            modelFolderPath = "./model"
            if not os.path.exists(modelFolderPath):
                os.makedirs(modelFolderPath)

            fileName = os.path.join(modelFolderPath, fileName)
            torch.save(self.state_dict(), fileName)

    class QTrainerSnake:
        def __init__(self, model, lr, gamma):
            self.lr = lr
            self.gamma = gamma
            self.model = model
            self.optimizer = optim.Adam(model.parameters(), lr=self.lr)
            self.criterion = nn.MSELoss()

        def trainStep(self, state, action, reward, stateNext, gameOver):
            state = torch.tensor(state, dtype=torch.float)
            stateNext = torch.tensor(stateNext, dtype=torch.float)
            action = torch.tensor(action, dtype=torch.long)
            reward = torch.tensor(reward, dtype=torch.float)
            # (n, x)

            if len(state.shape) == 1: # Cit01
                    # (1, x)
                state = torch.unsqueeze(state, 0)
                stateNext = torch.unsqueeze(stateNext, 0)
                action = torch.unsqueeze(action, 0)
                reward = torch.unsqueeze(reward, 0)
                gameOver = (gameOver, )

            # 1: predicted Q values in current state
            pred = self.model(state)

            target = pred.clone()
            for idx in range(len(gameOver)): # Cit01
                QNew = reward[idx]
                if not gameOver[idx]:
                    QNew = reward[idx] + self.gamma * torch.max(self.model(stateNext[idx]))

                target[idx][torch.argmax(action).item()] = QNew

            #2: QNew = r + gamma * max(next predicted q value), only if not gameOver
            #pred.clone()
            #preds[argmax(action)] = QNew
            self.optimizer.zero_grad()
            loss = self.criterion(target, pred)
            loss.backward()

            self.optimizer.step()

    while run0 == True:
        import pygame
        import random
        from enum import Enum
        from collections import namedtuple

        pygame.init()
        font = pygame.font.SysFont('calibri', 25)

        class Direction(Enum):
            RIGHT = 1
            LEFT = 2
            UP = 3
            DOWN = 4

        Point = namedtuple('Point', 'x, y')

        # rgb colors
        white = (255, 255, 255)
        red = (200, 0, 0)
        blue1 = (0, 0, 255)  # Cit01 for two colored snake rects idea
        blue2 = (0, 100, 255)  # Cit01 for two colored snake rects idea
        black = (0, 0, 0)

        BLOCK_SIZE = 20
        SPEED = 20  # Cit01 specifically for how this variable works as opposed to fps

        class SnakeGame:

            def __init__(self, w=640, h=480):
                self.w = w  # Cit01
                self.h = h  # Cit01
                # init display
                self.display = pygame.display.set_mode((self.w, self.h))
                pygame.display.set_caption('Snake')
                self.clock = pygame.time.Clock()

                # init game state
                self.direction = Direction.RIGHT

                self.head = Point(self.w / 2, self.h / 2)  # Cit01
                self.snake = [self.head,  # Cit01
                              Point(self.head.x - BLOCK_SIZE, self.head.y),  # Cit01
                              Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]  # Cit01

                self.score = 0
                self.food = None
                self._placeFood()

            def _placeFood(self):
                x = random.randint(0, (self.w - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
                y = random.randint(0, (self.h - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
                self.food = Point(x, y)
                if self.food in self.snake:
                    self._placeFood()

            def playStep(self):
                # 1. collect user input
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        quit()
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                            self.direction = Direction.LEFT
                        elif event.key == pygame.K_RIGHT:
                            self.direction = Direction.RIGHT
                        elif event.key == pygame.K_UP:
                            self.direction = Direction.UP
                        elif event.key == pygame.K_DOWN:
                            self.direction = Direction.DOWN

                # 2. move
                self._move(self.direction)  # update the head
                self.snake.insert(0, self.head)

                # 3. check if game over
                gameOver = False
                if self._isCollision():
                    gameOver = True
                    return gameOver, self.score

                # 4. place new food or just move
                if self.head == self.food:
                    self.score += 1
                    self._placeFood()
                else:
                    self.snake.pop()

                # 5. update ui and clock
                self._updateUI()
                self.clock.tick(SPEED)
                # 6. return game over and score
                return gameOver, self.score

            def _isCollision(self):  # Cit01
                # hits boundary
                if self.head.x > self.w - BLOCK_SIZE or self.head.x < 0 or self.head.y > self.h - BLOCK_SIZE or self.head.y < 0:
                    return True
                # hits itself
                if self.head in self.snake[1:]:
                    return True

                return False

            def _updateUI(self):
                self.display.fill(black)

                for pt in self.snake:
                    pygame.draw.rect(self.display, blue1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))  # Cit01 two colored snake
                    pygame.draw.rect(self.display, blue2, pygame.Rect(pt.x + 4, pt.y + 4, 12, 12))  # Cit01 two colored snake idea

                pygame.draw.rect(self.display, red, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))

                self.text = font.render("Score: " + str(self.score), True, white)
                self.display.blit(self.text, [0, 0])
                pygame.display.flip()

            def _move(self, direction):
                x = self.head.x
                y = self.head.y
                if direction == Direction.RIGHT:
                    x += BLOCK_SIZE
                elif direction == Direction.LEFT:
                    x -= BLOCK_SIZE
                elif direction == Direction.DOWN:
                    y += BLOCK_SIZE
                elif direction == Direction.UP:
                    y -= BLOCK_SIZE

                self.head = Point(x, y)

        while run0 == True:
            game = SnakeGame()

            # game loop
            while True:
                gameOver, score = game.playStep()

                if gameOver == True:
                    break

            print('Final Score', score)

            pygame.quit()

    while run1 == True:
        pygame.init()

        # colors
        white = (255, 255, 255)
        black = (0, 0, 0)
        red = (255, 0, 0)
        green = (0, 255, 0)
        blue = (50, 100, 200)
        gray = (220, 220, 220)

        # classes
        class Paddle(pygame.sprite.Sprite):
            def __init__(self):
                super().__init__()
                black = (0, 0, 0)

                self.image = pygame.Surface([120, 20])
                pygame.draw.rect(self.image, black, [0, 0, 120, 20])
                self.rect = self.image.get_rect()

            def moveRight(self):
                self.rect.x += 6
                if self.rect.x >= (SW - 120):
                    self.rect.x = SW - 120

            def moveLeft(self):
                self.rect.x -= 6
                if self.rect.x <= 0:
                    self.rect.x = 0

        class Ball(pygame.sprite.Sprite):
            def __init__(self):
                super().__init__()
                red = (255, 0, 0)

                self.image = pygame.Surface([20, 20])
                pygame.draw.rect(self.image, red, [0, 0, 20, 20])
                self.rect = self.image.get_rect()

                self.velocity = [random.randint(3, 7), random.randint(4, 8)]

            def initPos(self):
                self.rect.x = (SW / 2) - 10
                self.rect.y = SH - 300

            def update(self):
                self.rect.x += self.velocity[0]
                self.rect.y += self.velocity[1]

            def bounceX(self):
                self.velocity[0] = -self.velocity[0]

            def bounceY(self):
                self.velocity[1] = -self.velocity[1]

        class Brick(pygame.sprite.Sprite):
            def __init__(self, color):
                super().__init__()

                self.image = pygame.Surface([100, 20])
                pygame.draw.rect(self.image, color, [0, 0, 100, 20])
                self.rect = self.image.get_rect()

        # functions
        def createBricks(c, r):
            for i in range(c):
                for j in range(r):
                    brick = Brick(blue)
                    brick.rect.x = 20 + i * 110
                    brick.rect.y = 20 + j * 30
                    allBricks.add(brick)
                    allSprites.add(brick)

        def killAllBricks():
            for brick in allBricks:
                brick.kill()

        # display
        screen = pygame.display.set_mode((SW, SH))
        pygame.display.set_caption("Brick Breaker")

        # clock
        FPS = 60
        clock = pygame.time.Clock()

        # create paddle
        paddle = Paddle()
        paddle.rect.x = (SW / 2) - 60
        paddle.rect.y = (SH) - 60

        # create ball
        ball = Ball()
        ball.initPos()

        # group of sprites
        allSprites = pygame.sprite.Group()
        allSprites.add(paddle)
        allSprites.add(ball)

        # bricks
        allBricks = pygame.sprite.Group()

        # create bricks
        createBricks(7, 9)

        score = 0
        lives = 3
        start = False
        while True:
            # event listeners
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            # fill screen
            screen.fill(gray)

            # draw the sprites
            allSprites.draw(screen)

            # handle key events
            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE]:
                start = True
            if keys[pygame.K_RIGHT]:
                paddle.moveRight()
            if keys[pygame.K_LEFT]:
                paddle.moveLeft()

            # Score
            font = pygame.font.Font(None, 40)
            text = font.render(f'Score: {score}', 1, black)
            screen.blit(text, (20, SH - 30))
            # Lives
            font = pygame.font.Font(None, 40)
            text = font.render(f'Lives: {lives}', 1, black)
            screen.blit(text, (SW - 120, SH - 30))

            # game over message
            if lives == 0:
                font = pygame.font.Font(None, 40)
                text = font.render(f'GAME OVER', 1, black)
                screen.blit(text, (SW / 2.5, SH / 2))
                font = pygame.font.Font(None, 40)
                text = font.render(f'PRESS SPACE TO REPLAY', 1, black)
                screen.blit(text, (SW / 3.3, SH / 1.5))
            if len(allBricks) == 0:
                font = pygame.font.Font(None, 40)
                text = font.render(f'YOU WIN!!', 1, black)
                screen.blit(text, (SW / 2.5, SH / 2))
                ball.initPos()
                score = 0
                start = False

            if start:
                # update the Sprites
                allSprites.update()
                if lives == 0:
                    lives = 3
                    score = 0
                    killAllBricks()
                    createBricks(7, 9)
                if ball.rect.right >= SW or ball.rect.left < 0:
                    ball.bounceX()
                if ball.rect.top <= 0:
                    ball.bounceY()
                if ball.rect.y >= SH - 40:
                    ball.initPos()
                    lives -= 1
                    start = False

                # collisions with paddle
                if ball.rect.colliderect(paddle.rect):
                    if abs(paddle.rect.top - ball.rect.bottom) < 9:
                        ball.bounceY()
                    if abs(paddle.rect.left - ball.rect.right) < 9 or abs(paddle.rect.right - ball.rect.left) < 9:
                        ball.bounceX()

                # collisions with bricks
                ballHitList = pygame.sprite.spritecollide(ball, allBricks, False)
                for brick in ballHitList:
                    ball.bounceY()
                    brick.kill()
                    score += 1

            # draw a line
            pygame.draw.line(screen, black, [0, SH - 35], [SW, SH - 35], 5)

            # update display
            pygame.display.update()

            # tick clock
            clock.tick(FPS)

    from collections import deque
    MAX_MEMORY = 100_000
    BATCH_SIZE = 1000
    LR = 0.001

    class snakeAgent:

        def __init__(self):
            self.numGames = 0
            self.epsilon = 0  # randomness
            self.gamma = 0.9  # discount rate, must be smaller than 1
            self.memory = deque(maxlen=MAX_MEMORY)  # popleft()
            self.model = snakeLinearQNet(11, 256, 3)
            self.trainer = QTrainerSnake(self.model, lr=LR, gamma=self.gamma)

        def getState(self, game):  # Cit01, this is the one thing I was
                                   # completely lost on without the cited source
            head = game.snake[0]
            pointL = Point(head.x - 20, head.y)
            pointR = Point(head.x + 20, head.y)
            pointU = Point(head.x, head.y - 20)
            pointD = Point(head.x, head.y + 20)

            dirL = game.direction == Direction.LEFT
            dirR = game.direction == Direction.RIGHT
            dirU = game.direction == Direction.UP
            dirD = game.direction == Direction.DOWN

            state = [
                # Danger straight
                (dirR and game.isCollision(pointR)) or
                (dirL and game.isCollision(pointL)) or
                (dirU and game.isCollision(pointU)) or
                (dirD and game.isCollision(pointD)),

                # Danger right
                (dirU and game.isCollision(pointR)) or
                (dirD and game.isCollision(pointL)) or
                (dirL and game.isCollision(pointU)) or
                (dirR and game.isCollision(pointD)),

                # Danger left
                (dirD and game.isCollision(pointR)) or
                (dirU and game.isCollision(pointL)) or
                (dirR and game.isCollision(pointU)) or
                (dirL and game.isCollision(pointD)),

                # Move direction
                dirL,
                dirR,
                dirU,
                dirD,

                # Food location
                game.food.x < game.head.x,  # food left
                game.food.x > game.head.x,  # food right
                game.food.y < game.head.y,  # food up
                game.food.y > game.head.y  # food down
                ]
            return np.array(state, dtype=int)

        def remember(self, state, action, reward, nextState, gameOver):
            self.memory.append((state, action, reward, nextState, gameOver)) # popleft if MAX_MEMORY is reached

        def trainLongMemory(self):
            if len(self.memory) > BATCH_SIZE:
                miniSample = random.sample(self.memory, BATCH_SIZE)  # list of tuples
            else:
                miniSample = self.memory

            states, actions, rewards, nextStates, gameOvers = zip(*miniSample)
            self.trainer.trainStep(states, actions, rewards, nextStates, gameOvers)
        def trainShortMemory(self, state, action, reward, nextState, gameOver):
            self.trainer.trainStep(state, action, reward, nextState, gameOver)

        def getAction(self, state):  # Cit01
            # random moves: tradeoff exploration / exploitation
            self.epsilon = 80 - self.numGames
            finalMove = [0,0,0]
            if random.randint(0, 200) < self.epsilon:
                move = random.randint(0, 2)
                finalMove[move] = 1
            else:
                state0 = torch.tensor(state, dtype=torch.float)
                prediction = self.model(state0)
                move = torch.argmax(prediction).item()
                finalMove[move] = 1

            return finalMove

    def snakeTrain():  # Cit01
        global numGames
        plotScores = []
        plotMeanScores = []
        totalScore = 0
        record = 0
        agent = snakeAgent()
        game = SnakeAI()
        while True:  # Cit01
            # get old state
            stateOld = agent.getState(game)

            # get move
            finalMove = agent.getAction(stateOld)

            # perform move and get new state
            reward, gameOver, score = game.playStep(finalMove)
            stateNew = agent.getState(game)

            # train short term memory
            agent.trainShortMemory(stateOld, finalMove, reward, stateNew, gameOver)

            # remember
            agent.remember(stateOld, finalMove, reward, stateNew, gameOver)

            if gameOver:
                # train long memory
                game.reset()
                agent.numGames += 1
                agent.trainLongMemory()

                if score > record:
                    record = score
                    agent.model.save()

                print("Game", agent.numGames, "Score", score, "Record:", record)

                plotScores.append(score)
                totalScore += score
                meanScore = totalScore / agent.numGames
                plotMeanScores.append(meanScore)
                plot(plotScores, plotMeanScores)

    def turnOnSnakeAgent():
        global snakeAgentOn
        snakeAgentOn = True

    def turnOnbbAgent():
        global bbAgentOn
        bbAgentOn = True

    while run2 == True:
        import pygame
        import random
        from enum import Enum
        from collections import namedtuple

        pygame.init()
        font = pygame.font.SysFont('calibri', 25)

        class Direction(Enum):
            RIGHT = 1
            LEFT = 2
            UP = 3
            DOWN = 4

        Point = namedtuple('Point', 'x, y')

        # rgb colors
        white = (255, 255, 255)
        red = (200, 0, 0)
        blue1 = (0, 0, 255)  # Cit01
        blue2 = (0, 100, 255)  # Cit01
        black = (0, 0, 0)

        BLOCK_SIZE = 20
        SPEED = 120  #snake game for player at 20

        class SnakeAI:

            def __init__(self, w=640, h=480):
                self.w = w  # Cit01
                self.h = h  # Cit01
                # init display
                self.display = pygame.display.set_mode((self.w, self.h))
                pygame.display.set_caption('Snake')
                self.clock = pygame.time.Clock()

                # init game state
                self.direction = Direction.RIGHT

                self.head = Point(self.w / 2, self.h / 2)  # Cit01
                self.snake = [self.head,  # Cit01
                              Point(self.head.x - BLOCK_SIZE, self.head.y),  # Cit01
                              Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]  # Cit01

                self.score = 0
                self.food = None
                self._placeFood()
                self.frameIteration = 0

            def reset(self):
                # init game state
                self.direction = Direction.RIGHT

                self.head = Point(self.w / 2, self.h / 2)
                self.snake = [self.head,
                              Point(self.head.x - BLOCK_SIZE, self.head.y),
                              Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]

                self.score = 0
                self.food = None
                self._placeFood()
                self.frameIteration = 0

            def _placeFood(self):
                x = random.randint(0, (self.w - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
                y = random.randint(0, (self.h - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
                self.food = Point(x, y)
                if self.food in self.snake:
                    self._placeFood()

            def playStep(self, action):
                self.frameIteration += 1
                # 1. collect user input
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        quit()

                # 2. move
                self._move(action)  # update the head
                self.snake.insert(0, self.head)

                # 3. check if game over
                reward = 0
                gameOver = False
                if self.isCollision() or self.frameIteration > 100*len(self.snake):
                    gameOver = True
                    reward = -10
                    return reward, gameOver, self.score

                # 4. place new food or just move
                if self.head == self.food:
                    self.score += 1
                    reward = 10
                    self._placeFood()
                else:
                    self.snake.pop()

                # 5. update ui and clock
                self._updateUI()
                self.clock.tick(SPEED)
                # 6. return game over and score
                return reward, gameOver, self.score

            def isCollision(self, pt=None):  # Cit01
                if pt is None:
                    pt = self.head
                # hits boundary
                if pt.x > self.w - BLOCK_SIZE or pt.x < 0 or pt.y > self.h - BLOCK_SIZE or pt.y < 0:
                    return True
                # hits itself
                if pt in self.snake[1:]:
                    return True

                return False

            def _updateUI(self):
                self.display.fill(black)

                for pt in self.snake:
                    pygame.draw.rect(self.display, blue1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))  # Cit01
                    pygame.draw.rect(self.display, blue2, pygame.Rect(pt.x + 4, pt.y + 4, 12, 12))  # Cit01

                pygame.draw.rect(self.display, red, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))

                text = font.render("Score: " + str(self.score), True, white)
                self.display.blit(text, [0, 0])
                pygame.display.flip()

            def _move(self, action):
                # [straight, right, left]

                clockwise = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]  # Cit01
                idx = clockwise.index(self.direction)  # Cit01

                if np.array_equal(action, [1, 0, 0]):  # Cit01
                    newDir = clockwise[idx]
                elif np.array_equal(action, [0, 1, 0]):  # Cit01
                    nextIdx = (idx + 1) % 4 #clockwise turn
                    newDir = clockwise[nextIdx]
                else:  # Cit01
                    nextIdx = (idx - 1) % 4 #counterclockwise turn
                    newDir = clockwise[nextIdx]

                self.direction = newDir

                x = self.head.x
                y = self.head.y
                if self.direction == Direction.RIGHT:
                    x += BLOCK_SIZE
                elif self.direction == Direction.LEFT:
                    x -= BLOCK_SIZE
                elif self.direction == Direction.DOWN:
                    y += BLOCK_SIZE
                elif self.direction == Direction.UP:
                    y -= BLOCK_SIZE

                self.head = Point(x, y)

        turnOnSnakeAgent()
        while snakeAgentOn == True:
            snakeTrain()

    while run3 == True:
        import neat
        import os
        import pickle
        import time

        pygame.init()

        # colors
        white = (255, 255, 255)
        black = (0, 0, 0)
        red = (255, 0, 0)
        green = (0, 255, 0)
        blue = (50, 100, 200)
        gray = (220, 220, 220)

        # group of sprites
        allSprites = pygame.sprite.Group()
        # bricks
        allBricks = pygame.sprite.Group()

        # classes
        class Paddle(pygame.sprite.Sprite):

            def __init__(self):
                super().__init__()
                black = (0, 0, 0)

                self.image = pygame.Surface([200, 20])
                pygame.draw.rect(self.image, black, [0, 0, 120, 20])
                self.rect = self.image.get_rect()

            def moveRight(self):
                self.rect.x += 7
                if self.rect.x >= (SW - 120):
                    self.rect.x = SW - 120

            def moveLeft(self):
                self.rect.x -= 7
                if self.rect.x <= 0:
                    self.rect.x = 0

        class Ball(pygame.sprite.Sprite):
            def __init__(self):
                super().__init__()
                red = (255, 0, 0)

                self.image = pygame.Surface([20, 20])
                pygame.draw.rect(self.image, red, [0, 0, 20, 20])
                self.rect = self.image.get_rect()

                self.velocity = [random.randint(-1, 1) * 5, 5]
                if self.velocity[0] == 0:
                    self.velocity[0] = 1

            def initPos(self):
                self.rect.x = (SW / 2) - 10
                self.rect.y = SH - 300

            def update(self):
                self.rect.x += self.velocity[0]
                self.rect.y += self.velocity[1]

            def bounceX(self):
                self.velocity[0] = -self.velocity[0]

            def bounceY(self):
                self.velocity[1] = -self.velocity[1]

        class Brick(pygame.sprite.Sprite):
            def __init__(self, color):
                super().__init__()

                self.image = pygame.Surface([100, 20])
                pygame.draw.rect(self.image, color, [0, 0, 100, 20])
                self.rect = self.image.get_rect()

        # functions
        def createBricks(c, r):
            global allSprites
            global allBricks
            for i in range(c):
                for j in range(r):
                    brick = Brick(blue)
                    brick.rect.x = 20 + i * 110
                    brick.rect.y = 20 + j * 30
                    allBricks.add(brick)
                    allSprites.add(brick)

        def killAllBricks():
            for brick in allBricks:
                brick.kill()

        class bbGameInfo:
            def __init__(self, score, fail, quit):
                self.score = score
                self.fail = fail
                self.quit = quit

        class bbGame:

            def __init__(self, SW, SH, screen):
                # display
                self.SW = SW
                self.SH = SH
                self.screen = screen
                pygame.display.set_caption("Brick Breaker")

                # create paddle
                self.paddle = Paddle()
                self.paddle.rect.x = (self.SW / 2) - 60
                self.paddle.rect.y = (self.SH) - 60

                # create ball
                self.ball = Ball()
                self.ball.initPos()

                # clock
                self.FPS = 600
                self.clock = pygame.time.Clock()

                # make sprites
                allSprites.add(self.paddle)
                allSprites.add(self.ball)

                # create bricks
                createBricks(7, 9)

                self.score = 0.0
                self.fail = 0
                self.quit = False

                #self.lives = 3

                self.cur = 0
                self.prev = 0

                self.start = True

            def _collisions(self):
                # collisions with paddle
                if self.ball.rect.colliderect(self.paddle.rect):
                    if abs(self.paddle.rect.top - self.ball.rect.bottom) < 9:
                        self.ball.bounceY()
                    if abs(self.paddle.rect.left - self.ball.rect.right) < 9 or abs(
                            self.paddle.rect.right - self.ball.rect.left) < 9:
                        self.ball.bounceX()

                # collisions with bricks
                self.ballHitList = pygame.sprite.spritecollide(self.ball, allBricks, False)
                for brick in self.ballHitList:
                    self.ball.bounceY()
                    brick.kill()
                    self.score += 1

            def resetPos(self):
                killAllBricks()
                createBricks(7, 9)
                self.ball.initPos()

            def loop(self):
                # event listeners
                keys = pygame.key.get_pressed()
                if keys[pygame.K_SPACE]:
                    self.quit = True
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        sys.exit()

                # fill screen
                self.screen.fill(gray)

                # draw the sprites
                allSprites.draw(screen)

                # handle key events
                #keys = pygame.key.get_pressed()
                #if keys[pygame.K_RIGHT]:
                #    self.paddle.moveRight()
                #if keys[pygame.K_LEFT]:
                #    self.paddle.moveLeft()

                # Score
                font = pygame.font.Font(None, 40)
                text = font.render(f'Score: {self.score}', 1, black)
                screen.blit(text, (20, self.SH - 30))
                # Lives
                #font = pygame.font.Font(None, 40)
                #text = font.render(f'Lives: {self.lives}', 1, black)
                #screen.blit(text, (self.SW - 120, self.SH - 30))

                # game over message
                #if self.lives == 0:
                #    font = pygame.font.Font(None, 40)
                #    text = font.render(f'GAME OVER', 1, black)
                #    self.screen.blit(text, (self.SW / 2.5, self.SH / 2))
                #    font = pygame.font.Font(None, 40)
                #    text = font.render(f'PRESS SPACE TO REPLAY', 1, black)
                #    self.screen.blit(text, (self.SW / 3.3, self.SH / 1.5))
                #if len(allBricks) == 0:
                #    font = pygame.font.Font(None, 40)
                #    text = font.render(f'YOU WIN!!', 1, black)
                #    self.screen.blit(text, (self.SW / 2.5, self.SH / 2))
                #    self.ball.initPos()
                #    self.score = 0
                #    self.start = False

                if self.start:
                    # update the Sprites
                    allSprites.update()
                    allBricks.update()
                    #if self.lives == 0:
                    #    self.lives = 3
                    #    self.score = 0
                    #    killAllBricks()
                    #    createBricks(7, 9)
                    if self.ball.rect.right >= self.SW or self.ball.rect.left < 0:
                        self.ball.bounceX()
                    if self.ball.rect.top <= 0:
                        self.ball.bounceY()
                    if self.ball.rect.y >= self.SH - 40:
                        self.fail = 1
                        killAllBricks()
                        self.paddle.kill()
                        gameInfo = bbGameInfo(self.score, self.fail, self.quit)

                        return gameInfo
                        #self.resetPos()
                        #self.lives -= 1

                    self._collisions()

                # draw a line
                pygame.draw.line(self.screen, black, [0, self.SH - 35], [SW, self.SH - 35], 5)

                # update display
                pygame.display.update()
                allSprites.update()
                allBricks.update()
                allSprites.draw(screen)

                # tick clock
                self.clock.tick(self.FPS)

                gameInfo = bbGameInfo(self.score, self.fail, self.quit)

                return gameInfo

            def moveAI(self, net):
                player = [(self.genome, net, self.paddle)]
                for (genome, net, paddle) in player:
                    output = net.activate(
                        (self.paddle.rect.x, self.ball.rect.x, abs(self.paddle.rect.y - self.ball.rect.y)))
                    decision = output.index(max(output))

                    if decision == 0:  # Don't move
                        self.genome.fitness -= 0.01  # we want to discourage this
                    elif decision == 1:
                        self.paddle.moveRight()
                    else:  # Move down
                        self.paddle.moveLeft()

            def bbGameTrainAI(self, game, genome, config):
                startTime = time.time()

                net = neat.nn.FeedForwardNetwork.create(genome, config)
                self.genome = genome

                while True:

                    gameInfo = game.loop()

                    self.moveAI(net)

                    duration = time.time() - startTime

                    if gameInfo.fail >= 1 or gameInfo.score >= 62 or gameInfo.quit:
                        killAllBricks()
                        self.paddle.kill()
                        self.calcFitness(gameInfo.score, duration)
                        break

            def calcFitness(self, gameInfoScore, duration):
                self.genome.fitness += gameInfoScore + duration

        def evalGenomes(genomes, config):
            #screen = pygame.display.set_mode((SW, SH))
            #game = bbGame(800, 800, screen)

            for i, (genomeID, genome) in enumerate(genomes):
                screen = pygame.display.set_mode((SW, SH))
                killAllBricks()
                game = bbGame(800, 800, screen)
                genome.fitness = 0
                if i == len(genomes) - 1:
                    killAllBricks()
                    game.paddle.kill()
                    break

                game.bbGameTrainAI(game, genome, config)

                #for j, (genomeID1, genome1) in enumerate(genomes):
                #    genome1.fitness = 0
                #    if i == len(genomes) - 1:
                #        break

                #    game.bbGameTrainAI(game, genome1, config)

        def runNeat(config):
            #p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-7')
            p = neat.Population(config)
            p.add_reporter(neat.StdOutReporter(True))
            stats = neat.StatisticsReporter()
            p.add_reporter(stats)
            p.add_reporter(neat.Checkpointer(1))

            winner = p.run(evalGenomes, 50)

            with open("best.pickle", "wb") as f:
                pickle.dump(winner, f)

        bbAgentOn = True
        while bbAgentOn:
            localDir = os.path.dirname(__file__)
            configPath = os.path.join(localDir, "config.txt")

            config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                 neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                 configPath)

            runNeat(config)

    run4 = True
    while run4:
        screen.fill("purple")

        snakeButton.draw()
        bbButton.draw()
        snakeAIButton.draw()
        bbAIButton.draw()
        mainMenuText = mainFont.render("Games Played By AI!!", True, "white")
        mainMenuTextRect = mainMenuText.get_rect(center=(377, 200))
        screen.blit(mainMenuText, mainMenuTextRect)

        # event handler
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    gameStatePause = True
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
            # todo add event listeners for click mainMenu buttons
        if run0 + run1 + run2 + run3 != 0:
            run4 = False

        if run4 == True:
            pygame.display.update()


# -*- coding: utf-8 -*-
import requests
import re

def get_fund(code):
    url = "http://hq.sinajs.cn/list=%s" % code
    res = requests.get(url).text
    str_com = re.compile(r'\"(.*)\"')
    result = str_com.findall(res)[0].split(',')
    yesterday_closing = float(result[2])
    now = float(result[3])
    # 根据现价和昨日收盘价格判断
    closing_diff = round(now - yesterday_closing, 2)
    closing_diff_percent = round(closing_diff / yesterday_closing * 100, 2)
    color = '#ff0000' if closing_diff > 0 else '#006d21'
    content = f'现价：{round(now, 2)}，幅度：{closing_diff_percent}%，'
    if closing_diff_percent <= -1:
        if 3600 > now > 3400:
            multiple = '单倍'
        elif 3400 > now > 3200:
            multiple = '双倍'
        else:
            multiple = '三倍'
        content += f'{multiple}定投'
    return content


import cv2
import numpy as np

def valueChanged(value):
    pass

cv2.namedWindow("HSV")
cv2.resizeWindow("HSV", 640, 240)
cv2.createTrackbar("HUE MIN","HSV",0,179,valueChanged)
cv2.createTrackbar("HUE MAX","HSV",179,179,valueChanged)
cv2.createTrackbar("SAT MIN","HSV",0,255,valueChanged)
cv2.createTrackbar("SAT MAX","HSV",255,255,valueChanged)
cv2.createTrackbar("VALUE MIN","HSV",0,255,valueChanged)
cv2.createTrackbar("VALUE MAX","HSV",255,255,valueChanged)

if __name__ == "__main__":
    vid = cv2.VideoCapture('foot.mp4')
    framecount=0

    while True:
        if vid.get(cv2.CAP_PROP_FRAME_COUNT) == framecount:
            vid.set(cv2.CAP_PROP_POS_FRAMES,0)
            framecount=0
        framecount+=1
        success, frame= vid.read()

        frame = cv2.resize(frame,(480,240))
        hsvimg = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

        h_min = cv2.getTrackbarPos("HUE MIN","HSV")
        h_max = cv2.getTrackbarPos("HUE MAX", "HSV")
        s_min = cv2.getTrackbarPos("SAT MIN","HSV")
        s_max = cv2.getTrackbarPos("SAT MAX", "HSV")
        v_min = cv2.getTrackbarPos("VALUE MIN","HSV")
        v_max = cv2.getTrackbarPos("VALUE MAX", "HSV")

        lower = np.array([h_min,s_min,v_min])
        upper = np.array([h_max,s_max,v_max])

        mask = cv2.inRange(hsvimg,lower, upper)
        result = cv2.bitwise_and(frame,frame, mask=mask)
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

        hstack = np.hstack([img, result, mask])

        #cv2.imshow("frame", frame)
        #cv2.imshow("hsv",frame)
        #cv2.imshow("img", img)
        cv2.imshow("mask",hstack)
        #cv2.imshow("result",result)

        key = cv2.waitKey(1)

        if key == 27:
            break


#!/usr/bin/python2

import sys
import csv
import subprocess
from StringIO import StringIO

cvsoutput = subprocess.check_output(["ssh", "zimbra@zmx.bauru.unesp.br", "zmmailbox", "-z", "-m", sys.argv[1], "gru", "/Contacts"])
buff = StringIO(cvsoutput)

reader = csv.DictReader(buff)
out = csv.writer(sys.stdout)

for line in reader:
    if not 'email' in line or line['email'] == '':
        continue
    if not 'firstName' in line:
        line['firstName'] = ''
    if not 'lastName' in line:
        line['lastName'] = ''
    if not 'fullName' in line:
        line['fullName'] = ''
    out.writerow([line['email'], line['firstName'], line['lastName'], line['fullName']])