import json
import pandas as pd
import numpy as np
import glob
from collections import OrderedDict
# In this program we are searching in Sentinel5-P Json formatted files for data in the location of UCD
# UCD : 53.3067° N, 6.2210° W  location 1 :Stillorgan Road, Booterstown, Dublin, D04 F438
# Booterstown Dublin Ireland
# To merge the ouptut file with EPA and in-situ sensors datasets
# The nearest input data to UCD location
# The output file will have an entry daily for air quality
def display():
    #################################Choose Output file of merged Data##################################################
    outputFilePath = "/THE_FINAL/SP5_CO.json"
    #('C:/NC/SentinelData/THE_FINAL/SP5_NO2.json')
    merged_array = []
    pollutant_name = ""
    ################################# Reading Data in OGC standardized json file ####################################
    for file_name in glob.glob("/processed_json/*.json"):
        series = pd.read_json(file_name)
        for series_name in series:
            pollutant_name = series_name ##reading pollutant name
        longitude = 0.0
        latitude = 0.0
        surface_pressure = 0.0
        least_long = 300
        least_lat = 300
        air_quality = 0.0
        eucledean_min_dist = 0
        air_quality_uom = ""
        min_long = 0.0
        min_lat = 0.0
        optimum_value = 0
        dist_min = 100
        var = series[pollutant_name]
        for key in var.keys():
            iterate = 0
            dist_min = 100
            for (subkey, value) in zip(var[key].keys(), var[key].values()):
                if (subkey == "time"):
                    time = value["instant"]
                elif (subkey == "surface_pressure"):
                    surface_pressure = value["value"]
                    surface_pressure_uom = value["uom"]
                elif (subkey == "Latitude"):  # searching for nearest latitude
                    if (51.0 < value["value"] < 54.0):
                        latitude = value["value"]
                        iterate = iterate + 1
                elif (subkey == "Longitude"): # searching for nearest longitude
                    if (-8.0 <= value["value"] <= -5.0):
                        longitude = value["value"]
                        iterate = iterate + 1
                elif (subkey == "uom"):
                    air_quality_uom = value

                elif (subkey == "value"):
                    air_quality = value

            if iterate == 2:
                a = np.array((latitude, longitude))
                b = np.array((53.350140, -6.266155)) # Location of UCD
                dist = np.linalg.norm(a - b)
                ############ Searching for nearest Point ###############
                if dist < dist_min: # Eucledean distance in file to UCD
                    dist_min = dist
                    min_long = longitude
                    min_lat = latitude
                    optimum_value = air_quality
                    optimum_time = time
                    eucledean_min_dist = dist_min
##########################Making new file with one entry daily for air quality##########################################
        if optimum_value != 0:
            merged_array.append(
                {"uom": str(air_quality_uom), "value": str(optimum_value), "optimum_dist": str(eucledean_min_dist),
                "time": {"instant": str(optimum_time)},"surface_pressure":{"value":surface_pressure,"uom":surface_pressure_uom}})
    pollutantValues = {pollutant_name: merged_array}
    outfile = open(outputFilePath, 'w')
    outfile.write(json.dumps(OrderedDict(pollutantValues), indent=4, sort_keys=True))

if __name__ == '__main__':

    NO2_file_path = display()


import sys

# Load Python version specific modules
if sys.version_info[0] == 3:
    import urllib.request
    import urllib.parse
else:
    import urllib

def get_zincid_from_smile(smile_str, backend='zinc15'):
    """
    Gets the corresponding ZINC ID(s) for a SMILE string query from
    the ZINC online database. Requires an internet connection.
    Keyword arguments:
        smile_str (str): A valid SMILE string, e.g.,
            C[C@H]1CCCC[NH+]1CC#CC(c2ccccc2)(c3ccccc3)O'
        backend (str): Specifies the database backend, "zinc12" or "zinc15"
    Returns the SMILE string for the corresponding ZINC ID(s) in a list.
        E.g., ['ZINC01234567', 'ZINC01234568', 'ZINC01242053', 'ZINC01242055']
    """

    if backend not in {'zinc12', 'zinc15'}:
        raise ValueError("backend must be 'zinc12' or 'zinc15'")

    stripped_smile = smile_str.strip()
    encoded_smile = urllib.parse.quote(stripped_smile)

    if backend == 'zinc12':
        url_part1 = 'http://zinc12.docking.org/results?structure.smiles='
        url_part3 = '&structure.similarity=1.0'
    elif backend == 'zinc15':
        url_part1 = 'http://zinc.docking.org/substances/search/?q='
        url_part3 = ''
    else:
        raise ValueError("Backend must be 'zinc12' or 'zinc15'. "
                         "Got %s" % (backend))

    zinc_ids = []

    try:
        if sys.version_info[0] == 3:
            #smile_url = urllib.request.pathname2url(encoded_smile)
            response = urllib.request.urlopen('{}{}{}'
                                              .format(url_part1,
                                                      encoded_smile,
                                                      url_part3))
        else:
            #smile_url = urllib.pathname2url(encoded_smile)
            response = urllib.urlopen('{}{}{}'
                                      .format(url_part1,
                                              encoded_smile,
                                              url_part3))
    except urllib.error.HTTPError:
        print('Invalid SMILE string {}'.format(smile_str))
        response = []
    for line in response:
        line = line.decode(encoding='UTF-8').strip()

        if backend == 'zinc15':
            if line.startswith('<a href="/substances/ZINC'):
                line = line.split('/')[-2]
                if sys.version_info[0] == 3:
                    zinc_id = urllib.parse.unquote(line)
                else:
                    zinc_id = urllib.unquote(line)
                zinc_ids.append(str(zinc_id))
        else:
            if line.startswith('<a href="//zinc.docking.org/substance/'):
                line = line.split('')[-2].split('>')[-1]
                if sys.version_info[0] == 3:
                    zinc_id = urllib.parse.unquote(line)
                else:
                    zinc_id = urllib.unquote(line)
                zinc_id = 'ZINC' + (8-len(zinc_id)) * '0' + zinc_id
                zinc_ids.append(str(zinc_id))
    return zinc_ids


T = int(input())
for tc in range(1, T+1):
    N = int(input())
    prime_factor = [2, 3, 5, 7, 11]  # 소인수 리스트에 2, 3, 5, 7, 11을 담는다.
    cnt = [0]*5  # 각 소인수 5개의 지수를 담을 빈 리스트 생성

    for n in range(len(prime_factor)):
        while True:
            if N % prime_factor[n] == 0:  # 주어진 숫자 N을 소인수 리스트의 n번째 숫자로 나눈 나머지가 0이면
                N = N//prime_factor[n]  # N은 그 숫자로 나눈 몫
                cnt[n] += 1  # cnt 리스트에서 n번째 인덱스에 1을 더한다.
            else:  # 나눈 나머지가 0이 아니면 멈추고 그 다음 인덱스로
                break
    # 한 칸 공백을 주고 출력해야 하므로 ' '.join
    # .join()은 리스트를 '문자열'로 일정하게 합쳐주는 메서드 ==>  '구분자'.join()으로 사용
    print("#{} {}".format(tc, ' '.join(map(str, cnt))))

    # print("#{} {}".format(tc,cnt)) 이대로 입력하면 #1 [3, 2, 2, 3, 1]과 같이 리스트 형태로 출력된다.


from openpyxl import load_workbook

# get map set
def get_map_set(sheet, nrow, ncol):
    SET = set()
    for row in range(2, nrow + 1):
        for column in range(2, ncol + 1):
            V = sheet.cell(row=row, column=column).value
            V_str = str(V).strip()
            SET.add(V_str)
    return SET

#create dictionary from massive
def get_bus_elements(str_pack, str_chip):
    #Dictionary
    DIC = {}

    #package string
    left_pack = str_pack.find('[')
    right_pack = str_pack.find(']')
    delta_pack = right_pack - left_pack

    l_num_pack=int(str_pack[right_pack - 1])
    h_num_pack = int(str_pack[left_pack+1:left_pack+1+delta_pack-3])

    #chip string
    left_chip = str_chip.find('[')
    right_chip = str_chip.find(']')
    delta_chip = right_chip - left_chip

    l_num_chip=int(str_chip[right_chip - 1])
    h_num_chip = int(str_chip[left_chip+1:left_chip+1+delta_chip-3])

    for i in range(l_num_pack, h_num_pack+1):
        str_0 = str_pack[:left_pack]+f'{i}' #package
        str_1 = str_chip[:left_chip] + f'{i+l_num_chip-l_num_pack}' #chip
        DIC[str_0]=str_1

    return DIC

def get_one_elements_set(str):
    # Dictionary
    SET = set()

    # package string
    left_pack = str.find('[')
    right_pack = str.find(']')
    delta_pack = right_pack - left_pack
    if right_pack - left_pack > 2:
        l_num_pack = int(str[right_pack - 1])
        h_num_pack = int(str[left_pack + 1:left_pack + 1 + delta_pack - 3])
        for i in range(l_num_pack, h_num_pack + 1):
            if '_[' in str:
                str_0 = str[:left_pack] + f'{i}'  # element str
                SET.add(str_0)
            else:
                str_0 = str[:left_pack]  + f'{i}'  # element str
                SET.add(str_0)
    else:
        str_0=str[:left_pack] + f'{str[-2]}'
        SET.add(str_0)
    return SET

def get_one_elements_set_chip(str):
    # Dictionary
    SET = set()

    # package string
    left_pack = str.find('[')
    right_pack = str.find(']')
    delta_pack = right_pack - left_pack
    if right_pack - left_pack > 2:
        l_num_pack = int(str[right_pack - 1])
        h_num_pack = int(str[left_pack + 1:left_pack + 1 + delta_pack - 3])
        for i in range(l_num_pack, h_num_pack + 1):
            str_0 = str[:left_pack] + f'{i}'  # element str
            SET.add(str_0)
    else:
        str_0=str[:left_pack] + f'{str[-2]}'
        SET.add(str_0)
    return SET

#create dictionary from any input
def get_elements(str_pack, str_chip):

    DIC = {}

    if str_pack.find(']'):
        DIC.update(get_bus_elements(str_pack, str_chip))
    else:
        DIC[str_pack] = str_chip
    return DIC

def get_elements_set(string):
    SET = set()
    if string != None:
        if string[-1] ==']':
            SET.update(get_one_elements_set(string))
        else:

            #split and work with separator
            LIST = string.replace(" ", "").split(',')
            SET.update(LIST)
    return SET

def get_elements_set_chip(str):
    SET = set()
    if str != None:
        if str[-1] ==']':
            SET.update(get_one_elements_set_chip(str))
        else:
            #split and work with separator
            LIST = str.replace(' ','').split(',')
            SET.update(LIST)
    return SET

HOME = 'DATA/Pinout_prove_change'
File = 'VESTA400_18_04_23'
wb = load_workbook(f'{HOME}/{File}.xlsx')
# get sheet names
sheetnames = wb.sheetnames
# get sheet data
sheet_tb_gnss = wb[sheetnames[1 - 1]]
sheet_tb_test = wb[sheetnames[2 - 1]]
sheet_tb_modem = wb[sheetnames[3 - 1]]
sheet_tb_app_ui = wb[sheetnames[4 - 1]]
sheet_tb_app_ps = wb[sheetnames[5 - 1]]
sheet_map_pack = wb[sheetnames[6 - 1]]
sheet_map_chip = wb[sheetnames[7 - 1]]
#mirror
#sheet_map_chip = wb[sheetnames[8 - 1]]

SET_TABLE=set()
SET_MAP = set()

#generate set tb_gnss
for i in range(3,44+1):
    cell_left =  sheet_tb_gnss.cell(row=i, column=1).value
    cell_right = sheet_tb_gnss.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE.update(get_elements_set(cell_left))

#generate set tb_test
for i in range(3,18+1):
    cell_left =  sheet_tb_test.cell(row=i, column=1).value
    cell_right = sheet_tb_test.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE.update(get_elements_set(cell_left))

#generate set tb_modem
for i in range(3,68+1):
    cell_left =  sheet_tb_modem.cell(row=i, column=1).value
    cell_right = sheet_tb_modem.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE.update(get_elements_set(cell_left))

#generate set tb_app_ui
for i in range(3,70+1):
    cell_left =  sheet_tb_app_ui.cell(row=i, column=1).value
    cell_right = sheet_tb_app_ui.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE.update(get_elements_set(cell_left))

#generate set tb_app_ps
for i in range(4,39+1):
    cell_left =  sheet_tb_app_ps.cell(row=i, column=1).value
    cell_right = sheet_tb_app_ps.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE.update(get_elements_set(cell_left))

SET_MAP=get_map_set(sheet_map_pack, 21, 21)

print('Package errors')
print('Table - Map')
print(SET_TABLE-SET_MAP)
print('Map - Table')
print(SET_MAP-SET_TABLE)
print('#------------#')

##work with chip

SET_TABLE_CHIP=set()

#generate set tb_gnss
for i in range(3,44+1):
    cell_left_1 =  sheet_tb_gnss.cell(row=i, column=8).value
    cell_left_2 = sheet_tb_gnss.cell(row=i, column=9).value
    SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_1))
    SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_2))

#generate set tb_test
for i in range(3,18+1):
    cell_left =  sheet_tb_test.cell(row=i, column=9).value
    cell_right = sheet_tb_test.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left))

#generate set tb_modem
for i in range(3,68+1):
    cell_left_1 =  sheet_tb_modem.cell(row=i, column=9).value
    cell_left_2 = sheet_tb_modem.cell(row=i, column=8).value
    cell_right = sheet_tb_modem.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_1))
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_2))

#generate set tb_app_ui
for i in range(3,70+1):
    cell_left =  sheet_tb_app_ui.cell(row=i, column=5).value
    cell_right = sheet_tb_app_ui.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left))

#generate set tb_app_ps
for i in range(4,39+1):
    cell_left_1 =  sheet_tb_app_ps.cell(row=i, column=8).value
    cell_left_2 = sheet_tb_app_ps.cell(row=i, column=9).value
    cell_right = sheet_tb_app_ps.cell(row=i, column=2).value
    if cell_right!=None:
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_1))
        SET_TABLE_CHIP.update(get_elements_set_chip(cell_left_2))

SET_MAP_CHIP=get_map_set(sheet_map_chip, 62, 62)

print('Chip errors')
print('Table - Map')
print(SET_TABLE_CHIP-SET_MAP_CHIP)
print('Map - Table')
print(SET_MAP_CHIP-SET_TABLE_CHIP)
print('#------------#')

##---------------------------------------------------------
##---------------------------------------------------------
'''

print('RSV' in SET_TABLE_CHIP)
'''


from model.pif import ProgramInternalForm
from model.st import SymbolTable
from model.spec_language import *
from model.scanner import *

if __name__ == '__main__':
    fileName = input("Insert file name: ")

    file = open(fileName, 'r', errors='ignore', encoding="utf8")
    for line in file:
        print(line)

    with open(fileName, 'r', encoding="utf8") as file:
        for line in file:
            print([token for token in tokenGenerator(line, separators)])

    symbolTable = SymbolTable()
    pif = ProgramInternalForm()

    with open(fileName, 'r', encoding="utf8") as file:
        lineNo = 0
        for line in file:
            lineNo += 1
            for token in tokenGenerator(line[0:-1], separators):
                if token == ' ':
                    continue
                if token in separators + operators + reservedWords:
                    pif.add(token, -1)
                elif isIdentifier(token):
                    id = symbolTable.add(token)
                    pif.add(codification['identifier'], id)
                elif isConstant(token):
                    id = symbolTable.add(token)
                    pif.add(codification['constant'], id)
                else:
                    raise Exception('Unknown token ' + token + ' at line ' + str(lineNo))

    print('Program Internal Form: \n', pif)
    print('Symbol Table: \n', symbolTable)


# script for transforming dataset (JSON + images) to digit-per-image representation

import sys
import os
import json
from shapely.geometry import Polygon
from PIL import Image

ann_file = sys.argv[1]
destination_folder = sys.argv[2]

if os.listdir(destination_folder):
    print("ERROR: Directory is not empty")
    sys.exit()

with open(ann_file) as json_file:
    data = json.load(json_file)
    imgs = {}
    for img in data['images']:
        imgs[img['id']] = Image.open(img['file_name'])
    data['images'].clear()

    # delete category ID=0 which is reserved for background
    for cat in data['categories']:
        if cat['id'] == 0:
            data['categories'].remove(cat)
    cnts = {
        1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
        7: 0,
        8: 0,
        9: 0,
        10: 0
    }
    ann_id = 0
    for ann in data['annotations']:
        img = imgs[ann['image_id']]
        img_cropped = img.crop((
            ann['bbox'][0],
            ann['bbox'][1],
            ann['bbox'][0] + ann['bbox'][2],
            ann['bbox'][1] + ann['bbox'][3]))
        img_cropped.save(
            destination_folder + '/' + str(ann['category_id']) + '_' + str(cnts[ann['category_id']]) + '.jpg',
            quality=95)
        width, height = img_cropped.size
        data['images'].append({
            'license': 0,
            'url': None,
            'file_name': 'JPEGImages/' + str(ann['category_id']) + '_' + str(cnts[ann['category_id']]) + '.jpg',
            'height': height,
            'width': width,
            'date_captured': None,
            'id': ann_id
        })
        ann['image_id'] = ann_id
        for seg in ann['segmentation']:
            counter = 0
            for i in range(len(seg)):
                if counter % 2 == 0:  # x
                    seg[i] = seg[i] - ann['bbox'][0]
                else:  # y
                    seg[i] = seg[i] - ann['bbox'][1]
                counter = counter + 1

        ann['bbox'] = [0, 0, width, height]

        cnts[ann['category_id']] = cnts[ann['category_id']] + 1
        ann_id = ann_id + 1

    with open('annotations-new.json', 'w') as outfile:
        json.dump(data, outfile)
    print(cnts)


import pandas as pd
df = pd.read_csv('C:/python_data_analysis/resources/course1_downloads/census.csv')
print(df.head())

# method chaining
print(df.where(df['SUMLEV']==50)
    .dropna()
    .set_index(['STNAME','CTYNAME'])
    .rename(columns={'ESTIMATESBASE2010': 'Estimates Base 2010'})
    .head())


import os

from menu import MENU

profit = 0

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

def report():
    global resources
    global profit
    print(f"Water: {resources['water']}ml")
    print(f"Milk: {resources['milk']}ml")
    print(f"Coffee: {resources['coffee']}g")
    print(f"Money: ${profit}")

def count_money():
    """Returns the total calculated from coins inserted."""
    print("Please insert coins.")
    total = int(input("how many quarters?: ")) * 0.25
    total += int(input("how many dimes?: ")) * 0.1
    total += int(input("how many nickles?: ")) * 0.05
    total += int(input("how many pennies?: ")) * 0.01
    return total

def check_resourse(choice):

    check=MENU[choice]

    for item in resources:
        if resources[item] >=check["ingredients"][item]:
            return "True"
        else:
            return "False"

flag=True

while flag==True:

    choice = input("What would you like? (espresso/latte/cappuccino): ")

    if choice=="report":
        os.system('cls||clear')
        report()

    elif choice=="off":
        flag=False

    elif not (choice=="report" and choice=="off"):
        varify=check_resourse(choice)
        if varify=="True":
            chose=MENU[choice]
            payment=count_money()
            cost=chose['cost']

            if cost>payment:
                os.system('cls||clear')
                print (f'your payment ${payment} is low it requires atleast ${cost}')

            elif cost <payment:

                exchange=payment-cost
                profit +=cost
                os.system('cls||clear')
                print (f'here is your exchange ${exchange}')
                print (f'here is your cofy enjoy')

                chose=MENU[choice]

                for item in resources:
                    resources[item] -=chose["ingredients"][item]

            else:
                os.system('cls||clear')
                print (f'here is your cofy enjoy')
                profit +=cost
                chose=MENU[choice]

                for item in resources:
                    resources[item] -=chose["ingredients"][item]

        elif varify=="False":
            os.system('cls||clear')
            print('resources are not sufficient')


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2022/10/29 15:48
# @Author  : HuntingGame
# @FileName: 1267. 统计参与通信的服务器.py
# @Software: PyCharm
# C'est la vie. Enjoy ur day ! :D
from typing import List

class Solution:

    def countServers(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        ans = 0
        onecomputer = []
        for i in range(m):
            if sum(grid[i]) >1:
                ans +=sum(grid[i])
            else:
                onecomputer.append(i)

        for j in range(n):

            # 这个时候值需要统计一行只有一个的情况，因为其他的已经统计过了
            sumtmp = sum([each[j] for each in grid])
            sumrow = sum([grid[i][j] for i in onecomputer])
            if sumtmp >1:
                ans +=sumrow

        return ans

计数/1267. 统计参与通信的服务器.py

1267. 统计参与通信的服务器.py


import csv
import pandas as pd
import numpy as np
from sklearn import preprocessing
import os

class Preprocessor(object):
	"""
    An instance of this class helps in loading and preprocessing the data

	Members:
        type : Type of preprocessing. Only 'Default' implemented
        data : Contains data without the target as lists of lists
        target : Contains target of each row
        feature_names : Name of columns stored in list of strings
        class_name :

	Usage:
	>>> p=Preprocessor().load('datasamples/','winequality.csv').Preprocess()

    """

	def __init__(self, type='Default'):
		self.type=type
		self.data=[];           #list of rows of data
		self.target=[];         #target value
		self.feature_names=[]   #column names
		self.class_name=""
		self.strategy = "mean"

	def load(self, path, filename, strategy):
		"""
        Loads data from csv, json and xlsx files

        Args :
            path : Path to the directory containing the folder
            filename : Name of the file

        Returns:
            self : returns a Preprocessor object with feature_names, class_name, data, target loaded from the file
        """

		absolute_path = os.path.join(path, filename)
		assert os.path.exists(absolute_path)
		if filename.lower().endswith('.csv'):
			csv_load = pd.read_csv(absolute_path)
			self.feature_names = csv_load.columns[:-1]
			self.class_name = csv_load.columns[-1]
			self.data = csv_load[self.feature_names]
			self.target = csv_load[self.class_name]
		elif filename.lower().endswith('.json'):
			json_load = pd.read_json(absolute_path)
			self.feature_names = json_load.columns[:-1]
			self.class_name = json_load.columns[-1]
			self.data = json_load[self.feature_names]
			self.target = json_load[self.class_name]
			pass
		elif filename.lower().endswith('.xlsx'):
			xlsx_load = pd.read_excel(absolute_path)
			self.feature_names = xlsx_load.columns[:-1]
			self.class_name = xlsx_load.columns[-1]
			self.data = xlsx_load[self.feature_names]
			self.target = xlsx_load[self.class_name]

		if strategy is not None:
			self.strategy = strategy

		return self

	def Preprocess(self):
		"""
        Preprocesses the loaded data

        Args :

        Returns:
            formated_data : Returns a dictionary with keys 'data', 'target', 'feature_names', 'class_names' which are the same as the data elements of the Preprocessor object.
        """

		if self.type == 'Default':

			#converting string type columns into category type
			categorical_columns=[]
			for col in self.data.columns:
				if self.data[col].dtype==np.object:  #by default string data was of object type
					categorical_columns.append(col)
					self.data[col] = self.data[col].astype('category')

			#for one hot encoding
			self.data=pd.get_dummies(self.data,columns=categorical_columns)

			#transformation and scaling
			formated_data = {}

			# print(self.data['alcohol'])

			imputer = preprocessing.Imputer(strategy=self.strategy).fit(self.data)
			formated_data['data'] = imputer.transform(self.data)

			# print(self.data.columns, formated_data['data'][-1])

			# For handling missing values
			scaler = preprocessing.MinMaxScaler()
			formated_data['data'] = scaler.fit_transform(formated_data['data'])

			# print(formated_data['data'][:,:-1])

			formated_data['target'] = self.target
			#formated_data['feature_names'] = self.feature_names
			formated_data['feature_names'] = self.data.columns
			formated_data['class_name'] = self.class_name
			return formated_data
		else:
			raise NotImplementedError


"""      DATA ABSTRACTION - hiding data behind something like class etc     """

class Ineuron:
    # private variable
    __student = "data science"
    achievers = "achieved"

    def students(self):
        print("print the class of students", Ineuron.__student)

""" Here we are hiding student variable as protected mode. So can only
    be accessed by entering to class and then to variable   """

i = Ineuron()
i.students()

''' Abstraction data '''
print(i._Ineuron__student)

'''not abstracted data'''
print(i.achievers)

Day to day Learning/Day 13 (30-12-2022) oops_inheritance_abstraction_encapsulation_polymorphism/oops_inheritance_abstraction_polymorphism/test4.py


import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal
from scipy.signal import welch

from mne.time_frequency import psd_array_multitaper, psd_array_welch
from mne.time_frequency.multitaper import _psd_from_mt
from mne.time_frequency.psd import _median_biases
from mne.utils import catch_logging

def test_psd_nan():
    """Test handling of NaN in psd_array_welch."""
    n_samples, n_fft, n_overlap = 2048, 1024, 512
    x = np.random.RandomState(0).randn(1, n_samples)
    psds, freqs = psd_array_welch(
        x[:, : n_fft + n_overlap], float(n_fft), n_fft=n_fft, n_overlap=n_overlap
    )
    x[:, n_fft + n_overlap :] = np.nan  # what Raw.get_data() will give us
    psds_2, freqs_2 = psd_array_welch(x, float(n_fft), n_fft=n_fft, n_overlap=n_overlap)
    assert_allclose(freqs, freqs_2)
    assert_allclose(psds, psds_2)
    # 1-d
    psds_2, freqs_2 = psd_array_welch(
        x[0], float(n_fft), n_fft=n_fft, n_overlap=n_overlap
    )
    assert_allclose(freqs, freqs_2)
    assert_allclose(psds[0], psds_2)
    # defaults
    with catch_logging() as log:
        psd_array_welch(x, float(n_fft), verbose="debug")
    log = log.getvalue()
    assert "using 256-point FFT on 256 samples with 0 overlap" in log
    assert "hamming window" in log

def _make_psd_data():
    """Make noise data with sinusoids in 2 out of 7 channels."""
    rng = np.random.default_rng(0)
    n_chan, n_times, sfreq = 7, 8000, 1000
    data = 0.1 * rng.random((n_chan, n_times))
    times = np.arange(n_times) / sfreq
    sinusoid_freqs = [8.0, 50.0]
    chs_with_sinusoids = [0, 1]
    for ix, freq in zip(chs_with_sinusoids, sinusoid_freqs):
        data[ix, :] += 2 * np.sin(np.pi * 2.0 * freq * times)
    return data, sfreq, sinusoid_freqs

@pytest.mark.parametrize(
    "psd_func, psd_kwargs",
    [
        (psd_array_welch, dict(n_fft=128, window="hann")),
        (psd_array_multitaper, dict(low_bias=True)),
    ],
)
def test_psd(psd_func, psd_kwargs):
    """Tests the welch and multitaper PSD."""
    data, sfreq, sinusoid_freqs = _make_psd_data()
    # prepare kwargs
    psd_kwargs.update(dict(fmin=2, fmax=70, verbose="debug"))
    # compute PSD and test basic conformity
    with catch_logging() as log:
        psds, freqs = psd_func(data, sfreq, **psd_kwargs)
    if psd_func is psd_array_welch:
        log = log.getvalue()
        n_fft = psd_kwargs["n_fft"]
        assert f"{n_fft}-point FFT on {n_fft} samples with 0 overl" in log
        assert "hann window" in log
    assert psds.shape == (data.shape[0], len(freqs))
    assert np.sum(freqs < 0) == 0
    assert np.sum(psds < 0) == 0
    # Is power found where it should be?
    ixs_max = np.argmax(psds, axis=1)
    for ixmax, ifreq in zip(ixs_max, sinusoid_freqs):
        # Find nearest frequency to the "true" freq
        ixtrue = np.argmin(np.abs(ifreq - freqs))
        assert np.abs(ixmax - ixtrue) < 2

def test_psd_array_welch_nperseg_kwarg():
    """Test n_per_seg and padding in psd_array_welch()."""
    data, sfreq, _ = _make_psd_data()
    # prepare kwargs
    kwargs = dict(fmin=2, fmax=70, n_per_seg=128)
    # test n_per_seg in psd_array_welch (and padding)
    psds1, freqs1 = psd_array_welch(data, sfreq, n_fft=128, **kwargs)
    psds2, freqs2 = psd_array_welch(data, sfreq, n_fft=256, **kwargs)
    assert len(freqs1) == np.floor(len(freqs2) / 2.0)
    assert psds1.shape[-1] == np.floor(psds2.shape[-1] / 2.0)
    # test bad n_fft
    with pytest.raises(ValueError, match="n_fft is not allowed to be > n_tim"):
        kwargs.update(n_per_seg=None)
        bad_n_fft = int(data.shape[-1] * 1.1)
        psd_array_welch(data, sfreq, n_fft=bad_n_fft, **kwargs)
    # test bad n_overlap
    with pytest.raises(ValueError, match="n_overlap cannot be greater"):
        kwargs.update(n_per_seg=64)
        psd_array_welch(data, sfreq, n_fft=128, n_overlap=90, **kwargs)
    # test bad fmin/fmax
    with pytest.raises(ValueError, match="No frequencies found"):
        psd_array_welch(data, sfreq, fmin=10, fmax=1)

def test_complex_multitaper():
    """Test complex-valued multitaper output."""
    data, sfreq, _ = _make_psd_data()
    psd_complex, freq_complex, weights = psd_array_multitaper(
        data[:4, :500], sfreq, output="complex"
    )
    psd, freq = psd_array_multitaper(data[:4, :500], sfreq, output="power")
    assert_array_equal(freq_complex, freq)
    assert psd_complex.ndim == 3  # channels x tapers x freqs
    psd_from_complex = _psd_from_mt(psd_complex, weights)
    assert_allclose(psd_from_complex, psd)

# Copied from SciPy
def _median_bias(n):
    ii_2 = 2 * np.arange(1.0, (n - 1) // 2 + 1)
    return 1 + np.sum(1.0 / (ii_2 + 1) - 1.0 / ii_2)

@pytest.mark.parametrize("crop", (False, True))
def test_psd_array_welch_average_kwarg(crop):
    """Test `average` kwarg of psd_array_welch()."""
    data, sfreq, _ = _make_psd_data()
    # prepare kwargs
    n_per_seg = 32
    kwargs = dict(fmin=0, fmax=np.inf, n_fft=64, n_per_seg=n_per_seg, n_overlap=0)
    # optionally crop data by n_per_seg so that we are sure to test both an
    # odd number and an even number of estimates (for median bias)
    if crop:
        data = data[..., :-n_per_seg]
    # run with average=mean/median/None
    psds_mean, freqs_mean = psd_array_welch(data, sfreq, average="mean", **kwargs)
    psds_median, freqs_median = psd_array_welch(data, sfreq, average="median", **kwargs)
    psds_unagg, freqs_unagg = psd_array_welch(data, sfreq, average=None, **kwargs)
    # Frequencies should be equal across all "average" types, as we feed in
    # the exact same data.
    assert_array_equal(freqs_mean, freqs_median)
    assert_array_equal(freqs_mean, freqs_unagg)
    # For `average=None`, the last dimension contains the un-aggregated
    # segments.
    assert psds_mean.shape == psds_median.shape
    assert psds_mean.shape == psds_unagg.shape[:-1]
    assert_array_equal(psds_mean, psds_unagg.mean(axis=-1))
    # Compare with manual median calculation (_median_bias copied from SciPy)
    bias = _median_bias(psds_unagg.shape[-1])
    assert_allclose(psds_median, np.median(psds_unagg, axis=-1) / bias)
    # check shape of unagg
    n_chan, n_times = data.shape
    n_freq = len(freqs_unagg)
    n_segs = np.ceil(n_times / n_per_seg).astype(int)
    assert n_segs % 2 == (1 if crop else 0)
    assert psds_unagg.shape == (n_chan, n_freq, n_segs)

@pytest.mark.parametrize("n", (2, 3, 5, 8, 12, 13, 14, 15))
def test_median_biases(n):
    """Test vectorization of median_biases."""
    want_biases = np.concatenate(
        ([1.0, 1.0], [_median_bias(ii) for ii in range(2, n + 1)])
    )
    got_biases = _median_biases(n)
    assert_allclose(want_biases, got_biases)
    assert_allclose(got_biases[n], _median_bias(n))
    assert_allclose(got_biases[:3], 1.0)

@pytest.mark.slowtest
def test_compares_psd():
    """Test PSD estimation on raw for plt.psd and scipy.signal.welch."""
    data, sfreq, _ = _make_psd_data()
    n_fft = 2048
    fmin, fmax = 2, 70
    # Compute PSD with psd_array_welch
    psds_mne, freqs_mne = psd_array_welch(
        data, sfreq, fmin=fmin, fmax=fmax, n_fft=n_fft
    )
    # Compute psds with scipy.signal.welch
    freqs_scipy, psds_scipy = welch(
        data, fs=sfreq, nperseg=n_fft, noverlap=0, window="hamming"
    )
    # restrict to the relevant frequencies
    mask = (freqs_scipy >= fmin) & (freqs_scipy <= fmax)
    freqs_scipy = freqs_scipy[mask]
    psds_scipy = psds_scipy[:, mask]
    # make sure they match
    assert_array_almost_equal(psds_mne, psds_scipy)
    assert_array_equal(freqs_mne, freqs_scipy)
    assert psds_mne.shape == (data.shape[0], len(freqs_mne))
    assert psds_scipy.shape == (data.shape[0], len(freqs_scipy))
    assert np.sum(freqs_mne < 0) == 0
    assert np.sum(freqs_scipy < 0) == 0
    assert np.sum(psds_mne < 0) == 0
    assert np.sum(psds_scipy < 0) == 0

def test_psd_array_welch_n_jobs():
    """Test that n_jobs works even with more jobs than channels."""
    data = np.zeros((1, 2048))
    psd_array_welch(data, 1024, n_jobs=1)
    psd_array_welch(data, 1024, n_jobs=2)


import os
import socket
import requests
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.popup import Popup
from kivy.uix.image import Image
from kivy.core.window import Window
from kivy.uix.modalview import ModalView
from kivy.clock import Clock
from kivy.uix.spinner import Spinner
from kivy.uix.filechooser import FileChooserListView
import subprocess
from urllib.parse import urlparse
import re
from bs4 import BeautifulSoup

class ExploitsMang(App):
    def build(self):
        layout = BoxLayout(orientation="vertical", spacing=10, padding=10)

        label_title = Label(
            text="PythoPentest", size_hint_y=None, height=40, font_size=30
        )
        layout.add_widget(label_title)

        input_layout = BoxLayout(orientation="horizontal", size_hint_y=None, height=40)

        label_network = Label(text="URL:", size_hint_x=None, width=100, font_size=20)
        input_layout.add_widget(label_network)

        self.url_input = TextInput(text="", multiline=False, font_size=20)
        input_layout.add_widget(self.url_input)

        layout.add_widget(input_layout)

        full_extract_button = Button(
            text="URL Extraction", size_hint=(1, 0.1), font_size=20
        )
        full_extract_button.bind(on_press=self.full_url_extract)
        layout.add_widget(full_extract_button)

        scan_button = Button(text="Scan URL", size_hint=(1, 0.1), font_size=20)
        scan_button.bind(on_press=self.scan_admin_url)
        layout.add_widget(scan_button)

        scroll_view = ScrollView()
        self.output_label = Label(
            text="",
            size_hint_y=None,
            height=400,
            text_size=(700, None),
            valign="top",
            font_size=16,
        )
        scroll_view.add_widget(self.output_label)
        layout.add_widget(scroll_view)

        ipscan_button = Button(text="Scan IP", size_hint=(1, 0.1), font_size=20)
        ipscan_button.bind(on_press=self.scan_ip)
        layout.add_widget(ipscan_button)

        ipdetail_button = Button(text="IP Detail", size_hint=(1, 0.1), font_size=20)
        ipdetail_button.bind(on_press=self.ip_detail)
        layout.add_widget(ipdetail_button)

        vulnscan_button = Button(text="Vuln Scan", size_hint=(1, 0.1), font_size=20)
        vulnscan_button.bind(on_press=self.vuln_scan)
        layout.add_widget(vulnscan_button)

        ddos_button = Button(text="DDOS", size_hint=(1, 0.1), font_size=20)
        ddos_button.bind(on_press=self.ddos_test_popup)
        layout.add_widget(ddos_button)

        deface_button = Button(text="Deface", size_hint=(1, 0.1), font_size=20)
        deface_button.bind(on_press=self.deface_test_popup)
        layout.add_widget(deface_button)

        ping_button = Button(text="Ping", size_hint=(1, 0.1), font_size=20)
        ping_button.bind(on_press=self.ping_url)
        layout.add_widget(ping_button)

        return layout

    def full_url_extract(self, instance):
        url = self.url_input.text
        parsed_url = urlparse(url)
        full_extracted = f"Full URL: {url}\nScheme: {parsed_url.scheme}\nNetloc: {parsed_url.netloc}\nPath: {parsed_url.path}\nParams: {parsed_url.params}\nQuery: {parsed_url.query}\nFragment: {parsed_url.fragment}"
        self.output_label.text = full_extracted

    def scan_admin_url(self, instance):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        try:
            url = self.url_input.text
            response = requests.get(f"{url}/admin", timeout=5)
            if response.status_code == 200:
                self.output_label.text = "Admin page found."
            else:
                self.output_label.text = "Admin page not found."
        except requests.ConnectionError:
            self.output_label.text = "Connection failed. Make sure the URL is valid and connected to the internet."
        except requests.Timeout:
            self.output_label.text = "Request timed out. Please check your internet connection."
        except requests.RequestException as e:
            self.output_label.text = f"Error: {str(e)}"

        loading.dismiss()

    def scan_ip(self, instance):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        try:
            host = socket.gethostbyname(self.url_input.text)
            self.output_label.text = f"The IP of {self.url_input.text} is {host}"
        except socket.gaierror:
            self.output_label.text = "Invalid URL"

        loading.dismiss()

    def ip_detail(self, instance):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        try:
            ip = socket.gethostbyname(self.url_input.text)
            response = requests.get(f"https://ipinfo.io/{ip}/json")
            data = response.json()
            detail = f"IP Address: {data['ip']}\nCity: {data['city']}\nRegion: {data['region']}\nCountry: {data['country']}\nPostal Code: {data['postal']}\nTimezone: {data['timezone']}\nCoordinates: {data['loc']}"
            self.output_label.text = detail
        except socket.gaierror:
            self.output_label.text = "Invalid URL"

        loading.dismiss()

    def vuln_scan(self, instance):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        url = self.url_input.text
        try:
            response = requests.get(url)
            soup = BeautifulSoup(response.text, 'html.parser')
            vulnerabilities = soup.find_all('meta', attrs={'name': 'vulnerabilities'})
            if vulnerabilities:
                self.output_label.text = f"Vulnerabilities found: {', '.join([vul['content'] for vul in vulnerabilities])}"
            else:
                self.output_label.text = "No vulnerabilities found."
        except requests.RequestException as e:
            self.output_label.text = f"Error: {str(e)}"

        loading.dismiss()

    def ddos_test_popup(self, instance):
        self.popup_input("Jumlah Permintaan", self.ddos_test)

    def ddos_test(self, request_count):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        try:
            url = self.url_input.text
            for _ in range(int(request_count)):
                response = requests.get(url)
                self.output_label.text += f"Request Status: {response.status_code}\n"
        except Exception as e:
            self.output_label.text = f"Error: {str(e)}"

        loading.dismiss()

    def deface_test_popup(self, instance):
        content = BoxLayout(orientation="vertical")
        file_chooser = FileChooserListView()
        content.add_widget(file_chooser)

        button = Button(text="Pilih", size_hint=(None, None), size=(100, 50))
        button.bind(on_release=lambda x: self.select_file(file_chooser))
        content.add_widget(button)

        popup = Popup(
            title='Pilih File HTML',
            content=content,
            size_hint=(None, None),
            size=(400, 400)
        )
        popup.open()

    def select_file(self, file_chooser):
        file_path = file_chooser.selection and file_chooser.selection[0] or None
        if file_path:
            self.deface_test(file_path)

    def deface_test(self, file_path):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        try:
            url = self.url_input.text
            files = {'file': open(file_path, 'rb')}
            response = requests.post(url, files=files)
            if response.status_code == 200:
                target_url = response.url  # Ambil URL target dari respon
                self.output_label.text = f"Deface successful. Website content updated. URL: {target_url}"
            else:
                self.output_label.text = f"Deface unsuccessful. Status Code: {response.status_code}"
        except Exception as e:
            self.output_label.text = f"Error: {str(e)}"

        loading.dismiss()

    def ping_url(self, instance):
        loading = ModalView(size_hint=(None, None), size=(150, 150))
        loading.add_widget(Spinner(size_hint=(None, None), size=(100, 100), pos_hint={'center_x': .5, 'center_y': .5}))
        loading.open()

        url = self.url_input.text
        output = subprocess.getoutput(f"ping -c 4 {url}")
        self.output_label.text = output

        loading.dismiss()

    def popup_input(self, title, callback):
        content = BoxLayout(orientation="vertical", spacing=10, padding=10)
        input_box = TextInput(multiline=False)
        content.add_widget(input_box)

        button = Button(text="OK")
        content.add_widget(button)

        popup = Popup(title=title, content=content, size_hint=(None, None), size=(400, 200))
        button.bind(on_press=lambda x: self.popup_callback(popup, input_box.text, callback))
        popup.open()

    def popup_callback(self, popup, text, callback):
        popup.dismiss()
        callback(text)

if __name__ == '__main__':
    Window.clearcolor = (0, 0, 0, 1)  # Mengatur warna latar belakang ke hitam
    ExploitsMang().run()


"""
Created on Wed Jun 19 11:13:05 2019

Author: Corey R. Randall

Optimization routine:
    Minimize the error between the data from Owejan et. al. paper and the PEMFC
    models (core-shell and flooded-agglomerate) by varying the following:
    theta, offset, R_naf, i_o, and A (if using a 2-step reaction mechanism).

Instructions:
    To use this script, open up the pemfc_runner.py file and comment out the
    line of code that specifies w_Pt. Copy and paste the lines of code
    below to input i_OCV, i_ext1, i_ext2, and i_ext3 into pemfc_runner.py.

    Once these items have been completed, fill out the initial guess values for
    the optimization in 'p*' in the order commented below. Ranges for each of
    these parameters should also be specified in the respective 'b*' variable
    below. Simply run this script after these inputs have been filled out and
    allow for the error to be minimized for the data sets using the package
    scipy.optimize.minize.

Optimization options:
    The 'tog' variable can be set to 0, 1, or 2 in order to change which set of
    parameters are being varied in the optmization. When tog = 0 then R_naf,
    theta, i_o, and offset are all varied and assumed to be constant accross all
    Pt loadings. If tog = 1 then the same parameters are varied except i_o is
    treated as a function of Pt loading as i_o = a*w_Pt + b which allows both a
    and b to be varied instead of just a constant i_o. The last case is when
    tog = 2 which again assumes the same parameters are being varied except that
    R_naf is treated as a function of Pt loading instead of i_o. The form of
    this function is R_naf = (c*w_Pt^d +e)*1e-3 where c, d, and e become the
    fitting parameters.

Units for inputs:
    R_naf [mOhm*cm^2], theta [degrees], i_o [A/cm^2 *(cm^3/kmol)^#], offset [-],
    a [A/cm^2 *(cm^3/kmol)^# /(mg/cm^2)], b [A/cm^2 *(cm^3/kmol)^#],
    c [mOhm*cm^2 /(mg/cm^2)], d [-], e [mOhm*cm^2], and A [(kmol/cm^3)^# / s].
"""

import numpy as np
import cantera as ct

# How to set up i_ext vector in the pemfc_runner.py file:
"""
i_OCV = 0
i_ext1 = np.array([0.05, 0.20, 0.40, 0.80, 1.0, 1.2, 1.5, 1.65, 1.85, 2.0])
i_ext2 = np.array([])
i_ext3 = np.array([])"""

###############################################################################
""" Use this section if optimizing with a 1-step reaction mechanism. """

# Inputs for optimization of R_naf, theta, i_o, and offset:
p0_1s = np.array([45e-3, 45, 4e-6, 0.55])
b0_1s = np.array([[20e-3, 120e-3], [42.5, 80], [1e-6, 9e-6], [0.52, 1.0]])

# Inputs for optimization of R_naf, theta, offset, a, and b from i_o = a*w_Pt + b:
p1_1s = np.array([55e-3, 45, 0.55, 24.2e-6, -0.40e-6])
b1_1s = np.array([[20e-3, 120e-3], [42.5, 80], [0.52, 1.0], [24.17e-6, 50e-6], [-0.5e-6, 1e-6]])

# Inputs for optimization of theta, i_o, offset, c, d, and e from R_naf = (c*w_Pt^d +e)*1e-3:
p2_1s = np.array([50, 1.3e-6, 0.65, 0.929, -1.249, 35])
b2_1s = np.array([[42.5, 80], [5e-7, 9e-6], [0.52, 1.0], [0., 1.5], [-1.5, 0.], [0., 120.]])

# Toggle for which optimization to run (0, 1, or 2):
tog = 2

###############################################################################
""" Use this section if optimizing with a 2-step reaction mechanism. """

# Inputs for optimization of R_naf, theta, i_o, offset, and A:
p0_2s = np.array([])
b0_2s = np.array([])

""" Do not edit anything below this line """
"-----------------------------------------------------------------------------"
###############################################################################
###############################################################################
###############################################################################

# Data to fit for different Pt loadings (x,y) -> (i [A/cm^2], Phi [V]):
" All x values are shared and y* is the y data, s* is the error bars (+/-) "
x = np.array([0.0, 0.05, 0.20, 0.40, 0.80, 1.0, 1.2, 1.5, 1.65, 1.85, 2.0])
y1 = np.array([0.95, 0.85, 0.80, 0.77, 0.73, 0.72, 0.70, 0.68, 0.67, 0.65, 0.63]) # w_Pt = 0.2 mg/cm^2
s1 = np.array([0.1, 12, 7, 7, 12, 1, 8, 7, 7, 9, 9]) *1e-3

y2 = np.array([0.93, 0.83, 0.79, 0.75, 0.71, 0.69, 0.67, 0.65, 0.64, 0.62, 0.60]) # w_Pt = 0.1 mg/cm^2
s2 = np.array([0.1, 9, 7, 5, 7, 11, 11, 7, 9, 11, 11]) *1e-3

y3 = np.array([0.92, 0.81, 0.76, 0.72, 0.67, 0.65, 0.63, 0.60, 0.59, 0.56, 0.54]) # w_Pt = 0.05 mg/cm^2
s3 = np.array([0.1, 8, 6, 6, 7, 7, 5, 5, 6, 7, 7]) *1e-3

y4 = np.array([0.91, 0.79, 0.72, 0.68, 0.63, 0.60, 0.57, 0.53, 0.50, 0.46, 0.43]) # w_Pt = 0.025 mg/cm^2
s4 = np.array([0.1, 4, 10, 14, 13, 13, 19, 24, 25, 23, 24]) *1e-3

# Scipy optimization (try now) vs scikits-learn (later??):
optimize = 1 # tell pre processor to reset optimized parameters

from scipy.optimize import minimize
y_data = np.hstack([y1[1:], y2[1:], y3[1:], y4[1:]])
s_data = np.hstack([s1[1:], s2[1:], s3[1:], s4[1:]])

def chi_sq_func0_1s(p_opt): # p_opt[:] = R_naf, theta, i_o, offset

    global w_Pt, R_naf_opt, theta_opt, i_o_opt, offset_opt
    R_naf_opt, theta_opt, i_o_opt, offset_opt = p_opt
    print('\n\nR_naf, theta, i_o, offset:', p_opt)

    y_model = np.array([])
    w_Pt_vec = np.array([0.2, 0.1, 0.05, 0.025])
    for i, w in enumerate(w_Pt_vec):
        w_Pt = w
        exec(open("pemfc_runner.py").read(), globals(), globals())
        y_model = np.hstack([y_model, dphi_ss[1:]])

    chi_sq = sum((y_data - y_model)**2 / s_data**2)
    print('\nchi_sq:', chi_sq)

    return chi_sq

# Results for by-hand fit: (comparison to tog = 0)
"""
chi_sq = 884.6912413825394

R_naf = user_inputs.R_naf = 45e-3
theta = user_inputs.theta = 45.
i_o = 4e-6
offset = 0.55"""

# Results for tog = 0:
"""
chi_sq = 442.3504466112417

R_naf = user_inputs.R_naf = 47.0708165e-3
theta = user_inputs.theta = 44.9310232
i_o = 1.47659887e-6
offset = 0.549173549"""

def chi_sq_func1_1s(p_opt): # p_opt[:] = R_naf, theta, offset, a, b
    w_Pt_vec = np.array([0.2, 0.1, 0.05, 0.025])

    global w_Pt, R_naf_opt, theta_opt, offset_opt, a, b
    R_naf_opt, theta_opt, offset_opt, a, b = p_opt
    print('\n\nR_naf, theta, offset, a, b:', p_opt)
    print('i_o:', abs(a*w_Pt_vec + b))

    y_model = np.array([])
    for i, w in enumerate(w_Pt_vec):
        w_Pt = w
        exec(open("pemfc_runner.py").read(), globals(), globals())
        y_model = np.hstack([y_model, dphi_ss[1:]])

    chi_sq = sum((y_data - y_model)**2 / s_data**2)
    print('\nchi_sq:', chi_sq)

    return chi_sq

# Results for by-hand with varying i_o: (comparison to tog = 1)
"""
chi_sq = 403.90458836954605

R_naf = user_inputs.R_naf = 45e-3
theta = user_inputs.theta = 45.
offset = 0.55
a = 24.5e-6
b = -0.60e-6"""

# Results for tog = 1:
"""
chi_sq = 111.3265875677507

R_naf = user_inputs.R_naf = 54.4607050e-3
theta = user_inputs.theta = 44.9763477
offset = 0.545805050
a = 24.17e-6
b = -0.434032963e-6"""

def chi_sq_func2_1s(p_opt): # p_opt[:] = theta, i_o, offset, c, d, e
    w_Pt_vec = np.array([0.2, 0.1, 0.05, 0.025])

    global w_Pt, theta_opt, i_o_opt, offset_opt, c, d, e
    theta_opt, i_o_opt, offset_opt, c, d, e = p_opt
    print('\n\ntheta, i_o, offset, c, d:', p_opt)
    print('R_naf:', (c*w_Pt_vec**d + 35) *1e-3)

    y_model = np.array([])
    for i, w in enumerate(w_Pt_vec):
        w_Pt = w
        exec(open("pemfc_runner.py").read(), globals(), globals())
        y_model = np.hstack([y_model, dphi_ss[1:]])

    chi_sq = sum((y_data - y_model)**2 / s_data**2)
    print('\nchi_sq:', chi_sq)

    return chi_sq

# Results for by-hand with varying R_naf: (comparison to tog = 2)
"""
chi_sq = 203.66835835935382

theta = user_inputs.theta = 45.
i_o = 2e-6
offset = 0.55
c = 0.874
d = -1.083
e = 35."""

# Results for tog = 2:
"""
chi_sq = 65.40625573579791

theta = user_inputs.theta = 50.0625811
i_o = 2.06131753e-6
offset = 0.655151490
c = 0.915326473
d = -1.23061654
e = 34.5429028"""

def chi_sq_func0_2s(p_opt): # p_opt[:] = R_naf, theta, i_o, offset, A
    w_Pt_vec = np.array([0.2, 0.1, 0.05, 0.025])

    global w_Pt, R_naf_opt, theta_opt, i_o_opt, offset_opt, A_opt
    theta_opt, i_o_opt, offset_opt, A_opt = p_opt
    print('\n\nR_naf, theta, i_o, offset, A:', p_opt)

    y_model = np.array([])
    for i, w in enumerate(w_Pt_vec):
        w_Pt = w
        exec(open("pemfc_runner.py").read(), globals(), globals())
        y_model = np.hstack([y_model, dphi_ss[1:]])

    chi_sq = sum((y_data - y_model)**2 / s_data**2)
    print('\nchi_sq:', chi_sq)

    return chi_sq

import pemfc_runner as run

if all([rxn_mech == '1s', tog == 0]):
    res = minimize(chi_sq_func0_1s, p0_1s, method='L-BFGS-B', bounds=b0_1s)
elif all([rxn_mech == '1s', tog == 1]):
    res = minimize(chi_sq_func1_1s, p1_1s, method='L-BFGS-B', bounds=b1_1s)
elif all([rxn_mech == '1s', tog == 2]):
    res = minimize(chi_sq_func2_1s, p2_1s, method='L-BFGS-B', bounds=b2_1s)
elif all([rxn_mech == '2s']):
    res = minimize(chi_sq_func0_2s, p0_2s, method='L-BFGS-B', bounds=b0_2s)

# Use this in w_Pt_runner to see what plots look like:
""" Post this line of code in w_Pt_runner.py between line 38 and line 40. Set
the tog value to the correct option (0, 1, or 2) based on what parameters are
being varied. Then set the needed values equal to their optimal parameters while
commenting out any that are unneeded. Run w_Pt_runner.py once done to see the
results.

optimize, tog = 1, 1
R_naf_opt = user_inputs.R_naf = 54.4607050e-3
theta_opt = user_inputs.theta = 50.0625811
i_o_opt = 2.06131753e-6
offset_opt = 0.655151490
a = 24.17e-6
b = -0.434032963e-6
c = 0.915326473
d = -1.23061654
e = 34.5429028"""


#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
# 欢迎关注微信公众号：点滴技术
# 这里有靠谱、有价值、免费分享
import datetime
import os

import ntplib

hosts1 = [
    'ntp.tuna.tsinghua.edu.cn',
    'time.ustc.edu.cn',
    'ntp.ntsc.ac.cn',
    'ntp.aliyun.com',
    'ntp.neu.edu.cn',
    'ntp.nju.edu.cn',
    'time.buptnet.edu.cn',
    's1d.time.edu.cn',
    'time.asia.apple.com',
]
hosts2 = ['0.cn.pool.ntp.org', '1.cn.pool.ntp.org', '2.cn.pool.ntp.org', '3.cn.pool.ntp.org']
hosts = []
hosts += hosts1
hosts += hosts2

def ntp_client():
    # 创建实例，NTPClient()是一个类
    t = ntplib.NTPClient()
    ok = False
    for host in hosts:
        try:
            # ntp server可以填写主机和域名，建议用域名
            # 缺省端口为ntp， 版本为2， 超时为5s
            # 作用：查询 NTP 服务器，并返回对象
            r = t.request(host, port='ntp', version=4, timeout=5)
            if r:
                # 显示的是时间戳
                t = r.tx_time
                ok = True
                print("从{}获取到时间".format(host))
                break
        except Exception as e:
            pass

    if ok:
        # 使用datetime模块,格式化：x年x月x日 时:分:秒.毫秒
        # _date, _time = str(datetime.datetime.fromtimestamp(t))[:22].split(' ')
        _date, _time = datetime.datetime.fromtimestamp(t).strftime("%Y%m%d %H:%M:%S")[:22].split(' ')
        print("调整前时间是：", datetime.datetime.now())
        os.system("date")
        command = 'sudo date -s "{} {}"'.format(_date, _time)
        os.system(command)
        print(command)
        print("调整后时间是：", datetime.datetime.now())
        os.system("date")

if __name__ == '__main__':
    # 适用于Windows
    ntp_client()


#!/usr/bin/env python3
import os, sys, re, shutil

def nbrLigne(tree):
    fichier = open(tree, "r", encoding="ISO-8859-1")
    n = 0
    while fichier.readline():
        n += 1
    return n

def compress(input,output="NULL"):
    if output=="NULL":
        output=input+'.huff'
    if os.path.isfile(input):
        out = open(output, "w", encoding="ISO-8859-1")
        out.write(input)
        out.write('\n')
        os.system("./huff -c "+ input +" "+ output+".temp")
        out.write(str(nbrLigne(output+".temp")))
        out.write('\n')
        shutil.copyfileobj(open(output+".temp", 'r', encoding="ISO-8859-1"), out)
        out.close()
        os.remove(output+".temp")
    else:
        if os.path.isdir(input):
            list_original_file = []
            sub_compress(input,list_original_file)
            out = open(output, "w", encoding="ISO-8859-1")
            for file in list_original_file:
                out.write(input+file)
                out.write('\n')
                out.write(str(nbrLigne(input+"_huff"+file)))
                out.write('\n')
                shutil.copyfileobj(open(input+"_huff"+file, 'r', encoding="ISO-8859-1"), out)
                out.write('\n')
            out.close()
            shutil.rmtree(input+"_huff")
        else:
            print("Erreur entrée inaccessible. Fatal.")
    return

def sub_compress(path,list_original_file,input=""):
    if os.path.isfile(path+input):
        os.system("./huff -c "+ path + "/" + input +" "+ path+"_huff/"+input)
        list_original_file.append(input)
    else:
        if os.path.isdir(path+input):
            if not(os.path.isdir(path+"_huff"+input)):
                os.mkdir(path+"_huff"+input);
                for file in os.listdir(path+input):
                    sub_compress(path,list_original_file,input+"/"+file)
            else:
                print("Verifiez que la compression n'est pas déja effectué ou supprimez le dossier _huff. Fatal.")
                return
        else:
            print("Erreur entrée inaccessible. Fatal. "+path+input)
    return

def decompress(input):
    if os.path.isfile(input):
        inFile = open(input, "r", encoding="ISO-8859-1")
        fichier = inFile.readlines()
        inFile.close()
        compress = -1;
        for ligne in fichier:
            if compress==-1:
                path = ligne.strip('\n')
                try:
                    os.makedirs(os.path.dirname(path))
                except:
                    pass
                temp = open(path+".huff.temp", "w", encoding="ISO-8859-1")
                compress=-2
            else:
                if compress==-2:
                    compress=int(ligne);
                else:
                    if compress>=0:
                        if compress>0:
                            temp.write(ligne)
                            compress=compress-1
                        if compress==0:
                            temp.close()
                            os.system("./huff -x "+path+".huff.temp " + path )
                            os.remove(path+".huff.temp")
                            compress=-1
    else:
        print("Erreur entrée inaccessible. Fatal.")
    return

if (len(sys.argv)!=3):
    print("No enough/Too many argument.");
else:
    if re.search("^-[c]?[x]?$",sys.argv[1]):
        if re.search("c",sys.argv[1]):
            compress(sys.argv[2])
        if re.search("x",sys.argv[1]):
            decompress(sys.argv[2])
    else:
        print(sys.argv[1], " is not a correct argument.");
exit();


#!/usr/bin/fontforge -script

r'''
python file from https://github.com/pteromys/svgs2ttf
Revise by MaoHuPi

terminal command:
"C:\Program Files (x86)\FontForgeBuilds\run_fontforge.exe" "./_svg2ttf.py"
'''

import sys
import os.path
import json
import fontforge
import psMat
import math

path = '.' if os.path.isfile('./'+os.path.basename(__file__)) else os.path.dirname(os.path.abspath(__file__))
IMPORT_OPTIONS = ('removeoverlap', 'correctdir')

try:
    unicode
except NameError:
    unicode = str

def readJson(filename='font.json'):
    f = open(filename, 'r', encoding='utf-8')
    c = f.read()
    f.close()
    o = json.loads(c)
    return(o)

def setProperties(font, config):
    props = config['props']
    lang = props.pop('lang', 'English (US)')
    family = props.pop('family', None)
    style = props.pop('style', 'Regular')
    props['encoding'] = props.get('encoding', 'UnicodeFull')
    if family is not None:
        font.familyname = family
        font.fontname = family + '-' + style
        font.fullname = family + ' ' + style
    for k, v in config['props'].items():
        if hasattr(font, k):
            if isinstance(v, list):
                v = tuple(v)
            setattr(font, k, v)
        else:
            font.appendSFNTName(lang, k, v)
    for t in config.get('sfnt_names', []):
        font.appendSFNTName(str(t[0]), str(t[1]), unicode(t[2]))

def addGlyphs(font, config):
    matrixs = []
    if config.get('transform', False) != False:
        matrixs = [getattr(psMat, k)(*v) for k, v in config['transform'].items()]
    for k, v in config['glyphs'].items():
        g = font.createMappedChar(int(k, 0))
        font.removeGlyph(g)
        g = font.createChar(int(k, 0))
        # Get outlines
        src = '%s.svg' % k
        if not isinstance(v, dict):
            v = {'src': v or src}
        src = f'{path}/{config.get("input", ".")}/{v.pop("src", src)}'
        config['glyphsDone'].append(src)
        try:
            g.importOutlines(src, IMPORT_OPTIONS)
            g.removeOverlap()
            for matrix in matrixs:
                g.transform(matrix)
        except:
            print('Error (overlap)')
            return
        # Copy attributes
        for k2, v2 in v.items():
            if hasattr(g, k2):
                if isinstance(v2, list):
                    v2 = tuple(v2)
                setattr(g, k2, v2)

def main(config):
    if '*' in config['glyphs']:
        svgDir = config["input"]
        if os.path.isdir(svgDir):
            svgs = dict([(hex(ord(name[-5]) if len(name[0:-4]) == 1 else int(name[0:-4].lower().replace('u', ''))), '{name}'.format(dir = svgDir, name = name)) for name in os.listdir(svgDir) if os.path.isfile('{dir}/{name}'.format(dir = svgDir, name = name)) and (name.find('.svg') == len(name) - len('.svg'))])
            svgsSettings = config['glyphs'].pop('*')
            if type(svgsSettings) == dict:
                svgs = dict([(k, {**svgsSettings, 'src': src}) for k, src in svgs.items()])
            config['glyphs'].update(svgs)

    font = False
    sfdPath = config.get("sfd", "font.sfd")
    if config.get('sfd', False) != False and os.path.isfile(sfdPath):
        font = fontforge.open(sfdPath)
    else:
        font = fontforge.font()
    if font == False:
        return
    setProperties(font, config)
    config['glyphsDone'] = []
    addGlyphs(font, config)
    sys.stderr.write('writting')

    font.save(sfdPath)
    print(font, sfdPath)
    for outfile in config['output']:
        sys.stderr.write('writting')
        sys.stderr.write('Generating %s...\n' % outfile)
        font.generate(outfile)

    for src in config['glyphsDone']:
        os.unlink(src)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        os.chdir(os.path.abspath(sys.argv[1]))
        config = readJson('settings.json')['font']
    else:
        config = readJson(path + '/font.json')
    main(config)
    print('done')


from multiprocessing import cpu_count
import jinja2
from datetime import datetime
import subprocess as sp
from os import path
from pathlib import Path
import random

def get_thread_numbers(max_number):
    number = 1
    while number <= max_number:
        yield number
        number <<= 1

def size_string(data_sizes):
    return "x".join(map(str, data_sizes))

def schedule_string(schedule):
    return f"{schedule['schedule_type']}" + \
           (f"-chunk{schedule['chunk_size']}" if 'chunk_size' in schedule else "")

def avg(nums):
    nums.remove(max(nums))
    nums.remove(min(nums))
    return sum(nums) / len(nums)

class Runner:

    def __init__(self, template_path="templates", compiler_path=None, compiler_exec="cl", data_path="data",
                 precompile_path=None):
        fs_loader = jinja2.FileSystemLoader(searchpath=template_path)
        self.env = jinja2.Environment(loader=fs_loader)
        self.precompile_path = precompile_path
        self.compiler_path = compiler_path
        self.compiler_exec = compiler_exec
        self.data_path = data_path

    def generate_matrix(self, n, m):
        return [[random.random() for x in range(m)] for y in range(n)]

    def write_matrix(self, matrix, file):
        file.write(f"{len(matrix)} {len(matrix[0]) if matrix else ''}\n")
        file.write(f"{len(matrix)} {len(matrix[0]) if matrix else ''}\n")
        for row in matrix:
            for item in row:
                file.write(f"{item:.2f} ")
            file.write("\n")

    def generate_data_dir(self, a_path, b_path, data_sizes):
        print(f"Generating data for {size_string(data_sizes)}")
        n = data_sizes[0]
        m = data_sizes[1]
        k = data_sizes[2]
        Path(a_path).parent.mkdir(parents=True, exist_ok=True)
        with open(a_path, "w+") as a_file:
            self.write_matrix(self.generate_matrix(n, m), a_file)
        Path(b_path).parent.mkdir(parents=True, exist_ok=True)
        with open(b_path, "w+") as b_file:
            self.write_matrix(self.generate_matrix(m, k), b_file)

    def perform_run(self, loop, threads, sizes, schedule):
        src_dir, src_name = self.render_src(loop, schedule, threads)

        self.compile_src(src_dir, src_name)

        results = dict()

        start = datetime.now()
        for size_spec in sizes:
            durations = [self.perform_single_run(path.join(src_dir, src_name.replace(".cpp", ".exe")), size_spec)
                         for _ in range(5)]
            duration = avg(list(map(float, durations)))
            results.update({size_string(size_spec): duration})
        end = datetime.now()
        print(end - start)
        return results

    def compile_src(self, src_dir, src_name):
        print(f"Compiling rendered {src_name}")
        cl_proc = sp.Popen([path.join(self.precompile_path, "VsDevCmd.bat"), "&",
                            path.join(self.compiler_path, self.compiler_exec), "/EHsc", "/openmp", "/O2", src_name],
                           stdout=sp.PIPE, stderr=sp.PIPE, shell=True,
                           cwd=src_dir)
        stdout, stderr = cl_proc.communicate()
        print("Compiled successfully")
        # if cl_proc.returncode

    def render_src(self, loop, schedule, threads):
        threads = str(threads)
        params = {"threads": threads,
                  "schedule": schedule}
        omp_line = self.env.get_template("lab1.omp.j2").render(**schedule)
        if loop == "inner":
            omp_line += " private(c_ij) reduction(+:c_ij)"
        params.update({
            loop: omp_line
        })
        rendered = self.env.get_template("lab1.cpp.j2").render(params)
        src_dir = f"run/{loop}/{threads}"
        Path(src_dir).mkdir(parents=True, exist_ok=True)
        src_name = f"{schedule_string(schedule)}.cpp"
        with open(path.join(src_dir, src_name), "w+") as src:
            src.write(rendered)
        return src_dir, src_name

    def perform_single_run(self, exec, data_sizes):
        run_data_dir = path.join(self.data_path, size_string(data_sizes))
        a_path = path.join(run_data_dir, "a")
        b_path = path.join(run_data_dir, "b")

        if not path.exists(run_data_dir):
            self.generate_data_dir(a_path, b_path, data_sizes)

        print(f"starting {size_string(data_sizes)}")
        process = sp.Popen([exec, a_path, b_path], stdout=sp.PIPE, stderr=sp.PIPE)
        stdout, stderr = process.communicate()
        if stderr:
            print(stderr.decode("utf-8"))
        return stdout.decode("utf-8").strip()

loops = ["outer", "inner"]
threads = list(get_thread_numbers(cpu_count()))
schedules = [
    {"schedule_type": "dynamic"},
    {"schedule_type": "static"},
    {"schedule_type": "guided"},
    {"schedule_type": "dynamic",
     "chunk_size": "100"},
    {"schedule_type": "static",
     "chunk_size": "100"},
]
sizes = [
         [500, 500, 500],
         [800, 800, 800],
         [8000, 80, 800],
         [64000, 8, 800]
         ]

runner = Runner(
    compiler_path="C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.24.28314\\bin\\Hostx64\\x86",
    precompile_path="C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools")

total_results = list()

for thread_number in threads:
    for schedule in schedules:
        for paralleled_loop in loops:
            result = runner.perform_run(paralleled_loop, thread_number, sizes, schedule)
            for size in result:
                total_results.append(
                    {"loop": paralleled_loop,
                     "threads": thread_number,
                     "schedule": schedule_string(schedule),
                     "size": size,
                     "duration": result[size]
                     })
        print(f"done with schedule {schedule_string(schedule)}")
    print(f"done with thread {thread_number}")

if not total_results:
    exit(-1)

import csv
with open("lab1_results500.csv", "w+") as out:
    writer = csv.DictWriter(out, total_results[0].keys(), delimiter=";")
    writer.writeheader()
    writer.writerows(total_results)

import tabulate

print(tabulate.tabulate(total_results))


import json

from cam_server import PipelineClient
pc = PipelineClient("http://sf-daqsync-01:8889")

pipeline_name = "SARES11-SPEC125-M2_psen_db"
instance_name = pipeline_name + "1"

# update config
with open("SARES11-SPEC125-M2_psen.json") as config_file:
    config = json.load(config_file)

pc.save_pipeline_config(pipeline_name, config)

pc.stop_instance(instance_name)


from neo4j import GraphDatabase
from pymongo import MongoClient

            # data_plane = {"project":"scraper","spider":"plane_detail","url":plane_data,'code':code,"depart":fromSource,"dest":toDest}
            # url = 'http://127.0.0.1:6800/schedule.json'
            # req_car = grequests.post(url,data=data_car)

# MATCH (a:administrative_area_level_1),(b:CarStation) WHERE a.name = b.name CREATE (a)-[r:route { min_price: 0, price = 0, ave_price = 0 ,min_time: 0, time = 0, ave_time = 0 }]->(b)

uri = "bolt://localhost"
driver = GraphDatabase.driver(uri, auth=("neo4j", "123a!@#A"))
mongo_uri = 'mongodb://localhost:27017'
mongo_db = 'DataTransport'
client = MongoClient(mongo_uri)
db = client[mongo_db]
# x = requests.post(url,data=j)
# print(x)
routes = list(db['car_route_detail_final'].find({}))

print(len(routes))

query_car_route = ["MATCH (a:CarStop {address:\"","","\"}),(b:CarStop {address:\"","","\"}) CREATE (a)-[r:route { min_price:","",", max_price :","",", ave_price :" ,"", ",min_time:","",", time : ","",", ave_time : ","",", type : 'car',hop:1, price :","","}]->(b)"]
#1 :code1, 3 : code2 , 5 :min_price , 7 :max_price,9 :ave_price, 11 :min_time , 13: time , 15 : ave_time
with driver.session() as graphDB_Session:
    for route in routes:

        query_car_route[1] = route['departure']
        query_car_route[3] = route['arrival']
        query_car_route[5] = str(route['price'])
        query_car_route[7] = str(route['price'])
        query_car_route[9] = str(route['price'])
        query_car_route[11] = str(route['time']*60)
        query_car_route[13] = str(route['time']*60)
        query_car_route[15] = str(route['time']*60)
        query_car_route[17] = str(route['price'])

        # print(''.join(query_car_route))
        graphDB_Session.run(''.join(query_car_route))


# Base Parameters
assets = asset_list('FX')

# Trading Parameters
horizon = 'H1'
pair    = 0

# Mass Imports
my_data = mass_import(pair, horizon)

# Indicator Parameters
lookback = 100

def lwma(Data, lookback, what):

    weighted = []
    for i in range(len(Data)):
            try:
                total = np.arange(1, lookback + 1, 1)

                matrix = Data[i - lookback + 1: i + 1, what:what + 1]
                matrix = np.ndarray.flatten(matrix)
                matrix = total * matrix
                wma = (matrix.sum()) / (total.sum())
                weighted = np.append(weighted, wma)

            except ValueError:
                pass

    Data = Data[lookback - 1:, ]
    weighted = np.reshape(weighted, (-1, 1))
    Data = np.concatenate((Data, weighted), axis = 1)

    return Data

my_data = lwma(my_data, lookback, 3)

ohlc_plot_bars(my_data, 500)
plt.plot(my_data[-500:, 4], label = '100-period Linear-Weighted Moving Average')
plt.legend()


DOMAIN = "euribor_rates"
API_BASE_URL = "https://www.euribor-rates.eu/umbraco/api/euriborpageapi/highchartsdata"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.5249.62 Safari/537.36"
MATURITIES = ["1 week", "1 month", "3 months", "6 months", "12 months"]
SERIES_YEAR = 4
SERIES_HALF_YEAR = 3
SERIES_QUARTER_YEAR = 2
SERIES_MONTH = 1
SERIES_WEEK = 5
CONF_MATURITY = "maturity"
CONF_DAYS = "days"


from turtle import *

shape('turtle')
speed(10)
for i in range(1,11):
    for j in range(4):
        forward(20*i)
        left(90)
    penup()
    goto(-10*i,-10*i)
    pendown()
mainloop()


from lsst.ts import salobj

class Commander:
    """Issues commands to a CSC device

    Parameters
    ----------
    device_name : `str`
        name of CSC device to commnad
    command : `str`
        command to issues
    timeout : `int`
        command timeout value, in seconds
    """

    def __init__(self, device_name, command, timeout):
        self.device_name = device_name
        self.command = command
        self.timeout = timeout

    async def run_command(self):
        """send a command to a CSC device"""
        async with salobj.Domain() as domain:
            arc = salobj.Remote(domain=domain, name=self.device_name, index=0)
            await arc.start_task

            try:
                cmd = getattr(arc, f"cmd_{self.command}")
                await cmd.set_start(timeout=self.timeout)
            except Exception as e:
                print(e)


# pong_game.py

import pygame, sys

# initialization
clock = pygame.time.Clock()
pygame.init()

class Ball :
    def __init__(self, screen, color, posX, posY, radius) :
        self.screen = screen
        self.color = color
        self.posX = posX
        self.posY = posY
        self.radius = radius
        self.dx = 0
        self.dy = 0
        self.show()

    def show (self) :
        pygame.draw.circle(self.screen, self.color, (self.posX, self.posY), self.radius)
    def start_moving(self):
        self.dx = 2
        self.dy = 0.7
    def move(self):
        self.posX += self.dx
        self.posY += self.dy

    def paddle_collision(self) :
        self.dx = -self.dx

    def wall_collision(self):
        self.dy = - self.dy

    def restart_pos(self):
        self.posX = width // 2
        self.posY = height // 2
        self.dx = 0
        self.dy = 0
        self.show()

class Paddle :
    def __init__(self, screen, color, posX, posY, width, height ):
        self.screen = screen
        self.color = color
        self.posX = posX
        self.posY = posY
        self.width = width
        self.height = height
        self.state = "stopped"

        self.show()
    def show(self):
        pygame.draw.rect(self.screen, self.color, (self.posX, self.posY, self.width, self.height))
    def move(self):
        if self.state == "up" :
            self.posY -= 1
        if self.state == "down" :
            self.posY += 1
    def clamp(self):
        if self.posY <= 0 :
            self.posY = 0
        if self.posY + self.height >= height :
            # self.posY  + self.height = height
            self.posY   = height - self.height

    def restart_pos(self):
        self.posY = height // 2 - self.height // 2
        self.state = "stopped"
        self.show()

class Score :
    def __init__(self, screen, points, posX, posY):
        self.screen = screen
        self.points = points
        self.posX = posX
        self.posY = posY
        self.font = pygame.font.SysFont("monospace", 80, bold=True)
        self.label = self.font.render(self.points, 0, white)
        self.show()

    def show(self) :
        self.screen.blit(self.label, (self.posX - self.label.get_rect().width //2 , self.posY))

    def increase(self):
        points = int(self.points) + 1
        self.points = str(points)
        self.label = self.font.render(self.points, 0, white)

    def restart(self):
        self.points = "0"
        self.label = self.font.render(self.points, 0, white)

class CollisionManager :
    def between_ball_and_paddle1(self, ball, paddle1):
        if (ball.posY + ball.radius > paddle1.posY and ball.posY - ball.radius < paddle1.posY + paddle1.height) and (ball.posX - ball.radius < paddle1.posX + paddle1.width):
            return True
        return False

    def between_ball_and_paddle2(self, ball, paddle2):
        if (ball.posY + ball.radius > paddle2.posY and ball.posY - ball.radius < paddle2.posY + paddle2.height) and (ball.posX + ball.radius > paddle2.posX):
            return True
        return False

    def between_ball_and_walls(self, ball):
        # top
        if ball.posY - ball.radius <= 0 :
            return True
        # bottom
        if ball.posY + ball.radius >= height :
            return True
        return False

    def check_goal_player1(self, ball):
        return ball.posX - ball.radius >= width

    def check_goal_player2(self, ball):
        return ball.posX + ball.radius <= 0

width = 900
height = 500
height1 = 600

black = (0, 0, 0)
white = (255, 255, 255)

screen = pygame.display.set_mode((width, height1))
pygame.display.set_caption("PONG GAME by sai kumar adapa ")

def paint_back() :
    screen.fill(black)
    pygame.draw.line(screen, white, (width//2, 0), (width//2, height), 5)
    pygame.draw.line(screen, white, (0, height), (width, height), 5)
    font = pygame.font.SysFont("monospace", 20, bold=True)
    moves = "E = Left_Up || D = Left_Down || I = Right_Up || K = Right_Down"
    instructions = "P = start the match || R = Reset the match"
    label = font.render(moves, 0, white)
    screen.blit(label, (15, height + 15))
    label = font.render(instructions, 0, white)
    screen.blit(label, (15, height + 45))
    label = font.render("-ask", 0, (0, 255, 0))
    screen.blit(label, (width - 57, height1 - 35))
def restart() :
    paint_back()
    score1.restart()
    score2.restart()
    ball.restart_pos()
    paddle1.restart_pos()
    paddle2.restart_pos()

paint_back()
# OBJECTS

ball = Ball(screen, white, width//2, height//2, 15)
paddle1 = Paddle(screen, white, 15, (height//2-120//2), 20, 120)
paddle2 = Paddle(screen, white, width-20-15, (height//2-120//2), 20, 120)
collision = CollisionManager()
score1 = Score(screen, '0',width//4, 15)
score2 = Score(screen, '0',width - width//4, 15)

# pygame.draw.line(screen, white, (15, (height//2-120//2)), (width-20-15, (height//2-120//2)), 5)

# VARIABLES
playing = False

# main loop
while True :
    for event in pygame.event.get() :
        if event.type == pygame.QUIT :
            sys.exit()

        if event.type == pygame.KEYDOWN :

            if event.key == pygame.K_ESCAPE:

                sys.exit()

            if event.key == pygame.K_p :
                ball.start_moving()
                playing = True

            if event.key == pygame.K_r :
                restart()
                playing = False

            if event.key == pygame.K_e :
                paddle1.state = "up"
            if event.key == pygame.K_d :
                paddle1.state = "down"
            if event.key == pygame.K_i:
                paddle2.state = "up"
            if event.key == pygame.K_k:
                paddle2.state = "down"

        if event.type == pygame.KEYUP :
            paddle1.state = "stopped"
            paddle2.state = "stopped"

    if playing :
        paint_back()
        ball.move()
        ball.show()

        paddle1.move()
        paddle1.clamp()
        paddle1.show()
        paddle2.move()
        paddle2.clamp()
        paddle2.show()

        # check for collision

        if collision.between_ball_and_paddle1(ball, paddle1) :
            ball.paddle_collision()
        if collision.between_ball_and_paddle2(ball, paddle2) :
            ball.paddle_collision()
        if collision.between_ball_and_walls(ball) :
            ball.wall_collision()

        if collision.check_goal_player1(ball) :
            paint_back()
            score1.increase()
            ball.restart_pos()
            paddle1.restart_pos()
            paddle2.restart_pos()
            playing = False
        if collision.check_goal_player2(ball) :
            paint_back()
            score2.increase()
            ball.restart_pos()
            paddle1.restart_pos()
            paddle2.restart_pos()
            playing = False

    score1.show()
    score2.show()
    clock.tick(400)

    pygame.display.update()


import json
import ast
file = open("/projects/academic/esnell/kferger/PDB-input/sensible_structures_final.json", "r")
outfile = open("/projects/academic/esnell/kferger/PDB-input/sensible_structures_final_edit.json", "w")

new_data = " ".join(line.strip() for line in file)

outdict = {}
d = "}{"
if "}{" in new_data:
    s = new_data.split("}{")
for i in range(len(s)-1):
    s[i+1] = "{"+s[i+1]+"}"

outdict['structures'] = s
json.dump(outdict, outfile, indent=4, separators=(',', ': '))

"""
for line in data:
    if "}{" not in line:
        outfile.write(line)
    else:
        split = line.split("}")
        outfile.write("},\n")
        outfile.write(split[1])
        #lines.append(line)
outfile.write("\n}")
#for elem in lines:
    #outfile.write(elem)

file.close()
outfile.close()
"""


# @Time : 2022-08-04 17:17
# @Author : Phalange
# @File : 1669. 合并两个链表.py
# @Software: PyCharm
# C'est la vie,enjoy it! :D

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:

        cur1 = list1
        cur2 = list2
        prev1 = None

        # 找一下list2的尾节点
        t2 = list2
        while t2.next:
            t2 = t2.next

        idx = 0 #索引
        while cur1:
            if idx ==a:
                prev1.next = cur2

            elif idx == b+1:
                prev1.next = None# 到这里内存该回收删除的地方了
                t2.next = cur1

            prev1 = cur1
            cur1 = cur1.next
            idx +=1

        return list1


from aiohttp import web
from jinja2 import Environment, PackageLoader, select_autoescape

import dhtc

class WebHandler(object):
    def __init__(self, db: dhtc.Database):
        self.db = db
        self.env = Environment(
            loader=PackageLoader("dhtc", "templates"),
            autoescape=select_autoescape(["html"])
        )

    def build_page(self, template, ctx):
        tpl = self.env.get_template(template)
        return web.Response(body=tpl.render(ctx), content_type="text/html")

    async def handle_root(self, req):
        return self.build_page("dashboard.html", {
            "info_hash_count": self.db.get_count(),
            "bootstrap_nodes": dhtc.BOOTSTRAP_NODES
        })

    async def handle_dashboard(self, req):
        return self.build_page("dashboard.html", {
            "info_hash_count": self.db.get_count(),
            "bootstrap_nodes": dhtc.BOOTSTRAP_NODES
        })

    async def handle_search_get(self, req):
        return self.build_page("search.html", {
            "placeholder": self.db.get_random_title()
        })

    async def handle_search_post(self, req):
        data = req.post()
        print(data)
        return self.build_page("search.html", {
            "placeholder": ""
        })

    async def handle_discover_request_get(self, req):
        return self.build_page("discover.html", {
            "items": self.db.get_x_random()
        })

    async def handle_discover_request_post(self, req):
        return self.build_page("discover.html", {})

async def create_webserver(db, host, port):
    wh = WebHandler(db)
    app = web.Application()
    app.add_routes([
        web.get("/", wh.handle_root),
        web.get("/dashboard", wh.handle_dashboard),
        web.get("/search", wh.handle_search_get),
        web.post("/search", wh.handle_search_post),
        web.get("/discover", wh.handle_discover_request_get),
        web.post("/discover", wh.handle_discover_request_post)
    ])
    r = web.AppRunner(app)
    await r.setup()
    s = web.TCPSite(r, host, port)
    await s.start()