#
# @lc app=leetcode id=328 lang=python3
#
# [328] Odd Even Linked List
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# Clear Python Solution
# https://leetcode.com/problems/odd-even-linked-list/discuss/78095/Clear-Python-Solution

# : ListNode) -> ListNode:
class Solution:
    # def oddEvenList(self, head):
    #     odd_list = p1 = ListNode(0) # odd_list 做頭, p1當移動指標
    #     # print(odd_list) #1
    #     even_list = p2 = ListNode(0) # even_list 做頭, p2當移動指標
    #     # print(even_list) #2

    #     # print(out_list) #1
    #     d1 = head

    #     while(True):
    #         if head: # odd
    #             # print(head)
    #             p1.next = head #不改掉自己的0 -> 下一個從1開始
    #             # print(p1)
    #             p1 = p1.next #移動指標
    #             head = head.next
    #         else:
    #             p1.next = None
    #             break

    #         if head: #even
    #             # print(head)
    #             p2.next = head #不改掉自己的0 -> 下一個從2開始
    #             # print(p2)
    #             p2 = p2.next #移動指標
    #             head = head.next
    #         else:
    #             p2.next = None
    #             break

    #     # print(odd_list)
    #     # print(even_list)
    #     p1.next = even_list.next  #從自己的0下一個開始
    #     # print(odd_list)

    #     return odd_list.next #從自己的0下一個開始

#     def oddEvenList(self, head):
    #     dummy1 = odd = ListNode(0) #一個當頭一個移動指標
        # dummy2 = even = ListNode(0) #一個當頭一個移動指標
        # while head:
        #     odd.next = head #從0的下一個開始塞資料
        #     even.next = head.next  #從0的下一個開始塞資料
        #     odd = odd.next #移動指標
        #     even = even.next #移動指標
        #     head = head.next.next if even else None #移動指標

        # odd.next = dummy2.next #接起來 奇數尾巴 接 偶數頭
        # return dummy1.next

    # class Solution(object):
        # def oddEvenList(self, head):
        # """
        # :type head: ListNode
        # :rtype: ListNode
        # """
        # d1=odd=ListNode(0)
        # d2=even=ListNode(0)
        # i=1
        # while head:
        #     if i%2: # 有餘數是奇數
        #         odd.next,odd=head,head # 先移"此處oddnext"指的東西, 再移"移動指標odd"
        #     else: # 偶數
        #         even.next,even=head,head

        #     head=head.next
        #     i+=1
        # odd.next,even.next=d2.next,None
        # return d1.next

    # Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# With detailed explanation | Python
# https://leetcode.com/problems/odd-even-linked-list/discuss/133345/With-detailed-explanation-or-Python

    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head

        odd = head # Both of them point at the first node of the target linked list
        even = head.next # doesn't matter even there's only one node in the linked list (even will become None)
        eHead = even # We have to keep where the even-node list starts

        while even and even.next: # won't get in the loop at first if there's only one node in the linked list
            # both even and even.next are necessary condition because even might point to None, which has no attribute 'next'
            # AND, why these two, small discussion by myself as below
            odd.next = odd.next.next # 移動next指的東西
            even.next = even.next.next # 移動next指的東西
            # After these two ops, odd/even still points at its original place
            # Therefore, we move them to the next node repectively
            odd = odd.next # 移動動態指標
            even = even.next # 移動動態指標

        odd.next = eHead # the odd pointer currently points at the last node of the odd-node list

        return head # We keep the start of the odd-node list in the first of our code

# @lc code=end


# -*- coding:utf-8 -*-
# @auth ivan
# @time 2020-06-08
# @goal Test the difflib

import difflib
s1 = "Test the difflib"
s2 = "Test the python"

for _ in difflib.SequenceMatcher(None, s1, s2).get_matching_blocks():
    if _.size > 3:
        print(s1[_.a:_.a + _.size])
# Test the XXX


import input_data
import tensorflow as tf
import numpy as np
import os

slim = tf.contrib.slim
# 产生截断的正态分布
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)

# 设置L2正则的weight_decay, 标准差默认值0.1
def inception_v3_arg_scope(weight_decay = 0.00004, stddev = 0.1,
                           batch_norm_var_collection = 'moving_vars'):

    # 定义batch normalization（标准化）的参数字典
    batch_norm_params = {
        'decay': 0.9997,  #定义参数衰减系数
        'epsilon': 0.001, #防止除以0
        'updates_collections': tf.GraphKeys.UPDATE_OPS,
        'variables_collections':
        {
            'beta': None,
            'gamma': None,
            'moving_mean': [batch_norm_var_collection],
            'moving_variance': [batch_norm_var_collection],
        }
    }

    with slim.arg_scope([slim.conv2d, slim.fully_connected],
                weights_regularizer = slim.l2_regularizer(weight_decay)): # 对[slim.conv2d, slim.fully_connected]自动赋值
  # 使用slim.arg_scope后就不需要每次都重复设置参数了，只需要在有修改时设置
        with slim.arg_scope([slim.conv2d],
            weights_initializer = trunc_normal(stddev),
            activation_fn = tf.nn.relu,
            normalizer_fn = slim.batch_norm,
            normalizer_params = batch_norm_params) as sc:

            return sc # 最后返回定义好的scope

def inception_v3_base(inputs, scope = None):

    with tf.variable_scope(scope, 'InceptionV3', [inputs]):
        #对三个参数设置默认值
        with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride = 1, padding = 'VALID'):

            net = slim.conv2d(inputs, 32, [3, 3], stride = 2, scope = 'Conv2d_1a_3x3')
            #输出149*149*32数据
            net = slim.conv2d(net, 32, [3, 3], scope='Conv2d_2a_3x3')
            #输出147 x 147 x 32
            net = slim.max_pool2d(net, [3, 3], stride=2, scope='MaxPool_3a_3x3')
            #输出73 x 73 x 64
            net = slim.conv2d(net, 80, [1, 1], scope='Conv2d_3b_1x1')
            #输出73 x 73 x 80.
            net = slim.conv2d(net, 192, [3, 3], scope='Conv2d_4a_3x3')
            #输出71 x 71 x 192.
            net = slim.max_pool2d(net, [3, 3], stride=2, scope='MaxPool_5a_3x3')
            #输出35 x 35 x 192
            # 设置所有模块组的默认参数,将所有卷积层、最大池化、平均池化层步长都设置为1
            with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'):
                with tf.variable_scope('Mixed_5b'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 48, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 64, [5, 5], scope='Conv2d_0b_5x5')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 32, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出35 x 35 x 256
                with tf.variable_scope('Mixed_5c'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 48, [1, 1], scope='Conv2d_0b_1x1')
                        branch_1 = slim.conv2d(branch_1, 64, [5, 5], scope='Conv_1_0c_5x5')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出35 x 35 x 288
                with tf.variable_scope('Mixed_5d'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 48, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 64, [5, 5], scope='Conv2d_0b_5x5')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3')
                        branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 64, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出35 x 35 x 288
                #第二个inception模块
                with tf.variable_scope('Mixed_6a'):
                    with tf.variable_scope('Branch_0'):
                        #图片会被压缩
                        branch_0 = slim.conv2d(net, 384, [3, 3], stride = 2,padding='VALID', scope='Conv2d_1a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 64, [1, 1], scope = 'Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 96, [3, 3], scope = 'Conv2d_0b_3x3')
                        # 图片被压缩
                        branch_1 = slim.conv2d(branch_1, 96, [3, 3], stride = 2,padding = 'VALID', scope = 'Conv2d_1a_1x1')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID',scope='MaxPool_1a_3x3')
                    net = tf.concat([branch_0, branch_1, branch_2], 3)
                    #输出17 x 17 x 768
                with tf.variable_scope('Mixed_6b'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 128, [1, 7], scope='Conv2d_0b_1x7')
                        branch_1 = slim.conv2d(branch_1, 192, [7, 1], scope='Conv2d_0c_7x1')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 128, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 128, [7, 1], scope='Conv2d_0b_7x1')
                        branch_2 = slim.conv2d(branch_2, 128, [1, 7], scope='Conv2d_0c_1x7')
                        branch_2 = slim.conv2d(branch_2, 128, [7, 1], scope='Conv2d_0d_7x1')
                        branch_2 = slim.conv2d(branch_2, 192, [1, 7], scope='Conv2d_0e_1x7')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出17 x 17 x 768
                with tf.variable_scope('Mixed_6c'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 160, [1, 7], scope='Conv2d_0b_1x7')
                        branch_1 = slim.conv2d(branch_1, 192, [7, 1], scope='Conv2d_0c_7x1')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 160, [7, 1], scope='Conv2d_0b_7x1')
                        branch_2 = slim.conv2d(branch_2, 160, [1, 7], scope='Conv2d_0c_1x7')
                        branch_2 = slim.conv2d(branch_2, 160, [7, 1], scope='Conv2d_0d_7x1')
                        branch_2 = slim.conv2d(branch_2, 192, [1, 7], scope='Conv2d_0e_1x7')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出17 x 17 x 768
                with tf.variable_scope('Mixed_6d'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 160, [1, 7], scope='Conv2d_0b_1x7')
                        branch_1 = slim.conv2d(branch_1, 192, [7, 1], scope='Conv2d_0c_7x1')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 160, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 160, [7, 1], scope='Conv2d_0b_7x1')
                        branch_2 = slim.conv2d(branch_2, 160, [1, 7], scope='Conv2d_0c_1x7')
                        branch_2 = slim.conv2d(branch_2, 160, [7, 1], scope='Conv2d_0d_7x1')
                        branch_2 = slim.conv2d(branch_2, 192, [1, 7], scope='Conv2d_0e_1x7')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出17 x 17 x 768
                with tf.variable_scope('Mixed_6e'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 192, [1, 7], scope='Conv2d_0b_1x7')
                        branch_1 = slim.conv2d(branch_1, 192, [7, 1], scope='Conv2d_0c_7x1')
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 192, [7, 1], scope='Conv2d_0b_7x1')
                        branch_2 = slim.conv2d(branch_2, 192, [1, 7], scope='Conv2d_0c_1x7')
                        branch_2 = slim.conv2d(branch_2, 192, [7, 1], scope='Conv2d_0d_7x1')
                        branch_2 = slim.conv2d(branch_2, 192, [1, 7], scope='Conv2d_0e_1x7')
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出17 x 17 x 768
                # 第三个inception模块组包含了三个inception module
                with tf.variable_scope('Mixed_7a'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                        # 压缩图片
                        branch_0 = slim.conv2d(branch_0, 320, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 192, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = slim.conv2d(branch_1, 192, [1, 7], scope='Conv2d_0b_1x7')
                        branch_1 = slim.conv2d(branch_1, 192, [7, 1], scope='Conv2d_0c_7x1')
                        branch_1 = slim.conv2d(branch_1, 192, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
                    # 池化层不会对输出通道数产生改变
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3')
                    net = tf.concat([branch_0, branch_1, branch_2], 3)
                    #输出8 x 8 x 1280
                with tf.variable_scope('Mixed_7b'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 320, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 384, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = tf.concat([slim.conv2d(branch_1, 384, [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, 384, [3, 1], scope='Conv2d_0b_3x1')], 3)
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 448, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 384, [3, 3], scope='Conv2d_0b_3x3')
                        branch_2 = tf.concat([slim.conv2d(branch_2, 384, [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, 384, [3, 1], scope='Conv2d_0d_3x1')], 3)
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出8 x 8 x 2048
                with tf.variable_scope('Mixed_7c'):
                    with tf.variable_scope('Branch_0'):
                        branch_0 = slim.conv2d(net, 320, [1, 1], scope='Conv2d_0a_1x1')
                    with tf.variable_scope('Branch_1'):
                        branch_1 = slim.conv2d(net, 384, [1, 1], scope='Conv2d_0a_1x1')
                        branch_1 = tf.concat([slim.conv2d(branch_1, 384, [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, 384, [3, 1], scope='Conv2d_0c_3x1')], 3)
                    with tf.variable_scope('Branch_2'):
                        branch_2 = slim.conv2d(net, 448, [1, 1], scope='Conv2d_0a_1x1')
                        branch_2 = slim.conv2d(branch_2, 384, [3, 3], scope='Conv2d_0b_3x3')
                        branch_2 = tf.concat([slim.conv2d(branch_2, 384, [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, 384, [3, 1], scope='Conv2d_0d_3x1')], 3)
                    with tf.variable_scope('Branch_3'):
                        branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3')
                        branch_3 = slim.conv2d(branch_3, 192, [1, 1], scope='Conv2d_0b_1x1')
                    net = tf.concat([branch_0, branch_1, branch_2, branch_3], 3)
                    #输出8 x 8 x 2048
                    return net

def inception_v3(inputs, dim_vector = 900, is_training = False,
                 dropout_keep_prob = 1, # 节点保留比率
                 prediction_fn = slim.softmax, # 最后用来分类的函数
                 reuse = tf.AUTO_REUSE, # 是否对网络和Variable进行重复使用
                 scope = 'InceptionV3'):# 包含函数默认参数的环境
    # 定义参数默认值
    with tf.variable_scope(scope, 'InceptionV3', [inputs, dim_vector], reuse = reuse) as scope:
        # 定义标志默认值
        with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training):
            # 用定义好的函数构筑整个网络的卷积部分
            net = inception_v3_base(inputs, scope = scope)
            with tf.variable_scope('Logits'):
                net = slim.avg_pool2d(net, [8, 8], padding = 'VALID', scope='AvgPool_1a_8x8')

                net = slim.dropout(net, keep_prob = dropout_keep_prob, scope = 'Dropout_1b')
                logits = slim.conv2d(net, dim_vector, [1, 1], activation_fn = None, normalizer_fn = None, scope='Conv2d_1c_1x1')
                logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze')
                return logits

def dense_to_one_hot(label_list, num_examples):

    length = len(label_list)
    result_label = np.zeros((length, num_examples))
    for x in range(length):
        temp = label_list[x]
        result_label[x][temp] = 1

    return np.array(result_label)

if __name__ == "__main__":

    learning_rate = 0.0001

    batch_size = 4

    capacity = 12

    dim_vector = 900

    epochs = 2
    '''
    sess = tf.InteractiveSession()
    sess.run(tf.initialize_all_variables())
    '''
    xml_file_path = "..\\doc\\train.xml"

    train_path = "..\\train"

    train_tfRecords_path = "train.tfrecords"

    test_tfRecords_path = "test.tfrecords"

    if not (os.path.isfile(train_tfRecords_path) and os.path.isfile(test_tfRecords_path)):
        print("tfrecords file开始生成...")
        input_data.create_record(xml_file_path, train_path)
    # 创建训练文件队列,不限读取的数量
    train_filename_queue = tf.train.string_input_producer(["train.tfrecords"], shuffle = True, num_epochs = epochs)#重复多少次并且在每个epoch内打乱顺序

    train_image, train_label = input_data.decode_file(train_filename_queue, batch_size = batch_size, capacity = capacity)

    train_image = tf.cast(train_image, tf.float32)

    '''
    placeholder_img = tf.placeholder("float", shape=[None, 299, 299, 3], name="placeholder_img")
    placeholder_lab = tf.placeholder("float", shape=[None, dim_vector], name="placeholder_lab")
    keep_prob = tf.placeholder("float", name="keep_prob")
	'''
    init_op = tf.group(tf.global_variables_initializer(),
                       tf.local_variables_initializer())
    count = 0
    #saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(init_op)
        #saver.restore(sess, "..\\Model\\model.ckpt")
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord = coord)

        with slim.arg_scope(inception_v3_arg_scope()) as scope:

            try:
                while not coord.should_stop():
                    train_image_value, train_label_index = sess.run([train_image, train_label])
                    train_label_value = dense_to_one_hot(train_label_index,dim_vector)

                    predictions = inception_v3(train_image_value, is_training = True, dim_vector = dim_vector, reuse = tf.AUTO_REUSE, dropout_keep_prob = 0.8)

                    correct_prediction = tf.equal(tf.argmax(predictions,1), tf.argmax(train_label_value,1))
                    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
                    loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels = train_label_value, logits = predictions))
                    total_loss = slim.losses.get_total_loss()
                    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
                    train_op = slim.learning.create_train_op(total_loss, optimizer)
                    if count % 500 == 0:

                        loss_value = loss.eval()
                        accuracy_value = accuracy.eval()
                        print(loss_value)
                        print(accuracy_value)

                    count = count + 1

                    slim.learning.train(train_op, "..\\Model\\model.ckpt")
            except tf.errors.OutOfRangeError:
                print('Done reading Training comes to end')
                print('==========================================')
            finally:
                coord.request_stop()
                #print("Model saved in file:", saver_path)

            #coord.request_stop()
            coord.join(threads)


from ..question import Question

class Series(list):

    def __init__(self, question_list=None, template_vars=None):

        if question_list is None:
            question_list = []

        if not all([isinstance(x, Question) for x in question_list]):
            raise ValueError("question_list must be a list of Questions!")

        names = [x.name for x in question_list]

        if len(set(names)) != len(question_list):
            raise ValueError("Questions must have distinct names!")

        self.template_vars = template_vars

        super(list, self).__init__(question_list)

    def ask(self):

        for q in self:
            q.ask()

    def process(self):

        for q in self:
            q.process()

    def get_question_by_name(self, name):

        if name not in [x.names for x in self]:
            return None
        else:
            return [x for x in self if x.names == name][0]

import init


from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from catboost import CatBoostRegressor
import optuna

def objective(trial):
    X_train, X_test, y_train, y_test = train_test_split(train_x, train_y, test_size=0.2)
    param = {
        "loss_function": trial.suggest_categorical("loss_function", ["RMSE", "MAE"]),
        "learning_rate": trial.suggest_loguniform("learning_rate", 1e-5, 1),
        "l2_leaf_reg": trial.suggest_loguniform("l2_leaf_reg", 1e-2, 1),
        # "colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.01, 1),
        "depth": trial.suggest_int("depth", 1, 16),
        "boosting_type": trial.suggest_categorical("boosting_type", ["Ordered", "Plain"]),
        "bootstrap_type": trial.suggest_categorical("bootstrap_type", ["Bayesian", "Bernoulli", "MVS"]),
        "min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 2, 20),
        "one_hot_max_size": trial.suggest_int("one_hot_max_size", 2, 20),
        "iterations": trial.suggest_int("iterations", 500, 5000),
        "random_strength": trial.suggest_float("random_strength", 0.1, 50),
        "rsm": trial.suggest_float("rsm", 0, 1),
        # "bagging_temperature": trial.suggest_float("bagging_temperature", 0, 1)
    }
    # Conditional Hyper-Parameters
    if param["bootstrap_type"] == "Bayesian":
        param["bagging_temperature"] = trial.suggest_float("bagging_temperature", 0, 10)
    elif param["bootstrap_type"] == "Bernoulli":
        param["subsample"] = trial.suggest_float("subsample", 0.1, 1)

    reg = CatBoostRegressor(**param)
    reg.fit(X_train, y_train, eval_set=[(X_test, y_test)], verbose=0, early_stopping_rounds=100)
    y_pred = reg.predict(X_test)
    score = r2_score(y_test, y_pred)
    return score

from sklearn.utils import resample
from sklearn.model_selection import train_test_split
import pandas as pd
from optuna.samplers import TPESampler

train = pd.read_csv("./ml.csv")
df_majority = train[train.label == 0]
df_minority = train[train.label == 1]

df_minority_upsampled = resample(df_minority,
                                 replace=True,     # sample with replacement
                                 n_samples=39325,    # to match majority class
                                 random_state=123)
df_upsampled = pd.concat([df_majority, df_minority_upsampled])
train_x = df_upsampled.drop('label', axis=1)     # 删除表中的某一行或者某一列
train_y = df_upsampled['label']
Xy = train_test_split(train_x, train_y, test_size=0.2)
train_data, test_data, train_labels, test_labels = Xy
from sklearn.metrics import roc_auc_score, accuracy_score, f1_score, precision_score, recall_score
# reg = CatBoostRegressor(**param)
# y_pred = reg.predict(test_data)
# print('AUC→',roc_auc_score(test_labels, y_pred))
# print('ACC→',accuracy_score(test_labels, y_pred))
# print('F1 score→',f1_score(test_labels, y_pred))
# print('precision→',precision_score(test_labels, y_pred))
# print('recall→',recall_score(test_labels, y_pred))

study = optuna.create_study(sampler=TPESampler(), direction="maximize")
study.optimize(objective, n_trials=100)  # Run for 10 minutes，timeout=600
print("Number of completed trials: {}".format(len(study.trials)))
print("Best trial:")
trial = study.best_trial

print("\tBest Score: {}".format(trial.value))
print("\tBest Params: ")
for key, value in trial.params.items():
    print("    {}: {}".format(key, value))

comparison of DL and ML/catboost/catbooost用optuna调参.py


from sgmtradingcore.strategies.config.configurations import BETA_CONFIG, PROD_ALGO_SPORTS_CONFIG, \
    PROD_CONFIG, DEV_CONFIG
from stratagemdataprocessing import data_api
from stratagemdataprocessing.enums.odds import Bookmakers
from stratagemdataprocessing.parsing.common.stickers import BOOKMAKER_ABBR

DEFAULT_COMMISSIONS = {
    BOOKMAKER_ABBR[Bookmakers.SBO_BET]: 0.0,

    # Commission is 5%, ignoring the Discount Rate
    BOOKMAKER_ABBR[Bookmakers.BETDAQ]: 0.05,
    BOOKMAKER_ABBR[Bookmakers.PINNACLE_SPORTS]: 0.0,
    BOOKMAKER_ABBR[Bookmakers.A3ET]: 0.0,

    # Commission is applied to the win amount on winning bets, or the lesser of the stake or potential win amount,
    # for losing bets.
    # Commission in halved if you we are posting an offer instead of matching one
    # Cricket have a different commission
    BOOKMAKER_ABBR[Bookmakers.MATCHBOOK]: 0.015,  # Only half of this for matching a bet

    # Commission is 5%, ignoring the Discount Rate which depends from volume
    BOOKMAKER_ABBR[Bookmakers.BETFAIR]: 0.05,
}

def get_current_commission(config):
    commission_dict = DEFAULT_COMMISSIONS.copy()

    trading_user_id = config['trading_user_id']
    account_ids = config['account_ids']

    curr_info = data_api.get_commission_info(trading_user_id, account_ids)

    # update values
    for key, acc_rates in curr_info.items():
        if len(set(acc_rates.values())) == 1:  # if it is the same rate for all accounts
            commission_dict[key] = acc_rates.values()[0]

    return commission_dict

def get_commission_rates_for_user(trading_user_id):
    if trading_user_id in ['default', 'test']:
        return DEFAULT_COMMISSIONS
    for conf in [BETA_CONFIG, PROD_ALGO_SPORTS_CONFIG, PROD_CONFIG,DEV_CONFIG]:
        if conf['trading_user_id'] == trading_user_id:
            break
    else:
        raise ValueError('Could not find config for trading_user_id {}'.format(trading_user_id))

    return get_current_commission(conf)

def get_net_odds(odds, bookmaker=None, is_back=True, commissions=None):
    if commissions is None:
        return odds

    bookmaker_abbr = BOOKMAKER_ABBR.get(bookmaker, None)
    rate = commissions.get(bookmaker_abbr, 0)
    if rate == 0:
        return odds

    if bookmaker == Bookmakers.MATCHBOOK:
        if is_back:
            net = 1 + (((odds - 1) * (1 - rate)) / (1 + (min(1, odds - 1) * rate)))
        else:
            net = 1 + ((odds - 1) + min(1, odds - 1) * rate) / (1 - rate)

    else:
        if is_back:
            net = ((odds - 1) * (1 - rate)) + 1
        else:
            net = ((odds - 1) / (1 - rate)) + 1

    return net

def get_gross_odds(odds, bookmaker, is_back, commissions):
    bookmaker_abbr = BOOKMAKER_ABBR[bookmaker]
    rate = commissions.get(bookmaker_abbr, 0)

    if bookmaker in (Bookmakers.BETFAIR, Bookmakers.BETDAQ):
        if is_back:
            gross = ((odds - 1) / (1 - rate)) + 1
        else:
            gross = ((odds - 1) * (1 - rate)) + 1

    elif bookmaker == Bookmakers.MATCHBOOK:
        if is_back:
            if odds >= 2:
                gross = (odds-1)*(1+rate)/(1-rate) + 1
            else:
                gross = (odds-1)/((1-rate)-(odds-1)*rate) + 1
        else:
            if odds >= 2:
                gross = (odds-1)*(1-rate) - rate + 1
            else:
                gross = (odds-1)*(1-rate)/(rate+1) + 1
    else:
        gross = odds

    return gross


import sys # для передачи argv в QApplication
import ui_lab8 # файл дизайна
from PyQt5 import QtWidgets
from collections import Counter
import string

class ExampleApp(QtWidgets.QMainWindow, ui_lab8.Ui_MainWindow):
    # Через данный метод происходит доступ к интерфейсу
    def __init__(self):
        super().__init__()
        self.setupUi(self) # инициализации дизайна
        # Назначаем функцию по нажатию
        self.button.clicked.connect(self.button_clicked)

    # Функция обработки кнопки для проверки анаграмм
    def button_clicked(self):
        positive = "Данные предложения анаграммы"
        negative = "Данные предложения НЕ анаграммы"
        what = "Данные предложения не существуют"
        first = self.first_input.text()
        second = self.second_input.text()
        if first == "" or second == "": self.output.setText(what)
        elif self.is_anagram(first, second): self.output.setText(positive)
        else: self.output.setText(negative)

    def is_anagram(self, first = None, second = None):
        print(first, second)
        # Переводим предложения в нижний регистр
        first = first.lower()
        second = second.lower()
        print(first, second)
        # Удаляем из текста знаки пунктуации и пробел
        marks = string.punctuation + ' '
        for letter in marks:
            first = first.replace(letter, '')
            second = second.replace(letter, '')
        print(first, second)
        # Проверка на соответствие длины
        if len(first) != len(second): return False
        # Преобразование в словарь подсчета
        first_counter = Counter(first)
        second_counter = Counter(second)
        print(first_counter, second_counter)
        # Возвращаем результат
        if first_counter == second_counter: return True
        else: return False

def main():
    app = QtWidgets.QApplication(sys.argv)  # новый экземпляр QApplication
    window = ExampleApp()  # создаём объект класса ExampleApp
    window.show()  # показываем окно
    app.exec_()  # запускаем приложение

# Если файл запущен напрямую
if __name__ == '__main__':
    main()


from collections import *

class Graph:
    def __init__(self):
        self.adj = defaultdict(list)
        self.dfs_found = False

    def insert(self, s, t):
        self.adj[s].append(t)
        self.adj[t].append(s)

    def get_graph(self):
        return self.adj

    def _print(self, prev : dict, s, t):
        if prev[t] == s:
            print('path: ', t)
            return

        self._print(prev, s, prev[t])
        print('path: ', t)

    def bfs(self, s, t):
        visited = set()
        prev = {}
        queue = deque([s])

        while len(queue):
            element = queue.popleft()
            for item in self.adj[element]:

                if item == t:
                    prev[item] = element
                    self._print(prev, s, t)
                    return
                elif item not in visited:
                    prev[item] = element
                    visited.add(item)
                    queue.append(item)

    def _recursive_dfs(self, visited, prev, s, t):
        if self.dfs_found:
            return

        visited.add(s)

        for node in self.adj[s]:

            if node in visited:
                continue

            prev[node] = s
            if node == t:
                self.dfs_found = True

            self._recursive_dfs(visited, prev, node, t)

    def dfs(self, s, t):
        visited = set()
        prev = {}

        self._recursive_dfs(visited, prev, s, t)

        self._print(prev, s, t)

graph = Graph()
graph.insert(1, 2)
graph.insert(1, 3)
graph.insert(2, 4)
graph.insert(2, 5)
graph.insert(3, 4)
graph.insert(4, 6)
graph.insert(5, 6)
graph.insert(6, 7)

print(graph.get_graph())
# graph.bfs(1, 7)

graph.dfs(1, 7)


import numpy as np
from numba import jit

@jit(nopython=True)
def calc_darcy_fluxes(pslwc, psnowc, psnic, pdgrain, prhofirn):
    # calc_darcy_fluxes: Calculates the amount of water (mm weq) that each layer
    # can transmit to the next one according to a Darcy flow.
    #
    #   syntax:
    #   [darcy_fluxes] = calc_darcy_fluxes (pslwc, psnowc, psnic, pdgrain, prhofirn, c)
    #
    #   input:
    #         psnowc, psnic, pslwc - vectors of respectively snow, ice and
    #         liquid water part for each subsurface layer (mm weq). Their sum
    #         for each layer should always be equal to the layer fixed water
    #         eq. thickness.
    #
    #         pdgrain - Vector of layer grain size. see graingrowth def.
    #
    #         prhofirn - vector of firn (snow) density (kg/m**3)
    #
    #         c - Structure containing all the physical, site-depant or user
    #         defined variables.
    #
    #   output:
    #         darcy_fluxes - vector containing the amount of water (mm weq) that each layer
    #         can transmit to the next one according to a Darcy flow.
    #
    #   This script was originally developped by Peter Langen (pla@dmi.dk) and
    #   Robert S. Fausto (rsf@geus.dk) in FORTRAN then translated to python by
    #   Baptiste Vandecrux (bav@geus.dk).
    #
    #   Aug. 2016
    # =========================================================================

    darcy_fluxes = np.zeros_like(pslwc)

    for jk in range(len(pslwc) - 1):  # 1:c.jpgrnd-1
        # Special treatment of top layer in case of no snow
        if (jk == 0) & (psnowc[jk] < 1e-12):
            # In case of no snow, the calculation below of K crashes. Instead we say
            # * if layer below may receive water, it gets all there is in layer 1
            # * if layer may not receive water, it all runs off.
            #
            # As long as we set darcy_fluxes[1] = pslwc[1] then this will
            # be taken care of in the perc_runoff code.
            darcy_fluxes[jk] = pslwc[jk]
        else:
            # Other layers do (should!) not come into a situation where there is only ice and water
            qlim = qlimF(
                pslwc[jk],
                pslwc[jk + 1],
                psnowc[jk],
                psnowc[jk + 1],
                psnic[jk],
                psnic[jk + 1],
                prhofirn[jk],
                prhofirn[jk + 1],
                pdgrain[jk],
                pdgrain[jk + 1],
            )
            Theta1 = ThetaF(pslwc[jk], psnowc[jk], prhofirn[jk])
            Theta2 = ThetaF(pslwc[jk + 1], psnowc[jk + 1], prhofirn[jk + 1])
            h1 = hHirF(Theta1, pdgrain[jk])
            h2 = hHirF(Theta2, pdgrain[jk + 1])

            delz1 = 999.8395 * (psnowc[jk] / prhofirn[jk] + psnic[jk] / 900)  # layer 1
            delz2 = 999.8395 * (
                psnowc[jk + 1] / prhofirn[jk + 1] + psnic[jk + 1] / 900
            )  # layer 2
            delz = (delz1 + delz2) / 2  # Midpoint-to-midpoint distance

            dhdz = (h2 - h1) / delz

            k1 = kF(Theta1, pdgrain[jk], prhofirn[jk], psnic[jk], psnowc[jk])
            k2 = kF(
                Theta2, pdgrain[jk + 1], prhofirn[jk + 1], psnic[jk + 1], psnowc[jk + 1]
            )
            k = (k1 + k2) / 2  # Average k between the two layers

            # Initial flux according to Hirashima eqn [1]
            q0 = max(k * (dhdz + 1), 0)

            # Total time-step flux according to Hirashima eqn (23)
            # and make sure it doesn't exceed available water in
            # the upper of the two layers:
            zdtime = 3600
            if qlim > 0:
                darcy_fluxes[jk] = min(
                    pslwc[jk], qlim * (1 - np.exp(-q0 / qlim * zdtime))
                )
            else:
                darcy_fluxes[jk] = 0
    return darcy_fluxes

@jit(nopython=True)
def CLliqF(rhosin):
    # Calculates per pore space volume irreducible liquid water content
    # following the parameterization by Coleou and Lesaffre (1998)
    # Cap input rho_snow at pore-close off value (830) to avoid infinite numbers
    rhos = min(rhosin, 830)
    # Porosity
    P = 1 - rhos / 900
    # Per mass parameterized Irreducible LWC
    Wm = 0.057 * P / max(1 - P, 1e-12) + 0.017
    # Per pore space volume
    return Wm / (P / max(1 - P, 1e-12)) * 900 / 999.8395 / max(1 - Wm, 1e-12)

def hetero_percol(prhofirn, psnowc, psnic, pslwc, pdgrain, c):
    # hetero_percol
    #   syntax:
    # [prhofirn, psnowc, psnic, pslwc, pdgrain] = hetero_percol (prhofirn, psnowc, psnic, pslwc, pdgrain, c)
    #   input:
    #         prhofirn - vector of firn (snow) density (kg/m**3)
    #         psnowc, psnic, pslwc - vectors of respectively snow, ice and
    #         liquid water part for each subsurface layer (mm weq). Their sum
    #         for each layer should always be equal to the layer fixed water
    #         eq. thickness.
    #         ptsoil - vector of subsurface temperature (K)
    #         pdgrain - Vector of layer grain size. see graingrowth def.
    #         pTdeep - lower boundary temperature (K). Defined by the constant
    #         T_ice_AWS so far.
    #         zrogl - total amount of run off (mm weq)
    #         c - Structure containing all the physical, site-depant or user
    #         defined variables.
    #   output:
    #          updated [prhofirn, psnowc, psnic, pslwc, ptsoil, pdgrain, zrogl]
    #   This script was originally developped by Baptiste Vandecrux (bav@geus.dk)
    # =========================================================================
    avail_water = zeros(size(prhofirn))

    # in the formulation of Marchenko et al. 2017, the liquid water is
    # distributed according to a probability funcion accross the layers before
    # the standard percolation scheme takes over. In theory the heterogeneous
    # flow could start from any layer at depth, routing water even deeper
    # That is why we commented:
    # for jk = 1:c.jpgrnd-1
    # and work with all the water located in the 1st layer
    jk = 1

    # calculating the amount of water that can be held by capillary forces
    if c.calc_CLliq:
        liqmaxloc = CLliqF(prhofirn[jk])
    else:
        liqmaxloc = c.liqmax

    liqmaxM = liqmaxloc * 999.8395 / 900 * (900 / prhofirn[jk] - 1)
    potret = max(liqmaxM * psnowc[jk], 0)
    # and what is in excess
    liqexcess = pslwc[jk] - potret
    avail_water[jk] = max(liqexcess, 0)

    # if there is available water
    if avail_water[jk] > 1e-12:
        # we draw from a binomial distribution of mode hetero_percol_p to
        # know whether this layer leads to heterogeneous percolation
        if np.random.binomial(1, c.hetero_percol_p):
            percol_water = c.hetero_percol_frac * avail_water[jk]
            # note: dflux is positive when it leaves the layer

            # determine random depth between current layer and maximum depth range
            thickness_act = psnowc * (999.8395 / prhofirn) + psnic * (999.8395 / 900)
            depth_act = np.zeros_like(thickness_act)
            depth_act[1] = thickness_act[1] / 2
            for i in range(1, len(pslwc)):  # 2:size(thickness_act,1)
                depth_act[i] = np.sum(thickness_act[:i]) + thickness_act[i] / 2

            depth_current = depth_act[jk]
            depth_dest = c.hetero_percol_dist  # * rand(1,1) + depth_current
            # find index of layer at closest depth to the destination of
            # percolation
            ind_dest = np.argmin(np.abs(depth_act - depth_dest))

            # sav.depth_current = depth_current
            # sav.depth_dest = depth_dest

            # In the percolation scheme of Marchenko et al. (2017) the meltwater is
            # redistributed from the surface down to a specified destination depth
            # according to a probability def

            # in an uniform distribution def, the subsurface layers receive water
            # proportional to their thickness:

            # pslwc[jk] = pslwc[jk] - avail_water[jk]
            # frac_received = thickness_act(jk:ind_dest)./sum(thickness_act(jk:ind_dest))
            # pslwc(jk:ind_dest) = pslwc(jk:ind_dest) + avail_water[jk]*frac_received

            # an alternative is to go through the stratigraphy and stop when there is a
            # gradient in grain size or an ice layer
            for ii in range(jk, ind_dest):  # = jk:ind_dest-1
                # here we test all the layer through which the pipe travels
                if prhofirn(ii + 1) > 800:
                    # fprintf('ice - ')
                    break
                    # elseif psnic(ii+1)> c.ice_threshold
                    # plus relative to frozen mass
                    # if there is too much ie in the next layer
                    #                     fprintf('ice - ')
                    #                     break
                    #                 elseif ThetaF(pslwc(ii+1), psnowc(ii+1), prhofirn(ii+1), c) >= 1
                    # if there is a saturated layer piping can't go through
                    # it
                    #                     fprintf('sat - ')
                    #                     break
                    # PERMEABILITY? h?
                    #                 elseif pdgrain(ii)-pdgrain(ii+1) < c.crit_diff_grain
                    #                     fprintf('grain - ')
                    #                     break

            # if ind_dest ~= ii:
            #     print('Piping stopped at layer#i instead of#i\n',ii, ind_dest)
            ind_dest = ii
            jj = ind_dest
            while (jj > jk) & (percol_water > 1e-12):
                # Calculate water in destination layer, when this is at saturation (Theta = 1):
                plsat = psnowc[jj] * 999.8395 / 900 * (900 / prhofirn[jj] - 1)
                # Do not allow flux to be greater than plsat-pl in next layer.
                dflux = min(max(0, plsat - pslwc[jj]), percol_water)

                pslwc[jk] = pslwc[jk] - dflux
                pslwc[jj] = pslwc[jj] + dflux
                percol_water = percol_water - dflux
                jj = jj - 1
    return pslwc

@jit(nopython=True)
def hHirF(Theta, d):
    # The F in the name hHirF stands for "def"
    # calculates hydraulic suction h (in m) ac.ccording to
    # Hirashima et al 2010.
    alpha = 7.3 * np.exp(1.9)
    #  Hirashima (15)
    n = nHirF(d)
    m = 1 - 1 / n
    #  Hirashima (9)
    Theta_nozero = max(Theta, 1e-12)  # ! To avoid divide-by-zero
    return 1 / alpha * (Theta_nozero ** (-1 / m) - 1) ** (1 / n)  # ! Hirashima (9)

@jit(nopython=True)
def kF(Theta, d, rhos, pi, ps):
    # The F in the name stands for "def"
    # Permeability as in Hirashima 2010, using units on Ks as in
    # Calonne (2012) and correction for ice layering using Colbeck 1975 (eqn 32)
    # Saturated hydraulic conductivity of snow (m/s) as fitted by Shimizu (1970). Here
    # units are as in Calonne et al (2012) and d/1000 is the grain diameter in m. It
    # corresponds to H10-eqn3 with units as in Calonne
    # ks_shim = 9.82/1.79e-06*0.077*(d/1000.)**2. * np.exp(-7.8e-3*rhos)
    # Permeability according to Calonne (2012)
    ks = 3 * (d / 2000) ** 2 * 9.82 / 1.79e-06 * np.exp(-0.013 * rhos)

    # Unsaturated correction to conductivity. Hirashima eqn 10
    n = nHirF(d)
    m = 1 - 1 / n  # Hirashima (9)
    kr = Theta ** 0.5 * (1.0 - (1.0 - Theta ** (1.0 / m)) ** m) ** 2  # Hirashima eqn 10

    # Unsaturated hydraulic conductivity of the snow. Hirashima eqn 11
    k11 = kr * ks

    # Factor to divide k11 by to account for ice lenses within the
    # layer. Colbeck 1975 eqn 32
    Hs = ps / rhos  # total depth of snow in layer
    Hi = pi / 900  # total depth of ice in layer
    fsnow = Hs / (Hs + Hi)  # Fraction of layer that is snow
    whwice = 0.1  # scaling constant from colbeck
    if k11 > 0:
        k22factor = fsnow + (1 - fsnow) * (1.0 + whwice) / (0.0 / k11 + whwice)
    else:
        # If k11 is 0 (because Theta is 0) then set to 1, so kF = 0/1 = 0 in next line
        k22factor = 1
    # Effective hydraulic conductivity (in vertical direction perpicular to
    # ice lenses) in snow-ice-sublayered model. Colbeck 1975 eqn 32
    return k11 / k22factor

@jit(nopython=True)
def nHirF(d):
    # calculates n as in Hirashima et al 2010.
    return 15.68 * np.exp(-0.46 * d) + 1  # Hirashima (17)

@jit(nopython=True)
def qlimF(pl1, pl2, ps1, ps2, pi1, pi2, rhos1, rhos2, d1, d2):
    # The F in the name stands for "def"
    # Calculates Hirashima (2010) qlim in eqn 20  iteratively

    # Physical layer thicknesses (m)
    delz1 = 999.8395 * (ps1 / rhos1 + pi1 / 900)  # layer 1
    delz2 = 999.8395 * (ps2 / rhos2 + pi2 / 900)  # layer 2
    delz = (delz1 + delz2) / 2  # Midpoint-to-midpoint distance

    # First, see if there is a solution, by moving all in upper layer down.
    # If this provides positive h1-(h2+delz) then there is a solution
    qlim = pl1

    pl1test = pl1 - qlim
    pl2test = pl2 + qlim
    Theta1 = ThetaF(pl1test, ps1, rhos1)
    Theta2 = ThetaF(pl2test, ps2, rhos2)
    h1 = hHirF(Theta1, d1)
    h2 = hHirF(Theta2, d2)
    diff = h1 - (h2 + delz)
    if diff < 0:
        Conv = 1  # If moving everything isn't enough for equilibrium, move everything and do no more
        qlimOut = pl1
    else:
        Conv = (
            0  # If it is enough, we haven't converged yet and we start iteration below
        )

    if Conv == 0:
        # First guess is half of water in top layer
        qlim = pl1 / 2
        qlimL = 0
        qlimR = pl1

        Nmax = 11  # Number of iterations (usually 10 suffices since
        # we are halving intervals and 0.5**9 - 0.5**10 = 9.7656e-04 < 0.001)

        for i in range(Nmax):  # 1:Nmax
            pl1test = pl1 - qlim
            pl2test = pl2 + qlim
            Theta1 = ThetaF(pl1test, ps1, rhos1)
            Theta2 = ThetaF(pl2test, ps2, rhos2)
            h1 = hHirF(Theta1, d1)
            h2 = hHirF(Theta2, d2)
            diff = h1 - (
                h2 + delz
            )  # Difference between LHS and RHS in Hirashima eqn 20

            # If positive, we moved too much, and  qlim becomes new right  point
            # if negative, we moved too little, and qlim becoms new left :
            if diff > 0:
                qlimR = qlim
            else:
                qlimL = qlim

            # New value is halfway between new interval  points
            qlim = (qlimR + qlimL) / 2

        # Set final output qlim to iterated value:
        qlimOut = qlim
    return qlimOut

@jit(nopython=True)
def ThetaF(pl, ps, rhos):
    # The F in the name stands for "def"
    # Calculates effective water saturation.
    # Force Theta to be between 0 and 1
    # Calculate liqmax according to Coleou and Lesaffre?
    # liqmaxloc is the value of liqmax used locally here
    # if c.calc_CLliq:
    liqmaxloc = CLliqF(rhos)
    # else:
    #     liqmaxloc = c.liqmax
    if ps > 1e-12:
        # Force Theta to be between 0 and 1
        ThetaF = min(
            1,
            max(
                0,
                (
                    (
                        pl / ps * rhos * 900 / 999.8395 / max(1e-12, 900 - rhos)
                        - liqmaxloc
                    )
                    / (1 - liqmaxloc)
                ),
            ),
        )
    else:
        # If there is no snow, write out Theta=1 to avoid divide-by-zero
        ThetaF = 1
    return ThetaF

@jit(nopython=True)
def perc_runoff_new(prhofirn, psnowc, psnic, pslwc, pdgrain):
    # perc_runoff_new: Calculates meltwater percolation and runoff in the column
    # either according to a standard bucket scheme or to a Darcy-like bucket
    # scheme. Update BV2017: no mass shift anymore, the water is
    # moving from one layer to the next and layer's total mass is allowed to change.
    # At the  of the routine, it is checked that no layer has a mass lower
    # than lim_old_lay. If one is found too small, it is merged with its
    # underlying layer and another layer is split elsewhere.
    #
    #   syntax:
    #   [prhofirn, psnowc, psnic, pslwc, ptsoil, pdgrain, pTdeep, zrogl] =
    #     perc_runoff_new (prhofirn, psnowc, psnic, pslwc, ptsoil,#           pdgrain, pTdeep, c.ElevGrad, zrogl, c)
    #
    #   input:
    #         prhofirn - vector of firn (snow) density (kg/m**3)
    #
    #         psnowc, psnic, pslwc - vectors of respectively snow, ice and
    #         liquid water part for each subsurface layer (m weq).
    #
    #         ptsoil - vector of subsurface temperature (K)
    #
    #         pdgrain - Vector of layer grain size. see graingrowth def.
    #
    #         pTdeep - lower boundary temperature (K). Defined by the constant
    #         T_ice_AWS so far.
    #
    #         zrogl - total amount of run off (mm weq)
    #
    #         c - Structure containing all the physical, site-depant or user
    #         defined variables.
    #
    #   output:
    #          updated [prhofirn, psnowc, psnic, pslwc, ptsoil, pdgrain, zrogl]
    #
    #   This script was originally developped by Peter Langen (pla@dmi.dk) and
    #   Robert S. Fausto (rsf@geus.dk) in FORTRAN then translated to python by
    #   Baptiste Vandecrux (bav@geus.dk).
    # =========================================================================

    # ======================================================
    # Here we do liquid water percolation and runoff
    # ======================================================
    # *** Calculate potential Darcy fluxes for all columns ***
    #  (if do-no-darcy, then fluxes will be calculated on-the-fly in loops below)
    # This calculation makes sure potential darcy flux across interfaces does
    # not exceed the water amount in the upper of the two layers

    if np.sum(pslwc) < 1e-12:
        return prhofirn, psnowc, psnic, pslwc, pdgrain, 0

    # if do_no_darcy==0:
    darcy_fluxes = calc_darcy_fluxes(pslwc, psnowc, psnic, pdgrain, prhofirn)

    # Update BV2017: t_runoff is now calculated outside of the subsurface scheme
    # Bottom layer: Receive from above. Give excess liquid to runoff.
    jk = len(pslwc) - 1
    zrogl = 0
    # Remove runoff from layer (and add to runoff-box zrogl)
    # Adjust bottom layer interface due to removal of mass
    # PLA Darcy 2016
    # if c.calc_CLliq:
    liqmaxloc = CLliqF(prhofirn[jk])
    # else:
    #     liqmaxloc = c.liqmax

    liqmaxM = liqmaxloc * 999.8395 / 900 * (900 / prhofirn[jk] - 1)
    potret = max(liqmaxM * psnowc[jk], 0)
    # Calculate liqexcess from layer water. Make sure it is not negative:
    liqexcess = max(pslwc[jk] - potret, 0)

    t_runoff = 28513.796102033262
    zdtime = 3600
    do_no_darcy = 0
    avoid_runoff = 0

    liqro = liqexcess / t_runoff * zdtime
    # Take runoff from water content and give to runoff box (Update PLA)
    zrogl = zrogl + liqro
    pslwc[jk] = pslwc[jk] - liqro

    for jk in range(len(pslwc) - 2, -1, -1):  # c.jpgrnd-1:-1:1
        # BV2017 removing percolation blocking criteria
        if ThetaF(pslwc[jk + 1], psnowc[jk + 1], prhofirn[jk + 1]) >= 1:
            # if next layer already saturated, then we do not allow flux
            # into that layer, but instead activate runoff
            dflux = 0
            do_runoff = 1
        else:
            if do_no_darcy:
                # Potential Darcy-like flux in case of do-no-Darcy,
                # basically just all liqexcess:
                # PLA Darcy 2016
                # if (c.calc_CLliq):
                liqmaxloc = CLliqF(prhofirn[jk])
                # else:
                #    liqmaxloc = c.liqmax
                liqmaxM = liqmaxloc * 999.8395 / 900 * (900 / prhofirn[jk] - 1)
                potret = max(liqmaxM * psnowc[jk], 0)
                liqexcess = pslwc[jk] - potret
                darcy_fluxes[jk] = max(liqexcess, 0)

            # Calculate water in next layer, when this is at saturation (Theta = 1):
            plsat = psnowc[jk + 1] * 999.8395 / 900 * (900 / prhofirn[jk + 1] - 1)

            # Do not allow flux to be greater than plsat-pl in next layer.
            # Also, do not allow it to be negative
            dflux = max(min(darcy_fluxes[jk], plsat - pslwc[jk + 1]), 0)

            # Update BV2017: if no snow to hold liquid water then runoff is
            # turned on
            if (darcy_fluxes[jk] >= plsat - pslwc[jk + 1]) | (psnowc[jk] < 1e-12):
                # There is enough darcy flow to fill up layer below (and perhaps more)
                # so runoff should be activated (on what's left here after
                # we have moved down enough to fill layer below):
                do_runoff = 1
            else:
                # No runoff from this layer, since darcy flow is not large enough
                # to fill up layer below
                do_runoff = 0

        if dflux > 0:
            # Yes: Darcy flow to next layer
            # Update BV2017: Now temperature is not updated. water
            # percolating is at 0degC cannot change temperature until phase
            # change occurs in refreezing scheme
            pslwc[jk + 1] = pslwc[jk + 1] + dflux
            pslwc[jk] = pslwc[jk] - dflux

        if do_runoff & (~avoid_runoff):
            # Yes: Remove runoff from layer (and add to runoff-box zrogl)
            # PLA Darcy 2016
            # if c.calc_CLliq:
            liqmaxloc = CLliqF(prhofirn[jk])
            # else:
            #     liqmaxloc = c.liqmax

            liqmaxM = liqmaxloc * 999.8395 / 900 * (900 / prhofirn[jk] - 1)
            potret = max(liqmaxM * psnowc[jk], 0)

            # Calculate liqexcess from layer water. Make sure it is not negative:
            # Update BV2017: since dflux has already left slwc[jk] so no
            # need to remove it anymore (compared to old version)
            liqexcess = max(pslwc[jk] - potret, 0)

            # Update BV2017: for all layer, if there is no snow to hold
            # liquid water then runoff is instantaneous (not allowing
            # subglacial lakes to form
            if psnowc[jk] < 1e-12:
                # Here in layer: If there is no snow, run off immediately
                # in other word surface runoff is instantaneous
                liqro = liqexcess
            else:
                Theta = ThetaF(
                    pslwc[jk],
                    psnowc[jk],
                    prhofirn[jk],
                )
                # liqro_darcy = kF(Theta,pdgrain[jk],prhofirn[jk],psnic[jk],psnowc[jk], c) * c.ElevGrad
                # old version based on Zuo and Oerlemans (1996)
                liqro_darcy = liqexcess / t_runoff * zdtime

                liqro = min(liqro_darcy, liqexcess)
                pore_space = psnowc[jk] * 999.8395 * (1 / prhofirn[jk] - 1 / 900)

                # Update PLA
                if pslwc[jk] - liqro > pore_space:
                    liqro = pslwc[jk] - pore_space

            # Take runoff from water content and give to runoff box
            zrogl = zrogl + liqro
            pslwc[jk] = pslwc[jk] - liqro
    return prhofirn, psnowc, psnic, pslwc, pdgrain, zrogl


import random
import time
a1, a2 = [], []

def setup(n):
    global a1, a2
    a1 = random.sample(range(0, 2*n), n)
    a2 = random.sample(range(0, 2 * n), n)

def common_items():

    common = []
    for item in a1:
        if item in a2:
            common.append(item)

def test_function():

    list_time = []
    for _ in range(10):
        start = time.time()
        common_items()
        end = time.time()
        list_time.append(end - start)
    return sum(list_time)/(len(list_time))

if __name__ == "__main__":

    # Time the function with input of size 100 elements
    setup(100)
    val = test_function()
    print(val)

    # Time the function with input of size 1000 elements
    setup(1000)
    val = test_function()
    print(val)

    # Time the function with input of size 10000 elements
    setup(10000)
    val = test_function()
    print(val)


class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        d = defaultdict(list)
        for str in strs:
            asciis = [0] * 26
            for c in str:
                idx = ord(c) - ord('a')
                asciis[idx] = asciis[idx] + 1

            key = tuple(asciis)
            d[key].append(str)

        return d.values()


from guardian.shortcuts import assign_perm
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from permissions.services import APIPermissionClassFactory
from hosts.models import Host
from hosts.serializers import HostSerializer

class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer
    permission_classes = (
        APIPermissionClassFactory(
            name='HostPermission',
            permission_configuration={
                'base': {
                    'create': 'hosts.add_host',
                    'list': True,
                },
                'instance': {
                    'retrieve': True,
                    'destroy': 'hosts.delete_host',
                    'update': 'hosts.change_host',
                    'partial_update': 'hosts.change_host',
                }
            }
        ),
    )


import os

from pyltp import SentenceSplitter
from pyltp import Segmentor
from pyltp import Postagger
from pyltp import NamedEntityRecognizer
import jieba

LTP_DATA_DIR = "D:\\Anaconda\\Lib\\site-packages\\ltp\\3.4"
text = "元芳你怎么看？我就趴窗口上看呗！"

def split(text):
    return SentenceSplitter.split(text)

def cut(sentences):
    return jieba.cut(sentences)

def segment(sentences):
    cws_model_path = os.path.join(LTP_DATA_DIR, "cws.model")
    lexicon_path = os.path.join(LTP_DATA_DIR, "lexicon.txt")

    segmentor = Segmentor()
    # segmentor.load(cws_model_path)
    segmentor.load_with_lexicon(cws_model_path, lexicon_path)
    words = segmentor.segment(sentences)
    segmentor.release()
    return words

def pos(words):
    pos_model_path = os.path.join(LTP_DATA_DIR, "pos.model")

    postagger = Postagger()
    postagger.load(pos_model_path)
    postags = postagger.postag(words)
    postagger.release()
    return postags

def ner(words, postags):
    ner_model_path = os.path.join(LTP_DATA_DIR, "ner.model")

    recognizer = NamedEntityRecognizer()
    recognizer.load(ner_model_path)
    netags = recognizer.recognize(words, postags)
    recognizer.release()
    return netags

def match(tokens, tag, tags, word, namedentity):
    if tokens[0] == "B":
        tags += [tag]
        namedentity += [word]
    elif tokens[0] == "I":
        tags += [tag]
        namedentity += [word]
    elif tokens[0] == "E":
        tags += [tag, " "]
        namedentity += [word, " "]
    else:
        tags += [tag, " "]
        namedentity += [word, " "]
    return tags, namedentity

def recognize(words, netags):
    namedentity = []
    tags = []
    for word, tag in zip(words, netags):
        if tag != "O":
            tokens = tag.split("-")
            if tokens[1] == "Nh":
                tags, namedentity = match(tokens, tag, tags, word, namedentity)
            elif tokens[1] == "Ni":
                tags, namedentity = match(tokens, tag, tags, word, namedentity)
            else:
                tags, namedentity = match(tokens, tag, tags, word, namedentity)

    namedentity = "".join(namedentity).split()
    tags = [tag.split("-")[-1] for tag in "".join(tags).split()]
    return dict(zip(namedentity, tags))


from rest_framework import status
from helpers.response import Response
from helpers.permissions import IsAdminUser, IsUser

from .models import Organization
from .serializers import OrganizationSerializer

from event.service import EventService

class OrganizationService:
    @classmethod
    def create_organization(cls, user, **kwargs):

        existing_record = Organization.objects.filter(name=kwargs.get("name")).first()
        if existing_record:
            return Response(
                errors={"error": "Organization with this name already exists"}
            )

        organization = Organization.objects.create(
            name=kwargs.get("name"),
            description=kwargs.get("description"),
            category=kwargs.get("category"),
            owner=user,
        )
        return Response(data=OrganizationSerializer(instance=organization).data)

    @classmethod
    def get_organization(cls, **kwargs):
        return Organization.objects.filter(**kwargs).first()

    @classmethod
    def list_organization(cls, **kwargs):
        return Organization.objects.filter(**kwargs)

    @classmethod
    def update_organization(cls, organization_id, **kwargs):
        organization = Organization.objects.filter(id=organization_id).first()
        organization.name = kwargs.get("name", "")
        organization.description = kwargs.get("description", "")
        organization.category = kwargs.get("category", "")
        organization.save()
        return organization

    @classmethod
    def get_events_by_organization(cls, org_id):
        """
        This method returns a list of all the events that belongs to an organization
        """
        organization = cls.get_organization(id=org_id)
        return EventService.get_events(organization=organization, status="ACTIVE")


class Solution:
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        arr = [i for i in range(1, n+1)]
        facs = [0]
        ret = ''
        tmp = 1
        for i in range(1, 10):
            tmp *= i
            facs.append(tmp)
        for i in range(n-1, 0, -1):
            iteration = k // facs[i]
            k %= facs[i]
            if k != 0:
                ret += str(arr[iteration])
                arr.pop(iteration)
            else:
                ret += str(arr[iteration-1])
                arr.pop(iteration-1)
        ret += str(arr[0])
        return ret


from re import S
from tracemalloc import start
from science_utils_k.echarts.EChart import EChart
from science_utils_k.utils import princess
import time
import os

class LineChart(EChart):

    def __init__(self, global_args=None, options=None):
        super(LineChart, self).__init__(global_args)
        if options == None:
            self.options = {
                'title': {
                    'text': '',
                },
                'tooltip': {},
                'legend': {},
                'xAxis': {
                    'name': "epoch",
                    'nameLocation': "end",
                    'data': None,
                    'axisLabel': {
                        'show': 'true'
                    }
                },
                'yAxis': {},
                'series': None
            }
        else:
            self.options = options

    def get_options(self):
        return self.options

    def set_options(self, attrs, values):
        for attr, value in zip(attrs, values):
            # print(attr)
            # print(value)
            attr = attr.split(".")
            princess.set_attr(self.options, attr, value)

    def output(self, time_stamp,type="html", log_root_path="log"):

        o_path = log_root_path + "/"+time_stamp
        if type == "html":
            if not os.path.exists("log"):
                os.makedirs("log")
            if time_stamp not in os.listdir("log"):
                os.makedirs(o_path)

            if "html" not in os.listdir(o_path):
                os.makedirs(o_path+"/html")
            if "js" not in os.listdir(o_path+"/html"):
                os.makedirs(o_path+"/html/js")
            # os.makedirs(o_path+"/html/js/")

            # 如果main.html已存在，从以有文件读入html。否则使用默认html模板
            if "main.html" in os.listdir(o_path+"/html"):
                echart_html = princess.echart2html(self,log_path=o_path)
            else:
                echart_html = princess.echart2html(self)

            # write html file
            fd = open(o_path+"/html/main.html", "w")
            fd.write(str(echart_html))
            fd.close()

            # write js file
            fd = open(o_path+"/html/js/charts_cfg.js","a")
            fd.write(princess.js_init_echart(self))
            fd.write(princess.js_init_chartOption(self))
            fd.close()


# -*- coding: utf-8 -*-
"""
Created on Sat Apr  1 11:13:44 2017

@author: rstreet
"""

from os import getcwd, path, remove, environ
from sys import path as systempath
cwd = getcwd()
systempath.append(path.join(cwd,'..'))
import observation_classes, log_utilities
import socket

def test_obs_build():

    config = get_test_config()
    log = log_utilities.start_day_log( config, 'test_obs' )

    obs = get_test_obs_request()
    log.info(obs.summary())

    ur = obs.build_cadence_request( log=log, debug=True )
    status = obs.submit_request( ur, config, log=log )

    log_utilities.end_day_log( log )

def get_test_config():

    host_name = socket.gethostname()
    if 'rachel' in host_name:
        logdir = '/Users/rstreet/ROMEREA/Logs/2017'
    else:
        logdir = '/var/www/robonetsite/logs/2017'

    config = {'log_root_name': 'test_obs',
              'log_directory': logdir,
              'simulate': 'false'}
    return config

def get_test_obs_request():

    obs = observation_classes.ObsRequest()
    obs.name = 'ROME-FIELD-01'
    obs.ra = '17:51:20.6149'
    obs.dec = '-30:03:38.9442'
    obs.site = 'lsc'
    obs.observatory= 'doma'
    obs.tel = '1m0'
    obs.instrument = 'fl15'
    obs.instrument_class = '1M0-SCICAM-SINISTRO'
    obs.set_aperture_class()
    obs.filters = [ 'SDSS-g', 'SDSS-r', 'SDSS-i' ]
    obs.exposure_times = [ 300.0, 300.0, 300.0 ]
    obs.exposure_counts = [ 1, 1, 1 ]
    obs.cadence = 4.0
    obs.jitter = 1.0
    obs.priority = 1.0
    obs.ttl = 7.0
    obs.user_id = 'tester@lco.global'
    obs.token = 'foobar'
    obs.proposal_id = 'TEST2017-001'
    obs.focus_offset = [ 0.0, 0.0, 0.0 ]
    obs.request_type = 'L'
    obs.req_origin = 'obscontrol'
    obs.get_group_id()

    return obs

if __name__ == '__main__':
    test_obs_build()


# Solution 1 (30 ms, 13.9 MB)

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        arr = Counter(text)
        dict1 = dict([(idx, val) if idx in 'ban' else (idx, val//2) for idx, val in arr.items() if idx in 'balon'])
        if len(dict1) == 5:
            return min(dict1.values())
        else:
            return 0


class EmptyStackException(Exception):
    pass

class EmptyQueueException(Exception):
    pass

class Node:

    def __init__(self, value):
        self.value = value
        self.next = None

class Stack:

    def __init__(self):
        self.top = None

    def push(self, value):

        node = Node(value)
        node.next = self.top
        self.top = node

    def pop(self):

        if not self.top:
            raise EmptyStackException("Nothing to pop ,Empty Stack")

        temp = self.top
        self.top = self.top.next
        temp.next = None
        return temp.value

    def is_empty(self):

        return True if self.top is None else False

    def peek(self):

        if self.is_empty() == False:
            return self.top.value
        else:
            raise EmptyStackException("No peek, Empty Stack")

    def __str__(self):
        current = self.top
        items = ''

        while current:
            items += str(current.value) + ' - '
            current = current.next

        return items

class Queue:
    def __init__(self):
        self.front = None
        self.rear = None

    def enqueue(self, value):
        node = Node(value)
        if self.front is None:
            self.front = node
            self.rear = node
        else:
            self.rear.next = node
            self.rear = node

    def is_empty(self):
        return True if self.front is None else False

    def peek(self):
        if self.is_empty():
            raise EmptyQueueException('Empty Queue')
        else:
            return self.front.value

    def dequeue(self):
        if self.is_empty():
            raise EmptyQueueException('Queue Empty')
        else:
            dequeued = self.front
            self.front = self.front.next
        return dequeued.value

    def __str__(self):
        current = self.front
        items = ''
        while current:
            items += str(current.value) + ' - '
            current = current.next

        return items

#
# if __name__ == '__main__':
#     stack = Stack()
#     print(stack.is_empty())
#     queue = Queue()
#     print(stack.is_empty())


class Tree:
    def __init__(self, children: dict, is_end: bool):
        self.children = children
        self.is_end = is_end

class WordDictionary:
    def __init__(self):
        self._tree: Tree = Tree({}, False)

    def addWord(self, word: str) -> None:
        tree = self._tree
        for s in word:
            if s not in tree.children:
                tree.children[s] = Tree({}, False)
            tree = tree.children[s]
        tree.is_end = True

    def search(self, word: str, tree: Tree = None) -> bool:
        if not tree:
            tree = self._tree

        if not (word and tree.children):
            return not word and tree.is_end

        if word[0] == ".":
            for child in tree.children.values():
                if self.search(word[1:], child):
                    return True
            return False

        if word[0] not in tree.children:
            return False

        return self.search(word[1:], tree.children[word[0]])


import unicodedata

from django.http import HttpRequest

from events.utils import (
    get_business_id,
    get_organization_name,
    PROVIDER_BUSINESS_ID_FIELD,
    PROVIDER_NAME_FIELD,
)

EVENT_BASE_DATA = {
    "offers": [
        {
            "is_free": True,
            "price": {"fi": "", "sv": "", "en": ""},
            "description": {"fi": "", "sv": "", "en": ""},
            "info_url": None,
        }
    ],
}

CREATE_EVENT_BASE_DATA = {
    "event_status": "EventScheduled",
    "type_id": "General",
    "data_source": "tet",
    "in_language": [{"@id": "http://localhost:8080/v1/language/fi/"}],
}

def _new_from(obj, keys):
    new = {}
    for key in keys:
        new[key] = obj[key]
    return new

def _shorten_description(descobj):
    shortened_obj = {}
    for lang in descobj.keys():
        desc = descobj[lang]
        if len(desc) <= 125:
            shortened_obj[lang] = desc
        else:
            shortened_obj[
                lang
            ] = f"{desc[:125]}{unicodedata.lookup('Horizontal ellipsis')}"

    return shortened_obj

def _set_event_owner(event, request):
    user = request.user

    if user.is_staff:
        if user.email:
            event["custom_data"]["editor_email"] = user.email
        # In TET settings we specify `USERNAME_CLAIM = "oid"`, which sets the user's object identifier as
        # Django username. This is added to provide "event ownership info" in case user.email is empty.
        event["custom_data"]["editor_oid"] = user.username

        event["provider"] = {
            PROVIDER_NAME_FIELD: get_organization_name(request),
        }
    else:  # user is logged in via suomi.fi
        event["provider"] = {
            PROVIDER_NAME_FIELD: get_organization_name(request),
            PROVIDER_BUSINESS_ID_FIELD: get_business_id(request),
        }

def enrich_create_event(event, publisher, request: HttpRequest):
    event.update(EVENT_BASE_DATA)
    event.update(CREATE_EVENT_BASE_DATA)

    if "publication_status" not in event or event["publication_status"] is None:
        event["publication_status"] = "draft"

    event["publisher"] = publisher
    event["short_description"] = _shorten_description(event["description"])

    _set_event_owner(event, request)

    return event

def enrich_update_event(event, request):
    event.update(EVENT_BASE_DATA)
    event["short_description"] = _shorten_description(event["description"])

    _set_event_owner(event, request)

    # Not sure why it resets publication status from draft to public without the following line
    # This is not a problem because we keep the two in sync
    # publication_status is what decides whether the event is shown in Youth UI
    event["publication_status"] = "public" if event["date_published"] else "draft"
    return event

def reduce_get_event(event):
    tetevent = _new_from(
        event,
        (
            "id",
            "name",
            "description",
            "location",
            "keywords",
            "date_published",
            "start_time",
            "end_time",
            "custom_data",
            "publication_status",
            "in_language",
            "images",
            "provider",
        ),
    )

    return tetevent


from rsf.proj import *

#==============================================================
# job running parameters
par = dict(
    ns=2801,
    dt=0.0005,

    isep1=0,
    isep2=1,
    ihomo=0,
    tapertype="TTI",
    nstep=2,

    seed=2012,
    npk=50,
    eps=1.0e-6,

	n2w=1,
	o2w=50.5,

    )
# =============================================================
# download Hess VTI models from 'ftp://software.seg.org'
# Depth grid: 1501
# Horizontal grid: 3617
# Vertical and horizontal spacing are both 20ft.

import bptti2007

bptti2007.get_model('Vp Vs Epsilon Delta Theta')

# =============================================================
# produce vp0 & vs0 model by scaling vp model
Flow('vp0','Vp',
     '''
     smooth rect1=8 rect2=8
     ''')

Flow('vs0','Vs',
     '''
     smooth rect1=8 rect2=8
     ''')

Flow('epsi','Epsilon',
     '''
     smooth rect1=8 rect2=8
     ''')

Flow('del','Delta',
     '''
     smooth rect1=8 rect2=8
     ''')

Flow('the','Theta',
     '''
     smooth rect1=8 rect2=8
     ''')

name0='''
vp0 vs0
'''

name00='''
epsi del the
'''

for ff in Split(name0):
        Result(ff,
	'''
	grey color=j scalebar=y bias=1.5 allpos=n barreverse=y wanttitle=n}
	''')

for gg in Split(name00):
        Result(gg,
	'''
	grey color=j scalebar=y allpos=n barreverse=y wanttitle=n}
	''')

# =================================================================================
# Forward modeling using original elastic wave eq.
# =================================================================================
name1='''
Elasticx Elasticz ElasticSepP ElasticSepSV
'''

Flow(['Elasticx', 'Elasticz', 'ElasticSepP', 'ElasticSepSV'],
         'vp0  vs0  epsi del the',
         '''
         tti2delrsep
         vp0=${SOURCES[0]}
         vs0=${SOURCES[1]}
         epsi=${SOURCES[2]}
         del=${SOURCES[3]}
         the=${SOURCES[4]}
         Elasticz=${TARGETS[1]}
         ElasticSepP=${TARGETS[2]}
         ElasticSepSV=${TARGETS[3]}
         ns=%d
         dt=%g
		 eps=%g
		 seed=%d
		 npk=%d
         ''' % (par['ns'],par['dt'],par['eps'],par['seed'],par['npk'])
    )

for qq in Split(name1):
        Result(qq,
	'''
	grey polarity=n scalebar=n screenratio=1 wanttitle=n }
	''')

Flow('ElasticSepSVwave','ElasticSepSV',
        '''
        window n2=%d min2=%g
        ''' % (par['n2w'],par['o2w']))

Result('ElasticSepSVwave',
        '''
        graph label1=Z title='Scalar qSV-wave from elastic field' label2=Amplitude screenratio=0.4
        ''')

name2='''
PseudoPureSVx PseudoPureSVz
PseudoPureSV PseudoPureSepSV
PseudoPureSepSVx PseudoPureSepSVz
'''

Flow(['PseudoPureSVx',  'PseudoPureSVz',  'PseudoPureSV', 'PseudoPureSepSV', 'PseudoPureSepSVx', 'PseudoPureSepSVz'],
         'vp0  vs0  epsi del the',
         '''
         tti2dpseudosvlrsep
         vp0=${SOURCES[0]}
         vs0=${SOURCES[1]}
         epsi=${SOURCES[2]}
         del=${SOURCES[3]}
         the=${SOURCES[4]}
         PseudoPureSVz=${TARGETS[1]}
         PseudoPureSV=${TARGETS[2]}
         PseudoPureSepSV=${TARGETS[3]}
         PseudoPureSepSVx=${TARGETS[4]}
         PseudoPureSepSVz=${TARGETS[5]}
         ns=%d
         dt=%g
         npk=%d
         eps=%g
         ''' % (par['ns'],par['dt'],par['npk'],par['eps'])
		 )

for qq in Split(name2):
        Result(qq,
	'''
	grey polarity=n scalebar=n screenratio=1 wanttitle=n }
	''')

Flow('PseudoPureSVwave','PseudoPureSV',
        '''
        window n2=%d min2=%g
        ''' % (par['n2w'],par['o2w']))

Result('PseudoPureSVwave',
        '''
        graph label1=Z title='Scalar pseudo-pure-mode qSV-wave' label2=Amplitude screenratio=0.4
        ''')

Flow('PseudoPureSepSVwave','PseudoPureSepSV',
        '''
        window n2=%d min2=%g
        ''' % (par['n2w'],par['o2w']))

Result('PseudoPureSepSVwave',
        '''
        graph label1=Z title='Scalar qSV-wave from pseudo-pure-mode fields' label2=Amplitude screenratio=0.4
        ''')
End()


import json
import random
"""
变量的类型注解
"""

# 基础数据类型注解
var_1: int = 10
var_2: float = 12.32
var_3: bool = True
Var_4: str = 'Annie'

# 类对象类型注解
class Student:
    pass

stu: Student = Student()

# 基础容器类型注解
my_list: list = [1,2,3]
my_tuple: tuple = (1,2,3)
my_dict: dict = {"Annie", 23}

# 容器类型详细注解
my_list: list[int] = [1,2,3]
my_tuple: tuple[int,str,bool,float] = (1,'Annie',True,4.23) # 每个元素都要注解类型
my_dict: dict[str,int] = {"Annie", 23}

# 在注释中进行类型注解
var_4 = random.randint(1,10) # type: int
print(var_4)
var_5 = json.loads('{"name": "Annie","age": 23}') # type: dict[str,str]
print(var_5)

def func():
    return 10
#对函数返回值做注释类型注解
var_6 = func() # type: int

# 类型注解的限制
var_7: int = 'petter'
var_8: str = 123
# 以上代码可运行，类型注解只是给开发者提示用，不是强制。哪怕标记错了，也不会影响程序运行


# ----------------------------------------------------------------------
# |
# |  LockBranchPlugin.py
# |
# |  David Brownell <db@DavidBrownell.com>
# |      2023-11-10 15:50:53
# |
# ----------------------------------------------------------------------
# |
# |  Copyright David Brownell 2023
# |  Distributed under the Boost Software License, Version 1.0. See
# |  accompanying file LICENSE_1_0.txt or copy at
# |  http://www.boost.org/LICENSE_1_0.txt.
# |
# ----------------------------------------------------------------------
"""Contains the Plugin object"""

import textwrap

from semantic_version import Version as SemVer

from GitHubConfigurationValidatorLib.Plugin import Plugin as PluginBase
from GitHubConfigurationValidatorLib.Impl.PluginImpl import CreateEnablePlugin

# ----------------------------------------------------------------------
Plugin = CreateEnablePlugin(
    "LockBranch",
    PluginBase.ConfigurationType.BranchProtection,
    SemVer("0.1.0"),
    False,
    "--lock-branch",
    "settings/branches",
    "Protect matching branches",
    "Lock branch",
    lambda configuration: configuration["lock_branch"]["enabled"],
    rationale=textwrap.dedent(
        """\
        The default behavior is to not lock the mainline branch.

        Reasons for this Default
        ------------------------
        - Archiving a repository is a much more effective way to make it read-only.

        Reasons to Override this Default
        --------------------------------
        <unknown>
        """,
    ),
)


import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

##################################################
# Initial variable setup
##################################################
# Grab data from source
data_training = pd.read_csv('https://personal.utdallas.edu/~cwk200000/files/auto-mpg-training.csv')
data_test = pd.read_csv('https://personal.utdallas.edu/~cwk200000/files/auto-mpg-test.csv')

# Format the data into x and y axis
X_train = data_training.drop('mpg', axis=1)
y_train = data_training['mpg']
X_test = data_test.drop('mpg', axis=1)
y_test = data_test['mpg']

##################################################
# Function definitions
##################################################

def run_linear_regression():
    # Create a linear regression model
    model = LinearRegression()

    # Fit the model to the training data
    model.fit(X_train, y_train)

    # Predict on the sets
    y_pred_train = model.predict(X_train)
    y_pred_test = model.predict(X_test)

    log_file = open('files/grad_descent_part_2.log', 'w')

    # Evaluate the model using Mean Squared Error (MSE)
    mse_train = mean_squared_error(y_train, y_pred_train)
    mse_test = mean_squared_error(y_test, y_pred_test)
    r2_train = model.score(X_train, y_train)
    r2_test = model.score(X_test, y_test)

    log_entry = ("--- Scikit Linear Regression ---\n"
                f"Weights: {model.coef_}\n"
                f"Training MSE: {mse_train}\n"
                f"Test MSE: {mse_test}\n"
                f"Training R^2: {r2_train}\n"
                f"Test R^2: {r2_test}\n\n")
    log_file.write(log_entry)

    log_file.close()

##################################################
# Main Function
##################################################

if __name__ == '__main__':
    run_linear_regression()


def printBoard(board):
    print("   0   1   2")
    print("0  " + board[0][0] + '  | ' + board[0][1] + ' | ' + board[0][2])
    print('   ---+---+---')
    print("1  " + board[1][0] + '  | ' + board[1][1] + ' | ' + board[1][2])
    print('   ---+---+---')
    print("2  " + board[2][0] + '  | ' + board[2][1] + ' | ' + board[2][2])

def changePlayer(player):
    if turns % 2 == 0:
        player = "X"
    else:
        player = "O"
    return player

def playerMove(board, player):
    player_move_row = int(input('Player {}'.format(new_player) + ', Pick a row(0-2): '))
    player_move_column = int(input('Pick a column(0-2): '))
    while myBoard[player_move_row][player_move_column] != ' ':
        player_move_row = int(input("Invalid Move! Try another row: "))
        player_move_column = int(input('Pick a column: '))
    myBoard[player_move_row][player_move_column] = new_player

def winHorizontal(board, player):
    for row in myBoard:
        if row == ["X", "X", "X"] or row == ["O", "O", "O"]:
            print("Player {} Wins by Horizontal Line!!".format(player))
            end_game = 0
            return end_game
    return 1

def winVertical(board, player):
    if myBoard[0][0] == new_player and myBoard[1][0] == new_player and myBoard[2][0] == new_player:
        print("Player {} Wins by Vertical Line!!".format(new_player))
        end_game = 0
        return end_game
    elif myBoard[0][1] == new_player and myBoard[1][1] == new_player and myBoard[2][1] == new_player:
        print("Player {} Wins by Vertical Line!!".format(new_player))
        end_game = 0
        return end_game
    elif myBoard[0][2] == new_player and myBoard[1][2] == new_player and myBoard[2][2] == new_player:
        print("Player {} Wins by Vertical Line!".format(new_player))
        end_game = 0
        return end_game
    else:
        return 1

def winDiagonal(board, player):
    if myBoard[0][0] == new_player and myBoard[1][1] == new_player and myBoard[2][2] == new_player:
        print("Player {} Wins by Diagonal!".format(new_player))
        end_game = 0
        return end_game
    elif myBoard[0][2] == new_player and myBoard[1][1] == new_player and myBoard[2][0] == new_player:
        print("Player {} Wins by Diagonal!".format(new_player))
        end_game = 0
        return end_game
    else:
        return 1

# The Board code is inspired by the book but wanted to try it as a matrix and not a dictionary
myBoard = [[" ", " ", " "],
           [" ", " ", " "],
           [" ", " ", " "]]
# new_board = printBoard(myBoard)

# blank_board = [[" ", " ", " "],
#                [" ", " ", " "],
#                [" ", " ", " "]]

end_game_h = 1
end_game_v = 1
end_game_d = 1
player = ""
turns = 0

while turns < 9 and end_game_h == 1 and end_game_v == 1 and end_game_d == 1:
    new_player = changePlayer(player)
    printBoard(myBoard)
    playerMove(myBoard, new_player)

    end_game_h = winHorizontal(myBoard, new_player)
    end_game_v = winVertical(myBoard, new_player)
    end_game_d = winDiagonal(myBoard, new_player)

    turns += 1

printBoard(myBoard)


#!/usr/bin/python3
"""script for testing POST requests so servers
"""
if __name__ == "__main__":
    import urllib.request
    import urllib.parse
    import sys
    url = sys.argv[1]
    email = sys.argv[2]
    payload = {'email': email}
    payload = urllib.parse.urlencode(payload)
    payload = payload.encode('ascii')
    req = urllib.request.Request(url, payload)
    with urllib.request.urlopen(req) as response:
        print(response.read().decode('utf-8'))


#!/usr/bin/env python3
import psycopg2

db = psycopg2.connect(database='news')
cur = db.cursor()

def execute_query(title, query, unit):
    cur.execute(query)
    results = cur.fetchall()
    print(title)
    for result in results:
        print(str(result[0]) + '  --->  ' + str(result[1]) + unit)
    print()

titles = []
queries = []
units = []

titles.append('What are the most popular three articles of all time?')
queries.append('select * from article_views order by views desc limit 3;')
units.append(' views')

titles.append('Who are the most popular article authors of all time?')
queries.append('select * from author_views order by views desc limit 4;')
units.append(' views')

titles.append('On which days did more than 1% of requests lead to errors?')
queries.append('select * from error_logs where error > 1;')
units.append(' %')

for title, query, unit in zip(titles, queries, units):
    execute_query(title, query, unit)

db.close()


#=import hgsysinc
#=from hgstat_test_data import (
#=    kma_weather_2010, kosos_drink_2010, kosos_soymilk_2010, kosos_carbonated_drink_2010,
#=)
#-----
#=data_x = [kosos_drink_2010[k] for k in kosos_drink_2010] # 혼합 음료
#=data_y = [kma_weather_2010[k] for k in kma_weather_2010] # 날씨
#=print('data_x:', data_x)
#=print('data_y:', data_y)

# 산포도 : 혼합음료 x 날씨
data_drink = [32122, 36529, 52409, 63650, 72324, 72228, 71971, 69514, 56564, 53861, 45193]
data_weather = [-1.7, 2.3, 5.5, 9.9, 17.1, 22.3, 25.4, 26.9, 21.8, 14.5, 7.1]

#
data_x = data_weather # 날씨
data_y = data_drink # 혼합 음료

title_x = '2010 Weather'
title_y = '2010 Drink',
label_x = 'Weather'
label_y = 'Drink'

title = '2010 ' + label_y + ' & ' + label_x

# 그래프 출력
import matplotlib.pyplot as plt

#=figsize = (10, 5) # 가로 데이터가 많을 때
figsize = (6, 6) # 가로, 세로 데이터 수가 같을 때
#=dotSize = 50
dotSize = 130 # 점을 크게
#
plt.figure(figsize=figsize)
plt.scatter(data_x, data_y, s=dotSize) # 날씨(data_x)를 가로축에
#
plt.xlabel(label_x, fontsize=15)
plt.ylabel(label_y, fontsize=15)
#=plt.legend(loc='upper left')

figure = plt.gcf()
#=figure.canvas.set_window_title(title) # 윈도우 창에 [제목] 보이기
#=#=plt.suptitle(title, fontsize=20, y=1.04) # 이미지 밖의 위쪽에 [제목] 표시
plt.title(title, fontsize=20, y=1.04) # 이미지 밖의 위쪽에 [제목] 표시

#=# 숫자가 클 경우에 라벨 표기가 지수형(exponential)으로 바뀌지 않게
#=plt.ticklabel_format(useOffset=False, style='plain', axis='y')
#
figure.tight_layout() # x,y label 잘리지 않도록
#
plt.show()

#
plt.close() # 이 함수를 호출하지 않으면 다음 호출에 이전 그림이 같이 호출됨.

'''
출력 결과:

#================
#================

data_x: [32122, 36529, 52409, 63650, 72324, 72228, 71971, 69514, 56564, 53861, 45193]
data_y: [-1.7, 2.3, 5.5, 9.9, 17.1, 22.3, 25.4, 26.9, 21.8, 14.5, 7.1

'''