import pandas as pd
import tabula
import numpy as np
import json
import sys, getopt
import argparse

def converttide(pdfPath):

  pdf = tabula.read_pdf(""+pdfPath+"", pages="all")
  pagecount =len(pdf)
  #(pagecount)

  first = []
  schemeFirst = {
    "page": 1,
    "extraction_method": "guess",
    "x1": 29.31871524578892,
    "x2": 563.6040149284062,
    "y1": 460.2443702697754,
    "y2": 758.6404777526856,
    "width": 534.2852996826172,
    "height": 298.39610748291017
  }
  first.append(schemeFirst)

  with open('tideFirst.json', 'w') as outfile:
      json.dump(first, outfile)
  outfile.close()

  readFirst = tabula.read_pdf_with_template(""+pdfPath+"", "tideFirst.json",output_format=None,encoding="utf-8", multiple_tables=False, pages="1", pandas_options={"header":None})

  xyz = []
  for x in range(pagecount-1):

    schemeMiddle = {
    "page": x+2,
    "extraction_method": "guess",
    "x1": 35.27175479657017,
    "x2": 563.6040149284062,
    "y1": 178.96325149536133,
    "y2": 746.7343986511231,
    "width": 528.3322601318359,
    "height": 567.7711471557617
    }
    xyz.append(schemeMiddle)

  with open('tideMiddle.json', 'w') as outfile:
      json.dump(xyz, outfile)
  outfile.close()

  readMiddle = tabula.read_pdf_with_template(""+pdfPath+"", "tideMiddle.json",output_format=None,encoding="utf-8", multiple_tables=False, pandas_options={"header":None})

  df1= pd.DataFrame(np.concatenate(readFirst))
  df2= pd.DataFrame(np.concatenate(readMiddle))
  final = pd.concat([df1, df2], axis=0)

 # print(final)
  final.to_excel(""+pdfPath+".xlsx",header=False)

param1 = sys.argv[1]
converttide(param1)
finalPath = ""+param1+".xlsx"
print(finalPath)


import r2pipe
from r2p_helpers import preserve_esil_registers,\
                        preserve_flagspace,\
                        preserve_position

@preserve_esil_registers
@preserve_flagspace
@preserve_position
def rename_stubs(r, f):
    '''
    calculate proper function name for reloc stub.

    Arguments:
      r: r2pipe() object
      f: json representation of function (from aflj)
    '''

    #if name starts with 'sym.imp' it's already been named
    if f['name'].startswith('sym.imp'):
        return

    #setup analysis
    r.cmd('s {}'.format(f['offset']))
    #setup ESIL
    r.cmd('aeip; aeim')

    #execute until final instruction
    while True:#lol
        current_instr = r.cmdj('pdj1 @ pc')[0]
        #I used to check if offset = fcn_last but aav flags fuck that up
        if current_instr["opcode"].startswith('ldr pc'):
            break
        else:
            r.cmd('aes')

    #exploit the format of the ESIL. Probably only works for ARM
    got_offset = int(r.cmdj('pdj1 @ pc')[0]['esil'].split(",")[0])
    ip = r.cmdj('aerj')['ip']
    reloc_addr = got_offset + ip
    r.cmd('fs relocs')

    flag = [f for f in r.cmdj('fj') if f['offset'] == reloc_addr]
    if len(flag) < 1:
        print("no reloc found @ {} in function {}".format(hex(reloc_addr), f['name']))
    else:
        fname = flag[0]['name'][6:]
        r.cmd('afn sym.imp.{}'.format(fname))

r = r2pipe.open()

############################
#get bounds of .plt section#
############################

sections = r.cmdj('iSj')

#find section named '.plt'.
#assume there's only one
plts = [s for s in sections if s['name']=='.plt']
if len(plts) < 1:
    print('no .plt section found.')
    exit()
else:
    plt = plts[0]
    plt_start = plt['vaddr']
    plt_size = plt['vsize']
    plt_end = plt_start + plt_size

#get list of functions
all_functions = r.cmdj('aflj')

#use f['offset'] > plt_start instead of f['offset'] >=plt_start
#to exclude the resolver function at the top of .plt
plt_stubs = [f for f in all_functions if f['offset'] > plt_start\
             and f['offset'] < plt_end]

for stub in plt_stubs:
    rename_stubs(r, stub)


import numpy as np
import scipy
import os
import shutil
import time
from openmdao.api import pyOptSparseDriver
from openmdao.api import ScipyOptimizeDriver
try:
    from openmdao.api import pyOptSparseDriver
except:
    pyOptSparseDriver = None
from ctr_framework.ctrseq_group import CtrseqGroup
from lsdo_viz.api import Problem
from ctr_framework.mesh import trianglemesh
from ctr_framework.initpt import initialize_pt
from ctr_framework.collision_check import collision_check
from ctr_framework.log import log
from ctr_framework.equofplane import equofplane
from ctr_framework.findcircle import findCircle

def seq_opt(num_nodes,viapts_nbr,base,rot,meshfile,pathfile,j):

    #new line
    pts_nbr = viapts_nbr + 3

    tube_nbr = 4
    k=1
    a = 30
    pt = initialize_pt(viapts_nbr,pathfile)
    pt_pri =  initialize_pt(viapts_nbr * 2,pathfile)
    pt_full =  initialize_pt(100,pathfile)
    p_plane = np.zeros((3,3))
    equ_paras = equofplane(p_plane[0,:],p_plane[1,:],p_plane[2,:])

    center = findCircle(pt[0,1],pt[0,2], \
            pt[-1,1],pt[-1,2],pt[int(viapts_nbr/2),1],pt[int(viapts_nbr/2),2])
    mesh = trianglemesh(num_nodes,k,pt[-1,:],center,meshfile)

    zeta = 0
    rho = 1
    eps_e = 1
    eps_r = 1
    eps_p = 1
    lag = 1
    norm1 = np.linalg.norm(pt[0,:]-pt[-1,:],ord=1.125)
    tol = np.ones((pts_nbr))*10
    tol[viapts_nbr:] = 3
    t0 = time.time()

    # add reachable points ----- testing
    # pt_reach = np.zeros((pts_nbr,3))
    # pt_reach[:viapts_nbr,:] = pt
    # pt_reach[viapts_nbr:,:] = np.array([[0,-5,182.5],[0,0,185],[0,5,182.5]])

    #### feasibility test
    pt[-1,:] = np.array((0,0,185))
    # [0,0,0],[-5,0,5],[182.5,185,182.5]
    for i in range(9,viapts_nbr,1):
        count = 1
        count1 = 1
        count_error=1
        trigger = 0
        flag = 1
        error = 1
        lag = 1
        while flag==1 or error>tol[i]:

            # if count >= 10:

            #     if flag==1:
            #         multiplier = 20*count1
            #         zeta = (1e-3) * multiplier + zeta
            #         count1+=1

            #     prob1 = Problem(model=CtrseqGroup(k=1, num_nodes=num_nodes, a=a, tube_nbr=tube_nbr,\
            #             pt=pt_pri[(i+1)*2-1,:],i=i,target = pt[-1,:], center=center, lag = lag,\
            #                 zeta=zeta,rho=rho,eps_r=eps_r,eps_p=eps_p, eps_e=eps_e, \
            #                     pt_full = pt, viapts_nbr=viapts_nbr, meshfile = meshfile,\
            #                         rotx_init=rot[0],roty_init=rot[1],rotz_init=rot[2],base = base,count=0,equ_paras = equ_paras,pt_test = pt[-1,:]))
            # else:

            #     if flag==1:
            #         multiplier = 20 * count
            #         zeta = 1e-3 * multiplier + zeta

            #     prob1 = Problem(model=CtrseqGroup(k=1, num_nodes=num_nodes, a=a, tube_nbr=tube_nbr,\
            #             pt=pt[i,:],i=i,target = pt[-1,:], center=center, lag = lag,\
            #                 zeta=zeta,rho=rho,eps_r=eps_r,eps_p=eps_p, eps_e=eps_e,\
            #                     pt_full = pt, viapts_nbr=viapts_nbr, meshfile = meshfile,\
            #                         rotx_init=rot[0],roty_init=rot[1],rotz_init=rot[2],base = base,count=0,equ_paras = equ_paras,pt_test = pt[-1,:]))
            #option 2
            if flag==1 and count1>=1:
                multiplier = 20*count1
                    # zeta = (1e-3) * multiplier1
                zeta = (1e-2) * multiplier + zeta
                count1+=1
            prob1 = Problem(model=CtrseqGroup(k=1, num_nodes=num_nodes, a=a, tube_nbr=tube_nbr,\
                    pt=pt[i,:],i=i,target = pt[-1,:], center=center, lag = lag,\
                        zeta=zeta,rho=rho,eps_r=eps_r,eps_p=eps_p, eps_e=eps_e,\
                            pt_full = pt, viapts_nbr=viapts_nbr, meshfile = meshfile,\
                                rotx_init=rot[0],roty_init=rot[1],rotz_init=rot[2],base = base,count=0,equ_paras = equ_paras,pt_test = pt[-1,:]))
            prob1.driver = pyOptSparseDriver()
            prob1.driver.options['optimizer'] = 'SNOPT'
            prob1.driver.opt_settings['Verify level'] = 0
            prob1.driver.opt_settings['Major iterations limit'] = 20
            prob1.driver.opt_settings['Minor iterations limit'] = 1000
            prob1.driver.opt_settings['Iterations limit'] = 1000000
            prob1.driver.opt_settings['Major step limit'] = 2.0
            prob1.driver.opt_settings['Major feasibility tolerance'] = 1.0e-4
            prob1.driver.opt_settings['Major optimality tolerance'] = 1.0e-3
            prob1.driver.opt_settings['Minor feasibility tolerance'] = 1.0e-4
            prob1.setup()
            # prob1.run()
            prob1.run_model()
            prob1.run_driver()
            flag,detection = collision_check(prob1['rot_p'],prob1['d2'],prob1['d4'],prob1['d6'],\
                                    prob1['tube_ends'],num_nodes,mesh,k)
            error = prob1['targetnorm']
            log(count,multiplier,i,flag,error,detection)
            if error >= tol[i] or flag==1:
                lag = lag + rho * prob1['targetnorm']/norm1
                rho = count_error * 5
                count_error+=1
                break

            elif error<tol[i] and flag==0:
                mdict1 = {'points':prob1['integrator_group3.state:p'], 'alpha':prob1['alpha'], 'beta':prob1['beta'],'kappa':prob1['kappa'],
                        'tube_section_straight':prob1['tube_section_straight'],'tube_section_length':prob1['tube_section_length'],
                        'd1':prob1['d1'], 'd2':prob1['d2'], 'd3':prob1['d3'], 'd4':prob1['d4'], 'd5':prob1['d5'], 'd6':prob1['d6'],
                        'd7':prob1['d7'], 'd8':prob1['d8'], 'error':error,
                        'initial_condition_dpsi':prob1['initial_condition_dpsi'],'rotx':prob1['rotx'],'roty':prob1['roty'], 'rotz':prob1['rotz'],
                        'loc':prob1['loc'],'rot_p':prob1['rot_p'],'flag':flag, 'detection':detection, 'zeta':zeta, 'dl0':prob1['tube_section_length'] + prob1['beta'],
                        'rho':rho, 'eps_r':eps_r, 'eps_p':eps_p, 'eps_e':eps_e,
                        'lag':lag
                        }
                scipy.io.savemat('seq_ftc'+str(j+56)+'.mat',mdict1)
                break
            trigger = 1
            count+=1
            mdict1 = {'points':prob1['integrator_group3.state:p'], 'alpha':prob1['alpha'], 'beta':prob1['beta'],'kappa':prob1['kappa'],
                        'tube_section_straight':prob1['tube_section_straight'],'tube_section_length':prob1['tube_section_length'],
                        'd1':prob1['d1'], 'd2':prob1['d2'], 'd3':prob1['d3'], 'd4':prob1['d4'], 'd5':prob1['d5'], 'd6':prob1['d6'],
                        'd7':prob1['d7'], 'd8':prob1['d8'],
                        'initial_condition_dpsi':prob1['initial_condition_dpsi'],'rotx':prob1['rotx'],'roty':prob1['roty'], 'rotz':prob1['rotz'],
                        'loc':prob1['loc'],'rot_p':prob1['rot_p'],'flag':flag, 'detection':detection, 'zeta':zeta, 'dl0':prob1['tube_section_length'] + prob1['beta'],
                        'rho':rho, 'eps_r':eps_r, 'eps_p':eps_p, 'eps_e':eps_e,
                        'lag':lag
                        }
            scipy.io.savemat('seq_test_flag'+str(i)+'.mat',mdict1)

        # mdict1 = {'points':prob1['integrator_group3.state:p'], 'alpha':prob1['alpha'], 'beta':prob1['beta'],'kappa':prob1['kappa'],
        #                 'tube_section_straight':prob1['tube_section_straight'],'tube_section_length':prob1['tube_section_length'],
        #                 'd1':prob1['d1'], 'd2':prob1['d2'], 'd3':prob1['d3'], 'd4':prob1['d4'], 'd5':prob1['d5'], 'd6':prob1['d6'],
        #                 'd7':prob1['d7'], 'd8':prob1['d8'],
        #                 'initial_condition_dpsi':prob1['initial_condition_dpsi'],'rotx':prob1['rotx'],'roty':prob1['roty'], 'rotz':prob1['rotz'],
        #                 'loc':prob1['loc'],'rot_p':prob1['rot_p'],'flag':flag, 'detection':detection, 'zeta':zeta, 'dl0':prob1['tube_section_length'] + prob1['beta'],
        #                 'rho':rho, 'eps_r':eps_r, 'eps_p':eps_p, 'eps_e':eps_e,
        #                 'lag':lag
        #                 }
        # scipy.io.savemat('seq_ftr'+str(j+4)+'.mat',mdict1)
        os.rename('SNOPT_print.out','SNOPT_print'+str(i)+'.out')

    t1 = time.time()
    print(t1-t0)


# Convert the above numpy matrix to a pandas data frame

import numpy as np
import pandas as pd

my_array = np.array([[11,22,33],[44,55,66]])

print(my_array)
print(type(my_array))

df = pd.DataFrame(my_array, columns = ['Column_A','Column_B','Column_C'])

print(df)
print(type(df))

# Save the above data frame as a csv file
df.to_csv('my_csv.csv')

# Save the above data frame as a excel file
df.to_excel('my_excel.xlsx')

# Replicate the same data in the excel file across multiple sheets with different names

# df.to_excel('excel1.xlsx', sheet_name='Sheet1')
# df.to_excel('excel1.xlsx', sheet_name='Sheet2')
# df.to_excel('excel1.xlsx', sheet_name='Sheet3')


#!/usr/bin/python3
"""
Defines the Square class that inherits from Rectangle.
"""

Rectangle = __import__('9-rectangle').Rectangle

class Square(Rectangle):
    """
    Represents a square.

    Attributes:
        __size (int): The size of the square.
    """
    def __init__(self, size):
        """
        Initialize a Square instance.

        Args:
            size (int): The size of the square.

        Raises:
            TypeError: If size is not an integer.
            ValueError: If size is less than or equal to 0.
        """
        self.__size = size
        super().__init__(self.__size, self.__size)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import argparse
import Models, LoadBatches
from PIL import Image
from keras.models import load_model
import glob
import cv2
import numpy as np
import random
import os
import tensorflow as tf

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)
config.gpu_options.allow_growth = True
session = tf.Session(config=config)

parser = argparse.ArgumentParser()
parser.add_argument("--save_weights_path", type=str, default='weights/rock_model/resnet50unet/resnet50Unet_rock_75_0.73.h5')  #调用模型路径
parser.add_argument("--epoch_number", type=int, default=9)
parser.add_argument("--test_images", type=str, default="data/rock/val/")  #测试集图像路径
parser.add_argument("--output_path", type=str, default="data/predictions/")  #预测结果保存路径
parser.add_argument("--input_height", type=int, default=512)
parser.add_argument("--input_width", type=int, default=512)  #输入图片尺寸
parser.add_argument("--model_name", type=str, default="resnet50Unet")  #调用模型
parser.add_argument("--n_classes", type=int, default=5)  #矿物种类

args = parser.parse_args()

n_classes = args.n_classes
model_name = args.model_name
images_path = args.test_images
input_width = args.input_width
input_height = args.input_height
epoch_number = args.epoch_number

modelFns = {'vgg_segnet': Models.VGGSegnet.VGGSegnet, 'vgg_unet': Models.VGGUnet.VGGUnet,
                'vgg_unet2': Models.VGGUnet.VGGUnet2, 'fcn8': Models.FCN8.FCN8, 'fcn32': Models.FCN32.FCN32,
                'mobile-segnet': Models.mobile_segnet.mobilenet_segnet,
                'resnet50Unet':Models.resnet_unet.resnet_50_unet}
modelFN = modelFns[model_name]

m = modelFN(n_classes, input_height=input_height, input_width=input_width)
m.load_weights(args.save_weights_path)
m.compile(loss='categorical_crossentropy',
          optimizer='adadelta',
          metrics=['accuracy'])

output_height = m.outputHeight
output_width = m.outputWidth
testroot = images_path
images = os.listdir(testroot)
print(images)

colors = np.array([[0, 0, 0],
                   [128, 0, 0],
                   [0, 128, 0],
                   [0, 0, 128],
                   [128, 0, 128]
                   ], dtype='uint8')

for imgName in images:
    img = cv2.imread(os.path.join(testroot, imgName), 1)
    X = LoadBatches.getImageArr(img, args.input_width, args.input_height)
    pr = m.predict(np.array([X]))[0]

    pr = pr.reshape((output_height, output_width, n_classes)).argmax(axis=2)
    seg_img = np.zeros((output_height, output_width, 3))
    for c in range(n_classes):
        seg_img[:, :, 0] += ((pr[:, :] == c) * (colors[c][0])).astype('uint8')
        seg_img[:, :, 1] += ((pr[:, :] == c) * (colors[c][1])).astype('uint8')
        seg_img[:, :, 2] += ((pr[:, :] == c) * (colors[c][2])).astype('uint8')
    seg_img = cv2.resize(seg_img, (input_width, input_height))
    origin_img = Image.open(os.path.join(testroot, imgName))
    width, height = origin_img.size
    seg_img = Image.fromarray(np.uint8(seg_img))
    seg_img = seg_img.resize((width, height))
    origin_img = origin_img.convert('RGBA')
    seg_img = seg_img.convert('RGBA')
    pred_image = Image.blend(origin_img, seg_img, 0.5)
    pred_image.save("data/predictions/" + imgName.split(".")[0] + ".png")


import os
import shutil
import random

from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings

class Command(BaseCommand):
    help = "Creates initial models"

    def handle(self, *args, **options):
        works = [
            "makemigrations",
            "migrate",
            "collectstatic",
        ]
        for work in works:
            try:
                call_command(work)
                self.stdout.write(
            self.style.SUCCESS(f"Successfully {work}")
        )
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f"{work} Failed  \n \t \t Error is: {e}")
                )

        ##
        load_data = [
            "languages.json",
            "currencies.json",
            "countries.json",
            "governorates.json",
            "cities.json",
            "categories.json",
            "meals.json",
            "drivers.json",
            "hospitalities.json",
            "colors.json",
            "gradients.json",
            "color_steps.json",
            "logos.json",
            "restaurants.json",
            "restaurant_meals.json",
            "restaurant_meal_images.json",
            "restaurant_meal_sizes.json",
            # "users.json",
        ]
        for data in load_data:
            try:
                call_command("loaddata", data)
                self.stdout.write(
                    self.style.SUCCESS(f"Successfully {data} Load Data")
                )
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f"Load Data Failed from {data} , \n \t Error is: \t \t{e}")
                )
        ##
        call_command("users_seeds")
        call_command("runserver")

        self.stdout.write(
            self.style.SUCCESS("Successfully created initial models")
        )


# @author: Gautam Patel
# Problem Description URL: https://www.hackerrank.com/challenges/find-digits/problem
#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the findDigits function below.
def findDigits(n):
    result = 0
    d = n
    while True:
        if n < 10:
            if n > 0 and d % n == 0:
                result += 1
            break
        nd = n - 10*int(n/10)
        if nd > 0 and d % nd == 0:
            result += 1
        n = int(n/10)
    return result

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        n = int(input())

        result = findDigits(n)

        fptr.write(str(result) + '\n')

    fptr.close()


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

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return None
        sp = head
        fp = head
        while fp != None and fp.next != None:
            sp = sp.next
            fp = fp.next.next
            if sp == fp:
                break
        if fp == None or fp.next == None:
            return None
        fp = head
        while sp != fp:
            sp = sp.next
            fp = fp.next
        return sp


# Author: Julia Gordon
# date: 3/2/2022
# Homework 6
# this code will tell you if a positive number is a perfect number
print('--------------------------------------')
i = int(input("Enter any positive number: "))
PerSum = 0
for x in range(1, i): # here we are listing out the divisors of i in a for loop
    if(i % x == 0): # if i is divisible by our i then it is prime
        PerSum = PerSum + x # so we add it to the sum
if (PerSum == i): # when the sum is equal to our number we know its a perfect number
    print(i, "Is a Perfect number!")
else: # if the sum does not equal to our i then n is not a perfect number
    print(i, "Is not a Perfect number!")
print('--------------------------------------')

# this code will list perfect numbers in a given range
def PrintPerNum(start, end):
    for i in range(start, end+1): #for the integer within the given range
        PerSum = 0
        for x in range(1, i): # here we are listing out the divisors of the integer in a for loop
            if(i % x == 0): # if i is divisible by our x indice then it is prime
                PerSum = PerSum + x # so we add it to the sum
        if (PerSum == i): # when the sum is equal to our integer we know its a perfect number
            print(i)
print('In the range',(1,2000), 'the perfect numbers are: ')
PrintPerNum(1,2000)
print('--------------------------------------')

# This code will tell you the 8th perfect number only:

def PrintPerNum8(start, end):
    for i in range(start, end+1): #for the integer within the given range
        PerSum = 0
        for x in range(1, i): # here we are listing out the divisors of the integer in a for loop
            if(i % x == 0): # if i is divisible by our x indice then it is prime
                PerSum = PerSum + x # so we add it to the sum
        if (PerSum == i): # when the sum is equal to our integer we know its a perfect number
            print(i)
print('the 8th perfect number is: ',)
PrintPerNum8(1,300000000000000000) # here I thought i could isolate the range of te 8th perfect number
print('--------------------------------------')

print('--------------------------------------')
# Create an implementation of the Affine cipher with Python.
# The Affine cipher is a simple substitution cipher.  Cipher Each character is mapped to
# its numeric equivalent, encrypted with a mathematical function and then convert to the
# letter relating to its new numeric value.
#
import re
alphaMatches = {
    "a": 0,
    "b": 1,
    "c": 2,
    "d": 3,
    "e": 4,
    "f": 5,
    "g": 6,
    "h": 7,
    "i": 8,
    "j": 9,
    "k": 10,
    "l": 11,
    "m": 12,
    "n": 13,
    "o": 14,
    "p": 15,
    "q": 16,
    "r": 17,
    "s": 18,
    "t": 19,
    "u": 20,
    "v": 21,
    "w": 22,
    "x": 23,
    "y": 24,
    "z": 25
}

numMatches = {
    "0": "a",
    "1": "b",
    "2": "c",
    "3": "d",
    "4": "e",
    "5": "f",
    "6": "g",
    "7": "h",
    "8": "i",
    "9": "j",
    "10": "k",
    "11": "l",
    "12": "m",
    "13": "n",
    "14": "o",
    "15": "p",
    "16": "q",
    "17": "r",
    "18": "s",
    "19": "t",
    "20": "u",
    "21": "v",
    "22": "w",
    "23": "x",
    "24": "y",
    "25": "z"
}


# 4

import csv

with open("StudentsPerformance 14.csv") as f:
    reader = csv.DictReader(f, skipinitialspace=True)
    data = [r for r in reader]

filteredData = list(
    filter(
        lambda x: x["race/ethnicity"] == "group C" and x["test preparation course"] == "completed",
        data,
    )
)

print(filteredData)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 22 11:54:45 2022

@author: alitim179
"""

class myUniversity:
    def __init__(self):
        self.name = ""
        self.state = ""
        self.level = ""
        self.students = 0
        self.courses = 0
        self.staff = 0

    def uni_info(self):
        print("Let's define your university with the following details: ")
        self.name = input("Name of your university: ")
        self.state = input("State in which it is located: ")
        self.level = input("University Level: ")
        self.students = int(input("Number of students: "))
        self.courses = int(input("Nunmber of courses: "))
        self.staff = int(input("Number of staff: "))
        info =  (f"Your university is called {self.name}."+
                f"\nIt is located in {self.state}."+
                f"\nIts level is {self.level}."+
                f"\nIt has {self.students} students, {self.courses} courses, and "+
                f"{self.staff} people working there.")
        return info

my_uni = myUniversity()
print(my_uni.uni_info())


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

import time
import logging
from cleep.libs.drivers.driver import Driver
from cleep.libs.configs.cleepaudio import CleepAudio
from cleep.libs.commands.alsa import Alsa

class AudioDriver(Driver):
    """
    Audio driver base class

    As mentionned in Driver base class, we implements following methods:
     - _install
     - _uninstall
     - is_installed
    """

    def __init__(self, driver_name):
        """
        Constructor

        Args:
            driver_name (string): driver name
        """
        Driver.__init__(self, Driver.DRIVER_AUDIO, driver_name)

        self.__card_name = None

    def _on_registered(self):
        """
        Driver registered
        """
        self._cleep_audio = CleepAudio(self.cleep_filesystem)
        self.alsa = Alsa(self.cleep_filesystem)

        self._on_audio_registered()

        self.__card_name = self.__get_card_name()
        self.logger.debug('Found card_name=%s' , self.__card_name)

    def _on_audio_registered(self): # pragma: no cover
        """
        Audio driver registered
        """
        raise NotImplementedError('Function "_on_audio_registered" must be implemented in "%s"' % self.__class__.__name__)

    def __get_card_name(self):
        """
        Request for associated driver card name

        Returns:
            string: driver card name
        """
        devices = self.alsa.get_playback_devices()
        devices_names = []
        for _, card in devices.items():
            data = {
                'card_name': card['name'],
                'card_desc': card['desc'],
                'device_name': None,
                'device_desc': None,
            }
            for _, device in card['devices'].items():
                data['device_name'] = device['name']
                data['device_desc'] = device['desc']
                devices_names.append(data)

        return self._get_card_name(devices_names)

    def _get_card_name(self, devices_names): # pragma: no cover
        """
        Get card name to be able to identify the card associated to the driver.
        You must return a string found in one of devices_names strings.

        Args:
            devices_names (list): list of devices names installed on device::

                [
                    {
                        card_name (string): card name
                        card_desc (string): card description
                        device_name (string): device name
                        device_desc (string): device description
                    },
                    ...
                ]

        Returns:
            string: card name used to identify the card associated to the driver

        """
        raise NotImplementedError('Function "_get_card_name" must be implemented in "%s"' % self.__class__.__name__)

    def get_card_name(self):
        """
        Return card name

        Returns:
            string: card name
        """
        return self.__card_name

    def get_device_infos(self):
        """
        Returns infos about device associated to driver

        Returns:
            dict: device infos::

                {
                    cardname (string): handled card name
                    cardid (int): card id
                    deviceid (int): device id
                    playback (bool): True if audio playback is possible
                    capture (bool): True if audio capture is possible
                }

        """
        if not self.__card_name:
            raise Exception('No hardware found for driver "%s"' % self.__class__.__name__)

        alsa_infos = self.get_alsa_infos()
        self.logger.debug('alsa_infos=%s' % alsa_infos)
        card_infos = {
            'cardid': None,
            'deviceid': None
        }
        if alsa_infos and 'devices' in alsa_infos and len(alsa_infos['devices'])>0:
            card_infos['cardid'] = alsa_infos['devices'][0]['cardid']
            card_infos['deviceid'] = alsa_infos['devices'][0]['deviceid']
        capabilities = self.get_card_capabilities()

        return {
            'cardname': self.__card_name,
            'cardid': card_infos['cardid'],
            'deviceid': card_infos['deviceid'],
            'playback': capabilities[0],
            'capture': capabilities[1],
        }

    def is_card_enabled(self):
        """
        Is specified card enabled ?

        Returns:
            bool: True if enable
        """
        selected_device = self.alsa.get_selected_device()
        self.logger.debug('card name=%s selected device=%s', self.__card_name, selected_device)

        is_enabled = selected_device and selected_device['name'] == self.__card_name

        if is_enabled:
            self._set_volumes_controls()

        return is_enabled

    def get_cardid_deviceid(self):
        """
        Returns only cardid/deviceid for current card

        Returns:
            tuple: cardid/deviceid::

                (
                    cardid (int): card id or None if not found
                    deviceid (int): device id or None if not found
                )

        """
        infos = self.get_alsa_infos()
        self.logger.debug('alsa infos: %s', infos)
        return (infos['devices'][0]['cardid'], infos['devices'][0]['deviceid']) if infos else (None, None)

    def get_alsa_infos(self):
        """
        Return alsa infos for current card

        Returns:
            dict: alsa infos or None if card not found::

                {
                    name (string): card name
                    desc (string): card description
                    devices (list): list of devices
                        [
                            {
                                cardid (string): card id
                                deviceid (string): device id
                                name (string): device name
                                desc (string): device description
                            },
                            ...
                        ]
                }

        """
        return self.alsa.get_device_infos(self.__card_name)

    def get_control_numid(self, control_name):
        """
        Return numid for specified control name. Control name has not to be exact but contains the specified string
        to match result. Search is not case sensitive.

        Args:
            control_name (string): control name to search for

        Returns:
            int: control numid or None if control not found
        """
        found_controls = [control['numid'] for control in self.alsa.get_controls() if control['name'].lower().find(control_name.lower()) >= 0]
        self.logger.debug('Found controls: %s', found_controls)

        return found_controls[0] if len(found_controls) > 0 else None

    def get_card_capabilities(self): # pragma: no cover
        """
        Return card capabilities

        Warning:
            This function must be implemented in audio driver

        Returns:
            tuple: card capabilities::

                (
                    bool: playback capability,
                    bool: capture capability
                )
        """
        raise NotImplementedError('Function "get_card_capabilities" must be implemented in "%s"' % self.__class__.__name__)

    def enable(self, params=None): # pragma: no cover
        """
        Enable driver

        Warning:
            This function must be implemented in audio driver

        Args:
            params (dict): additionnal parameters if necessary
        """
        raise NotImplementedError('Function "enable" must be implemented in "%s"' % self.__class__.__name__)

    def disable(self, params=None): # pragma: no cover
        """
        Disable driver

        Warning:
            This function must be implemented in audio driver

        Args:
            params (dict): additionnal parameters if necessary
        """
        raise NotImplementedError('Function "disable" must be implemented in "%s"' % self.__class__.__name__)

    def _set_volumes_controls(self): # pragma: no cover
        """
        Set controls to configure volumes

        Warning:
            This function must be implemented in audio driver
        """
        raise NotImplementedError('Function "_set_volumes_controls" must be implemented in "%s"' % self.__class__.__name__)

    def get_volumes(self): # pragma: no cover
        """
        Get volumes

        Warning:
            This function must be implemented in audio driver

        Returns:
            dict: volumes level::

                {
                    playback (float): playback volume
                    capture (float): capture volume
                }

        """
        raise NotImplementedError('Function "get_volumes" must be implemented in "%s"' % self.__class__.__name__)

    def set_volumes(self, playback=None, capture=None): # pragma: no cover
        """
        Set volumes

        Warning:
            This function must be implemented in audio driver

        Args:
            playback (float): playback volume (None to disable update)
            capture (float): capture volume (None to disable update)
        """
        raise NotImplementedError('Function "set_volumes" must be implemented in "%s"' % self.__class__.__name__)


import sys
import random as rd
import numpy as np

def open_data(which):
	file = open(which, "r")
	data = []

	for i in file:
		tmp = i.split()
		tmp_data = []

		for t in tmp:
			tmp_data.append(eval(t))

		x = np.matrix([1] + tmp_data[:-1])
		y = np.matrix(tmp_data[-1])

		data.append((x, y))

	return data

def main():
	dataes = open_data("data1.txt")

	learning_rate = 0.00005
	max_iteration = 2000
	w = np.full_like(dataes[0][0], rd.random(), dtype='float64')

	for it in range(max_iteration):
		for data in dataes:
			(x, y) = data

			w += learning_rate * 2. * (y - w * x.transpose()) * x

	print(w)

main()

2019_03_16/Machine Learning by processor Hwang/linear_regression.py


import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

import irtemp
import edge_detection
import pixel_analysis

from irtemp import centikelvin_to_celsius
from skimage import io
from skimage import feature
from skimage.exposure import equalize_adapthist
from skimage.feature import canny
from scipy.ndimage.morphology import binary_fill_holes
from skimage.measure import label
from skimage.measure import regionprops
from skimage.morphology import remove_small_objects
from scipy.signal import find_peaks

# def test_name():
#     '''Doc String'''
#     #inputs
#     #running function
#     #asserts
#     return

##################### Peak detection and pixel analysis function #######################################

def test_image_eq():
    ''' Test for fucntion which equalizes a low contrast image'''
    pixel_frames = edge_detection.input_file('../musical-robot/musicalrobot/data/CHCl_CA_DES_5_31_19.tiff')
    n_frames = len(pixel_frames)
    img_eq = pixel_analysis.image_eq(n_frames,pixel_frames)
    assert isinstance(img_eq,np.ndarray),'Output is not an array'
    assert pixel_frames[0].shape == img_eq.shape, 'Output array shape is not same as the input array shape.'
    return

def test_pixel_sum():
    '''Test for function which obtains the sum of pixels over all rows and columns'''
    pixel_frames = edge_detection.input_file('../musical-robot/musicalrobot/data/CHCl_CA_DES_5_31_19.tiff')
    n_frames = len(pixel_frames)
    img_eq = pixel_analysis.image_eq(n_frames,pixel_frames)
    column_sum, row_sum = pixel_analysis.pixel_sum(img_eq)
    assert isinstance(column_sum,list),'Column sum is not a list'
    assert isinstance(row_sum,list),'Row sum is not a list'
    assert len(row_sum) == img_eq.shape[0], 'The length of row_sum is not equal to number of rows in the input image'
    assert len(column_sum) == img_eq.shape[1], 'The length of column_sum is not equal to number of columns in the input image'
    return

def test_peak_values():
    '''Test for function which finds peaks from the column_sum and row_sum arrays
        and return a dataframe with sample locations and plate locations.'''
    pixel_frames = edge_detection.input_file('../musical-robot/musicalrobot/data/CHCl_CA_DES_5_31_19.tiff')
    n_frames = len(pixel_frames)
    img_eq = pixel_analysis.image_eq(n_frames,pixel_frames)
    column_sum, row_sum = pixel_analysis.pixel_sum(img_eq)
    n_columns = 12
    n_rows = 8
    sample_location = pixel_analysis.peak_values(column_sum,row_sum,n_columns,n_rows,img_eq)
    assert isinstance(sample_location,pd.DataFrame),'Output is not a dataframe'
    assert len(sample_location)==n_columns*n_rows, 'Wrong number of sample locations are present'
    return

def test_pixel_intensity():
    '''Test for function which determines sample temperature and plate temperature'''
    pixel_frames = edge_detection.input_file('../musical-robot/musicalrobot/data/CHCl_CA_DES_5_31_19.tiff')
    n_frames = len(pixel_frames)
    img_eq = pixel_analysis.image_eq(n_frames,pixel_frames)
    column_sum, row_sum = pixel_analysis.pixel_sum(img_eq)
    n_columns = 12
    n_rows = 8
    sample_location = pixel_analysis.peak_values(column_sum,row_sum,n_columns,n_rows,img_eq)
    x_name = 'Row'
    y_name = 'Column'
    plate_name = 'plate_location'
    pixel_sample,pixel_plate = pixel_analysis.pixel_intensity(sample_location, pixel_frames, x_name,y_name,plate_name)
    assert isinstance(pixel_sample,list),'Output is not a list'
    assert isinstance(pixel_plate,list),'Output is not a list'
    assert len(pixel_sample)==n_columns*n_rows,'Temperature obtained for wrong number of samples'
    assert len(pixel_plate)==n_columns*n_rows,'Temperature obtained for wrong number of plate locations'
    return

def test_pixel_temp():
    '''Test for the wrapping function'''
    pixel_frames = edge_detection.input_file('../musical-robot/musicalrobot/data/CHCl_CA_DES_5_31_19.tiff')
    n_frames = len(pixel_frames)
    n_columns = 12
    n_rows = 8
    m_df = pixel_analysis.pixel_temp(pixel_frames,n_frames,n_columns,n_rows)
    assert isinstance(m_df,pd.DataFrame),'Output obtained is not a dataframe'
    assert len(m_df)==n_columns*n_rows,'Temperature obtained for wrong number of samples'
    return


# https://leetcode.com/problems/partition-equal-subset-sum/
# tags: #array, #dp
#
# Brute-Force solution
# For demo purposes, it can be solved using backtracking
# # Time complexity: O(2^n), Space complexity O(n)
#
# Solution: Dynamic Programming
# Great explanation at:
# https://leetcode.com/problems/partition-equal-subset-sum/discuss/462699/Whiteboard-Editorial.-All-Approaches-explained.
# Solution is similar to Knapsack problem:
# dp[sum] will denote whether sum is achievable or not.
# Initially, we have dp[0] = true since a 0 sum is always achievable.
# Then for each element num, we will iterate & find if it is possible to form a sum j by adding num to
# some previously formable sum.
# Time complexity: O(n*sum), Space complexity O(sum)
from typing import List

class Solution:
    def canPartition_backtracking(self, nums: List[int]) -> bool:
        def backtracking(subset: List[int], current_sum: int) -> bool:
            for i in range(len(subset)):
                new_sum = current_sum + subset[i]
                new_set = subset[:i] + subset[i + 1:]
                if new_sum == sum(new_set) or backtracking(new_set, new_sum): return True

            return False

        return backtracking(nums, 0)

    def canPartition_dp(self, nums: List[int]) -> bool:
        total_sum = sum(nums)
        if total_sum % 2 != 0: return False

        half_sum = total_sum // 2
        dp = [True] + [False] * half_sum

        for num in nums:
            for j in range(half_sum, num - 1, -1):
                dp[j] |= dp[j - num]

        return dp[half_sum]

if __name__ == "__main__":
    sol = Solution()
    print(sol.canPartition_dp(nums=[1, 5, 11, 5]))  # True
    print(sol.canPartition_dp(nums=[1, 2, 3, 5]))  # False
    print(sol.canPartition_dp(nums=[1, 3, 4, 4]))  # False


import sys
input = sys.stdin.readline
white = 0
blue = 0

n = int(input())
paper = []
for i in range(n):
    paper.append(list(map(int, input().split())))

def cut(n, paper):
    global white, blue

    if not any(1 in i for i in paper):
        white += 1
        return
    elif not any(0 in i for i in paper):
        blue += 1
        return
    else:
        left = []
        right = []
        for i in paper:
            left.append(i[:n//2])
            right.append(i[n//2:])
        cut(n//2, left[:n//2])
        cut(n//2, left[n//2:])
        cut(n//2, right[:n//2])
        cut(n//2, right[n//2:])
        return

cut(n, paper)
print(white)
print(blue)

HomeWork/eunjung/8. 분할정복, 동적프로그래밍/2630_색종이만들기.py


import tensorflow as tf
from typing import List, Optional
from tensorflow.keras.layers import Layer, LeakyReLU, BatchNormalization
from ...mesh.Mesh import Mesh
from ..feature import features_valid
from ..pooling.MeshUnpool import MeshUnpool
from ..pooling.CollapseSnapshot import CollapseSnapshot
from .ConvolutionSequence import ConvolutionSequence

class UpConvolution(Layer):
    """An UpConvolution combines several skip-connected ConvolutionSequence
    blocks separated by nonlinearities and batch normalization. It can
    optionally include an unpooling step at the end.
    """

    convolutions: List[ConvolutionSequence]
    mesh_unpool: Optional[MeshUnpool]
    batch_normalizations: List[BatchNormalization]
    leaky_relu: LeakyReLU

    def __init__(
        self,
        out_channels: int,
        convolutions_per_sequence: int,
        num_sequences: int,
        leaky_relu_alpha: float,
        unpool: bool,
    ):
        Layer.__init__(self)
        self.convolutions = [
            ConvolutionSequence(out_channels, convolutions_per_sequence)
            for _ in range(num_sequences)
        ]
        self.leaky_relu = LeakyReLU(leaky_relu_alpha)
        self.batch_normalizations = [BatchNormalization() for _ in range(num_sequences)]
        self.mesh_unpool = MeshUnpool() if unpool else None

    def call(
        self, mesh: Mesh, features: tf.Tensor, snapshot: CollapseSnapshot
    ) -> tf.Tensor:
        assert features_valid(mesh, features)

        # Run through the first ConvolutionSequence.
        out_features = self.convolutions[0](mesh, features)
        out_features = self.leaky_relu(out_features)
        out_features = self.batch_normalizations[0](out_features, training=True)

        # Run the remaining ConvolutionSequences with skip connections.
        in_features = out_features
        for i in range(1, len(self.convolutions)):
            # Create out_features using in_features.
            out_features = self.convolutions[i](mesh, in_features)
            out_features = self.leaky_relu(out_features)
            out_features = self.batch_normalizations[i](out_features, training=True)

            # Add the skip connections.
            out_features += in_features
            in_features = out_features

        # Optionally run unpooling.
        if self.mesh_unpool is not None:
            return self.mesh_unpool(mesh, out_features, snapshot)
        return out_features


"""

Flask AD query service implementation
    - includes a bunch of endpoints to facilitate AD tasks
    - supports jsonp
    - Service should be run as LocalSystem user, uses computer's AD acct for query auth

"""

from flask import Flask
import sys
import os
import time
import datetime
from flask import jsonify
import subprocess
import socket
import json
from functools import wraps
from flask import redirect, request, current_app, app
import win32api, win32ts, win32net, win32security, ntsecuritycon
import psutil
from subprocess import PIPE
import tempfile
import re
import pyad.adquery
import pyad.pyad
import pyad.pyadutils
import pythoncom

logfile = "C:\\scripts\\AD query service\\AD query service log.txt"
domain_config_file = "C:\\scripts\\AD query service\\domains.conf"
port = 9994

hostname = socket.gethostname()
app = Flask(__name__)

# Wrapper functions to support JSONP requests should we want to access this API from a browser in the future
def jsonp(func):
    """Wraps JSONified output for JSONP requests."""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            resp = func(*args, **kwargs)
            resp.set_data('{}({})'.format(
                str(callback),
                resp.get_data(as_text=True)
            ))
            resp.mimetype = 'application/javascript'
            return resp
        else:
            return func(*args, **kwargs)
    return decorated_function

# Add a log entry + datetime
def log_entry(log_message):
	with open(logfile, 'a') as f:
		f.write(str(datetime.datetime.now()) + " : ")
		f.write(log_message + '\n')

class domain_obj(object):
    def __init__(self,
                domain,
                base_dn,
                ldap_servers
                ):
        self.domain = domain
        self.base_dn = base_dn
        self.ldap_servers = ldap_servers

    def serialize(self):
        return {
            'domain': self.domain,
            'base_dn': self.base_dn,
            'ldap_servers': [e for e in self.ldap_servers]
        }

@app.route("/ListKnownDomains", methods=['GET'])
@jsonp
def ListKnownDomains():
    domain_objs = []
    try:
        with open(domain_config_file, 'r') as f:
            line = f.readline()
            while line:
                line_domain = line.split('|')[1]
                line_base_dn = line.split('|')[3].strip()
                line_ldap_servers = line.split('|')[5].strip().split(';')
                d = domain_obj(domain=line_domain,base_dn=line_base_dn,ldap_servers=line_ldap_servers[:])
                domain_objs.append(d)
                line = f.readline()
    except Exception as e:
        return jsonify(success=False,
                  error=("Error loading domain_config_file: " + domain_config_file),
                  exception=str(e))

    return jsonify(success=True,
                   domains=[e.serialize() for e in domain_objs])

@app.route("/GroupUsers", methods=['GET'])
@jsonp
def GroupUsers():
    domain = request.args.get('domain')
    group = request.args.get('group')
    last_exception = None

    if domain and group:
        try:
            domain_objs = []
            with open(domain_config_file, 'r') as f:
                line = f.readline()
                while line:
                    line_domain = line.split('|')[1]
                    line_base_dn = line.split('|')[3].strip()
                    line_ldap_servers = line.split('|')[5].strip().split(';')
                    d = domain_obj(domain=line_domain,base_dn=line_base_dn,ldap_servers=line_ldap_servers[:])
                    domain_objs.append(d)
                    line = f.readline()
            domain_set = [e.serialize() for e in domain_objs]
            domain_check = next((item for item in domain_set if item["domain"] == domain), None)
            if not domain_check:
                return jsonify(success=False,
                               error=("'domain' parameter '" + domain + "' not present in domain_config_file"))
            base_dn = domain_check['base_dn']
            ldap_servers = domain_check['ldap_servers']

        except Exception as e:
            return jsonify(success=False,
                    error=("Error loading domain_config_file: " + domain_config_file),
                    exception=str(e))

        # Now try the AD query
        ldap_server_query_success = 0
        for ldap_server in ldap_servers:
            pyad.pyad_setdefaults(ldap_server=ldap_server)
            if ldap_server_query_success == 0:
                try:
                    query_results = []
                    pythoncom.CoInitialize()

                    q = pyad.adquery.ADQuery()
                    q.execute_query(
                        attributes=["distinguishedName"],
                        where_clause="objectClass = 'group' AND cn = '{}'".format(group),
                        base_dn=base_dn
                    )

                    if q.get_row_count() == 0:
                        return jsonify(success=False,
                                domain=domain,
                                group=group,
                                ldap_server=ldap_server,
                                error='No rows returned from adsi query')

                    group_dn = ''
                    for row in q.get_results():
                        group_dn = row['distinguishedName']
                    ldap_server_query_success = 1

                except Exception as e:
                    last_exception = e

            if last_exception:
                pythoncom.CoUninitialize()
                return jsonify(success=False,
                               error=("Error querying domain controller"),
                               ldap_server=ldap_server,
                               domain=domain,
                               group=group,
                               exception=str(last_exception))

            if group_dn == '':
                pythoncom.CoUninitialize()
                return jsonify(success=False,
                        error=("Error group cn specified invalid"),
                        domain=domain,
                        group=group
                        )

            if ldap_server_query_success == 1:
                try:
                    q = pyad.adquery.ADQuery()
                    q.execute_query(
                                    attributes=["distinguishedName", "sAMAccountName"],
                                    where_clause="memberOf = '{}'".format(group_dn),
                                    base_dn=base_dn
                                )

                    # parse the user dn/samaccountname results
                    users = []
                    for row in q.get_results():
                        users.append({"distinguishedName": row['distinguishedName'],
                                    "sAMAccountName": row['sAMAccountName'] })
                    pythoncom.CoUninitialize()
                    return jsonify(success=True,
                                domain=domain,
                                group=group,
                                ldap_server=ldap_server,
                                group_dn=group_dn,
                                users=[e for e in users])

                except Exception as e:
                    return jsonify(success=False,
                                    error=("Error querying domain controller for memberOf information"),
                                    domain=domain,
                                    group=group,
                                    ldap_server=ldap_server,
                                    exception=str(e))

    else:
        return jsonify(success=False,
                       error="/GroupUsers requires parameter 'domain', and 'group'")

@app.route("/UserInGroup", methods=['GET'])
@jsonp
def UserInGroup():
    last_exception = None
    user_in_group = False
    samAccountName = request.args.get('samAccountName')
    domain = request.args.get('domain')
    group = request.args.get('group')

    if samAccountName and domain and group:
        try:
            domain_objs = []
            with open(domain_config_file, 'r') as f:
                line = f.readline()
                while line:
                    line_domain = line.split('|')[1]
                    line_base_dn = line.split('|')[3].strip()
                    line_ldap_servers = line.split('|')[5].strip().split(';')
                    d = domain_obj(domain=line_domain,base_dn=line_base_dn,ldap_servers=line_ldap_servers[:])
                    domain_objs.append(d)
                    line = f.readline()
            domain_set = [e.serialize() for e in domain_objs]
            domain_check = next((item for item in domain_set if item["domain"] == domain), None)
            if not domain_check:
                return jsonify(success=False,
                               error=("'domain' parameter '" + domain + "' not present in domain_config_file"))
            base_dn = domain_check['base_dn']
            ldap_servers = domain_check['ldap_servers']

        except Exception as e:
            return jsonify(success=False,
                    error=("Error loading domain_config_file: " + domain_config_file),
                    exception=str(e))

        # Now try the AD query
        ldap_server_query_success = 0
        for ldap_server in ldap_servers:
            pyad.pyad_setdefaults(ldap_server=ldap_server)
            if ldap_server_query_success == 0:
                try:
                    query_results = []
                    pythoncom.CoInitialize()

                    q = pyad.adquery.ADQuery()
                    q.execute_query(
                        attributes=["distinguishedName"],
                        where_clause="objectClass = 'group' AND cn = '{}'".format(group),
                        base_dn=base_dn
                    )

                    if q.get_row_count() == 0:
                        return jsonify(success=False,
                                domain=domain,
                                group=group,
                                ldap_server=ldap_server,
                                error='Group CN does not exist, No rows returned from adsi query')

                    group_dn = ''
                    for row in q.get_results():
                        group_dn = row['distinguishedName']

                    ldap_server_query_success = 1

                except Exception as e:
                    last_exception = e

            if last_exception:
                pythoncom.CoUninitialize()
                return jsonify(success=False,
                               error=("Error querying domain controller"),
                               ldap_server=ldap_server,
                               domain=domain,
                               group=group,
                               exception=str(last_exception))

            if group_dn == '':
                pythoncom.CoUninitialize()
                return jsonify(success=False,
                        error=("Error group cn specified invalid"),
                        domain=domain,
                        group=group
                        )

            print('found group_dn: ' + str((group_dn)))
            if ldap_server_query_success == 1:
                try:
                    query_results = []

                    q = pyad.adquery.ADQuery()
                    q.execute_query(
                                    attributes=["sAMAccountName", "memberOf"],
                                    where_clause="samAccountName = '{}' AND memberOf='{}'".format(samAccountName, group_dn),
                                    base_dn=base_dn
                                )

                    print('q.get_row_count(): ' + str(q.get_row_count()))
                    if q.get_row_count() == 0:

                        pythoncom.CoUninitialize()
                        return jsonify(success=True,
                                samAccountName=samAccountName,
                                domain=domain,
                                ldap_server=ldap_server,
                                group=group,
                                user_in_group=False,
                                )
                    else:
                        pythoncom.CoUninitialize()
                        return jsonify(success=True,
                                samAccountName=samAccountName,
                                domain=domain,
                                ldap_server=ldap_server,
                                group=group,
                                user_in_group=True,
                                )

                except Exception as e:
                    return jsonify(success=False,
                                samAccountName=samAccountName,
                                domain=domain,
                                ldap_server=ldap_server,
                                group=group,
                                error=("Error querying domain controller"),
                                exception=str(e))

    else:
        return jsonify(success=False,
                       error="/UserInGroup requires parameter 'samAccountName', 'domain', and 'group'")

@app.route("/UserInfo", methods=['GET'])
@jsonp
def UserInfo():
    samAccountName = request.args.get('samAccountName')
    domain = request.args.get('domain')
    last_exception = None

    if samAccountName and domain:
        try:
            domain_objs = []
            with open(domain_config_file, 'r') as f:
                line = f.readline()
                while line:
                    line_domain = line.split('|')[1]
                    line_base_dn = line.split('|')[3].strip()
                    line_ldap_servers = line.split('|')[5].strip().split(';')
                    d = domain_obj(domain=line_domain,base_dn=line_base_dn,ldap_servers=line_ldap_servers[:])
                    domain_objs.append(d)
                    line = f.readline()
            domain_set = [e.serialize() for e in domain_objs]
            domain_check = next((item for item in domain_set if item["domain"] == domain), None)
            if not domain_check:
                return jsonify(success=False,
                               error=("'domain' parameter '" + domain + "' not present in domain_config_file"))
            base_dn = domain_check['base_dn']
            ldap_servers = domain_check['ldap_servers']

        except Exception as e:
            return jsonify(success=False,
                    error=("Error loading domain_config_file: " + domain_config_file),
                    exception=str(e))

        # Now try the AD query
        ldap_server_query_success = 0
        for ldap_server in ldap_servers:
            pyad.pyad_setdefaults(ldap_server=ldap_server)
            if ldap_server_query_success == 0:
                try:
                    query_results = []
                    pythoncom.CoInitialize()

                    q = pyad.adquery.ADQuery()
                    q.execute_query(
                                    attributes=["sAMAccountName",
                                                "memberOf",
                                                "cn",
                                                "sn",
                                                "l",
                                                "st",
                                                "title",
                                                "description",
                                                "postalCode",
                                                "physicalDeliveryOfficeName",
                                                "telephoneNumber",
                                                "givenName",
                                                "initials",
                                                "distinguishedName",
                                                "displayName",
                                                "memberOf",
                                                "department",
                                                "company",
                                                "streetAddress",
                                                "targetAddress",
                                                "employeeNumber",
                                                "employeeType",
                                                "name",
                                                "homeDirectory",
                                                "lastLogon",
                                                "pwdLastSet",
                                                "objectSid",
                                                "userPrincipalName",
                                                "lastLogonTimestamp",
                                                "mail",
                                                "departmentNumber",
                                                "ADsPath"],
                                    where_clause="samAccountName = '{}'".format(samAccountName),
                                    base_dn=base_dn
                                )

                    if q.get_row_count() == 0:
                        ldap_server_query_success = 1
                        return jsonify(success=False,
                                samAccountName=samAccountName,
                                domain=domain,
                                ldap_server=ldap_server,
                                error='No rows returned from adsi query')

                    cn = None
                    group_count = 0
                    groups = []
                    for row in q.get_results():
                        for attr in row:
                            if attr == 'cn':
                                cn = str(row[attr])
                            if attr == 'sn':
                                sn = str(row[attr])
                            if attr == 'l':
                                l = str(row[attr])
                            if attr == 'st':
                                st = str(row[attr])
                            if attr == 'title':
                                title = str(row[attr])
                            if attr == 'description':
                                description = str(row[attr])
                            if attr == 'postalCode':
                                postalCode = str(row[attr])
                            if attr == 'physicalDeliveryOfficeName':
                                physicalDeliveryOfficeName = str(row[attr])
                            if attr == 'telephoneNumber':
                                telephoneNumber = str(row[attr])
                            if attr == 'givenName':
                                givenName = str(row[attr])
                            if attr == 'initials':
                                initials = str(row[attr])
                            if attr == 'distinguishedName':
                                distinguishedName = str(row[attr])
                            if attr == 'displayName':
                                displayName = str(row[attr])
                            if attr == 'department':
                                department = str(row[attr])
                            if attr == 'company':
                                company = str(row[attr])
                            if attr == 'streetAddress':
                                streetAddress = str(row[attr])
                            if attr == 'targetAddress':
                                targetAddress = str(row[attr])
                            if attr == 'employeeNumber':
                                employeeNumber = str(row[attr])
                            if attr == 'employeeType':
                                employeeType = str(row[attr])
                            if attr == 'name':
                                name = str(row[attr])
                            if attr == 'homeDirectory':
                                homeDirectory = str(row[attr])
                            if attr == 'lastLogon':
                                lastLogon = pyad.pyadutils.convert_datetime(row[attr])
                            if attr == 'pwdLastSet':
                                pwdLastSet = pyad.pyadutils.convert_datetime(row[attr])
                            if attr == 'objectSid':
                                objectSid = str(row[attr].tobytes())
                            if attr == 'userPrincipalName':
                                userPrincipalName = str(row[attr])
                            if attr == 'lastLogonTimestamp':
                                lastLogonTimestamp = pyad.pyadutils.convert_datetime(row[attr])
                            if attr == 'mail':
                                mail = str(row[attr])
                            if attr == 'departmentNumber':
                                departmentNumber = str(row[attr])
                            if attr == 'ADsPath':
                                ADsPath = str(row[attr])
                            if attr == 'memberOf':
                                for member in row[attr]:
                                    full_cn = member
                                    member_of_group = member.split(',')[0].split('=')[1]
                                    groups.append({
                                                    "group":member_of_group,
                                                    "full_cn":full_cn
                                    })
                                    group_count = group_count + 1

                    if not cn:
                        ldap_server_query_success = 1
                        pythoncom.CoUninitialize()
                        return jsonify(success=False,
                                    error="samAccountName not found",
                                    samAccountName=samAccountName,
                                    domain=domain,
                                    ldap_server=ldap_server,
                                    )

                    pythoncom.CoUninitialize()
                    ldap_server_query_success = 1
                    return jsonify(success=True,
                                sAMAccountName=samAccountName,
                                domain=domain,
                                memberOf=[e for e in groups],
                                cn=cn,
                                sn=sn,
                                l=l,
                                st=st,
                                title=title,
                                description=description,
                                postalCode=postalCode,
                                physicalDeliveryOfficeName=physicalDeliveryOfficeName,
                                telephoneNumber=telephoneNumber,
                                givenName=givenName,
                                initials=initials,
                                distinguishedName=distinguishedName,
                                displayName=displayName,
                                department=department,
                                company=company,
                                streetAddress=streetAddress,
                                targetAddress=targetAddress,
                                employeeNumber=employeeNumber,
                                employeeType=employeeType,
                                name=name,
                                homeDirectory=homeDirectory,
                                lastLogon=lastLogon,
                                pwdLastSet=pwdLastSet,
                                objectSid=objectSid,
                                userPrincipalName=userPrincipalName,
                                lastLogonTimestamp=lastLogonTimestamp,
                                mail=mail,
                                departmentNumber=departmentNumber,
                                ADsPath=ADsPath,
                                ldap_server=ldap_server,
                                )

                except Exception as e:
                    last_exception = e

            if ldap_server_query_success == 0:
                return jsonify(success=False,
                                samAccountName=samAccountName,
                                domain=domain,
                                ldap_server=ldap_server,
                                error=("Error querying domain controller"),
                                exception=str(last_exception))

    else:
        return jsonify(success=False,
                  error="/UserFullName requires parameter 'samAccountName' and 'domain'")

@app.route("/UserFullName", methods=['GET'])
@jsonp
def UserFullName():
    samAccountName = request.args.get('samAccountName')
    domain = request.args.get('domain')

    if samAccountName and domain:
        try:
            domain_objs = []
            with open(domain_config_file, 'r') as f:
                line = f.readline()
                while line:
                    line_domain = line.split('|')[1]
                    line_base_dn = line.split('|')[3].strip()
                    line_ldap_servers = line.split('|')[5].strip().split(';')
                    d = domain_obj(domain=line_domain,base_dn=line_base_dn,ldap_servers=line_ldap_servers[:])
                    domain_objs.append(d)
                    line = f.readline()
            domain_set = [e.serialize() for e in domain_objs]
            domain_check = next((item for item in domain_set if item["domain"] == domain), None)
            if not domain_check:
                return jsonify(success=False,
                               error=("'domain' parameter '" + domain + "' not present in domain_config_file"))
            base_dn = domain_check['base_dn']
            ldap_servers = domain_check['ldap_servers']

        except Exception as e:
            return jsonify(success=False,
                    error=("Error loading domain_config_file: " + domain_config_file),
                    exception=str(e))

        # Now try the AD query
        ldap_server_query_success = 0
        for ldap_server in ldap_servers:
            pyad.pyad_setdefaults(ldap_server=ldap_server)
            try:
                query_results = []
                pythoncom.CoInitialize()

                q = pyad.adquery.ADQuery()
                q.execute_query(
                                attributes=["sAMAccountName", "displayName"],
                                where_clause="samAccountName = '{}'".format(samAccountName),
                                base_dn=base_dn
                            )

                if q.get_row_count() == 0:
                    return jsonify(success=False,
                            samAccountName=samAccountName,
                            domain=domain,
                            ldap_server=ldap_server,
                            error='No rows returned from adsi query')

                last_row = ''
                for row in q.get_results():
                    last_row = row
                FullName = last_row['displayName']

                pythoncom.CoUninitialize()
                ldap_server_query_success = 1
                return jsonify(success=True,
                            displayName=FullName,
                            samAccountName=samAccountName,
                            domain=domain,
                            FullName=FullName,
                            ldap_server=ldap_server)

            except Exception as e:
                last_exception = e

        if ldap_server_query_success == 0:
            return jsonify(success=False,
                    error=("No data returned from querying domain controllers: " + str(ldap_servers)))

    else:
        return jsonify(success=False,
                  error="/UserFullName requires parameter 'samAccountName' and 'domain'")

@app.route("/RunCmd", methods=['GET'])
@jsonp
def RunCmd():
    cmd = request.args.get('cmd')

    if cmd:
        try:
            #sys.stderr.write(str(cmd_args))
            proc = subprocess.run(("C:\\Windows\\System32\\cmd.exe /c " + cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)
            proc_stdout = proc.stdout.decode('ascii')
            proc_stderr = proc.stderr.decode('ascii')
            #print(cmd)

            return jsonify(success=True,
                           cmd=cmd,
                           stdout=proc_stdout,
                           stderr=proc_stderr)

        except Exception as e:
            return jsonify(success=False,
                    error=("Error RunCmd()"),
                    exception=str(e))

    else:
        return jsonify(success=False,
                    error=("Error: 'cmd' argument must be provided with each request to RunCmd"),
                    exception="")

@app.route("/ListRoutes", methods=['GET'])
@jsonp
def ListRoutes():
    routes = []

    for rule in app.url_map.iter_rules():
        routes.append('%s' % rule)

    return jsonify(success=True,
                   routes=[e for e in routes])

@app.route("/", methods=['GET'])
@jsonp
def DefaultPath():
    return jsonify(success=True,
                   message='This is the AD query service API, please contact Matthew.Brown.mls@gmail.com with any questions.')

if __name__ == "__main__":
    #app.run(ssl_context='adhoc', debug=True, host='0.0.0.0', port=9990)
    #pythoncom.CoInitialize()
    app.run(debug=True, host='0.0.0.0', port=port)
    #pythoncom.CoUninitialize()


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

# In[ ]:

#Question link - https://leetcode.com/problems/search-a-2d-matrix/
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False

        m = len(matrix)
        n = len(matrix[0])

        for i in range(m):
            for j in range(n):
                if matrix[i][j]>target:
                    continue
                if matrix[i][j] == target:
                    return True

        return False


import requests
from requests_html import HTMLSession
import json
import urllib.request
from bs4 import BeautifulSoup

def sacarDatos(url,urlBase):
    respuesta = {}

    this_session = HTMLSession()
    response = this_session.get(url)
    response.html.render()

    soup = BeautifulSoup(response.html.raw_html, "html.parser")

    # tipo de barco
    tipoBarco = soup.find_all("a", class_="active nav-link")[1].text
    respuesta["clase"] = tipoBarco

    respuesta["barcos"] = []

    divBody = soup.find_all("div", class_="card-body")
    divContenedor = divBody[0].find_all("div", class_="tab-pane active")
    divsBarcos = divContenedor[0].findChildren("div",recursive=False)

    # el primero es el filtro por tipos especiales
    divsBarcos.pop(0)

    for divsBarcosTier in divsBarcos:
        # Comprobar que no este vacio
        # tier
        tier = ""
        try:
            tier = divsBarcosTier.find("h3",class_="title").text.split(" ")[1]
        except:
            continue

        divsBarcos = divsBarcosTier.findChildren("div",recursive=False)[0].findChildren("div",recursive=False)
        for divBarco in divsBarcos:
            barco = {}

            # nombre
            nombre = divBarco.find("p").text

            print("-----------------------")
            print("Barco: "+nombre)

            # badges
            divBadges = divBarco.findChildren("div",recursive=False)[0]
            imgBadges = divBadges.find_all("img")
            badges = []
            if len(imgBadges)>0:
                for imgBadge in imgBadges:
                    badge = []
                    badge.append(imgBadge["src"])
                    badge.append(imgBadge["data-tip"])

                    badges.append(badge)

            # imagen barco
            imagenTag = divBarco.find("img",recursive=False)
            imagen = imagenTag["src"]
            imagenNombre = imagen.split("/")[-1]
            download_image(urlBase+urllib.parse.quote(imagen),imagenNombre)

            # rareza
            rareza = imagenTag.get_attribute_list('class')[-1]

            barco["nombre"] = nombre
            barco["tier"] = tier
            barco["imagen"] = imagenNombre
            barco["rareza"] = rareza
            barco["badges"] = badges

            respuesta["barcos"].append(barco)

    # print(json.dumps(respuesta))
    return respuesta

def download_image(url, file_name):
    full_path = "web/static/datos/img/" + file_name
    urllib.request.urlretrieve(url, full_path)


import logging
from datetime import datetime

from comm.chatterbase import ChatterBase
from comm.messageparser import MessageParser

class Chatter(ChatterBase):

    def __init__(self, config, collector, channel='saltybet'):
        self.collector = collector
        self.parser = MessageParser(collector)

        self.channel = '#' + channel
        self.last_message_date = datetime.now()

        server = 'irc.chat.twitch.tv'
        port = 6667
        logging.info(f'Connecting to {server} on port {port}...')

        username = config.auth[0]
        oauth_token = config.auth[1]
        ChatterBase.__init__(self, server, port, oauth_token, username)

    def on_welcome(self, connection, event):
        self.collector.state = None
        logging.info(f'Joining {self.channel}...')

        connection.join(self.channel)
        logging.info('Joined.')

    def on_pubmsg(self, connection, event):
        self.last_message_date = datetime.now()
        if event.source.nick != 'waifu4u':
            return

        message = event.arguments[0]
        logging.debug(f'{event.source.nick}: {message}')
        self.parser.parse(message)


from dash import html, dcc
import plotly.express as px
import pandas as pd
from sklearn.decomposition import PCA
import dash_bootstrap_components as dbc
from util.styles import BORDER_STYLE
from util.components import row
from util.styles import FIGURE_STYLE,border_style

# PCA
df_iris = px.data.iris()
X = df_iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]

pca = PCA(n_components=3)
components = pca.fit_transform(X)
total_var = pca.explained_variance_ratio_.sum() * 100

fig_iris = px.scatter_3d(
    components, x=0, y=1, z=2, color=df_iris['species'],
    # title=f'Total Explained Variance: {total_var:.2f}%',
    labels={'0': 'PC 1', '1': 'PC 2', '2': 'PC 3'}
)

fig_iris.update_layout(FIGURE_STYLE)

fig_scatter = px.scatter(df_iris, x="sepal_width",
                         y="sepal_length", color="species", symbol="species")

fig_scatter.update_layout(FIGURE_STYLE)

df = pd.read_csv(
    'https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv')

fig = px.scatter(df, x="gdp per capita", y="life expectancy",
                 size="population", color="continent", hover_name="country",
                 log_x=True, size_max=60)

fig.update_layout(FIGURE_STYLE)

analysis_layout = html.Div(children=[

    html.H2(children='Iris Data PCA 3D', style={'color': 'white'}),

    row([
        dcc.Graph(
            id='iris-exp-vs-gdp',
            figure=fig_iris,
            style=BORDER_STYLE
        ),
        dcc.Graph(
            id='iris-exp-vs-gdp',
            figure=fig_iris,
            style=BORDER_STYLE
        ),
    ]),

    html.H2(children='''
        Iris Data PCA 2D
    ''', style={'color': 'white'}),

    dcc.Graph(
        id='iris-2d-vs-gdp',
        figure=fig_scatter,
        style=BORDER_STYLE
    ),

    html.H2(children='''
            Official Dash example
        ''', style={'color': 'white', 'margin-top': 30}),

    html.Div([

        dcc.Graph(
            id='life-exp-vs-gdp',
            figure=fig,
            style=BORDER_STYLE
        ),

    ], style=BORDER_STYLE),

])


from django import template
from django.template import Variable
from django.template.loader import render_to_string
from django.db.models import Avg

register = template.Library()

from django_votes.models import VotesField
from django_votes.utils import get_vote_model

class VoteNode(template.Node):
    def __init__(self, object):
        self.object = object

    def get_info(self, context):
        v = Variable(self.object)
        object = v.resolve(context)

        self.model_name = '%s.%sVote' % (object._meta.app_label,
                                         object._meta.object_name,)

        self.model = get_vote_model(self.model_name)

        return object

class UpDownVoteNode(VoteNode):
    def render(self, context):
        object = self.get_info(context)

        total_votes = self.model.objects.filter(object__id=object.id).count()

        up_votes = self.model.objects.filter(object__id=object.id,
                                             value=1).count()

        down_votes = self.model.objects.filter(object__id=object.id,
                                               value= -1).count()

        up_pct = (float(up_votes) / float(total_votes) if total_votes else 0) * 98
        down_pct = (float(down_votes) / float(total_votes) if total_votes else 0) * 98

        dictionary = {'object': object,
                      'model_name': self.model_name,
                      'up_pct': up_pct,
                      'down_pct': down_pct,
                      'up_votes': up_votes,
                      'down_votes': down_votes,
                      'total_votes': total_votes}

        return render_to_string('django_votes/updownvote.html', dictionary, context_instance=context)

class RatingVoteNode(VoteNode):
    def render(self, context):
        object = self.get_info(context)

        avg = self.model.objects.filter(object__id=object.id).aggregate(value=Avg('value'))

        dictionary = {'rating': int(avg['value']) if 'value' in avg else None,
                      'object': object,
                      'model_name': self.model_name}

        return render_to_string('django_votes/rating.html', dictionary, context_instance=context)

@register.tag
def updown_vote(parser, token):

    args = token.split_contents()

    object = args[1]

    return UpDownVoteNode(object)

@register.tag
def rating_vote(parser, token):

    args = token.split_contents()

    object = args[1]

    return RatingVoteNode(object)


import cifar10, cifar10_input
import tensorflow as tf
import numpy as np
import time
import math
import matplotlib.pyplot as plt

max_steps = 300
batch_size = 128
data_dir='/tmp/cifar10_data/cifar-10-batches-bin'

def variable_with_weight_loss(shape, stddev, wl=None):
    '''创建变量

    创建变量，并为变量添加L2约束'''
    var = tf.Variable(tf.truncated_normal(shape, stddev=stddev))
    if wl is not None:
        weight_loss = tf.multiply(tf.nn.l2_loss(var), wl, name='weight_loss')
        tf.add_to_collection('losses', weight_loss)
    return var

##下载数据集
cifar10.maybe_download_and_extract()

##生成增强(distorted)过的训练数据
images_train, labels_train = cifar10_input.distorted_inputs(data_dir=data_dir, batch_size=batch_size)
##生成测试数据，只裁剪，无增强
images_test, labels_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size)

##创建输入数据的占位符
images_holder = tf.placeholder(dtype=tf.float32, shape=[batch_size, 24, 24, 3])
labels_holder = tf.placeholder(dtype=tf.int32, shape=[batch_size])

#================================↓开始构建正向网络↓==================================

#======================================
#            创建第一个卷积层
#======================================
w_conv1 = variable_with_weight_loss(shape=[5, 5, 3, 64], stddev=0.05)
b_conv1 = tf.Variable(tf.constant(0.0, shape=[64]))
conv_conv1 = tf.nn.conv2d(input=images_holder, filter=w_conv1, strides=[1, 1, 1, 1], padding='SAME')
h_conv1 = tf.nn.relu(tf.nn.bias_add(conv_conv1, b_conv1))
h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
norm1 = tf.nn.lrn(h_pool1, depth_radius=4, alpha=0.001/9.0, beta=0.75)

#======================================
#            创建第二个卷积层
#======================================
w_conv2 = variable_with_weight_loss(shape=[5, 5, 64, 64], stddev=5e-2)
b_conv2 = tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[64]))
conv_conv2 = tf.nn.conv2d(norm1, w_conv2, strides=[1, 1, 1, 1], padding='SAME')
h_conv2 = tf.nn.relu(tf.nn.bias_add(conv_conv2, b_conv2))
norm2 = tf.nn.lrn(h_conv2, 4, bias=1.0, alpha=0.001/9.0, beta=0.75)
h_pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')

#======================================
#            创建第一个全连接层
#======================================
reshape = tf.reshape(h_pool2, shape=[batch_size, -1])
dim = reshape.get_shape()[1].value
w_fc1 = variable_with_weight_loss([dim, 384], stddev=0.04, wl=0.004)
b_fc1 = tf.Variable(tf.constant(0.1, shape=[384]))
h_fc1 = tf.nn.relu(tf.matmul(reshape, w_fc1) + b_fc1)

#======================================
#            创建第二个全连接层
#======================================
w_fc2 = variable_with_weight_loss([384, 192], stddev=0.04, wl=0.004)
b_fc2 = tf.Variable(tf.constant(0.1, shape=[192]))
h_fc2 = tf.nn.relu(tf.matmul(h_fc1, w_fc2) + b_fc2)

#======================================
#            创建输出层
#======================================
w_out = variable_with_weight_loss([192, 10] ,stddev=1/192) #stddev设置为输入节点数的倒数
b_out = tf.Variable(tf.constant(0.0, shape=[10]))
y_out = tf.add(tf.matmul(h_fc2, w_out), b_out)

#================================↑正向网络构建完毕↑==================================

#======================================
#            定义模型损失函数
#======================================
def loss(logits, labels):
    '''计算模型损失

    输入参数：
     logits: 网络输出层的输出
     labels: 训练数据或测试数据的类别标签

    输出：模型的总体损失，包括交叉熵和正则化项'''

    labels = tf.cast(labels, tf.int64)
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    tf.add_to_collection('losses', cross_entropy_mean)

    return tf.add_n(tf.get_collection('losses'), name='total_loss')

loss = loss(y_out, labels_holder)

##采用Adam优化器，最小化总体损失
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)

top_k_op = tf.nn.in_top_k(y_out, labels_holder, 1)

#================================开始训练==================================
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

tf.train.start_queue_runners() #启动线程队列

for step in range(max_steps):
    start_time = time.time()
    image_batch, label_batch = sess.run([images_train, labels_train])
    _, loss_value = sess.run([train_op, loss], feed_dict={images_holder:image_batch, labels_holder:label_batch})
    duration = time.time() - start_time
    if (step+1)%10 == 0:
        examples_per_sec = batch_size / duration
        sec_per_example = float(duration)

        format_str = ('step%d, loss=%.2f (%.1f examples/sec, %.3f sec/batch)')
        real_step = step + 1
        print(format_str % (real_step, loss_value, examples_per_sec, sec_per_example))

#================================评估测试机上的准确率==================================
num_examples = 10000
num_iter = int(math.ceil(num_examples/batch_size))
totle_sample_count = num_iter * batch_size
true_count = 0
for step in range(num_iter):
    image_batch, label_batch = sess.run([images_test, labels_test])
    predictions = sess.run([top_k_op],
                            feed_dict={images_holder:image_batch,
                                       labels_holder:label_batch})
    true_count += np.sum(predictions)

precision = true_count / totle_sample_count
print('precision @ 1 = %.3f' % precision)


import aocd

data = """Player 1 starting position: 4
Player 2 starting position: 8"""

data = aocd.get_data(year=2021, day=21)

pos = [int(data[28]), int(data[-1])]
score = [0, 0]

player = 0
die = 99

rolled = 0
while True:
    for _ in range(3):
        die += 1
        rolled += 1
        pos[player] += (die % 100) + 1
    score[player] += ((pos[player] - 1) % 10) + 1

    if score[player] >= 1000:
        print(score[1 - player] * rolled)
        break

    player = 1 - player


#demonstration framework of writing out a netcdf file from python

#Robert Grumbine
#20 August 2020

import numpy
from netCDF4 import Dataset

rootgrp = Dataset("test.nc","w", format="NETCDF4")

nx   = int(360*12)
ny   = int(180*12)
dlat = 1./12.
dlon = 1./12.

#skip_hr is the byte file flagging points to skip in computing sea ice metrics
fin = open("skip_hr","rb")
dt = numpy.dtype('ubyte')
x = numpy.zeros((nx,ny),dtype=dt)
x = numpy.fromfile(fin,dtype=dt,count=nx*ny)
x.shape = (ny,nx)
print("x max ",x.max(), x.min())

lat = rootgrp.createDimension("lat", ny)
lon = rootgrp.createDimension("lon", nx)

masks = rootgrp.createVariable("skip","ubyte",("lat","lon")  )
masks.units = "none"

#Seems to be important to initialize at least a single element before
#  assigning from x
masks[:,:] = 0
masks = x
print("max ",masks.max(), masks.min(), masks[5,5])

lats  = rootgrp.createVariable("latitude","f4",("lat"))
lats.units = "Degrees N"
lats[:] = 0.0
lats = numpy.arange(-90+dlat/2., 180., dlat)
print("lats: ",lats.max(), lats )

lons  = rootgrp.createVariable("longitude","f4",("lon"))
lons.units = "Degrees E"
lons[:] = 0.0
lons = numpy.arange(    dlon/2., 360., dlon)
print("lons: ",lons.max(), lons )


# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rec(self, head):
        if (head == None):
            is_uni = True
            uval = None
            num = 0
            return is_uni, uval, num
        if (head.left == None and head.right == None):
            is_uni = True
            uval = head.val
            num = 1
            return is_uni, uval, num

        l_is_uni, l_uval, l_num = self.rec(head.left)
        r_is_uni, r_uval, r_num = self.rec(head.right)

        is_uni = False
        uval = None
        num = l_num + r_num
        if (l_is_uni == True and r_is_uni == True and l_uval == r_uval and l_uval == head.val):
            is_uni = True

        if (l_is_uni == True and r_is_uni == True and (
                l_uval == None and head.val == r_uval or r_uval == None and head.val == l_uval)):
            is_uni = True

        if (is_uni == True and l_uval == r_uval):
            uval = l_uval
            num += 1

        if (is_uni == True and l_uval == None and r_uval != None):
            uval = r_uval
            num += 1

        if (is_uni == True and r_uval == None and l_uval != None):
            uval = l_uval
            num += 1
        return is_uni, uval, num

    def solve(self, root):
        is_uni, uval, num = self.rec(root)
        return num


import os
import sys
import asyncio
import logging
import colorlog

import yaml

from ..common import crypto
from .router import mgr as routermgr
from .router import api as apigroup

from ..models.database import db
from ..models.channel import mgr as chanmgr
from ..models.key import mgr as keymgr
from ..models.router import group as routergroup
from ..models.watchdog import wd as wdmgr

from .adapter import revChatGPT
from .adapter import claude
from .adapter import bard
from .adapter import gpt4free
from .adapter import hugchat
from .adapter import qianwen

from . import log
from . import cfg as cfgutil

class Application:
    """Application instance."""

    dbmgr: db.DatabaseInterface
    """Database manager."""""

    router: routermgr.RouterManager
    """Router manager."""

    channel: chanmgr.AbsChannelManager
    """Channel manager."""

    key: keymgr.AbsAPIKeyManager
    """API Key manager."""

    watchdog: wdmgr.AbsWatchDog

    logging_level: int = logging.INFO

    def __init__(
        self,
        dbmgr: db.DatabaseInterface,
        router: routermgr.RouterManager,
        channel: chanmgr.AbsChannelManager,
        key: keymgr.AbsAPIKeyManager,
        watchdog: wdmgr.AbsWatchDog,
        logging_level: int = logging.INFO,
    ):
        self.dbmgr = dbmgr
        self.router = router
        self.channel = channel
        self.key = key
        self.watchdog = watchdog
        self.logging_level = logging_level

    async def run(self):
        """Run application."""
        loop = asyncio.get_running_loop()

        loop.create_task(self.watchdog.run())

        await self.router.serve(loop)

log_colors_config = {
    'DEBUG': 'green',  # cyan white
    'INFO': 'white',
    'WARNING': 'yellow',
    'ERROR': 'red',
    'CRITICAL': 'cyan',
}

default_config = {
    "1-documentation": "see at https://github.com/RockChinQ/free-one-api",
    "database": {
        "type": "sqlite",
        "path": "./data/free_one_api.db",
    },
    "watchdog": {
        "heartbeat": {
            "interval": 1800,
            "timeout": 300,
            "fail_limit": 3,
        },
    },
    "router": {
        "port": 3000,
        "token": "12345678",
    },
    "web": {
        "frontend_path": "./web/dist/",
    },
    "logging": {
        "debug": False,
    },
    "random_ad": {
        "enabled": False,
        "rate": 0.05,
        "ad_list": [
            " (This response is sponsored by Free One API. Consider star the project on GitHub: https://github.com/RockChinQ/free-one-api )",
        ]
    },
    "misc": {
        "chatgpt_api_base": "https://chatproxy.rockchin.top/api/",
    }
}

async def make_application(config_path: str) -> Application:
    """Make application."""
    if not os.path.exists(config_path):
        with open(config_path, "w") as f:
            yaml.dump(default_config, f)
            print("Config file created at", config_path)
            # print("Please edit it and run again.")
            # sys.exit(0)
    config = {}
    with open(config_path, "r") as f:
        config = yaml.load(f, Loader=yaml.FullLoader)

    # complete config
    config = cfgutil.complete_config(config, default_config)

    # dump config
    with open(config_path, "w") as f:
        yaml.dump(config, f)

    # set default values
    from .adapter import revChatGPT

    revChatGPT.RevChatGPTAdapter.CHATGPT_API_BASE = config['misc']['chatgpt_api_base']

    # logging
    logging_level = logging.INFO

    if 'logging' in config and 'debug' in config['logging'] and config['logging']['debug']:
        logging_level = logging.DEBUG

    if 'DEBUG' in os.environ and os.environ['DEBUG'] == 'true':
        logging_level = logging.DEBUG

    print("Logging level:", logging_level)
    logging.debug("Debug mode enabled.")

    terminal_out = logging.StreamHandler()

    terminal_out.setLevel(logging_level)
    terminal_out.setFormatter(colorlog.ColoredFormatter(
        "[%(asctime)s.%(msecs)03d] %(log_color)s%(pathname)s (%(lineno)d) - [%(levelname)s] :\n"
            "%(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        log_colors=log_colors_config,
    ))

    for handler in logging.getLogger().handlers:
        logging.getLogger().removeHandler(handler)

    logging.getLogger().addHandler(terminal_out)

    # save ad to runtime
    if 'random_ad' in config and config['random_ad']['enabled']:
        from ..common import randomad

        randomad.enabled = config['random_ad']['enabled']
        randomad.rate = config['random_ad']['rate']
        randomad.ads = config['random_ad']['ad_list']

    from ..common import randomad

    # make database manager
    from .database import sqlite as sqlitedb

    dbmgr_cls_mapping = {
        "sqlite": sqlitedb.SQLiteDB,
    }

    dbmgr = dbmgr_cls_mapping[config['database']['type']](config['database'])
    await dbmgr.initialize()

    # database handler
    dblogger = log.SQLiteHandler(dbmgr)

    # failed to set debug level for db handler
    dblogger.setLevel(logging.INFO if logging_level <= logging.INFO else logging_level)
    dblogger.setFormatter(logging.Formatter("[%(asctime)s.%(msecs)03d] %(pathname)s (%(lineno)d) - [%(levelname)s] :\n%(message)s"))

    logging.getLogger().addHandler(dblogger)

    # make channel manager
    from .channel import mgr as chanmgr

    channelmgr = chanmgr.ChannelManager(dbmgr)
    await channelmgr.load_channels()

    # make key manager
    from .key import mgr as keymgr

    apikeymgr = keymgr.APIKeyManager(dbmgr)
    await apikeymgr.list_keys()

    # make forward manager
    from .forward import mgr as forwardmgr

    fwdmgr = forwardmgr.ForwardManager(channelmgr, apikeymgr)

    # make router manager
    from .router import mgr as routermgr

    #   import all api groups
    from .router import forward as forwardgroup
    from .router import api as apigroup
    from .router import web as webgroup

    # ========= API Groups =========
    group_forward = forwardgroup.ForwardAPIGroup(dbmgr, channelmgr, apikeymgr, fwdmgr)
    group_api = apigroup.WebAPIGroup(dbmgr, channelmgr, apikeymgr)
    group_api.tokens = [crypto.md5_digest(config['router']['token'])]
    group_web = webgroup.WebPageGroup(config['web'], config['router'])

    paths = []

    paths += group_forward.get_routers()
    paths += group_web.get_routers()
    paths += group_api.get_routers()

    # ========= API Groups =========

    routermgr = routermgr.RouterManager(
        routes=paths,
        config=config['router'],
    )

    # watchdog and tasks
    from .watchdog import wd as watchdog

    wdmgr = watchdog.WatchDog()

    # tasks
    from .watchdog.tasks import heartbeat

    hbtask = heartbeat.HeartBeatTask(
        channelmgr,
        config['watchdog']['heartbeat'],
    )

    wdmgr.add_task(hbtask)

    app = Application(
        dbmgr=dbmgr,
        router=routermgr,
        channel=channelmgr,
        key=apikeymgr,
        watchdog=wdmgr,
        logging_level=logging_level,
    )

    logging.info("Application initialized.")

    return app


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 13:47:07 2019

@author: jg
"""

import matplotlib.pyplot as plt

L=range(1,7)

def sp(L):
    M=[]
    for i in range(len(L)):
        if i%2==0:
            M.append(L[-i/2-1])
        else:
            M.append(L[(i+1)/2-1])
    return(M)

print(sp(range(1,7)))
print(sp(range(1,8)))

for i in range(6):
    L=sp(L)
print(L)

def p(L):
    n=1
    Lorigine=L
    while sp(L)!=Lorigine:
        L=sp(L)
        n=n+1
    return(n)

X=range(1,100)
Y=[]
for i in X:
    Y.append(p(range(0,i))/float(i))

plt.plot(X,Y)

print(Y.index(min(Y)))