from selenium import  webdriver
from new_selenium.bin.login import Login
from new_selenium.bin.main import Method
import time
from selenium.common.exceptions import NoSuchElementException
from new_selenium.tech_rams.rams_config import *
from config.config import path_dir
from config.log_config import logger
from bin.select_fault_occur import deal_fault

class Picture:
    def log_file_out(self,msg):
        fo = open(r'{}/usecase.txt'.format(path_dir), mode='a', encoding='utf-8')
        fo.write(msg + '\r\n')
        fo.close()

    def correct(self,url,username,password,db,value,value1,start,end,car,fault,select_fault,fault1,time_sleep,wait_time):

        driver = webdriver.Chrome()
        Login().login(url,username, password, driver)

        self.log_file_out('-----图形正确性-----')
        for i in contents:
            try:
                Method(driver).contains_xpath('click',i)
                self.log_file_out('点击'+i+'成功')
            except Exception as e:
                logger.error(e)
                self.log_file_out('点击' + i + '失败')
        time.sleep(2)
        js_s = " return $('#switchDb').prop('checked')"
        status = driver.execute_script(js_s)
        if db == '默认':
            if status is True:
                Method(driver).click('class', 'onoffswitch-label')
            else:
                time.sleep(1)
        else:
            if status is True:
                time.sleep(1)
            else:
                Method(driver).click('class', 'onoffswitch-label')

        time.sleep(time_sleep)
        try:
            Method(driver).switch_out()
            Method(driver).switch_iframe(
                driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/disposableModel/form')]"))
            time.sleep(time_sleep)
        except NoSuchElementException as e:
            self.log_file_out('切入iframe失败')

        try:
            Method(driver).select_down_list('id', 'modelObject', value)
            if value1 == '里程':
                Method(driver).input('id', 'confMileageList0_startMileage', start)
                Method(driver).input('id', 'confMileageList0_endMileage', end)
            elif value1 == '时间':
                time.sleep(time_sleep)
                Method(driver).select_down_list('id', 'confMileageSelect', 1)
                time.sleep(time_sleep)
                Method(driver).input('name', 'confDateList[0].startDate', start)
                Method(driver).input('name', 'confDateList[0].endDate', end)

        except NoSuchElementException as e:
            print('模型基本信息输入失败')
        except:
            print('请录入评估对象')
            return

        try:
            Method(driver).contains_xpath('click', '新增')
        except NoSuchElementException as e:
            print('点击新建按钮失败')

        try:
            Method(driver).switch_out()
            b = Method(driver).get_attr('css', "[class='layui-layer layui-layer-iframe my-skin']", 'times')
            Method(driver).switch_iframe('layui-layer-iframe' + b)
        except:
            print('请录入评估对象')
            return

        time.sleep(time_sleep)

        # 车型 车号新增页面

        if select_fault == '交集':
            js_s = "return $('#partType').prop('checked')"
            status = driver.execute_script(js_s)
            if status is True:
                Method(driver).click('id', 'partType')
            else:
                time.sleep(1)
        elif select_fault == '并集':
            js_s = "return $('#partType').prop('checked')"
            status = driver.execute_script(js_s)
            if status is True:
                time.sleep(1)
            else:
                Method(driver).click('id', 'partType')

        try:
            for x in car:
                driver.find_element_by_xpath(
                    "//span[@class='train zoomIn' and contains(text(),\'{}\')]".format(x)).click()
                car_num = car.get(x)
                time.sleep(2)
                for i in car_num:
                    # driver.find_element_by_xpath("//span[contains(text(),\'{}\')]".format(i)).click()
                    car_num = driver.find_element_by_xpath(
                        '//span[contains(text(),\'{}\')]/..'.format(i)).get_attribute('id')

                    js = 'top.checked(top.$("#{}"))'.format(car_num)
                    driver.execute_script(js)

                    # time.sleep(2)
                driver.execute_script('top.$(".layui-layer-btn0")[1].click()')
                time.sleep(2)
            Method(driver).switch_out()

            Method(driver).two_element_click("[class='layui-layer layui-layer-iframe my-skin']", 'layui-layer-btn1')
        except NoSuchElementException as e:
            logger.error('xpath' + '不存在!')

        # 故障模式选择页面
        Method(driver).switch_out()
        c = Method(driver).get_attr('css', "[class='layui-layer layui-layer-iframe my-skin']", 'times')
        Method(driver).switch_iframe('layui-layer-iframe' + c)
        time.sleep(5)

        fault_status = deal_fault(driver, fault)
        if fault_status is True:
            self.log_file_out('故障模式选择成功')
        else:
            self.log_file_out('故障模式选择失败')

        try:
            Method(driver).switch_out()
            Method(driver).click('class', 'layui-layer-btn2')
        except NoSuchElementException as e:
            logger.error('xpath' + '不存在!')
            self.log_file_out('点击确定按钮失败')
        except:
            self.log_file_out('请录入完整的模型')
            return

        time.sleep(time_sleep)
        try:
            Method(driver).switch_out()
            Method(driver).switch_iframe(
                driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/disposableModel/form')]"))
            Method(driver).click('id', 'calculate')
            self.log_file_out('点击计算按钮成功')
        except:
            self.log_file_out('点击计算按钮失败')

        time.sleep(wait_time)
        try:
            Method(driver).switch_out()
            Method(driver).switch_iframe(
                driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/disposableModel/data_view')]"))
            driver.maximize_window()
            Method(driver).click('id', 'tab-1-btn1')
        except:
            self.log_file_out('请输入正确的模型')
            return

        Method(driver).click('id','tab-1-btn1')
        time.sleep(1)
        Method(driver).click('id','tab1chart1')

        time.sleep(2)
        js = 'var aa = echarts.getInstanceByDom($("#tab1chart1")[0]);'\
             'var option = aa.getOption();' \
             'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'

        try:
            value_baiwan = driver.execute_script(js)
        except:
            self.log_file_out('获取值失败')

        time.sleep(2)
        Method(driver).click('id','tab-1-btn3')
        time.sleep(1)
        Method(driver).click('id','tab1chart3')

        js1 = 'var aa = echarts.getInstanceByDom($("#tab1chart3")[0]);' \
              'var option = aa.getOption();' \
              'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_pinjun = driver.execute_script(js1)
        except:
            self.log_file_out('获取值失败')

        time.sleep(2)
        Method(driver).click('id', 'tab-1-btn4')
        time.sleep(1)
        Method(driver).click('id', 'tab1chart4')

        js2 = 'var aa = echarts.getInstanceByDom($("#tab1chart4")[0]);' \
              'var option = aa.getOption();' \
              'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_guzhang = driver.execute_script(js2)
        except:
            self.log_file_out('获取值失败')

        time.sleep(2)
        Method(driver).click('id','tab-1-btn5')
        time.sleep(1)
        Method(driver).click('id', 'tab-1-btn2')
        time.sleep(1)
        Method(driver).click('id', 'tab1chart2')

        js3 = 'var aa = echarts.getInstanceByDom($("#tab1chart2")[0]);' \
              'var option = aa.getOption();' \
              'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_guyou = driver.execute_script(js3)
        except:
            self.log_file_out('获取值失败')

        time.sleep(2)
        Method(driver).click('xpath','/html/body/div/ul/li[2]/a')

        time.sleep(2)
        Method(driver).click('id', 'tab-2-chart1')
        time.sleep(1)
        Method(driver).click('id', 'tab2chart1')

        js4 = 'var aa = echarts.getInstanceByDom($("#tab2chart1")[0]);' \
              'var option = aa.getOption();' \
              'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_danyi = driver.execute_script(js4)
        except:
            self.log_file_out('获取值失败')

        time.sleep(2)

        Method(driver).switch_out()
        driver.find_element_by_class_name('layui-layer-ico ').click()

        time.sleep(2)

        Method(driver).switch_out()
        time.sleep(1)
        Method(driver).contains_xpath('click','产品RAMS指标统计评估')

        time.sleep(2)

        Method(driver).switch_out()
        Method(driver).switch_iframe(
            driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/confModel')]"))
        time.sleep(2)

        driver.find_element_by_xpath("//a[contains(text(),\'{}\')]/../../td[8]/a[3]".format('图值正确模型')).click()
        time.sleep(2)
        Method(driver).switch_out()

        driver.find_element_by_class_name('layui-layer-btn0').click()
        time.sleep(2)
        Method(driver).switch_out()
        Method(driver).switch_iframe(
            driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/confModel')]"))
        time.sleep(5)
        driver.find_element_by_xpath("//a[contains(text(),\'{}\')]/../../td[8]/a[4]".format('图值正确模型')).click()

        time.sleep(2)
        Method(driver).switch_out()
        c = Method(driver).get_attr('css', "[class='layui-layer layui-layer-iframe']", 'times')
        Method(driver).switch_iframe('layui-layer-iframe' + c)

        time.sleep(2)
        Method(driver).click('id','chart1')

        js_rams1 = 'var aa = echarts.getInstanceByDom($("#chart1")[0]);' \
             'var option = aa.getOption();' \
              'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_baiwan1 = driver.execute_script(js_rams1)
        except:
            self.log_file_out('获取值失败')

        if len([item for item in value_baiwan[0] if not item in value_baiwan1[0]]) != 0 and len([item for item in value_baiwan[1] if not item in value_baiwan1[1]]) != 0:
            self.log_file_out('百万公里图的值不一致')
        else:
            self.log_file_out('百万公里的值一致')
        time.sleep(2)
        Method(driver).click('id','chart2')

        js_rams2 = 'var aa = echarts.getInstanceByDom($("#chart2")[0]);' \
                   'var option = aa.getOption();' \
                   'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_guzhang1 = driver.execute_script(js_rams2)
        except:
            self.log_file_out('获取值失败')

        L = [item for item in value_guzhang[0] if not item in value_guzhang1[0]]
        L1 = [item for item in value_guzhang[1] if not item in value_guzhang1[1]]
        L2 = ['0.00']
        if  len([item for item in L if not item in L2]) != 0 and len([item for item in L1 if not item in L2]) != 0:
            self.log_file_out('平均故障的值不一致')
        else:
            self.log_file_out('平均故障的值一致')

        time.sleep(2)
        Method(driver).click('id', 'chart3')
        js_rams3 = 'var aa = echarts.getInstanceByDom($("#chart3")[0]);' \
                   'var option = aa.getOption();' \
                   'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'

        try:
            value_pingjun1 = driver.execute_script(js_rams3)
        except:
            self.log_file_out('获取值失败')

        if len([item for item in value_pinjun[0] if not item in value_pingjun1[0]]) != 0 and len([item for item in value_pinjun[1] if not item in value_pingjun1[1]]) != 0:
            self.log_file_out('平均时间的值不一致')
        else:
            self.log_file_out('平均时间的值一致')

        time.sleep(2)
        Method(driver).click('id', 'chart4')
        js_rams4 = 'var aa = echarts.getInstanceByDom($("#chart4")[0]);' \
                   'var option = aa.getOption();' \
                   'return [[option.series[0].data[1],option.series[1].data[1],option.series[2].data[1],option.series[3].data[1],option.series[4].data[1]],[option.series[0].data[4],option.series[1].data[4],option.series[2].data[4],option.series[3].data[4],option.series[4].data[4]]]'
        try:
            value_guyou1 = driver.execute_script(js_rams4)
        except:
            self.log_file_out('获取值失败')

        if len([item for item in value_guyou[0] if not item in value_guyou1[0]]) != 0 and len([item for item in value_guyou[1] if not item in value_guyou1[1]]) != 0:
            self.log_file_out('固有可用度的值不一致')
        else:
            self.log_file_out('固有可用度的值一致')

        driver.execute_script('top.$(".layui-layer-ico")[1].click()')

        Method(driver).switch_out()
        time.sleep(1)
        Method(driver).contains_xpath('click', '单一模型指标分析')

        Method(driver).switch_out()
        Method(driver).switch_iframe(
            driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/singleModel')]"))

        driver.find_element_by_xpath(
            "//a[contains(text(),\'{}\')]/../../td[8]/a[3]".format('图形')).click()

        time.sleep(2)
        Method(driver).switch_out()

        driver.find_element_by_class_name('layui-layer-btn0').click()
        time.sleep(2)
        Method(driver).switch_out()
        Method(driver).switch_iframe(
            driver.find_element_by_xpath("//iframe[contains(@src,'/darams/a/mould/singleModel')]"))
        time.sleep(5)
        driver.find_element_by_xpath(
            "//a[contains(text(),\'{}\')]/../../td[8]/a[4]".format('图形')).click()

        Method(driver).switch_out()
        c = Method(driver).get_attr('css', "[class='layui-layer layui-layer-iframe']", 'times')
        Method(driver).switch_iframe('layui-layer-iframe' + c)

        time.sleep(2)
        Method(driver).click('id', 'maxMin')

        js_danyi = 'var aa = echarts.getInstanceByDom($("#maxMin")[0]);' \
              'var option = aa.getOption();' \
              'return[[option.series[6].data[1],option.series[8].data[1],option.series[4].data[1],option.series[0].data[1],option.series[3].data[1]],[option.series[6].data[4],option.series[8].data[4],option.series[4].data[4],option.series[0].data[4],option.series[3].data[4]]]'
        try:
            value_danyi1 = driver.execute_script(js_danyi)
        except:
            self.log_file_out('获取值失败')

        L3 = [item for item in value_danyi[0] if not item in value_danyi1[0]]
        L4 = [item for item in value_danyi[1] if not item in value_danyi1[1]]
        L5 = [item for item in L3 if not item in L4]
        if len(L5) != 0:
            self.log_file_out('单一模型值不一致')
        else:
            self.log_file_out('单一模型值一致')

url = 'http://192.168.1.115:8080/darams/a/login'
car = {
    'E27': ['2641','2642','2643','2644','2645','2646','2647']
}

fault_pattern = {'高压供电系统':'all'}

#
fault1 = {'辅助供电系统':'all'}

time_sleep = 3
wait_time = 10

Picture().correct(url,'test','1234','切换',1,'里程','0','100',car,fault_pattern,'交集',fault1,time_sleep,wait_time)


# -*- coding: utf-8 -*-
from selenium import webdriver
import unittest

# didn't actually run, couldn't get Appium to work properly

class SearchProductsOnIphone(unittest.TestCase):
    """SearchProductsOnIphone
    """

    # need RemoteWebDriver to run tests with Appium. To use desired
    # platform, pass set of desired capailities
    def setUp(self):
        desired_caps = {}
        # platform
        desired_caps['device'] = 'iPhone Simulator'
        # platform vesion
        desired_caps['version'] = '7.1'
        # mobile browser
        desired_caps['app'] = 'safari'

        # connect to Appium server
        # pass desired capabilities to RemoteWebDriver
        self.driver = webdriver.Remote(
            'http://127.0.0.1:4723/wd/hub',
            desired_caps
        )
        self.desired_caps.get(
            'http://demo.magentocommerce.com/'
        )
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

    def tearDown(self):
        self.driver.quit()

    def teatSearchByCategory(self):
        # click on serch idcon
        self.driver.find_element_by_xpath(
            "//a[@href='#header-search']"
        ).click()

        self.search_field = self.driver.find_element_by_name('q')
        self.search_field.clear()

        self.search_field.send_keys('phones')
        self.search_field.submit()

        # get all anchor elements which have product names
        # displayed on current page using xpath method
        products = self.driver.find_element_by_xpath(
            "//div[@class='catagory-products'/ul/li"
        )

        # check products count
        self.assertEqual(2, len(products))

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


from random import seed, shuffle
import numpy as np
import time
import json

# global
DATA_SIZE = 64

''' Random set '''
seed(time.time())
nums = list(range(1, DATA_SIZE+1))
shuffle(nums)
colors = [(0, 0.5 + n/(2*DATA_SIZE), 1 - n/(2*DATA_SIZE), 1) for n in nums]
data = [[nums[i], colors[i]] for i in range(len(nums))]

fo = open("random_data.json", "w")
json.dump(obj=data, fp=fo)

''' Decending set '''
nums = list(range(DATA_SIZE, 0, -1))
colors = [(0, 0.5 + n/(2*DATA_SIZE), 1 - n/(2*DATA_SIZE), 1) for n in nums]
data = [[nums[i], colors[i]] for i in range(len(nums))]

fo = open("decending_data.json", "w")
json.dump(obj=data, fp=fo)

''' Read data '''
# fr = open("random_data.json")
# raw_data = json.load(fp=fr)
# print(raw_data)


from __future__ import print_function

import unittest
from backtest import Backtest
from data import SecurityMasterDataHandler
from execution import *
from portfolio import Portfolio
from order import *

class StrategiesTest(unittest.TestCase):

    def setUp(self):

        import sys

        if '../../SqlConnWraper' not in sys.path:
            sys.path.append('../../SqlConnWraper')

        if '../Strategies' not in sys.path:
            sys.path.append('../Strategies')

        from BuildSQLConnection import build_sql_conn

        self.cxcn = build_sql_conn('../config.ini')

    def test_mac_strategy(self):
        """
        Unit test for Moving Average Crossover Strategy

        :return:
        """

        from mac import MovingAverageCrossStrategy

        symbol_list = ['AAPL']
        initial_capital = 100000.0
        heartbeat = 0.0

        data_handler = SecurityMasterDataHandler(symbol_list, self.cxcn)

        start_date = data_handler.start_dt

        order_method = EquityWeightOrder

        backtest = Backtest(
            symbol_list, initial_capital, heartbeat,
            start_date, data_handler, SimulatedExecutionHandlerWithCommision,
            Portfolio, MovingAverageCrossStrategy, order_method
        )

        backtest.simulate_trading()

        print(backtest.portfolio.summary_stats)

        self.assertAlmostEqual(backtest.portfolio.summary_stats['Total Return'],
                               -11.908907924000056, places=7, msg=None, delta=None)

        self.assertAlmostEqual(backtest.portfolio.summary_stats['Sharpe Ratio'],
                               0.17652509997281265, places=7, msg=None, delta=None)

        self.assertAlmostEqual(backtest.portfolio.summary_stats['Max Drawdown'],
                               74.337676325221068, places=7, msg=None, delta=None)

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


n = int(input())
s = input().split()
x = []
for i in s:
    x.append(int(i))
counter = 0
for i in range(1, len(x) - 1):
    if x[i] > x[i - 1] and x[i] > x[i + 1]:
        counter += 1
print(counter)


import os
from scipy.signal import chirp, find_peaks, peak_widths
import scipy.signal as signal
import matplotlib.pyplot as plt
import numpy as np
import constant as const
import multiprocessing
plt.switch_backend('agg')

b = const.x_max/3e8/const.dt_snapshot/2
x = int(b)
Ey=np.load("baktxt/"+const.data_name+str(x)+"Ey_y0.npy")
data=Ey
x=np.abs(np.fft.rfft(Ey))
max_x=x.max()/10

def a0_x(x):
    if os.path.exists("baktxt/"+const.data_name+str(x)+"Ey_y0.npy")==False:
        #print("baktxt/"+const.data_name+str(x)+"Ey_y0.txt")
        return np.nan,np.nan,np.nan

    #p "draw",x
    Ey=np.load("baktxt/"+const.data_name+str(x)+"Ey_y0.npy")

    #Ey=np.loadtxt('3500Ey_y0.txt')
    data=Ey

    x=np.abs(np.fft.rfft(Ey))
    x.max()/3
    peaks, _ = find_peaks(x,prominence=max_x)
    if len(peaks) == 0:
        return np.nan,np.nan,np.nan
    T=const.x_end/3e8
    fs_1=1/T/1e12

    fff=peaks[0]*fs_1

    #if fff > 10:
    #    return np.nan,np.nan,np.nan

    results_half = peak_widths(x, [peaks[0]], rel_height=0.5)
    width=results_half[0]*fs_1  # widths

    #print(peaks*fs_1)
    #print(results_half,peaks[0])

    T=const.x_end/3e8
    fs_1=1/T/1e12

    def multi_fs(array):
        new_array=array*1
        for i in range(len(array)):
                #print(i)
            if i !=1:
                #print(results_half[i])
                new_array[i][0] = array[i][0] * fs_1
        return new_array

    a_h=multi_fs(results_half)

    #plt.plot(np.arange(Nx/2+1)*fs_1,x)
    #plt.plot(peaks*fs_1, x[peaks], "x")
    #plt.hlines(*a_h[1:], color="C2")
    #plt.xlim([0,40])

    #Ey=np.loadtxt('3500Ey_y0.txt')
    data=Ey
    dx=const.x_end/const.Nx
    #print(dx)
    T=dx/3e8
    #print(T)
    fs=1/(2*T)
    w1=a_h[2][0]*1e12
    w2=a_h[3][0]*1e12
    print('ahshape',np.array(a_h).shape)
    print('w1,w2'+w1*1+','+w2*1)
    print('ok')
    Ey_y0=Ey
    k_bz=np.fft.fft(Ey_y0)
    delta_k=3.14/const.delta_x/(const.Nx/2)
    k_bz2=k_bz*1
    k_n=[]
    for n in range(0,const.Nx):
        mi = 3e8/w1
        ma = 3e8/w2
        if 2 * 3.14 / ma  > n * delta_k and  n * delta_k > 2 * 3.14 / mi:
            k_n.append(n)
    k_bz2[0:k_n[0]]=0    #k_bz.argmin()
    k_bz2[k_n[-1]:-k_n[-1]]=0  #k_bz.argmin()
    k_bz2[-k_n[0]:]=0    #k_bz.argmin()
    bz_filter=np.fft.ifft(k_bz2)

    E0_w0=np.abs(bz_filter.real).max()
    #print('E0:'+str(E0_w0))
    c=3e8
    #w0=4e12
    me=9.10956e-31
    e=1.602176565e-19
    freqs=peaks*fs_1*1e12
    w0=freqs*2*3.1415926
    a0_w0=e*E0_w0/(me*c*w0)
    #return a0_w0
    '''
    #print(w1,w2)
    b, a = signal.butter(8,w2, 'lowpass')
    filtedData = signal.filtfilt(b, a, data)       #

    b, a = signal.butter(8,w1, 'highpass')
    filtedData2 = signal.filtfilt(b, a, filtedData)       #

    #print(np.abs(filtedData2).max())
    c=3e8
    #w0=4e12
    me=9.10956e-31
    e=1.602176565e-19
    freqs=peaks*fs_1*1e12
    E0_w0=np.abs(filtedData2).max()[0]
    w0=freqs*2*3.1415926
    a0_w0=e*E0_w0/(me*c*w0)
    #print(a0_w0)
    '''
    #plt.plot(filtedData2)
    #plt.show()
    #print('a,f',a0_w0,fff)
    #print(width)
    return [a0_w0[0],fff,width[0]]
#a,f=a0_x(1)
#a0=[]
#freqs=[]

def m_a0(i):
	#print(i)
	a,f,w=a0_x(i)
	#a0.append(a)
	#freqs.append(f)
	return [a,f,w]
#a0_x(1)
pool = multiprocessing.Pool(processes=96)
results = pool.map(m_a0,range(1,const.stop+1))
'''
a0=np.array(results[:][0])

max_a0=np.nanmax(a0)

i_a0=a0.index(max_a0)
width=results[:][2]
width_a0=width[i_a0]
'''

results=np.array(results)
print(results,results.shape)
pool.close()
pool.join()

a0=results[:,0]
freqs=results[:,1]
width=results[:,2]
#a0=np.array(a0)
#freqs=np.array(freqs)
np.savetxt(const.txtdir+'a0_fwhm.txt',a0)
np.savetxt(const.txtdir+'freqs_min.txt',freqs)

time = np.arange(int(1),int(const.stop+1))
locate = (time*const.dt_snapshot - const.window_start_time)*3e8*1e6

np.savetxt(const.txtdir + 'a0_distance.txt',locate)

plt.plot(locate,a0,label='a0')
plt.plot(locate,width,label='width')
plt.legend()
plt.savefig(const.figdir+'a0_width.jpg',dpi=160)
plt.close('all')

plt.plot(locate,freqs,label='freqs')
plt.plot(locate,width,label='width')
plt.plot(locate,a0,label='a0')
#plt.ylim([0,10])
plt.legend()
plt.savefig(const.figdir+'a0_freqs.jpg',dpi=160)

max_a0=np.nanmax(a0)

max_width=np.nanmax(width)

with open("txt/scan_new.txt","a") as f:
        f.write(const.case_name+":"+"\n"+'max_a0:'+str(max_a0)+" "+'min_freqs:'+ str(np.nanmin(freqs))+"\n"+"width:"+str(max_width)+"\n")#+"\n"+'const.dt_snapshot,const.window_start_time:'+"\n"+str(const.dt_snapshot)+','+str(const.window_start_time)+"\n")
#print(a0,freqs)
#print(np.nanmax(a0),np.nanmin(freqs))


#
# Tests for quintagroup.plonegooglesitemaps
#

from base import *
from cgi import FieldStorage
from tempfile import TemporaryFile, NamedTemporaryFile

from OFS.Image import cookId
from Products.CMFPlone.utils import _createObjectByType
from ZPublisher.HTTPRequest import FileUpload

class TestConfigletSettings(FunctionalTestCase):

    def afterSetUp(self):
        super(TestConfigletSettings, self).afterSetUp()
        self.settingsURL = '/'+self.portal.absolute_url(1) + '/prefs_gsm_settings'

    def submitForm(self, fdata, fextra={}):
        form = {'form.submitted': 1}
        form.update(fdata)
        return self.publish(self.settingsURL, request_method='POST',
                            stdin=StringIO(urlencode(form)),
                            basic=self.auth, extra=fextra)

    def testInitButtons(self):
        settings = self.publish(self.settingsURL, self.auth).getBody()
        self.assert_("Add Content Sitemap" in settings)
        self.assert_("Add News Sitemap" in settings)
        self.assert_("Add Mobile Sitemap" in settings)

    def testAddContentSitemap(self):
        resp = self.submitForm({'form.button.AddContent': "Add Content Sitemap"})
        self.assertEqual(resp.getStatus() / 100, 3)
        self.assertEqual(resp.getHeader("Location").endswith("sitemap.xml/edit"), True)
        # Add SM
        sm = self.portal["sitemap.xml"]
        #sm.setPortalTypes(("Documents",))
        newform = self.publish(self.settingsURL, basic=self.auth).getBody()
        self.assertEqual('href="http://nohost/plone/sitemap.xml/edit"' in newform, True)
        self.assertEqual("form.button.AddContent" in newform, False)

    def testAddNewsSitemap(self):
        resp = self.submitForm({'form.button.AddNews': "Add News Sitemap"})
        self.assertEqual(resp.getStatus() / 100, 3)
        self.assertEqual(resp.getHeader("Location").endswith("news-sitemap.xml/edit"), True)
        # Add SM
        sm = self.portal["news-sitemap.xml"]
        #sm.setPortalTypes(("News Item",))
        newform = self.publish(self.settingsURL, basic=self.auth).getBody()
        self.assertEqual('href="http://nohost/plone/news-sitemap.xml/edit"' in newform, True)
        self.assertEqual("form.button.AddNews" in newform, False)

    def testAddMobileSitemap(self):
        resp = self.submitForm({'form.button.AddMobile': "Add Mobile Sitemap"})
        self.assertEqual(resp.getStatus() / 100, 3)
        self.assertEqual(resp.getHeader("Location").endswith("mobile-sitemap.xml/edit"), True)
        # Add SM
        sm = self.portal["mobile-sitemap.xml"]
        #sm.setPortalTypes(("Documents",))
        newform = self.publish(self.settingsURL, basic=self.auth).getBody()
        self.assertEqual('href="http://nohost/plone/mobile-sitemap.xml/edit"' in newform, True)
        self.assertEqual("form.button.AddMobile" in newform, False)

class TestConfigletOverview(FunctionalTestCase):

    def afterSetUp(self):
        super(TestConfigletOverview, self).afterSetUp()
        self.overviewURL = '/'+self.portal.absolute_url(1) + '/prefs_gsm_overview'
        self.smURL = "%s/sitemap.xml" % self.portal.absolute_url()

    def testInitial(self):
        overview = self.publish(self.overviewURL, self.auth).getBody()
        self.assert_(not self.smURL in overview)

    def testPresentedSM(self):
        _createObjectByType("Sitemap", self.portal, id="sitemap.xml",
                            sitemapType="content")
        overview = self.publish(self.overviewURL, self.auth).getBody()
        self.assert_(self.smURL in overview)

def test_suite():
    from unittest import TestSuite, makeSuite
    suite = TestSuite()
    suite.addTest(makeSuite(TestConfigletSettings))
    suite.addTest(makeSuite(TestConfigletOverview))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='test_suite')
#    framework()


#!/usr/bin/env python3
#programed by Jason Renna
from MoveWithPercision2 import *
var = ""
while var != "exit":
   var = input("Please enter something: ")
   if var == "forward":
       #moveStraightWithPercision()
       move_foward()
       print("forward")
   elif var == "left":
       turnLeftWithPercision()
       print("left")
   elif var == "right":
       turnRightWithPercision()
       print("right")
   elif var == "exit":
       print("closing program")
   else:
       print("invalid input")


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='HotWordCount',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('hot_word', models.CharField(max_length=50)),
                ('counter', models.IntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='SearchHistory',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('user_id', models.IntegerField()),
                ('key_word', models.CharField(max_length=50)),
                ('created_at', models.DateTimeField(default=datetime.datetime(2016, 7, 22, 17, 21, 3, 335076))),
            ],
        ),
    ]


#!/usr/bin/python3
# implement TF model which will be used to classify MNIST digits using keras.
#
# Name: R. Melton
# email: rnm@pobox.com
# date: 1/3/2021
# based on: https://www.youtube.com/watch?v=bee0GrKBCrE
# you will need sudo apt install nvidia-cuda-toolkit

import tensorflow as tf
from tensorflow import keras
from matplotlib import pyplot as plt
import numpy as np
import time,sys,os,platform,distro,vers
from tensorflow.python.client import device_lib

#try to install TF 2 if it will run on this HW
# try:
#   tensorflow_version   #<< this function only exists in google colab VM
#   print('installed TF 2.x')
# except Exception:
#   print('could not install TF 2')
#   pass

if __name__ == '__main__':
  vers.show_versions_info()

#see if GPU is available
physical_devices = tf.config.experimental.list_physical_devices('GPU')
print('num GPUs ',len(physical_devices))
# if len(physical_devices) > 0:
#   tf.config.experimental.set_memory_growth(physical_devices[0],True)

objects = tf.keras.datasets.mnist    # many images of digits 0-9
(training_images, training_labels),(test_images,test_labels) = objects.load_data()

device_lib.list_local_devices()

#print some of the digit images
for i in range(9):
  plt.subplot(330+1+i)
  plt.imshow(training_images[i])

# print dimensions for training data
print(training_images.shape)

#print 1st training image of one digit
print(training_images[0])

#now normalize all training and test input values to 0 - 1
training_images = training_images / 255.0
test_images = test_images / 255.0

m = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),
  tf.keras.layers.Dense(128,activation='relu'),
  tf.keras.layers.Dense(10,activation=tf.nn.softmax)])

m.summary() #show summary

m.compile(optimizer = tf.keras.optimizers.Adam(),
  loss = 'sparse_categorical_crossentropy',
  metrics=['accuracy'])

#train the model
t = time.time()
m.fit(training_images,training_labels,epochs=5,shuffle=True) #5 itterations over all data

print(f'training duration: {time.time() - t}s')
start_test_time = time.time()
m.evaluate(test_images,test_labels)
print(f'test duration: {time.time() - start_test_time}s')
# write out one hot data values so we know what they are.
# test_images.class_indices

#show first image from test data
plt.imshow(test_images[0])
prediction=m.predict(test_images)  # do all test images
print('predicted number0: ',np.argmax(prediction[0]))
print(': ',prediction[0])
print('predicted number1: ',np.argmax(prediction[1]))
print(': ',prediction[1])
print('predicted number2: ',np.argmax(prediction[2]))
print(': ',prediction[2])
print('predicted number3: ',np.argmax(prediction[3]))
print(': ',prediction[3])
print('predicted number4: ',np.argmax(prediction[4]))
print(': ',prediction[4])


import numpy as np
import healpy as hp
from astropy import units as u
from astropy import constants as c

# Longest baseline
b_max = 1000*u.m
# Highest frequency
nu_max = 200.*u.MHz
# Lowest frequency
nu_min = 100.*u.MHz
# Highest resolution
res_max = np.degrees(1./(b_max * nu_max/c.c).to(u.dimensionless_unscaled).value)*60.
# Oversampling of synthesizbeam
pixel_oversamp = 2.

# Calculate FoV
FoV = np.degrees(((c.c/nu_min)/(14.*u.m)).to(u.dimensionless_unscaled).value)
FoV_oversamp = 2.

# Calculate number of healpix pixels
nside = 1024
npix_hp = hp.nside2npix(nside)
res = hp.nside2resol(nside,arcmin=True)

area_arcmin2 = np.power(res_max/pixel_oversamp,2)

# Calculate number of pixels in 12 hour equatorial map
sq_arcmin_eq = (FoV*60.*FoV_oversamp) * (180.*60.)
npix_eq = sq_arcmin_eq/area_arcmin2

# Calcualte number of pixels in 1 hour snapshot
sq_arcmin_snap = np.power(FoV*60.*FoV_oversamp,2)
npix_snap = sq_arcmin_snap/area_arcmin2

# Number of channels
nchan = 200.

# Conversion to size
bytes_per_float = 8
mb_per_vox = bytes_per_float / 1e6

size_eq = npix_eq * nchan * mb_per_vox
size_snap = npix_snap * nchan * mb_per_vox


# -*- coding: utf-8 -*-

from mongo_cache import MongoCache
from mongo_queue import MongoPackage
from pypi_parser import PackageParser
from downloader import Downloader
import threading
import multiprocessing
from urllib import parse
from os import path
import time
SEED_URL = 'https://pypi.python.org'
SLEEP_TIME = 1

def threaded_crawler(seed_url, delay = 5, cache = None, scrape_callback = None, user_agent = 'wswp', proxies = None, num_retries = 1, max_threads = 10, timeout = 60):
    '''
    Crawl using multiple threads
    '''
    package_queue = MongoPackage()
    #crawl_queue.clear()
    #crawl_queue.push(seed_url)
    D = Downloader(delay, user_agent, proxies, num_retries, timeout, cache = cache)

    def process_queue():
        while True:
            try:
                url = package_queue.pop()
                #url is like '/pypi/xxx/'
                full_url = parse.urljoin(seed_url, url + 'json')
                print(full_url)
            except KeyError:
                break
            else:
                html = D(full_url)
                '''
                Here handle the html
                '''
                with open(path.join('../results/pypi_packinfo', url.split('/')[-2] + '.json'), 'wb') as f:
                    f.write(html)
                package_queue.complete(url)
    threads = []
    while threads or package_queue:
        # the crawl is still active
        for th in threads:
            if not th.is_alive():
                # remove the stopped threads
                threads.remove(th)
        while len(threads) < max_threads and package_queue.peek():
            # can start some more threads
            th = threading.Thread(target = process_queue, daemon = True)
            th.start()
            threads.append(th)
        # sleep temporarily so CPU can focus execution on other threads
        time.sleep(SLEEP_TIME)

def process_crawler(args, **kwargs):
    num_cpus = multiprocessing.cpu_count()
    print('Starting %s processes' % num_cpus)
    processes = []
    for i in range(num_cpus):
        p = multiprocessing.Process(target = threaded_crawler, args=(args,), kwargs = kwargs)
        p.start()
        processes.append(p)
    for p in processes:
        p.join()

def normalize(seed_url, link):
    '''
    Normalize this URL by removing hash and adding domain
    seed_url: the domain
    link: the relative path
    '''
    link, _ = parse.urldefrag(link)
    return parse.urljoin(seed_url, link)

def generate_packinfo():
    cache = MongoCache()
    cache.clear()
    process_crawler(SEED_URL, cache = cache)

if __name__ == '__main__':
    generate_packinfo()


from lxml import etree

NS = {"w": "http://www.mediawiki.org/xml/export-0.5/"}
PAGE_TAG = "{%s}page" % NS["w"]

def extract_pages(f):
    """Extract pages from Wikimedia database dump.

    Returns
    -------
    pages : iterable over (int, str, str)
        Generates (page_id, title, content) triples.
    """
    for event, elem in etree.iterparse(f, events=["end"]):
        if elem.tag == PAGE_TAG:
            text = elem.xpath("./w:revision/w:text", namespaces=NS)[0].text \
                    or ""   # may be None
            yield (int(elem.xpath("./w:id", namespaces=NS)[0].text),
                   elem.xpath("./w:title", namespaces=NS)[0].text,
                   text)

            # http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
            # We do this only for <page>s, since we need to inspect the
            # ./revision/text element. That shouldn't matter since the pages
            # comprise the bulk of the file.
            elem.clear()
            while elem.getprevious() is not None:
                del elem.getparent()[0]

if __name__ == "__main__":
    import sys

    for pageid, title, text in extract_pages(sys.stdin):
        print("%d '%s' (%s)" % (pageid, title, text[:40].replace("\n", "_")))


__author__ = 'haibane'
import pymongo
import sys
conn = pymongo.MongoClient(host=["mongodb://192.168.1.42:27001",
                                 "mongodb://192.168.1.42:27002",
                                 "mongodb://192.168.1.42:27003"], replicaSet="abc", w=1, j=True)
db = conn.m101
people = db.people
try:
    print("inserting")
    people.insert({"name": "andrew", "favority_color": "blue"})
except:
    print("Unexcepted error:", sys.exc_info()[0])
print("completed inserting")


import unittest

TEST_FOLDER_NAME = "Tests"

###############
#Run unit tests
###############
suite = unittest.TestLoader().discover(start_dir = TEST_FOLDER_NAME, pattern="*_tests.py")
test_runner = unittest.TextTestRunner(verbosity = 2, failfast = True)
test_result = test_runner.run(suite)
assert test_result.wasSuccessful(), "At least one test failed."


import argparse

from . import encode

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("N",
                        help="Display the namehash for the given number",
                        type=int)
    args = parser.parse_args()
    print(encode(args.N))

if __name__ == '__main__':
    main()


# coding:utf-8

import datetime
import reportlab.rl_config

reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen.canvas import Canvas
import calendar
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib import fonts, colors
from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, Image, PageTemplate, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus.doctemplate import *
import copy

##注册中文字体
pdfmetrics.registerFont(TTFont('song', "C:\\Windows\\Fonts\\simsun.ttc"))  # 路径
pdfmetrics.registerFont(TTFont('hei', 'C:\\Windows\\Fonts\\simhei.ttf'))  # 粗体
fonts.addMapping('song', 0, 0, 'song')
fonts.addMapping('song', 0, 1, 'song')
fonts.addMapping('song', 1, 0, 'hei')
fonts.addMapping('song', 1, 1, 'hei')

class MyPDFdoc:
    class MyPageTemp(PageTemplate):
        '''
        定义一个页面模板
        '''

        def __init__(self):
            F6 = Frame(x1=0.5 * inch, y1=0.5 * inch, width=7.5 * inch, height=2.0 * inch, showBoundary=0)
            F5 = Frame(x1=0.5 * inch, y1=2.5 * inch, width=7.5 * inch, height=2.0 * inch, showBoundary=0)
            F4 = Frame(x1=0.5 * inch, y1=4.5 * inch, width=7.5 * inch, height=2.0 * inch, showBoundary=0)
            F3 = Frame(x1=0.5 * inch, y1=6.5 * inch, width=7.5 * inch, height=2.0 * inch, showBoundary=0)
            F2 = Frame(x1=0.5 * inch, y1=8.5 * inch, width=7.5 * inch, height=2.0 * inch, showBoundary=0)
            F1 = Frame(x1=0.5 * inch, y1=10.5 * inch, width=7.5 * inch, height=0.5 * inch, showBoundary=0)
            PageTemplate.__init__(self, "MyTemplate", [F1, F2, F3, F4, F5, F6])

        def beforeDrawPage(self, canvas, doc):  # 在页面生成之前做什么画logo
            pass

    def __init__(self, filename):
        self.filename = filename
        self.objects = []  ##story
        self.doc = BaseDocTemplate(self.filename)
        self.doc.addPageTemplates(self.MyPageTemp())
        self.Style = getSampleStyleSheet()
        # 设置中文,设置四种格式
        # self.nor=self.Style['Normal']
        self.cn = self.Style['Normal']
        self.cn.fontName = 'song'
        self.cn.fontSize = 9
        self.t = self.Style['Title']
        self.t.fontName = 'song'
        self.t.fontSize = 15
        self.h = self.Style['Heading1']
        self.h.fontName = 'song'
        self.h.fontSize = 10
        self.end = copy.deepcopy(self.t)
        self.end.fontSize = 7

    def _str3tocoma(self, num):  # 每三个数字加一个逗号
        e = list(str(num).split(".")[0])
        for i in range(len(e))[::-3][1:]:
            e.insert(i + 1, ",")
        return "".join(e) + "." + str(num).split(".")[1]

    def _CreatePDF(self, path=''):  #
        data_1 = []
        tmp_arr = []
        col = [u'测试信息', u'']

        # 生成对应关系

        # 生成table Style
        S1 = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]
        # 添加标题
        self.objects.append(Paragraph('''NF-Chain测试报告''', self.t))
        self.objects.append(FrameBreak())  # 切换到第二个FORM
        self.objects.append(Paragraph('''基本信息''', self.h))
        for y in col:
            tmp_arr.append(Paragraph('''%s''' % y, self.cn))
        t = Paragraph('''测试时间''', self.cn)
        data_1.append([t, '2017.5.14'])
        t = Paragraph('''NF-Chain''', self.cn)
        data_1.append([t, 'TCPReplay -> Snort -> Tcpdump'])
        t = Paragraph('''XXXXXX''', self.cn)
        data_1.append([t, 'OOOOOOO'])
        data_1.insert(0, tmp_arr)
        t = Table(data_1, style=S1, colWidths=3 * inch, rowHeights=0.2 * inch)
        self.objects.append(t)

        self.objects.append(FrameBreak())
        self.objects.append(Paragraph('''CDF''', self.h))
        self.objects.append(Spacer(0, 0))
        self.objects.append(Image('%s\\%s' % (path, 'Figure_1.png'), 500, 102))

        # self.objects.append(FrameBreak())
        # self.objects.append(Paragraph('''IDC流量趋势''',self.h))
        # if d.has_key('idc'):
        #    self.objects.append(Image('%s/%s' % (path,d['idc'] ),500,102))
        # else:
        #    self.objects.append(Paragraph('本图缺失',self.end))

        self.doc.build(self.objects)

if __name__ == "__main__":
    # 生成PDF对象
    # 取当月的第一天
    filename = '1' + '.pdf'
    pdf = MyPDFdoc(filename)
    pdf._CreatePDF(path='C:\\Users\\Shinelon\\Desktop')


#!/usr/bin/env python

from os import getenv
import paho.mqtt.client as mqtt
import json
import bot

TALK_TO_BOT = 'uldis:talk_to_bot'
INTERRUPT = 'uldis:interrupt'

INTENT = TALK_TO_BOT

def on_connect(mqtt_client, userdata, flags, rc):
    print('[snips] connected')
    mqtt_client.subscribe('hermes/intent/#')

slot_name_is = lambda x: lambda s: s['slotName'] == x
first_slot_value = lambda s: s['value']['value']

CONTINUE_SESSION = 'hermes/dialogueManager/continueSession'

def continue_session(id, text, bot_name):
    return json.dumps({
        'sessionId': id,
        'text': text,
        'intentFilter': [INTERRUPT],
        'customData': bot_name,
        'sendIntentNotRecognized': False
    })

def on_message(client, _, msg):
    data = json.loads(msg.payload)
    intent_name = data['intent']['intentName']
    sessionId = data['sessionId']

    if (intent_name == TALK_TO_BOT):
        slot = filter(
            slot_name_is('bot'),
            data['slots']
        )[0]
        bot_name = first_slot_value(slot)

        print('[snips] user wants to talk to {}'.format(bot_name))
        on_continue = lambda response: snips_client.publish(
            CONTINUE_SESSION,
            continue_session(
                sessionId,
                response,
                bot_name
            )
        )
        bot.start(bot_name, on_continue)
    else:
        debug(data)

def on_log(client, userdata, level, buf):
    print('[snips] {}'.format([client, userdata, level, buf]))

def debug(data):
    slots = data['slots']
    intent_name = data['intent']['intentName']
    print('[snips] Intent {}'.format(intent_name))
    for slot in slots:
        slot_name = slot['slotName']
        raw_value = slot['rawValue']
        value = slot['value']['value']
        print('[snips] Slot {} -> \n\tRaw: {} \tValue: {}'.format(slot_name, raw_value, value))

def start():
    MQTT_HOST = getenv('MQTT_HOST', 'pi')
    MQTT_PORT = getenv('MQTT_PORT', 1883)
    mqtt_client = mqtt.Client()
    if getenv('DEBUG'):
        mqtt_client.on_log = on_log
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.connect(MQTT_HOST, MQTT_PORT)
    mqtt_client.loop_forever()

if __name__ == '__main__':
    print('[snips] starting...')
    start()


#
# Problem: Write a function to find the rectangular intersection of two given rectangles.
#

# Rectangles are dicts with the following props:
#
# my_rectangle = {
# 	# Coordinates of bottom-left corner
# 	'left_x': 1,
# 	'bottom_y': 1,
#
# 	# Width and height
# 	'width': 6,
# 	'height': 3,
# }

def find_x_overlap(rect1, rect2):
	"""
	Return left_x and width of overlapping x of two rects
	"""
	r1left = rect1['left_x']
	r1right = r1left + rect1['width']
	r2left = rect2['left_x']
	r2right = r2left + rect2['width']

	highest_start_point = r1left if r1left >= r2left else r2left
	lowest_end_point = r1right if r1right <= r2right else r2right

	if highest_start_point < lowest_end_point:
		return highest_start_point, lowest_end_point - highest_start_point
	else:
		return None

def find_y_overlap(rect1, rect2):
	"""
	Return bottom_y and height of overlapping y of two rects
	"""
	r1bottom = rect1['bottom_y']
	r1top = r1bottom + rect1['height']
	r2bottom = rect2['bottom_y']
	r2top = r2bottom + rect2['height']

	highest_start_point = r1bottom if r1bottom >= r2bottom else r2bottom
	lowest_end_point = r1top if r1top <= r2top else r2top

	if highest_start_point < lowest_end_point:
		return highest_start_point, lowest_end_point - highest_start_point
	else:
		return None

def solution(rect1, rect2):
	result = {
		'left_x': 0,
		'bottom_y': 0,
		'width': 0,
		'height': 0,
	}

	x_overlap = find_x_overlap(rect1, rect2)
	if x_overlap:
		result['left_x'] = x_overlap[0]
		result['width'] = x_overlap[1]
		y_overlap = find_y_overlap(rect1, rect2)
		if y_overlap:
			result['bottom_y'] = y_overlap[0]
			result['height'] = y_overlap[1]
			return result

	return None


# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.

celery 任务示例

本地启动celery命令: python  manage.py  celery  worker  --settings=settings
周期性任务还需要启动celery调度命令：python  manage.py  celerybeat --settings=settings
"""
import datetime
import json

from celery import task
from celery.schedules import crontab
from celery.task import periodic_task

from blueking.component.shortcuts import get_client_by_user, logger
from home_application.models import *
from home_application.utils import *

#
# @periodic_task(run_every=crontab(minute='*', hour='*', day_of_week="*"))
# def run_task():
#     try:
#         pass
#     except Exception as e:
#         logger.exception("get_servers_perform error: %s" % e.message)

@periodic_task(run_every=crontab(minute='*/1', hour='*', day_of_week="*"))
def get_data():
    hosts = HostInfo.objects.all()
    if not hosts:
        return
    username = hosts[0].created_by
    client = get_client_by_user(username)
    biz_ids = list(set([i.bk_biz_id for i in hosts]))
    script_content = """
# !/bin/bash
cat /proc/loadavg
free -m
df -h
    """
    for bk_biz_id in biz_ids:
        biz_hosts = HostInfo.objects.filter(bk_biz_id=bk_biz_id)
        ip_list = [{'ip':j.ip,'bk_cloud_id':j.bk_cloud_id} for j in biz_hosts]
        data_mes = fast_execute_script(client, bk_biz_id, username, ip_list, script_content)
        log_data = data_mes['data']
        for i in log_data:
            ip = i['ip']
            host_obj = HostInfo.objects.get(ip=ip)
            log_content = i['log_content']
            cpu_mes = log_content.split('\n')[0]
            real_cpu_load = [float(cpu_mes.split(" ")[z]) for z in xrange(3)]
            cpu_use = (real_cpu_load[0] + real_cpu_load[1] + real_cpu_load[2])/3
            mem_mes = log_content.split('\n')[2]
            mem_list = [zx for zx in mem_mes.split(" ") if zx]
            mem_use = float(mem_list[2])
            mem_free = float(mem_list[3])
            disk_mes = log_content.split('\n')[4:]
            real_disk_mes = []
            for disk in disk_mes[1:-1]:
                disk_list = [k for k in disk.split(" ") if k]
                real_disk_mes.append({'Filesystem': disk_list[0],
                                      'Size': disk_list[1],
                                      'Used': disk_list[2],
                                      'Avail': disk_list[3],
                                      'Useage': disk_list[4],
                                      'Mounted': disk_list[5],})
            HostData.objects.create(host=host_obj,cpu_use=cpu_use,mem_use=mem_use,mem_free=mem_free,disk_mes=json.dumps(real_disk_mes),when_created=timezone.now())


'''
Created on 21.07.2017

@author: Jascha Riedel
'''

import numpy as np

def findRp(data, indexRange = 10):
    '''
    Calculates Rp by fitting (+- indexRange) around I = 0 and
    taking the inverse of the slope.
    Parameters:
        data:        2-D Array with U-I datapoints
        indexRange:  Range around I = 0 of datapoints that will be used for fitting
    '''
    data = data[data[:,0].argsort()]

    firstPositiveCurrent = np.where((data[:, 1] > 0) == True)[0][0]
    fitRange = range(firstPositiveCurrent-indexRange, firstPositiveCurrent+indexRange)
    return 1/np.polyfit(data[fitRange, 0], data[fitRange, 1], 1)[0] * -1


"""Admin for news-related models."""

import wtforms

from pygotham.admin.utils import model_view
from pygotham.news import models

__all__ = ('AnnouncementModelView',)

AnnouncementModelView = model_view(
    models.Announcement,
    'Announcements',
    'News',
    column_default_sort='published',
    column_list=('title', 'published', 'active'),
    form_columns=('title', 'content', 'active', 'published'),
    form_overrides={
        'published': wtforms.DateTimeField,
    },
)


import os
import csv
import requests
from bs4 import BeautifulSoup

csv_header = [['NAME', 'TITLE', 'Phone', 'Email', 'IMAGE']]

def write_direct_csv(lines, filename):
    with open('output/%s' % filename, 'a', encoding="utf-8", newline='') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        writer.writerows(lines)
    csv_file.close()

def write_csv(lines, filename):
    if not os.path.isdir('output'):
        os.mkdir('output')
    if not os.path.isfile('output/%s' % filename):
        write_direct_csv(lines=csv_header, filename=filename)
    write_direct_csv(lines=lines, filename=filename)

initial_url = 'https://www.bobeuckmanford.com/dealership/staff.htm'
header = {
    'user-agent': "mozila/5.0"
}
res = requests.request(method='GET', url=initial_url, headers=header)
soup = BeautifulSoup(res.text, 'html5lib')
cards = soup.find_all('li', {'class': "staff"})
for card in cards:
    name = card.find('dt', {'class': 'fn'}).text.strip()
    title = card.find('dd', {'class': 'title'}).text.strip()
    phone = card.find('dd', {'class': 'phone'}).text.strip()
    email = card.find('dd', {'class': 'email'}).text.strip()
    image = card.find('dd', {'class': 'photo'}).img['data-src'].split('?')[0]
    line = [name, title, phone, email, image]
    write_csv(lines=[line], filename='Ford_Dealer.csv')


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

#
#  Copyright 2019 The FATE Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import copy

from federatedml.param.glm_param import LinearModelParam
from federatedml.param.callback_param import CallbackParam
from federatedml.param.encrypt_param import EncryptParam
from federatedml.param.encrypted_mode_calculation_param import EncryptedModeCalculatorParam
from federatedml.param.cross_validation_param import CrossValidationParam
from federatedml.param.init_model_param import InitParam
from federatedml.param.stepwise_param import StepwiseParam
from federatedml.util import consts

class PoissonParam(LinearModelParam):
    """
    Parameters used for Poisson Regression.

    Parameters
    ----------
    penalty : {'L2', 'L1'}, default: 'L2'
        Penalty method used in Poisson. Please note that, when using encrypted version in HeteroPoisson,
        'L1' is not supported.
    tol : float, default: 1e-4
        The tolerance of convergence
    alpha : float, default: 1.0
        Regularization strength coefficient.
    optimizer : {'rmsprop', 'sgd', 'adam', 'adagrad'}, default: 'rmsprop'
        Optimize method
    batch_size : int, default: -1
        Batch size when updating model. -1 means use all data in a batch. i.e. Not to use mini-batch strategy.
    learning_rate : float, default: 0.01
        Learning rate
    max_iter : int, default: 20
        The maximum iteration for training.
    init_param: InitParam object, default: default InitParam object
        Init param method object.
    early_stop : str, 'weight_diff', 'diff' or 'abs', default: 'diff'
        Method used to judge convergence.
            a)	diff： Use difference of loss between two iterations to judge whether converge.
            b)  weight_diff: Use difference between weights of two consecutive iterations
            c)	abs: Use the absolute value of loss to judge whether converge. i.e. if loss < eps, it is converged.
    exposure_colname: str or None, default: None
        Name of optional exposure variable in dTable.
    encrypt_param: EncryptParam object, default: default EncryptParam object
        encrypt param
    encrypted_mode_calculator_param: EncryptedModeCalculatorParam object, default: default EncryptedModeCalculatorParam object
        encrypted mode calculator param
    cv_param: CrossValidationParam object, default: default CrossValidationParam object
        cv param
    stepwise_param: StepwiseParam object, default: default StepwiseParam object
        stepwise param
    decay: int or float, default: 1
        Decay rate for learning rate. learning rate will follow the following decay schedule.
        lr = lr0/(1+decay*t) if decay_sqrt is False. If decay_sqrt is True, lr = lr0 / sqrt(1+decay*t)
        where t is the iter number.
    decay_sqrt: bool, default: True
        lr = lr0/(1+decay*t) if decay_sqrt is False, otherwise, lr = lr0 / sqrt(1+decay*t)
    validation_freqs: int, list, tuple, set, or None
        validation frequency during training, required when using early stopping.
        The default value is None, 1 is suggested. You can set it to a number larger than 1 in order to speed up training by skipping validation rounds.
        When it is larger than 1, a number which is divisible by "max_iter" is recommended, otherwise, you will miss the validation scores of the last training iteration.
    early_stopping_rounds: int, default: None
        If positive number specified, at every specified training rounds, program checks for early stopping criteria.
        Validation_freqs must also be set when using early stopping.
    metrics: list or None, default: None
        Specify which metrics to be used when performing evaluation during training process. If metrics have not improved at early_stopping rounds, trianing stops before convergence.
        If set as empty, default metrics will be used. For regression tasks, default metrics are ['root_mean_squared_error', 'mean_absolute_error']
    use_first_metric_only: bool, default: False
        Indicate whether to use the first metric in `metrics` as the only criterion for early stopping judgement.
    floating_point_precision: None or integer
        if not None, use floating_point_precision-bit to speed up calculation,
        e.g.: convert an x to round(x * 2**floating_point_precision) during Paillier operation, divide
                the result by 2**floating_point_precision in the end.
    callback_param: CallbackParam object
        callback param

    """

    def __init__(self, penalty='L2',
                 tol=1e-4, alpha=1.0, optimizer='rmsprop',
                 batch_size=-1, learning_rate=0.01, init_param=InitParam(),
                 max_iter=20, early_stop='diff',
                 exposure_colname=None,
                 encrypt_param=EncryptParam(),
                 encrypted_mode_calculator_param=EncryptedModeCalculatorParam(),
                 cv_param=CrossValidationParam(), stepwise_param=StepwiseParam(),
                 decay=1, decay_sqrt=True,
                 validation_freqs=None, early_stopping_rounds=None, metrics=None, use_first_metric_only=False,
                 floating_point_precision=23, callback_param=CallbackParam()):
        super(PoissonParam, self).__init__(penalty=penalty, tol=tol, alpha=alpha, optimizer=optimizer,
                                           batch_size=batch_size, learning_rate=learning_rate,
                                           init_param=init_param, max_iter=max_iter,
                                           early_stop=early_stop, cv_param=cv_param, decay=decay,
                                           decay_sqrt=decay_sqrt, validation_freqs=validation_freqs,
                                           early_stopping_rounds=early_stopping_rounds, metrics=metrics,
                                           floating_point_precision=floating_point_precision,
                                           encrypt_param=encrypt_param,
                                           use_first_metric_only=use_first_metric_only,
                                           stepwise_param=stepwise_param,
                                           callback_param=callback_param)
        self.encrypted_mode_calculator_param = copy.deepcopy(encrypted_mode_calculator_param)
        self.exposure_colname = exposure_colname

    def check(self):
        descr = "poisson_regression_param's "
        super(PoissonParam, self).check()
        if self.encrypt_param.method != consts.PAILLIER:
            raise ValueError(
                descr + "encrypt method supports 'Paillier' only")
        if self.optimizer not in ['sgd', 'rmsprop', 'adam', 'adagrad']:
            raise ValueError(
                descr + "optimizer not supported, optimizer should be"
                        " 'sgd', 'rmsprop', 'adam', or 'adagrad'")
        if self.exposure_colname is not None:
            if type(self.exposure_colname).__name__ != "str":
                raise ValueError(
                    descr + "exposure_colname {} not supported, should be string type".format(self.exposure_colname))
        self.encrypted_mode_calculator_param.check()
        return True


#!/usr/bin/env python

from csv import reader
from datetime import datetime, timedelta

from core import AbstractScan, AbstractList

__all__ = [
    'AScan',
    'AList',
    'parse_alist',
    ]

# Taken from Haystack's aformat.doc
#       = ( (FIELD_NAME, TYPE_FUNC),
#           ...
#           )
AFIELDS = (
    ('format', int),  # >=5 implies Mk4
    ('root', str),  # 6-char lower case
    ('type', int),  # General format for fringe data
    ('fileset', int),  # Part of filename
    ('duration', int),  # Nominal duration (sec)
    ('length', int),  # Seconds of data represented.
    ('offset', int),  # Offset (sec) of mean time of data
    ('experiment', int),  # Part of filename
    ('scan', str),  # From obsvex, blanks trimmed
    ('procdate', str),  # FRNGE/fourfit processing time
    ('year', int),  # Four-digit year.
    ('timetag', str),  # Nominal start time of data record
    ('scan_offset', int),  # Scan time to time tag (sec)
    ('source', str),  # Blank-padded ascii string
    ('baseline', str),  # 2-char baseline id
    ('errcode', str),  # 2-char qcode and errcode
    ('band', str),  # e.g. X08 for X-band 8 freqs
    ('pol', str),  # RR, LL, RL, LR
    ('lags', int),  # Number of lags in correlation
    ('amp', float),  # In units of 1/10000
    ('snr', float),  # 4 significant digits
    ('phase_deg', float),  # Can be of various type
    ('phase_snr', float),  # 4 significant digits
    ('data_type', str  ),  # First char is data origin
    ('sbd', float),  # Microseconds
    ('mbd', float),  # Microseconds
    ('mbd_amb', float),  # Microseconds
    ('rate', float),  # Picoseconds/second
    ('ref_el', float),  # At reference epoch, degrees
    ('rem_el', float),  # At reference epoch, degrees
    ('ref_az', float),  # At reference epoch, degrees
    ('rem_az', float),  # At reference epoch, degrees
    ('u', float),  # precision 4 sig. digits
    ('v', float),  # precision 4 sig. digits
    ('ESDESP', str),  # E=ref.tape error rate exponent:
    ('epoch', str),  # mmss
    ('freq', float),  # Precision 10 KHz
    ('ecphase', float),  # Regardless of field 21
    ('drate', float),  # At ref epoch, microsec/sec
    ('total_mbd', float),  # At ref epoch, microsec
    ('total_sbdmbd', float),  # At ref epoch, microsec
    ('scotime', int),  # Seconds
    ('ncotime', int),  # Seconds
    )

# A list of fields to add on to the standard ones that are dependent
# on other fields, i.e. their callback functions require some previous
# field
#          = ( (SHORT_NAME, CALLBACK),
#              ...
#              )
DEP_AFIELDS = (
    ('datetime', lambda F: datetime.strptime(str(F['year'])+F['timetag'], "%y%j-%H%M%S")),
    ('duration', lambda F: timedelta(seconds=F['duration'])),
    )

class AScan(AbstractScan):

    def __init__(self, dict_):
        self.repr_format = "< {source}/{baseline} @ {datetime} >"
        AbstractScan.__init__(self, dict_, pivot='datetime', repr_format=self.repr_format)

    def _merge_scans(self, other):
        return AScan(dict(self, **other))

class AList(AbstractList):

    def __init__(self, iter_, baseline):
        self.baseline = baseline
        self.repr_format = "** {name}: {0.length} scans, {baseline}, {0.source_sj} **"
        AbstractList.__init__(self, iter_, merge=False, repr_format=self.repr_format)

    def _list_from_scans(self, iter_):
        return AList(iter_, baseline=self.baseline)

def parse_baseline(filename, baseline, comment):
    for row in reader(open(filename, 'r'), delimiter=' ', skipinitialspace=True):
        if not row[0]==comment:
            assert len(row)==len(AFIELDS)
            scan = AScan((field, func(row.pop(0))) for field, func in AFIELDS)
            scan.update((field, func(scan)) for field, func in DEP_AFIELDS)
            if scan.baseline==baseline:
                yield scan

def parse_alist(filename, baseline, comment='*'):
    return AList(parse_baseline(filename, baseline, comment), baseline=baseline)


import os
from art import logo

bids={}
bidding_finished=False

def find_highest_bidder(bidding_record):
  highest_bid=0
  winner=''
  for bidder in bidding_record:
    bid_amount= bidding_record[bidder]
    if bid_amount> highest_bid:
      highest_bid=bid_amount
      winner=bidder
  print(f"The highest bidder is {winner} with a bid amount of ${bid_amount}")

while not bidding_finished:

  name=input("What is your name?:")
  price=int(input("What\'s your bid?: $"))
  bids[name]=price
  should_continue=input("Are there any other bidders? Type 'yes' or 'no'.")
  if should_continue == 'no':
    bidding_finished=True
    find_highest_bidder(bids)
  elif should_continue == 'yes':
    os.system('cls')


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = 'Inpool'
SITENAME = "英银坡'S BLOG"
SITEURL = ''

PATH = 'content'

TIMEZONE = 'Asia/Shanghai'

DEFAULT_LANG = 'zh'

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

DATE_FORMATS = {
    'zh': '%Y-%m-%d %H:%M'
}

# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),)

# Social widget
SOCIAL = (('微博', 'http://weibo.com/inpool'),
          ('电子邮件', 'mailto:%69%6e%70%6f%6f%6c%40%31%32%36%2e%63%6f%6d'),)

DEFAULT_PAGINATION = 10
RELATIVE_URLS = True
ARTICLE_URL = '{category}/{slug}.html'
ARTICLE_SAVE_AS = '{category}/{slug}.html'
THEME = 'Architect'
SLUG_SUBSTITUTIONS = (
    ('gong ju', 'tools'),
)


# Name: Siddique Neha
# Roll no : 14co09
# Batch : 3
# Aim : To Implement Product Cipher.

message=input("Enter the Message:")
message=list(message.upper().replace(' ', ''))

keyword=input("Enter the Keyword:")
keyword=list(keyword.upper().replace(' ', ''))

alphabet=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

keylen=len(keyword)
vegenere=[]

for e in range(len(message)):
	key=e%keylen
	vegenere.append(alphabet[(alphabet.index(message[e])+alphabet.index(keyword[key]))%26])

product_cipher=""
odd=""

for i,val in enumerate(vegenere):
	if i & 1:
		odd+=val
	else:
		product_cipher+=val

product_cipher+=odd

print(product_cipher)

#
#Output:
#Enter the Message:"Neha"
#Enter the Keyword:"beco"
#OJIO

#


# Author: Lucas Galleguillos
# Description: Calculates the magnitude of electric force between two
#              electric charges using Coulomb's law.
# Filename: coulomb.py

print('Enter charges in Coulombs and radius in meters')

from math import pi, pow

q1 = float(input('q' + u'\u2081' + ' = '))

q2 = float(input('q' + u'\u2082' + ' = '))

r  = float(input('r  = '))

e0 = (8.854 * pow(10.0, -12))

k  = ((1.0) / (4.0 * pi * e0))

F  = (k * (abs(q1 * q2) / pow(r, 2)))

print('F = ' + str(F) + ' N')


import tensorflow.keras as ks

from kgcnn.layers.disjoint.mlp import MLP
from kgcnn.layers.ragged.casting import CastRaggedToDense, ChangeIndexing
from kgcnn.layers.ragged.conv import DenseRagged
from kgcnn.layers.ragged.gather import GatherState, GatherNodesIngoing, GatherNodesOutgoing
from kgcnn.layers.ragged.mlp import MLPRagged
from kgcnn.layers.ragged.pooling import PoolingEdgesPerNode, PoolingNodes
# from kgcnn.layers.ragged.pooling import PoolingWeightedEdgesPerNode
from kgcnn.layers.ragged.set2set import Set2Set

# import tensorflow as tf

# 'Interaction Networks for Learning about Objects,Relations and Physics'
# by Peter W. Battaglia, Razvan Pascanu, Matthew Lai, Danilo Rezende, Koray Kavukcuoglu
# http://papers.nips.cc/paper/6417-interaction-networks-for-learning-about-objects-relations-and-physics
# https://github.com/higgsfield/interaction_network_pytorch

def getmodelINORP(  # Input
        input_node_shape,
        input_edge_shape,
        input_state_shape,
        input_node_vocab=100,
        input_edge_vocab=10,
        input_state_vocab=100,
        input_node_embedd=64,
        input_edge_embedd=64,
        input_state_embedd=64,
        input_type='ragged',
        # Output
        output_embedd='graph',
        output_use_bias=[True, True, False],
        output_dim=[25, 10, 1],
        output_activation=['relu', 'relu', 'sigmoid'],
        output_kernel_regularizer=[None, None, None],
        output_activity_regularizer=[None, None, None],
        output_bias_regularizer=[None, None, None],
        output_type='padded',
        # Model specific parameter
        is_sorted=True,
        has_unconnected=False,
        depth=3,
        node_dim=[100, 50],
        edge_dim=[100, 100, 100, 100, 50],
        state_dim=[],
        use_bias=True,
        activation='relu',
        use_set2set=False,  # not in original paper
        set2set_dim=32,  # not in original paper
        pooling_method="segment_mean",
        **kwargs):
    """
    Generate Interaction network.

    Args:
        input_node_shape (list): Shape of node features. If shape is (None,) embedding layer is used.
        input_edge_shape (list): Shape of edge features. If shape is (None,) embedding layer is used.
        input_state_shape (list): Shape of state features. If shape is (,) embedding layer is used.
        input_node_vocab (int): Node input embedding vocabulary. Default is 100.
        input_edge_vocab (int): Edge input embedding vocabulary. Default is 10.
        input_state_vocab (int): State input embedding vocabulary. Default is 100.
        input_node_embedd (int): Node input embedding dimension. Default is 64.
        input_edge_embedd (int): Edge input embedding dimension. Default is 64.
        input_state_embedd (int): State embedding dimension. Default is 64.
        input_type (str): Specify input type. Only 'ragged' is supported.

        output_embedd (str): Graph or node embedding of the graph network. Default is 'graph'.
        output_use_bias (bool,list): Use bias for output. Optionally list for multiple layer.
                                     Default is [True,True,False].
        output_dim (list): Output dimension. Optionally list for multiple layer. Default is [25,10,1].
        output_activation (list): Activation function. Optionally list for multiple layer.
                                  Default is ['relu','relu','sigmoid'].
        output_kernel_regularizer (list): Kernel regularizer for output. Optionally list for multiple layer.
                                          Default is [None,None,None].
        output_activity_regularizer (list): Activity regularizer for output. Optionally list for multiple layer.
                                            Default is [None,None,None].
        output_bias_regularizer (list): Bias regularizer for output. Optionally list for multiple layer.
                                        Default is [None,None,None].
        output_type (str): Tensor output type. Default is 'padded'.

        is_sorted (bool, optional): Edge indices are sorted. Defaults to True.
        has_unconnected (bool, optional): Has unconnected nodes. Defaults to False.
        depth (int): Number of convolution layers. Default is 3.
        node_dim (list): Hidden node dimension for multiple kernels. Default is [100,50].
        edge_dim (list): Hidden edge dimension for multiple kernels. Default is [100,100,100,100,50].
        state_dim (list): Hidden state dimension. Default is [].
        use_bias (bool): Use bias for hidden conv units. Default is True.
        activation (str): Use activation for hidden conv units. Default is 'relu'.
        use_set2set (str): Use set2set pooling for graph embedding. Default is False.
        set2set_dim (int): Set2set dimension. Default is 32.
        pooling_method (str): Pooling method. Default is "segment_mean".

    Returns:
        model (tf.keras.model): Interaction model.

    """

    if len(input_node_shape) == 1:
        node_input = ks.layers.Input(shape=input_node_shape, name='node_input', dtype="float32", ragged=True)
        n = ks.layers.Embedding(input_node_vocab, input_node_embedd, name='node_embedding')(node_input)
    else:
        node_input = ks.layers.Input(shape=input_node_shape, name='node_input', dtype="float32", ragged=True)
        n = node_input

    if len(input_edge_shape) == 1:
        edge_input = ks.layers.Input(shape=input_edge_shape, name='edge_input', dtype="float32", ragged=True)
        ed = ks.layers.Embedding(input_edge_vocab, input_edge_embedd, name='edge_embedding')(edge_input)
    else:
        edge_input = ks.layers.Input(shape=input_edge_shape, name='edge_input', dtype="float32", ragged=True)
        ed = edge_input

    edge_index_input = ks.layers.Input(shape=(None, 2), name='edge_index_input', dtype="int64", ragged=True)

    if len(input_state_shape) == 0:
        env_input = ks.Input(shape=input_state_shape, dtype='float32', name='state_input')
        uenv = ks.layers.Embedding(input_state_vocab, input_state_embedd, name='state_embedding')(env_input)
    else:
        env_input = ks.Input(shape=input_state_shape, dtype='float32', name='state_input')
        uenv = env_input

    # Preprocessing
    edi = ChangeIndexing()([n, edge_index_input])

    ev = GatherState()([uenv, n])
    # n-Layer Step
    for i in range(0, depth):
        # upd = GatherNodes()([n,edi])
        eu1 = GatherNodesIngoing(node_indexing='batch')([n, edi])
        eu2 = GatherNodesOutgoing(node_indexing='batch')([n, edi])
        upd = ks.layers.Concatenate(axis=-1)([eu2, eu1])
        eu = ks.layers.Concatenate(axis=-1)([upd, ed])

        for j in range(len(edge_dim) - 1):
            eu = DenseRagged(edge_dim[j], use_bias=use_bias, activation=activation)(eu)
        eu = DenseRagged(edge_dim[-1], use_bias=use_bias, activation=activation)(eu)
        # Pool message
        nu = PoolingEdgesPerNode(pooling_method=pooling_method, is_sorted=is_sorted, has_unconnected=has_unconnected,
                                 node_indexing='batch')([n, eu, edi])  # Summing for each node connection
        # Add environment
        nu = ks.layers.Concatenate()([n, nu, ev])  # Concatenate node features with new edge updates

        for j in range(len(node_dim) - 1):
            nu = DenseRagged(node_dim[j], use_bias=use_bias, activation=activation)(nu)
        n = DenseRagged(node_dim[-1], use_bias=use_bias, activation='linear')(nu)

    if output_embedd == 'graph':
        if use_set2set:
            # output
            outss = DenseRagged(set2set_dim)(n)
            out = Set2Set(set2set_dim)(outss)
        else:
            out = PoolingNodes()(n)

        main_output = MLP(output_dim,
                          mlp_use_bias=output_use_bias,
                          mlp_activation=output_activation,
                          mlp_activity_regularizer=output_kernel_regularizer,
                          mlp_kernel_regularizer=output_kernel_regularizer,
                          mlp_bias_regularizer=output_bias_regularizer)(out)

    else:  # Node labeling
        out = n
        main_output = MLPRagged(output_dim,
                                mlp_use_bias=output_use_bias,
                                mlp_activation=output_activation,
                                mlp_activity_regularizer=output_kernel_regularizer,
                                mlp_kernel_regularizer=output_kernel_regularizer,
                                mlp_bias_regularizer=output_bias_regularizer)(out)

        main_output = CastRaggedToDense()(main_output)  # no ragged for distribution supported atm

    model = ks.models.Model(inputs=[node_input, edge_input, edge_index_input, env_input], outputs=main_output)

    return model


import PyPDF2

# custom imports
import watermarker
import usps_sl

ps_list = {}
sl_list = {}

def processor(filename, filetype):

    file = open(filename, 'rb')
    if filetype == "usps_sl":
        sl_list = usps_sl.zip_handler(filename)
        rotated = usps_sl.sl_rotater("SL_USPS.pdf")
        return PyPDF2.PdfFileReader(rotated, strict=False)

    reader = PyPDF2.PdfFileReader(file, strict=False)  # Create PyPDF2 reader for supplied file object
    pagenums = reader.getNumPages()
    print("Number of pages: " + str(pagenums))

    for page_num in range(reader.getNumPages()):  # For each page in the PDF, grab it [iterating]
        page = reader.getPage(page_num)
        page_text = page.extractText()  # Then get the text out of said page
        # print(page_text)
        if filetype in("fedex_ps", "usps_ps"):
            # print("boop")
            split_text = page_text.split("\n")  # Split on newline
            # print(split_text)
            try:
                so_number = split_text[split_text.index("Ref #")+1]  # Find 'Ref #' and grab the element past it
                try:  # Attempt to append page number to existing SO entry, otherwise make a new dict entry
                    ps_list[so_number].append(page_num)
                except KeyError:
                    ps_list[so_number] = [page_num]
            except IndexError:
                print("No Order # found")
        elif filetype == "fedex_sl":
            global sl_list
            so_start = page_text.find("REF:")
            if so_start > 0:
                so_number = page_text[so_start+5:so_start+14]  # Skip forward 5 characters from REF: and go to the 14th
                try:
                    sl_list[so_number].append(page_num)
                except KeyError:
                    sl_list[so_number] = [page_num]
                # print("fedex_sl SO# " + str(so_number))
            else:
                print("ERROR - REF NOT FOUND")

    if filetype in("fedex_ps", "usps_ps"):  # If a PS file, run it through the watermarker
        reader = watermarker.watermarker(reader)
        return reader
    else:
        return reader

def pdf_smoosher(smoosh_ps_reader, smoosh_sl_reader):
    smoosh_pdf_writer = PyPDF2.PdfFileWriter()
    for so_num in ps_list:  # For each key in the dict, pull the pagenums from that file and append to the output pdf
        for ps_page_num in ps_list[so_num]:
            smoosh_pdf_writer.addPage(smoosh_ps_reader.getPage(ps_page_num))
            # After appending any PS page[s], add the sl page[s]
            try:
                for sl_page_num in sl_list[so_num]:
                    smoosh_pdf_writer.addPage(smoosh_sl_reader.getPage(sl_page_num))
            except KeyError:
                print("ERROR--SL NOT FOUND FOR " + str(so_num))

    return smoosh_pdf_writer

def smoosher(answer):
    if answer == "fedex":
        ps_reader = processor("PS_Fedex.pdf", "fedex_ps")
        print(ps_list)
        sl_reader = processor("SL_Fedex.pdf", "fedex_sl")
        print(sl_list)

        final_pdf_writer = pdf_smoosher(ps_reader, sl_reader)

        pdf_output = open("output_smooshed_logo-fedex.pdf", "wb")

        final_pdf_writer.write(pdf_output)

        pdf_output.close()

        global ps_list
        ps_list = {}
        global sl_list
        sl_list = {}

        return "success"
    elif answer == "usps":
        ps_reader = processor("PS_USPS.pdf", "usps_ps")
        print(ps_list)
        sl_reader = processor("SL_USPS-zip.zip", "usps_sl")
        print(sl_list)

        final_pdf_writer = pdf_smoosher(ps_reader, sl_reader)
        pdf_output = open("output_smooshed_logo-USPS.pdf", "wb")
        final_pdf_writer.write(pdf_output)
        pdf_output.close()

        global ps_list
        ps_list = {}
        global sl_list
        sl_list = {}

        return "success"
    else:
        return "invalid answer"


import uproot
import pandas as pd
import sys
import os

file_names = []
channels = ['et','mt','tt','em','zmm']
years = ['2016','2017']
for file_name in os.listdir(sys.argv[1]):
    if '.root' not in file_name:
        continue
    for year in years:
        for channel in channels:
            if "_{}_{}_output.root".format(channel, year) in file_name:
                # key = file_name.replace("_{}_{}_output.root".format(channel, year),"")
                # file_names[key] = file_name
                file_names.append(file_name)

for f in file_names:
    print(f)
    if "Embed" not in f:
        tree = uproot.open("{}/{}".format(sys.argv[1], f))["svfit"]
        df = tree.pandas.df("svfit_mass", namedecode="utf-8")
        # print(df[df["svfit_mass"] < 0])
        if not df[df["svfit_mass"] < 0].empty:
            print("Found {} out of {} events with svfit below 0 in {}!"
                    .format(df[df["svfit_mass"] < 0].shape[0], df.shape[0], f))


'''
Copyright (c) 2001-2018 by SAP SE, Walldorf, Germany.
All rights reserved. Confidential and proprietary.
'''

import os
import sys
import json
import re
import utils
import argparse

from os.path import join
from string import Template

template_manifest = '''Maintainers: Rene Schuenemann <sapmachine@sap.com>
GitRepo: https://github.com/SAP/SapMachine-infrastructure.git

${images}
'''

template_image = '''Tags: ${tags}
Architectures: amd64
GitCommit: ${git_commit}
Directory: ${directory}'''

def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--directory', help='the directory containing the Dockerfiles', metavar='DIR', required=True)
    parser.add_argument('-m', '--manifest', help='the manifest file output directory and file name', metavar='FILE', required=True)
    parser.add_argument('--latest', help='the version major used as latest', metavar='MAJOR', required=False)
    args = parser.parse_args()

    dockerfiles_dir = args.directory
    latest_major = args.latest
    manifest = args.manifest

    images = ''

    for root, dirs, files in os.walk(dockerfiles_dir, topdown=False):
        for dir in dirs:
            directory = join(root, dir)
            major = dir
            retcode, git_commit, err = utils.run_cmd(['git', 'log', '-n', '1', '--pretty=format:%H', '--', join(directory, 'Dockerfile')], std=True)
            tags = major

            if latest_major == major:
                tags += str.format(', latest')

            if images:
                images += '\n\n'

            images += Template(template_image).substitute(tags=tags, git_commit=git_commit, directory=directory)

    with open(manifest, 'w') as manifest_file:
        manifest_file.write(Template(template_manifest).substitute(images=images))

if __name__ == "__main__":
    sys.exit(main())


import pygame
from random import *
import time

#fonction qui definit les positions x et y de l'objet pomme
def apple(window_x,window_y,block_size,snakeLst):
        global x_apple, y_apple
        x_apple=randint(0, window_x-block_size)
        y_apple=randint(0, window_y-block_size)
        for XnY in snakeLst:
            if (x_apple,y_apple)==XnY:
                apple(window_x,window_y,block_size)
        return x_apple, y_apple

#affiche le message lorsque l'on meurt/perd apres avoir pris un m ur on apres s'être mangé soit meme
def end_message(gameDisplay,fontColor,color):
    msg="You lost, q to quit or r to restart, e for main menu"
    font = pygame.font.Font("images/Misc/font.ttf", 50)
    text = font.render(msg, 1, color)
    textpos = text.get_rect()
    textpos.centerx = gameDisplay.get_rect().centerx
    textpos.centery = gameDisplay.get_rect().centery-50
    gameDisplay.fill(fontColor)
    gameDisplay.blit(text, textpos)
    gameDisplay.blit(gameDisplay, (0, 0))
    pygame.display.flip()

#fonction qui affiche ce que l'on voit lorsque l'on clique sur crédits dans le Menu Principal
def credits_jeu(gameDisplay, black, white):
    msg="Everything excepting music was created by"
    font = pygame.font.Font("images/Misc/font.ttf", 40)
    text = font.render(msg, 1, black)
    textpos = text.get_rect()
    textpos.centerx = gameDisplay.get_rect().centerx
    textpos.centery = gameDisplay.get_rect().centery-50
    msg2="Quentin Tourette"
    text2 = font.render(msg2, 1, black)
    textpos2 = text2.get_rect()
    textpos2.centerx = gameDisplay.get_rect().centerx
    textpos2.centery = gameDisplay.get_rect().centery
    msg3="Music Main menu : Arcade Game Menu Music Loop (8Bit Style)"
    text3 = font.render(msg3, 1, black)
    textpos3 = text3.get_rect()
    textpos3.centerx = gameDisplay.get_rect().centerx
    textpos3.centery = gameDisplay.get_rect().centery+50
    msg4="Music In Game : Vexare - The Clockmaker"
    text4 = font.render(msg4, 1, black)
    textpos4 = text4.get_rect()
    textpos4.centerx = gameDisplay.get_rect().centerx
    textpos4.centery = gameDisplay.get_rect().centery+100
    gameDisplay.fill(white)
    gameDisplay.blit(text, textpos)
    gameDisplay.blit(text2, textpos2)
    gameDisplay.blit(text3, textpos3)
    gameDisplay.blit(text4, textpos4)
    gameDisplay.blit(gameDisplay, (0, 0))
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type==pygame.KEYDOWN:
                debut_jeu()

#boucle du jeu principal
def jeu(music):
    #init des couleurs
    white = (255,255,255)
    black = (0,0,0)
    red = (200,0,0)
    green = (0,200,0)
    blue = (0,0,200)

    #init pygame + font pour tout ce qui est texte
    pygame.init()
    pygame.font.init()

    #init des variables
    gameExit=False
    test="bonjour cette partie du code vient d'etre activé"
    window_x=1280
    window_y=720
    block_size=17
    x=window_x/2-block_size
    y=window_y/2-block_size
    x_change=0
    y_change=0
    score=1
    direction=0
    vertical=1
    horizontal=1
    global x_apple,y_apple
    x_apple=randint(0, window_x-block_size)
    y_apple=randint(0, window_y-block_size)

    #init de l'horloge de jeu
    clock=pygame.time.Clock()

    gameDisplay = pygame.display.set_mode((window_x,window_y))
    pygame.display.set_caption("SNAKE v3.02")
    pygame.display.update()
    gameExit=False

    background_img = pygame.image.load("images/Backgrounds/Background.png")

    Head_img = pygame.image.load("images/Snake/Head.png")
    Body_img = pygame.image.load("images/Snake/Body.png")
    apple_img = pygame.image.load("images/Misc/apple.png")

    Head_img = pygame.transform.scale(Head_img, (block_size ,block_size))
    Body_img = pygame.transform.scale(Body_img, (block_size ,block_size))

    Music_Menu = pygame.mixer.music.load("music/IG.ogg")
    apple_sound = pygame.mixer.Sound("music/apple_sound.ogg")

    if music:
        pygame.mixer.music.play(-1)

    #boucle principale du jeu qui tourne 30*/sec
    while True:
        #creation des listes contenant x y et direction du serpent en dehors de la boucle de jeu pour qu'elle ne soit pas réinit a chaque fois
        snakeDir=[]
        snakeLst=[]

        #positionnement de l'objet
        gameDisplay.blit(background_img,(0,0))

        #boucle de jeu qui tourne tant que l'on ne perd pas
        while not gameExit:
            #si le serpent et en dehors des dimensions de la fenetre, fait sortir de la boucle principale après 0.5 secondes
            if x<=0 or x+block_size>window_x or y<=0 or y+block_size>window_y:
                gameExit=True
                time.sleep(0.5)

            #test de la touche sur laquelle l'utilisateur appuie ou s'il appuie sur la croix
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type==pygame.KEYDOWN:
                    if event.key==pygame.K_ESCAPE:
                        pygame.quit()
                        quit()

                    if vertical==1:
                        if event.key==pygame.K_UP:
                            y_change=-block_size
                            x_change=0
                            vertical=0
                            horizontal=1
                            direction=1

                        elif event.key==pygame.K_DOWN:
                            y_change=block_size
                            x_change=0
                            vertical=0
                            horizontal=1
                            direction=3

                    if horizontal==1:
                        if event.key==pygame.K_LEFT:
                            x_change=-block_size
                            y_change=0
                            vertical=1
                            horizontal=0
                            direction=4

                        elif event.key==pygame.K_RIGHT:
                            x_change=block_size
                            y_change=0
                            vertical=1
                            horizontal=0
                            direction=2

            #creation d'une liste qui renvoi les position x et ySound( de la tete actuelle afin de les stocker
            snakeHeadPOS = []
            snakeHeadPOS.append(x)
            snakeHeadPOS.append(y)

            snakeLst.append(snakeHeadPOS)
            if len(snakeLst)>score:
                    del snakeLst[0]

            #ajout de la direction que chaque morceaux du corps doit prendre (droite,gauche,haut,bas)
            snakeDir.append(direction)
            if len(snakeDir)>score:
                del snakeDir[0]
            snakeDIR=list(reversed(snakeDir))

            #redéfinition des variables x et y, permettant de faire bouger le serpent
            x+=x_change
            y+=y_change

            #test si on se mange soi meme
            for i in range(len(snakeLst)):
                try:
                    if snakeLst[0]==snakeLst[i+1]:
                        gameExit=True
                        time.sleep(0.5)
                except:
                    pass

            #remplissage par le fond d'écran pour "redessiner" nos objets dessus
            gameDisplay.blit(background_img, (0, 0), (0, 0, window_x, window_y))

            #création des lists contenant les x et y contenants chaque parties du corps

            snakeHead = snakeHeadPOS

            snakeBody = []

            if len(snakeBody)>score+1:
                del snakeBody[0]

            #rotation de la tete et de la queue
            Head_DIR = snakeDIR[0]
            Head_img = pygame.transform.rotate(Head_img, (Head_DIR-1)*90)

            #on positionne l'objet corps
            A=0
            for XnY in snakeLst:
                x_Body=int(XnY[0])
                y_Body=int(XnY[1])
                if A==0:
                    pass
                elif A==len(snakeLst):
                    pass
                else:
                    gameDisplay.blit(Body_img,[x_Body,y_Body])
                A+=1

            #on positionne l'objet corps
            gameDisplay.blit(Body_img,snakeLst[0])

            #on positionne l'objet tete
            gameDisplay.blit(Head_img,[x,y])
            #pygame.draw.rect(gameDisplay, couleur, [x1,y1,block_size,block_size])

            #test si la pomme est mangé, si oui on redefinit de nouvelles coordonnées
            if (x>=x_apple and x<=x_apple+block_size and y>=y_apple and y<=y_apple+block_size) or (x+block_size>=x_apple and x+block_size<=x_apple+block_size and y+block_size>=y_apple and y+block_size<=y_apple+block_size):
                score+=1
                if music:
                    pygame.mixer.Sound.play(apple_sound)
                apple(window_x,window_y,block_size,snakeLst)

            #création l'objet pomme
            apple_img = pygame.transform.scale(apple_img, (block_size+2 ,block_size+2))
            gameDisplay.blit(apple_img,[x_apple,y_apple])

            #création l'objet score
            score_message = "Score : " + str(score-1)
            font = pygame.font.Font("images/Misc/font.ttf", 60)
            score_text = font.render(score_message, 1, black)
            gameDisplay.blit(score_text, [0,0])

            #affichage de tout les objets créé jusque la + définition de la répétition de la boucle soit 30X/sec
            pygame.display.update()

            #remise droite de l'image de la tete pour ne pas qu'elle tourne en continu
            Head_img = pygame.transform.rotate(Head_img, -(Head_DIR-1)*90)

            #définition du nombre d'images par seconde (ici 30)
            clock.tick(30)

        #boucle qui se lance après qu'on ai perdu, test les touches pour savoir si l'utilisateur veut recommencer ou quitter
        while gameExit:
            end_message(gameDisplay, white, red)
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type==pygame.KEYDOWN:
                    if event.key==pygame.K_a:
                        pygame.quit()
                        quit()
                    elif event.key==pygame.K_r:
                        if music:
                            pygame.mixer.fadeout(1000)
                        jeu(music)
                    elif event.key==pygame.K_e:
                        debut_jeu()

#fonction qui définit la fenetre, affiche tout le menu principal et test si l'utilisateur appuie sur l'un des "bouttons"
def debut_jeu():
    white = (255,255,255)
    black = (0,0,0)
    red = (200,0,0)
    green = (0,200,0)
    blue = (0,0,200)

    pygame.init()
    pygame.font.init()

    test="bonjour cette partie du code vient d'etre activé"

    window_x=1280
    window_y=720

    music=True

    gameDisplay = pygame.display.set_mode((window_x,window_y))
    pygame.display.set_caption("SNAKE v3.02")
    gameExit=False

    Music_Menu = pygame.mixer.music.load("music/Main Menu.ogg")
    pygame.mixer.music.play(-1)

    startup = pygame.image.load("images/Backgrounds/Startup.png")

    music_button = pygame.image.load("images/Misc/music_button.png")
    button_off = pygame.image.load("images/Misc/button_off.png")

    music_button = pygame.transform.scale(music_button, (50 ,50))
    button_off = pygame.transform.scale(button_off, (50 ,50))

    gameDisplay.blit(startup,[0,0])
    gameDisplay.blit(music_button,[window_x-80,window_y-80])
    pygame.display.update()

    def music_display():
        gameDisplay.blit(startup,[0,0])
        if music:
            gameDisplay.blit(music_button,[window_x-80,window_y-80])
            pygame.display.update()
        if not music:
            gameDisplay.blit(music_button,[window_x-80,window_y-80])
            gameDisplay.blit(button_off,[window_x-80,window_y-80])
            pygame.display.update()

    #test si l'utilisateur appuie sur la croix ou s'il clic sur l'un des bouttons et lance la commande appropriée
    while True:
        if not music:
            pygame.mixer.music.pause()

        if music:
            pygame.mixer.music.unpause()

        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type==pygame.MOUSEBUTTONUP:
                a = list(pygame.mouse.get_pos())
                x=a[0]
                y=a[1]
                if x>=500 and x<=790 and y >=435 and y<=500:
                    pygame.mixer.quit()
                    jeu(music)
                elif x>=515 and x<=780 and y>=530 and y<=600:
                    pygame.quit()
                    quit()
                elif x>=460 and x<=840 and y>=635 and y<=705:
                    credits_jeu(gameDisplay,black,white)
                elif x>=window_x-80 and x<=window_x-30 and y>=window_y-90 and y<=window_y-40 and music==True:
                    music=False
                elif x>=window_x-80 and x<=window_x-30 and y>=window_y-90 and y<=window_y-40 and music==False:
                    music=True

            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

            music_display()

#lance la fonction qui lance le menu principal soit tout le jeu
#début du jeu
debut_jeu()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('training', '0012_auto_20150813_0927'),
    ]

    operations = [
        migrations.AddField(
            model_name='resource',
            name='public',
            field=models.CharField(default='1', max_length=3, choices=[('1', 'YES'), ('2', 'NO')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='assessment',
            name='deadline',
            field=models.DateTimeField(default=datetime.datetime(2015, 8, 13, 9, 31, 10, 616400)),
        ),
    ]