text
stringlengths
38
1.54M
import mysql.connector def inject_data(data, user='root', database='restaurantwebsite'): cnx = mysql.connector.connect(user=user, database=database) cursor0 = cnx.cursor() cursor1 = cnx.cursor() cursor2 = cnx.cursor(prepared=True) query0 = ("DROP TABLE IF EXISTS top10") query1 = ("CREATE TABLE top10(id varchar(50), first varchar(20), second varchar(20), third varchar(20), fourth varchar(20)," "fifth varchar(20), sixth varchar(20), seventh varchar(20), eighth varchar(20), nineth varchar(20), tenth varchar(20))") query2 = ("INSERT INTO top10(id, first, second, third, fourth, fifth, sixth, seventh, eighth, nineth, tenth)" "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ") cursor0.execute(query0) cursor1.execute(query1) for tuple in data: helper = [] helper.append(tuple[0]) for elem in tuple[1]: helper.append(elem) print(helper) cursor2.execute(query2, helper) cnx.commit() cursor0.close() cursor1.close() cursor2.close() cnx.close()
# coding: utf-8 import os from .default import Config class DevelopmentConfig(Config): """Base config class.""" # Flask app config DEBUG = True TESTING = False SECRET_KEY = "sample_key" # Db config SQLALCHEMY_BINDS = { 'geo_pickups': 'mysql+pymysql://root:123qwe,./@10.0.11.91:18806/geo_pickups?charset=utf8' }
import os import datetime import pymongo from flask import Flask, flash, render_template, redirect, url_for, request from flask_pymongo import PyMongo from bson.objectid import ObjectId app = Flask(__name__) app.config["MONGO_DBNAME"] = 'space_definitions' app.config["MONGO_URI"] = os.environ.get('MONGO_URI') # The following isn't used for security, this is just to enable flash messages app.secret_key = 'supersecretk3y' mongo = PyMongo(app) @app.route('/') @app.route('/space') def get_definitions(): # Grab the latest 10 definitions for display on the main page. Filter to only print ones marked as top (most votes) coll = mongo.db.definitions.find({'top_definition': True}).sort("date", pymongo.DESCENDING).limit(10) return render_template('space.html', definitions=coll) @app.route('/add_vote/<def_id>', methods=['POST']) def add_vote(def_id): definitions = mongo.db.definitions definitions.update_one({'_id': ObjectId(def_id)}, { '$inc': {'votes': 1} }) calculate_and_set_top_definition(def_id) flash('Thank you for voting!') return redirect(url_for('get_definitions')) @app.route('/add_definition') def add_definition(): return render_template('add_definition.html') @app.route('/insert_definition', methods=['POST']) def insert_definition(): definitions = mongo.db.definitions # Take data from HTML form data = request.form.to_dict() # Add in the current date / time and initialise vote count data['date'] = datetime.datetime.now() data['votes'] = 1 # Check MongoDB Database if definition exists. If unique, sets 'top_definition' to True query = {'definition_name': data['definition_name']} cursor = definitions.find(query) # Need to use count() function of cursor to get the length cursor_length = cursor.count() # If no matches were found for the same definition name, it will be the top definition if cursor_length == 0: data['top_definition'] = True flash('Congratulations, you are as smart as Spock, this is the first definition!') else: data['top_definition'] = False flash('Uh oh, you were not the first to add this definition, try to get some votes!') definitions.insert_one(data) return redirect(url_for('get_definitions')) @app.route('/edit_definition/<def_id>') def edit_definition(def_id): definition = mongo.db.definitions.find_one({"_id": ObjectId(def_id)}) return render_template('edit_definition.html', definition=definition) @app.route('/update_definition', methods=['POST']) def update_definition(): definitions = mongo.db.definitions # Take data from HTML form data = request.form.to_dict() definitions.update_one({'_id': ObjectId(data['def_id'])}, {'$set': { 'definition': data['definition'], 'editor': data['editor'], 'updated_when': datetime.datetime.now() }}) flash('Your edit has been accepted!') return redirect(url_for('get_definitions')) @app.route('/delete_definition/<def_id>', methods=['POST']) def delete_definition(def_id): definitions = mongo.db.definitions # Get definition entry definition_dict = definitions.find_one({'_id': ObjectId(def_id)}) # If definition to be deleted is the current top, a re-evaluation needs to be performed to set the new top if definition_dict['top_definition']: # For the evaluation function to work, we set the votes to 0 to force a full recalculation definitions.update_one({'_id': definition_dict['_id']}, {'$set': { 'votes': 0 }}) # With this set to 0, another definition must be the new top calculate_and_set_top_definition(def_id) # With the new top set, this record is safe to delete definitions.delete_one({'_id': ObjectId(def_id)}) flash('I hope you meant to delete that!') return redirect(url_for('get_definitions')) @app.route('/search', methods=['POST']) def search_definitions(): definitions = mongo.db.definitions data = request.form.to_dict() # A dictionary is returned above, place the value into variable search_text = data['definition_search'] # For the below search syntax to work, the MongoDB collection needs to have text indexes set for both keys # this allows for case-insensitive searching - https://docs.mongodb.com/manual/core/index-text/#create-text-index # The single search will look in both definitions and definition names return render_template('search_results.html', definition_name_hits=definitions.find({"$text": {"$search": search_text}}).sort("date", pymongo.DESCENDING)) # Utility functions def calculate_and_set_top_definition(def_id): definitions = mongo.db.definitions # Get definition entry definition_dict = definitions.find_one({'_id': ObjectId(def_id)}) print(definition_dict) # Check MongoDB Database if definition exists in more than one record query = {'definition_name': definition_dict['definition_name']} cursor = definitions.find(query) # Get the cursor count if cursor.count() > 1: # Get the definition_name definition_dict_name = definition_dict['definition_name'] # Get the current top definition current_top = definitions.find_one({'$and': [ {'top_definition': True}, {'definition_name': definition_dict_name} ] }) # Get the entry with the most votes after this vote. If there is a tie, oldest definition wins cursor_top = definitions.find({'definition_name': definition_dict_name}).sort( [('votes', -1), ('date', 1)]).limit(1) # Convert cursor to dict. Whilst using a for loop it will only be a single entry due to limit(1) above calculated_top = {} for c in cursor_top: calculated_top = c # If the entry voted on is different to the current top, set new top definition if current_top['_id'] != calculated_top['_id']: definitions.update_one({'_id': current_top['_id']}, {'$set': { 'top_definition': False }}) definitions.update_one({'_id': calculated_top['_id']}, {'$set': { 'top_definition': True }}) if __name__ == '__main__': app.run(host=os.environ.get('IP'), port=int(os.environ.get('PORT')), debug=True)
# Generated by Django 3.0.8 on 2020-11-08 05:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('events', '0017_auto_20201107_1239'), ('events', '0018_auto_20201107_1108'), ] operations = [ ]
from selenium.webdriver import Chrome from selenium.webdriver.common.keys import Keys from time import sleep driver = Chrome(executable_path='/opt/WebDriver/bin/chromedriver') # test link driver.get("https://www.bhphotovideo.com/c/product/1561250-REG/fractal_design_fd_ca_mesh_c_bko_meshify_c_atx_matx_itx_blackout.html") sleep(2) driver.find_element_by_xpath("//button[@data-selenium = 'addToCartButton']").click() sleep(2) viewCartBtn = None while viewCartBtn is None: try: viewCartBtn = driver.find_element_by_xpath("//a[@data-selenium = 'itemLayerViewCartBtn']") except: pass viewCartBtn.click() # driver.execute_script("window.open('');") # sleep(0.5) # # Switch to the new window # driver.switch_to.window(driver.window_handles[1]) # driver.get("https://www.bhphotovideo.com/find/cart.jsp") sleep(2) checkoutBtn = None while checkoutBtn is None: try: checkoutBtn = driver.find_element_by_xpath("//input[@data-selenium = 'checkoutLogin']") except: pass checkoutBtn.click() sleep(5) checkoutNoLoginBtn = None while checkoutNoLoginBtn is None: try: checkoutNoLoginBtn = driver.find_element_by_xpath("//input[@data-selenium = 'checkoutNoLogin']") except: pass driver.find_element_by_xpath("//input[@data-selenium = 'emailAddress']").send_keys() driver.find_element_by_xpath("//input[@data-selenium = 'password']").send_keys() sleep(0.5) checkoutNoLoginBtn.click()
#func to prin ladder based on input def display_ladder(steps): for count in range(steps): print("| |\n***") #func to get steps input def create_ladder(): lad_steps = int(input("How many steps remain?\n")) display_ladder(lad_steps) #call func create_ladder()
"""Methods often used to compare against to indicate baselines performance. Many are based on [Raa16a]_. """ from dapper import * @DA_Config def EnCheat(**kwargs): """A baseline/reference method. Should be implemented as part of Stats instead.""" def assimilator(stats,HMM,xx,yy): pass return assimilator @DA_Config def Climatology(**kwargs): """ A baseline/reference method. Note that the "climatology" is computed from truth, which might be (unfairly) advantageous if the simulation is too short (vs mixing time). """ def assimilator(stats,HMM,xx,yy): Dyn,Obs,chrono,X0 = HMM.Dyn, HMM.Obs, HMM.t, HMM.X0 muC = mean(xx,0) AC = xx - muC PC = CovMat(AC,'A') stats.assess(0,mu=muC,Cov=PC) stats.trHK[:] = 0 for k,kObs,_,_ in progbar(chrono.ticker): fau = 'u' if kObs is None else 'fau' stats.assess(k,kObs,fau,mu=muC,Cov=PC) return assimilator @DA_Config def OptInterp(**kwargs): """ Optimal Interpolation -- a baseline/reference method. Uses the Kalman filter equations, but with a prior from the Climatology. """ def assimilator(stats,HMM,xx,yy): Dyn,Obs,chrono,X0 = HMM.Dyn, HMM.Obs, HMM.t, HMM.X0 # Get H. msg = "For speed, only time-independent H is supported." H = Obs.linear(np.nan, np.nan) if not np.all(np.isfinite(H)): raise AssimFailedError(msg) # Compute "climatological" Kalman gain muC = mean(xx,0) AC = xx - muC PC = (AC.T @ AC) / (xx.shape[0] - 1) KG = mrdiv(PC@H.T, H@PC@H.T + Obs.noise.C.full) # Setup scalar "time-series" covariance dynamics. # ONLY USED FOR DIAGNOSTICS, not to change the Kalman gain. P = (eye(Dyn.M) - KG@H) @ PC L = estimate_corr_length(AC.ravel(order='F')) SM = fit_sigmoid(trace(P)/trace(2*PC),L,0) # Init mu = muC stats.assess(0,mu=mu,Cov=PC) for k,kObs,t,dt in progbar(chrono.ticker): # Forecast mu = Dyn(mu,t-dt,dt) if kObs is not None: stats.assess(k,kObs,'f',mu=muC,Cov=PC) # Analysis mu = muC + KG@(yy[kObs] - Obs(muC,t)) SM = fit_sigmoid(trace(P)/trace(PC),L,k) stats.assess(k,kObs,mu=mu,Cov=2*PC*SM(k)) return assimilator @DA_Config def Var3D(B=None,xB=1.0,**kwargs): """ 3D-Var -- a baseline/reference method. This implementation is not "Var"-ish: there is no *iterative* optimzt. Instead, it does the full analysis update in one step: the Kalman filter, with the background covariance being user specified, through B and xB. """ def assimilator(stats,HMM,xx,yy): Dyn,Obs,chrono,X0 = HMM.Dyn, HMM.Obs, HMM.t, HMM.X0 nonlocal B if B in (None,'clim'): # Use climatological cov, ... B = np.cov(xx.T) # ... estimated from truth B *= xB # ONLY USED FOR DIAGNOSTICS, not to change the Kalman gain. CC = 2*np.cov(xx.T) L = estimate_corr_length(center(xx)[0].ravel(order='F')) P = X0.C.full SM = fit_sigmoid(trace(P)/trace(CC),L,0) # Init mu = X0.mu stats.assess(0,mu=mu,Cov=P) for k,kObs,t,dt in progbar(chrono.ticker): # Forecast mu = Dyn(mu,t-dt,dt) P = CC*SM(k) if kObs is not None: stats.assess(k,kObs,'f',mu=mu,Cov=P) # Analysis H = Obs.linear(mu,t) KG = mrdiv(B@H.T, H@B@H.T + Obs.noise.C.full) mu = mu + KG@(yy[kObs] - Obs(mu,t)) # Re-calibrate fit_sigmoid with new W0 = Pa/B P = (eye(Dyn.M) - KG@H) @ B SM = fit_sigmoid(trace(P)/trace(CC),L,k) stats.assess(k,kObs,mu=mu,Cov=P) return assimilator def fit_sigmoid(Sb,L,kb): """Return a sigmoid [function S(k)] for approximating error dynamics. We use the logistic function for the sigmoid; it's the solution of the "population growth" ODE: dS/dt = a*S*(1-S/S(∞)). NB: It might be better to use the "error growth ODE" of Lorenz/Dalcher/Kalnay, but this has a significantly more complicated closed-form solution, and reduces to the above ODE when there's no model error (ODE source term). The "normalized" sigmoid, S1, is symmetric around 0, and S1(-∞)=0 and S1(∞)=1. The sigmoid S(k) = S1(a*(k-kb) + b) is fitted (see doc_snippets/sigmoid.jpg) with - a corresponding to a given corr. length L. - b to match values of S(kb) and Sb """ sigmoid = lambda k: 1/(1+exp(-k)) # normalized sigmoid inv_sig = lambda s: log(s/(1-s)) # its inverse a = 1/L b = inv_sig(Sb) def S(k): return sigmoid(b + a*(k-kb)) return S
# -*- coding: utf-8 -*- """ Created on Thu Sep 1 11:50:13 2016 @author: mads #Make crops of images and annotations History: 2017-05-23: Added support for keeping both original and cropped 2017-05-24: Fixed an error causing multiple threads to access same image when writing """ import os import csv import codecs from PIL import Image import numpy as np from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=30) exportExecutor = ThreadPoolExecutor(max_workers=30) futures = [] import time def createIfNotExist(directory): if not os.path.exists(directory): os.makedirs(directory) def flipAndRotateImageAndAnnotations(image,annotations,interval): #interval is number between 0 and 7 if interval<4: image = image.transpose(Image.TRANSPOSE) for i in range(len(annotations)): annotations[i][4:8]=[annotations[i][ii] for ii in [5,4,7,6]] for i in range(np.mod(interval,4)): annotations = rotateCoordinate90degrees(annotations,imagesize=image.size) image = image.transpose(Image.ROTATE_90) return image, annotations def rotateCoordinate90degrees(annotations,imagesize): annotationsold=np.copy(annotations).tolist() for ix,annotation in enumerate(annotations): annotations[ix][5]=str(int(imagesize[0])-int(annotationsold[ix][4])) annotations[ix][4]=annotationsold[ix][5] annotations[ix][7]=str(int(imagesize[0])-int(annotationsold[ix][6])) annotations[ix][6]=annotationsold[ix][7] return annotations def getAnnotationsInBbox(annotationList, ystart,xstart,(cropsizeX,cropsizeY)): #Run through all annotations and convert them AnnotationStringList=[] for annotation in annotationList: label=annotation[0] xmin=int(float(annotation[4]))-xstart ymin=int(float(annotation[5]))-ystart xmax=int(float(annotation[6]))-xstart ymax=int(float(annotation[7]))-ystart replacePlantBycar=False if replacePlantBycar: if label.lower()=='plant': label='Car' #Get truncated area #Number of pixels of annotation that is in the image nPixelsInX=sum([1 for x in range(xmin,xmax) if 0<=x<=cropsizeX]) nPixelsInY=sum([1 for x in range(ymin,ymax) if 0<=x<=cropsizeY]) pixelsOfAnnotationInImage = nPixelsInX*nPixelsInY #size of boundingbox annotationarea = 1.0*(xmax-xmin)*(ymax-ymin) annotationOutOfImage = annotationarea - pixelsOfAnnotationInImage trunkation = annotationOutOfImage / annotationarea #truncate crop xmin=max(0,xmin) ymin=max(0,ymin) xmax=min(cropsizeX,xmax) ymax=min(cropsizeY,ymax) #Get the size of the annotations after cropping annotationarea = 1.0*(xmax-xmin)*(ymax-ymin) # object size should be between 50×50 and 400×400 px in the input images #only accept annotations where at least 20% is visible (1.0-0.2 = 0.8) okAnnotations = trunkation<0.8 #Only accept objects larger than 50 pixels on the widthest point # okAnnotations = okAnnotations and 50<(xmax-xmin) and 50<(ymax-ymin) #Only accept objects smaller than 400px on the widthest point # okAnnotations = okAnnotations and (xmax-xmin)<400 and (ymax-ymin)<400 if okAnnotations: #only accept annotations where at least 80% is visible (1.0-0.8 = 0.2) Object=annotation[:] #Create string to save Object[0]=label Object[1]=str(trunkation) Object[4]=str(xmin) Object[5]=str(ymin) #ændret til xmin ymin xmax ymax format Object[6]=str(xmax) Object[7]=str(ymax) AnnotationStringList.append(Object[:]) return AnnotationStringList def exportImageAndAnnotation(imcrop,AnnotationStringList, writeName='', flipAndRotate=False): images = [] AnnotationStringListRot=[] if flipAndRotate: intervals=[1,3,4,6] # number from 0 to 7 for interval in intervals: imrot,anno = flipAndRotateImageAndAnnotations(imcrop.copy(),np.copy(AnnotationStringList).tolist(),interval=interval) images.append(imrot) AnnotationStringListRot.append(np.copy(anno).tolist()) else: images.append(imcrop) AnnotationStringListRot=[AnnotationStringList] #Export the annotation createIfNotExist(os.path.join(annotationOutputPath,trainval)) createIfNotExist(os.path.join(imageOutputPath,trainval)) iii=0 for imcrop, AnnotationStringList in zip(images,AnnotationStringListRot): while os.path.exists(os.path.join(annotationOutputPath,trainval,writeName+str(iii)+'.txt')): iii+=1 #MAXANNOTATIONS=-1 MAXANNOTATIONS=50 AnnotationStringList=AnnotationStringList[:MAXANNOTATIONS] annotationsavename = os.path.join(annotationOutputPath,trainval,writeName+str(iii)+'.txt') imagesavename = os.path.join(imageOutputPath,trainval,writeName + str(iii)+image_extension) with open(annotationsavename, 'w') as f: f.writelines([' '.join(an)+'\n' for an in AnnotationStringList]) imcrop.save(imagesavename) assert os.path.exists(imagesavename) and os.path.exists(annotationsavename) #Copy exifdata cmd1="exiftool -overwrite_original -TagsFromFile " + '"' + imagefile + '"' + ' '+ '"' + imagesavename + '"' a = executor.submit(os.system, cmd1) futures.append(a) ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### ############################################################################### imagedir='/media/mads/Eksternt drev/GetThumbnailsFromServer/KittiAnnotationsOneDir/images' annotationPath='/media/mads/Eksternt drev/GetThumbnailsFromServer/KittiAnnotationsOneDir/labelsOneLabel' imageOutputPath='/media/mads/Eksternt drev/GetThumbnailsFromServer/KittiAnnotationsOneDir/ImagesCrop' annotationOutputPath='/media/mads/Eksternt drev/GetThumbnailsFromServer/KittiAnnotationsOneDir/LabelsCrop' #imagedir='/media/slow-storage/DataFolder/MadsDyrmann/Database/GetThumbnailsFromServerForDetection/KittiAnnotationsOneDir/images' #annotationPath='/media/slow-storage/DataFolder/MadsDyrmann/Database/GetThumbnailsFromServerForDetection/KittiAnnotationsOneDir/labelsOneLabel' # #imageOutputPath='/media/slow-storage/DataFolder/MadsDyrmann/Database/GetThumbnailsFromServerForDetection/KittiAnnotationsOneDir/ImagesCrop' #annotationOutputPath='/media/slow-storage/DataFolder/MadsDyrmann/Database/GetThumbnailsFromServerForDetection/KittiAnnotationsOneDir/LabelsCrop' cropsize={} #Kitti size #cropsize['width']=1224 #cropsize['height']=370 cropsize['width']=1224 cropsize['height']=1024 #Probabilities for val/train/test (Nb: Digits does not support both test and val for object detection -> set test to 0.0) Trainprob=0.9 #Probability of ending in train TestProb=0.0 #val prob is the remainer futures=[] datestr=time.strftime("%Y-%m-%d") imageOutputPath=os.path.join(imageOutputPath,'imagesCropped'+'_'+datestr+'_'+str(cropsize['height'])+'x'+str(cropsize['width'])) annotationOutputPath=os.path.join(annotationOutputPath,'labelsDontCareCropped'+'_'+datestr+'_'+str(cropsize['height'])+'x'+str(cropsize['width'])) imagefiles = [] for root, dirnames, filenames in os.walk(imagedir): for filename in filenames: if filename.lower().endswith(('.png','.jpg','.jpeg','.tif','.tiff','.gif')): imagefiles.append(os.path.join(root, filename)) imagefiles.sort() #imagefiles=imagefiles[:5] iii=0 for i in range(len(imagefiles)): print('image '+str(i)+' of ' + str(len(imagefiles))+', '+imagefiles[i]) imagefile=imagefiles[i] #get image name _,filename=os.path.split(imagefile) filename, image_extension = os.path.splitext(filename) image_extension=image_extension.lower() im = Image.open(imagefile) #Pad image if it is too small padw=max(cropsize['width']-im.size[0],0) padh=max(cropsize['height']-im.size[1],0) if padw>0 or padh>0: im=Image.fromarray(np.pad(im,((0,padh),(0,padw),(0,0)),'constant')) possibleStartHeight=im.height-cropsize['height'] possibleStartWidth=im.width-cropsize['width'] #ncrops=5 ncrops=int(np.ceil(1.0*(im.size[0]*im.size[1])/(cropsize['width']*cropsize['height']))) rowStart=np.random.randint(0,possibleStartHeight+1,ncrops) colStart=np.random.randint(0,possibleStartWidth+1,ncrops) #Load the annotation speciesDictionary=[] with codecs.open(annotationPath+'/'+filename+'.txt','r') as csvfile: reader = csv.reader(csvfile,delimiter=' ',skipinitialspace=True) annotationList=[row for row in reader] #Use image for train, validation or test p=np.random.rand() if p<Trainprob: trainval='train' elif p>Trainprob and p<Trainprob+TestProb: trainval='test' else: trainval='val' #Run through all the crops for ystart,xstart in zip(rowStart,colStart): AnnotationStringList = getAnnotationsInBbox(annotationList, ystart,xstart,(cropsize['width'],cropsize['height'])) if len(AnnotationStringList)>0: #Create cropped image imcrop = im.crop((xstart, ystart, xstart+cropsize['width'], ystart+cropsize['height'])) imname=im.filename.split('/')[-1].split('.')[-2] #exportExecutor.submit(exportImageAndAnnotation,imcrop,AnnotationStringList, writeName=imname+'_'+str(ystart)+'_'+str(xstart),flipAndRotate=True) exportImageAndAnnotation(imcrop,AnnotationStringList, writeName=imname+'_'+str(ystart)+'_'+str(xstart)+'_',flipAndRotate=True) #Export whole image, scaled imcrop = im.resize((cropsize['width'],cropsize['height'])) scalefactor = (1.0*cropsize['width']/im.size[0],1.0*cropsize['height']/im.size[1]) AnnotationStringList = np.copy(annotationList).tolist() for i in range(len(AnnotationStringList)): AnnotationStringList[i][4] = str(int(int(AnnotationStringList[i][4])*scalefactor[0])) AnnotationStringList[i][5] = str(int(int(AnnotationStringList[i][5])*scalefactor[1])) AnnotationStringList[i][6] = str(int(int(AnnotationStringList[i][6])*scalefactor[0])) AnnotationStringList[i][7] = str(int(int(AnnotationStringList[i][7])*scalefactor[1])) #exportExecutor.submit(exportImageAndAnnotation,imcrop,AnnotationStringList, writeName=imname,flipAndRotate=True) exportImageAndAnnotation(imcrop,AnnotationStringList,flipAndRotate=True) while exportExecutor._work_queue.full(): #Avoid filling the ram, by not reading more images into memory than what fits in the work queue pass executor.shutdown(wait=True) exportExecutor.shutdown(wait=True) #import matplotlib.pyplot as plt #import seaborn as sns #sns.set(style="darkgrid") # ## Load the long-form example gammas dataset #gammas = sns.load_dataset("gammas") # ## Plot the response with standard error #plt.imshow(x) #sns.tsplot(data=gammas, time="timepoint", unit="subject", condition="ROI", value="BOLD signal") # # #plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') #plt.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off') #plt.legend().set_visible(False) #plt.show()
from omega_pygame.core.pygame_api import pygame def load_image(img_path): return pygame.image.load(img_path) def save_image(surface, img_path): pygame.image.save(surface, img_path) __all__ = ["load_image", "save_image"]
"""Tests for the entity blueprint""" from json import dumps import requests from tentd.documents.entity import Follower from tentd.tests import EntityTentdTestCase from tentd.tests.mocking import MockFunction, MockResponse, patch class FollowerTests(EntityTentdTestCase): """Tests relating to followers.""" name = "localuser" @classmethod def beforeClass(self): """Set up details of followers.""" # Urls used for the follower self.identity = 'http://follower.example.com' self.profile = 'http://follower.example.com/tentd/profile' self.notification = 'http://follower.example.com/tentd/notification' # Urls used to update the follower self.new_identity = 'http://changed.follower.example.com' self.new_profile = 'http://follower.example.com/new/profile' # Mocks for the server responses self.head = patch('requests.head', new_callable=MockFunction) self.head.start() profile_response = MockResponse( headers={'Link': '<{}>; rel="https://tent.io/rels/profile"'\ .format(self.profile)}) new_profile_response = MockResponse( headers={'Link': '<{}>; rel="https://tent.io/rels/profile"'\ .format(self.new_profile)}) requests.head[self.identity] = profile_response requests.head[self.new_identity] = new_profile_response self.get = patch('requests.get', new_callable=MockFunction) self.get.start() requests.get[self.notification] = MockResponse() requests.get[self.profile] = MockResponse( json={ "https://tent.io/types/info/core/v0.1.0": { "entity": self.identity, "servers": ["http://follower.example.com/tentd"], "licences": [], "tent_version": "0.2", }}) requests.get[self.new_profile] = MockResponse( json={ "https://tent.io/types/info/core/v0.1.0": { "entity": self.new_identity, "servers": ["http://follower.example.com/tentd"], "licences": [], "tent_version": "0.2", }}) @classmethod def afterClass(self): """Clean up after testing.""" self.head.stop() self.get.stop() def before(self): """Assert that the mocks are working correctly""" self.assertIsInstance(requests.head, MockFunction) self.assertIsInstance(requests.get, MockFunction) def test_entity_follow(self): """Test that you can start following an entity.""" response = self.client.post( '/localuser/followers', data=dumps({ 'entity': self.identity, 'licences': [], 'types': 'all', 'notification_path': 'notification' })) # Ensure the request was made sucessfully. self.assertStatus(response, 200) # Ensure the follower was created in the DB. Follower.objects.get(id=response.json()['id']) requests.get(self.notification) requests.get.assert_called(self.notification) def test_entity_follow_error(self): """Test that trying to follow an invalid entity will fail.""" response = self.client.post( '/{}/followers'.format(self.name), data='<invalid>') self.assertJSONError(response) requests.get.assert_not_called(self.notification) def test_entity_follow_delete(self): """Test that an entity can stop being followed.""" # Add a follower to delete follower = Follower( entity=self.entity, identity="http://tent.example.com/test", notification_path="notification").save() # Delete it. response = self.client.delete( '/{}/followers/{}'.format(self.name, follower.id)) self.assertEquals(200, response.status_code) def test_entity_follow_delete_non_existant(self): """Test that trying to stop following a non-existent user fails.""" response = self.client.delete('/{}/followers/0'.format(self.name)) self.assertEquals(400, response.status_code) def test_entity_follow_update(self): """Test that the following relationship can be edited correctly.""" # Add a follower to update follower = Follower( entity=self.entity, identity='http://follower.example.com', notification_path='notification').save() response = self.client.put( '/{}/followers/{}'.format(self.name, follower.id), data=dumps({'entity': self.new_identity})) # Ensure the request was made sucessfully. self.assertIsNotNone(response) self.assertStatus(response, 200) # Ensure the update happened sucessfully in the JSON. self.assertEquals(str(follower.id), response.json()['id']) self.assertEquals(self.new_identity, response.json()['identity']) # Ensure the DB was updated updated_follower = Follower.objects.get(id=follower.id) self.assertEquals(self.new_identity, updated_follower.identity)
#!/usr/bin/env python # -*- coding: UTF-8 -*- # coding=utf-8 """ @author: Li Tian @contact: litian_cup@163.com @software: pycharm @file: Caltools.py @time: 2020/1/15 9:32 @desc: 小朋友计算小程序 【version 1.0】 20200115 实现基本功能 1. 输入数字a,计算a以内的加减法 """ import random class Caltool: def __init__(self): # 随机影子 self.random_state = None random.seed(self.random_state) # 多少以内的加减法 self.number_limit = 20 # 生成多少个算术 self.count = 5 # 运算符包含 self.operator = ['+', '-'] # 统计正确率 self.sum = 0 # 序号统计 self.xuhao = 0 # 最后结果 self.strings = '' # 计算式统计,防止重复 self.lists = [] def reset(self): self.xuhao = 0 self.strings = '' self.sum = 0 self.lists = [] def check(self): if self.count == self.xuhao: return True else: return False def cal(self): # 开始 while self.xuhao < self.count: x = random.randint(1, self.number_limit) y = random.randint(1, self.number_limit) ope = random.choice(self.operator) # 判断 if ope == '+': result = x + y string = str(self.xuhao + 1) + '. ' + str(x) + ope + str(y) elif ope == '-': if x < y: temp = x x = y y = temp result = x - y string = str(self.xuhao + 1) + '. ' + str(x) + ope + str(y) else: print('报错了,看看啥问题!') info = string + '=?' print(info) # 获取输入 rr = input() try: int_rr = int(rr) except: print('只许输入数字哦,小朋友!') continue if int_rr == result: print('(√)恭喜你答对啦!') self.sum += 1 flag = True else: print('(×)答错了哦!') flag = False self.strings += info + '\t\t你的答案:' + rr + '\t\t正确答案:' + str(result) + '\t\t' + ('√' if flag else '×') + '\n' # 序号+1 self.xuhao += 1 print('*' * 30) print('小朋友你的得分是:', int((self.sum / self.count) * 100), '分') print('*' * 30) print(self.strings) def next_ti(self): x = random.randint(1, self.number_limit) y = random.randint(1, self.number_limit) ope = random.choice(self.operator) # 初始化 ti = None result = None string = None # 判断 if ope == '+': result = x + y ti = str(x) + ope + str(y) + '=?' string = str(self.xuhao + 1) + '. ' + str(x) + ope + str(y) + '=?' elif ope == '-': if x < y: temp = x x = y y = temp result = x - y ti = str(x) + ope + str(y) + '=?' string = str(self.xuhao + 1) + '. ' + str(x) + ope + str(y) + '=?' else: pass # 检查是否超纲 if result > self.number_limit: return self.next_ti() else: # 检查是否重复 if ti not in self.lists: self.lists.append(ti) return ti, result, string else: return self.next_ti() if __name__ == '__main__': tt = Caltool() tt.cal()
""" get user's id by m.ixigua.com """ # coding: utf-8 import requests import json import re import sqlite3 from database import SqlXigua, AllUser from config import XConfig, logging from utilities import record_data import time from multiprocessing import Pool from datetime import datetime from user import User # region 存储用户信息 class RequestPrepare: def __init__(self): self.db = AllUser() self.params = { 'tag': 'video_new', 'ac': 'wap', 'count': '20', 'format': 'json_raw', 'as': 'A135CAC5F8B2CC3', 'cp': '5A58220C8CD32E1', 'max_behot_time': '1515727802' } self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'm.ixigua.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Mobile Safari/537.36', } self.cookies = { 'csrftoken': 'f07abcdea7036c89aa516b67c44cbf0b', # 一年 'tt_webid': '6510022945200047630', # 10年 '_ga': 'GA1.2.1807487632.1515732834', # 两年 '_gid': 'GA1.2.2105862598.1515732834', # 一天 '_ba': 'BA0.2-20171227-51225-0QOfevbdMYurWcR3FEl' # 两年 } self.base_url = 'http://m.ixigua.com/list/' self.categorys = ['subv_voice', 'subv_funny', 'subv_society', 'subv_comedy', 'subv_life', 'subv_movie', 'subv_entertainment', 'subv_cute', 'subv_game', 'subv_boutique', 'subv_broaden_view', 'video_new'] rp = RequestPrepare() def get_now_min_behot_time(): return int(time.time()) def extract_user_id(source_open_url): """ extract the user id from given user's id :param source_open_url: "sslocal://profile?refer=video&uid=6115075278" example :return: """ if source_open_url[10:17] != 'profile': return None try: res = re.search("\d+$", source_open_url).group(0) return res.strip() except (AttributeError, KeyError): return None def run_pool(category): rp.params['tag'] = category user_ids = [] try: r = requests.get(rp.base_url, params=rp.params, headers=rp.headers, timeout=XConfig.TIMEOUT, cookies=rp.cookies) data = json.loads(r.text.encode('utf-8'), encoding='ascii') for item in data['data']: user_id = extract_user_id(item['source_open_url']) if user_id is None: continue user_ids.append(user_id) except requests.Timeout: logging.error('timeout occur when requesting user ids') except json.JSONDecodeError: logging.error('error occur when decoding requests.text to json. r={}/category={}'.format(r, category)) except requests.HTTPError: logging.error('http error occur when requesting user ids') except requests.ConnectionError: logging.error('connection error occur when requesting user ids') return list(set(user_ids)) def run(times): now_time_stamp = get_now_min_behot_time() all_count = 0 for i in range(times): max_behot_time = int(now_time_stamp - (604800 / 2 - (604800 / times) * i)) rp.params['max_behot_time'] = max_behot_time with Pool(12) as p: user_ids_s = p.map(run_pool, rp.categorys) count = 0 for user_ids in user_ids_s: for user_id in user_ids: try: u = User(user_id) rp.db.insert(u, is_commit=False) count += 1 except sqlite3.IntegrityError: logging.info('[{}] {} has appear in database!'.format(datetime.now(), user_id)) rp.db.conn.commit() all_count += count print("{}th => {} / {}".format(i + 1, count, all_count)) # endregion 存储用户信息
import logging from flask import Flask, jsonify, request ############ INIT ########### app = Flask(__name__) logging.basicConfig(filename='prl2016.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class Tube: def __init__(self, _id): self.loaded = False self.id = _id def __str__(self): return str(self.loaded) + str(self.id) def serialize(self): return { 'id': self.id, 'loaded': self.loaded, } class LaunchingSystem: def __init__(self): self.armed = False self.tubes = [] for i in range(20): self.tubes.append(Tube(i)) def __str__(self): return str(self.armed) def serialize(self): return { 'armed': self.armed, 'tubes': [t.serialize() for t in self.tubes], } prl = LaunchingSystem() ############# REST ############# @app.route('/') def index(): logging.info('INDEX') return "PRL2016" @app.route('/launch/arm', methods=['POST']) def arm(): logging.info('ARM') prl.armed = True return "System armed", 200 @app.route('/launch/disarm', methods=['POST']) def disarm(): logging.info('DISARM') prl.armed = False return "System disarmed", 200 @app.route('/launch/status', methods=['GET']) def status(): return jsonify(prl.serialize()), 200 @app.route('/launch/fire', methods=['POST']) def fire(): if not request.json: return "No JSON received.", 400 elif not prl.armed: return "System is not armed!", 403 else: for r in request.json["tubeIds"]: print(str(r) + " launched.") return "Given rockets launched", 200 @app.route('/launch/fire/all', methods=['POST']) def fire_all(): if not prl.armed: return "System is not armed!", 403 else: print("All lauched.") return "All rockets launched!", 200 @app.route('/test', methods=['GET']) def _relay_test(): print("Relay test.") ########### APP ############# if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=8000)
-*- coding: utf-8 -*- """ Created on Tue Feb 3 23:52:23 2015 @author: erostate type can be "train", "validation" can skip records on keep only some records if needed will skip/keep last day on train/validation command line format is: $pypy csv_to_vwoneNamespacePerFeature.py filetoread filetowrite train $pypy csv_to_vwoneNamespacePerFeature.py filetoread filetowrite validation """ import sys from datetime import datetime encoding = 'UTF-8' data_type = sys.argv[3] feature_list = ['C1','banner_pos','site_id','site_domain','site_category','app_id','app_domain','app_category','device_id','device_ip','device_model','device_type','device_conn_type','C14','C15','C16','C17','C18','C19','C20','C21'] #records to skip/keep linesToSkip={} keepOnlyLines={} if data_type=='train': linesToSkip['date'] = '20141030' elif data_type=='validation': keepOnlyLines['date'] = '20141030' #get file path from command line arguments fileinpath = sys.argv[1] fileoutpath=sys.argv[2] print('Converting file %s to VW format, output to file %s'%(fileinpath,fileoutpath)) for feature,value in linesToSkip.items(): print('Skipping lines where %s=%s'%(feature,value)) for feature,value in keepOnlyLines.items(): print('Keeping only lines where %s=%s'%(feature,value)) filein = open(fileinpath, 'r') # Open file for to transform (csv) fileout = open(fileoutpath, 'wb') # Open file to write (txt) start = datetime.now() #get headers, remove end of line headers = filein.readline() headers = headers[:-2].split(',') #define namespaces #namespaces contains as key the namespace letters, and as values the feature names namespaces = {} namespaces['h'] = ['hour'] namespaces['w'] = ['weekday'] #namespaces['c'] = ['C1','C14','C15','C16','C17','C18','C19','C20','C21'] #namespaces['b'] = ['banner_pos'] #namespaces['s'] = ['site_id','site_domain','site_category'] #namespaces['a'] = ['app_id','app_domain','app_category'] #namespaces['d'] = ['device_id','device_ip','device_model','device_type','device_conn_type'] #get some letters for namespaces namespacesKeys = map(chr,range(ord('a'),ord('z')+1)) namespacesKeys.remove('h') #already used this letter namespacesKeys.remove('w') #already used this letter for i in xrange(len(feature_list)): namespaces[namespacesKeys[i]] = [feature_list[i]] print('Namespace \t Feature') for namespace,feature in namespaces.items(): print('%s \t %s'%(namespace,feature)) countRecords = 0 keptRecords = 0 skippedRecords = 0 # Start reading the file for line in filein: countRecords += 1 #read line line = line[:-2].split(',') # Parse line lined = dict(zip(headers, line)) #format date daten = lined['hour'] hour = daten[6:8] year = int('20'+daten[0:2]) month = int(daten[2:4]) day = int(daten[4:6]) #date = datetime(year,month,day) #weekday = str(date.strftime('%A')) weekday = day%7 #faster lined['hour'] = hour lined['weekday'] = weekday lined['date'] = '%s%s%s'%(year,month,day) if lined.has_key('click'): label = 2 * int(lined['click']) - 1 else: label = 1 #check if we should skip this line skip = False for feature, value in linesToSkip.items(): if lined[feature]==value: skip = True break if not(skip): for feature,value in keepOnlyLines.items(): if lined[feature]!=value: skip = True break if skip: skippedRecords += 1 continue keptRecords += 1 #creating entry entry = str(label) + ' |' #adding features values = [' '.join(str(lined[feature]) for feature in features) for features in namespaces.values()] nameFeat = zip(namespaces.keys(),values) entry += '|'.join('%s %s' % t for t in nameFeat) #print entry fileout.write(entry + '\n') print("Task completed in %ss, processed %d lines, kept %d lines, skipped %d lines"% (datetime.now() - start, countRecords, keptRecords, skippedRecords ))
# http://bazel.io/ # vim: set ft=python sts=2 sw=2 et: UNKNOWN_SRCS = [ "aes/aes_cbc.c", "aes/aes_core.c", "bf/bf_enc.c", "bn/bn_asm.c", "camellia/camellia.c", "camellia/cmll_cbc.c", "camellia/cmll_misc.c", "des/des_enc.c", "des/fcrypt_b.c", "rc4/rc4_enc.c", "rc4/rc4_skey.c", "whrlpool/wp_block.c", ] UNKNOWN_OPTS = [ "-DOPENSSL_NO_ASM", ] I386_SRCS = [ "bf/bf_enc.c", "des/fcrypt_b.c", "whrlpool/wp_block.c", ] I386_OPTS = [ "-DOPENSSL_CPUID_OBJ", "-DOPENSSL_IA32_SSE2", "-DOPENSSL_BN_ASM_PART_WORDS", "-DOPENSSL_BN_ASM_MONT", "-DOPENSSL_BN_ASM_GF2m", "-DAES_ASM", "-DVPAES_ASM", "-DGHASH_ASM", "-DMD5_ASM", "-DRMD160_ASM", "-DSHA1_ASM", "-DSHA256_ASM", "-DSHA512_ASM", "-DWHIRLPOOL_ASM", ] AMD64_SRCS = [ "bf/bf_enc.c", "bn/asm/x86_64-gcc.c", "camellia/cmll_misc.c", "des/des_enc.c", "des/fcrypt_b.c", ] AMD64_OPTS = [ "-DOPENSSL_CPUID_OBJ", "-DOPENSSL_IA32_SSE2", "-DOPENSSL_BN_ASM_MONT", "-DOPENSSL_BN_ASM_MONT5", "-DOPENSSL_BN_ASM_GF2m", "-DAES_ASM", "-DBSAES_ASM", "-DVPAES_ASM", "-DGHASH_ASM", "-DMD5_ASM", "-DRC4_MD5_ASM", "-DRSA_ASM", "-DSHA1_ASM", "-DSHA256_ASM", "-DSHA512_ASM", "-DWHIRLPOOL_ASM", ] DONOTWANT_SRCS = ["bf/bf_cbc.c"] GENERIC_SRCS = glob( ["**/*.c", "**/*.h"], exclude=UNKNOWN_SRCS + I386_SRCS + AMD64_SRCS + DONOTWANT_SRCS, ) GENERIC_COPTS = [ "-Ilibressl/include", "-Ilibressl/crypto", "-Ilibressl/crypto/asn1", "-Ilibressl/crypto/evp", "-Ilibressl/crypto/modes", "-DHAVE_GETAUXVAL", "-DHAVE_VA_COPY", "-DLIBRESSL_INTERNAL", ] cc_library( name = "crypto", hdrs = ["//libressl/include:libcrypto"], srcs = select({ "//libressl:asm-i386-elf": GENERIC_SRCS + I386_SRCS + glob(["**/*-elf-x86.S"]), "//libressl:asm-i386-macosx": GENERIC_SRCS + I386_SRCS + glob(["**/*-macosx-x86.S"]), "//libressl:asm-amd64-elf": GENERIC_SRCS + AMD64_SRCS + glob(["**/*-elf-x86_64.S"]), "//libressl:asm-amd64-macosx": GENERIC_SRCS + AMD64_SRCS + glob(["**/*-macosx-x86_64.S"]), "//conditions:default": GENERIC_SRCS + UNKNOWN_SRCS, }), copts = select({ "//libressl:asm-i386-elf": GENERIC_COPTS + I386_OPTS, "//libressl:asm-i386-macosx": GENERIC_COPTS + I386_OPTS, "//libressl:asm-amd64-elf": GENERIC_COPTS + AMD64_OPTS, "//libressl:asm-amd64-macosx": GENERIC_COPTS + AMD64_OPTS, "//conditions:default": GENERIC_COPTS + UNKNOWN_OPTS, }), deps = [":headers"], visibility = ["//visibility:public"], ) cc_library( name = "headers", hdrs = [ "//libressl/include:compat", "//libressl/include:libcrypto", ], includes = ["libressl/include"], visibility = ["//visibility:public"], ) cc_library( name = "internal_asn1", hdrs = ["asn1/asn1_locl.h"], visibility = ["//libressl/tests:__pkg__"], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import hashlib import random def md5_encryption(text): ''' 加密处理字符串 :param text:加密字符串 :return: ''' md5 = hashlib.md5() # 实例化MD5加密对象 md5.update(text.encode('utf-8')) # 字符串必须转码 data = md5.hexdigest() # 获取加密数据 return data def pwd_md5_encryption(text,key): ''' 密码加密处理 :param text: 加密字符串 :param key:验证码 :return: ''' return md5_encryption(md5_encryption(text)+key) def json_convert_to_key_value(json_object, split_str='&'): """ json对象转换为字符串键值对 :param json_object: json 对象 :param split_str: 字符串切片字符 """ key_value_str = '' for key, value in json_object.items(): key_value_str += key + '=' + str(value) + split_str return key_value_str.rstrip(split_str) def get_new_sort_data(item,temp): ''' 获取可迭代对象值进行排列 :return: ''' new_data = [] data = [] for i in temp: if i and i != ',': new_data.append(i) while True: data.append(random.choice(new_data)) if len(data) == item: break return data if __name__ == '__main__': #print(pwd_md5_encryption('aaaa2222','9999')) y = ['大', '小', '单', '双'] t = (1,2,3,4,5) d = {"age":18,"name":'laowang',"height":175} print(get_new_sort_data(2,d))
from wknn.models.units.sigmoid_neuron import Sigmoid_Neuron from itertools import tee def test_train_sigmoid_function(): from matplotlib import pyplot as plt from wknn.utilities.output_fuctions import sigmoid_funct p = Sigmoid_Neuron() p.W = [5.5, 2.50, -2.01] X = { 1: ([1.0, 1.5, -0.5], 0), 2: ([1.0, 0.5, -0.5], 0), 3: ([1.0, -0.5, -0.5], 0), 4: ([1.0, 0.0, 1.0], 0), 5: ([1.0, 1.5, 1.5], 1), 6: ([1.0, 2.5, 2.0], 1), 7: ([1.0, 1.5, 2.5], 1), 8: ([1.0, 2.0, -1.0], 1) } y = {} Xs = [] Ys = [] for ii in range(100): for k, v in X.items(): p.X = v[0] p.ytrain = v[1] y[k] = { "error": p.error, "goal": v[1] } Xs.append(range(-10, 10, 1)) Ys.append( list(map(lambda x: (-p.W[0]-p.W[1]*x)/p.W[2], range(-10, 10, 1)))) # for i in range(len(Xs)-1): # plt.plot(Xs[i],Ys[i],"-",lw=0.5) plt.xlim(-4, 4) plt.ylim(-4, 4) plt.grid() p.train() pass m = map(lambda y: y[0][1:], filter(lambda x: x[1] == 0, X.values())) p = map(lambda y: y[0][1:], filter(lambda x: x[1] == 1, X.values())) m1, m2 = tee(m) p1, p2 = tee(p) import os if os.environ['DEBUG_WKNN'] == 'TRUE': plt.plot(Xs[-1], Ys[-1], "--", lw=2.0) plt.plot(Xs[0], Ys[0], "-", lw=2.0) plt.plot([x for x, y in m1], [y for x, y in m2], "x") plt.plot([x for x, y in p1], [y for x, y in p2], "s") plt.show() def check_error(x): if x['goal']-x['error'] >= 0: return True else: return False assert all(map(lambda x: check_error(x), y.values())) pass
#!/usr/bin/env python """ Generates the output for the /prism directory inside /_site. Converts any .shtml files encountered to plain .html files. Usage: python _plugins/prism.py """ import os import os.path import shutil import re import sys def main(args): for (dirpath, dirnames, filenames) in os.walk('prism'): out_dirpath = os.path.join('_site', dirpath) if not os.path.exists(out_dirpath): os.mkdir(out_dirpath) for filename in filenames: filepath = os.path.join(dirpath, filename) out_filepath = os.path.join(out_dirpath, filename) if filename.endswith('.shtml'): out_filepath = os.path.splitext(out_filepath)[0] + '.html' convert_shtml_to_html(filepath, out_filepath) else: shutil.copyfile(filepath, out_filepath) def convert_shtml_to_html(in_filepath, out_filepath): regex = re.compile(br'<!--#include virtual="([^"]*)" -->') file_contents = lambda filename: open(filename, 'rb').read() resolve_path = lambda filepath: \ filepath if not filepath.startswith('/') else ('.' + filepath) match_ssi = lambda match: ssi(file_contents(resolve_path(match.group(1)))) ssi = lambda txt: regex.sub(match_ssi, txt) # HACK: Assumes the specified filepath ends with 'index.shtml'. # Does not actually check. def chop_index_shtml_suffix(filepath): return os.path.dirname(filepath) + '/' with open(out_filepath, 'wb') as out_file: out_file.write(ssi(file_contents(in_filepath)).replace( '<!--#echo var="SCRIPT_NAME" -->', '/' + chop_index_shtml_suffix(in_filepath))) if __name__ == '__main__': main(sys.argv[1:])
#!/usr/bin/env python """Translate quaternion orientation into heading angle. Subscribes: imu/data (Imu) Publishes: heading (Float32) """ from __future__ import division import rospy import tf import math from std_msgs.msg import Float32 from sensor_msgs.msg import Imu class heading_processing(object): def __init__(self): rospy.init_node('Heading_service') self.heading = 0 self.heading_pub = rospy.Publisher('heading', Float32, queue_size=10) #self.pitch_pub = rospy.Publisher('pitch', Float32, queue_size=10) #self.roll_pub = rospy.Publisher('roll', Float32, queue_size=10) rospy.Subscriber('imu/data', Imu, self.heading_publisher) def heading_publisher(self, msg): imu = msg.orientation self.heading = (math.degrees( tf.transformations.euler_from_quaternion( (imu.x, imu.y,imu.z, imu.w))[2]) - 90) % 360 #self.pitch = math.degrees( # tf.transformations.euler_from_quaternion( # (imu.x, imu.y,imu.z, imu.w))[1]) #self.roll = math.degrees( # tf.transformations.euler_from_quaternion( # (imu.x, imu.y,imu.z, imu.w))[0]) def run(self): r = rospy.Rate(20) while not rospy.is_shutdown(): self.heading_pub.publish(self.heading) r.sleep() if __name__ == '__main__': process = heading_processing() try: process.run() except rospy.ROSInterruptException: pass
# Copyright 2018 Google LLC # # 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. # [START gae_python37_render_template] import datetime from flask import Flask, render_template from flask import request import json import random from sklearn.linear_model import LinearRegression from sklearn import linear_model # linear & logistic regression from sklearn import preprocessing # polynomial features for polynomial regression from sklearn import model_selection import numpy as np from google.cloud import storage import firebase_admin from firebase_admin import credentials app = Flask(__name__) @app.route('/query') def query(): building = request.args.get('building') #f = open("data.txt","r") #content = json.loads(f.read()) if building=='a': content=random.randrange(1,200) else: content=random.randrange(150,400) return str(content) @app.route('/store') def store(): f = open("data.txt", "r") return f.read() @app.route('/predict') def predict(): value=[466,1675,3242,4514,4595,4289,3511] fin=[value] for i in range(14): new_val=[] for i in range(len(value)): new_val.append(random.randrange(int(value[i]*0.8),int(value[i]*1.2))) fin.append(new_val) val=[5,6,7,8,9,10,11] X=np.array(val*15) Y=np.array(fin) lm = linear_model.LinearRegression() poly = preprocessing.PolynomialFeatures(2) poly_X = poly.fit_transform(np.ndarray.flatten(X).reshape(-1,1)) lm.fit(poly_X,np.ndarray.flatten(Y).reshape(-1,1)) #reg=LinearRegression().fit(np.ndarray.flatten(X).reshape(-1,1),np.ndarray.flatten(Y).reshape(-1,1)) stime = request.args.get('stime') etime = request.args.get('etime') min=5515 val=stime for i in range(int(stime),int(etime)+1): #update=reg.predict(np.array(i).reshape(-1,1)) update=lm.predict(poly.fit_transform(np.reshape([i], (1,-1)))) print(update) if update<min: val=i min=update return str(val) @app.route('/') def root(): # For the sake of example, use static information to inflate the template. # This will be replaced with real information in later steps. dummy_times = [datetime.datetime(2018, 1, 1, 10, 0, 0), datetime.datetime(2018, 1, 2, 10, 30, 0), datetime.datetime(2018, 1, 3, 11, 0, 0), ] return render_template('index.html', times=dummy_times) if __name__ == '__main__': # This is used when running locally only. When deploying to Google App # Engine, a webserver process such as Gunicorn will serve the app. This # can be configured by adding an `entrypoint` to app.yaml. # Flask's development server will automatically serve static files in # the "static" directory. See: # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed, # App Engine itself will serve those files as configured in app.yaml. app.run(host='127.0.0.1', port=8080, debug=True) # [START gae_python37_render_template]
class Vehical: def __init__(self,number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels, = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity def drive(self): print("The vehicle is in driving mode now.") vios = Vehical ('4', 'petrol', 5, 180) print(vios.number_of_wheels) print(vios.type_of_tank) print(vios.seating_capacity) print(vios.maximum_velocity) class ElectircCar(Vehical): def __init__(self,number_of_wheels, seating_capacity, maximum_velocity): Vehical.__init__(self, number_of_wheels, ElectircCar, seating_capacity, maximum_velocity) blueSG = ElectircCar ('4', 5, 150) blueSG.drive()
from django.conf.urls import url from . import views app_name = 'areas' urlpatterns = [ url(r'^$', views.areacomum, name='areacomum'), url(r'^apostar/$', views.apostar, name='apostar'), url(r'^areapessoal/$', views.areapessoal, name='areapessoal'), url(r'^carregarsaldo$', views.carregarsaldo, name='carregarsaldo'), url(r'^editardados/$', views.editardados, name='editardados'), url(r'^mostardados$', views.mostrardados, name='mostrardados'), ]
# import pandas as pd # import re # re.match def ab(a, b): """a plus b""" return a + b c = ab(1, 2) print(c) import pandas as pd pd.read_pickle
class Queue(object): def __init__(self, alist): self.alist = alist def enqueue(self, param): self.alist.append(param) return param def dequeue(self): aparam = self.alist[0] self.alist = self.alist[1:] return aparam alist = [5, 4, 8, 7] queue = Queue(alist) print(queue.enqueue(10)) print(queue.alist) print(queue.dequeue()) print(queue.alist)
# Copyright (c) 2009-2010 Simon van Heeringen <s.vanheeringen@ncmls.ru.nl> # # This module is free software. You can redistribute it and/or modify it under # the terms of the MIT License, see the file COPYING included with this # distribution. """ Module to calculate ROC and MNCP scores """ # External imports from scipy.stats import stats from numpy import array def fraction_fdr(fg_vals, bg_vals, fdr=5): from scipy.stats import scoreatpercentile fg_vals = array(fg_vals) s = scoreatpercentile(bg_vals, 100 - fdr) return len(fg_vals[fg_vals >= s]) / float(len(fg_vals)) def score_at_fdr(fg_vals, bg_vals, fdr=5): from scipy.stats import scoreatpercentile bg_vals = array(bg_vals) return scoreatpercentile(bg_vals, 100 - fdr) def enr_at_fdr(fg_vals, bg_vals, fdr=5): from scipy.stats import scoreatpercentile pos = array(fg_vals) neg = array(bg_vals) s = scoreatpercentile(neg, 100 - fdr) return len(pos[pos >= s]) / float(len(neg[neg >= s])) * len(neg) / float(len(pos)) def max_enrichment(fg_vals, bg_vals, minbg=2): from numpy import hstack,argsort,ones,zeros scores = hstack((fg_vals, bg_vals)) idx = argsort(scores) x = hstack((ones(len(fg_vals)), zeros(len(bg_vals)))) xsort = x[idx] m = 0 s = 0 for i in range(len(scores), 0, -1): bgcount = float(len(xsort[i:][xsort[i:] == 0])) if bgcount >= minbg: enr = len(xsort[i:][xsort[i:] == 1]) / bgcount if enr > m: m = enr s = scores[idx[i]] return m, s def MNCP(fg_vals, bg_vals): from scipy.stats import stats from numpy import mean,array,hstack #from pylab import * fg_len = len(fg_vals) total_len = len(fg_vals) + len(bg_vals) if type(fg_vals) != type(array([])): fg_vals = array(fg_vals) if type(bg_vals) != type(array([])): bg_vals = array(bg_vals) fg_rank = stats.rankdata(fg_vals) total_rank = stats.rankdata(hstack((fg_vals, bg_vals))) slopes = [] for i in range(len(fg_vals)): slope = ((fg_len - fg_rank[i] + 1) / fg_len ) / ((total_len - total_rank[i] + 1)/ total_len) slopes.append(slope) return mean(slopes) def ROC_AUC(fg_vals, bg_vals): from scipy.stats import stats from numpy import mean,array,hstack #if len(fg_vals) != len(bg_vals): # return None if len(fg_vals) == 0 or len(bg_vals) == 0: return None fg_len = len(fg_vals) total_len = len(fg_vals) + len(bg_vals) if type(fg_vals) != type(array([])): fg_vals = array(fg_vals) if type(bg_vals) != type(array([])): bg_vals = array(bg_vals) fg_rank = stats.rankdata(fg_vals) total_rank = stats.rankdata(hstack((fg_vals, bg_vals))) return (sum(total_rank[:fg_len]) - sum(fg_rank))/ (fg_len * (total_len - fg_len)) def ROC_AUC_xlim(x_bla, y_bla, xlim=None): x = x_bla[:] y = y_bla[:] x.sort() y.sort() u = {} for i in x + y: u[i] = 1 vals = u.keys() vals.sort() len_x = float(len(x)) len_y = float(len(y)) new_x = [] new_y = [] x_p = 0 y_p = 0 for val in vals[::-1]: while len(x) > 0 and x[-1] >= val: x.pop() x_p += 1 while len(y) > 0 and y[-1] >= val: y.pop() y_p += 1 new_y.append((len_x - x_p) / len_x) new_x.append((len_y - y_p) / len_y) #print new_x #print new_y new_x = 1 - array(new_x) new_y = 1 - array(new_y) #plot(new_x, new_y) #show() x = new_x y = new_y if len(x) != len(y): raise "Unequal!" if not xlim: xlim = 1.0 auc = 0.0 bla = zip(stats.rankdata(x), range(len(x))) def sortfunc(x,y): res = x[0] - y[0] if res < 0: return -1 elif res > 0: return 1 elif res == 0: return y[1] - x[1] bla.sort(sortfunc) prev_x = x[bla[0][1]] prev_y = y[bla[0][1]] index = 1 while index < len(bla) and x[bla[index][1]] <= xlim: (rank, i) = bla[index] auc += y[i] * (x[i] - prev_x) - ((x[i] - prev_x) * (y[i] - prev_y) / 2.0) prev_x = x[i] prev_y = y[i] index += 1 if index < len(bla): (rank, i) = bla[index] auc += prev_y * (xlim - prev_x) + ((y[i] - prev_y)/(x[i] - prev_x) * (xlim -prev_x) * (xlim - prev_x)/2) return auc def ROC_values(x_bla, y_bla): if len(x_bla) == 0 or len(y_bla) == 0: return [],[] x = x_bla[:] y = y_bla[:] x.sort() y.sort() u = {} for i in x + y: u[i] = 1 vals = u.keys() vals.sort() len_x = float(len(x)) len_y = float(len(y)) new_x = [] new_y = [] x_p = 0 y_p = 0 for val in vals[::-1]: while len(x) > 0 and x[-1] >= val: x.pop() x_p += 1 while len(y) > 0 and y[-1] >= val: y.pop() y_p += 1 new_y.append((len_x - x_p) / len_x) new_x.append((len_y - y_p) / len_y) #print new_x #print new_y new_x = 1 - array(new_x) new_y = 1 - array(new_y) return (new_x, new_y) def max_fmeasure(x,y): from numpy import array, logical_and, nanmax x = array(x[:]) y = array(y[:]) p = y / (y + x) filt = logical_and((p * y) > 0, (p + y) > 0) p = p[filt] y = y[filt] f = (2 * p * y) / (p + y) if len(f) > 0: return nanmax(f), nanmax(y[f == nanmax(f)]) else: return None,None
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import datetime import csv import regex import click import csv_utf8 import HTMLParser from pprint import pprint import requests from lxml import html import logging logger = logging.getLogger() # Setting up logger logger.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) class Ciencia_hoje(): def __init__(self): # tabela.append([edicao, titulo + ': ' + subtitulo, publicacao, link, tags]) # tabela2.append([edicao, titulo, subtitulo, publicacao, link, tags]) self.publicacao = u'Ciencia Hoje' self.url_base = u'http://cienciahoje.uol.com.br' self.tabela = [] self.tabela2 = [] def extract_noticia(self, link): r = requests.get(link[1]) if not r.text: logger.info(u'erro ao iniciar extração das noticias, saindo...') return False pagina = r.text tree = html.fromstring(pagina) try: titulo = tree.xpath(u'//span[@id="parent-fieldname-title"]/text()')[0].strip() subtitulo = tree.xpath(u'//span[@id="parent-fieldname-description"]/text()')[0].strip() data_publicacao = tree.xpath(u'//*[(self::span or self::p) and contains(text(), "Publicado em")]/text()')[0].strip() data_publicacao = regex.sub(ur'Publicado em ', u'', data_publicacao) categoria = u', '.join(tree.xpath(u'//div[@id="category"]/span/a/text()')) except: return True print data_publicacao + u'\n' + titulo + u'\n' + subtitulo + u'\n' + link[1] + u'\n' + categoria + u'\n' self.tabela.append([data_publicacao, titulo + u': ' + subtitulo, self.publicacao + u' - ' + link[0], link[1], categoria]) self.tabela2.append([data_publicacao, titulo, subtitulo, self.publicacao + u' - ' + link[0], link[1], categoria]) return True def extract_noticias_pages(self, url_l): links = [] tipo = url_l[0] url = url_l[1] while url != None: r = requests.get(url) if not r.text: logger.info(u'erro ao iniciar extração das noticias, saindo...') return [] pagina = r.text tree = html.fromstring(pagina) noticias_c = tree.xpath(u'//h2[@class="tileHeadline"]/a') for noticia_c in noticias_c: links.append([tipo, noticia_c.get(u'href').strip()]) try: url = tree.xpath(u'//span[@class="next"]/a')[0].get(u'href') except: url = None return links def extract_noticias_pagination(self): urls = [ [u'sobreCultura', u'http://cienciahoje.uol.com.br/revista-ch/sobrecultura/sobreCultura/folder_summary_view?b_start:int=0'], [u'Resenhas', u'http://cienciahoje.uol.com.br/resenhas/resenhas/folder_summary_view?b_start:int=0'], [u'Notícias', u'http://cienciahoje.uol.com.br/noticias/noticias/folder_summary_view?b_start:int=0']] urls = urls + self.extract_especiais() links = [] for url in urls: links = links + self.extract_noticias_pages(url) return links def extract_especiais(self): url = 'http://cienciahoje.uol.com.br/categorias?listasubject=Especiais&b_start:int=0' links = [] while url != None: r = requests.get(url) if not r.text: logger.info(u'erro ao iniciar extração das noticias, saindo...') return [] pagina = r.text tree = html.fromstring(pagina) especiais_c = tree.xpath(u'//dt[@class="contenttype-folder" or @class="contenttype-topic"]/a[2]') for especial_c in especiais_c: links.append([u'Especiais', especial_c.get(u'href')]) try: url = tree.xpath(u'//span[@class="next"]/a')[0].get(u'href') except: url = None return links def extract_noticias(self): links = self.extract_noticias_pagination() for link in links: self.extract_noticia(link) def extract_edicao(self, url_l): # faltando pegar primeira notícia if url_l[2].find(u'2014') != -1 or url_l[2].find(u'2015') != -1: return True ano = int(regex.search(ur'([0-9]{4})', url_l[2]).group(1)) # pra testar mais rapidamente #if ano > 2008: # return True r = requests.get(url_l[1]) if not r.text: logger.info(u'erro ao iniciar extração das noticias, saindo...') return False pagina = r.text tree = html.fromstring(pagina) materias_c = tree.xpath(u'//table[@class="invisible"]//td') for materia_c in materias_c: try: if len(materia_c.xpath(u'.//p[@class="callout"]')) > 0 or len(materia_c.xpath(u'.//p')) == 0: continue edicao = url_l[2] try: titulo = materia_c.xpath(u'./p//strong/text()')[0] except: titulo = materia_c.xpath(u'.//strong/text()')[0] subtitulo = materia_c.xpath(u'./p')[-1].text_content() try: link = materia_c.xpath(u'./p//a')[-1].get(u'href') if link.startswith(u'/'): link = self.url_base + link except: link = url_l[1] categoria = u'' print edicao + u'\n' + titulo + u'\n' + subtitulo + u'\n' + link + u'\n' + categoria + u'\n' self.tabela.append([edicao, titulo + u': ' + subtitulo, self.publicacao + u' - ' + url_l[0], link, categoria]) self.tabela2.append([edicao, titulo, subtitulo, self.publicacao + u' - ' + url_l[0], link, categoria]) except: logger.exception(u'erro ao pegar chamada de dentro da edicao') # antes da edição 255b if len(materias_c) == 0: materias_c = tree.xpath(u'//div[@class="migratedContent"]//p[@class="titch2"]/..') for materia_c in materias_c: edicao = url_l[2] titulo = ''.join(materia_c.xpath(u'.//strong/text()')).strip() subtitulo = materia_c.text_content().strip() subtitulo = regex.sub(ur'[\n\r\s]{1,}', u' ', subtitulo.replace(titulo, u'')).strip() titulo = regex.sub(ur'[\n\r\s]{1,}', u' ', titulo).strip() try: link = materia_c.xpath(u'.//a')[-1].get(u'href') if link.startswith(u'/'): link = self.url_base + link except: link = url_l[1] categoria = u'' print edicao + u'\n' + titulo + u'\n' + subtitulo + u'\n' + link + u'\n' + categoria + u'\n' self.tabela.append([edicao, titulo + u': ' + subtitulo, self.publicacao + u' - ' + url_l[0], link, categoria]) self.tabela2.append([edicao, titulo, subtitulo, self.publicacao + u' - ' + url_l[0], link, categoria]) def extract_edicoes_pages(self): url = 'http://cienciahoje.uol.com.br/revista-ch' links = [] while url != None: r = requests.get(url) if not r.text: logger.info(u'erro ao iniciar extração das noticias, saindo...') return [] pagina = r.text tree = html.fromstring(pagina) edicoes_c = tree.xpath(u'//p[@class="edicao"]') for edicao_c in edicoes_c: links.append([u'Revista', edicao_c.xpath(u'./a')[0].get(u'href'), edicao_c.xpath(u'./a/text()')[0] + u' - ' + edicao_c.xpath(u'./span/text()')[0]]) try: url = tree.xpath(u'//span[@class="next"]/a')[0].get(u'href') except: url = None return links def extract_edicoes(self): links = self.extract_edicoes_pages() for link in links: self.extract_edicao(link) def extrai_salva(self): self.extract_noticias() self.extract_edicoes() with open('%s-%s.csv' % (self.publicacao, time.strftime(u'%Y-%m-%d')), 'wb') as myfile: wr = csv_utf8.UnicodeWriter(myfile, quoting=csv.QUOTE_ALL) wr.writerows(self.tabela) with open('%s-%s-ajustado.csv' % (self.publicacao, time.strftime(u'%Y-%m-%d')), 'wb') as myfile: wr = csv_utf8.UnicodeWriter(myfile, quoting=csv.QUOTE_ALL) wr.writerows(self.tabela2) @click.group() def cli(): pass @click.option('--inicio', help='Pagina de inicio', default=1) @cli.command() def extrai(inicio): ciencia_hoje = Ciencia_hoje() ciencia_hoje.extrai_salva() if __name__ == '__main__': cli()
#!/usr/bin/env python # -*- coding: UTF-8 -*- import numpy as np def mean_squared_error(y, label): # y/label can be multi dimensional array row_count = y.shape[0] ret = 0.5 * np.sum((y - label) ** 2) / row_count return ret # sum((y-t)**2) / row_count def softmax(array): tmp = array.copy() # array will be modified later, so make a copy tmp -= tmp.max(axis=1, keepdims=True) # max of array in axis_1(batch direction) exp = np.exp(tmp) # exp(matrix) return exp / np.sum(exp, axis=1, keepdims=True) # exp / sum of each row def cross_entropy(y, label): # slice prediction result by label # TODO y/label can be multi dimensional array ??? # y.shape: (batch_size, feature_size) # label.shape: (batch_size, 1) assert y.shape[0] == label.shape[0] # assert label.ndim == 2 delta = 1e-6 # in case of log(0) row_count = y.shape[0] index_row = range(row_count) index_column = label.flatten() # Error Fixed: label must be a one dimensional array picked = y[index_row, index_column] + delta # choose prediction corresponding to label return np.sum(-np.log(picked)) / row_count # sum(-t * ln(y)) / row_count
import boto3 dynamodb = boto3.client('dynamodb') def lambda_handler(event, context): params = event['queryStringParameters'] if 'email' not in params or 'dropbox_oauth_token' not in params: response = create_response(400, 'Missing info for registration.') return response email = params['email'] dropbox_oauth_token = params['dropbox_oauth_token'] try: dynamodb.put_item( TableName='Registrations', Item={ 'email': {'S': email}, 'dropbox_oauth_token': {'S': dropbox_oauth_token}, } ) except: response = create_response(500, 'Error in registering user.') return response response = create_response(200, 'Email {} registered!'.format(email)) return response def create_response(statusCode, body): response = { 'headers': { 'Access-Control-Allow-Origin': '*' } } response['statusCode'] = statusCode response['body'] = body print('Response: %s' % (response)) return response
class Node: def __init__(self,data): self.data = data; self.next = None; class Linked: def printList(self): temp = self.first while temp: print temp.data temp = temp.next def __init__(self): self.first = None if __name__ == '__main__': list = Linked() list.first = Node(10) second = Node(20) third = Node(30) list.first.next = second second.next = third print list.first.data print list.first.next.data print list.first.next.next.data list.printList()
""" Task database support module. A database which react with the following JSON format data. JSON Format: { 'id': int, task id; 'desc': str, task description; 'data': dict, any data of specific task, e.g. sid, .sh file; 'time_stamp': dict with: 'create': str, time of task creation 'start': str, time of start running 'end': str, time of complete 'state': str, task state 'is_root': bool, is task is a root task, i.e. which is automitically submitted by run deamon 'worker': str, worker of action, one of 'NoAction', 'Multithreading', 'Slurm' 'type': str, type of task, ['Regular', 'Command', 'Script'] 'workdir': str, path of workdir, 'dependency': list, dependency ids; } """ from .api import *
from datetime import datetime, timedelta from decimal import Decimal, InvalidOperation from io import StringIO import re from django.core.exceptions import ValidationError from django.core.management import call_command from django.db import connection, transaction from authentication import models as a_models from migrator import models as m_models from wip import models as w_models from wip.utils import duration_to_decimal_hrs def format_url(url): if url and not url.startswith('http'): return 'http://%s' % url return url def load(): """ from migrator.migrate import load; load() """ with transaction.atomic(): print('add users') legacy_users = m_models.Staff.objects.using('legacy').all() for obj in legacy_users: new_user = a_models.User.objects.create( id=obj.staffid, email='%s@example.com' % obj.staffid, first_name=obj.staffname, is_active=obj.currentyn ) if obj.currentyn: new_user.set_password('password') new_user.save() reset_sequences() print('add clients') new_clients = [] legacy_clients = m_models.Client.objects.using('legacy').all() for obj in legacy_clients: new_client = w_models.Client( id=obj.clientid, name=obj.clientname, colour='#FFFFFF', phone_number=obj.clientphone or '', email_address=obj.clientemail or '', website=format_url(obj.clientwebsite) or '', notes=obj.clientnotes or '', address='' ) new_client.full_clean() new_clients.append(new_client) w_models.Client.objects.bulk_create(new_clients) reset_sequences() print('add job types') job_types = m_models.Jobtype.objects.using('legacy').all().order_by('jobtypetitle') for obj in job_types: new_job_type = w_models.JobType( id=obj.jobtypeid, title=obj.jobtypetitle ) new_job_type.full_clean() new_job_type.save() reset_sequences() w_models.JobType.objects.create( title='Maintenance' ) print('add job statuses') job_statuses = m_models.Jobstatus.objects.using('legacy').all().order_by('jobstatustitle') order = 0 for obj in job_statuses: new_job_status = w_models.JobStatus( id=obj.jobstatusid, title=obj.jobstatustitle, allow_new_timesheet_entries=False if obj.jobstatustitle == 'Completed' else True, order=order ) new_job_status.full_clean() new_job_status.save() order += 1 reset_sequences() print('add jobs') new_jobs = [] maintenance_id = w_models.JobType.objects.get(title='Maintenance').pk jobs = m_models.Job.objects.using('legacy').all() for obj in jobs: new_job = w_models.Job( id=obj.jobnumber, title=obj.jobtitle, description=obj.jobdesc, client_id=obj.clientid_id, type_id=maintenance_id if obj.ismaintenance else obj.jobtype, estimated_hours=obj.estimatedtime, colour=obj.jobcolour, status_id=obj.jobstatusid_id, billed_to=obj.billedto.date() if obj.billedto and obj.billedto.year != 5000 else None ) new_job.full_clean() new_jobs.append(new_job) w_models.Job.objects.bulk_create(new_jobs) reset_sequences() print('add job related guff') manager = w_models.Relationship.objects.create(title='Project Manager') lead = w_models.Relationship.objects.create(title='Lead Developer') jobs = m_models.Job.objects.using('legacy').all() new_relationships = [] new_notes = [] for obj in jobs: if obj.managerid: new_relationship = w_models.JobRelationship( job_id=obj.jobnumber, user_id=obj.managerid, relationship=manager ) new_relationship.full_clean() new_relationships.append(new_relationship) if obj.jobleadid: new_relationship = w_models.JobRelationship( job_id=obj.jobnumber, user_id=obj.jobleadid, relationship=lead ) new_relationship.full_clean() new_relationships.append(new_relationship) if obj.jobnotes: new_note = w_models.JobNote( job_id=obj.jobnumber, user_id=obj.managerid or 12, # studio note=obj.jobnotes ) new_note.full_clean() new_notes.append(new_note) w_models.JobRelationship.objects.bulk_create(new_relationships) w_models.JobNote.objects.bulk_create(new_notes) print('add task statuses') task_statuses = m_models.Taskstatus.objects.using('legacy').all().order_by('display_order', 'description') order = 0 for obj in task_statuses: new_task_status = w_models.TaskStatus( id=obj.id, title=obj.description, order=order ) new_task_status.full_clean() new_task_status.save() order += 1 reset_sequences() print('add tasks') new_tasks = [] tasks = m_models.Task.objects.using('legacy').order_by( 'jobid_id', 'taskstatusid_id', 'display_order', 'title' ).select_related( 'jobid' ) job = None status = None order = 0 for obj in tasks: # increment the order or reset on a status change if obj.taskstatusid_id != status or obj.jobid_id != job: order = 16384 else: order += 16384 # set the status and job status = obj.taskstatusid_id job = obj.jobid_id new_task = w_models.Task( id=obj.taskid, title=obj.title, description=obj.description, job_id=obj.jobid.jobnumber, status_id=obj.taskstatusid_id, created_at=obj.created_at, target_date=obj.tasktargetdate.date() if obj.tasktargetdate else None, closed=obj.is_closed, not_chargeable=False, order=order ) new_task.full_clean() # turn off auto_now_add new_task._meta.get_field('created_at').auto_now_add = False new_tasks.append(new_task) w_models.Task.objects.bulk_create(new_tasks) reset_sequences() print('add task related guff') tasks = m_models.Task.objects.using('legacy').all() new_assignees = [] new_notes = [] for obj in tasks: # clean the hrs up as the source is not even a number if obj.tasktargethours: hrs = None try: hrs = Decimal(obj.tasktargethours.strip()).quantize(Decimal('0.01')) except (ValidationError, InvalidOperation): print('%s error converting tasktargethours as decimal "%s"' % (obj, obj.tasktargethours)) if hrs: new_assignee = w_models.TaskAssignee( task_id=obj.taskid, user_id=obj.staffid or 1, allocated_hours=hrs ) new_assignee.full_clean() new_assignees.append(new_assignee) if obj.notes: new_note = w_models.TaskNote( task_id=obj.taskid, user_id=obj.staffid or 12, # studio note=obj.notes ) new_note.full_clean() new_notes.append(new_note) w_models.TaskAssignee.objects.bulk_create(new_assignees) w_models.TaskNote.objects.bulk_create(new_notes) reset_sequences() print('add time entries') legacy_entries = m_models.Entry.objects.using('legacy').filter(taskid__isnull=False).order_by('entryid') new_time_entries = [] for obj in legacy_entries: started_at = datetime.combine(obj.date, obj.started_at) ended_at = datetime.combine(obj.date, obj.ended_at) new_time_entry = w_models.TimeEntry( id=obj.entryid, task_id=obj.taskid_id, started_at=started_at, ended_at=max(ended_at, started_at + timedelta(minutes=1)), user_id=obj.staffid_id, comments=obj.comment ) new_time_entry.full_clean() new_time_entries.append(new_time_entry) w_models.TimeEntry.objects.bulk_create(new_time_entries) reset_sequences() def tidyup(): """ from migrator.migrate import tidyup; tidyup() """ print('set client colour to first job colour') for obj in w_models.Client.objects.all(): if obj.jobs.count() > 0: obj.colour = obj.jobs.first().colour obj.save() print('add job timings') new_timings = [] for job in w_models.Job.objects.all(): new_timing = w_models.JobTiming( job=job ) new_timings.append(new_timing) w_models.JobTiming.objects.bulk_create(new_timings) print('set job timing defaults') for timing in w_models.JobTiming.objects.with_calculated().all(): timing.allocated_hours = timing.qs_allocated_hours or Decimal('0.00') timing.time_spent_hours = timing.qs_time_spent_hours or Decimal('0.00') timing.save() print('add task timings') new_timings = [] for task in w_models.Task.objects.all(): new_timing = w_models.TaskTiming( task=task ) new_timings.append(new_timing) w_models.TaskTiming.objects.bulk_create(new_timings) print('set task timing defaults') for timing in w_models.TaskTiming.objects.with_calculated().all(): timing.allocated_hours = timing.qs_allocated_hours or Decimal('0.00') timing.time_spent_hours = duration_to_decimal_hrs(timing.qs_time_spent_hours) timing.save() print('closed date of tasks') tasks = w_models.Task.objects.filter(closed=True) for task in tasks: last_entry = task.time_entries.last() if last_entry: task.closed_date = last_entry.ended_at else: task.closed_date = task.created_at task.save() print('sign off timesheets') w_models.TimeEntry.objects.filter(started_at__date__lte='2018-11-25').update( signed_off=True, signed_off_date=datetime.today().date() ) def reset_sequences(): """ reset the sql sequences """ print('reset_sequences') app_names = ['authentication', 'wip'] for app_name in app_names: output = StringIO() call_command('sqlsequencereset', app_name, stdout=output) sql = output.getvalue() # Remove terminal color codes from sqlsequencereset output ansi_escape = re.compile(r'\x1b[^m]*m') sql = ansi_escape.sub('', sql) with connection.cursor() as cursor: cursor.execute(sql)
# Contains various functions which are used for tasks which does not fit to any other python file. import netTools as nt import ipaddress import netTools as net # tools for network connection from subprocess import check_output DISCOVERY_TIMEOUT_SEC = 1200 # secs within which all nodes should be reached ; if timeout, node terminated NODE_ROLE_MASTER = 'MASTER' # const - machine is identified as master NODE_ROLE_SLAVE = 'SLAVE' # const - machine is identified as a slave # Check whether program args entered by user are valid or not. Program expects two args - 0: name of prog, 1: count of started nodes. def check_args(args): if len(args) == 2: return True else: return False # Prints information about the node itself (hostname and ip addr). def print_info_node(): print('***Printing info about newly created node - START***', flush=True) node_hostname = nt.get_node_hostname() ips = check_output(['hostname', '--all-ip-addresses']) ip = ips.split()[1] node_ip = ip.decode('UTF-8') print('Node hostname: ', node_hostname, ', IP: ', node_ip, flush=True) print('***Printing info about newly created node - END***', flush=True) # Function determines starting role of the node. Node with highest IP will start as master, others as slave. This can change later on (some may disc etc)... # expect_node_count - expected count of nodes to be present in the network def determine_node_start_role(total_node_num): print('***Determining role of node (wait for all nodes to come up) - START***', flush=True) retrieved_network_nodes = net.retrieve_network_nodes(total_node_num, DISCOVERY_TIMEOUT_SEC) # scan network for other nodes if not retrieved_network_nodes: # no nodes found till time ran out print('Not all nodes are up within time, terminating master node...', flush=True) return else: # ok, nodes up within time, continue print('All nodes are up and ready!', flush=True) highest_ip = None # highest IP encountered in net list node_w_highest_ip = None # hostname of node with highest IP for netNode in retrieved_network_nodes: traversed_node_ip = ipaddress.IPv4Address(netNode.node_ip) if highest_ip is None or traversed_node_ip > highest_ip: # if no IP assigned or traversed IP higher highest_ip = traversed_node_ip node_w_highest_ip = netNode.node_hostname # get hostname of node with highest IP print('***Determining role of node (wait for all nodes to come up) - END***', flush=True) if net.get_node_hostname() == node_w_highest_ip: # machine with highest IP will become master, others are slaves print('Node is acting as master!', flush=True) return [NODE_ROLE_MASTER, retrieved_network_nodes] else: # machine is gonna be a slave print('Node is acting as slave!', flush=True) return [NODE_ROLE_SLAVE, retrieved_network_nodes]
def car(x): return x[0] def cdr(x): return x[1:] def cons(x, y): return [x] + y def acharLugar(x, lista1): if lista1 == []: return cons(x, lista1) elif x > car(lista1): return cons(car(lista1), acharLugar(x, cdr(lista1))) elif x <= car(lista1): return cons(x,lista1) def misturar(lis1, lis2): if lis2 == []: return lis1 if lis1 == []: return lis2 else: return misturar(acharLugar(car(lis2), lis1), cdr(lis2)) a = [1,3,5,7,9] b = [2,4,6,8] #misturar as listas em uma print(misturar(a, b))
from union_find import UnionFind # Friend Circles class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ n = len(M) uf = UnionFind(n) for i in range(n): for j in range(i + 1, n): if M[i][j] == 1: uf.union(i, j) return uf.num_groups
import urllib2 response = urllib2.urlopen("https://raw.github.com/BenOut/PythonLogFileReader/master/dilemmas_new_users.py") python_script_from_git = response.read() exec python_script_from_git raw_input("Press enter to close")
import discord from discord.ext import commands, tasks from discord.ext.commands import has_permissions, MissingPermissions import discord.abc import sys, traceback import bot_config import psutil import os import random import re import asyncio from quickstart import * spread = spread() lbIDFile = "leaderboardmessage.txt" class leaderboard(commands.Cog): def __init__(self, bot): self.bot = bot self.homeserver = bot_config.Home_Server self.leaderboardMsg = None self.channel = self.bot.get_channel(826526139756969984) self.updateLeaderboard.start() def createLeaderboard(self): sortSheet(spread, "Leaderboard", 2, "DESCENDING") ids = [] names = [] scores = [] ids, names, scores = get_sheet(spread, "Leaderboard") lb = "**Top Accountable Users:**\n" for i in range(len(scores)): lb += "**{}**: {}\t\t{}\n".format(i+1,names[i],scores[i]); #lb = "First: {}: {}\nSecond: {}: {}\nThird: {}: {}".format(names[0], scores[0], names[1], scores[1], names[2], scores[2]) return lb @tasks.loop(seconds=30) async def updateLeaderboard(self): mid = 0 msg = None #check file for leaderboard message with open(lbIDFile,"r") as f: try: mid = int(f.read()) msg = await self.channel.fetch_message(mid) except Exception as e: print("[leaderboard updateLeaderboard] failed to read file or fetch message (ERROR IS OK): {}".format(e)) #check if the message exists if(msg == None): #create new self.leaderboardMsg = await self.channel.send(self.createLeaderboard()) with open(lbIDFile,"w") as f: f.write(str(self.leaderboardMsg.id)) else: self.leaderboardMsg = msg await self.leaderboardMsg.edit(content=self.createLeaderboard()) #if(self.leaderboardMsg == None): # self.leaderboardMsg = await self.channel.send(self.createLeaderboard()) #else: # await self.leaderboardMsg.edit(content=self.createLeaderboard()) def setup(bot): bot.add_cog(leaderboard(bot))
#!/usr/bin/env python ''' Service Now ticket CLI ''' import argparse import os import json from ticketutil.servicenow import ServiceNowTicket # pylint: disable=import-error class ServiceNow(object): """SNOW object""" def __init__(self): """Set object params""" self.url = os.environ.get("snowurl", None) self.username = os.environ.get("snowuser", None) self.password = os.environ.get("snowpass", None) self.args = ServiceNow.parse_args() self.ticket = ServiceNowTicket(url=self.url, project='incident', auth=(self.username, self.password)) @staticmethod def parse_args(): """Parse CLI arguments""" parser = argparse.ArgumentParser( description='Create, update, query and close Service Now tickets.') subparsers = parser.add_subparsers(help='sub-command help') common_args = argparse.ArgumentParser(add_help=False) common_args.add_argument( '--assigned-to', '-a', metavar='USER', help='SNOW user to assign ticket to') common_args.add_argument( 'extra', metavar='KEY=VAL', nargs='*', help='Other SNOW key=value pairs (SNOW implementation-dependent)') parser_create = subparsers.add_parser('create', parents=[common_args], help='Create a new ticket') parser_create.add_argument( '--short-description', '-d', metavar='SHORT DESCRIPTION', help='Short ticket description') parser_create.add_argument('--description', '-D', metavar='LONG DESCRIPTION', help='Long ticket description') parser_create.add_argument('--category', '-C', metavar='CATEGORY', default='incident', help='Ticket category') parser_create.add_argument('--priority', '-p', metavar='PRIORITY', help='Ticket priority') parser_create.set_defaults(action='create') parser_update = subparsers.add_parser('update', parents=[common_args], help='Update an existing ticket') parser_update.set_defaults(action='update') parser_update.add_argument( 'ticketid', metavar='TICKETID', help='Existing ticket ID') parser_update.add_argument( '--status', '-s', choices=['New', 'In Progress', 'On Hold', 'Resolved', 'Closed', 'Canceled'], help='Ticket status') parser_update.add_argument('--comment', '-c', help='Ticket comment') parser_close = subparsers.add_parser('close', help='Close an existing ticket') parser_close.set_defaults(action='close') parser_close.add_argument('ticketid', metavar='TICKETID', help='Existing ticket ID') parser_get = subparsers.add_parser('get', help='Get ticket details') parser_get.set_defaults(action='get') parser_get.add_argument('ticketid', metavar='TICKETID', help='Existing ticket ID') return parser.parse_args() @property def extra_args(self): """Return extra SNOW CLI args as k:v dict""" extra_args = dict() for arg in self.args.extra: key, val = arg.split('=') extra_args[key] = val return extra_args def create(self, **kwargs): """Create service now ticket""" self.ticket.create(short_description=self.args.short_description, description=self.args.description, category=self.args.category, item='', **kwargs) _ticket = self.ticket.get_ticket_content() print _ticket.ticket_content['number'] def update(self, ticket_id, **kwargs): """Update service now ticket""" self.ticket.set_ticket_id(ticket_id) if self.args.comment: self.ticket.add_comment(self.args.comment) if self.args.status: self.ticket.change_status(self.args.status) if self.args.assigned_to: self.ticket.edit(assigned_to="self.args.assigned_to") if kwargs: self.ticket.edit(**kwargs) print "Updated %s" % ticket_id def close(self, ticket_id): """Close service now ticket""" _ticket = self.ticket.set_ticket_id(ticket_id) self.ticket.change_status('Closed') print "Closed %s" % _ticket.ticket_content['number'] def get(self, ticket_id): """Print service now ticket contents""" _ticket = self.ticket.get_ticket_content(ticket_id) print json.dumps(_ticket.ticket_content, indent=4, sort_keys=True) def main(): """ main() function :return: """ snow = ServiceNow() if snow.args.action is 'create': snow.create(**snow.extra_args) elif snow.args.action is 'update': snow.update(snow.args.ticketid, **snow.extra_args) elif snow.args.action is 'close': snow.close(snow.args.ticketid) elif snow.args.action is 'get': snow.get(snow.args.ticketid) snow.ticket.close_requests_session() if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Sun Jul 20 00:49:17 2014 @author: LeBronJames """ import MapReduce, sys mr = MapReduce.MapReduce() def mapper(record): key = record[1] value = record mr.emit_intermediate(key, value) def reducer(key, list_of_values): order_records = filter(lambda x : x[0] == 'order', list_of_values) item_records = filter(lambda x : x[0] == 'line_item', list_of_values) for order in order_records: for item in item_records: mr.emit(order + item) if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
''' Solves problem #27 on https://projecteuler.net Sergey Lisitsin. May 2019''' def sequence(a,b): n = 0 seq = 0 while seq == n: # print ((n*(n+a))+b) if isprime(n*(n+a)+b): seq +=1 n += 1 return(seq) def isprime(num): for x in range(2,(abs(num)//2)+1): if abs(num) % x == 0: return False return True a = [x for x in range(-999,1000)] b = [x for x in range(-1000,1001)] champseq = 0 champs = [0,0] for x in a: for y in b: if sequence(x,y) > champseq: champseq = sequence(x,y) champs[0] = x champs[1] = y print("{}".format(champs[0]*champs[1]))
class Prime(object): @classmethod def main(cls, args): print(cls.isPrime(50)) print(cls.isPrime(47)) @classmethod def isPrime(self, n): if( n > 1): answer = True else: answer = False i = 2 while(i*i <= n): if(n%i == 0): answer = False break i += 1 return answer if __name__ == '__main__': import sys Prime.main(sys.argv)
from django.shortcuts import render, redirect, render_to_response from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse, Http404, JsonResponse from django.db import transaction from forms import * from models import * from account.models import * import time import json from itertools import chain from drealtime import iShoutClient ishout_client = iShoutClient() from datetime import datetime from pytz import timezone from mimetypes import guess_type @login_required # @transaction.atomic def post_question(request): return render(request, 'discussion/discussion_board.html', {}) @login_required # @transaction.atomic def reply_question(request): return render(request, 'discussion/discussion_reply.html', context) @login_required # @transaction.atomic def delete_post(request): return render(request, 'discussion/discussion_board.html', {}) @login_required def discussion_home(request): posts = Post.objects.all().order_by('-post_time') post_replies = []; context={} i = len(posts) for post in posts: number_replies = len(Reply.objects.filter(reply_to = post).order_by('post_time')) post_replies.append({'post':post, 'number_replies' : number_replies, 'list_id' : i}) i -= 1 if Learner.objects.filter(user = request.user): learner = Learner.objects.get(user = request.user) flag= 0 if Teacher.objects.filter(user = request.user): teacher = Teacher.objects.get(user = request.user) flag = 1 context = {'username' : request.user.username, 'posts' : post_replies,'flag':flag} context['newmsgs'] = request.user.newmsg.all().order_by('-timestamp') context['msgcount'] = request.user.newmsg.all().count() if request.user.newmsg.filter(isReply=False): context['hasnewmsg'] = 'yes' else: context['hasnewmsg'] = 'no' return render(request, 'discussion/discussion_board.html', context) @login_required def discussion_reply(request, post_id): if not Post.objects.filter(id__exact = post_id): return HttpResponse("This post ID does not exist!") else: post = Post.objects.get(id__exact = post_id) learnerSet = Learner.objects.filter(user = post.author) if len(learnerSet) > 0: post_user = learnerSet[0] else: teacher = Teacher.objects.get(user = post.author) post_user = teacher replies = Reply.objects.filter(reply_to__id = post_id) max_reply_id = replies.aggregate(Max('id'))['id__max'] or 0 user_temp = Learner.objects.filter(user = request.user) is_learner = len(user_temp) if is_learner == 1: cur_user = user_temp[0] flag = 0 else: flag = 1 cur_user = Teacher.objects.get(user = request.user) # print 'hello' return render(request, 'discussion/discussion_reply.html', \ {'post': post, 'replies' : replies, 'post_user': post_user, 'max_reply_id' : max_reply_id,\ 'username' : request.user.username, 'cur_user' : cur_user,'flag':flag}) @login_required def get_posts(request): all_posts = Post.objects.all().order_by('-post_time') post_replies = [] i = len(all_posts) for post in all_posts: replies = Reply.objects.filter(reply_to__id = post.id).order_by('post_time') context_temp = {'post' : post, 'replies' : replies, 'list_id' : i, 'number_replies' : len(replies)} post_replies.append(context_temp) i -= 1 context = {'post_replies' : post_replies} return render(request, 'discussion/posts.json', context, content_type = 'application/json') @login_required # @transaction.atomic def post_post(request): form = PostFormForm(request.POST) if not form.is_valid(): print 'form not valid' return render(request, 'discussion/post.json', {}, content_type='application/json') new_post = Post(title = form.cleaned_data['title'],\ text = form.cleaned_data['text'], \ post_time = form.cleaned_data['post_time'],\ author = request.user) new_post.save() return render(request, 'discussion/post.json', \ {'post': new_post}, content_type='application/json') @login_required # @transaction.atomic def post_reply(request): usernameTemp = request.user.username userTemp = User.objects.get(username = usernameTemp) learnerSet = Learner.objects.filter(user = userTemp) if len(learnerSet) > 0: retUser = learnerSet[0] else: teacher = Teacher.objects.get(user = userTemp) retUser = teacher form = ReplyForm(request.POST) if not form.is_valid(): print 'form not valid!' return render(request, 'discussion/reply.json', {}, content_type='application/json') to_post = Post.objects.get(id=form.cleaned_data['post_id']) new_reply = Reply(text = form.cleaned_data['text'], \ post_time = form.cleaned_data['post_time'],\ reply_to = Post.objects.get(id = form.cleaned_data['post_id']),\ author = request.user) new_reply.save() return render(request, 'discussion/reply.json', {'reply': new_reply, 'user': retUser}, content_type='application/json') @login_required def get_postreply(request, post_id, max_reply_id): replies = Reply.objects.filter(reply_to__id = post_id).filter(id__gt = max_reply_id) return render(request, 'discussion/replies.json', {'replies' : replies}, content_type='application/json') @login_required def get_user_photo(request, user_id): learnerSet = Learner.objects.filter(user__id = user_id) if len(learnerSet) > 0: retUser = learnerSet[0] else: retUser = Teacher.objects.get(user__id = user_id) if not retUser.photo: raise Http404 content_type = guess_type(retUser.photo.name) return HttpResponse(retUser.photo, content_type = content_type) @login_required # @transaction.atomic def delete_post(request, post_id): postTemp = Post.objects.get(id = post_id) replies = Reply.objects.filter(reply_to__id = post_id) postTemp.delete() for reply in replies: reply.delete() return redirect(reverse('discussion_home')) @login_required # @transaction.atomic def delete_reply(request, reply_id): replySet = Reply.objects.filter(id = reply_id) if len(replySet) > 0: replyTemp = replySet[0] learnerSet = Learner.objects.filter(user = replyTemp.author) if len(learnerSet) > 0: retUser = learnerSet[0] else: retUser = Teacher.objects.get(user = replyTemp.author) post_id = replyTemp.reply_to.id replyTemp.delete() return render(request, 'discussion/empty.json', {'flag': 1}, content_type = 'application/json') else: return render(request, 'discussion/empty.json', {'flag' : 0}, content_type = 'application/json') @login_required def index(request): user = request.user if Learner.objects.filter(user__exact=user): flag = 0 else: flag = 1 RoomObj = ChatRoom.objects.all() if request.user.newmsg.filter(isReply=False): hasnewmsg = 'yes' else: hasnewmsg = 'no' return render(request, 'discussion/index.html', {'username': user.username, 'hasnewmsg':hasnewmsg,'RoomObj': RoomObj,'flag':flag, 'newmsgs':user.newmsg.all().order_by('-timestamp'), 'msgcount':user.newmsg.all().count()}) @login_required def video_home(request): user = request.user if Learner.objects.filter(user__exact=user): flag = 0 else: flag = 1 VedioObj = VideoRoom.objects.all() if request.user.newmsg.filter(isReply=False): hasnewmsg = 'yes' else: hasnewmsg = 'no' return render(request, 'discussion/video_home.html', {'username': user.username, 'hasnewmsg':hasnewmsg,'RoomObj': VedioObj,'flag':flag, 'newmsgs':user.newmsg.all().order_by('-timestamp'), 'msgcount':user.newmsg.all().count()}) @login_required def newVideoRoom(request): error = [] if not 'roomname' in request.POST or not request.POST['roomname']: error.append('Room name is required.') if error: return render(request, 'discussion/video_home.html', {'error':error}) name = request.POST['roomname'] new_room = VideoRoom(roomname=name+" "+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),owner=request.user.username) new_room.save() return redirect("/discussion/video") @login_required def deleteVideoRoom(request,rid): if len(VideoRoom.objects.filter(id = rid))>0: roomObj = VideoRoom.objects.get(id__exact= rid) roomObj.delete() return redirect("/discussion/video") @login_required def room(request, room_id): if not room_id.isdigit(): return HttpResponse('<h1>No room</h1>') if not ChatRoom.objects.filter(id=room_id): return HttpResponse('<h1>No room</h1>') user = request.user ishout_client.register_group( user.id, room_id ) if request.user.newmsg.filter(isReply=False): hasnewmsg = 'yes' else: hasnewmsg = 'no' roomObj = ChatRoom.objects.get(id=room_id) chatpoolObj = ChatPool.objects.filter(roomname=roomObj) msglist = [] for i in chatpoolObj: msglist.append(i) print i if Learner.objects.filter(user__exact=user): learner = Learner.objects.get(user__exact=user) learner.save() flag= 0 else: teacher = Teacher.objects.get(user__exact=user) teacher.save() flag= 1 roomObj = ChatRoom.objects.get(id=room_id) result = RoomAccount.objects.filter(username=user, roomname=roomObj) if not result: u = RoomAccount(username=user, roomname=roomObj) u.save() userlObj = RoomAccount.objects.filter(roomname=roomObj) userlist = [] for i in userlObj: userlist.append(i.username) return render(request,'discussion/room.html', {'user': user, 'roomObj': roomObj,'flag': flag, 'userlist': userlist,'msglist':msglist,'hasnewmsg':hasnewmsg, 'newmsgs' :user.newmsg.all().order_by('-timestamp'), 'cur_username':user.username,'msgcount':user.newmsg.all().count()}) @login_required def getmsg(request): roomid = request.GET.get('roomid') roomObj = ChatRoom.objects.get(id=roomid) chatpoolObj = ChatPool.objects.filter(roomname=roomObj) msglist = [] for i in chatpoolObj: msglist.append(i.msg) return HttpResponse(json.dumps(msglist)) @login_required def updatechat(request): roomid = request.GET.get('roomid') print roomid roomObj = ChatRoom.objects.get(id=roomid) chatpoolObj = ChatPool.objects.filter(roomname=roomObj) eastern = timezone('US/Eastern') fmt = '%b. %d, %Y, %I:%M %p.' msglist = [] for i in chatpoolObj: list = {} list['sender'] = i.sender loc_time = i.time.astimezone(eastern) list['time'] = loc_time.strftime(fmt) list['msg'] = i.msg msglist.append(list) return HttpResponse(json.dumps(msglist)) @login_required def putmsg(request): roomid, content = request.POST.get('roomid'), request.POST.get('content') roomObj = ChatRoom.objects.get(id=roomid) s = ChatPool(roomname=roomObj, msg=content) s.save() return HttpResponse("OK") @login_required def exituser(request): print "exituser" roomid, userid = request.POST.get('roomid'), request.POST.get('userid') roomObj = ChatRoom.objects.get(id=roomid) userObj = User.objects.get(id=userid) u = RoomAccount.objects.filter(username=userObj, roomname=roomObj) u.delete() ishout_client.unregister_group( userid, roomid ) return HttpResponse("OK") @login_required def onlineuser(request): roomid, userid = request.GET.get('roomid'), request.GET.get('userid') roomObj = ChatRoom.objects.get(id=roomid) userObj = User.objects.get(id=userid) u = RoomAccount.objects.filter(username=userObj, roomname=roomObj) if not u: u = RoomAccount(username=userObj, roomname=roomObj) u.save() userlObj = RoomAccount.objects.filter(roomname=roomObj) userlist = [] for i in userlObj: userlist.append(str(i.username)) return HttpResponse(json.dumps(userlist)) @login_required def newRoom(request): error = [] if not 'roomname' in request.POST or not request.POST['roomname']: error.append('Room name is required.') if error: return render(request, 'discussion/index.html', {'error':error}) name = request.POST['roomname'] new_room = ChatRoom(roomname=name+" "+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),owner=request.user.username) new_room.save() return redirect("/discussion/chat") @login_required def deleteRoom(request,rid): if len(ChatRoom.objects.filter(id = rid))>0: roomObj = ChatRoom.objects.get(id__exact= rid) ishout_client.broadcast_group( rid, 'deletechannel', data = {'roomname':roomObj.roomname} ) roomObj.delete() return redirect("/discussion/chat") @login_required def updateRoom(request): rooms = ChatRoom.objects.all() json = {} json['rooms'] = [] json['cur_username']=request.user.username for room in rooms: print room.roomname r = {'roomname': room.roomname, 'id': room.id, 'owner':room.owner} json['rooms'].append(r) return JsonResponse(json) def send_message(request, room_id): text=request.POST.get('text') uname=request.POST.get('username') if len(text) > 0: roomObj = ChatRoom.objects.get(id=room_id) s = ChatPool(roomname=roomObj, msg=text, sender=uname) s.save() print room_id ishout_client.broadcast_group( room_id, 'alerts', data = {'text':text,'username':uname} ) return HttpResponse("OK") @login_required def testVideoRoom(request,rid): if Learner.objects.filter(user__exact=request.user): flag = 0 else: flag = 1 return render(request, 'discussion/video_room.html', {'rid':rid,'username':request.user.username,'flag':flag})
str = input("Enter the string value ") result = '' first = '' last = '' if len(str) < 2: result = "Empty String" else: first = str[0:2] last = str[-2:] result = first+last print(result)
# -*- coding: utf-8 -*- from melange.exceptions import FragmentError import json import lxml.html import UserDict class MelangeFragment(object): """Single Melange Fragment """ def __init__(self, raw): self._manifest = None self.raw = raw self.html = lxml.html.fromstring(raw) self.manifest # initialize and minor validation @property def manifest(self): """reads manifest from fragment once and caches """ if self._manifest is None: for element in self.html.xpath('//*[@data-melange-manifest]'): # take first raw = element.attrib['data-melange-manifest'] self._manifest = json.loads(raw) break if self._manifest is None: raise FragmentError('No manifest found.') if 'name' not in self._manifest: raise FragmentError('Manifest must contain a "name".\n' + raw) return self._manifest @property def name(self): return self.manifest['name'] def __str__(self): return lxml.html.tostring(self.html) class FragmentRegistry(UserDict.IterableUserDict): """registry for MelangeFragments """ def register(self, raw): fragment = MelangeFragment(raw) self.data[fragment.name] = fragment def __add__(self, raw): self.register(raw) return self fragment_registry = FragmentRegistry()
import turtle import sys from time import sleep from easyTypeWriter import typeWriter import winsound #sound credit goes to harshnative on github wn = turtle.Screen() wn.setup(600,600) sky =('sky.gif') wn.bgpic(sky) # message = "Hello" obj = typeWriter.EasyInput() words = "Hello! Welcome to our typing game! :P" def clearScreen(): os.system("clear") for char in words: sleep(0.1) sys.stdout.write(char) sys.stdout.flush() winsound.PlaySound('keyhee.wav', winsound.SND_FILENAME) words = "Instructions: type as many words as accurately as you can before the timer runs out. Good luck and have fun!" def clearScreen(): os.system("clear") for char in words: sleep(0.1) sys.stdout.write(char) sys.stdout.flush() winsound.PlaySound('keyhee.wav', winsound.SND_FILENAME) sleep(1) clearScreen() wn.mainloop()
import random import math import matplotlib.pyplot as plt LEARNRATE = 0.05 def getRandom(): return random.random()*0.5 class Neuron: def __init__(self,id,numInput): self.id = id self.error = 0 self.output = 0 self.input = [] self.weights = [] #Initialization of the weights. self.threshold = getRandom() for i in range(numInput): self.weights.append(getRandom()) def getId(self): return self.id def setInput(self,inputs): self.input = inputs def getThreshold(self): return self.threshold def getWeights(self): w = self.weights w.append(self.threshold) return w def setWeights(self,weights): self.weights = weights[:-2] self.threshold = weights[-1] def updateWeights(self): self.threshold += LEARNRATE*self.error for i in range(len(self.input)): self.weights[i] += LEARNRATE*self.error*self.input[i] def getOutput(self): return self.output def calculateOutput(self): net = self.threshold for i in range(len(self.input)): net += self.weights[i] * self.input[i] output = 1 / (1 + math.exp(-net)) self.output = output return output def getError(self): return self.error def setError(self,error): self.error = error def calculateOuterError(self,target): self.error = self.output*(1-self.output)*(target-self.output) return self.error def calculateErrorSum(self,pos): return self.weights[pos] * self.error class NeuronLayer: def __init__(self,initId,numNeurons,numInput): self.neurons = [] for i in range(numNeurons): self.neurons.append(Neuron(i+initId,numInput)) def setInput(self,inputs): for neuron in self.neurons: neuron.setInput(inputs) def getWeights(self): weights = [] for neuron in self.neurons: weights.append(neuron.getWeights()) return weights def setWeights(self,weights): for i in range(len(self.neurons)): self.neurons[i].setWeights(weights[i]) def updateWeights(self): for neuron in self.neurons: neuron.updateWeights() def printWeights(self): for neuron in self.neurons: print "Neuron: %s - " %(neuron.getId()), print "Weights: %s" %(neuron.getThreshold()), for weight in neuron.weights: print "%s " %(weight), print def getOutput(self): outputs = [] for neuron in self.neurons: outputs.append(neuron.getOutput()) return outputs def calculateOutputs(self): outputs = [] for neuron in self.neurons: outputs.append(neuron.calculateOutput()) return outputs def calculateOuterErrors(self,target): errors = [] for i in range(len(self.neurons)): errors.append(self.neurons[i].calculateOuterError(target[i])) return errors class Network: def __init__(self,numInput,numHidden,numOuter,learnRate): self.numHidden = numHidden self.numOuter = numOuter global LEARNRATE LEARNRATE = learnRate self.hiddenLayer = NeuronLayer(0,numHidden,numInput) self.outerLayer = NeuronLayer(numHidden,numOuter,numHidden) def getWeights(self): weights = [] weights.append(self.hiddenLayer.getWeights()) weights.append(self.outerLayer.getWeights()) return (self.hiddenLayer.getWeights(),self.outerLayer.getWeights()) def setWeights(self,weights): hiddenWeights,outerWeights = weights self.hiddenLayer.setWeights(hiddenWeights) self.outerLayer.setWeights(outerWeights) def printWeights(self): print "\nHIDDEN LAYER WEIGHTS:" self.hiddenLayer.printWeights() print "\nOUTER LAYER WEIGHTS:" self.outerLayer.printWeights() def train(self,data): totalError = 0 for example in data: inputs = [] for i in example[:-1]: inputs.append(i) target = example[-1] self.hiddenLayer.setInput(inputs) hiddenOutputs = self.hiddenLayer.calculateOutputs() self.outerLayer.setInput(hiddenOutputs) outerOutputs = self.outerLayer.calculateOutputs() errorsOuter = self.outerLayer.calculateOuterErrors(target) for neuron in self.hiddenLayer.neurons: output = neuron.getOutput() errorHidden = output*(1-output) errorSum = 0 for outerNeuron in self.outerLayer.neurons: errorSum += outerNeuron.calculateErrorSum(neuron.getId()) errorHidden = errorHidden * errorSum neuron.setError(errorHidden) self.hiddenLayer.updateWeights() self.outerLayer.updateWeights() error, i = 0, 0 for o in self.outerLayer.getOutput(): error += (target[i]-o) i += 1 error *= error totalError += error totalError = totalError / len(data) return totalError def classify(self,data,datasetType): output = [] for example in data: inputs = [] for i in example[:-1]: inputs.append(i) self.hiddenLayer.setInput(inputs) hiddenOutputs = self.hiddenLayer.calculateOutputs() self.outerLayer.setInput(hiddenOutputs) outerOutputs = self.outerLayer.calculateOutputs() if datasetType != 3: for o in outerOutputs: if (o < 0.5): output.append(0) elif (o >= 0.5): output.append(1) if datasetType == 3: oList = [] for o in outerOutputs: if (o < 0.5): oList.append(0) elif (o >= 0.5): oList.append(1) output.append(oList) return output
#!usr/bin/python n=int(raw_input("Enter the no. of elements :")) a=[] b=[] print "Enter the elements :" for i in xrange(n): x=int(input()) a.append(x) for i in xrange(n): for j in range(i+1,n): if a[i]==a[j]: a[i]=a[j]=0 for i in xrange(n): if not a[i]==0: print a[i]
import pandas as pd from pandas import DataFrame EXCEL_TYPES = ['xls', 'xlsx', 'xlsm', 'xlsb', 'odf', 'ods', 'odt'] NUMERICS = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] def return_numerical_columns(df: DataFrame, result_column: DataFrame, exclude: [] = None): df_num = df.select_dtypes(include=NUMERICS) if exclude: for ex in exclude: df_num = df_num.drop(ex, axis=1) df_num = df_num.join(result_column) return df_num def return_str_columns(df: DataFrame, result_column: DataFrame, include: [] = None): return df.drop(return_numerical_columns(df, result_column, exclude=include).columns.values, axis=1)\ .join(result_column) class DatasetReader: def __init__(self, file: str): self.data: DataFrame try: if file.split('.')[-1] in EXCEL_TYPES: self.data = pd.read_excel(file, engine='openpyxl') elif file.split('.')[-1] == 'csv': self.data = pd.read_csv(file) else: raise Exception('Cannot handle that type of file.') except IndexError: raise Exception('File must match [path].[extension]') def get_column_names_except_first(self): return self.data.columns[1:].values def return_df_without_first_column(self): return self.data[self.get_column_names_except_first()].copy()
# -*- coding: utf-8 -*- from typing import List class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def mergeTwoKLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1.val <= l2.val: l1.next = self.mergeTwoKLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoKLists(l1, l2.next) return l2 def merge(self, lists, left, right): if left == right: return lists[left] mid = (right + left) // 2 l1 = self.merge() def mergeKLists(self, lists: List[ListNode]) -> ListNode: if lists.length == 0: return [] if lists.length == 1: return lists[0] if lists.length == 2: return self.mergeTwoKLists(lists[0], lists[1]) n = len(lists) mid = len(lists) // 2 l1 = [] l2 = [] for i in range(mid): l1[i] = lists[i] for i in range((n - mid), n): l2[i] = lists[i] return self.mergeTwoKLists(l1, l2)
""" # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next """ from collections import deque class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root q = deque([root]) while q: front = q[0] last = None while q: cur = q.pop() if last: last.next = cur last = cur if cur.left: q.appendleft(cur.left) if cur.right: q.appendleft(cur.right) if cur == front: break return root
# Sum of odd numbers # https://www.codewars.com/kata/55fd2d567d94ac3bc9000064/train/python # Instructions: # Given the triangle of consecutive odd numbers: # 1 # 3 5 # 7 9 11 # 13 15 17 19 # 21 23 25 27 29 # ... # Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: # row_sum_odd_numbers(1); # 1 # row_sum_odd_numbers(2); # 3 + 5 = 8 def row_sum_odd_numbers(n): return (n**3) print(row_sum_odd_numbers(1)) print(row_sum_odd_numbers(2)) print(row_sum_odd_numbers(13)) print(row_sum_odd_numbers(41)) # Tests for code wars # # Test.assert_equals(row_sum_odd_numbers(1), 1) # # Test.assert_equals(row_sum_odd_numbers(2), 8) # # Test.assert_equals(row_sum_odd_numbers(13), 2197) # # Test.assert_equals(row_sum_odd_numbers(19), 6859) # # Test.assert_equals(row_sum_odd_numbers(41), 68921)
def main(): m,d = map(int, input().split()) for i in range(1,m): if i == 1 or i == 3 or i == 5 or i == 7 or i ==8 or i == 10 or i ==12: d += 31 elif i == 2: d += 28 else: d += 30 today = d % 7 print(switch(today)) def switch(today): return { 4 : "THU", 5 : "FRI", 6 : "SAT", 0 : "SUN", 1 : "MON", 2 : "TUE", 3 : "WED" }.get(today, 9) if __name__=="__main__": main()
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'mainHDlTlQ.ui' ## ## Created by: Qt User Interface Compiler version 5.14.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PyQt5.QtCore import (QCoreApplication, QMetaObject, QObject, QPoint, QRect, QSize, QUrl, Qt) from PyQt5.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap, QRadialGradient) from PyQt5.QtWidgets import * class Ui_MainWindow(object): def setupUi(self, MainWindow): if MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1168, 659) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.verticalLayout_12 = QVBoxLayout(self.centralwidget) self.verticalLayout_12.setObjectName(u"verticalLayout_12") self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setObjectName(u"tabWidget") self.tab = QWidget() self.tab.setObjectName(u"tab") self.verticalLayout_3 = QVBoxLayout(self.tab) self.verticalLayout_3.setObjectName(u"verticalLayout_3") self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.verticalLayout_5 = QVBoxLayout() self.verticalLayout_5.setObjectName(u"verticalLayout_5") self.horizontalLayout_13 = QHBoxLayout() self.horizontalLayout_13.setObjectName(u"horizontalLayout_13") self.verticalLayout_34 = QVBoxLayout() self.verticalLayout_34.setObjectName(u"verticalLayout_34") self.frame_10 = QFrame(self.tab) self.frame_10.setObjectName(u"frame_10") self.frame_10.setFrameShape(QFrame.NoFrame) self.frame_10.setFrameShadow(QFrame.Raised) self.verticalLayout_37 = QVBoxLayout(self.frame_10) self.verticalLayout_37.setSpacing(0) self.verticalLayout_37.setObjectName(u"verticalLayout_37") self.verticalLayout_37.setContentsMargins(0, 0, 0, 0) self.groupBox = QGroupBox(self.frame_10) self.groupBox.setObjectName(u"groupBox") self.groupBox.setMaximumSize(QSize(500, 182)) self.verticalLayout_14 = QVBoxLayout(self.groupBox) self.verticalLayout_14.setObjectName(u"verticalLayout_14") self.verticalLayout_13 = QVBoxLayout() self.verticalLayout_13.setObjectName(u"verticalLayout_13") self.label_3 = QLabel(self.groupBox) self.label_3.setObjectName(u"label_3") self.verticalLayout_13.addWidget(self.label_3) self.label_2 = QLabel(self.groupBox) self.label_2.setObjectName(u"label_2") self.verticalLayout_13.addWidget(self.label_2) self.label = QLabel(self.groupBox) self.label.setObjectName(u"label") self.verticalLayout_13.addWidget(self.label) self.label_4 = QLabel(self.groupBox) self.label_4.setObjectName(u"label_4") self.verticalLayout_13.addWidget(self.label_4) self.label_5 = QLabel(self.groupBox) self.label_5.setObjectName(u"label_5") self.verticalLayout_13.addWidget(self.label_5) self.label_6 = QLabel(self.groupBox) self.label_6.setObjectName(u"label_6") self.verticalLayout_13.addWidget(self.label_6) self.verticalLayout_14.addLayout(self.verticalLayout_13) self.verticalLayout_37.addWidget(self.groupBox) self.verticalLayout_34.addWidget(self.frame_10, 0, Qt.AlignTop) self.groupBox_17 = QGroupBox(self.tab) self.groupBox_17.setObjectName(u"groupBox_17") self.verticalLayout_94 = QVBoxLayout(self.groupBox_17) self.verticalLayout_94.setObjectName(u"verticalLayout_94") self.verticalLayout_93 = QVBoxLayout() self.verticalLayout_93.setObjectName(u"verticalLayout_93") self.label_37 = QLabel(self.groupBox_17) self.label_37.setObjectName(u"label_37") self.verticalLayout_93.addWidget(self.label_37) self.label_38 = QLabel(self.groupBox_17) self.label_38.setObjectName(u"label_38") self.verticalLayout_93.addWidget(self.label_38) self.label_36 = QLabel(self.groupBox_17) self.label_36.setObjectName(u"label_36") self.verticalLayout_93.addWidget(self.label_36) self.label_15 = QLabel(self.groupBox_17) self.label_15.setObjectName(u"label_15") self.verticalLayout_93.addWidget(self.label_15) self.verticalLayout_94.addLayout(self.verticalLayout_93) self.horizontalLayout_73 = QHBoxLayout() self.horizontalLayout_73.setObjectName(u"horizontalLayout_73") self.pushButton_19 = QPushButton(self.groupBox_17) self.pushButton_19.setObjectName(u"pushButton_19") self.horizontalLayout_73.addWidget(self.pushButton_19) self.pushButton_20 = QPushButton(self.groupBox_17) self.pushButton_20.setObjectName(u"pushButton_20") self.horizontalLayout_73.addWidget(self.pushButton_20) self.verticalLayout_94.addLayout(self.horizontalLayout_73) self.verticalLayout_34.addWidget(self.groupBox_17, 0, Qt.AlignTop) self.tableWidget_9 = QTableWidget(self.tab) if (self.tableWidget_9.columnCount() < 2): self.tableWidget_9.setColumnCount(2) __qtablewidgetitem = QTableWidgetItem() self.tableWidget_9.setHorizontalHeaderItem(0, __qtablewidgetitem) __qtablewidgetitem1 = QTableWidgetItem() self.tableWidget_9.setHorizontalHeaderItem(1, __qtablewidgetitem1) self.tableWidget_9.setObjectName(u"tableWidget_9") sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tableWidget_9.sizePolicy().hasHeightForWidth()) self.tableWidget_9.setSizePolicy(sizePolicy) self.tableWidget_9.setShowGrid(False) self.tableWidget_9.horizontalHeader().setVisible(False) self.tableWidget_9.horizontalHeader().setMinimumSectionSize(23) self.tableWidget_9.verticalHeader().setVisible(False) self.tableWidget_9.verticalHeader().setDefaultSectionSize(23) self.verticalLayout_34.addWidget(self.tableWidget_9) self.frame_11 = QFrame(self.tab) self.frame_11.setObjectName(u"frame_11") self.frame_11.setFrameShape(QFrame.NoFrame) self.frame_11.setFrameShadow(QFrame.Raised) self.verticalLayout_38 = QVBoxLayout(self.frame_11) self.verticalLayout_38.setSpacing(0) self.verticalLayout_38.setObjectName(u"verticalLayout_38") self.verticalLayout_38.setContentsMargins(0, 0, 0, 0) self.frame_12 = QFrame(self.frame_11) self.frame_12.setObjectName(u"frame_12") self.frame_12.setFrameShape(QFrame.NoFrame) self.frame_12.setFrameShadow(QFrame.Raised) self.horizontalLayout_2 = QHBoxLayout(self.frame_12) self.horizontalLayout_2.setSpacing(1) self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.horizontalLayout_2.setContentsMargins(1, 1, 1, 1) self.verticalLayout_38.addWidget(self.frame_12) self.frame_13 = QFrame(self.frame_11) self.frame_13.setObjectName(u"frame_13") self.frame_13.setFrameShape(QFrame.NoFrame) self.frame_13.setFrameShadow(QFrame.Raised) self.horizontalLayout_3 = QHBoxLayout(self.frame_13) self.horizontalLayout_3.setSpacing(1) self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") self.horizontalLayout_3.setContentsMargins(1, 1, 1, 1) self.verticalLayout_38.addWidget(self.frame_13) self.verticalLayout_34.addWidget(self.frame_11, 0, Qt.AlignHCenter|Qt.AlignBottom) self.horizontalLayout_13.addLayout(self.verticalLayout_34) self.verticalLayout_33 = QVBoxLayout() self.verticalLayout_33.setObjectName(u"verticalLayout_33") self.groupBox_2 = QGroupBox(self.tab) self.groupBox_2.setObjectName(u"groupBox_2") self.verticalLayout_35 = QVBoxLayout(self.groupBox_2) self.verticalLayout_35.setObjectName(u"verticalLayout_35") self.tableWidget_7 = QTableWidget(self.groupBox_2) if (self.tableWidget_7.columnCount() < 4): self.tableWidget_7.setColumnCount(4) __qtablewidgetitem2 = QTableWidgetItem() self.tableWidget_7.setHorizontalHeaderItem(0, __qtablewidgetitem2) __qtablewidgetitem3 = QTableWidgetItem() self.tableWidget_7.setHorizontalHeaderItem(1, __qtablewidgetitem3) __qtablewidgetitem4 = QTableWidgetItem() self.tableWidget_7.setHorizontalHeaderItem(2, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem() self.tableWidget_7.setHorizontalHeaderItem(3, __qtablewidgetitem5) self.tableWidget_7.setObjectName(u"tableWidget_7") self.tableWidget_7.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.tableWidget_7.verticalHeader().setVisible(False) self.tableWidget_7.verticalHeader().setDefaultSectionSize(23) self.verticalLayout_35.addWidget(self.tableWidget_7) self.verticalLayout_33.addWidget(self.groupBox_2) self.groupBox_3 = QGroupBox(self.tab) self.groupBox_3.setObjectName(u"groupBox_3") self.verticalLayout_36 = QVBoxLayout(self.groupBox_3) self.verticalLayout_36.setObjectName(u"verticalLayout_36") self.tableWidget_8 = QTableWidget(self.groupBox_3) if (self.tableWidget_8.columnCount() < 4): self.tableWidget_8.setColumnCount(4) __qtablewidgetitem6 = QTableWidgetItem() self.tableWidget_8.setHorizontalHeaderItem(0, __qtablewidgetitem6) __qtablewidgetitem7 = QTableWidgetItem() self.tableWidget_8.setHorizontalHeaderItem(1, __qtablewidgetitem7) __qtablewidgetitem8 = QTableWidgetItem() self.tableWidget_8.setHorizontalHeaderItem(2, __qtablewidgetitem8) __qtablewidgetitem9 = QTableWidgetItem() self.tableWidget_8.setHorizontalHeaderItem(3, __qtablewidgetitem9) self.tableWidget_8.setObjectName(u"tableWidget_8") self.tableWidget_8.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.tableWidget_8.verticalHeader().setVisible(False) self.tableWidget_8.verticalHeader().setDefaultSectionSize(23) self.verticalLayout_36.addWidget(self.tableWidget_8) self.verticalLayout_33.addWidget(self.groupBox_3) self.horizontalLayout_13.addLayout(self.verticalLayout_33) self.verticalLayout_5.addLayout(self.horizontalLayout_13) self.verticalLayout_2.addLayout(self.verticalLayout_5) self.verticalLayout_4 = QVBoxLayout() self.verticalLayout_4.setObjectName(u"verticalLayout_4") self.verticalLayout_6 = QVBoxLayout() self.verticalLayout_6.setObjectName(u"verticalLayout_6") self.frame_3 = QFrame(self.tab) self.frame_3.setObjectName(u"frame_3") self.frame_3.setFrameShape(QFrame.NoFrame) self.frame_3.setFrameShadow(QFrame.Raised) self.verticalLayout_16 = QVBoxLayout(self.frame_3) self.verticalLayout_16.setSpacing(6) self.verticalLayout_16.setObjectName(u"verticalLayout_16") self.verticalLayout_16.setContentsMargins(9, -1, 9, -1) self.frame_14 = QFrame(self.frame_3) self.frame_14.setObjectName(u"frame_14") self.frame_14.setFrameShape(QFrame.NoFrame) self.frame_14.setFrameShadow(QFrame.Plain) self.horizontalLayout_14 = QHBoxLayout(self.frame_14) self.horizontalLayout_14.setSpacing(6) self.horizontalLayout_14.setObjectName(u"horizontalLayout_14") self.horizontalLayout_14.setContentsMargins(0, 0, 0, 0) self.verticalLayout_15 = QVBoxLayout() self.verticalLayout_15.setObjectName(u"verticalLayout_15") self.label_7 = QLabel(self.frame_14) self.label_7.setObjectName(u"label_7") self.verticalLayout_15.addWidget(self.label_7) self.horizontalLayout_14.addLayout(self.verticalLayout_15) self.verticalLayout_16.addWidget(self.frame_14) self.verticalLayout_6.addWidget(self.frame_3) self.verticalLayout_4.addLayout(self.verticalLayout_6) self.verticalLayout_7 = QVBoxLayout() self.verticalLayout_7.setObjectName(u"verticalLayout_7") self.frame = QFrame(self.tab) self.frame.setObjectName(u"frame") self.frame.setFrameShape(QFrame.NoFrame) self.frame.setFrameShadow(QFrame.Raised) self.horizontalLayout_5 = QHBoxLayout(self.frame) self.horizontalLayout_5.setObjectName(u"horizontalLayout_5") self.frame_2 = QFrame(self.frame) self.frame_2.setObjectName(u"frame_2") self.frame_2.setEnabled(True) sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.frame_2.sizePolicy().hasHeightForWidth()) self.frame_2.setSizePolicy(sizePolicy1) self.frame_2.setMinimumSize(QSize(0, 0)) self.frame_2.setStyleSheet(u";\n" "border-color: rgb(0, 0, 0);") self.frame_2.setFrameShape(QFrame.NoFrame) self.frame_2.setFrameShadow(QFrame.Raised) self.horizontalLayout_4 = QHBoxLayout(self.frame_2) self.horizontalLayout_4.setSpacing(6) self.horizontalLayout_4.setObjectName(u"horizontalLayout_4") self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_10 = QVBoxLayout() self.verticalLayout_10.setObjectName(u"verticalLayout_10") self.pushButton = QPushButton(self.frame_2) self.pushButton.setObjectName(u"pushButton") self.pushButton.setMinimumSize(QSize(200, 30)) self.pushButton.setBaseSize(QSize(0, 0)) self.verticalLayout_10.addWidget(self.pushButton) self.pushButton_2 = QPushButton(self.frame_2) self.pushButton_2.setObjectName(u"pushButton_2") self.pushButton_2.setMinimumSize(QSize(200, 30)) self.verticalLayout_10.addWidget(self.pushButton_2) self.horizontalLayout_4.addLayout(self.verticalLayout_10) self.verticalLayout_11 = QVBoxLayout() self.verticalLayout_11.setObjectName(u"verticalLayout_11") self.progressBar = QProgressBar(self.frame_2) self.progressBar.setObjectName(u"progressBar") self.progressBar.setMinimumSize(QSize(0, 30)) font = QFont() font.setBold(False) font.setWeight(50) font.setKerning(True) self.progressBar.setFont(font) self.progressBar.setStyleSheet(u"background-color: rgb(218, 218, 218);") self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setTextVisible(True) self.progressBar.setOrientation(Qt.Horizontal) self.progressBar.setInvertedAppearance(False) self.progressBar.setTextDirection(QProgressBar.TopToBottom) self.verticalLayout_11.addWidget(self.progressBar, 0, Qt.AlignBottom) self.progressBar_2 = QProgressBar(self.frame_2) self.progressBar_2.setObjectName(u"progressBar_2") self.progressBar_2.setMinimumSize(QSize(0, 30)) font1 = QFont() font1.setKerning(False) self.progressBar_2.setFont(font1) self.progressBar_2.setMouseTracking(False) self.progressBar_2.setStyleSheet(u"background-color: rgb(218, 218, 218);") self.progressBar_2.setAlignment(Qt.AlignCenter) self.progressBar_2.setTextVisible(True) self.progressBar_2.setOrientation(Qt.Horizontal) self.progressBar_2.setInvertedAppearance(False) self.progressBar_2.setTextDirection(QProgressBar.TopToBottom) self.verticalLayout_11.addWidget(self.progressBar_2, 0, Qt.AlignBottom) self.horizontalLayout_4.addLayout(self.verticalLayout_11) self.horizontalLayout_5.addWidget(self.frame_2, 0, Qt.AlignBottom) self.verticalLayout_7.addWidget(self.frame) self.verticalLayout_4.addLayout(self.verticalLayout_7) self.verticalLayout_2.addLayout(self.verticalLayout_4) self.verticalLayout_3.addLayout(self.verticalLayout_2) self.tabWidget.addTab(self.tab, "") self.tab_2 = QWidget() self.tab_2.setObjectName(u"tab_2") self.verticalLayout_18 = QVBoxLayout(self.tab_2) self.verticalLayout_18.setObjectName(u"verticalLayout_18") self.horizontalLayout_74 = QHBoxLayout() self.horizontalLayout_74.setObjectName(u"horizontalLayout_74") self.frame_4 = QFrame(self.tab_2) self.frame_4.setObjectName(u"frame_4") self.frame_4.setFrameShape(QFrame.NoFrame) self.frame_4.setFrameShadow(QFrame.Raised) self.horizontalLayout_7 = QHBoxLayout(self.frame_4) self.horizontalLayout_7.setSpacing(6) self.horizontalLayout_7.setObjectName(u"horizontalLayout_7") self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName(u"horizontalLayout_6") self.lineEdit = QLineEdit(self.frame_4) self.lineEdit.setObjectName(u"lineEdit") sizePolicy2 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth()) self.lineEdit.setSizePolicy(sizePolicy2) self.lineEdit.setMinimumSize(QSize(200, 0)) self.lineEdit.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_6.addWidget(self.lineEdit) self.pushButton_7 = QPushButton(self.frame_4) self.pushButton_7.setObjectName(u"pushButton_7") self.horizontalLayout_6.addWidget(self.pushButton_7) self.horizontalLayout_7.addLayout(self.horizontalLayout_6) self.horizontalLayout_74.addWidget(self.frame_4, 0, Qt.AlignLeft) self.frame_30 = QFrame(self.tab_2) self.frame_30.setObjectName(u"frame_30") self.frame_30.setFrameShape(QFrame.NoFrame) self.frame_30.setFrameShadow(QFrame.Raised) self.verticalLayout_8 = QVBoxLayout(self.frame_30) self.verticalLayout_8.setObjectName(u"verticalLayout_8") self.verticalLayout_8.setContentsMargins(0, 0, 0, 0) self.label_20 = QLabel(self.frame_30) self.label_20.setObjectName(u"label_20") self.verticalLayout_8.addWidget(self.label_20, 0, Qt.AlignRight) self.horizontalLayout_74.addWidget(self.frame_30) self.verticalLayout_18.addLayout(self.horizontalLayout_74) self.horizontalLayout_83 = QHBoxLayout() self.horizontalLayout_83.setSpacing(0) self.horizontalLayout_83.setObjectName(u"horizontalLayout_83") self.pushButton_61 = QPushButton(self.tab_2) self.pushButton_61.setObjectName(u"pushButton_61") self.horizontalLayout_83.addWidget(self.pushButton_61) self.pushButton_60 = QPushButton(self.tab_2) self.pushButton_60.setObjectName(u"pushButton_60") self.pushButton_60.setMinimumSize(QSize(100, 0)) self.pushButton_60.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_83.addWidget(self.pushButton_60) self.pushButton_59 = QPushButton(self.tab_2) self.pushButton_59.setObjectName(u"pushButton_59") self.pushButton_59.setMinimumSize(QSize(100, 0)) self.pushButton_59.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_83.addWidget(self.pushButton_59) self.pushButton_62 = QPushButton(self.tab_2) self.pushButton_62.setObjectName(u"pushButton_62") self.pushButton_62.setMinimumSize(QSize(47, 0)) self.pushButton_62.setMaximumSize(QSize(47, 16777215)) self.pushButton_62.setFlat(True) self.horizontalLayout_83.addWidget(self.pushButton_62) self.verticalLayout_18.addLayout(self.horizontalLayout_83) self.tableWidget = QTableWidget(self.tab_2) if (self.tableWidget.columnCount() < 4): self.tableWidget.setColumnCount(4) __qtablewidgetitem10 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem10) __qtablewidgetitem11 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem11) __qtablewidgetitem12 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, __qtablewidgetitem12) __qtablewidgetitem13 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, __qtablewidgetitem13) self.tableWidget.setObjectName(u"tableWidget") self.tableWidget.horizontalHeader().setVisible(False) self.tableWidget.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_18.addWidget(self.tableWidget) self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QWidget() self.tab_3.setObjectName(u"tab_3") self.verticalLayout_23 = QVBoxLayout(self.tab_3) self.verticalLayout_23.setObjectName(u"verticalLayout_23") self.horizontalLayout_75 = QHBoxLayout() self.horizontalLayout_75.setObjectName(u"horizontalLayout_75") self.frame_5 = QFrame(self.tab_3) self.frame_5.setObjectName(u"frame_5") self.frame_5.setFrameShape(QFrame.NoFrame) self.frame_5.setFrameShadow(QFrame.Raised) self.verticalLayout_28 = QVBoxLayout(self.frame_5) self.verticalLayout_28.setSpacing(6) self.verticalLayout_28.setObjectName(u"verticalLayout_28") self.verticalLayout_28.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_8 = QHBoxLayout() self.horizontalLayout_8.setObjectName(u"horizontalLayout_8") self.lineEdit_2 = QLineEdit(self.frame_5) self.lineEdit_2.setObjectName(u"lineEdit_2") sizePolicy2.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth()) self.lineEdit_2.setSizePolicy(sizePolicy2) self.lineEdit_2.setMinimumSize(QSize(200, 0)) self.horizontalLayout_8.addWidget(self.lineEdit_2) self.pushButton_8 = QPushButton(self.frame_5) self.pushButton_8.setObjectName(u"pushButton_8") self.horizontalLayout_8.addWidget(self.pushButton_8) self.pushButton_22 = QPushButton(self.frame_5) self.pushButton_22.setObjectName(u"pushButton_22") self.pushButton_22.setFlat(True) self.horizontalLayout_8.addWidget(self.pushButton_22) self.verticalLayout_28.addLayout(self.horizontalLayout_8) self.horizontalLayout_75.addWidget(self.frame_5, 0, Qt.AlignLeft) self.frame_31 = QFrame(self.tab_3) self.frame_31.setObjectName(u"frame_31") self.frame_31.setFrameShape(QFrame.NoFrame) self.frame_31.setFrameShadow(QFrame.Raised) self.horizontalLayout_76 = QHBoxLayout(self.frame_31) self.horizontalLayout_76.setObjectName(u"horizontalLayout_76") self.horizontalLayout_76.setContentsMargins(0, 0, 0, 0) self.label_21 = QLabel(self.frame_31) self.label_21.setObjectName(u"label_21") self.horizontalLayout_76.addWidget(self.label_21, 0, Qt.AlignLeft) self.horizontalLayout_75.addWidget(self.frame_31, 0, Qt.AlignRight) self.verticalLayout_23.addLayout(self.horizontalLayout_75) self.horizontalLayout_82 = QHBoxLayout() self.horizontalLayout_82.setSpacing(0) self.horizontalLayout_82.setObjectName(u"horizontalLayout_82") self.pushButton_58 = QPushButton(self.tab_3) self.pushButton_58.setObjectName(u"pushButton_58") self.horizontalLayout_82.addWidget(self.pushButton_58) self.pushButton_57 = QPushButton(self.tab_3) self.pushButton_57.setObjectName(u"pushButton_57") self.pushButton_57.setMinimumSize(QSize(150, 0)) self.pushButton_57.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_82.addWidget(self.pushButton_57) self.pushButton_56 = QPushButton(self.tab_3) self.pushButton_56.setObjectName(u"pushButton_56") self.pushButton_56.setMinimumSize(QSize(150, 0)) self.pushButton_56.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_82.addWidget(self.pushButton_56) self.pushButton_55 = QPushButton(self.tab_3) self.pushButton_55.setObjectName(u"pushButton_55") self.pushButton_55.setMinimumSize(QSize(150, 0)) self.pushButton_55.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_82.addWidget(self.pushButton_55) self.pushButton_54 = QPushButton(self.tab_3) self.pushButton_54.setObjectName(u"pushButton_54") self.pushButton_54.setMinimumSize(QSize(78, 0)) self.pushButton_54.setMaximumSize(QSize(78, 16777215)) self.pushButton_54.setFlat(True) self.horizontalLayout_82.addWidget(self.pushButton_54) self.verticalLayout_23.addLayout(self.horizontalLayout_82) self.tableWidget_2 = QTableWidget(self.tab_3) if (self.tableWidget_2.columnCount() < 6): self.tableWidget_2.setColumnCount(6) __qtablewidgetitem14 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(0, __qtablewidgetitem14) __qtablewidgetitem15 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(1, __qtablewidgetitem15) __qtablewidgetitem16 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(2, __qtablewidgetitem16) __qtablewidgetitem17 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(3, __qtablewidgetitem17) __qtablewidgetitem18 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(4, __qtablewidgetitem18) __qtablewidgetitem19 = QTableWidgetItem() self.tableWidget_2.setHorizontalHeaderItem(5, __qtablewidgetitem19) self.tableWidget_2.setObjectName(u"tableWidget_2") self.tableWidget_2.horizontalHeader().setVisible(False) self.tableWidget_2.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_23.addWidget(self.tableWidget_2) self.tabWidget.addTab(self.tab_3, "") self.tab_4 = QWidget() self.tab_4.setObjectName(u"tab_4") self.verticalLayout_22 = QVBoxLayout(self.tab_4) self.verticalLayout_22.setObjectName(u"verticalLayout_22") self.horizontalLayout_77 = QHBoxLayout() self.horizontalLayout_77.setObjectName(u"horizontalLayout_77") self.frame_6 = QFrame(self.tab_4) self.frame_6.setObjectName(u"frame_6") self.frame_6.setFrameShape(QFrame.NoFrame) self.frame_6.setFrameShadow(QFrame.Raised) self.verticalLayout_29 = QVBoxLayout(self.frame_6) self.verticalLayout_29.setSpacing(6) self.verticalLayout_29.setObjectName(u"verticalLayout_29") self.verticalLayout_29.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_9 = QHBoxLayout() self.horizontalLayout_9.setObjectName(u"horizontalLayout_9") self.lineEdit_3 = QLineEdit(self.frame_6) self.lineEdit_3.setObjectName(u"lineEdit_3") sizePolicy2.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth()) self.lineEdit_3.setSizePolicy(sizePolicy2) self.lineEdit_3.setMinimumSize(QSize(200, 0)) self.horizontalLayout_9.addWidget(self.lineEdit_3) self.pushButton_9 = QPushButton(self.frame_6) self.pushButton_9.setObjectName(u"pushButton_9") self.horizontalLayout_9.addWidget(self.pushButton_9) self.pushButton_26 = QPushButton(self.frame_6) self.pushButton_26.setObjectName(u"pushButton_26") self.pushButton_26.setFlat(True) self.horizontalLayout_9.addWidget(self.pushButton_26) self.verticalLayout_29.addLayout(self.horizontalLayout_9) self.horizontalLayout_77.addWidget(self.frame_6, 0, Qt.AlignLeft) self.frame_32 = QFrame(self.tab_4) self.frame_32.setObjectName(u"frame_32") self.frame_32.setFrameShape(QFrame.NoFrame) self.frame_32.setFrameShadow(QFrame.Raised) self.horizontalLayout_78 = QHBoxLayout(self.frame_32) self.horizontalLayout_78.setObjectName(u"horizontalLayout_78") self.horizontalLayout_78.setContentsMargins(0, 0, 0, 0) self.label_24 = QLabel(self.frame_32) self.label_24.setObjectName(u"label_24") self.horizontalLayout_78.addWidget(self.label_24) self.horizontalLayout_77.addWidget(self.frame_32, 0, Qt.AlignRight) self.verticalLayout_22.addLayout(self.horizontalLayout_77) self.horizontalLayout_47 = QHBoxLayout() self.horizontalLayout_47.setSpacing(0) self.horizontalLayout_47.setObjectName(u"horizontalLayout_47") self.pushButton_51 = QPushButton(self.tab_4) self.pushButton_51.setObjectName(u"pushButton_51") self.horizontalLayout_47.addWidget(self.pushButton_51) self.pushButton_50 = QPushButton(self.tab_4) self.pushButton_50.setObjectName(u"pushButton_50") self.pushButton_50.setMinimumSize(QSize(150, 0)) self.pushButton_50.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_47.addWidget(self.pushButton_50) self.pushButton_49 = QPushButton(self.tab_4) self.pushButton_49.setObjectName(u"pushButton_49") self.pushButton_49.setMinimumSize(QSize(150, 0)) self.pushButton_49.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_47.addWidget(self.pushButton_49) self.pushButton_48 = QPushButton(self.tab_4) self.pushButton_48.setObjectName(u"pushButton_48") self.pushButton_48.setMinimumSize(QSize(150, 0)) self.pushButton_48.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_47.addWidget(self.pushButton_48) self.pushButton_53 = QPushButton(self.tab_4) self.pushButton_53.setObjectName(u"pushButton_53") self.pushButton_53.setMinimumSize(QSize(150, 0)) self.pushButton_53.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_47.addWidget(self.pushButton_53) self.pushButton_52 = QPushButton(self.tab_4) self.pushButton_52.setObjectName(u"pushButton_52") self.pushButton_52.setMinimumSize(QSize(107, 0)) self.pushButton_52.setMaximumSize(QSize(107, 16777215)) self.pushButton_52.setFlat(True) self.horizontalLayout_47.addWidget(self.pushButton_52) self.verticalLayout_22.addLayout(self.horizontalLayout_47) self.tableWidget_3 = QTableWidget(self.tab_4) if (self.tableWidget_3.columnCount() < 8): self.tableWidget_3.setColumnCount(8) __qtablewidgetitem20 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(0, __qtablewidgetitem20) __qtablewidgetitem21 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(1, __qtablewidgetitem21) __qtablewidgetitem22 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(2, __qtablewidgetitem22) __qtablewidgetitem23 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(3, __qtablewidgetitem23) __qtablewidgetitem24 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(4, __qtablewidgetitem24) __qtablewidgetitem25 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(5, __qtablewidgetitem25) __qtablewidgetitem26 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(6, __qtablewidgetitem26) __qtablewidgetitem27 = QTableWidgetItem() self.tableWidget_3.setHorizontalHeaderItem(7, __qtablewidgetitem27) self.tableWidget_3.setObjectName(u"tableWidget_3") self.tableWidget_3.horizontalHeader().setVisible(False) self.tableWidget_3.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_22.addWidget(self.tableWidget_3) self.tabWidget.addTab(self.tab_4, "") self.tab_5 = QWidget() self.tab_5.setObjectName(u"tab_5") self.verticalLayout_17 = QVBoxLayout(self.tab_5) self.verticalLayout_17.setObjectName(u"verticalLayout_17") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName(u"horizontalLayout") self.label_8 = QLabel(self.tab_5) self.label_8.setObjectName(u"label_8") self.horizontalLayout.addWidget(self.label_8) self.pushButton_27 = QPushButton(self.tab_5) self.pushButton_27.setObjectName(u"pushButton_27") sizePolicy3 = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy3.setHorizontalStretch(0) sizePolicy3.setVerticalStretch(0) sizePolicy3.setHeightForWidth(self.pushButton_27.sizePolicy().hasHeightForWidth()) self.pushButton_27.setSizePolicy(sizePolicy3) self.pushButton_27.setFlat(True) self.horizontalLayout.addWidget(self.pushButton_27) self.pushButton_4 = QPushButton(self.tab_5) self.pushButton_4.setObjectName(u"pushButton_4") self.pushButton_4.setMaximumSize(QSize(120, 16777215)) self.horizontalLayout.addWidget(self.pushButton_4) self.pushButton_5 = QPushButton(self.tab_5) self.pushButton_5.setObjectName(u"pushButton_5") self.pushButton_5.setMaximumSize(QSize(110, 16777215)) self.horizontalLayout.addWidget(self.pushButton_5) self.pushButton_3 = QPushButton(self.tab_5) self.pushButton_3.setObjectName(u"pushButton_3") self.pushButton_3.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout.addWidget(self.pushButton_3) self.verticalLayout_17.addLayout(self.horizontalLayout) self.tabWidget_2 = QTabWidget(self.tab_5) self.tabWidget_2.setObjectName(u"tabWidget_2") self.tab_7 = QWidget() self.tab_7.setObjectName(u"tab_7") self.verticalLayout_21 = QVBoxLayout(self.tab_7) self.verticalLayout_21.setObjectName(u"verticalLayout_21") self.verticalLayout_25 = QVBoxLayout() self.verticalLayout_25.setObjectName(u"verticalLayout_25") self.frame_7 = QFrame(self.tab_7) self.frame_7.setObjectName(u"frame_7") self.frame_7.setFrameShape(QFrame.NoFrame) self.frame_7.setFrameShadow(QFrame.Raised) self.verticalLayout_31 = QVBoxLayout(self.frame_7) self.verticalLayout_31.setSpacing(6) self.verticalLayout_31.setObjectName(u"verticalLayout_31") self.verticalLayout_31.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_10 = QHBoxLayout() self.horizontalLayout_10.setObjectName(u"horizontalLayout_10") self.lineEdit_4 = QLineEdit(self.frame_7) self.lineEdit_4.setObjectName(u"lineEdit_4") self.lineEdit_4.setMinimumSize(QSize(200, 0)) self.horizontalLayout_10.addWidget(self.lineEdit_4) self.pushButton_10 = QPushButton(self.frame_7) self.pushButton_10.setObjectName(u"pushButton_10") self.horizontalLayout_10.addWidget(self.pushButton_10) self.verticalLayout_31.addLayout(self.horizontalLayout_10) self.verticalLayout_25.addWidget(self.frame_7, 0, Qt.AlignLeft) self.verticalLayout_21.addLayout(self.verticalLayout_25) self.horizontalLayout_35 = QHBoxLayout() self.horizontalLayout_35.setSpacing(0) self.horizontalLayout_35.setObjectName(u"horizontalLayout_35") self.pushButton_29 = QPushButton(self.tab_7) self.pushButton_29.setObjectName(u"pushButton_29") self.horizontalLayout_35.addWidget(self.pushButton_29) self.pushButton_28 = QPushButton(self.tab_7) self.pushButton_28.setObjectName(u"pushButton_28") self.pushButton_28.setMinimumSize(QSize(100, 0)) self.pushButton_28.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_35.addWidget(self.pushButton_28) self.pushButton_24 = QPushButton(self.tab_7) self.pushButton_24.setObjectName(u"pushButton_24") self.pushButton_24.setMinimumSize(QSize(150, 0)) self.pushButton_24.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_35.addWidget(self.pushButton_24) self.pushButton_32 = QPushButton(self.tab_7) self.pushButton_32.setObjectName(u"pushButton_32") self.pushButton_32.setMinimumSize(QSize(150, 0)) self.pushButton_32.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_35.addWidget(self.pushButton_32) self.pushButton_31 = QPushButton(self.tab_7) self.pushButton_31.setObjectName(u"pushButton_31") self.pushButton_31.setMinimumSize(QSize(150, 0)) self.pushButton_31.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_35.addWidget(self.pushButton_31) self.pushButton_30 = QPushButton(self.tab_7) self.pushButton_30.setObjectName(u"pushButton_30") self.pushButton_30.setMinimumSize(QSize(150, 0)) self.pushButton_30.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_35.addWidget(self.pushButton_30) self.pushButton_33 = QPushButton(self.tab_7) self.pushButton_33.setObjectName(u"pushButton_33") self.pushButton_33.setMinimumSize(QSize(102, 0)) self.pushButton_33.setMaximumSize(QSize(102, 16777215)) self.pushButton_33.setFlat(True) self.horizontalLayout_35.addWidget(self.pushButton_33) self.verticalLayout_21.addLayout(self.horizontalLayout_35) self.tableWidget_4 = QTableWidget(self.tab_7) if (self.tableWidget_4.columnCount() < 9): self.tableWidget_4.setColumnCount(9) __qtablewidgetitem28 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(0, __qtablewidgetitem28) __qtablewidgetitem29 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(1, __qtablewidgetitem29) __qtablewidgetitem30 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(2, __qtablewidgetitem30) __qtablewidgetitem31 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(3, __qtablewidgetitem31) __qtablewidgetitem32 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(4, __qtablewidgetitem32) __qtablewidgetitem33 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(5, __qtablewidgetitem33) __qtablewidgetitem34 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(6, __qtablewidgetitem34) __qtablewidgetitem35 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(7, __qtablewidgetitem35) __qtablewidgetitem36 = QTableWidgetItem() self.tableWidget_4.setHorizontalHeaderItem(8, __qtablewidgetitem36) self.tableWidget_4.setObjectName(u"tableWidget_4") self.tableWidget_4.horizontalHeader().setVisible(False) self.tableWidget_4.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_21.addWidget(self.tableWidget_4) self.tabWidget_2.addTab(self.tab_7, "") self.tab_8 = QWidget() self.tab_8.setObjectName(u"tab_8") self.verticalLayout_20 = QVBoxLayout(self.tab_8) self.verticalLayout_20.setObjectName(u"verticalLayout_20") self.horizontalLayout_48 = QHBoxLayout() self.horizontalLayout_48.setObjectName(u"horizontalLayout_48") self.frame_8 = QFrame(self.tab_8) self.frame_8.setObjectName(u"frame_8") self.frame_8.setFrameShape(QFrame.NoFrame) self.frame_8.setFrameShadow(QFrame.Raised) self.verticalLayout_32 = QVBoxLayout(self.frame_8) self.verticalLayout_32.setSpacing(6) self.verticalLayout_32.setObjectName(u"verticalLayout_32") self.verticalLayout_32.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_11 = QHBoxLayout() self.horizontalLayout_11.setObjectName(u"horizontalLayout_11") self.lineEdit_5 = QLineEdit(self.frame_8) self.lineEdit_5.setObjectName(u"lineEdit_5") sizePolicy2.setHeightForWidth(self.lineEdit_5.sizePolicy().hasHeightForWidth()) self.lineEdit_5.setSizePolicy(sizePolicy2) self.lineEdit_5.setMinimumSize(QSize(200, 0)) self.lineEdit_5.setMaximumSize(QSize(200, 16777215)) self.horizontalLayout_11.addWidget(self.lineEdit_5) self.pushButton_11 = QPushButton(self.frame_8) self.pushButton_11.setObjectName(u"pushButton_11") self.pushButton_11.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_11.addWidget(self.pushButton_11) self.verticalLayout_32.addLayout(self.horizontalLayout_11) self.horizontalLayout_48.addWidget(self.frame_8, 0, Qt.AlignLeft) self.frame_29 = QFrame(self.tab_8) self.frame_29.setObjectName(u"frame_29") self.frame_29.setFrameShape(QFrame.StyledPanel) self.frame_29.setFrameShadow(QFrame.Raised) self.horizontalLayout_50 = QHBoxLayout(self.frame_29) self.horizontalLayout_50.setObjectName(u"horizontalLayout_50") self.horizontalLayout_50.setContentsMargins(0, 0, 0, 0) self.pushButton_25 = QPushButton(self.frame_29) self.pushButton_25.setObjectName(u"pushButton_25") self.pushButton_25.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_50.addWidget(self.pushButton_25, 0, Qt.AlignRight) self.horizontalLayout_48.addWidget(self.frame_29, 0, Qt.AlignRight) self.verticalLayout_20.addLayout(self.horizontalLayout_48) self.horizontalLayout_36 = QHBoxLayout() self.horizontalLayout_36.setSpacing(0) self.horizontalLayout_36.setObjectName(u"horizontalLayout_36") self.pushButton_37 = QPushButton(self.tab_8) self.pushButton_37.setObjectName(u"pushButton_37") self.horizontalLayout_36.addWidget(self.pushButton_37) self.pushButton_36 = QPushButton(self.tab_8) self.pushButton_36.setObjectName(u"pushButton_36") self.pushButton_36.setMinimumSize(QSize(100, 0)) self.pushButton_36.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_36.addWidget(self.pushButton_36) self.pushButton_35 = QPushButton(self.tab_8) self.pushButton_35.setObjectName(u"pushButton_35") self.pushButton_35.setMinimumSize(QSize(150, 0)) self.pushButton_35.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_36.addWidget(self.pushButton_35) self.pushButton_34 = QPushButton(self.tab_8) self.pushButton_34.setObjectName(u"pushButton_34") self.pushButton_34.setMinimumSize(QSize(150, 0)) self.pushButton_34.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_36.addWidget(self.pushButton_34) self.pushButton_40 = QPushButton(self.tab_8) self.pushButton_40.setObjectName(u"pushButton_40") self.pushButton_40.setMinimumSize(QSize(150, 0)) self.pushButton_40.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_36.addWidget(self.pushButton_40) self.pushButton_39 = QPushButton(self.tab_8) self.pushButton_39.setObjectName(u"pushButton_39") self.pushButton_39.setMinimumSize(QSize(150, 0)) self.pushButton_39.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_36.addWidget(self.pushButton_39) self.pushButton_38 = QPushButton(self.tab_8) self.pushButton_38.setObjectName(u"pushButton_38") self.pushButton_38.setMinimumSize(QSize(102, 0)) self.pushButton_38.setMaximumSize(QSize(102, 16777215)) self.pushButton_38.setFlat(True) self.horizontalLayout_36.addWidget(self.pushButton_38) self.verticalLayout_20.addLayout(self.horizontalLayout_36) self.tableWidget_5 = QTableWidget(self.tab_8) if (self.tableWidget_5.columnCount() < 9): self.tableWidget_5.setColumnCount(9) __qtablewidgetitem37 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(0, __qtablewidgetitem37) __qtablewidgetitem38 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(1, __qtablewidgetitem38) __qtablewidgetitem39 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(2, __qtablewidgetitem39) __qtablewidgetitem40 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(3, __qtablewidgetitem40) __qtablewidgetitem41 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(4, __qtablewidgetitem41) __qtablewidgetitem42 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(5, __qtablewidgetitem42) __qtablewidgetitem43 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(6, __qtablewidgetitem43) __qtablewidgetitem44 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(7, __qtablewidgetitem44) __qtablewidgetitem45 = QTableWidgetItem() self.tableWidget_5.setHorizontalHeaderItem(8, __qtablewidgetitem45) self.tableWidget_5.setObjectName(u"tableWidget_5") self.tableWidget_5.horizontalHeader().setVisible(False) self.tableWidget_5.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_20.addWidget(self.tableWidget_5) self.tabWidget_2.addTab(self.tab_8, "") self.tab_9 = QWidget() self.tab_9.setObjectName(u"tab_9") self.verticalLayout_19 = QVBoxLayout(self.tab_9) self.verticalLayout_19.setObjectName(u"verticalLayout_19") self.verticalLayout_27 = QVBoxLayout() self.verticalLayout_27.setObjectName(u"verticalLayout_27") self.frame_9 = QFrame(self.tab_9) self.frame_9.setObjectName(u"frame_9") self.frame_9.setFrameShape(QFrame.NoFrame) self.frame_9.setFrameShadow(QFrame.Raised) self.verticalLayout_30 = QVBoxLayout(self.frame_9) self.verticalLayout_30.setSpacing(6) self.verticalLayout_30.setObjectName(u"verticalLayout_30") self.verticalLayout_30.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_12 = QHBoxLayout() self.horizontalLayout_12.setObjectName(u"horizontalLayout_12") self.lineEdit_6 = QLineEdit(self.frame_9) self.lineEdit_6.setObjectName(u"lineEdit_6") self.lineEdit_6.setMinimumSize(QSize(200, 0)) self.horizontalLayout_12.addWidget(self.lineEdit_6) self.pushButton_12 = QPushButton(self.frame_9) self.pushButton_12.setObjectName(u"pushButton_12") self.horizontalLayout_12.addWidget(self.pushButton_12) self.verticalLayout_30.addLayout(self.horizontalLayout_12) self.verticalLayout_27.addWidget(self.frame_9, 0, Qt.AlignLeft) self.verticalLayout_19.addLayout(self.verticalLayout_27) self.horizontalLayout_46 = QHBoxLayout() self.horizontalLayout_46.setSpacing(0) self.horizontalLayout_46.setObjectName(u"horizontalLayout_46") self.pushButton_44 = QPushButton(self.tab_9) self.pushButton_44.setObjectName(u"pushButton_44") self.horizontalLayout_46.addWidget(self.pushButton_44) self.pushButton_43 = QPushButton(self.tab_9) self.pushButton_43.setObjectName(u"pushButton_43") self.pushButton_43.setMinimumSize(QSize(100, 0)) self.pushButton_43.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_46.addWidget(self.pushButton_43) self.pushButton_42 = QPushButton(self.tab_9) self.pushButton_42.setObjectName(u"pushButton_42") self.pushButton_42.setMinimumSize(QSize(150, 0)) self.pushButton_42.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_46.addWidget(self.pushButton_42) self.pushButton_41 = QPushButton(self.tab_9) self.pushButton_41.setObjectName(u"pushButton_41") self.pushButton_41.setMinimumSize(QSize(150, 0)) self.pushButton_41.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_46.addWidget(self.pushButton_41) self.pushButton_47 = QPushButton(self.tab_9) self.pushButton_47.setObjectName(u"pushButton_47") self.pushButton_47.setMinimumSize(QSize(150, 0)) self.pushButton_47.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_46.addWidget(self.pushButton_47) self.pushButton_46 = QPushButton(self.tab_9) self.pushButton_46.setObjectName(u"pushButton_46") self.pushButton_46.setMinimumSize(QSize(150, 0)) self.pushButton_46.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_46.addWidget(self.pushButton_46) self.pushButton_45 = QPushButton(self.tab_9) self.pushButton_45.setObjectName(u"pushButton_45") self.pushButton_45.setMinimumSize(QSize(32, 0)) self.pushButton_45.setMaximumSize(QSize(32, 16777215)) self.pushButton_45.setFlat(True) self.horizontalLayout_46.addWidget(self.pushButton_45) self.verticalLayout_19.addLayout(self.horizontalLayout_46) self.tableWidget_6 = QTableWidget(self.tab_9) if (self.tableWidget_6.columnCount() < 7): self.tableWidget_6.setColumnCount(7) __qtablewidgetitem46 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(0, __qtablewidgetitem46) __qtablewidgetitem47 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(1, __qtablewidgetitem47) __qtablewidgetitem48 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(2, __qtablewidgetitem48) __qtablewidgetitem49 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(3, __qtablewidgetitem49) __qtablewidgetitem50 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(4, __qtablewidgetitem50) __qtablewidgetitem51 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(5, __qtablewidgetitem51) __qtablewidgetitem52 = QTableWidgetItem() self.tableWidget_6.setHorizontalHeaderItem(6, __qtablewidgetitem52) self.tableWidget_6.setObjectName(u"tableWidget_6") self.tableWidget_6.horizontalHeader().setVisible(False) self.tableWidget_6.horizontalHeader().setMinimumSectionSize(16) self.verticalLayout_19.addWidget(self.tableWidget_6) self.tabWidget_2.addTab(self.tab_9, "") self.verticalLayout_17.addWidget(self.tabWidget_2) self.tabWidget.addTab(self.tab_5, "") self.tab_6 = QWidget() self.tab_6.setObjectName(u"tab_6") self.verticalLayout = QVBoxLayout(self.tab_6) self.verticalLayout.setObjectName(u"verticalLayout") self.tabWidget_3 = QTabWidget(self.tab_6) self.tabWidget_3.setObjectName(u"tabWidget_3") self.tab_10 = QWidget() self.tab_10.setObjectName(u"tab_10") self.verticalLayout_75 = QVBoxLayout(self.tab_10) self.verticalLayout_75.setObjectName(u"verticalLayout_75") self.verticalLayout_74 = QVBoxLayout() self.verticalLayout_74.setObjectName(u"verticalLayout_74") self.horizontalLayout_54 = QHBoxLayout() self.horizontalLayout_54.setObjectName(u"horizontalLayout_54") self.verticalLayout_77 = QVBoxLayout() self.verticalLayout_77.setObjectName(u"verticalLayout_77") self.groupBox_13 = QGroupBox(self.tab_10) self.groupBox_13.setObjectName(u"groupBox_13") self.verticalLayout_81 = QVBoxLayout(self.groupBox_13) self.verticalLayout_81.setObjectName(u"verticalLayout_81") self.frame_20 = QFrame(self.groupBox_13) self.frame_20.setObjectName(u"frame_20") self.frame_20.setFrameShape(QFrame.NoFrame) self.frame_20.setFrameShadow(QFrame.Raised) self.verticalLayout_90 = QVBoxLayout(self.frame_20) self.verticalLayout_90.setObjectName(u"verticalLayout_90") self.verticalLayout_90.setContentsMargins(0, 0, 0, 0) self.verticalLayout_89 = QVBoxLayout() self.verticalLayout_89.setObjectName(u"verticalLayout_89") self.horizontalLayout_62 = QHBoxLayout() self.horizontalLayout_62.setObjectName(u"horizontalLayout_62") self.label_33 = QLabel(self.frame_20) self.label_33.setObjectName(u"label_33") self.horizontalLayout_62.addWidget(self.label_33) self.lineEdit_17 = QLineEdit(self.frame_20) self.lineEdit_17.setObjectName(u"lineEdit_17") sizePolicy3.setHeightForWidth(self.lineEdit_17.sizePolicy().hasHeightForWidth()) self.lineEdit_17.setSizePolicy(sizePolicy3) self.lineEdit_17.setMinimumSize(QSize(0, 20)) self.horizontalLayout_62.addWidget(self.lineEdit_17) self.verticalLayout_89.addLayout(self.horizontalLayout_62) self.horizontalLayout_57 = QHBoxLayout() self.horizontalLayout_57.setObjectName(u"horizontalLayout_57") self.label_31 = QLabel(self.frame_20) self.label_31.setObjectName(u"label_31") self.horizontalLayout_57.addWidget(self.label_31) self.lineEdit_15 = QLineEdit(self.frame_20) self.lineEdit_15.setObjectName(u"lineEdit_15") sizePolicy3.setHeightForWidth(self.lineEdit_15.sizePolicy().hasHeightForWidth()) self.lineEdit_15.setSizePolicy(sizePolicy3) self.lineEdit_15.setMinimumSize(QSize(0, 20)) self.horizontalLayout_57.addWidget(self.lineEdit_15) self.verticalLayout_89.addLayout(self.horizontalLayout_57) self.horizontalLayout_61 = QHBoxLayout() self.horizontalLayout_61.setObjectName(u"horizontalLayout_61") self.label_32 = QLabel(self.frame_20) self.label_32.setObjectName(u"label_32") self.horizontalLayout_61.addWidget(self.label_32) self.lineEdit_16 = QLineEdit(self.frame_20) self.lineEdit_16.setObjectName(u"lineEdit_16") sizePolicy3.setHeightForWidth(self.lineEdit_16.sizePolicy().hasHeightForWidth()) self.lineEdit_16.setSizePolicy(sizePolicy3) self.lineEdit_16.setMinimumSize(QSize(0, 20)) self.horizontalLayout_61.addWidget(self.lineEdit_16) self.verticalLayout_89.addLayout(self.horizontalLayout_61) self.horizontalLayout_63 = QHBoxLayout() self.horizontalLayout_63.setObjectName(u"horizontalLayout_63") self.label_34 = QLabel(self.frame_20) self.label_34.setObjectName(u"label_34") self.horizontalLayout_63.addWidget(self.label_34) self.lineEdit_18 = QLineEdit(self.frame_20) self.lineEdit_18.setObjectName(u"lineEdit_18") sizePolicy3.setHeightForWidth(self.lineEdit_18.sizePolicy().hasHeightForWidth()) self.lineEdit_18.setSizePolicy(sizePolicy3) self.lineEdit_18.setMinimumSize(QSize(0, 20)) self.horizontalLayout_63.addWidget(self.lineEdit_18) self.verticalLayout_89.addLayout(self.horizontalLayout_63) self.horizontalLayout_56 = QHBoxLayout() self.horizontalLayout_56.setObjectName(u"horizontalLayout_56") self.label_35 = QLabel(self.frame_20) self.label_35.setObjectName(u"label_35") self.horizontalLayout_56.addWidget(self.label_35) self.lineEdit_13 = QLineEdit(self.frame_20) self.lineEdit_13.setObjectName(u"lineEdit_13") sizePolicy3.setHeightForWidth(self.lineEdit_13.sizePolicy().hasHeightForWidth()) self.lineEdit_13.setSizePolicy(sizePolicy3) self.lineEdit_13.setMinimumSize(QSize(0, 20)) self.horizontalLayout_56.addWidget(self.lineEdit_13) self.verticalLayout_89.addLayout(self.horizontalLayout_56) self.verticalLayout_80 = QVBoxLayout() self.verticalLayout_80.setObjectName(u"verticalLayout_80") self.horizontalLayout_55 = QHBoxLayout() self.horizontalLayout_55.setObjectName(u"horizontalLayout_55") self.label_30 = QLabel(self.frame_20) self.label_30.setObjectName(u"label_30") self.horizontalLayout_55.addWidget(self.label_30) self.lineEdit_14 = QLineEdit(self.frame_20) self.lineEdit_14.setObjectName(u"lineEdit_14") sizePolicy3.setHeightForWidth(self.lineEdit_14.sizePolicy().hasHeightForWidth()) self.lineEdit_14.setSizePolicy(sizePolicy3) self.lineEdit_14.setMinimumSize(QSize(0, 20)) self.horizontalLayout_55.addWidget(self.lineEdit_14) self.verticalLayout_80.addLayout(self.horizontalLayout_55) self.verticalLayout_89.addLayout(self.verticalLayout_80) self.verticalLayout_90.addLayout(self.verticalLayout_89) self.verticalLayout_81.addWidget(self.frame_20, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_77.addWidget(self.groupBox_13) self.horizontalLayout_54.addLayout(self.verticalLayout_77) self.verticalLayout_76 = QVBoxLayout() self.verticalLayout_76.setObjectName(u"verticalLayout_76") self.groupBox_16 = QGroupBox(self.tab_10) self.groupBox_16.setObjectName(u"groupBox_16") self.verticalLayout_86 = QVBoxLayout(self.groupBox_16) self.verticalLayout_86.setObjectName(u"verticalLayout_86") self.frame_21 = QFrame(self.groupBox_16) self.frame_21.setObjectName(u"frame_21") self.frame_21.setFrameShape(QFrame.NoFrame) self.frame_21.setFrameShadow(QFrame.Raised) self.verticalLayout_91 = QVBoxLayout(self.frame_21) self.verticalLayout_91.setObjectName(u"verticalLayout_91") self.verticalLayout_91.setContentsMargins(0, 0, 0, 0) self.verticalLayout_83 = QVBoxLayout() self.verticalLayout_83.setObjectName(u"verticalLayout_83") self.horizontalLayout_59 = QHBoxLayout() self.horizontalLayout_59.setObjectName(u"horizontalLayout_59") self.checkBox_4 = QCheckBox(self.frame_21) self.checkBox_4.setObjectName(u"checkBox_4") self.checkBox_4.setMinimumSize(QSize(0, 20)) self.horizontalLayout_59.addWidget(self.checkBox_4) self.verticalLayout_83.addLayout(self.horizontalLayout_59) self.horizontalLayout_60 = QHBoxLayout() self.horizontalLayout_60.setObjectName(u"horizontalLayout_60") self.checkBox_5 = QCheckBox(self.frame_21) self.checkBox_5.setObjectName(u"checkBox_5") self.checkBox_5.setMinimumSize(QSize(0, 20)) self.horizontalLayout_60.addWidget(self.checkBox_5) self.verticalLayout_83.addLayout(self.horizontalLayout_60) self.horizontalLayout_58 = QHBoxLayout() self.horizontalLayout_58.setObjectName(u"horizontalLayout_58") self.checkBox_6 = QCheckBox(self.frame_21) self.checkBox_6.setObjectName(u"checkBox_6") self.checkBox_6.setMinimumSize(QSize(0, 20)) self.horizontalLayout_58.addWidget(self.checkBox_6) self.verticalLayout_83.addLayout(self.horizontalLayout_58) self.horizontalLayout_64 = QHBoxLayout() self.horizontalLayout_64.setObjectName(u"horizontalLayout_64") self.checkBox_7 = QCheckBox(self.frame_21) self.checkBox_7.setObjectName(u"checkBox_7") self.checkBox_7.setMinimumSize(QSize(0, 20)) self.horizontalLayout_64.addWidget(self.checkBox_7) self.verticalLayout_83.addLayout(self.horizontalLayout_64) self.horizontalLayout_65 = QHBoxLayout() self.horizontalLayout_65.setObjectName(u"horizontalLayout_65") self.checkBox_8 = QCheckBox(self.frame_21) self.checkBox_8.setObjectName(u"checkBox_8") self.checkBox_8.setMinimumSize(QSize(0, 20)) self.horizontalLayout_65.addWidget(self.checkBox_8) self.verticalLayout_83.addLayout(self.horizontalLayout_65) self.verticalLayout_91.addLayout(self.verticalLayout_83) self.verticalLayout_86.addWidget(self.frame_21, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_76.addWidget(self.groupBox_16) self.horizontalLayout_54.addLayout(self.verticalLayout_76) self.verticalLayout_74.addLayout(self.horizontalLayout_54) self.horizontalLayout_53 = QHBoxLayout() self.horizontalLayout_53.setObjectName(u"horizontalLayout_53") self.verticalLayout_79 = QVBoxLayout() self.verticalLayout_79.setObjectName(u"verticalLayout_79") self.horizontalLayout_81 = QHBoxLayout() self.horizontalLayout_81.setObjectName(u"horizontalLayout_81") self.groupBox_21 = QGroupBox(self.tab_10) self.groupBox_21.setObjectName(u"groupBox_21") self.horizontalLayout_80 = QHBoxLayout(self.groupBox_21) self.horizontalLayout_80.setObjectName(u"horizontalLayout_80") self.frame_23 = QFrame(self.groupBox_21) self.frame_23.setObjectName(u"frame_23") self.frame_23.setFrameShape(QFrame.NoFrame) self.frame_23.setFrameShadow(QFrame.Raised) self.horizontalLayout_79 = QHBoxLayout(self.frame_23) self.horizontalLayout_79.setObjectName(u"horizontalLayout_79") self.horizontalLayout_79.setContentsMargins(0, 0, 0, 0) self.verticalLayout_57 = QVBoxLayout() self.verticalLayout_57.setObjectName(u"verticalLayout_57") self.horizontalLayout_38 = QHBoxLayout() self.horizontalLayout_38.setObjectName(u"horizontalLayout_38") self.frame_16 = QFrame(self.frame_23) self.frame_16.setObjectName(u"frame_16") self.frame_16.setFrameShape(QFrame.NoFrame) self.frame_16.setFrameShadow(QFrame.Raised) self.horizontalLayout_43 = QHBoxLayout(self.frame_16) self.horizontalLayout_43.setObjectName(u"horizontalLayout_43") self.horizontalLayout_43.setContentsMargins(0, 0, 0, 0) self.label_22 = QLabel(self.frame_16) self.label_22.setObjectName(u"label_22") self.label_22.setMinimumSize(QSize(100, 0)) self.label_22.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_43.addWidget(self.label_22) self.lineEdit_12 = QLineEdit(self.frame_16) self.lineEdit_12.setObjectName(u"lineEdit_12") sizePolicy3.setHeightForWidth(self.lineEdit_12.sizePolicy().hasHeightForWidth()) self.lineEdit_12.setSizePolicy(sizePolicy3) self.lineEdit_12.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_43.addWidget(self.lineEdit_12) self.horizontalLayout_38.addWidget(self.frame_16, 0, Qt.AlignLeft) self.verticalLayout_57.addLayout(self.horizontalLayout_38) self.horizontalLayout_41 = QHBoxLayout() self.horizontalLayout_41.setObjectName(u"horizontalLayout_41") self.frame_15 = QFrame(self.frame_23) self.frame_15.setObjectName(u"frame_15") self.frame_15.setFrameShape(QFrame.NoFrame) self.frame_15.setFrameShadow(QFrame.Raised) self.horizontalLayout_42 = QHBoxLayout(self.frame_15) self.horizontalLayout_42.setObjectName(u"horizontalLayout_42") self.horizontalLayout_42.setContentsMargins(0, 0, 0, 0) self.label_23 = QLabel(self.frame_15) self.label_23.setObjectName(u"label_23") self.label_23.setMinimumSize(QSize(100, 0)) self.label_23.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_42.addWidget(self.label_23) self.lineEdit_11 = QLineEdit(self.frame_15) self.lineEdit_11.setObjectName(u"lineEdit_11") sizePolicy3.setHeightForWidth(self.lineEdit_11.sizePolicy().hasHeightForWidth()) self.lineEdit_11.setSizePolicy(sizePolicy3) self.lineEdit_11.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_42.addWidget(self.lineEdit_11) self.horizontalLayout_41.addWidget(self.frame_15, 0, Qt.AlignLeft) self.verticalLayout_57.addLayout(self.horizontalLayout_41) self.horizontalLayout_40 = QHBoxLayout() self.horizontalLayout_40.setObjectName(u"horizontalLayout_40") self.frame_18 = QFrame(self.frame_23) self.frame_18.setObjectName(u"frame_18") self.frame_18.setFrameShape(QFrame.NoFrame) self.frame_18.setFrameShadow(QFrame.Raised) self.horizontalLayout_44 = QHBoxLayout(self.frame_18) self.horizontalLayout_44.setObjectName(u"horizontalLayout_44") self.horizontalLayout_44.setContentsMargins(0, 0, 0, 0) self.checkBox_3 = QCheckBox(self.frame_18) self.checkBox_3.setObjectName(u"checkBox_3") self.checkBox_3.setLayoutDirection(Qt.LeftToRight) self.horizontalLayout_44.addWidget(self.checkBox_3) self.horizontalLayout_40.addWidget(self.frame_18) self.verticalLayout_57.addLayout(self.horizontalLayout_40) self.horizontalLayout_39 = QHBoxLayout() self.horizontalLayout_39.setObjectName(u"horizontalLayout_39") self.frame_17 = QFrame(self.frame_23) self.frame_17.setObjectName(u"frame_17") self.frame_17.setFrameShape(QFrame.NoFrame) self.frame_17.setFrameShadow(QFrame.Raised) self.horizontalLayout_45 = QHBoxLayout(self.frame_17) self.horizontalLayout_45.setObjectName(u"horizontalLayout_45") self.horizontalLayout_45.setContentsMargins(0, 0, 0, 0) self.checkBox_2 = QCheckBox(self.frame_17) self.checkBox_2.setObjectName(u"checkBox_2") self.checkBox_2.setLayoutDirection(Qt.LeftToRight) self.horizontalLayout_45.addWidget(self.checkBox_2) self.horizontalLayout_39.addWidget(self.frame_17, 0, Qt.AlignLeft) self.verticalLayout_57.addLayout(self.horizontalLayout_39) self.horizontalLayout_79.addLayout(self.verticalLayout_57) self.horizontalLayout_80.addWidget(self.frame_23, 0, Qt.AlignLeft) self.horizontalLayout_81.addWidget(self.groupBox_21) self.groupBox_8 = QGroupBox(self.tab_10) self.groupBox_8.setObjectName(u"groupBox_8") self.verticalLayout_55 = QVBoxLayout(self.groupBox_8) self.verticalLayout_55.setObjectName(u"verticalLayout_55") self.verticalLayout_54 = QVBoxLayout() self.verticalLayout_54.setObjectName(u"verticalLayout_54") self.horizontalLayout_84 = QHBoxLayout() self.horizontalLayout_84.setObjectName(u"horizontalLayout_84") self.frame_33 = QFrame(self.groupBox_8) self.frame_33.setObjectName(u"frame_33") sizePolicy1.setHeightForWidth(self.frame_33.sizePolicy().hasHeightForWidth()) self.frame_33.setSizePolicy(sizePolicy1) self.frame_33.setFrameShape(QFrame.NoFrame) self.frame_33.setFrameShadow(QFrame.Raised) self.horizontalLayout_88 = QHBoxLayout(self.frame_33) self.horizontalLayout_88.setObjectName(u"horizontalLayout_88") self.horizontalLayout_88.setContentsMargins(0, 0, 0, 0) self.label_39 = QLabel(self.frame_33) self.label_39.setObjectName(u"label_39") self.label_39.setMinimumSize(QSize(150, 0)) self.label_39.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_88.addWidget(self.label_39) self.lineEdit_23 = QLineEdit(self.frame_33) self.lineEdit_23.setObjectName(u"lineEdit_23") self.lineEdit_23.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_88.addWidget(self.lineEdit_23) self.horizontalLayout_84.addWidget(self.frame_33, 0, Qt.AlignLeft) self.verticalLayout_54.addLayout(self.horizontalLayout_84) self.horizontalLayout_85 = QHBoxLayout() self.horizontalLayout_85.setObjectName(u"horizontalLayout_85") self.frame_34 = QFrame(self.groupBox_8) self.frame_34.setObjectName(u"frame_34") self.frame_34.setFrameShape(QFrame.NoFrame) self.frame_34.setFrameShadow(QFrame.Raised) self.horizontalLayout_89 = QHBoxLayout(self.frame_34) self.horizontalLayout_89.setObjectName(u"horizontalLayout_89") self.horizontalLayout_89.setContentsMargins(0, 0, 0, 0) self.label_40 = QLabel(self.frame_34) self.label_40.setObjectName(u"label_40") self.label_40.setMinimumSize(QSize(150, 0)) self.label_40.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_89.addWidget(self.label_40) self.lineEdit_24 = QLineEdit(self.frame_34) self.lineEdit_24.setObjectName(u"lineEdit_24") self.lineEdit_24.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_89.addWidget(self.lineEdit_24) self.horizontalLayout_85.addWidget(self.frame_34, 0, Qt.AlignLeft) self.verticalLayout_54.addLayout(self.horizontalLayout_85) self.horizontalLayout_86 = QHBoxLayout() self.horizontalLayout_86.setObjectName(u"horizontalLayout_86") self.frame_35 = QFrame(self.groupBox_8) self.frame_35.setObjectName(u"frame_35") self.frame_35.setFrameShape(QFrame.NoFrame) self.frame_35.setFrameShadow(QFrame.Raised) self.horizontalLayout_90 = QHBoxLayout(self.frame_35) self.horizontalLayout_90.setObjectName(u"horizontalLayout_90") self.horizontalLayout_90.setContentsMargins(0, 0, 0, 0) self.label_45 = QLabel(self.frame_35) self.label_45.setObjectName(u"label_45") self.label_45.setEnabled(True) self.label_45.setMinimumSize(QSize(150, 0)) self.label_45.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_90.addWidget(self.label_45) self.lineEdit_25 = QLineEdit(self.frame_35) self.lineEdit_25.setObjectName(u"lineEdit_25") self.lineEdit_25.setEnabled(False) self.lineEdit_25.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_90.addWidget(self.lineEdit_25) self.horizontalLayout_86.addWidget(self.frame_35, 0, Qt.AlignLeft) self.verticalLayout_54.addLayout(self.horizontalLayout_86) self.horizontalLayout_37 = QHBoxLayout() self.horizontalLayout_37.setObjectName(u"horizontalLayout_37") self.frame_36 = QFrame(self.groupBox_8) self.frame_36.setObjectName(u"frame_36") self.frame_36.setFrameShape(QFrame.NoFrame) self.frame_36.setFrameShadow(QFrame.Raised) self.horizontalLayout_87 = QHBoxLayout(self.frame_36) self.horizontalLayout_87.setObjectName(u"horizontalLayout_87") self.horizontalLayout_87.setContentsMargins(0, 0, 0, 0) self.label_46 = QLabel(self.frame_36) self.label_46.setObjectName(u"label_46") self.label_46.setMinimumSize(QSize(150, 0)) self.label_46.setMaximumSize(QSize(150, 16777215)) self.horizontalLayout_87.addWidget(self.label_46) self.lineEdit_26 = QLineEdit(self.frame_36) self.lineEdit_26.setObjectName(u"lineEdit_26") self.lineEdit_26.setEnabled(False) self.lineEdit_26.setMaximumSize(QSize(100, 16777215)) self.horizontalLayout_87.addWidget(self.lineEdit_26) self.horizontalLayout_37.addWidget(self.frame_36, 0, Qt.AlignLeft) self.verticalLayout_54.addLayout(self.horizontalLayout_37) self.verticalLayout_55.addLayout(self.verticalLayout_54) self.horizontalLayout_81.addWidget(self.groupBox_8) self.verticalLayout_79.addLayout(self.horizontalLayout_81) self.groupBox_14 = QGroupBox(self.tab_10) self.groupBox_14.setObjectName(u"groupBox_14") self.verticalLayout_85 = QVBoxLayout(self.groupBox_14) self.verticalLayout_85.setObjectName(u"verticalLayout_85") self.verticalLayout_82 = QVBoxLayout() self.verticalLayout_82.setObjectName(u"verticalLayout_82") self.frame_22 = QFrame(self.groupBox_14) self.frame_22.setObjectName(u"frame_22") self.frame_22.setFrameShape(QFrame.NoFrame) self.frame_22.setFrameShadow(QFrame.Raised) self.verticalLayout_92 = QVBoxLayout(self.frame_22) self.verticalLayout_92.setObjectName(u"verticalLayout_92") self.verticalLayout_92.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_72 = QHBoxLayout() self.horizontalLayout_72.setObjectName(u"horizontalLayout_72") self.pushButton_6 = QPushButton(self.frame_22) self.pushButton_6.setObjectName(u"pushButton_6") self.pushButton_6.setMinimumSize(QSize(160, 30)) self.horizontalLayout_72.addWidget(self.pushButton_6) self.pushButton_13 = QPushButton(self.frame_22) self.pushButton_13.setObjectName(u"pushButton_13") self.pushButton_13.setMinimumSize(QSize(160, 30)) self.pushButton_13.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_72.addWidget(self.pushButton_13) self.verticalLayout_92.addLayout(self.horizontalLayout_72) self.verticalLayout_82.addWidget(self.frame_22, 0, Qt.AlignBottom) self.progressBar_3 = QProgressBar(self.groupBox_14) self.progressBar_3.setObjectName(u"progressBar_3") sizePolicy4 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy4.setHorizontalStretch(0) sizePolicy4.setVerticalStretch(0) sizePolicy4.setHeightForWidth(self.progressBar_3.sizePolicy().hasHeightForWidth()) self.progressBar_3.setSizePolicy(sizePolicy4) self.progressBar_3.setAlignment(Qt.AlignCenter) self.verticalLayout_82.addWidget(self.progressBar_3) self.verticalLayout_85.addLayout(self.verticalLayout_82) self.verticalLayout_79.addWidget(self.groupBox_14) self.horizontalLayout_53.addLayout(self.verticalLayout_79) self.verticalLayout_78 = QVBoxLayout() self.verticalLayout_78.setObjectName(u"verticalLayout_78") self.groupBox_15 = QGroupBox(self.tab_10) self.groupBox_15.setObjectName(u"groupBox_15") self.groupBox_15.setEnabled(False) self.verticalLayout_87 = QVBoxLayout(self.groupBox_15) self.verticalLayout_87.setObjectName(u"verticalLayout_87") self.frame_19 = QFrame(self.groupBox_15) self.frame_19.setObjectName(u"frame_19") self.frame_19.setFrameShape(QFrame.NoFrame) self.frame_19.setFrameShadow(QFrame.Raised) self.verticalLayout_88 = QVBoxLayout(self.frame_19) self.verticalLayout_88.setSpacing(6) self.verticalLayout_88.setObjectName(u"verticalLayout_88") self.verticalLayout_88.setContentsMargins(0, 0, 0, 0) self.verticalLayout_84 = QVBoxLayout() self.verticalLayout_84.setObjectName(u"verticalLayout_84") self.horizontalLayout_67 = QHBoxLayout() self.horizontalLayout_67.setObjectName(u"horizontalLayout_67") self.label_41 = QLabel(self.frame_19) self.label_41.setObjectName(u"label_41") self.label_41.setMinimumSize(QSize(0, 0)) self.label_41.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_67.addWidget(self.label_41) self.lineEdit_19 = QLineEdit(self.frame_19) self.lineEdit_19.setObjectName(u"lineEdit_19") sizePolicy3.setHeightForWidth(self.lineEdit_19.sizePolicy().hasHeightForWidth()) self.lineEdit_19.setSizePolicy(sizePolicy3) self.lineEdit_19.setMinimumSize(QSize(0, 25)) self.horizontalLayout_67.addWidget(self.lineEdit_19) self.verticalLayout_84.addLayout(self.horizontalLayout_67) self.horizontalLayout_71 = QHBoxLayout() self.horizontalLayout_71.setObjectName(u"horizontalLayout_71") self.label_42 = QLabel(self.frame_19) self.label_42.setObjectName(u"label_42") self.label_42.setMinimumSize(QSize(100, 0)) self.label_42.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_71.addWidget(self.label_42) self.lineEdit_20 = QLineEdit(self.frame_19) self.lineEdit_20.setObjectName(u"lineEdit_20") sizePolicy3.setHeightForWidth(self.lineEdit_20.sizePolicy().hasHeightForWidth()) self.lineEdit_20.setSizePolicy(sizePolicy3) self.lineEdit_20.setMinimumSize(QSize(0, 25)) self.horizontalLayout_71.addWidget(self.lineEdit_20) self.verticalLayout_84.addLayout(self.horizontalLayout_71) self.horizontalLayout_70 = QHBoxLayout() self.horizontalLayout_70.setObjectName(u"horizontalLayout_70") self.label_43 = QLabel(self.frame_19) self.label_43.setObjectName(u"label_43") self.label_43.setMinimumSize(QSize(100, 0)) self.label_43.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_70.addWidget(self.label_43) self.lineEdit_21 = QLineEdit(self.frame_19) self.lineEdit_21.setObjectName(u"lineEdit_21") sizePolicy3.setHeightForWidth(self.lineEdit_21.sizePolicy().hasHeightForWidth()) self.lineEdit_21.setSizePolicy(sizePolicy3) self.lineEdit_21.setMinimumSize(QSize(0, 25)) self.horizontalLayout_70.addWidget(self.lineEdit_21) self.verticalLayout_84.addLayout(self.horizontalLayout_70) self.horizontalLayout_68 = QHBoxLayout() self.horizontalLayout_68.setObjectName(u"horizontalLayout_68") self.label_44 = QLabel(self.frame_19) self.label_44.setObjectName(u"label_44") self.label_44.setMinimumSize(QSize(100, 0)) self.label_44.setMaximumSize(QSize(16777215, 16777215)) self.horizontalLayout_68.addWidget(self.label_44) self.lineEdit_22 = QLineEdit(self.frame_19) self.lineEdit_22.setObjectName(u"lineEdit_22") sizePolicy3.setHeightForWidth(self.lineEdit_22.sizePolicy().hasHeightForWidth()) self.lineEdit_22.setSizePolicy(sizePolicy3) self.lineEdit_22.setMinimumSize(QSize(0, 25)) self.horizontalLayout_68.addWidget(self.lineEdit_22) self.verticalLayout_84.addLayout(self.horizontalLayout_68) self.horizontalLayout_69 = QHBoxLayout() self.horizontalLayout_69.setObjectName(u"horizontalLayout_69") self.checkBox_10 = QCheckBox(self.frame_19) self.checkBox_10.setObjectName(u"checkBox_10") self.horizontalLayout_69.addWidget(self.checkBox_10) self.checkBox_9 = QCheckBox(self.frame_19) self.checkBox_9.setObjectName(u"checkBox_9") self.horizontalLayout_69.addWidget(self.checkBox_9) self.checkBox_11 = QCheckBox(self.frame_19) self.checkBox_11.setObjectName(u"checkBox_11") self.horizontalLayout_69.addWidget(self.checkBox_11) self.verticalLayout_84.addLayout(self.horizontalLayout_69) self.horizontalLayout_66 = QHBoxLayout() self.horizontalLayout_66.setObjectName(u"horizontalLayout_66") self.verticalLayout_84.addLayout(self.horizontalLayout_66) self.verticalLayout_88.addLayout(self.verticalLayout_84) self.verticalLayout_87.addWidget(self.frame_19, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_78.addWidget(self.groupBox_15) self.horizontalLayout_53.addLayout(self.verticalLayout_78) self.verticalLayout_74.addLayout(self.horizontalLayout_53) self.verticalLayout_75.addLayout(self.verticalLayout_74) self.horizontalLayout_33 = QHBoxLayout() self.horizontalLayout_33.setObjectName(u"horizontalLayout_33") self.label_27 = QLabel(self.tab_10) self.label_27.setObjectName(u"label_27") self.horizontalLayout_33.addWidget(self.label_27) self.pushButton_21 = QPushButton(self.tab_10) self.pushButton_21.setObjectName(u"pushButton_21") self.pushButton_21.setMaximumSize(QSize(75, 16777215)) self.horizontalLayout_33.addWidget(self.pushButton_21) self.verticalLayout_75.addLayout(self.horizontalLayout_33) self.tabWidget_3.addTab(self.tab_10, "") self.tab_12 = QWidget() self.tab_12.setObjectName(u"tab_12") self.verticalLayout_40 = QVBoxLayout(self.tab_12) self.verticalLayout_40.setObjectName(u"verticalLayout_40") self.verticalLayout_39 = QVBoxLayout() self.verticalLayout_39.setObjectName(u"verticalLayout_39") self.horizontalLayout_15 = QHBoxLayout() self.horizontalLayout_15.setObjectName(u"horizontalLayout_15") self.verticalLayout_42 = QVBoxLayout() self.verticalLayout_42.setObjectName(u"verticalLayout_42") self.groupBox_4 = QGroupBox(self.tab_12) self.groupBox_4.setObjectName(u"groupBox_4") self.verticalLayout_46 = QVBoxLayout(self.groupBox_4) self.verticalLayout_46.setObjectName(u"verticalLayout_46") self.frame_24 = QFrame(self.groupBox_4) self.frame_24.setObjectName(u"frame_24") self.frame_24.setFrameShape(QFrame.NoFrame) self.frame_24.setFrameShadow(QFrame.Raised) self.verticalLayout_96 = QVBoxLayout(self.frame_24) self.verticalLayout_96.setObjectName(u"verticalLayout_96") self.verticalLayout_45 = QVBoxLayout() self.verticalLayout_45.setObjectName(u"verticalLayout_45") self.horizontalLayout_21 = QHBoxLayout() self.horizontalLayout_21.setObjectName(u"horizontalLayout_21") self.pushButton_18 = QPushButton(self.frame_24) self.pushButton_18.setObjectName(u"pushButton_18") self.pushButton_18.setMinimumSize(QSize(210, 30)) self.pushButton_18.setMaximumSize(QSize(210, 16777215)) self.horizontalLayout_21.addWidget(self.pushButton_18) self.label_13 = QLabel(self.frame_24) self.label_13.setObjectName(u"label_13") self.label_13.setMinimumSize(QSize(200, 0)) self.horizontalLayout_21.addWidget(self.label_13) self.verticalLayout_45.addLayout(self.horizontalLayout_21) self.horizontalLayout_20 = QHBoxLayout() self.horizontalLayout_20.setObjectName(u"horizontalLayout_20") self.pushButton_17 = QPushButton(self.frame_24) self.pushButton_17.setObjectName(u"pushButton_17") self.pushButton_17.setMinimumSize(QSize(210, 30)) self.pushButton_17.setMaximumSize(QSize(210, 16777215)) self.horizontalLayout_20.addWidget(self.pushButton_17) self.label_12 = QLabel(self.frame_24) self.label_12.setObjectName(u"label_12") self.label_12.setMinimumSize(QSize(200, 0)) self.horizontalLayout_20.addWidget(self.label_12) self.verticalLayout_45.addLayout(self.horizontalLayout_20) self.horizontalLayout_19 = QHBoxLayout() self.horizontalLayout_19.setObjectName(u"horizontalLayout_19") self.pushButton_16 = QPushButton(self.frame_24) self.pushButton_16.setObjectName(u"pushButton_16") self.pushButton_16.setMinimumSize(QSize(210, 30)) self.pushButton_16.setMaximumSize(QSize(210, 16777215)) self.horizontalLayout_19.addWidget(self.pushButton_16) self.label_11 = QLabel(self.frame_24) self.label_11.setObjectName(u"label_11") self.label_11.setMinimumSize(QSize(200, 0)) self.horizontalLayout_19.addWidget(self.label_11) self.verticalLayout_45.addLayout(self.horizontalLayout_19) self.horizontalLayout_18 = QHBoxLayout() self.horizontalLayout_18.setObjectName(u"horizontalLayout_18") self.pushButton_15 = QPushButton(self.frame_24) self.pushButton_15.setObjectName(u"pushButton_15") self.pushButton_15.setMinimumSize(QSize(210, 30)) self.pushButton_15.setMaximumSize(QSize(210, 16777215)) self.horizontalLayout_18.addWidget(self.pushButton_15) self.label_10 = QLabel(self.frame_24) self.label_10.setObjectName(u"label_10") self.label_10.setMinimumSize(QSize(200, 0)) self.horizontalLayout_18.addWidget(self.label_10) self.verticalLayout_45.addLayout(self.horizontalLayout_18) self.horizontalLayout_17 = QHBoxLayout() self.horizontalLayout_17.setObjectName(u"horizontalLayout_17") self.pushButton_14 = QPushButton(self.frame_24) self.pushButton_14.setObjectName(u"pushButton_14") self.pushButton_14.setMinimumSize(QSize(210, 30)) self.pushButton_14.setMaximumSize(QSize(210, 16777215)) self.horizontalLayout_17.addWidget(self.pushButton_14) self.label_9 = QLabel(self.frame_24) self.label_9.setObjectName(u"label_9") self.label_9.setMinimumSize(QSize(200, 0)) self.horizontalLayout_17.addWidget(self.label_9) self.verticalLayout_45.addLayout(self.horizontalLayout_17) self.verticalLayout_96.addLayout(self.verticalLayout_45) self.verticalLayout_46.addWidget(self.frame_24, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_42.addWidget(self.groupBox_4) self.horizontalLayout_15.addLayout(self.verticalLayout_42) self.verticalLayout_41 = QVBoxLayout() self.verticalLayout_41.setObjectName(u"verticalLayout_41") self.groupBox_7 = QGroupBox(self.tab_12) self.groupBox_7.setObjectName(u"groupBox_7") self.verticalLayout_52 = QVBoxLayout(self.groupBox_7) self.verticalLayout_52.setObjectName(u"verticalLayout_52") self.frame_26 = QFrame(self.groupBox_7) self.frame_26.setObjectName(u"frame_26") self.frame_26.setFrameShape(QFrame.NoFrame) self.frame_26.setFrameShadow(QFrame.Raised) self.verticalLayout_99 = QVBoxLayout(self.frame_26) self.verticalLayout_99.setObjectName(u"verticalLayout_99") self.verticalLayout_99.setContentsMargins(0, 0, 0, 0) self.verticalLayout_51 = QVBoxLayout() self.verticalLayout_51.setObjectName(u"verticalLayout_51") self.horizontalLayout_27 = QHBoxLayout() self.horizontalLayout_27.setObjectName(u"horizontalLayout_27") self.checkBox = QCheckBox(self.frame_26) self.checkBox.setObjectName(u"checkBox") self.checkBox.setMaximumSize(QSize(200, 16777215)) self.horizontalLayout_27.addWidget(self.checkBox) self.verticalLayout_51.addLayout(self.horizontalLayout_27) self.horizontalLayout_26 = QHBoxLayout() self.horizontalLayout_26.setObjectName(u"horizontalLayout_26") self.label_16 = QLabel(self.frame_26) self.label_16.setObjectName(u"label_16") self.label_16.setMaximumSize(QSize(50, 16777215)) self.horizontalLayout_26.addWidget(self.label_16) self.lineEdit_7 = QLineEdit(self.frame_26) self.lineEdit_7.setObjectName(u"lineEdit_7") sizePolicy3.setHeightForWidth(self.lineEdit_7.sizePolicy().hasHeightForWidth()) self.lineEdit_7.setSizePolicy(sizePolicy3) self.lineEdit_7.setMaximumSize(QSize(200, 20)) self.horizontalLayout_26.addWidget(self.lineEdit_7) self.verticalLayout_51.addLayout(self.horizontalLayout_26) self.horizontalLayout_25 = QHBoxLayout() self.horizontalLayout_25.setObjectName(u"horizontalLayout_25") self.label_17 = QLabel(self.frame_26) self.label_17.setObjectName(u"label_17") self.label_17.setMaximumSize(QSize(50, 16777215)) self.horizontalLayout_25.addWidget(self.label_17) self.lineEdit_8 = QLineEdit(self.frame_26) self.lineEdit_8.setObjectName(u"lineEdit_8") sizePolicy3.setHeightForWidth(self.lineEdit_8.sizePolicy().hasHeightForWidth()) self.lineEdit_8.setSizePolicy(sizePolicy3) self.lineEdit_8.setMaximumSize(QSize(200, 20)) self.horizontalLayout_25.addWidget(self.lineEdit_8) self.verticalLayout_51.addLayout(self.horizontalLayout_25) self.horizontalLayout_24 = QHBoxLayout() self.horizontalLayout_24.setObjectName(u"horizontalLayout_24") self.label_18 = QLabel(self.frame_26) self.label_18.setObjectName(u"label_18") self.label_18.setMaximumSize(QSize(50, 16777215)) self.horizontalLayout_24.addWidget(self.label_18) self.lineEdit_9 = QLineEdit(self.frame_26) self.lineEdit_9.setObjectName(u"lineEdit_9") sizePolicy3.setHeightForWidth(self.lineEdit_9.sizePolicy().hasHeightForWidth()) self.lineEdit_9.setSizePolicy(sizePolicy3) self.lineEdit_9.setMaximumSize(QSize(200, 20)) self.horizontalLayout_24.addWidget(self.lineEdit_9) self.verticalLayout_51.addLayout(self.horizontalLayout_24) self.horizontalLayout_23 = QHBoxLayout() self.horizontalLayout_23.setObjectName(u"horizontalLayout_23") self.label_19 = QLabel(self.frame_26) self.label_19.setObjectName(u"label_19") self.label_19.setMaximumSize(QSize(50, 16777215)) self.horizontalLayout_23.addWidget(self.label_19) self.lineEdit_10 = QLineEdit(self.frame_26) self.lineEdit_10.setObjectName(u"lineEdit_10") sizePolicy3.setHeightForWidth(self.lineEdit_10.sizePolicy().hasHeightForWidth()) self.lineEdit_10.setSizePolicy(sizePolicy3) self.lineEdit_10.setMaximumSize(QSize(200, 20)) self.horizontalLayout_23.addWidget(self.lineEdit_10) self.verticalLayout_51.addLayout(self.horizontalLayout_23) self.verticalLayout_99.addLayout(self.verticalLayout_51) self.verticalLayout_52.addWidget(self.frame_26, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_41.addWidget(self.groupBox_7) self.horizontalLayout_15.addLayout(self.verticalLayout_41) self.verticalLayout_39.addLayout(self.horizontalLayout_15) self.horizontalLayout_16 = QHBoxLayout() self.horizontalLayout_16.setObjectName(u"horizontalLayout_16") self.verticalLayout_44 = QVBoxLayout() self.verticalLayout_44.setObjectName(u"verticalLayout_44") self.groupBox_5 = QGroupBox(self.tab_12) self.groupBox_5.setObjectName(u"groupBox_5") self.groupBox_5.setEnabled(True) self.verticalLayout_50 = QVBoxLayout(self.groupBox_5) self.verticalLayout_50.setObjectName(u"verticalLayout_50") self.frame_25 = QFrame(self.groupBox_5) self.frame_25.setObjectName(u"frame_25") self.frame_25.setFrameShape(QFrame.NoFrame) self.frame_25.setFrameShadow(QFrame.Raised) self.verticalLayout_97 = QVBoxLayout(self.frame_25) self.verticalLayout_97.setObjectName(u"verticalLayout_97") self.verticalLayout_49 = QVBoxLayout() self.verticalLayout_49.setObjectName(u"verticalLayout_49") self.horizontalLayout_32 = QHBoxLayout() self.horizontalLayout_32.setObjectName(u"horizontalLayout_32") self.checkBox_12 = QCheckBox(self.frame_25) self.checkBox_12.setObjectName(u"checkBox_12") self.checkBox_12.setMinimumSize(QSize(0, 20)) self.horizontalLayout_32.addWidget(self.checkBox_12) self.verticalLayout_49.addLayout(self.horizontalLayout_32) self.horizontalLayout_31 = QHBoxLayout() self.horizontalLayout_31.setObjectName(u"horizontalLayout_31") self.checkBox_13 = QCheckBox(self.frame_25) self.checkBox_13.setObjectName(u"checkBox_13") self.checkBox_13.setMinimumSize(QSize(0, 20)) self.horizontalLayout_31.addWidget(self.checkBox_13) self.verticalLayout_49.addLayout(self.horizontalLayout_31) self.horizontalLayout_30 = QHBoxLayout() self.horizontalLayout_30.setObjectName(u"horizontalLayout_30") self.verticalLayout_49.addLayout(self.horizontalLayout_30) self.horizontalLayout_29 = QHBoxLayout() self.horizontalLayout_29.setObjectName(u"horizontalLayout_29") self.verticalLayout_49.addLayout(self.horizontalLayout_29) self.horizontalLayout_28 = QHBoxLayout() self.horizontalLayout_28.setObjectName(u"horizontalLayout_28") self.verticalLayout_49.addLayout(self.horizontalLayout_28) self.verticalLayout_97.addLayout(self.verticalLayout_49) self.verticalLayout_50.addWidget(self.frame_25, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_44.addWidget(self.groupBox_5) self.groupBox_6 = QGroupBox(self.tab_12) self.groupBox_6.setObjectName(u"groupBox_6") self.groupBox_6.setEnabled(False) self.verticalLayout_48 = QVBoxLayout(self.groupBox_6) self.verticalLayout_48.setObjectName(u"verticalLayout_48") self.frame_27 = QFrame(self.groupBox_6) self.frame_27.setObjectName(u"frame_27") self.frame_27.setMinimumSize(QSize(400, 0)) self.frame_27.setFrameShape(QFrame.NoFrame) self.frame_27.setFrameShadow(QFrame.Raised) self.verticalLayout_98 = QVBoxLayout(self.frame_27) self.verticalLayout_98.setObjectName(u"verticalLayout_98") self.verticalLayout_98.setContentsMargins(0, 0, 0, 0) self.verticalLayout_47 = QVBoxLayout() self.verticalLayout_47.setObjectName(u"verticalLayout_47") self.horizontalLayout_22 = QHBoxLayout() self.horizontalLayout_22.setObjectName(u"horizontalLayout_22") self.label_14 = QLabel(self.frame_27) self.label_14.setObjectName(u"label_14") self.label_14.setMinimumSize(QSize(0, 20)) self.horizontalLayout_22.addWidget(self.label_14, 0, Qt.AlignHCenter) self.radioButton_2 = QRadioButton(self.frame_27) self.radioButton_2.setObjectName(u"radioButton_2") self.radioButton_2.setMinimumSize(QSize(0, 20)) self.horizontalLayout_22.addWidget(self.radioButton_2, 0, Qt.AlignHCenter) self.radioButton = QRadioButton(self.frame_27) self.radioButton.setObjectName(u"radioButton") self.radioButton.setMinimumSize(QSize(0, 20)) self.horizontalLayout_22.addWidget(self.radioButton, 0, Qt.AlignHCenter) self.verticalLayout_47.addLayout(self.horizontalLayout_22) self.verticalLayout_98.addLayout(self.verticalLayout_47) self.verticalLayout_48.addWidget(self.frame_27, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_44.addWidget(self.groupBox_6) self.horizontalLayout_16.addLayout(self.verticalLayout_44) self.verticalLayout_43 = QVBoxLayout() self.verticalLayout_43.setObjectName(u"verticalLayout_43") self.groupBox_10 = QGroupBox(self.tab_12) self.groupBox_10.setObjectName(u"groupBox_10") self.groupBox_10.setEnabled(True) self.verticalLayout_70 = QVBoxLayout(self.groupBox_10) self.verticalLayout_70.setObjectName(u"verticalLayout_70") self.frame_28 = QFrame(self.groupBox_10) self.frame_28.setObjectName(u"frame_28") self.frame_28.setEnabled(True) self.frame_28.setFrameShape(QFrame.NoFrame) self.frame_28.setFrameShadow(QFrame.Raised) self.verticalLayout_100 = QVBoxLayout(self.frame_28) self.verticalLayout_100.setObjectName(u"verticalLayout_100") self.verticalLayout_66 = QVBoxLayout() self.verticalLayout_66.setObjectName(u"verticalLayout_66") self.horizontalLayout_51 = QHBoxLayout() self.horizontalLayout_51.setObjectName(u"horizontalLayout_51") self.label_26 = QLabel(self.frame_28) self.label_26.setObjectName(u"label_26") self.label_26.setMinimumSize(QSize(150, 0)) self.horizontalLayout_51.addWidget(self.label_26) self.comboBox = QComboBox(self.frame_28) self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.setObjectName(u"comboBox") self.horizontalLayout_51.addWidget(self.comboBox) self.verticalLayout_66.addLayout(self.horizontalLayout_51) self.horizontalLayout_52 = QHBoxLayout() self.horizontalLayout_52.setObjectName(u"horizontalLayout_52") self.label_29 = QLabel(self.frame_28) self.label_29.setObjectName(u"label_29") self.label_29.setMinimumSize(QSize(150, 0)) self.horizontalLayout_52.addWidget(self.label_29) self.spinBox = QSpinBox(self.frame_28) self.spinBox.setObjectName(u"spinBox") self.spinBox.setMinimum(1024) self.spinBox.setMaximum(8196) self.spinBox.setSingleStep(128) self.horizontalLayout_52.addWidget(self.spinBox) self.verticalLayout_66.addLayout(self.horizontalLayout_52) self.horizontalLayout_49 = QHBoxLayout() self.horizontalLayout_49.setObjectName(u"horizontalLayout_49") self.label_25 = QLabel(self.frame_28) self.label_25.setObjectName(u"label_25") self.label_25.setMinimumSize(QSize(0, 20)) self.horizontalLayout_49.addWidget(self.label_25) self.checkBox_14 = QCheckBox(self.frame_28) self.checkBox_14.setObjectName(u"checkBox_14") self.checkBox_14.setLayoutDirection(Qt.RightToLeft) self.horizontalLayout_49.addWidget(self.checkBox_14) self.verticalLayout_66.addLayout(self.horizontalLayout_49) self.verticalLayout_100.addLayout(self.verticalLayout_66) self.verticalLayout_70.addWidget(self.frame_28, 0, Qt.AlignLeft|Qt.AlignTop) self.verticalLayout_43.addWidget(self.groupBox_10) self.horizontalLayout_16.addLayout(self.verticalLayout_43) self.verticalLayout_39.addLayout(self.horizontalLayout_16) self.verticalLayout_40.addLayout(self.verticalLayout_39) self.horizontalLayout_34 = QHBoxLayout() self.horizontalLayout_34.setObjectName(u"horizontalLayout_34") self.label_28 = QLabel(self.tab_12) self.label_28.setObjectName(u"label_28") self.horizontalLayout_34.addWidget(self.label_28) self.pushButton_23 = QPushButton(self.tab_12) self.pushButton_23.setObjectName(u"pushButton_23") self.pushButton_23.setMaximumSize(QSize(75, 16777215)) self.horizontalLayout_34.addWidget(self.pushButton_23) self.verticalLayout_40.addLayout(self.horizontalLayout_34) self.tabWidget_3.addTab(self.tab_12, "") self.verticalLayout.addWidget(self.tabWidget_3) self.tabWidget.addTab(self.tab_6, "") self.tab_11 = QWidget() self.tab_11.setObjectName(u"tab_11") self.verticalLayout_9 = QVBoxLayout(self.tab_11) self.verticalLayout_9.setObjectName(u"verticalLayout_9") self.tabWidget_4 = QTabWidget(self.tab_11) self.tabWidget_4.setObjectName(u"tabWidget_4") self.tab_15 = QWidget() self.tab_15.setObjectName(u"tab_15") self.verticalLayout_24 = QVBoxLayout(self.tab_15) self.verticalLayout_24.setObjectName(u"verticalLayout_24") self.textBrowser = QTextBrowser(self.tab_15) self.textBrowser.setObjectName(u"textBrowser") sizePolicy5 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) sizePolicy5.setHorizontalStretch(0) sizePolicy5.setVerticalStretch(0) sizePolicy5.setHeightForWidth(self.textBrowser.sizePolicy().hasHeightForWidth()) self.textBrowser.setSizePolicy(sizePolicy5) self.verticalLayout_24.addWidget(self.textBrowser) self.tabWidget_4.addTab(self.tab_15, "") self.tab_16 = QWidget() self.tab_16.setObjectName(u"tab_16") self.verticalLayout_53 = QVBoxLayout(self.tab_16) self.verticalLayout_53.setObjectName(u"verticalLayout_53") self.textBrowser_3 = QTextBrowser(self.tab_16) self.textBrowser_3.setObjectName(u"textBrowser_3") self.verticalLayout_53.addWidget(self.textBrowser_3) self.tabWidget_4.addTab(self.tab_16, "") self.tab_17 = QWidget() self.tab_17.setObjectName(u"tab_17") self.verticalLayout_26 = QVBoxLayout(self.tab_17) self.verticalLayout_26.setObjectName(u"verticalLayout_26") self.textBrowser_2 = QTextBrowser(self.tab_17) self.textBrowser_2.setObjectName(u"textBrowser_2") sizePolicy5.setHeightForWidth(self.textBrowser_2.sizePolicy().hasHeightForWidth()) self.textBrowser_2.setSizePolicy(sizePolicy5) self.verticalLayout_26.addWidget(self.textBrowser_2) self.tabWidget_4.addTab(self.tab_17, "") self.verticalLayout_9.addWidget(self.tabWidget_4) self.tabWidget.addTab(self.tab_11, "") self.tab_14 = QWidget() self.tab_14.setObjectName(u"tab_14") self.verticalLayout_59 = QVBoxLayout(self.tab_14) self.verticalLayout_59.setObjectName(u"verticalLayout_59") self.textEdit = QTextEdit(self.tab_14) self.textEdit.setObjectName(u"textEdit") self.textEdit.setReadOnly(True) self.verticalLayout_59.addWidget(self.textEdit) self.tabWidget.addTab(self.tab_14, "") self.verticalLayout_12.addWidget(self.tabWidget, 0, Qt.AlignTop) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName(u"menubar") self.menubar.setGeometry(QRect(0, 0, 1168, 21)) MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(u"statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) self.tabWidget_2.setCurrentIndex(0) self.tabWidget_3.setCurrentIndex(0) self.tabWidget_4.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"E-Trust CRL Parsing v1.0.0-beta.14", None)) self.groupBox.setTitle(QCoreApplication.translate("MainWindow", u"\u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f TSL E-Trust", None)) self.label_3.setText(QCoreApplication.translate("MainWindow", u"\u0412\u0435\u0440\u0441\u0438\u044f \u0431\u0430\u0437\u044b:", None)) self.label_2.setText(QCoreApplication.translate("MainWindow", u"\u0414\u0430\u0442\u0430 \u0432\u044b\u043f\u0443\u0441\u043a\u0430 \u0431\u0430\u0437\u044b:", None)) self.label.setText(QCoreApplication.translate("MainWindow", u"\u0412\u0441\u0435\u0433\u043e \u0423\u0426:", None)) self.label_4.setText(QCoreApplication.translate("MainWindow", u"\u0412\u0441\u0435\u0433\u043e CRL:", None)) self.label_5.setText(QCoreApplication.translate("MainWindow", u"\u0423\u0426 \u0434\u043b\u044f \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 \u043e\u0442\u043c\u0435\u0447\u0435\u043d\u043e:", None)) self.label_6.setText(QCoreApplication.translate("MainWindow", u"CRL \u0431\u0443\u0434\u0435\u0442 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043d\u043e:", None)) self.groupBox_17.setTitle(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0441\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f:", None)) self.label_37.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435: ", None)) self.label_38.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435:", None)) self.label_36.setText(QCoreApplication.translate("MainWindow", u"\u0412\u0440\u0435\u043c\u044f \u0432 \u0440\u0430\u0431\u043e\u0442\u0435:", None)) self.label_15.setText(QCoreApplication.translate("MainWindow", u"\u0422\u0430\u0439\u043c\u0435\u0440:", None)) self.pushButton_19.setText(QCoreApplication.translate("MainWindow", u"\u0417\u0430\u043f\u0443\u0441\u043a", None)) self.pushButton_20.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c", None)) self.groupBox_2.setTitle(QCoreApplication.translate("MainWindow", u"\u0413\u043e\u043b\u043e\u0432\u043d\u043e\u0439 \u0423\u0434\u043e\u0441\u0442\u043e\u0432\u0435\u0440\u044f\u044e\u0449\u0438\u0439 \u0446\u0435\u043d\u0442\u0440", None)) ___qtablewidgetitem = self.tableWidget_7.horizontalHeaderItem(0) ___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem1 = self.tableWidget_7.horizontalHeaderItem(1) ___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem2 = self.tableWidget_7.horizontalHeaderItem(2) ___qtablewidgetitem2.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)); ___qtablewidgetitem3 = self.tableWidget_7.horizontalHeaderItem(3) ___qtablewidgetitem3.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)); self.groupBox_3.setTitle(QCoreApplication.translate("MainWindow", u"\u0421\u0432\u043e\u0439 \u0423\u0426: ", None)) ___qtablewidgetitem4 = self.tableWidget_8.horizontalHeaderItem(0) ___qtablewidgetitem4.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem5 = self.tableWidget_8.horizontalHeaderItem(1) ___qtablewidgetitem5.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem6 = self.tableWidget_8.horizontalHeaderItem(2) ___qtablewidgetitem6.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438", None)); ___qtablewidgetitem7 = self.tableWidget_8.horizontalHeaderItem(3) ___qtablewidgetitem7.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)); self.label_7.setText("") self.pushButton.setText(QCoreApplication.translate("MainWindow", u"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0435", None)) self.pushButton_2.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QCoreApplication.translate("MainWindow", u"\u0418\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", None)) self.pushButton_7.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.label_20.setText("") self.pushButton_61.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_60.setText(QCoreApplication.translate("MainWindow", u"\u0418\u041d\u041d", None)) self.pushButton_59.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)) self.pushButton_62.setText("") ___qtablewidgetitem8 = self.tableWidget.horizontalHeaderItem(0) ___qtablewidgetitem8.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem9 = self.tableWidget.horizontalHeaderItem(1) ___qtablewidgetitem9.setText(QCoreApplication.translate("MainWindow", u"\u0418\u041d\u041d", None)); ___qtablewidgetitem10 = self.tableWidget.horizontalHeaderItem(2) ___qtablewidgetitem10.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)); self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QCoreApplication.translate("MainWindow", u"\u0421\u043f\u0438\u0441\u043e\u043a \u0423\u0426", None)) self.pushButton_8.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.pushButton_22.setText("") self.label_21.setText("") self.pushButton_58.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_57.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)) self.pushButton_56.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)) self.pushButton_55.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440", None)) self.pushButton_54.setText("") ___qtablewidgetitem11 = self.tableWidget_2.horizontalHeaderItem(0) ___qtablewidgetitem11.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem12 = self.tableWidget_2.horizontalHeaderItem(1) ___qtablewidgetitem12.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem13 = self.tableWidget_2.horizontalHeaderItem(2) ___qtablewidgetitem13.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)); ___qtablewidgetitem14 = self.tableWidget_2.horizontalHeaderItem(3) ___qtablewidgetitem14.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440", None)); self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), QCoreApplication.translate("MainWindow", u"\u0421\u043f\u0438\u0441\u043e\u043a \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0432", None)) self.pushButton_9.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.pushButton_26.setText("") self.label_24.setText("") self.pushButton_51.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_50.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)) self.pushButton_49.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)) self.pushButton_48.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440", None)) self.pushButton_53.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 \u0432 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u0435", None)) self.pushButton_52.setText("") ___qtablewidgetitem15 = self.tableWidget_3.horizontalHeaderItem(0) ___qtablewidgetitem15.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem16 = self.tableWidget_3.horizontalHeaderItem(1) ___qtablewidgetitem16.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem17 = self.tableWidget_3.horizontalHeaderItem(2) ___qtablewidgetitem17.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)); ___qtablewidgetitem18 = self.tableWidget_3.horizontalHeaderItem(3) ___qtablewidgetitem18.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440", None)); ___qtablewidgetitem19 = self.tableWidget_3.horizontalHeaderItem(4) ___qtablewidgetitem19.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 \u0432 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u0435", None)); self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), QCoreApplication.translate("MainWindow", u"\u0421\u043f\u0438\u0441\u043e\u043a CRL", None)) self.label_8.setText("") self.pushButton_27.setText("") self.pushButton_4.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043a\u0430\u0447\u0430\u0442\u044c \u0432\u0441\u0435 CRL'\u044b", None)) self.pushButton_5.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0432\u0441\u0435 CRL", None)) self.pushButton_3.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c CRL \u0434\u043b\u044f \u0423\u0426", None)) self.pushButton_10.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.pushButton_29.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_28.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)) self.pushButton_24.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)) self.pushButton_32.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)) self.pushButton_31.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_30.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)) self.pushButton_33.setText("") ___qtablewidgetitem20 = self.tableWidget_4.horizontalHeaderItem(0) ___qtablewidgetitem20.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem21 = self.tableWidget_4.horizontalHeaderItem(1) ___qtablewidgetitem21.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)); ___qtablewidgetitem22 = self.tableWidget_4.horizontalHeaderItem(2) ___qtablewidgetitem22.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem23 = self.tableWidget_4.horizontalHeaderItem(3) ___qtablewidgetitem23.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)); ___qtablewidgetitem24 = self.tableWidget_4.horizontalHeaderItem(4) ___qtablewidgetitem24.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem25 = self.tableWidget_4.horizontalHeaderItem(5) ___qtablewidgetitem25.setText(QCoreApplication.translate("MainWindow", u"C\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)); self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_7), QCoreApplication.translate("MainWindow", u"\u041e\u0441\u043d\u043e\u0432\u043d\u044b\u0435 CRL", None)) self.pushButton_11.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.pushButton_25.setText(QCoreApplication.translate("MainWindow", u"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c", None)) self.pushButton_37.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_36.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)) self.pushButton_35.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)) self.pushButton_34.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)) self.pushButton_40.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_39.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)) self.pushButton_38.setText("") ___qtablewidgetitem26 = self.tableWidget_5.horizontalHeaderItem(0) ___qtablewidgetitem26.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem27 = self.tableWidget_5.horizontalHeaderItem(1) ___qtablewidgetitem27.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)); ___qtablewidgetitem28 = self.tableWidget_5.horizontalHeaderItem(2) ___qtablewidgetitem28.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem29 = self.tableWidget_5.horizontalHeaderItem(3) ___qtablewidgetitem29.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)); ___qtablewidgetitem30 = self.tableWidget_5.horizontalHeaderItem(4) ___qtablewidgetitem30.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem31 = self.tableWidget_5.horizontalHeaderItem(5) ___qtablewidgetitem31.setText(QCoreApplication.translate("MainWindow", u"C\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435", None)); self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_8), QCoreApplication.translate("MainWindow", u"\u0421\u0432\u043e\u0438 CRL", None)) self.pushButton_12.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0447\u0438\u0441\u0442\u0438\u0442\u044c", None)) self.pushButton_44.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)) self.pushButton_43.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)) self.pushButton_42.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)) self.pushButton_41.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)) self.pushButton_47.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0435 \u043d\u043e\u043c\u0435\u0440", None)) self.pushButton_46.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)) self.pushButton_45.setText("") ___qtablewidgetitem32 = self.tableWidget_6.horizontalHeaderItem(0) ___qtablewidgetitem32.setText(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435", None)); ___qtablewidgetitem33 = self.tableWidget_6.horizontalHeaderItem(1) ___qtablewidgetitem33.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d", None)); ___qtablewidgetitem34 = self.tableWidget_6.horizontalHeaderItem(2) ___qtablewidgetitem34.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u043a\u043b\u044e\u0447\u0430", None)); ___qtablewidgetitem35 = self.tableWidget_6.horizontalHeaderItem(3) ___qtablewidgetitem35.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043f\u0435\u0447\u0430\u0442\u043e\u043a", None)); ___qtablewidgetitem36 = self.tableWidget_6.horizontalHeaderItem(4) ___qtablewidgetitem36.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0438\u0439\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440", None)); ___qtablewidgetitem37 = self.tableWidget_6.horizontalHeaderItem(5) ___qtablewidgetitem37.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441 CRL", None)); self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_9), QCoreApplication.translate("MainWindow", u"\u041e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u043d\u044b\u0435", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_5), QCoreApplication.translate("MainWindow", u"\u0421\u043a\u0430\u0447\u0438\u0432\u0430\u0435\u043c\u044b\u0435 CRL", None)) self.groupBox_13.setTitle(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u0432\u043a\u043b\u0430\u0434\u043e\u043a", None)) self.label_33.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 CRL", None)) self.label_31.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u0441\u0432\u043e\u0435\u043c \u0441\u043f\u0438\u0441\u043a\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u044f CRL", None)) self.label_32.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u043c \u0441\u043f\u0438\u0441\u043a\u0435 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u044f CRL", None)) self.label_34.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u0421\u0435\u0440\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0432", None)) self.label_35.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u0423\u0426", None)) self.label_30.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u044b\u0432\u043e\u0434\u0438\u043c\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0432 \u0441\u043f\u0438\u0441\u043a\u0435 \u043e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u043d\u044b\u0445 CRL", None)) self.groupBox_16.setTitle(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u0438\u044f", None)) self.checkBox_4.setText(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044c \u0438\u043c\u043f\u043e\u0440\u0442 CRL", None)) self.checkBox_5.setText(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044c \u044d\u043a\u0441\u043f\u043e\u0440\u0442 CRL", None)) self.checkBox_6.setText(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044c \u0443\u0434\u0430\u043b\u044f\u0442\u044c CRL \u0438\u0437 \u0441\u043f\u0438\u0441\u043a\u0430 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u0435\u043c\u044b\u0445", None)) self.checkBox_7.setText(QCoreApplication.translate("MainWindow", u"\u0412\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u043a\u043d\u043e\u043f\u043a\u0443 \"\u0421\u043a\u0430\u0447\u0430\u0442\u044c \u0432\u0441\u0435 CRL\"", None)) self.checkBox_8.setText(QCoreApplication.translate("MainWindow", u"\u0412\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u043a\u043d\u043e\u043f\u043a\u0443 \"\u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0432\u0441\u0435 CRL\"", None)) self.groupBox_21.setTitle(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u043e\u0441\u043d\u043e\u0432\u043d\u043e\u0433\u043e \u043e\u043a\u043d\u0430", None)) self.label_22.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0441\u043e\u0442\u0430 \u043e\u043a\u043d\u0430:", None)) self.label_23.setText(QCoreApplication.translate("MainWindow", u"\u0428\u0438\u0440\u0438\u043d\u0430 \u043e\u043a\u043d\u0430:", None)) self.checkBox_3.setText(QCoreApplication.translate("MainWindow", u"\u0417\u0430\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u0430 \u043e\u043a\u043d\u0430", None)) self.checkBox_2.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043e\u0445\u0440\u0430\u043d\u044f\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0440 \u043e\u043a\u043d\u0430 \u043f\u0440\u0438 \u0432\u044b\u0445\u043e\u0434\u0435", None)) self.groupBox_8.setTitle(QCoreApplication.translate("MainWindow", u"\u041c\u043e\u043d\u0438\u0442\u043e\u0440\u0438\u043d\u0433", None)) self.label_39.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043b\u0435\u0434\u0438\u0442\u044c \u0432 \u043f\u0440\u0435\u0434\u0435\u043b\u0430\u0445 \u0434\u043d\u0435\u0439", None)) self.label_40.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0442\u044c CRL \u0434\u043e \u0438\u0441\u0442\u0435\u0447\u0435\u043d\u0438\u044f", None)) self.label_45.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d \u0423\u0426 \u0421\u0432\u043e\u0439", None)) self.label_46.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0413\u0420\u041d \u0423\u0426 \u041c\u0438\u043d\u043a\u043e\u043c\u0441\u0432\u044f\u0437\u044c", None)) self.groupBox_14.setTitle(QCoreApplication.translate("MainWindow", u"\u0418\u043c\u043f\u043e\u0440\u0442 / \u042d\u043a\u0441\u043f\u043e\u0440\u0442 CRL'\u043e\u0432", None)) self.pushButton_6.setText(QCoreApplication.translate("MainWindow", u"\u0418\u043c\u043f\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0441\u043f\u0438\u0441\u043e\u043a CRL", None)) self.pushButton_13.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0433\u0435\u043d\u0435\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c CRL \u043b\u0438\u0441\u0442", None)) self.groupBox_15.setTitle(QCoreApplication.translate("MainWindow", u"\u041e\u043f\u043e\u0432\u0435\u0449\u0435\u043d\u0438\u0435 \u043f\u043e XMPP", None)) self.label_41.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0435\u0440\u0432\u0435\u0440 XMPP", None)) self.label_42.setText(QCoreApplication.translate("MainWindow", u"\u041b\u043e\u0433\u0438\u043d", None)) self.label_43.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0430\u0440\u043e\u043b\u044c", None)) self.label_44.setText(QCoreApplication.translate("MainWindow", u"\u041a\u043e\u043c\u0443 \u043e\u0442\u0441\u044b\u043b\u0430\u0442\u044c", None)) self.checkBox_10.setText(QCoreApplication.translate("MainWindow", u"\u041e\u043f\u043e\u0432\u0435\u0449\u0430\u0442\u044c \u043e\u0431 \u043e\u0448\u0438\u0431\u043a\u0430\u0445", None)) self.checkBox_9.setText(QCoreApplication.translate("MainWindow", u"\u041e\u043f\u043e\u0432\u0435\u0449\u0430\u0442\u044c \u043e \u043d\u043e\u0432\u044b\u0445 CRL", None)) self.checkBox_11.setText(QCoreApplication.translate("MainWindow", u"\u041e\u043f\u043e\u0432\u0435\u0449\u0430\u0442\u044c \u043e \u043d\u043e\u0432\u043e\u043c TSL", None)) self.label_27.setText("") self.pushButton_21.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c", None)) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_10), QCoreApplication.translate("MainWindow", u"\u041e\u0441\u043d\u043e\u0432\u043d\u043e\u0435", None)) self.groupBox_4.setTitle(QCoreApplication.translate("MainWindow", u"\u041f\u0430\u043f\u043a\u0438 \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u044f", None)) self.pushButton_18.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443 \u0434\u043b\u044f \u0421\u0410\u0421", None)) self.label_13.setText("") self.pushButton_17.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443 \u0434\u043b\u044f \u0421\u0435\u0440\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0432", None)) self.label_12.setText("") self.pushButton_16.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443 \u0432\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0444\u0430\u0439\u043b\u043e\u0432 \u0423\u0426", None)) self.label_11.setText("") self.pushButton_15.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443 \u0432\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0444\u0430\u0439\u043b\u043e\u0432", None)) self.label_10.setText("") self.pushButton_14.setText(QCoreApplication.translate("MainWindow", u"\u0412\u044b\u0431\u0440\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443 \u0434\u043b\u044f \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 \u0432 \u0423\u0426", None)) self.label_9.setText("") self.groupBox_7.setTitle(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u043f\u0440\u043e\u043a\u0441\u0438", None)) self.checkBox.setText(QCoreApplication.translate("MainWindow", u"\u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u043f\u0440\u043e\u043a\u0441\u0438?", None)) self.label_16.setText(QCoreApplication.translate("MainWindow", u"\u0410\u0434\u0440\u0435\u0441:", None)) self.label_17.setText(QCoreApplication.translate("MainWindow", u"\u041f\u043e\u0440\u0442:", None)) self.label_18.setText(QCoreApplication.translate("MainWindow", u"\u041b\u043e\u0433\u0438\u043d:", None)) self.label_19.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0430\u0440\u043e\u043b\u044c:", None)) self.groupBox_5.setTitle(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u0438 \u0437\u0430\u043f\u0443\u0441\u043a\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b (\u043c\u043e\u0436\u0435\u0442 \u0437\u0430\u043c\u0435\u0434\u043b\u0438\u0442\u044c \u0437\u0430\u043f\u0443\u0441\u043a \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b)", None)) self.checkBox_12.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0442\u044c CRL \u043d\u0430 \u0430\u043a\u0442\u0443\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c \u0438 \u043a\u043e\u0440\u0440\u0435\u043a\u0442\u043d\u043e\u0441\u0442\u044c", None)) self.checkBox_13.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u043e\u0432\u0435\u0440\u044f\u0442\u044c TSL \u043d\u0430 \u0430\u043a\u0442\u0443\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c", None)) self.groupBox_6.setTitle(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 CRL", None)) self.label_14.setText(QCoreApplication.translate("MainWindow", u"\u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 CRL \u0432 \u0423\u0426", None)) self.radioButton_2.setText(QCoreApplication.translate("MainWindow", u"\u041e\u0441\u043d\u043e\u0432\u043d\u044b\u0435", None)) self.radioButton.setText(QCoreApplication.translate("MainWindow", u"\u0421\u0432\u043e\u0438", None)) self.groupBox_10.setTitle(QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u043b\u043e\u0433\u043e\u0432", None)) self.label_26.setText(QCoreApplication.translate("MainWindow", u"\u0423\u0440\u043e\u0432\u0435\u043d\u044c \u043b\u043e\u0433\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f", None)) self.comboBox.setItemText(0, QCoreApplication.translate("MainWindow", u"1", None)) self.comboBox.setItemText(1, QCoreApplication.translate("MainWindow", u"2", None)) self.comboBox.setItemText(2, QCoreApplication.translate("MainWindow", u"3", None)) self.comboBox.setItemText(3, QCoreApplication.translate("MainWindow", u"4", None)) self.comboBox.setItemText(4, QCoreApplication.translate("MainWindow", u"5", None)) self.comboBox.setItemText(5, QCoreApplication.translate("MainWindow", u"6", None)) self.comboBox.setItemText(6, QCoreApplication.translate("MainWindow", u"7", None)) self.comboBox.setItemText(7, QCoreApplication.translate("MainWindow", u"8", None)) self.comboBox.setItemText(8, QCoreApplication.translate("MainWindow", u"9", None)) self.label_29.setText(QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0437\u043c\u0435\u0440 \u043b\u043e\u0433\u043e\u0432 (\u041a\u0411)", None)) self.label_25.setText(QCoreApplication.translate("MainWindow", u"\u0414\u0435\u043b\u0438\u0442\u044c \u043b\u043e\u0433\u0438 \u043f\u043e \u0434\u043d\u044f\u043c", None)) self.checkBox_14.setText("") self.label_28.setText("") self.pushButton_23.setText(QCoreApplication.translate("MainWindow", u"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c", None)) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_12), QCoreApplication.translate("MainWindow", u"\u0414\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_6), QCoreApplication.translate("MainWindow", u"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438", None)) self.tabWidget_4.setTabText(self.tabWidget_4.indexOf(self.tab_15), QCoreApplication.translate("MainWindow", u"\u0420\u0430\u0431\u043e\u0442\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b", None)) self.tabWidget_4.setTabText(self.tabWidget_4.indexOf(self.tab_16), QCoreApplication.translate("MainWindow", u"\u0421\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0435", None)) self.tabWidget_4.setTabText(self.tabWidget_4.indexOf(self.tab_17), QCoreApplication.translate("MainWindow", u"\u041e\u0448\u0438\u0431\u043a\u0438", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_11), QCoreApplication.translate("MainWindow", u"\u041b\u043e\u0433\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", None)) self.textEdit.setHtml(QCoreApplication.translate("MainWindow", u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">GitHub:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><a href=\"https://github.com/MrSaerus/E-TrustCRLparsing\"><span style=\" font-size:8pt; text-decoration: underline; color:#0000ff;\">https://github.com/MrSaerus/E-TrustCRLparsing</span></a></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; " "margin-right:0px; -qt-block-indent:0; text-indent:0px;\">\u0423\u0440\u043e\u0432\u043d\u0438 \u043b\u043e\u0433\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 1 \u041a\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043e\u0448\u0438\u0431\u043a\u0438</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 2 \u041e\u0448\u0438\u0431\u043a\u0438 \u0440\u0430\u0431\u043e\u0442\u044b</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 3 \u041f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436\u0434\u0435\u043d\u0438\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u043c\u043e\u0434\u0443\u043b\u0435\u0439</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent" ":0px;\"> 4 \u041f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436\u0434\u0435\u043d\u0438\u044f \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u044f \u0438 \u043f\u0440\u0435\u0432\u043e\u0440\u043e\u043a</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 5 \u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0441\u043a\u0430\u0447\u0438\u0432\u0430\u043d\u0438\u0438 \u0438 \u043f\u0440\u043e\u0432\u0435\u0440\u043e\u043a</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 6 \u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043e \u0440\u0430\u0431\u043e\u0442\u0435 \u043c\u043e\u0434\u0443\u043b\u0435\u0439</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 7 \u0418\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u043f\u0440\u043e" "\u0447\u0430\u044f</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 8 \u0420\u0435\u0437\u0435\u0440\u0432</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> 9 \u0412\u0441\u0451</p></body></html>", None)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_14), QCoreApplication.translate("MainWindow", u"\u041f\u043e\u043c\u043e\u0449\u044c", None)) # retranslateUi
# -*- coding: utf-8 -*- __author__ = "SadLin" import sys import urlparse import optparse from lib.calc_check import * from lib.match_rule import match_type from lib.load_plugins import load_plugins,show_waf_list class checkWaf(object): def __init__(self,RespDict): self.respDict = RespDict #方法一: 遍历所有指纹规则 def Fingers_travel_check(self): pluginsDict = {} pluginsDict = load_plugins() for plugin_module in pluginsDict.values(): #print plugin_module.NAME if plugin_module.is_waf(self.respDict): print "[!] website is protect by : %s " % plugin_module.NAME if test_all: continue return True return False #方法二: 算法计算 def calculation_check(self): if connect_aborted(self.respDict): print "[!] malicious requests was aborted by website " return True if diff_status(self.respDict): print "[!] perform diff resppne status between normal and malicous request " return True if diff_header(self.respDict): print "[!] perform diff resppne header between normal and malicous request " return True if diff_content(self.respDict): print "[!] perform diff resppne content between notExistFile and xss_notExistFile request " return True return False if __name__ == "__main__": parser = optparse.OptionParser('usage: %prog [options] target.com', version="%prog 1.0") parser.add_option("-u","--url",dest="url",type="string",default=False,action="store",help="target url e.g:http://www.example.com/") parser.add_option("","--proxy",dest="proxy",type="string",default=None,action="store",help="scan proxy eg:127.0.0.1:8080") parser.add_option("-l","--list",dest="list",default=False,action="store_true",help="show all of the web application Firewall") parser.add_option("-a","--all",dest="all",default=False,action="store_true",help="test all fingers ignore an waf was identified") (options, args) = parser.parse_args() proxy = options.proxy global test_all test_all = False if options.all: test_all = True if options.list: show_waf_list() sys.exit(0) if options.url: url = options.url url_param = urlparse.urlparse(url) if url_param.scheme == "https": ssl = True else: ssl=False netloc = url_param.netloc path = url_param.path port = 80 match = match_type(netloc, port, path, proxy=proxy, ssl=ssl) respDict = match.getRespDict() identifyWaf = checkWaf(respDict) if identifyWaf.Fingers_travel_check(): sys.exit(0) if identifyWaf.calculation_check(): print "[!] website may be protect by Waf !" sys.exit(0) print "[!] the website seem not to be protected by waf" else: parser.print_help()
# Python3 program to count distinct # divisors of a given number n def SieveOfEratosthenes(n, prime, primesquare, a): # Create a boolean array "prime[0..n]" and initialize all entries it as true. # A value in prime[i] will finally be false if i is not a prime, else true. for i in range(2, n + 1): prime[i] = True # Create a boolean array "primesquare[0..n*n+1]" and initialize all entries it as false. # A value in squareprime[i] will finally be true if i is square of prime, else false. for i in range((n * n + 1) + 1): primesquare[i] = False # 1 is not a prime number prime[1] = False p = 2 while (p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * 2 while (i <= n): prime[i] = False i += p p += 1 j = 0 for p in range(2, n + 1): if (prime[p] == True): # Storing primes in an array a[j] = p # Update value in primesquare[p*p], # if p is prime. primesquare[p * p] = True j += 1 # Function to count divisors def countDivisors(n): # If number is 1, then it will # have only 1 as a factor. So, # total factors will be 1. if (n == 1): return 1 prime = [False] * (n + 2) primesquare = [False] * (n * n + 2) # for storing primes upto n a = [0] * n # Calling SieveOfEratosthenes to store prime factors of n and to store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a) # ans will contain total number of distinct divisors ans = 1 # Loop for counting factors of n i = 0 while (1): # a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n): break # Calculating power of a[i] in n. cnt = 1 # cnt is power of # prime a[i] in n. while (n % a[i] == 0): # if a[i] is a factor of n n = n / a[i] cnt = cnt + 1 # incrementing power # Calculating number of divisors # If n = a^p * b^q then total # divisors of n are (p+1)*(q+1) ans = ans * cnt i += 1 # if a[i] is greater than # cube root of n n = int(n) # First case if (prime[n] == True): ans = ans * 2 # Second case elif (primesquare[n] == True): ans = ans * 3 # Third casse elif (n != 1): ans = ans * 4 return ans # Total divisors # Driver Code if __name__ == '__main__': print("Total distinct divisors of 100 are :", countDivisors(10))
"""Take in any given and find best param USAGE ----- $ python mrec/model/grid_search.py # Launch an mlflow tracking ui after model results to compare $ mlflow ui Add parameters via `model/make_classifiers.py` with its associated model """ # Standard Dist Imports import logging import os import joblib from pprint import pprint import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2]) + '/') # Third Party Imports from sklearn.model_selection import GridSearchCV import mlflow import mlflow.sklearn import pandas as pd # Project Level Imports from mrec.data.make_dataset import preprocessing_dataset from mrec.model.make_classifiers import make_classifiers from mrec.model.ml_utils import fetch_logged_data logger = logging.getLogger(__name__) logger.root.setLevel(logging.INFO) SAVE_PATH = 'models/baseline_model/final_model.joblib' MODEL_NAME = 'NuSVC' csv_fnames = {'train': 'dataset/processed/train.csv', 'validation': 'dataset/processed/validation.csv', 'test': 'dataset/processed/test.csv'} def tuning_parameters(model, param_grid, X, y): """Fine-tuning parameter for a given model Args: model: classifier model param_grid: pram of that given model X (sparse matrix): countvectorizer of train feature(s) y (series): label of train set Returns: the best estimator """ grid_search = GridSearchCV(model, param_grid, cv=5, scoring='accuracy') grid_search.fit(X, y) return grid_search.best_estimator_ def main(): experiment_name = 'grid-search' mlflow.set_experiment(experiment_name) logger.info(f'Beginning experiment {experiment_name} (tracked ' f'{"remotely" if mlflow.tracking.is_tracking_uri_set() else "locally"})...') mlflow.sklearn.autolog() logger.info('Preparing datasets and models..') train, train_label, val, val_label, test, test_label = preprocessing_dataset(csv_fnames) classifiers, parameters = make_classifiers() run = mlflow.start_run() logger.info(f'Model trained using gridsearch: {MODEL_NAME}') final_model = tuning_parameters(classifiers[MODEL_NAME], parameters[MODEL_NAME], train, train_label) # show data logged in the parent run print("========== parent run ==========") for key, data in fetch_logged_data(run.info.run_id).items(): print("\n---------- logged {} ----------".format(key)) pprint(data) # show data logged in the child runs filter_child_runs = "tags.mlflow.parentRunId = '{}'".format(run.info.run_id) runs = mlflow.search_runs(filter_string=filter_child_runs) param_cols = ["params.{}".format(p) for p in parameters[MODEL_NAME].keys()] metric_cols = ["metrics.mean_test_score"] print("\n========== child runs ==========\n") pd.set_option("display.max_columns", None) # prevent truncating columns print(runs[["run_id", *param_cols, *metric_cols]]) # Save the model logger.info(f'Saving best model as {SAVE_PATH}') joblib.dump(final_model, SAVE_PATH) mlflow.log_artifact(SAVE_PATH, artifact_path="baseline_model") mlflow.end_run() if __name__ == '__main__': if not os.path.exists(SAVE_PATH): raise FileNotFoundError("Model weights not found. Please run `python select_model.py` to get a baseline model") main()
from golem import actions from projects.golem_integration.pages import golem_steps description = 'Verify step action' def test(data): actions.step('this is a step') golem_steps.assert_last_step_message('this is a step')
from django.contrib import admin from .models import ( GalleryProduct, Product, Color, Size ) class ImageProductInline(admin.StackedInline): model = GalleryProduct @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_filter = ('status', 'gold_or_jewelry') search_fields = ('title', 'slug', 'body') inlines = [ImageProductInline] prepopulated_fields = {'slug': ('title',)} list_display = ( 'rating', 'title', 'slug', 'gold_or_jewelry', 'status', 'image_tag' ) @admin.register(Color) class ColorAdmin(admin.ModelAdmin): pass @admin.register(Size) class SizeAdmin(admin.ModelAdmin): pass
import os import github3 from github3 import repos from datetime import datetime from tests.utils import (expect, BaseCase, load) from mock import patch, mock_open class TestRepository(BaseCase): def __init__(self, methodName='runTest'): super(TestRepository, self).__init__(methodName) self.repo = repos.Repository(load('repo')) def setUp(self): super(TestRepository, self).setUp() self.repo = repos.Repository(self.repo.to_json(), self.g) self.api = 'https://api.github.com/repos/sigmavirus24/github3.py/' def test_add_collaborator(self): self.response('', 204) self.put(self.api + 'collaborators/sigmavirus24') self.conf = {'data': None} with expect.githuberror(): self.repo.add_collaborator('foo') self.login() expect(self.repo.add_collaborator(None)).is_False() expect(self.repo.add_collaborator('sigmavirus24')).is_True() self.mock_assertions() def test_archive(self): headers = {'content-disposition': 'filename=foo'} self.response('archive', 200, **headers) self.get(self.api + 'tarball/master') self.conf.update({'stream': True}) expect(self.repo.archive(None)).is_False() expect(os.path.isfile('foo')).is_False() expect(self.repo.archive('tarball')).is_True() expect(os.path.isfile('foo')).is_True() os.unlink('foo') self.mock_assertions() self.request.return_value.raw.seek(0) self.request.return_value._content_consumed = False expect(os.path.isfile('path_to_file')).is_False() expect(self.repo.archive('tarball', 'path_to_file')).is_True() expect(os.path.isfile('path_to_file')).is_True() os.unlink('path_to_file') self.request.return_value.raw.seek(0) self.request.return_value._content_consumed = False self.get(self.api + 'zipball/randomref') expect(self.repo.archive('zipball', ref='randomref')).is_True() os.unlink('foo') self.request.return_value.raw.seek(0) self.request.return_value._content_consumed = False o = mock_open() with patch('{0}.open'.format(__name__), o, create=True): with open('archive', 'wb+') as fd: self.repo.archive('tarball', fd) o.assert_called_once_with('archive', 'wb+') fd = o() fd.write.assert_called_once_with(b'archive_data') def test_blob(self): self.response('blob') sha = '3ceb856e2f14e9669fed6384e58c9a1590a2314f' self.get(self.api + 'git/blobs/' + sha) blob = self.repo.blob(sha) expect(blob).isinstance(github3.git.Blob) expect(repr(blob).startswith('<Blob')).is_True() self.mock_assertions() def test_branch(self): self.response('branch') self.get(self.api + 'branches/master') b = self.repo.branch('master') expect(b).isinstance(repos.branch.Branch) self.mock_assertions() expect(repr(b)) == '<Repository Branch [master]>' def test_commit(self): self.response('commit') sha = '76dcc6cb4b9860034be81b7e58adc286a115aa97' self.get(self.api + 'commits/' + sha) expect(self.repo.commit(sha)).isinstance(repos.commit.RepoCommit) self.mock_assertions() def test_commit_comment(self): self.response('commit_comment') comment_id = 1380832 self.get(self.api + 'comments/{0}'.format(comment_id)) expect(self.repo.commit_comment(comment_id) ).isinstance(repos.comment.RepoComment) self.mock_assertions() def test_compare_commits(self): self.response('comparison') base = 'a811e1a270f65eecb65755eca38d888cbefcb0a7' head = '76dcc6cb4b9860034be81b7e58adc286a115aa97' self.get(self.api + 'compare/{0}...{1}'.format(base, head)) expect(self.repo.compare_commits(base, head) ).isinstance(repos.comparison.Comparison) self.mock_assertions() def test_contents(self): self.response('contents') filename = 'setup.py' self.get(self.api + 'contents/' + filename) expect(self.repo.contents(filename)).isinstance( repos.contents.Contents) self.mock_assertions() self.response('', 404) expect(self.repo.contents(filename)).is_None() self.response('contents', _iter=True) files = self.repo.contents(filename) expect(files).isinstance(dict) self.mock_assertions() def test_contents_ref(self): self.response('contents') filename = 'setup.py' self.get(self.api + 'contents/' + filename) self.conf = {'params': {'ref': 'foo'}} expect(self.repo.contents(filename, ref='foo')).isinstance( repos.contents.Contents) self.mock_assertions() def test_create_blob(self): self.response('blob', 201) content = 'VGVzdCBibG9i\n' encoding = 'base64' sha = '30f2c645388832f70d37ab2b47eb9ea527e5ae7c' self.post(self.api + 'git/blobs') self.conf = {'data': {'content': content, 'encoding': encoding}} with expect.githuberror(): self.repo.create_blob(content, encoding) self.login() expect(self.repo.create_blob(None, None)) == '' expect(self.repo.create_blob(content, encoding)) == sha self.mock_assertions() def test_create_comment(self): self.response('commit_comment', 201) body = ('Late night commits are never a good idea. I refactored a ' 'bit. `User` objects and `Organization` objects share a lot ' 'of common attributes. I turned those common attributes into ' 'one `BaseAccount` class to make things simpler. ') sha = 'd41566090114a752eb3a87dbcf2473eb427ef0f3' self.post(self.api + 'commits/{0}/comments'.format(sha)) self.conf = {'data': {'body': body, 'line': 1}} with expect.githuberror(): self.repo.create_comment(body, sha) self.login() expect(self.repo.create_comment(None, None)).is_None() expect(self.repo.create_comment(body, sha, line=0)).is_None() expect(self.repo.create_comment(body, sha) ).isinstance(repos.comment.RepoComment) self.mock_assertions() def test_create_commit(self): self.response('commit', 201) data = {'message': 'My commit message', 'author': { 'name': 'Ian Cordasco', 'email': 'foo@example.com', 'date': '2008-07-09T16:13:30+12:00', }, 'committer': {}, 'parents': [ '7d1b31e74ee336d15cbd21741bc88a537ed063a0' ], 'tree': '827efc6d56897b048c772eb4087f854f46256132', } self.conf = {'data': data} self.post(self.api + 'git/commits') with expect.githuberror(): self.repo.create_commit(**data) self.login() expect(self.repo.create_commit(None, None, None)).is_None() expect(self.repo.create_commit(**data)).isinstance(github3.git.Commit) self.mock_assertions() def test_create_fork(self): self.response('repo', 202) self.conf = {'data': None} self.post(self.api + 'forks') with expect.githuberror(): self.repo.create_fork() self.login() expect(self.repo.create_fork()).isinstance(repos.Repository) self.mock_assertions() self.conf['data'] = {'organization': 'github3py'} expect(self.repo.create_fork('github3py') ).isinstance(repos.Repository) self.mock_assertions() def test_create_hook(self): self.response('hook', 201) self.post(self.api + 'hooks') self.conf = { 'data': { 'name': 'Hookname', 'config': { 'foo': 'bar' } } } with expect.githuberror(): self.repo.create_hook(None, None) self.login() expect(self.repo.create_hook(None, {'foo': 'bar'})).is_None() expect(self.repo.create_hook('name', None)).is_None() expect(self.repo.create_hook('name', 'bar')).is_None() self.not_called() h = self.repo.create_hook(**self.conf['data']) expect(h).isinstance(repos.hook.Hook) self.mock_assertions() def test_create_issue(self): self.response('issue', 201) title = 'Construct _api attribute on our own' self.post(self.api + 'issues') self.conf = {'data': {'title': title}} with expect.githuberror(): self.repo.create_issue(title) self.login() expect(self.repo.create_issue(None)).is_None() expect(self.repo.create_issue(title)).isinstance(github3.issues.Issue) self.mock_assertions() body = 'Fake body' #self.conf['data'].update(body=body) expect(self.repo.create_issue(title, body) ).isinstance(github3.issues.Issue) self.mock_assertions() assignee, mile, labels = 'sigmavirus24', 1, ['bug', 'enhancement'] #self.conf['data'].update({'assignee': assignee, 'milestone': mile, # 'labels': labels}) expect(self.repo.create_issue(title, body, assignee, mile, labels) ).isinstance(github3.issues.Issue) self.mock_assertions() def test_create_key(self): self.response('key', 201) self.post(self.api + 'keys') self.conf = {'data': {'key': 'ssh-rsa foobarbogus', 'title': 'Fake key'}} with expect.githuberror(): self.repo.create_key(**self.conf['data']) self.login() expect(self.repo.create_key(None, None)).is_None() self.not_called() expect(self.repo.create_key(**self.conf['data'])).isinstance( github3.users.Key) self.mock_assertions() def test_create_label(self): self.response('label', 201) self.post(self.api + 'labels') self.conf = {'data': {'name': 'foo', 'color': 'f00f00'}} with expect.githuberror(): self.repo.create_label(**self.conf['data']) self.login() expect(self.repo.create_label(None, None)).is_None() self.not_called() expect(self.repo.create_label(**self.conf['data'])).isinstance( github3.issues.label.Label) self.mock_assertions() def test_create_milestone(self): self.response('milestone', 201) self.post(self.api + 'milestones') self.conf = {'data': {'title': 'foo'}} with expect.githuberror(): self.repo.create_milestone(**self.conf['data']) self.login() expect(self.repo.create_milestone(None)).is_None() self.not_called() expect(self.repo.create_milestone('foo')).isinstance( github3.issues.milestone.Milestone) self.mock_assertions() def test_create_pull(self): self.response('pull', 201) self.post(self.api + 'pulls') self.conf = {'data': {'title': 'Fake title', 'base': 'master', 'head': 'feature_branch'}} with expect.githuberror(): self.repo.create_pull(**self.conf['data']) self.login() expect(self.repo.create_pull(None, None, None)).is_None() self.not_called() expect(self.repo.create_pull(**self.conf['data'])).isinstance( github3.pulls.PullRequest) self.mock_assertions() def test_create_pull_from_issue(self): self.response('pull', 201) self.post(self.api + 'pulls') self.conf = {'data': {'issue': 1, 'base': 'master', 'head': 'feature_branch'}} with expect.githuberror(): self.repo.create_pull_from_issue(**self.conf['data']) self.login() expect(self.repo.create_pull_from_issue(0, 'foo', 'bar')).is_None() self.not_called() expect(self.repo.create_pull_from_issue(**self.conf['data']) ).isinstance(github3.pulls.PullRequest) self.mock_assertions() def test_create_ref(self): self.response('ref', 201) self.post(self.api + 'git/refs') self.conf = {'data': {'ref': 'refs/heads/master', 'sha': 'fakesha'}} with expect.githuberror(): self.repo.create_ref('foo', 'bar') self.login() expect(self.repo.create_ref('foo/bar', None)).is_None() expect(self.repo.create_ref(**self.conf['data'])).isinstance( github3.git.Reference) self.mock_assertions() def test_create_status(self): self.response('status', 201) self.post(self.api + 'statuses/fakesha') self.conf = {'data': {'state': 'success'}} with expect.githuberror(): self.repo.create_status('fakesha', 'success') self.login() expect(self.repo.create_status(None, None)).is_None() s = self.repo.create_status('fakesha', 'success') expect(s).isinstance(repos.status.Status) expect(repr(s)) > '' self.mock_assertions() def test_create_tag(self): self.response('tag', 201) self.post(self.api + 'git/tags') data = { 'tag': '0.3', 'message': 'Fake message', 'object': 'fakesha', 'type': 'commit', 'tagger': { 'name': 'Ian Cordasco', 'date': 'Not a UTC date', 'email': 'graffatcolmingov@gmail.com' } } self.conf = {'data': data.copy()} data['obj_type'] = data['type'] data['sha'] = data['object'] del(data['type'], data['object']) with expect.githuberror(): self.repo.create_tag(None, None, None, None, None) self.login() with patch.object(repos.Repository, 'create_ref'): expect(self.repo.create_tag(None, None, None, None, None)).is_None() tag = self.repo.create_tag(**data) expect(tag).isinstance(github3.git.Tag) expect(repr(tag).startswith('<Tag')).is_True() self.mock_assertions() with patch.object(repos.Repository, 'create_ref') as cr: self.repo.create_tag('tag', '', 'fakesha', '', '', lightweight=True) cr.assert_called_once_with('refs/tags/tag', 'fakesha') def test_create_tree(self): self.response('tree', 201) self.post(self.api + 'git/trees') data = {'tree': [{'path': 'file1', 'mode': '100755', 'type': 'tree', 'sha': '75b347329e3fc87ac78895ca1be58daff78872a1'}], 'base_tree': ''} self.conf = {'data': data} with expect.githuberror(): self.repo.create_tree(**data) self.login() expect(self.repo.create_tree(None)).is_None() expect(self.repo.create_tree({'foo': 'bar'})).is_None() self.not_called() expect(self.repo.create_tree(**data)).isinstance(github3.git.Tree) self.mock_assertions() def test_delete(self): self.response('', 204) self.delete(self.api[:-1]) self.conf = {} with expect.githuberror(): self.repo.delete() self.login() expect(self.repo.delete()).is_True() self.mock_assertions() def test_delete_key(self): self.response('', 204) self.delete(self.api + 'keys/2') self.conf = {} with expect.githuberror(): self.repo.delete_key(2) self.login() expect(self.repo.delete_key(-2)).is_False() self.not_called() expect(self.repo.delete_key(2)).is_True() self.mock_assertions() def test_download(self): self.response('download') self.get(self.api + 'downloads/2') expect(self.repo.download(-2)).is_None() self.not_called() expect(self.repo.download(2)).isinstance(repos.download.Download) self.mock_assertions() def test_edit(self): self.response('repo') self.patch(self.api[:-1]) self.conf = {'data': {'name': 'foo'}} with expect.githuberror(): self.repo.edit('Foo') self.login() expect(self.repo.edit(None)).is_False() self.not_called() expect(self.repo.edit('foo')).is_True() self.mock_assertions() self.conf['data']['description'] = 'bar' expect(self.repo.edit(**self.conf['data'])).is_True() self.mock_assertions() def test_is_collaborator(self): self.response('', 204) self.get(self.api + 'collaborators/user') expect(self.repo.is_collaborator(None)).is_False() self.not_called() expect(self.repo.is_collaborator('user')).is_True() self.mock_assertions() def test_git_commit(self): self.response('git_commit') self.get(self.api + 'git/commits/fakesha') expect(self.repo.git_commit(None)).is_None() self.not_called() expect(self.repo.git_commit('fakesha')).isinstance(github3.git.Commit) self.mock_assertions() def test_hook(self): self.response('hook') self.get(self.api + 'hooks/2') with expect.githuberror(): self.repo.hook(2) self.login() expect(self.repo.hook(-2)).is_None() self.not_called() expect(self.repo.hook(2)).isinstance(repos.hook.Hook) self.mock_assertions() def test_is_assignee(self): self.response('', 204) self.get(self.api + 'assignees/login') expect(self.repo.is_assignee(None)).is_False() self.not_called() expect(self.repo.is_assignee('login')).is_True() self.mock_assertions() def test_issue(self): self.response('issue') self.get(self.api + 'issues/2') expect(self.repo.issue(-2)).is_None() self.not_called() expect(self.repo.issue(2)).isinstance(github3.issues.Issue) self.mock_assertions() def test_key(self): self.response('key') self.get(self.api + 'keys/2') with expect.githuberror(): self.repo.key(2) self.login() expect(self.repo.key(-2)).is_None() self.not_called() expect(self.repo.key(2)).isinstance(github3.users.Key) self.mock_assertions() def test_label(self): self.response('label') self.get(self.api + 'labels/name') expect(self.repo.label(None)).is_None() self.not_called() expect(self.repo.label('name')).isinstance(github3.issues.label.Label) self.mock_assertions() def test_iter_assignees(self): self.response('user', _iter=True) self.get(self.api + 'assignees') self.conf = {'params': None} u = next(self.repo.iter_assignees()) expect(u).isinstance(github3.users.User) self.mock_assertions() def test_iter_branches(self): self.response('branch', _iter=True) self.get(self.api + 'branches') self.conf = {'params': None} b = next(self.repo.iter_branches()) expect(b).isinstance(repos.branch.Branch) self.mock_assertions() def test_iter_comments(self): self.response('repo_comment', _iter=True) self.get(self.api + 'comments') self.conf = {'params': None} c = next(self.repo.iter_comments()) expect(c).isinstance(repos.comment.RepoComment) self.mock_assertions() def test_iter_comments_on_commit(self): self.response('repo_comment', _iter=True) self.get(self.api + 'commits/fakesha/comments') self.conf = {'params': None} c = next(self.repo.iter_comments_on_commit('fakesha')) expect(c).isinstance(repos.comment.RepoComment) self.mock_assertions() def test_iter_commits(self): self.response('commit', _iter=True) self.get(self.api + 'commits') self.conf = {'params': {}} c = next(self.repo.iter_commits()) expect(c).isinstance(repos.commit.RepoCommit) self.mock_assertions() self.conf = {'params': {'sha': 'fakesha', 'path': '/'}} c = next(self.repo.iter_commits('fakesha', '/')) self.mock_assertions() since = datetime(2013, 6, 1, 0, 0, 0) until = datetime(2013, 6, 2, 0, 0, 0) self.conf = {'params': {'since': '2013-06-01T00:00:00', 'until': '2013-06-02T00:00:00'}} c = next(self.repo.iter_commits(since=since, until=until)) self.mock_assertions() since = '2013-06-01T00:00:00' until = '2013-06-02T00:00:00' self.conf = {'params': {'since': '2013-06-01T00:00:00', 'until': '2013-06-02T00:00:00'}} c = next(self.repo.iter_commits(since=since, until=until)) self.mock_assertions() def test_iter_contributors(self): self.response('user', _iter=True) self.get(self.api + 'contributors') self.conf = {'params': {}} u = next(self.repo.iter_contributors()) expect(u).isinstance(github3.users.User) self.mock_assertions() self.conf = {'params': {'anon': True}} next(self.repo.iter_contributors(True)) self.mock_assertions() next(self.repo.iter_contributors('true value')) self.mock_assertions() def test_iter_downloads(self): self.response('download', _iter=True) self.get(self.api + 'downloads') self.conf = {'params': None} d = next(self.repo.iter_downloads()) expect(d).isinstance(repos.download.Download) self.mock_assertions() def test_iter_events(self): self.response('event', _iter=True) self.get(self.api + 'events') self.conf = {'params': None} e = next(self.repo.iter_events()) expect(e).isinstance(github3.events.Event) self.mock_assertions() def test_iter_forks(self): self.response('repo', _iter=True) self.get(self.api + 'forks') self.conf = {'params': {}} r = next(self.repo.iter_forks()) expect(r).isinstance(repos.Repository) self.mock_assertions() self.conf['params']['sort'] = 'newest' next(self.repo.iter_forks(**self.conf['params'])) self.mock_assertions() def test_iter_hooks(self): self.response('hook', _iter=True) self.get(self.api + 'hooks') self.conf = {'params': None} with expect.githuberror(): self.repo.iter_hooks() self.login() h = next(self.repo.iter_hooks()) expect(h).isinstance(repos.hook.Hook) self.mock_assertions() def test_iter_issues(self): self.response('issue', _iter=True) self.get(self.api + 'issues') params = {} self.conf = {'params': params} i = next(self.repo.iter_issues()) expect(i).isinstance(github3.issues.Issue) self.mock_assertions() params['milestone'] = 'none' next(self.repo.iter_issues('none')) self.mock_assertions() params['state'] = 'open' next(self.repo.iter_issues(**params)) self.mock_assertions() def test_iter_issue_events(self): self.response('issue_event', _iter=True) self.get(self.api + 'issues/events') self.conf = {'params': None} e = next(self.repo.iter_issue_events()) expect(e).isinstance(github3.issues.event.IssueEvent) self.mock_assertions() def test_iter_keys(self): self.response('key', _iter=True) self.get(self.api + 'keys') with expect.githuberror(): self.repo.iter_keys() self.login() k = next(self.repo.iter_keys()) expect(k).isinstance(github3.users.Key) self.mock_assertions() def test_iter_labels(self): self.response('label', _iter=True) self.get(self.api + 'labels') l = next(self.repo.iter_labels()) expect(l).isinstance(github3.issues.label.Label) self.mock_assertions() def test_iter_languages(self): #: repos/:login/:repo/languages is just a dictionary, so _iter=False self.response('language') self.get(self.api + 'languages') l = next(self.repo.iter_languages()) expect(l).isinstance(tuple) self.mock_assertions() def test_iter_milestones(self): self.response('milestone', _iter=True) self.get(self.api + 'milestones') m = next(self.repo.iter_milestones()) expect(m).isinstance(github3.issues.milestone.Milestone) self.mock_assertions() def test_iter_network_events(self): self.response('event', _iter=True) self.get(self.api.replace('repos', 'networks', 1) + 'events') e = next(self.repo.iter_network_events()) expect(e).isinstance(github3.events.Event) self.mock_assertions() def test_iter_notifications(self): self.response('notification', _iter=True) self.get(self.api + 'notifications') self.conf.update(params={}) with expect.githuberror(): self.repo.iter_notifications() self.login() n = next(self.repo.iter_notifications()) expect(n).isinstance(github3.notifications.Thread) self.mock_assertions() def test_iter_pulls(self): self.response('pull', _iter=True) self.get(self.api + 'pulls') self.conf.update(params={}) p = next(self.repo.iter_pulls()) expect(p).isinstance(github3.pulls.PullRequest) self.mock_assertions() next(self.repo.iter_pulls('foo')) self.mock_assertions() self.conf.update(params={'state': 'open'}) next(self.repo.iter_pulls('Open')) self.mock_assertions() self.conf.update(params={'head': 'user:branch'}) next(self.repo.iter_pulls(head='user:branch')) self.mock_assertions() self.conf.update(params={'base': 'branch'}) next(self.repo.iter_pulls(base='branch')) self.mock_assertions() def test_iter_refs(self): self.response('ref', _iter=True) self.get(self.api + 'git/refs') r = next(self.repo.iter_refs()) expect(r).isinstance(github3.git.Reference) self.mock_assertions() self.get(self.api + 'git/refs/subspace') r = next(self.repo.iter_refs('subspace')) expect(r).isinstance(github3.git.Reference) self.mock_assertions() def test_iter_stargazers(self): self.response('user', _iter=True) self.get(self.api + 'stargazers') u = next(self.repo.iter_stargazers()) expect(u).isinstance(github3.users.User) self.mock_assertions() def test_iter_subscribers(self): self.response('user', _iter=True) self.get(self.api + 'subscribers') u = next(self.repo.iter_subscribers()) expect(u).isinstance(github3.users.User) self.mock_assertions() def test_iter_statuses(self): self.response('status', _iter=True) self.get(self.api + 'statuses/fakesha') with expect.raises(StopIteration): next(self.repo.iter_statuses(None)) self.not_called() s = next(self.repo.iter_statuses('fakesha')) expect(s).isinstance(repos.status.Status) self.mock_assertions() def test_iter_tags(self): self.response('tag', _iter=True) self.get(self.api + 'tags') t = next(self.repo.iter_tags()) expect(t).isinstance(repos.tag.RepoTag) self.mock_assertions() expect(repr(t).startswith('<Repository Tag')).is_True() expect(str(t) > '').is_True() def test_iter_teams(self): self.response('team', _iter=True) self.get(self.api + 'teams') with expect.githuberror(): self.repo.iter_teams() self.not_called() self.login() t = next(self.repo.iter_teams()) expect(t).isinstance(github3.orgs.Team) self.mock_assertions() def test_mark_notifications(self): self.response('', 205) self.put(self.api + 'notifications') self.conf = {'data': {'read': True}} with expect.githuberror(): self.repo.mark_notifications() self.not_called() self.login() expect(self.repo.mark_notifications()).is_True() self.mock_assertions() expect(self.repo.mark_notifications('2013-01-18T19:53:04Z')).is_True() self.conf['data']['last_read_at'] = '2013-01-18T19:53:04Z' self.mock_assertions() def test_merge(self): self.response('commit', 201) self.post(self.api + 'merges') self.conf = {'data': {'base': 'master', 'head': 'sigma/feature'}} with expect.githuberror(): self.repo.merge('foo', 'bar') self.not_called() self.login() expect(self.repo.merge('master', 'sigma/feature')).isinstance( repos.commit.RepoCommit) self.mock_assertions() self.conf['data']['commit_message'] = 'Commit message' self.repo.merge('master', 'sigma/feature', 'Commit message') self.mock_assertions() def test_milestone(self): self.response('milestone', 200) self.get(self.api + 'milestones/2') expect(self.repo.milestone(0)).is_None() self.not_called() expect(self.repo.milestone(2)).isinstance( github3.issues.milestone.Milestone) self.mock_assertions() def test_parent(self): json = self.repo.to_json().copy() json['parent'] = json.copy() r = repos.Repository(json) expect(r.parent).isinstance(repos.Repository) def test_pull_request(self): self.response('pull', 200) self.get(self.api + 'pulls/2') expect(self.repo.pull_request(0)).is_None() self.not_called() expect(self.repo.pull_request(2)).isinstance(github3.pulls.PullRequest) self.mock_assertions() def test_readme(self): self.response('readme', 200) self.get(self.api + 'readme') expect(self.repo.readme()).isinstance(repos.contents.Contents) self.mock_assertions() def test_ref(self): self.response('ref', 200) self.get(self.api + 'git/refs/fakesha') expect(self.repo.ref(None)).is_None() self.not_called() expect(self.repo.ref('fakesha')).isinstance(github3.git.Reference) self.mock_assertions() def test_remove_collaborator(self): self.response('', 204) self.delete(self.api + 'collaborators/login') with expect.githuberror(): self.repo.remove_collaborator(None) self.not_called() self.login() expect(self.repo.remove_collaborator(None)).is_False() self.not_called() expect(self.repo.remove_collaborator('login')).is_True() self.mock_assertions() def test_repr(self): expect(repr(self.repo)) == '<Repository [sigmavirus24/github3.py]>' def test_source(self): json = self.repo.to_json().copy() json['source'] = json.copy() r = repos.Repository(json) expect(r.source).isinstance(repos.Repository) def test_set_subscription(self): self.response('subscription') self.put(self.api + 'subscription') self.conf = {'data': {'subscribed': True, 'ignored': False}} with expect.githuberror(): self.repo.set_subscription(True, False) self.not_called() self.login() s = self.repo.set_subscription(True, False) expect(s).isinstance(github3.notifications.Subscription) self.mock_assertions() def test_subscription(self): self.response('subscription') self.get(self.api + 'subscription') with expect.githuberror(): self.repo.subscription() self.not_called() self.login() s = self.repo.subscription() expect(s).isinstance(github3.notifications.Subscription) self.mock_assertions() def test_tag(self): self.response('tag') self.get(self.api + 'git/tags/fakesha') expect(self.repo.tag(None)).is_None() self.not_called() expect(self.repo.tag('fakesha')).isinstance(github3.git.Tag) self.mock_assertions() def test_tree(self): self.response('tree') self.get(self.api + 'git/trees/fakesha') expect(self.repo.tree(None)).is_None() self.not_called() expect(self.repo.tree('fakesha')).isinstance(github3.git.Tree) self.mock_assertions() def test_update_label(self): self.response('label') self.patch(self.api + 'labels/Bug') self.conf = {'data': {'name': 'big_bug', 'color': 'fafafa'}} with expect.githuberror(): self.repo.update_label('foo', 'bar') self.not_called() self.login() with patch.object(repos.Repository, 'label') as l: l.return_value = None expect(self.repo.update_label('foo', 'bar')).is_False() self.not_called() with patch.object(repos.Repository, 'label') as l: l.return_value = github3.issues.label.Label(load('label'), self.g) expect(self.repo.update_label('big_bug', 'fafafa')).is_True() self.mock_assertions() def test_equality(self): expect(self.repo) == repos.Repository(load('repo')) def test_create_file(self): self.response('create_content', 201) self.put(self.api + 'contents/setup.py') self.conf = {'data': {'message': 'Foo bar', 'content': 'Zm9vIGJhciBib2d1cw==', 'branch': 'develop', 'author': {'name': 'Ian', 'email': 'foo'}, 'committer': {'name': 'Ian', 'email': 'foo'}}} with expect.githuberror(): self.repo.create_file(None, None, None) self.not_called() self.login() ret = self.repo.create_file('setup.py', 'Foo bar', b'foo bar bogus', 'develop', {'name': 'Ian', 'email': 'foo'}, {'name': 'Ian', 'email': 'foo'}) expect(ret).isinstance(dict) expect(ret['commit']).isinstance(github3.git.Commit) expect(ret['content']).isinstance(repos.contents.Contents) self.mock_assertions() def test_update_file(self): self.response('create_content', 200) self.put(self.api + 'contents/setup.py') self.conf = { 'data': { 'message': 'foo', 'content': 'Zm9vIGJhciBib2d1cw==', 'sha': 'ae02db', } } with expect.githuberror(): self.repo.update_file(None, None, None, None) self.not_called() self.login() ret = self.repo.update_file('setup.py', 'foo', b'foo bar bogus', 'ae02db') expect(ret).isinstance(dict) expect(ret['commit']).isinstance(github3.git.Commit) expect(ret['content']).isinstance(repos.contents.Contents) self.mock_assertions() def test_delete_file(self): self.response('create_content', 200) self.delete(self.api + 'contents/setup.py') self.conf = {'data': {'message': 'foo', 'sha': 'ae02db'}} with expect.githuberror(): self.repo.delete_file('setup.py', None, None) self.not_called() self.login() ret = self.repo.delete_file('setup.py', 'foo', 'ae02db') expect(ret).isinstance(github3.git.Commit) self.mock_assertions() def test_weekly_commit_count(self): self.response('weekly_commit_count', ETag='"foobarbogus"') self.request.return_value.headers['Last-Modified'] = 'foo' self.get(self.api + 'stats/participation') w = self.repo.weekly_commit_count() self.assertTrue(w.get('owner') is not None) self.assertTrue(w.get('all') is not None) self.mock_assertions() self.response('', 202) w = self.repo.weekly_commit_count() self.assertEqual(w, {}) self.mock_assertions() def test_iter_commit_activity(self): self.response('commit_activity', _iter=True) self.get(self.api + 'stats/commit_activity') w = next(self.repo.iter_commit_activity()) expect(w).isinstance(dict) self.mock_assertions() def test_iter_contributor_statistics(self): self.response('contributor_statistics', _iter=True) self.get(self.api + 'stats/contributors') s = next(self.repo.iter_contributor_statistics()) expect(s).isinstance(repos.stats.ContributorStats) self.mock_assertions() def test_iter_code_frequency(self): self.response('code_frequency', _iter=True) self.get(self.api + 'stats/code_frequency') s = next(self.repo.iter_code_frequency()) expect(s).isinstance(list) self.mock_assertions() class TestContents(BaseCase): def __init__(self, methodName='runTest'): super(TestContents, self).__init__(methodName) self.contents = repos.contents.Contents(load('readme')) self.api = self.contents._api def setUp(self): super(TestContents, self).setUp() self.contents = repos.contents.Contents(self.contents.to_json(), self.g) def test_equality(self): contents = repos.contents.Contents(load('readme')) expect(self.contents) == contents contents.sha = 'fakesha' expect(self.contents) != contents def test_git_url(self): expect(self.contents.links['git']) == self.contents.git_url def test_html_url(self): expect(self.contents.links['html']) == self.contents.html_url def test_repr(self): expect(repr(self.contents)) == '<Content [{0}]>'.format('README.rst') def test_delete(self): self.response('create_content', 200) self.delete(self.api) self.conf = { 'data': { 'message': 'foo', 'sha': self.contents.sha, } } with expect.githuberror(): self.contents.delete(None) self.not_called() self.login() c = self.contents.delete('foo') expect(c).isinstance(github3.git.Commit) self.mock_assertions() def test_update(self): self.response('create_content', 200) self.put(self.api) self.conf = { 'data': { 'message': 'foo', 'content': 'Zm9vIGJhciBib2d1cw==', 'sha': self.contents.sha, } } with expect.githuberror(): self.contents.update(None, None) self.not_called() self.login() ret = self.contents.update('foo', b'foo bar bogus') expect(ret).isinstance(github3.git.Commit) self.mock_assertions() class TestDownload(BaseCase): def __init__(self, methodName='runTest'): super(TestDownload, self).__init__(methodName) self.dl = repos.download.Download(load('download')) self.api = ("https://api.github.com/repos/sigmavirus24/github3.py/" "downloads/338893") def setUp(self): super(TestDownload, self).setUp() self.dl = repos.download.Download(self.dl.to_json(), self.g) def test_repr(self): expect(repr(self.dl)) == '<Download [kr.png]>' def test_delete(self): self.response('', 204) self.delete(self.api) with expect.githuberror(): self.dl.delete() self.not_called() self.login() expect(self.dl.delete()).is_True() self.mock_assertions() def test_saveas(self): self.response('archive', 200) self.get(self.dl.html_url) o = mock_open() with patch('{0}.open'.format(__name__), o, create=True): with open('archive', 'wb+') as fd: expect(self.dl.saveas(fd)).is_True() o.assert_called_once_with('archive', 'wb+') fd = o() fd.write.assert_called_once_with(b'archive_data') self.mock_assertions() self.request.return_value.raw.seek(0) self.request.return_value._content_consumed = False self.dl.saveas() expect(os.path.isfile(self.dl.name)).is_True() os.unlink(self.dl.name) expect(os.path.isfile(self.dl.name)).is_False() self.request.return_value.raw.seek(0) self.request.return_value._content_consumed = False self.dl.saveas('tmp') expect(os.path.isfile('tmp')).is_True() os.unlink('tmp') expect(os.path.isfile('tmp')).is_False() self.response('', 404) expect(self.dl.saveas()).is_False() class TestHook(BaseCase): def __init__(self, methodName='runTest'): super(TestHook, self).__init__(methodName) self.hook = repos.hook.Hook(load('hook')) self.api = ("https://api.github.com/repos/sigmavirus24/github3.py/" "hooks/292492") def setUp(self): super(TestHook, self).setUp() self.hook = repos.hook.Hook(self.hook.to_json(), self.g) def test_equality(self): h = repos.hook.Hook(load('hook')) expect(self.hook) == h h.id = 1 expect(self.hook) != h def test_repr(self): expect(repr(self.hook)) == '<Hook [readthedocs]>' def test_delete(self): self.response('', 204) self.delete(self.api) with expect.githuberror(): self.hook.delete() self.not_called() self.login() expect(self.hook.delete()).is_True() self.mock_assertions() def test_delete_subscription(self): self.response('', 204) self.delete(self.api + '/subscription') with expect.githuberror(): self.hook.delete_subscription() self.not_called() self.login() expect(self.hook.delete_subscription()).is_True() self.mock_assertions() def test_edit(self): self.response('hook', 200) self.patch(self.api) data = { 'config': {'push': 'http://example.com'}, 'events': ['push'], 'add_events': ['fake_ev'], 'rm_events': ['fake_ev'], 'active': True, } self.conf = {'data': data.copy()} self.conf['data']['remove_events'] = data['rm_events'] del(self.conf['data']['rm_events']) with expect.githuberror(): self.hook.edit(**data) self.login() self.not_called() expect(self.hook.edit(**data)).is_True() self.mock_assertions() def test_edit_failed(self): self.response('', 404) self.patch(self.api) self.conf = {} self.login() expect(self.hook.edit()).is_False() self.mock_assertions() def test_test(self): # Funny name, no? self.response('', 204) self.post(self.api + '/tests') self.conf = {} with expect.githuberror(): self.hook.test() self.not_called() self.login() expect(self.hook.test()).is_True() self.mock_assertions() class TestRepoComment(BaseCase): def __init__(self, methodName='runTest'): super(TestRepoComment, self).__init__(methodName) self.comment = repos.comment.RepoComment(load('repo_comment')) self.api = ("https://api.github.com/repos/sigmavirus24/github3.py/" "comments/1380832") def setUp(self): super(TestRepoComment, self).setUp() self.comment = repos.comment.RepoComment(self.comment.to_json(), self.g) def test_delete(self): self.response('', 204) self.delete(self.api) with expect.githuberror(): self.comment.delete() self.not_called() self.login() expect(self.comment.delete()).is_True() self.mock_assertions() def test_repr(self): expect(repr(self.comment).startswith('<Repository Comment')) def test_update(self): self.post(self.api) self.response('repo_comment', 200) self.conf = {'data': {'body': 'This is a comment body'}} with expect.githuberror(): self.comment.update('foo') self.login() expect(self.comment.update(None)).is_False() self.not_called() expect(self.comment.update('This is a comment body')).is_True() self.mock_assertions() class TestRepoCommit(BaseCase): def __init__(self, methodName='runTest'): super(TestRepoCommit, self).__init__(methodName) self.commit = repos.commit.RepoCommit(load('commit')) self.api = ("https://api.github.com/repos/sigmavirus24/github3.py/" "commits/76dcc6cb4b9860034be81b7e58adc286a115aa97") def test_equality(self): c = repos.commit.RepoCommit(load('commit')) expect(self.commit) == c c.sha = 'fake' expect(self.commit) != c def test_repr(self): expect(repr(self.commit).startswith('<Repository Commit')).is_True() def test_diff(self): self.response('archive', 200) self.get(self.api) self.conf.update(headers={'Accept': 'application/vnd.github.diff'}) expect(self.commit.diff().startswith(b'archive_data')).is_True() self.mock_assertions() def test_patch(self): self.response('archive', 200) self.get(self.api) self.conf.update(headers={'Accept': 'application/vnd.github.patch'}) expect(self.commit.patch().startswith(b'archive_data')).is_True() self.mock_assertions() class TestComparison(BaseCase): def __init__(self, methodName='runTest'): super(TestComparison, self).__init__(methodName) self.comp = repos.comparison.Comparison(load('comparison')) self.api = ("https://api.github.com/repos/sigmavirus24/github3.py/" "compare/a811e1a270f65eecb65755eca38d888cbefcb0a7..." "76dcc6cb4b9860034be81b7e58adc286a115aa97") def test_repr(self): expect(repr(self.comp).startswith('<Comparison ')).is_True() def test_equality(self): comp = repos.comparison.Comparison(load('comparison')) expect(self.comp) == comp comp.commits.pop(0) expect(self.comp) != comp def test_diff(self): self.response('archive', 200) self.get(self.api) self.conf.update(headers={'Accept': 'application/vnd.github.diff'}) expect(self.comp.diff().startswith(b'archive_data')).is_True() self.mock_assertions() def test_patch(self): self.response('archive', 200) self.get(self.api) self.conf.update(headers={'Accept': 'application/vnd.github.patch'}) expect(self.comp.patch().startswith(b'archive_data')).is_True() self.mock_assertions()
from data import * from table import * def getSize(vec): sq_sum = 0 for i in vec: sq_sum+= i**2 return round(np.sqrt(sq_sum),4) #Define Billiard ball object class Ball: pos = np.array([0.0,0.0,0.0]) vel = np.array([0.0,0.0,0.0]) ang = np.array([0.0,0.0,0.0]) initial_vel = np.array([0.0,0.0,0.0]) collision_count = 0 def printLog(self,file): file.write(str(np.round(self.pos,4))+"\n") file.write(str(np.round(self.vel,4))+"\n") file.write(str(np.round(self.ang,4))+"\n") file.write("\n") def initPos(self,px,py,pz): self.pos[0]=px; self.pos[1]=py; self.pos[2]=pz def hitBall(self,phi,a,b,V0,theta): F = Mc*V0/tc*np.array([0,np.cos(theta),-np.sin(theta)]) Fconv = np.array([F[1]*np.sin(phi),-F[1]*np.cos(phi),F[2]]) if Fconv[2]<0: Fconv[2]=0 self.vel = tc/Mb*Fconv self.initial_vel = self.vel r = np.array([-a,-np.sqrt(Rb**2-a**2-b**2),b]) T = np.cross(r,F) Tconv = np.array([T[0]*np.cos(phi)+T[1]*np.sin(phi),T[0]*np.sin(phi)-T[1]*np.cos(phi),T[2]]) self.ang = tc/Ib*Tconv def proceed(self): self.pos = self.pos+self.vel*dt direction = self.vel/getSize(self.vel) #Compute relative velocity between Center-Floor rel_vel = self.vel + np.cross(Rb*np.array([0,0,1]),self.ang) if getSize(rel_vel)==0.0:#rolling self.vel = self.vel - direction*fr*G*dt temp= self.ang[2];self.ang[2]=0 self.ang = self.ang/getSize(self.ang) * getSize(self.vel)/Rb self.ang[2] = temp else :#sliding self.vel = self.vel - direction*fs*G*dt self.ang = self.ang - np.cross(np.array([0,0,1]),direction)*5*fs*G/(2*Rb)*dt self.ang[2] = self.ang[2] - 5*fsp*G/(2*Rb)*dt def detect_collision(self,table): angle = [] flag = False for i in np.arange(-np.pi,np.pi+0.01,0.01): point = self.pos[0]+Rb*np.cos(i),self.pos[1]+Rb*np.sin(i) if table[int(point[1]*SF),int(point[0]*SF)] == Obstacle: flag = True angle.append(i) if flag: angle_ = (angle[0]+angle[-1])/2 return [flag,-angle_] return [flag,0] def collide(self,angle): self.collision_count +=1 # print("=====ccc======") # print("pos: ",self.pos) # print("ang: ",angle/np.pi,"pi") # print(self.vel) vel_T = self.vel[0]*np.sin(angle)+self.vel[1]*np.cos(angle) vel_N = -self.vel[0]*np.cos(angle)+self.vel[1]*np.sin(angle) # print(vel_T) # print(vel_N) vel_N = -e*vel_N self.vel[0] = vel_T*np.sin(angle) - vel_N*np.cos(angle) self.vel[1] = vel_T*np.cos(angle) + vel_N*np.sin(angle) temp= self.ang[2];self.ang[2]=0 self.ang = self.ang/getSize(self.ang) * getSize(self.vel)/Rb self.ang[2] = temp # print(self.vel) # print("==============") def isStop(self): if getSize(self.vel)< 0.05*getSize(self.initial_vel): print("Ball stopped") return True return False
import csv from pathlib import Path from datetime import datetime import matplotlib.pyplot as plt path = Path("weather_data/death_valley_2021_simple.csv") lines = path.read_text().splitlines() reader = csv.reader(lines) header_row = next(reader) # Extract dates and high temperatures. dates, highs, lows = [], [], [] for row in reader: current_date = datetime.strptime(row[2], "%Y-%m-%d") try: high = int(row[3]) low = int(row[4]) except ValueError: print(f"Missing data for {current_date}") else: dates.append(current_date) highs.append(high) lows.append(low) # Plot the high and low temperatures. plt.style.use("seaborn") fig, ax = plt.subplots() ax.plot(dates, highs, color="red", alpha=0.5) ax.plot(dates, lows, color="blue", alpha=0.5) ax.fill_between(dates, highs, lows, facecolor="blue", alpha=0.1) # Format plot. ax.set_title("Daily High And Low Temperatures, 2021\nDeath Valley, CA", fontsize=20) ax.set_xlabel("", fontsize=16) fig.autofmt_xdate() ax.set_ylabel("Temperature (F)", fontsize=16) ax.tick_params(labelsize=16) plt.show()
import collections import numpy as np import scipy.ndimage import scipy.signal from numba import njit from scipy.special import logit, expit def make_nondecreasing(x): dx = np.diff(x) dx[dx < 0] = 0 return x[0] + np.r_[0, np.cumsum(dx)] def ceil_pow_2(k): if bin(k).count('1') > 1: k = 1 << k.bit_length() return k def box_filter(x, size, k=1, **kwargs): size = int(np.round(size)) y = x.copy() for _ in range(k): scipy.ndimage.uniform_filter1d(y, size, output=y, **kwargs) return y def box_bandpass(x, low_cut_size, high_cut_size, k=1, **kwargs): y = box_filter(x, high_cut_size, k=k, **kwargs) return y - box_filter(y, low_cut_size, k=k, **kwargs) def box_baseline(x, size, k=1, iters=10, **kwargs): orig = x.copy() for i in range(iters): x = box_filter(x, size, k=k, **kwargs) if i < iters - 1: x = np.minimum(orig, x) return x def baseline_gauss(x, sigma, iters): orig = x for i in range(iters): x = scipy.ndimage.gaussian_filter1d(x, sigma) if i < iters - 1: x = np.minimum(orig, x) return x def butter_bandpass(x, fs_hz, low_hz, high_hz, order=15, axis=-1): nyq_hz = 0.5 * fs_hz sos = scipy.signal.butter(order, [low_hz / nyq_hz, high_hz / nyq_hz], btype='bandpass', output='sos') return scipy.signal.sosfiltfilt(sos, x, axis=axis) def butter_lowpass(x, fs_hz, low_hz, order=15, axis=-1): nyq_hz = 0.5 * fs_hz sos = scipy.signal.butter(order, low_hz / nyq_hz, btype='lowpass', output='sos') return scipy.signal.sosfiltfilt(sos, x, axis=axis) def butter_highpass(x, fs_hz, high_hz, order=15, axis=-1): nyq_hz = 0.5 * fs_hz sos = scipy.signal.butter(order, high_hz / nyq_hz, btype='highpass', output='sos') return scipy.signal.sosfiltfilt(sos, x, axis=axis) def gauss_smooth(x, sigma): n = len(x) n_nextpow2 = int(2 ** np.ceil(np.log2(n))) f = 2 * np.pi * np.fft.fftfreq(n_nextpow2) ft = np.exp(-0.5 * (f * sigma) ** 2) x_smooth = np.fft.ifft(ft * np.fft.fft(x, n_nextpow2))[:n] if np.isrealobj(x): return x_smooth.real else: return x_smooth @njit def find_extrema(x): """ Finds peaks and troughs in x and stores them in m. Ensures that no two peaks exist without a trough between them and visa-versa. Also ensures that find_extrema(m_pos, x) and find_extrema(m_neg, -x) implies that m_pos == -m_neg. :param x: input array for which to inspect for peaks and troughs, must of length >= 2. :return: int8 array equal length to x, storing values -1 for trough, 1 for peak, and 0 for neither """ # although the word "gradient" or "grad" is used here, # it is meant as the gradient sign or direction only rather than the sign and magnitude of the gradient m = np.empty(len(x), dtype=np.int8) # if negative gradient, then we consider the end a peak, positive gradient is a trough, otherwise neither m[0] = int(np.sign(x[0] - x[1])) grad_mem = 0 for i in range(1, len(x) - 1): # obtain the direction of the gradient before and after i grad_prev = int(np.sign(x[i] - x[i - 1])) grad_next = int(np.sign(x[i + 1] - x[i])) # carry the last non-zero gradient through if we're in a plateau (unless grad_mem is also 0 from start) if grad_prev == 0: grad_prev = grad_mem # p = grad_prev (could be current or carried over from grad_mem) # n = grad_next # a = any (can be either -1, 0, or 1, inconsequential which) # # can get this by using this # p n -> m n-p p*n (n-p)*p*n # ---------------------------------------------- # 0 a -> 0 a 0 0 # a 0 -> 0 -a 0 0 # -1 -1 -> 0 0 1 0 # 1 1 -> 0 0 1 0 # -1 1 -> -1 2 -1 -2 # 1 -1 -> 1 -2 -1 2 # m[i] will contain 1 for a peak, -1 for a trough, and 0 if neither, based on the above table m[i] = np.sign((grad_next - grad_prev) * grad_prev * grad_next) # remember the gradient so that it may be carried forward when we enter a plateau if grad_prev != 0: grad_mem = grad_prev # if positive gradient, then we consider the end a peak, negative gradient is a trough, otherwise neither m[-1] = int(np.sign(x[-1] - x[-2])) return m def mean_coh_logit(coh, weights=None, axis=None): # logit transform of R, ensuring to nan out any infinities z = logit(np.sqrt(coh)) z[np.isinf(z)] = np.nan if axis is None: z = np.nanmean(z) else: # this is needed since nanmean doesn't accept a tuple as the axis argument, so we need to loop over each axis if not isinstance(axis, collections.Iterable): axis = (axis, ) # perform the mean over each desired axis zm = np.ma.array(z, mask=np.isnan(z)) zm = np.ma.average(zm, axis=axis, weights=weights) z = zm.filled() # inverse logit transform, returning to R^2 return expit(z) ** 2 def mean_coh_fisher(coh, weights=None, axis=None): # Fisher transform, ensuring to nan out any infinities z = np.arctanh(np.sqrt(coh)) z[np.isinf(z)] = np.nan if axis is None: z = np.nanmean(z) else: # this is needed since nanmean doesn't accept a tuple as the axis argument, so we need to loop over each axis if not isinstance(axis, collections.Iterable): axis = (axis, ) # perform the mean over each desired axis zm = np.ma.array(z, mask=np.isnan(z)) zm = np.ma.average(zm, axis=axis, weights=weights) z = zm.filled() # inverse Fisher transform return np.tanh(z) ** 2 def noise_spec_func(t, spec_func): dt = t[1] - t[0] f = np.fft.fftfreq(2 * len(t) + 1, d=dt) phases = np.random.uniform(0, 2 * np.pi, len(f)) phases[:len(t)] = phases[len(t)+1:] c = spec_func(f) * np.exp(1j * phases) c[0] = 0 c[-1] = 0 y = np.fft.ifft(c)[:len(t)].real return y, f[:len(t)] def decim_half(x, is_time=False, reduce='mean'): # TODO currently runs on axis=0, allow an "axis" keyword to run on other axes if x.shape[0] % 2 != 0: x = x[:-1, ...] if is_time: x = x[::2, ...] else: if reduce == 'mean': x = 0.5 * (x[::2, ...] + x[1::2, ...]) elif reduce == 'max': x = np.maximum(x[::2, ...], x[1::2, ...]) elif reduce == 'min': x = np.minimum(x[::2, ...], x[1::2, ...]) return x def scale01(x): return (x - x.min()) / (x.max() - x.min()) @njit def viterbi(start_lp, trans_lp, emit_lp): """ Viterbi algorithm for n samples and k states :param start_lp: size k array of initial log probabilities (for the state just prior to the first emit sample), :param trans_lp: size k*k array of transition log probabilities with trans_lp[b, a] from state a to b, :param emit_lp: size n*k array of emission log probabilities, :return: pair (seq, lp) where seq is a size n array of most-likely hidden states in {0, 1, ..., k-1}, and lp is the log probability of the sequence. """ n, k = emit_lp.shape lp = np.zeros_like(emit_lp) # state_from[i, a] is the state at i-1 that we transitioned from to get to state a states_from = np.zeros((n, k), dtype=np.int64) # forward (initial step) for state_to in range(k): lp_s = emit_lp[0] + start_lp state_from = np.argmax(lp_s) states_from[0, state_to] = state_from lp[0, state_to] = lp_s[state_from] # forward (remaining steps) for i in range(1, n): for state_to in range(k): lp_s = emit_lp[i] + lp[i - 1] + trans_lp[state_to] state_from = np.argmax(lp_s) states_from[i, state_to] = state_from lp[i, state_to] = lp_s[state_from] # backward seq = np.zeros(n, dtype=np.int64) i = n - 1 seq[i] = np.argmax(lp[i]) while i >= 0: seq[i - 1] = states_from[i, seq[i]] i -= 1 return seq, np.max(lp[-1]) def xcorr(x, y, normalized=True): """ Cross-correlation between x and y using numpy.correlate(x, y, mode='full'). This results in lags where a negative lag means x comes before y, and positive lag x comes after y. As a mneumonic, think of it as a subtraction t_x - t_y, with a lower time for x meaning it comes before y and has a negative lag. :param x: size n signal array, :param y: size n signal array, :param normalized: bool on whether to use the normalized cross-correlation (default True), :return: pair (xc, lags) where xc is an array of length 2*n-1 of the values of correlation, and lags is an array of length 2*n-1 of lags in index units, with lags[n-1] representing 0 lag. """ # correlate y and x, # a negative lag means x occurs before y # a positive lag means x occurs after y xc = np.correlate(x, y, mode='full') n = len(x) lag0_idx = n - 1 if normalized: x_auto = np.correlate(x, x, mode='full') y_auto = np.correlate(y, y, mode='full') xc /= np.sqrt(x_auto[lag0_idx] * y_auto[lag0_idx]) lags = (np.arange(2 * n - 1) - lag0_idx) return xc, lags def consecutive(data, stepsize=1): """ Thanks to https://stackoverflow.com/a/7353335/142712. Find consecutive sequences in data. To get indexes of subsequences satsfying some predicate (e.g. > 0) do for example: idxs = consecutive(np.where(x > 0)[0]) """ return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
#!/usr/bin/env python """ Author: Loic Dutrieux Date: 2018-05-07 Purpose: Query the result of a classification and write the results to a vector file on disk """ from madmex.management.base import AntaresBaseCommand from madmex.models import Country, Region, PredictClassification from madmex.util.spatial import feature_transform import fiona from fiona.crs import from_string import json import logging logger = logging.getLogger(__name__) def write_to_file(fc, filename, layer, driver, crs): # Define output file schema schema = {'geometry': 'Polygon', 'properties': {'class':'str', 'code':'int'}} # Write to file logger.info('Writing feature collection to file') crs = from_string(crs) with fiona.open(filename, 'w', encoding='utf-8', schema=schema, driver=driver, layer=layer, crs=crs) as dst: write = dst.write [write(feature) for feature in fc] class Command(AntaresBaseCommand): help = """ Query the result of a classification and write the results to a vector file on disk -------------- Example usage: -------------- # Query classification performed for the state of Jalisco and write it to ESRI Shapfile antares db_to_vector --region Jalisco --name s2_001_jalisco_2017_bis_rf_1 --filename Jalisco_s2.shp # Query classification performed for the state of Jalisco and write it to Geopackage antares db_to_vector --region Jalisco --name s2_001_jalisco_2017_bis_rf_1 --filename madmex_mexico.shp --layer Jalisco --driver GPKG # With reprojection antares db_to_vector --region Jalisco --name s2_001_jalisco_2017_bis_rf_1 --filename Jalisco_s2.shp --proj4 '+proj=lcc +lat_1=17.5 +lat_2=29.5 +lat_0=12 +lon_0=-102 +x_0=2500000 +y_0=0 +a=6378137 +b=6378136.027241431 +units=m +no_defs' """ def add_arguments(self, parser): parser.add_argument('-n', '--name', type=str, default=None, help='Name of the classification to export to file') parser.add_argument('-region', '--region', type=str, default=None, help=('Name of the region over which the recipe should be applied. The geometry of the region should be present ' 'in the madmex-region or the madmex-country table of the database (Overrides lat and long when present) ' 'Use ISO country code for country name')) parser.add_argument('-f', '--filename', type=str, default=None, help='Name of the output filename. Can be an existing file if --layer is specified and the driver used support multiple layers') parser.add_argument('-l', '--layer', type=str, default=None, help='Name of the layer (only for drivers that support multi-layer files)') parser.add_argument('-d', '--driver', type=str, default='ESRI Shapefile', help='OGR driver to use for writting the data to file. Defaults to ESRI Shapefile') parser.add_argument('-p', '--proj4', type=str, default=None, help='Optional proj4 string defining the output projection') def handle(self, *args, **options): name = options['name'] region = options['region'] filename = options['filename'] layer = options['layer'] driver = options['driver'] proj4 = options['proj4'] # Define function to convert query set object to feature def to_fc(x): geometry = json.loads(x.predict_object.the_geom.geojson) feature = {'type': 'feature', 'geometry': geometry, 'properties': {'class': x.tag.value, 'code': x.tag.numeric_code}} return feature # Query country or region contour try: region = Country.objects.get(name=region).the_geom except Country.DoesNotExist: region = Region.objects.get(name=region).the_geom # Query objects logger.info('Querying the database for intersecting records') qs = PredictClassification.objects.filter(name=name) qs = qs.filter(predict_object__the_geom__intersects=region).prefetch_related('predict_object', 'tag') # Convert query set to feature collection generator logger.info('Generating feature collection') fc = (to_fc(x) for x in qs) crs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' if proj4 is not None: fc = (feature_transform(x, crs_out=proj4) for x in fc) crs = proj4 write_to_file(fc, filename, layer=layer, driver=driver, crs=crs)
""" CALM Copyright (c) 2021-present NAVER Corp. MIT license """ __all__ = ['activation_map'] def activation_map(model, images, targets, score_map_process, superclass=None, **kwargs): cams = model(images, targets, superclass, return_cam=score_map_process) return cams
import os import cv2 from base_camera import BaseCamera faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') class Camera(BaseCamera): video_source = 0 def __init__(self): if os.environ.get('OPENCV_CAMERA_SOURCE'): Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE'])) super(Camera, self).__init__() @staticmethod def set_video_source(source): Camera.video_source = source @staticmethod def frames(): camera = cv2.VideoCapture(Camera.video_source) if not camera.isOpened(): raise RuntimeError('Could not start camera.') while True: # read current frame _, img = camera.read() ## ----- Call your model here ----- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) ) for (x,y,w,h) in faces: img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # encode as a jpeg image and return it yield cv2.imencode('.jpg', img)[1].tobytes()
def myfunc(*args): out = [] for num in args: if num%2==0: out.append(num) return out
from bs4 import BeautifulSoup as bs from cleantext import clean from langdetect import detect def form_elements(soup): form_count = 0 input_count = 0 for form in soup.find_all("form"): form_count += 1 for input_element in form.find_all("input"): input_count += 1 return form_count, input_count def img_elements(soup): return len(soup.find_all("img",{"src":True})) def getHtmlFea(soup): fc, ic = form_elements(soup) im = img_elements(soup) return fc, ic, im def checkEnglish(text): if detect(text) == 'en': return text return '' def getEnglishText(soup): try: for script in soup(["script", "style"]): script.extract() rawtext = soup.get_text() s = '\n'.join([line.strip() for line in rawtext.splitlines() if len(line.strip()) > 0]) return checkEnglish(s) except Exception as e: pass return '' def extractFeature(html): try: soup = bs(html, "html.parser") fc, ic, im = getHtmlFea(soup) text = getEnglishText(soup) return fc, ic, im, text except Exception as e: pass return 0,0,0,'',''
# heavily inspired by https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py import logging import os import platform import re import subprocess import sys from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import click import wandb from wandb import util from wandb.apis.internal import Api from wandb.errors import CommError, LaunchError if TYPE_CHECKING: # pragma: no cover from wandb.apis.public import Artifact as PublicArtifact # TODO: this should be restricted to just Git repos and not S3 and stuff like that _GIT_URI_REGEX = re.compile(r"^[^/|^~|^\.].*(git|bitbucket)") _VALID_IP_REGEX = r"^https?://[0-9]+(?:\.[0-9]+){3}(:[0-9]+)?" _VALID_PIP_PACKAGE_REGEX = r"^[a-zA-Z0-9_.-]+$" _VALID_WANDB_REGEX = r"^https?://(api.)?wandb" _WANDB_URI_REGEX = re.compile(r"|".join([_VALID_WANDB_REGEX, _VALID_IP_REGEX])) _WANDB_QA_URI_REGEX = re.compile( r"^https?://ap\w.qa.wandb" ) # for testing, not sure if we wanna keep this _WANDB_DEV_URI_REGEX = re.compile( r"^https?://ap\w.wandb.test" ) # for testing, not sure if we wanna keep this _WANDB_LOCAL_DEV_URI_REGEX = re.compile( r"^https?://localhost" ) # for testing, not sure if we wanna keep this API_KEY_REGEX = r"WANDB_API_KEY=\w+" PROJECT_SYNCHRONOUS = "SYNCHRONOUS" PROJECT_DOCKER_ARGS = "DOCKER_ARGS" UNCATEGORIZED_PROJECT = "uncategorized" LAUNCH_CONFIG_FILE = "~/.config/wandb/launch-config.yaml" _logger = logging.getLogger(__name__) LOG_PREFIX = f"{click.style('launch:', fg='magenta')}: " def _is_wandb_uri(uri: str) -> bool: return ( _WANDB_URI_REGEX.match(uri) or _WANDB_DEV_URI_REGEX.match(uri) or _WANDB_LOCAL_DEV_URI_REGEX.match(uri) or _WANDB_QA_URI_REGEX.match(uri) ) is not None def _is_wandb_dev_uri(uri: str) -> bool: return bool(_WANDB_DEV_URI_REGEX.match(uri)) def _is_wandb_local_uri(uri: str) -> bool: return bool(_WANDB_LOCAL_DEV_URI_REGEX.match(uri)) def _is_git_uri(uri: str) -> bool: return bool(_GIT_URI_REGEX.match(uri)) def sanitize_wandb_api_key(s: str) -> str: return str(re.sub(API_KEY_REGEX, "WANDB_API_KEY", s)) def set_project_entity_defaults( uri: Optional[str], api: Api, project: Optional[str], entity: Optional[str], launch_config: Optional[Dict[str, Any]], ) -> Tuple[str, str]: # set the target project and entity if not provided if uri is not None: if _is_wandb_uri(uri): _, uri_project, _ = parse_wandb_uri(uri) elif _is_git_uri(uri): uri_project = os.path.splitext(os.path.basename(uri))[0] else: uri_project = UNCATEGORIZED_PROJECT else: uri_project = UNCATEGORIZED_PROJECT if project is None: config_project = None if launch_config: config_project = launch_config.get("project") project = config_project or uri_project or UNCATEGORIZED_PROJECT if entity is None: config_entity = None if launch_config: config_entity = launch_config.get("entity") entity = config_entity or api.default_entity prefix = "" if platform.system() != "Windows" and sys.stdout.encoding == "UTF-8": prefix = "🚀 " wandb.termlog(f"{LOG_PREFIX}{prefix}Launching run into {entity}/{project}") return project, entity def construct_launch_spec( uri: Optional[str], job: Optional[str], api: Api, name: Optional[str], project: Optional[str], entity: Optional[str], docker_image: Optional[str], resource: Optional[str], entry_point: Optional[List[str]], version: Optional[str], parameters: Optional[Dict[str, Any]], resource_args: Optional[Dict[str, Any]], launch_config: Optional[Dict[str, Any]], cuda: Optional[bool], run_id: Optional[str], ) -> Dict[str, Any]: """Constructs the launch specification from CLI arguments.""" # override base config (if supplied) with supplied args launch_spec = launch_config if launch_config is not None else {} if uri is not None: launch_spec["uri"] = uri if job is not None: launch_spec["job"] = job project, entity = set_project_entity_defaults( uri, api, project, entity, launch_config, ) launch_spec["entity"] = entity launch_spec["project"] = project if name: launch_spec["name"] = name if "docker" not in launch_spec: launch_spec["docker"] = {} if docker_image: launch_spec["docker"]["docker_image"] = docker_image if "resource" not in launch_spec: launch_spec["resource"] = resource or "local" if "git" not in launch_spec: launch_spec["git"] = {} if version: launch_spec["git"]["version"] = version if "overrides" not in launch_spec: launch_spec["overrides"] = {} if parameters: override_args = util._user_args_to_dict( launch_spec["overrides"].get("args", []) ) base_args = override_args launch_spec["overrides"]["args"] = merge_parameters(parameters, base_args) elif isinstance(launch_spec["overrides"].get("args"), list): launch_spec["overrides"]["args"] = util._user_args_to_dict( launch_spec["overrides"].get("args") ) if resource_args: launch_spec["resource_args"] = resource_args if entry_point: launch_spec["overrides"]["entry_point"] = entry_point if cuda is not None: launch_spec["cuda"] = cuda if run_id is not None: launch_spec["run_id"] = run_id return launch_spec def validate_launch_spec_source(launch_spec: Dict[str, Any]) -> None: uri = launch_spec.get("uri") job = launch_spec.get("job") docker_image = launch_spec.get("docker", {}).get("docker_image") if not bool(uri) and not bool(job) and not bool(docker_image): raise LaunchError("Must specify a uri, job or docker image") elif bool(uri) and bool(docker_image): raise LaunchError("Found both uri and docker-image, only one can be set") elif sum(map(bool, [uri, job, docker_image])) > 1: raise LaunchError("Must specify exactly one of uri, job or image") def parse_wandb_uri(uri: str) -> Tuple[str, str, str]: """Parses wandb uri to retrieve entity, project and run name.""" uri = uri.split("?")[0] # remove any possible query params (eg workspace) stripped_uri = re.sub(_WANDB_URI_REGEX, "", uri) stripped_uri = re.sub( _WANDB_DEV_URI_REGEX, "", stripped_uri ) # also for testing just run it twice stripped_uri = re.sub( _WANDB_LOCAL_DEV_URI_REGEX, "", stripped_uri ) # also for testing just run it twice stripped_uri = re.sub( _WANDB_QA_URI_REGEX, "", stripped_uri ) # also for testing just run it twice try: entity, project, _, name = stripped_uri.split("/")[1:] except ValueError as e: raise LaunchError(f"Trouble parsing wandb uri {uri}: {e}") return entity, project, name def is_bare_wandb_uri(uri: str) -> bool: """Checks if the uri is of the format /entity/project/runs/run_name""" _logger.info(f"Checking if uri {uri} is bare...") if not uri.startswith("/"): return False result = uri.split("/")[1:] # a bare wandb uri will have 4 parts, with the last being the run name # and the second last being "runs" if len(result) == 4 and result[-2] == "runs": return True return False def fetch_wandb_project_run_info( entity: str, project: str, run_name: str, api: Api ) -> Any: _logger.info("Fetching run info...") try: result = api.get_run_info(entity, project, run_name) except CommError: result = None if result is None: raise LaunchError( f"Run info is invalid or doesn't exist for {api.settings('base_url')}/{entity}/{project}/runs/{run_name}" ) if result.get("codePath") is None: # TODO: we don't currently expose codePath in the runInfo endpoint, this downloads # it from wandb-metadata.json if we can. metadata = api.download_url( project, "wandb-metadata.json", run=run_name, entity=entity ) if metadata is not None: _, response = api.download_file(metadata["url"]) data = response.json() result["codePath"] = data.get("codePath") result["cudaVersion"] = data.get("cuda", None) if result.get("args") is not None: result["args"] = util._user_args_to_dict(result["args"]) return result def download_entry_point( entity: str, project: str, run_name: str, api: Api, entry_point: str, dir: str ) -> bool: metadata = api.download_url( project, f"code/{entry_point}", run=run_name, entity=entity ) if metadata is not None: _, response = api.download_file(metadata["url"]) with util.fsync_open(os.path.join(dir, entry_point), "wb") as file: for data in response.iter_content(chunk_size=1024): file.write(data) return True return False def download_wandb_python_deps( entity: str, project: str, run_name: str, api: Api, dir: str ) -> Optional[str]: reqs = api.download_url(project, "requirements.txt", run=run_name, entity=entity) if reqs is not None: _logger.info("Downloading python dependencies") _, response = api.download_file(reqs["url"]) with util.fsync_open( os.path.join(dir, "requirements.frozen.txt"), "wb" ) as file: for data in response.iter_content(chunk_size=1024): file.write(data) return "requirements.frozen.txt" return None def get_local_python_deps( dir: str, filename: str = "requirements.local.txt" ) -> Optional[str]: try: env = os.environ with open(os.path.join(dir, filename), "w") as f: subprocess.call(["pip", "freeze"], env=env, stdout=f) return filename except subprocess.CalledProcessError as e: wandb.termerror(f"Command failed: {e}") return None def diff_pip_requirements(req_1: List[str], req_2: List[str]) -> Dict[str, str]: """Returns a list of pip requirements that are not in req_1 but are in req_2.""" def _parse_req(req: List[str]) -> Dict[str, str]: # TODO: This can be made more exhaustive, but for 99% of cases this is fine # see https://pip.pypa.io/en/stable/reference/requirements-file-format/#example d: Dict[str, str] = dict() for line in req: _name: str = None # type: ignore _version: str = None # type: ignore if line.startswith("#"): # Ignore comments continue elif "git+" in line or "hg+" in line: _name = line.split("#egg=")[1] _version = line.split("@")[-1].split("#")[0] elif "==" in line: _s = line.split("==") _name = _s[0].lower() _version = _s[1].split("#")[0].strip() elif ">=" in line: _s = line.split(">=") _name = _s[0].lower() _version = _s[1].split("#")[0].strip() elif ">" in line: _s = line.split(">") _name = _s[0].lower() _version = _s[1].split("#")[0].strip() elif re.match(_VALID_PIP_PACKAGE_REGEX, line) is not None: _name = line else: raise ValueError(f"Unable to parse pip requirements file line: {line}") if _name is not None: assert re.match( _VALID_PIP_PACKAGE_REGEX, _name ), f"Invalid pip package name {_name}" d[_name] = _version return d # Use symmetric difference between dict representation to print errors try: req_1_dict: Dict[str, str] = _parse_req(req_1) req_2_dict: Dict[str, str] = _parse_req(req_2) except (AssertionError, ValueError, IndexError, KeyError) as e: raise LaunchError(f"Failed to parse pip requirements: {e}") diff: List[Tuple[str, str]] = [] for item in set(req_1_dict.items()) ^ set(req_2_dict.items()): diff.append(item) # Parse through the diff to make it pretty pretty_diff: Dict[str, str] = {} for name, version in diff: if pretty_diff.get(name) is None: pretty_diff[name] = version else: pretty_diff[name] = f"v{version} and v{pretty_diff[name]}" return pretty_diff def validate_wandb_python_deps( requirements_file: Optional[str], dir: str, ) -> None: """Warns if local python dependencies differ from wandb requirements.txt""" if requirements_file is not None: requirements_path = os.path.join(dir, requirements_file) with open(requirements_path) as f: wandb_python_deps: List[str] = f.read().splitlines() local_python_file = get_local_python_deps(dir) if local_python_file is not None: local_python_deps_path = os.path.join(dir, local_python_file) with open(local_python_deps_path) as f: local_python_deps: List[str] = f.read().splitlines() diff_pip_requirements(wandb_python_deps, local_python_deps) return _logger.warning("Unable to validate local python dependencies") def fetch_project_diff( entity: str, project: str, run_name: str, api: Api ) -> Optional[str]: """Fetches project diff from wandb servers.""" _logger.info("Searching for diff.patch") patch = None try: (_, _, patch, _) = api.run_config(project, run_name, entity) except CommError: pass return patch def apply_patch(patch_string: str, dst_dir: str) -> None: """Applies a patch file to a directory.""" _logger.info("Applying diff.patch") with open(os.path.join(dst_dir, "diff.patch"), "w") as fp: fp.write(patch_string) try: subprocess.check_call( [ "patch", "-s", f"--directory={dst_dir}", "-p1", "-i", "diff.patch", ] ) except subprocess.CalledProcessError: raise wandb.Error("Failed to apply diff.patch associated with run.") def _fetch_git_repo(dst_dir: str, uri: str, version: Optional[str]) -> str: """Clones the git repo at ``uri`` into ``dst_dir``. checks out commit ``version`` (or defaults to the head commit of the repository's master branch if version is unspecified). Assumes authentication parameters are specified by the environment, e.g. by a Git credential helper. """ # We defer importing git until the last moment, because the import requires that the git # executable is available on the PATH, so we only want to fail if we actually need it. import git # type: ignore _logger.info("Fetching git repo") repo = git.Repo.init(dst_dir) origin = repo.create_remote("origin", uri) origin.fetch() if version is not None: try: repo.git.checkout(version) except git.exc.GitCommandError as e: raise LaunchError( "Unable to checkout version '%s' of git repo %s" "- please ensure that the version exists in the repo. " "Error: %s" % (version, uri, e) ) else: if getattr(repo, "references", None) is not None: branches = [ref.name for ref in repo.references] else: branches = [] # Check if main is in origin, else set branch to master if "main" in branches or "origin/main" in branches: version = "main" else: version = "master" try: repo.create_head(version, origin.refs[version]) repo.heads[version].checkout() wandb.termlog(f"No git branch passed. Defaulted to branch: {version}") except (AttributeError, IndexError) as e: raise LaunchError( "Unable to checkout default version '%s' of git repo %s " "- to specify a git version use: --git-version \n" "Error: %s" % (version, uri, e) ) repo.submodule_update(init=True, recursive=True) return version def merge_parameters( higher_priority_params: Dict[str, Any], lower_priority_params: Dict[str, Any] ) -> Dict[str, Any]: """Merge the contents of two dicts, keeping values from higher_priority_params if there are conflicts.""" return {**lower_priority_params, **higher_priority_params} def convert_jupyter_notebook_to_script(fname: str, project_dir: str) -> str: nbconvert = wandb.util.get_module( "nbconvert", "nbformat and nbconvert are required to use launch with notebooks" ) nbformat = wandb.util.get_module( "nbformat", "nbformat and nbconvert are required to use launch with notebooks" ) _logger.info("Converting notebook to script") new_name = fname.rstrip(".ipynb") + ".py" with open(os.path.join(project_dir, fname)) as fh: nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT) exporter = nbconvert.PythonExporter() source, meta = exporter.from_notebook_node(nb) with open(os.path.join(project_dir, new_name), "w+") as fh: fh.writelines(source) return new_name def check_and_download_code_artifacts( entity: str, project: str, run_name: str, internal_api: Api, project_dir: str ) -> Optional["PublicArtifact"]: _logger.info("Checking for code artifacts") public_api = wandb.PublicApi( overrides={"base_url": internal_api.settings("base_url")} ) run = public_api.run(f"{entity}/{project}/{run_name}") run_artifacts = run.logged_artifacts() for artifact in run_artifacts: if hasattr(artifact, "type") and artifact.type == "code": artifact.download(project_dir) return artifact # type: ignore return None def to_camel_case(maybe_snake_str: str) -> str: if "_" not in maybe_snake_str: return maybe_snake_str components = maybe_snake_str.split("_") return "".join(x.title() if x else "_" for x in components) def run_shell(args: List[str]) -> Tuple[str, str]: out = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return out.stdout.decode("utf-8").strip(), out.stderr.decode("utf-8").strip() def validate_build_and_registry_configs( build_config: Dict[str, Any], registry_config: Dict[str, Any] ) -> None: build_config_credentials = build_config.get("credentials", {}) registry_config_credentials = registry_config.get("credentials", {}) if ( build_config_credentials and registry_config_credentials and build_config_credentials != registry_config_credentials ): raise LaunchError("registry and build config credential mismatch") def get_kube_context_and_api_client( kubernetes: Any, # noqa: F811 resource_args: Dict[str, Any], # noqa: F811 ) -> Tuple[Any, Any]: config_file = resource_args.get("config_file", None) context = None if config_file is not None or os.path.exists(os.path.expanduser("~/.kube/config")): # context only exist in the non-incluster case all_contexts, active_context = kubernetes.config.list_kube_config_contexts( config_file ) context = None if resource_args.get("context"): context_name = resource_args["context"] for c in all_contexts: if c["name"] == context_name: context = c break raise LaunchError(f"Specified context {context_name} was not found.") else: context = active_context kubernetes.config.load_kube_config(config_file, context["name"]) api_client = kubernetes.config.new_client_from_config( config_file, context=context["name"] ) return context, api_client else: kubernetes.config.load_incluster_config() api_client = kubernetes.client.api_client.ApiClient() return context, api_client def resolve_build_and_registry_config( default_launch_config: Optional[Dict[str, Any]], build_config: Optional[Dict[str, Any]], registry_config: Optional[Dict[str, Any]], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: resolved_build_config: Dict[str, Any] = {} if build_config is None and default_launch_config is not None: resolved_build_config = default_launch_config.get("build", {}) elif build_config is not None: resolved_build_config = build_config resolved_registry_config: Dict[str, Any] = {} if registry_config is None and default_launch_config is not None: resolved_registry_config = default_launch_config.get("registry", {}) elif registry_config is not None: resolved_registry_config = registry_config validate_build_and_registry_configs(resolved_build_config, resolved_registry_config) return resolved_build_config, resolved_registry_config def check_logged_in(api: Api) -> bool: """ Uses an internal api reference to check if a user is logged in raises an error if the viewer doesn't load, likely broken API key expected time cost is 0.1-0.2 seconds """ res = api.api.viewer() if not res: raise LaunchError( "Could not connect with current API-key. " "Please relogin using `wandb login --relogin`" " and try again (see `wandb login --help` for more options)" ) return True
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import itertools import re import scrapy from datetime import datetime from functools import reduce class HcdnSpider(scrapy.Spider): name = "hcdn" allowed_domains = ["http://www.hcdn.gob.ar/proyectos/proyectoTP.jsp?exp="] def start_requests(self): projects = list() projects.append(("%04d-D-2011" % pid for pid in range(1, 6483))) projects.append(("%04d-D-2012" % pid for pid in range(1, 8781))) projects.append(("%04d-D-2013" % pid for pid in range(1, 8283))) projects.append(("%04d-D-2014" % pid for pid in range(1, 10017))) projects.append(("%04d-D-2015" % pid for pid in range(3, 6603))) projects.append(("%04d-D-2016" % pid for pid in range(2, 7918))) for project in itertools.chain(*projects): yield scrapy.Request(url="%s%s" % (self.allowed_domains[0], project), callback=self.parse) def parse(self, response): div = response.css('div.container.tabGral') project_type = div.css('h3::text').extract_first().lower().split()[-1] if project_type == 'ley': id, summary, date = div.css('h3').xpath('./parent::div/text()[normalize-space()]').extract() id = id.strip() summary = summary.strip() date = datetime.strptime(date.strip(), "%d/%m/%Y").strftime("%Y-%m-%d") law_text = div.css('#proyectosTexto').\ xpath(".//div[following-sibling::p and not(contains(@style, 'font-style:italic'))]/text()").extract() law_text = reduce(lambda x, y: x + ' ' + y, law_text, '') law_text = re.sub(r"\s+", " ", law_text) signers = list() for tr in div.css('#proyectosFirmantes').xpath('.//tr[child::td]'): congressman, district, party = tr.xpath('.//td/text()').extract() signers.append(dict( congressman=congressman.strip(), district=district.strip(), party=party.strip() )) dcommissions = div.css('#proyectosTramite')\ .xpath('.//table[preceding-sibling::div//text()=" Giro a comisiones en Diputados "]') if len(dcommissions) > 0: dcommissions = dcommissions[0].xpath('.//td/text()').extract() else: dcommissions = [] scommissions = div.css('#proyectosTramite') \ .xpath('.//table[preceding-sibling::div//text()=" Giro a comisiones en Senado "]') if len(scommissions) > 0: scommissions = scommissions[0].xpath('.//td/text()').extract() else: scommissions = [] results = [] for row in div.css('#proyectosTramite').xpath('.//table[preceding-sibling::div//text()=" Trámite "]')\ .xpath('.//tr[td]'): row = row.xpath('.//td/text()').extract() if len(row) == 4: chamber, _, rdate, result = row results.append(dict( chamber=chamber, result=result, date=datetime.strptime(rdate.strip(), "%d/%m/%Y").strftime("%Y-%m-%d") )) yield dict( id=id, summary=summary, date=date, law_text=law_text, signers=signers, dcommissions=dcommissions, scommissions=scommissions, results=results )
# practicing to scrape multiple pages on the web import requests from bs4 import BeautifulSoup # picking our site url = 'https://scrapingclub.com/exercise/list_basic/?page=1' # getting the response response = requests.get(url) # picking our parser soup = BeautifulSoup(response.text, 'lxml') items = soup.find_all('div', class_='col-lg-4 col-md-6 mb-4') count = 1 items = soup.find_all('div', class_='col-lg-4 col-md-6 mb-4') for i in items: item_name = i.find('h4', class_='card-title').text.strip('\n') item_price = i.find('h5').text print('%s ) Price: %s, Item Name: %s' % (count, item_price, item_name)) count = count + 1 pages = soup.find('ul', class_='pagination') urls = [] # getting all the links links = pages.find_all('a', class_='page-link') # try to convert to int for link in links: page_num = int(link.text) if link.text.isdigit() else None if page_num != None: x = link.get('href') urls.append(x) # See all items on page 1 print(urls) count = 1 for i in urls: new_url = url + i response = requests.get(new_url) items = soup.find_all('div', class_='col-lg-4 col-md-6 mb-4') for i in items: item_name = i.find('h4', class_='card-title').text.strip('\n') item_price = i.find('h5').text print('%s ) Price: %s, Item Name: %s' % (count, item_price, item_name)) count = count + 1
import math a = int(input("a 값? ")) b = int(input("b 값? ")) c = int(input("c 값? ")) 판별식 = b**2 - 4*a*c if 판별식 <0 : print("해가 없습니다.") elif 판별식 == 0 : print("해가 1개 입니다.") print("해 : %.2f" % (-b/2*a) ) elif 판별식 > 0 : 해1 = (-b + math.sqrt(판별식)) / (2*a) 해2 = (-b - math.sqrt(판별식)) / (2*a) print("해1: %.2f, 해2: %.2f" %(해1,해2) )
class Solution: def reverseBits(self, n: int) -> int: count = 31 num = 0 while n > 0: num = num + ((n&1) * 2**count) n = n >> 1 count -= 1 return num
class MathClock: # hour = 0 # minuts = 0 def __init__(self, hour = 0, minuts = 0): self.hour = hour self.minuts = minuts def __repr__(self): return repr(self.hour+self.minuts) def __add__(self, other): return MathClock(self.minuts + other) def __sub__(self, other): return MathClock(self.minuts - other) def __mul__(self, other): return MathClock(self.hour + other) def __truediv__(self, other): return MathClock(self.hour - other) def get_time(self): print(self.hour, self.minuts) return self.hour, self.minuts my_clock = MathClock() # print(repr(my_clock)) my_clock * 5 my_clock.get_time()
import keras from traitement_images import traitement_images import time model = keras.models.load_model("miniprojet_n_classes.h5") from cv2 import VideoCapture, imwrite # initialize the camera cam = VideoCapture(0) # 0 -> index of camera #cam = VideoCapture('http://192.168.1.36:4747/video') while(1): s, img = cam.read() imwrite("filename.jpg",img) while(s == False): s, img = cam.read() imwrite("filename.jpg",img) test = traitement_images("filename.jpg") res = model.predict(test) if (max(res[0]) == res[0][0]): print('BMW [' + "{:.2f}".format(100*res[0][0]) + '%]') elif (max(res[0]) == res[0][1]): print('Mercedes [' + "{:.2f}".format(100*res[0][1]) + '%]') elif (max(res[0]) == res[0][2]): print('Audi [' + "{:.2f}".format(100*res[0][2]) + '%]') else: print('Constructeur indéterminé') print("[{:.2f}".format(100*res[0][0]) + "%] [{:.2f}".format(100*res[0][1]) + "%] [{:.2f}".format(100*res[0][2]) + "%]") time.sleep(0.3) print('\n\n\n\n')
#!/usr/bin/env python from pru_speak import pru_speak import socket #Server on local host @ port 6060 TCP_IP = '127.0.0.1' TCP_PORT = 6060 #The max size upto which is recieved at one go BUFFER_SIZE = 1024 * 2 #create a passive socket and bind it to 127.0.0.1:6060 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) #Take max of one connection s.listen(1) print "PRU Speak server at ", TCP_IP + ":" + str(TCP_PORT) #connection is a one time affair - handles only one client conn, addr = s.accept() print 'Connection address:', addr while True: try: #blocking wait for data from client bs_code = conn.recv(BUFFER_SIZE) print "recieved : \n", bs_code, "\n" if (not bs_code) or (bs_code == 'EXIT'): break #send empty data to shutdown server try: ret = pru_speak.execute_instruction(bs_code) print "Return value : ", ret if ret == []: #no return value conn.send('\n') else: #the sends the list of ret values as a string sperated by " " conn.send(" ".join(map(str, ret)) + "\n") except Exception as e: print e except Exception as e: print "error : ", e break conn.close()
import hardware, cpu, time class ppu: def __init__(self, nes): self.DEBUG = 1 self.firstWrite = 0 self.mirroring = "vert" #PPU 2000 register indexes self.NMIOnVBlank = 0 self.ppuMasterSlave = 1 self.spriteSize = 2 self.backgroundPatternAddress = 3 self.spritePatternAddress = 4 self.ppuAddressIncrement = 5 self.baseNametableAddress = 6 #PPU 2001 register indexes self.grayscale = 7 self.backgroundClipping = 6 self.spriteClipping = 5 self.backgroundVisible = 4 self.spritesVisible = 3 #PPU 2006 register indexes self.prevVramAddress = 1 self.vramAddress = 0 self.scrollVert = 2 self.scrollHori = 3 def donothing(self, nesSystem): return 0 def nextScanline(self, nesSystem): if nesSystem.ppu.currentScanline < 240: #print "Clean up line from before" pass if nesSystem.ppu.currentScanline == 240: #print nesSystem.ppu.nameTables pass nesSystem.ppu.currentScanline += 1 if nesSystem.ppu.currentScanline == 262: nesSystem.ppu.currentScanline = 0 #print nesSystem.ppu.currentScanline, nesSystem.ppu.PPU2000Registers[0] #print nesSystem.ppu.PPU2000Registers[0] return ((nesSystem.ppu.currentScanline == nesSystem.ppu.ScanlinesofVBlank) and (nesSystem.ppu.PPU2000Registers[0] == 1)) #return True def controlRegister1Write(self, nesSystem, registerData): if (registerData & 128) == 128: nesSystem.ppu.PPU2000Registers[self.NMIOnVBlank] = 1 else: nesSystem.ppu.PPU2000Registers[self.NMIOnVBlank] = 0 if nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] == 255: if (registerData & 64) == 64: nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] = 0 else: nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] = 1 if (registerData & 32) == 32: nesSystem.ppu.PPU2000Registers[self.spriteSize] = 16 else: nesSystem.ppu.PPU2000Registers[self.spriteSize] = 8 if (registerData & 16) == 16: nesSystem.ppu.PPU2000Registers[self.backgroundPatternAddress] = 4096 #0x1000 else: nesSystem.ppu.PPU2000Registers[self.backgroundPatternAddress] = 0 #0x0000 if (registerData & 8) == 8: nesSystem.ppu.PPU2000Registers[self.spritePatternAddress] = 4096 #0x1000 else: nesSystem.ppu.PPU2000Registers[self.spritePatternAddress] = 0 #0x0000 if (registerData & 4) == 4: nesSystem.ppu.PPU2000Registers[self.ppuAddressIncrement] = 32 else: nesSystem.ppu.PPU2000Registers[self.ppuAddressIncrement] = 1 if (nesSystem.ppu.PPU2001Registers[self.backgroundVisible] == 1) or (nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] == 0xFF) or (nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] == 1): address = registerData & 0x3 if address == 0x0: nesSystem.ppu.PPU2000Registers[self.baseNametableAddress] = 0x2000 elif address == 0x1: nesSystem.ppu.PPU2000Registers[self.baseNametableAddress] = 0x2400 elif address == 0x2: nesSystem.ppu.PPU2000Registers[self.baseNametableAddress] = 0x2800 elif address == 0x3: nesSystem.ppu.PPU2000Registers[self.baseNametableAddress] = 0x2C00 if nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] == 0xFF: if (registerData & 0x40) == 0x40: nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] = 0 else: nesSystem.ppu.PPU2000Registers[self.ppuMasterSlave] = 1 def controlRegister2Write(self, nesSystem, registerData): if (registerData & 1) == 1: nesSystem.ppu.PPU2001Registers[self.grayscale] = 1 else: nesSystem.ppu.PPU2001Registers[self.grayscale] = 0 if (registerData & 2) == 2: nesSystem.ppu.PPU2001Registers[self.backgroundClipping] = 1 else: nesSystem.ppu.PPU2001Registers[self.backgroundClipping] = 0 if (registerData & 4) == 4: nesSystem.ppu.PPU2001Registers[self.spriteClipping] = 1 else: nesSystem.ppu.PPU2001Registers[self.spriteClipping] = 0 if (registerData & 8) == 8: nesSystem.ppu.PPU2001Registers[self.backgroundVisible] = 1 else: nesSystem.ppu.PPU2001Registers[self.backgroundVisible] = 0 if (registerData & 16) == 16: nesSystem.ppu.PPU2001Registers[self.spritesVisible] = 1 else: nesSystem.ppu.PPU2001Registers[self.spritesVisible] = 0 ppuColor = (registerData >> 5) #toggling between RGB def vRamRegister2Write(self, nesSystem, registerData): if self.firstWrite == 1: # if registerData == 1: #print "Found", nesSystem.cpu.programCounter #print "Register Data", registerData << 8, registerData # x = raw_input() nesSystem.ppu.PPU2006Registers[self.prevVramAddress] = nesSystem.ppu.PPU2006Registers[self.vramAddress] nesSystem.ppu.PPU2006Registers[self.vramAddress] = (registerData << 8) self.firstWrite = 0 else: nesSystem.ppu.PPU2006Registers[self.vramAddress] += registerData if (nesSystem.ppu.PPU2006Registers[self.prevVramAddress] == 0) and (nesSystem.ppu.currentScanline < 240): if ((nesSystem.ppu.PPU2006Registers[self.vramAddress] >= 8192) and (nesSystem.ppu.PPU2006Registers[self.vramAddress] <= 9216)): nesSystem.ppu.PPU2006Registers[self.scrollHori] = (((nesSystem.ppu.PPU2006Registers[self.vramAddress] - 8192) / 32) * 8 - nesSystem.ppu.currentScanline) self.firstWrite = 1 def vRamRegister1Write(self, nesSystem, registerData): if self.firstWrite == 1: nesSystem.ppu.PPU2006Registers[self.scrollVert] = registerData self.firstWrite = 0 else: nesSystem.ppu.PPU2006Registers[self.scrollHori] = registerData if nesSystem.ppu.PPU2006Registers[self.scrollVert] > 239: nesSystem.ppu.PPU2006Registers[self.scrollVert] = 0 self.firstWrite = 1 def ppuDataRegisterWrite(self, nesSystem, registerData): time.sleep(0.0001) address = nesSystem.ppu.PPU2006Registers[self.vramAddress] # print address if nesSystem.ppu.PPU2006Registers[self.vramAddress] < 0x2000: pass elif (nesSystem.ppu.PPU2006Registers[self.vramAddress] >= 0x2000) and (nesSystem.ppu.PPU2006Registers[self.vramAddress] < 0x3f00): if self.mirroring == "hori": pass elif self.mirroring == "vert": if address == 0x2000: nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x2000] = registerData elif address == 0x2400: nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x2000] = registerData elif address == 0x2800: nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x800 - 0x2000] = registerData elif address == 0x2C00: nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x800 - 0x2000] = registerData elif self.mirroring == "onescreen": pass else: nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x2000] = registerData elif (nesSystem.ppu.PPU2006Registers[self.vramAddress] >= 0x3f00) and (nesSystem.ppu.PPU2006Registers[self.vramAddress] < 0x3f20): nesSystem.ppu.nameTables[nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x2000] = registerData if ((nesSystem.ppu.PPU2006Registers[self.vramAddress] & 0x7) == 0): nesSystem.ppu.nameTables[(nesSystem.ppu.PPU2006Registers[self.vramAddress] - 0x2000) ^ 0x10] = registerData nesSystem.ppu.PPU2006Registers[self.vramAddress] += nesSystem.ppu.PPU2000Registers[self.ppuAddressIncrement] def ppuDataRegisterRead(self, nesSystem, registerData): #if nesSystem.ppu.PPU2006Registers[self.vramAddress] < 8192: #0x2000 pass def spriteAddressRegisterWrite(self, nesSystem, registerData): pass def statusRegisterRead(self, nesSystem): data = 0 if nesSystem.ppu.currentScanline == 240: #nesSystem.ppu.currentScanline = 0 data |= 128 self.firstWrite = 1 return data
import pygame import random import math from pygame import mixer # initialization pygame.init() # create the screen screen = pygame.display.set_mode((800, 620)) # background background = pygame.image.load('background.png') #bg sound mixer.music.load('background.wav') mixer.music.play(-1) # title and icon pygame.display.set_caption("Space Invendera") icon = pygame.image.load('battleship.png') pygame.display.set_icon(icon) # player playerimg = pygame.image.load('transport.png') playerx = 370 playery = 480 playerx_change = 0 # enemy enemyimg = [] enemyx = [] enemyy = [] enemyx_change = [] enemyy_change = [] number_of_enemies = 6 for i in range(number_of_enemies): enemyimg.append(pygame.image.load('enemy.png')) enemyx.append(random.randint(0, 800)) enemyy.append(random.randint(50, 150)) enemyx_change.append(2.5) enemyy_change.append(40) # bullet bulletimg = pygame.image.load('bullet.png') bulletx = 0 bullety = 480 bulletx_change = 0 bullety_change = 10 bullet_state = "ready" #score score_value = 0 font = pygame.font.Font('freesansbold.ttf',32) textx = 10 texty = 10 #game over txt over_font = pygame.font.Font('freesansbold.ttf',64) def show_score(x ,y): score = font.render("score :"+ str(score_value),True, (255, 255, 255)) screen.blit(score, (x, y)) def game_over_text(): over_txt = over_font.render("GAME OVER", True, (255, 255, 255)) screen.blit(over_txt, (200, 250)) # for display player img def player(x, y): screen.blit(playerimg, (x, y)) # foe desplaing enemy img def enemy(x, y ,i): screen.blit(enemyimg[i], (x, y)) def fire_bullet(x, y): global bullet_state bullet_state = "fire" screen.blit(bulletimg, (x + 16, y + 10)) def iscollision(enemyx, enemyy, bulletx, bullety): distance = math.sqrt((math.pow(enemyx - bulletx, 2)) + (math.pow(enemyy - bullety, 2))) if distance < 27: return True else: return False # game loop running = True while running: screen.fill((0, 0, 0)) # for bg img screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if keystroke in pressed whether it is right of left if (event.type == pygame.KEYDOWN): if (event.key == pygame.K_LEFT): playerx_change = -5 if (event.key == pygame.K_RIGHT): playerx_change = 5 if (event.key == pygame.K_SPACE): if bullet_state == "ready": bullet_sound = mixer.Sound('laser.wav') bullet_sound.play() bulletx = playerx fire_bullet(bulletx, bullety) if (event.type == pygame.KEYUP): if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerx_change = 0 playerx += playerx_change # create boundry for player if playerx <= 0: playerx = 0 elif playerx >= 736: playerx = 736 for i in range(number_of_enemies): #game over if enemyy[i] > 440: for j in range(number_of_enemies): enemyy[j] = 2000 game_over_text() break enemyx[i] += enemyx_change[i] # create boundry for enemy if enemyx[i] <= 0: enemyx_change[i] = 2.5 enemyy[i] += enemyy_change[i] elif enemyx[i] >= 736: enemyx_change[i] = -2.5 enemyy[i] += enemyy_change[i] # collision collision = iscollision(enemyx[i], enemyy[i], bulletx, bullety) if collision: explossion_sound = mixer.Sound('explosion.wav') explossion_sound.play() bullety = 480 bullet_state = "ready" score_value += 1 enemyx[i] = random.randint(0, 800) enemyy[i] = random.randint(50, 150) enemy(enemyx[i], enemyy[i], i) # bullet movement if bullety <= 0: bullety = 480 bullet_state = "ready" if bullet_state == "fire": fire_bullet(bulletx, bullety) bullety -= bullety_change player(playerx, playery) show_score(textx,texty) pygame.display.update()
# -*- coding: utf-8 -*- """ Created on Mon Jun 1 00:15:25 2015 @author: hoseung """ from galaxymodule import galaxy def get_center(x, y, z, m, method='default'): """ Determines the center of mass of given particles. IDL version was to iteratively search for mass weighted mean position of particles within gradually decreasing search radius. Let's do the same thing here. """ import numpy as np r = 10. / 200 * 1000 # 10kpc/h # Stops if r < 10pc # or, if dx_3d < 5 pc msum = sum(m) xc_old = sum(x * m)/msum yc_old = sum(y * m)/msum zc_old = sum(z * m)/msum i = 0 while i < 10 and r > 1e-7 : msum = sum(m) xc = sum(x * m)/msum yc = sum(y * m)/msum zc = sum(z * m)/msum dx3 = np.sqrt((xc_old - xc)**2 + (yc_old - yc)**2 + (zc_old - zc)**2) if dx3 < 5e-8: break xc_old = xc yc_old = yc zc_old = zc # shrink the search radius by half. ind = np.where( (x-xc)**2 + (x-xc)**2 + (x-xc)**2 < r**2) if len(ind) < 100: break x = x[ind] y = y[ind] z = z[ind] r = 0.2 * max([x.ptp(), y.ptp(), z.ptp()]) i +=1 return xc, yc, zc # set region to encircle multiple halos. def set_region(xc, yc, zc, radius): import utils.sampling as smp import numpy as np if len(xc) > 1: ranges = set_region_multi(xc=xc, yc=yc, zc=zc, radius=radius) rr = max([np.ptp(ranges[0:2]), np.ptp(ranges[2:4]), np.ptp(ranges[4:6])]) * 0.5 region = smp.set_region(xc=0.5 * sum(ranges[0:2]), yc=0.5 * sum(ranges[2:4]), zc=0.5 * sum(ranges[4:6]), radius = rr) else: region = smp.set_region(xc=xc, yc=yc, zc=zc, radius = radius) return region def set_region_multi(xc=[], yc=[], zc=[], radius = []): xmi=[] xma=[] ymi=[] yma=[] zmi=[] zma=[] for i in range(len(xc)): xmi.append(xc[i] - radius[i]) xma.append(xc[i] + radius[i]) ymi.append(yc[i] - radius[i]) yma.append(yc[i] + radius[i]) zmi.append(zc[i] - radius[i]) zma.append(zc[i] + radius[i]) return (min(xmi), max(xma), min(ymi), max(yma), min(zmi), max(zma)) import draw import matplotlib.pyplot as plt def part_2_den(part, info, region=None, proj='z', npix=800, ptype=None): """ creates img object, calculate 2dprojection map and return the img object. given part, info, region, it passes x,y,z,m,npix,info arrays to pp.den2d. """ import numpy as np from draw import img_obj, pp if region is None: region={"ranges":[[0,1]]*3, "center":[0.5]*3, "radius":0.5, \ "xr":[0, 1], "yr":[0, 1], "zr":[0, 1]} ind_ok = np.where((part.x > region["xr"][0]) & (part.x < region["xr"][1]) & \ (part.y > region["yr"][0]) & (part.y < region["yr"][1]) & \ (part.z > region["zr"][0]) & (part.z < region["zr"][1])) if len(ind_ok[0]) > 0: img = img_obj.MapImg(info=info, proj='z', npix=npix, ptype=ptype) img.set_region(region) img.set_data(pp.den2d(part["x"][ind_ok], part["y"][ind_ok], part["z"][ind_ok], \ part["m"][ind_ok], npix, info, cic=True, norm_integer=True, region=region)) return img else: return False #%% import load import tree import numpy as np import utils.sampling as smp from utils import util nout=132 snout = str(nout) rscale = 0.8 npix=800 wdir = '/home/hoseung/Work/data/AGN2/' info = load.info.Info(nout=nout, base=wdir) frefine= 'refine_params.txt' fnml = 'cosmo_200.nml' ptypes=["star id pos mass vel"]#, "dm id pos mass vel"] # Load all halo hall = tree.halomodule.Halo(nout=nout, base=wdir, halofinder="RS", info=info) #hall = tree.halomodule.Halo(nout=nout, base=wdir, halofinder="HM", info=info) hall.load() # convert to code unit. - done by default #hall.normalize() # subset of halos ONLY inside zoom-in region i_center = np.where(hall.data['np'] == max(hall.data['np']))[0] h_ind = smp.extract_halos_within(hall, i_center, scale=1.0) #%% h = tree.halomodule.Halo() #h.derive_from(hall, h_ind[5:35]) h.derive_from(hall, h_ind)#, [4921, 5281, 5343, 5365, 5375, 5412, 5415], 5442, 5639, 5665, 6095]) region = set_region(h.data.x, yc=h.data.y, zc=h.data.z, radius = h.data.rvir * rscale) print(region) hind = np.where( (hall.data.x > region["xr"][0]) & (hall.data.x < region["xr"][1]) & (hall.data.y > region["yr"][0]) & (hall.data.y < region["yr"][1]) & (hall.data.z > region["zr"][0]) & (hall.data.z < region["zr"][1]) & (hall.data.mvir > 1e11))[0] h.derive_from(hall, hind) #%% s = load.sim.Sim(nout, wdir) s.set_ranges(region["ranges"]) s.show_cpus() s.add_part(ptypes) s.part.load() # convert to km/s s.part.star['vx'] *= s.info.kms s.part.star['vy'] *= s.info.kms s.part.star['vz'] *= s.info.kms s.part.star["m"] *= s.info.msun if 'dm' in s.part.pt: s.part.dm['vx'] *= s.info.kms s.part.dm['vy'] *= s.info.kms s.part.dm['vz'] *= s.info.kms s.part.dm["m"] *= s.info.msun #s.add_hydro() #s.hydro.amr2cell(lmax=19) #%% # set range directly from a halo instance #region = smp.set_region(xc=h.data.x, yc=h.data.y, zc=h.data.z, radius = h.data.rvir * rscale) #util.reimport(draw) #util.reimport(draw.pp) #img = part_2_den(s.part.dm, s.info, region=region, npix=npix) #fig = plt.figure() #ax1 = fig.add_subplot(111) #img.plot_2d_den(axes=ax1, show=False, vmax=1e10, dpi=400, cname='brg', zposition=False) #draw.pp.pp_halo(hall, npix, ind=hind, region=region, rscale=30, \ # axes=ax1, facecolor='none', edgecolor='b', name=True) #plt.savefig(wdir + snout + "dmmap_w_halo.png") #plt.close() #%% # Now, make galaxy data set import numpy as np dtype_catalog = [('id', int), ('mtot', '<f8'), ('mgas', '<f8'), ('mstar', '<f8'), ('mdm', '<f8'), ('mhal', '<f8'), ('nstar', int), ('ndm', int), ('nsink', int), ('pos', '<f8', 3), ('vel', '<f8', 3), ('lx', '<f8', 3), ('dcluster', '<f8'), ('b2t', float), ('mag', float, 5), ('sfr', '<f8'), ('lambdar', '<f8'), ('lambdar_arr', '<f8', 30), ("nfit",float), ("morph_vi",str), ("morph_b2t",str), ("add2",float), ("add3",float)] x_clu = hall.data['x'][i_center] y_clu = hall.data['y'][i_center] z_clu = hall.data['z'][i_center] #%% util.reimport(galaxy) util.reimport(draw) util.reimport(draw.pp) util.reimport(draw.img_obj) plt.ioff() nh = len(hind) import matplotlib.pyplot as plt #from draw import pp #fig, axs = plt.subplots(np.ceil(nh/5), 5) #ax = axs[0,0] # First halo is the cen lambdar_arr=[] catalog = np.zeros(nh, dtype=dtype_catalog) for icat, i in enumerate(range(1,nh)): gal = galaxy.Galaxy(h.data[i], radius_method='simple', info=s.info) print(gal.id) gal.mk_gal(part=s.part, cell=None, rscale = 0.4) if gal.star is False: print(" Not a good galaxy") continue # gal.get_radius("eff") print("R eff:", gal.reff * info.pboxsize) gal.cal_lambda_r(npix=20, method=1, rscale=1.5) # calculate within 1.0 * reff gal.plot_gal(base=wdir + 'galaxy_plot4/') isort = np.argsort(gal.dist1d) print(gal.lambda_r[1:-1:5]) print(" ") # gal.save_gal(base = wdir) lambdar_arr.append(gal.lambda_r) catalog[i]['mstar'] = gal.mstar catalog[i]['id'] = gal.id catalog[i]['pos'][0] = gal.xc catalog[i]['pos'][1] = gal.yc catalog[i]['pos'][2] = gal.zc catalog[i]['lambdar_arr'][0:len(gal.lambda_r)] = gal.lambda_r catalog[i]['lambdar'] = 0.5*(gal.lambda_r[0.5*len(gal.lambda_r) -1] + gal.lambda_r[len(gal.lambda_r) -1]) catalog[i]['dcluster'] = np.sqrt((gal.xc - x_clu)**2 + (gal.yc - y_clu)**2 + (gal.zc - z_clu)**2)/hall.data['rvir'][i_center] # field = pp.den2d(gal.star["x"], gal.star["y"], gal.star["z"], # gal.star["m"], 600, s.info, region=None, # ngp=False, cic=True, tsc=False) #%% import pickle with open("catalog.pickle", 'wb') as f: pickle.dump(catalog, f) #%% import pickle with open(wdir + 'catalog.pickle', 'rb') as f: catalog = pickle.load(f) with open(wdir + 'lambdar.pickle', 'rb') as f: lambdar_arr = pickle.load(f) #dir+'000014gal.hdf5', "r") #sx = infile['galaxy/star/x'] #infile.close() #util.reimport(utils) #%% import utils # only massive galaxies ll = np.asarray(lambdar_arr) i_cat = np.where(catalog['id'] != 0) catalog = catalog[i_cat] #%% i_truegal = catalog['mstar'] > 3e9 disk_lit=[] # Exclude seemingly interacting galaxies id_nogood = [ ]#, 6033, 6179] #id_interacting=[5886,8909,6158,6226,] #id_nogood += disk_list i_ng = utils.match.match_list_ind(catalog['id'], id_nogood) tflist=np.full(len(catalog), True, dtype=bool) tflist[i_ng] = False #i_voffset = np.wehre(lambdar_arr) # intersection of two criteria i_ok = np.logical_and(i_truegal, tflist) #%% f = plt.figure() ax = f.add_subplot(111) #for i, val in enumerate(lambdar_arr): cnt = 0 for i, ok in enumerate(i_ok): if ok: cnt += 1 if catalog[i]['id'] in disk_list : print("disk") ax.plot(lambdar_arr[i], 'r-', alpha=0.5) # up to 1Reff pass # ax.plot(val, 'r-') # up to 1Reff else: ax.plot(lambdar_arr[i], 'b-', alpha=0.3) # up to 1Reff print(cnt) #plt.xlabel() # in the unit of Reff ax.set_title(r"$\lambda _{R}$") ax.set_ylabel(r"$\lambda _{R}$") ax.set_xlabel("["+ r'$R/R_{eff}$'+"]") ax.set_xlim(right=9) ax.set_xticks([0, 4.5, 9]) ax.set_xticklabels(["0", "0.5", "1"]) plt.savefig(wdir + "lambdar_disk.png") plt.close() #%% ll = 0.5 * (catalog['lambdar_arr'][i_ok,4] + catalog['lambdar_arr'][i_ok,9]) lld = 0.5 * (catalog['lambdar_arr'][i_disk,4] + catalog['lambdar_arr'][i_disk,9]) f = plt.figure() ax = f.add_subplot(111) ax.scatter(catalog['dcluster'][i_ok],ll) ax.scatter(catalog['dcluster'][i_disk],lld, color='r') # catalog['lambdar_arr'][i_ok])# catalog['lambdar'][i_ok]) ax.set_xlim(0,1.1) ax.set_ylim(0,1) ax.set_xlabel("["+ r'$R/R_{eff}$'+"]") ax.set_ylabel(r"$\lambda_{R}$") plt.savefig(wdir + "hdclustervslambdar.png") plt.close() f = plt.figure() ax2 = f.add_subplot(111) ax2.scatter(np.log10(catalog['mstar'][i_ok]), ll) ax2.scatter(np.log10(catalog['mstar'][i_disk]),lld, color='r') # catalog['lambdar'][i_ok])#catalog['lambdar'][i_ok] ) ax2.set_xlim([9,11]) ax2.set_ylim(0,1) ax2.set_xlabel("Stellar mass " + r"$[10^{10} M_{\odot}]$") ax2.set_ylabel(r"$\lambda_{R}$") plt.savefig(wdir + "msvslambdar.png") plt.close() #%% import pyfits f = "/home/hoseung/Work/data/AGN2/catalog132.fits" hdu = pyfits.open(f) cat = hdu[1].data #%% for i, idgal in enumerate(catalog['id'][1:]): print(i,idgal) ind = np.where(cat['hnu'] == idgal) try: catalog["b2t"][i] = 1 - cat['d2t'][ind] except: print(idgal, "is missing") # morp.append()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('adm', '0157_auto_20171124_0921'), ] operations = [ migrations.AlterModelOptions( name='rut', options={'permissions': (('cancel_rut', 'Can cancel RUT'), ('finish_rut', 'Can finish RUT'), ('read_rut', 'Can read RUT'))}, ), migrations.AlterModelOptions( name='si', options={'permissions': (('cancel_si', 'Can cancel SOT'), ('finish_si', 'Can finish SOT'), ('read_si', 'Can read SI'))}, ), migrations.AlterModelOptions( name='sot', options={'permissions': (('cancel_sot', 'Can cancel SOT'), ('finish_sot', 'Can finish SOT'), ('read_sot', 'Can read SOT'))}, ), ]
import couchdb import schemas from enum import Enum class DB_Schema(Enum): corey = 1 fang = 2 class Importer: def __init__(self): self.db_schemas = { "stackoverflow_daily": DB_Schema.corey, "stackoverflow_monthly": DB_Schema.fang, "stackoverflow_monthly_2000": DB_Schema.fang } def getDataFromDB(self, dbName): server = couchdb.Server() if dbName not in self.db_schemas: return {} schema = self.db_schemas[dbName] db = server[dbName] if schema == DB_Schema.corey: return schemas.importerCoreySchema(db) elif schema == DB_Schema.fang: return schemas.importerFangSchema(db)
def validate_data(data, attrs=list()): if not bool(data): return False response = True for key, value in data.iteritems(): if key not in attrs: response = False break return response
""" 이 경우 local_num 함수는 지역 변수 num이 존재하고 global_num 함수는 지역 변수 num이존재하지 않습니다. 그러므로 내부에서 return 할 때 num을 호출하지만 결과는 다르게 됩니다. """ num = 10 def local_num(a): num = 100 # 지역변수 인식, 전역변수에는 영향 없음 return a + num def global_num(a): return a + num val1 = local_num(100) val2 = global_num(100) print(val1) # 200 print(val2) # 110
from django.db import models class RegresionLineal(models.Model): cantidad = models.IntegerField() valor = models.FloatField() x = models.FloatField() p = models.FloatField() def set_valor(self, valor): self.valor = valor def get_valor(self): return self.valor def set_p(self, p): self.p = p def get_p(self): return self.p def set_x(self, x): self.x = x def get_x(self): return self.x class RegresionNoLineal(models.Model): cantidad = models.IntegerField() valor = models.FloatField() x = models.FloatField() p = models.FloatField() def set_valor(self, valor): self.valor = valor def get_valor(self): return self.valor def set_p(self, p): self.p = p def get_p(self): return self.p def set_x(self, x): self.x = x def get_x(self): return self.x
# -*- coding: utf-8 -*- import scrapy from news_scrap.items import NewsScrapItem from scrapy.linkextractors import LinkExtractor import urlparse from scrapy.spiders import CrawlSpider, Rule from scrapy.http import Request class BkkbizSpider(scrapy.Spider): name = 'bkkbiz' allowed_domains = ['www.bangkokbiznews.com/'] start_urls = ['http://www.bangkokbiznews.com//'] def start_requests(self): for i in range(550000,760000): yield Request('http://www.bangkokbiznews.com/news/detail/%d' % i, callback=self.parse) def parse(self, response): item = NewsScrapItem() item[u'news_title'] = response.xpath(u'//head/meta[@property="og:title"]/@content').extract_first() item["news_link"] = response.url # no need article item["news_article"] = ''.join(response.xpath(u'//div[@class="text_post_block"]//p').extract()).strip() if item[u'news_title']: yield item
# coding=utf-8 from data_common.utils.file_util import FileUtil from data_common.extract_common.template.template_analysis import TemplateAnalysis from data_common.extract_common.sites.site_base import BaseSite class Douban(BaseSite): url_patterns = ['https://movie.douban.com'] def __init__(self): super(BaseSite, self).__init__() self.template_file = FileUtil.get_abs_path(__file__, 'patterns.json') self.methods_file = FileUtil.get_abs_path(__file__, 'methods.py') def process(self, url, html): params = TemplateAnalysis(self.template_file, self.methods_file).process(url, html) params = self.process_step(params) return params def process_step(self, params): return params
{ 'includes': [ '../gyp/common.gypi', ], 'targets': [ { 'target_name': 'symlink_TEST_DATA', 'type': 'none', 'hard_dependency': 1, 'actions': [ { 'action_name': 'Symlink Fixture Directory', 'inputs': ['<!@(pwd)/../test'], 'outputs': ['<(PRODUCT_DIR)/TEST_DATA'], # symlinks the test dir into TEST_DATA 'action': ['ln', '-s', '-f', '-n', '<@(_inputs)', '<@(_outputs)' ], } ], }, { 'target_name': 'test', 'type': 'executable', 'include_dirs': [ '../include', '../src', '../platform/default' ], 'dependencies': [ 'symlink_TEST_DATA', 'mbgl.gyp:core', 'mbgl.gyp:platform-<(platform_lib)', 'mbgl.gyp:http-<(http_lib)', 'mbgl.gyp:asset-<(asset_lib)', 'mbgl.gyp:headless-<(headless_lib)', ], 'sources': [ 'fixtures/main.cpp', 'fixtures/stub_file_source.cpp', 'fixtures/stub_file_source.hpp', 'fixtures/mock_view.hpp', 'fixtures/util.hpp', 'fixtures/util.cpp', 'fixtures/fixture_log_observer.hpp', 'fixtures/fixture_log_observer.cpp', 'util/assert.cpp', 'util/async_task.cpp', 'util/clip_ids.cpp', 'util/geo.cpp', 'util/image.cpp', 'util/mapbox.cpp', 'util/merge_lines.cpp', 'util/run_loop.cpp', 'util/text_conversions.cpp', 'util/thread.cpp', 'util/thread_local.cpp', 'util/tile_cover.cpp', 'util/timer.cpp', 'util/token.cpp', 'util/work_queue.cpp', 'api/annotations.cpp', 'api/api_misuse.cpp', 'api/repeated_render.cpp', 'api/render_missing.cpp', 'api/set_style.cpp', 'api/custom_layer.cpp', 'api/offline.cpp', 'geometry/binpack.cpp', 'map/map.cpp', 'map/map_context.cpp', 'map/tile.cpp', 'map/transform.cpp', 'storage/storage.hpp', 'storage/storage.cpp', 'storage/default_file_source.cpp', 'storage/offline.cpp', 'storage/offline_database.cpp', 'storage/offline_download.cpp', 'storage/asset_file_source.cpp', 'storage/headers.cpp', 'storage/http_cancel.cpp', 'storage/http_error.cpp', 'storage/http_expires.cpp', 'storage/http_header_parsing.cpp', 'storage/http_issue_1369.cpp', 'storage/http_load.cpp', 'storage/http_other_loop.cpp', 'storage/http_retry_network_status.cpp', 'storage/http_reading.cpp', 'storage/http_timeout.cpp', 'storage/resource.cpp', 'style/glyph_store.cpp', 'style/source.cpp', 'style/style.cpp', 'style/style_layer.cpp', 'style/comparisons.cpp', 'style/functions.cpp', 'style/style_parser.cpp', 'style/variant.cpp', 'sprite/sprite_atlas.cpp', 'sprite/sprite_image.cpp', 'sprite/sprite_parser.cpp', 'sprite/sprite_store.cpp', ], 'variables': { 'cflags_cc': [ '<@(gtest_cflags)', '<@(opengl_cflags)', '<@(boost_cflags)', '<@(sqlite_cflags)', '<@(geojsonvt_cflags)', '<@(rapidjson_cflags)', '<@(pixelmatch_cflags)', '<@(variant_cflags)', ], 'ldflags': [ '<@(gtest_ldflags)', '<@(sqlite_ldflags)', ], 'libraries': [ '<@(gtest_static_libs)', '<@(sqlite_static_libs)', '<@(geojsonvt_static_libs)', ], }, 'conditions': [ ['OS == "mac"', { 'xcode_settings': { 'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ], }, }, { 'cflags_cc': [ '<@(cflags_cc)' ], }], ], 'link_settings': { 'conditions': [ ['OS == "mac"', { 'libraries': [ '<@(libraries)' ], 'xcode_settings': { 'OTHER_LDFLAGS': [ '<@(ldflags)' ] } }, { 'libraries': [ '<@(libraries)', '<@(ldflags)' ], }] ], }, }, ] }
from bs4 import BeautifulSoup import wikipedia as wiki from pathlib import Path import re def get_page(query): """ Returns a Wikipedia Page Object from a search term. Assumes the page esists and the query is mostly spelled right Args: query: (Str) The title of wiki page to search for Returns Wikipedia Page Object """ # Get a list of article titles based on the search query search = wiki.search(query) link_num = 0 # Check if search is empty and return none with an error message if search == []: print(f"*Error getting page: {query}*") print("Check your spelling, and if the page exists.") return None # if the page is a disambiguation page return the first valid link while is_disamb(search[link_num]) and link_num < len(search): link_num += 1 # otherwise return a vailid Wikipedia Page or None try: page = wiki.WikipediaPage(search[link_num]) except wiki.exceptions.DisambiguationError: return None except wiki.exceptions.PageError: return None return page def get_links(page_name): """ Returns all the links in a wikipedia article. Args: page_name: (Str) The title of the current wiki page Returns a list of all the links in the wiki article """ # Check if the articles' links are save in a file and return those links if is_stored(page_name): return read_links(page_name) # Parse the HTML for links, save them to a file, and return links else: try: page = wiki.WikipediaPage(page_name) # Get the wikipedia page links = parse_links(page) if len(links) > 0: print("Page stored to a file:") save_links(page_name, links) return links # If the page is a disambiguation return the links within it except wiki.exceptions.DisambiguationError as de: return de.options except wiki.exceptions.PageError: return [] pass def read_links(title): """ Reads the links from a file in directory link_data. Assumes the file exists, as well as the directory link_data Args: title: (Str) The title of the current wiki file to read Returns a list of all the links in the wiki article with the name title """ with open(f"link_data/{title}", "r") as f: read_data = f.read() return read_data.split("\n")[:-1] def save_links(title, links): """ Saves the links to a file for easy access. Assumes the directory link_data Args: title: (Str) The title of the current wiki article to save as a file links: (List) List of all the links in the wikipedia article Returns true is the the file is created, false if is not created """ # If the article title has a "/" in it, do not save it as a file # Otherwise the program throws an error if title.find("/") != -1: return False # Open a file in the directory linkdata with the file name "title" # and save all the links in the file with open(f"link_data/{title}", "w") as f: for link in links: f.write(link + "\n") return True def is_stored(title): """ Checks if the file for the page exists, returning a Boolean Args: title: (Str) The title of the current file to check Returns true is the file exists, false if it does not """ return Path(f"link_data/{title}").is_file() def is_disamb(page_name): """ Checks if the page is a disambiguation page, returning a Boolean Args: page_name: (Str) The title of the current page to check Returns true is the page is a disambiguation, false if it does not """ try: wiki.WikipediaPage(page_name) except wiki.exceptions.DisambiguationError: return True except wiki.exceptions.PageError: return False return False def is_page(page_name): """ Checks if the page exists, returning a Boolean Args: page_title: (Str) The title of the current page to check Returns true is the page exists, false if it does not """ try: wiki.WikipediaPage(page_name) except wiki.exceptions.PageError: return False except wiki.exceptions.DisambiguationError: return True return True def has_end(page_title, end_page): """ Searches the links in a page for the end page. Args: page_title: (Str) The title of the current page to search end_page: (Wikipedia Page) The last page we are searching for. Returns a true if the current page has the end page in its links otherwise returns false """ return end_page.title in get_links(page_title) def parse_links(page): """ Takes a Wikipedia Page and returns a list of the links inside of it. Expects a valid Wikipedia Object, if the page is a stub or improperly formated will default to the .links funtion in Wikipedia library Uses Beautiful soup to scrap wikipedia HTML and then uses get_titles to only grab relevant titles Args: Page: (Wikipedia Page) A Wikipedia Page Object to find all the links in Returns a list of links without any "Meta" wiki links """ # Get the pages' HTML and parse it with Beautiful Soup main_html = BeautifulSoup(page.html(), "html.parser") # A list of all the refference section labels # Only one of these will be used, but a list is needed # as wikipedia pages are configured in many ways args = [ ["div", {"class": "mw-references-wrap"}], ["span", {"id": "References"}], ["span", {"id": "Sources"}], ["span", {"id": "External_links"}], ["div", {"class": "navbox"}], ["table", {"id": "disambigbox"}], ["table", {"id": "setindexbox"}], ["div", {"class": "reflist"}]] args_opt = 0 # try to get the reference section using the first argument in the list ref_html = main_html.find_all( name=args[args_opt][0], attrs=args[args_opt][1]) # if that returns empty try each argument till one returns not empty while ref_html == [] and args_opt < len(args) - 1: args_opt += 1 ref_html = main_html.find_all( name=args[args_opt][0], attrs=args[args_opt][1]) # Check if it still could not find a section # if so use the Wikipedia API method and print this information to the user if ref_html == []: if main_html.find_all(["div", {"id": "copyvio"}]) != []: print("*This page contains a Copyright issue*") return [] print(f"*Wiki format error or page stub* {page.title}") return page.links else: # get the first and only item in the list ref_html = ref_html[0] # remove everything in and below the references section main_str = str(main_html) references_str = str(ref_html) references_idex = main_str.find(references_str) page_content = main_str[:references_idex] # parse the new shortened HTML and get all links with a tile content_soup = BeautifulSoup(page_content, "html.parser") all_links = content_soup.find_all( name="a", attrs={"class": None, "title": re.compile(".")}) all_links += content_soup.find_all( name="a", attrs={"class": "mw-disambig", "title": re.compile(".")}) # Call get_titles to return only non-"Meta" Links return get_titles(all_links) def get_titles(all_links): """ Takes a BeutifulSoup ResultsSet of all links and returns only wanted links Args: all_links: (ResultsSet) A set of alll the links in the wikipedia article Returns a list of links without any "Meta" wiki links """ links = set() meta_links = set() # for each link, Check if its a Meta page add it to a meta_links to remove for link in all_links: if re.search("^Edit section:", link["title"]): # This step is unnecessary but adds protection against errors meta_links.add(link["title"]) elif re.search("^Wikipedia:", link["title"]): meta_links.add(link["title"]) elif re.search("^Help:", link["title"]): meta_links.add(link["title"]) elif re.search("^Talk:", link["title"]): meta_links.add(link["title"]) elif re.search("^Template:", link["title"]): meta_links.add(link["title"]) elif re.search("^File:", link["title"]): meta_links.add(link["title"]) elif re.search("^Template talk:", link["title"]): meta_links.add(link["title"]) elif re.search("^Special:", link["title"]): meta_links.add(link["title"]) elif re.search("^Category:", link["title"]): meta_links.add(link["title"]) elif re.search("^MediaWiki:", link["title"]): meta_links.add(link["title"]) elif re.search("^About this Sound", link["title"]): meta_links.add(link["title"]) elif re.search("^#", link["title"]): meta_links.add(link["title"]) elif re.search("^Portal:", link["title"]): meta_links.add(link["title"]) elif re.search("^commons:", link["title"]): meta_links.add(link["title"]) elif re.search("^Commons:", link["title"]): meta_links.add(link["title"]) elif re.search("^ru:", link["title"]): meta_links.add(link["title"]) # if the page is not a meta page add it to the set "links" else: links.add(link["title"]) # Return the links that are not "Meta" pages return list(links - meta_links) def get_min_path(paths): """ Takes a list of paths and returns the shortest one. If there are more than one of the same length, returns the first one Args: Paths: (List) A set of all the paths between the starting page and the end page Returns a list of article titles in the shortest path """ min_path = None min_len = 25 # For each path check if it is shorter than the current min length # If so update the minimum length and path for path in paths: if len(path) < min_len: min_len = len(path) min_path = path return min_path def plot_path(path): """ Takes a found path and prints a formated version of the path Args: Path: (List) A set of all the links in the wikipedia article Returns a string verion of the path """ if path == []: print("No path found, try more steps between pages!") return None path_str = "| " for page in path: path_str += page path_str += " ---> " path_str = path_str[:-5] + "|" # print(path_str) return path_str def plot_all_paths(paths): """ Takes a list of found paths and prints a formated version of the paths Args: Paths: (List) A set of all the paths between the starting page and the end page Returns a string verion of all the paths """ formated = "" print(f"We found {len(paths)} links!") print(f"The shortest path(s) are {len(get_min_path(paths))} links long.") print(f"The first short path is: {plot_path(get_min_path(paths))}") print("\n-------------------------------\n") # If the list of pthats is empty, print out that result if paths == []: print("No paths found, try more steps between pages!") # Format each path and add it to a string to return # with newlines between paths for path in paths: formated += plot_path(path) + "\n" print(plot_path(path)) # Return a string containing all the paths return formated def save_paths(paths, start, end, steps): """ Takes a list of found paths and prints a formated version of the paths Saves the file with a title showing the start page, end page, and number of steps Args: Paths: (List) A set of all the paths between the starting page and the end page Start: (Str) The name of the page each path starts at End: (Str) The name of the page each path ends at Steps: (Int) The number of maximum steps between the start page and the end page Returns a string verion of all the paths """ with open(f"paths/{start},_{end},_{steps}", "w") as f: print(f"We found {len(paths)} paths from {start} to {end}!", file=f) print( f"The shortest path(s) are {len(get_min_path(paths))} links long.", file=f) print( f"The first short path is: {plot_path(get_min_path(paths))}", file=f) print("\n-------------------------------\n", file=f) print("\n-------------------------------\n") print(plot_all_paths(paths), file=f)
""" data set will look like this [[23], [56] ... ] <--- size going to be length of data set when we first calculate the centroids [[23], [56]...] <--- size is going to be k clusters will look like each sub list is a cluster each element in cluster... is the original index of the actual data point [[1, 2, 8], [9, 10, 3] ...] <--- size is going to be k 1. choose k centroids/clusters <-- (this is pretty significant to outcome of algo) 2. pick k random points from our data set (k random points are our initial set of centroids) 3. go through all points in data set.... 4. drop them in the closest centroid (which forms a cluster) 5. calculate a new centroid.... by taking the average of all of the features in that cluster 6. go back to number 3! """ import random import math test_scores = [23, 56, 12, 44, 87, 45, 76, 98, 25, 34, 76, 12, 78, 98, 78, 90, 89, 45, 77, 22, 11] d = [[score] for score in test_scores] def generate_initial_centroids(k, data): """ we're going to choose k data points from data no duplicate centroids """ centroids = [] used_indexes = [] while len(centroids) < k: random_index = random.randint(0, len(data) - 1) if random_index not in used_indexes: centroids.append(data[random_index]) used_indexes.append(random_index) return centroids print(generate_initial_centroids(5, d)) def generate_initial_centroids(k, data): return random.sample(data, k) print(generate_initial_centroids(5, d)) def distance(p1, p2): """returns euclidean distance p1 is a list of features p2 is alsoa a list of features p1 and p2 should be the same size distance is the squareroot of sum of all squares of differences for each feature """ """ (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + """ sum_all = 0 for i, v in enumerate(p1): diff_squared = (v - p2[i]) ** 2 sum_all += diff_squared return(math.sqrt(sum_all)) print(distance((5, 0), (2, 12))) def distance(p1, p2): sum_all = 0 for v1, v2 in zip(p1, p2): diff_squared = (v1 - v2) ** 2 sum_all += diff_squared return(math.sqrt(sum_all)) print(distance((5, 0), (2, 12))) def distance(p1, p2): return math.sqrt(sum([(v1 - v2) ** 2 for v1, v2 in zip(p1, p2)])) print(distance((5, 0), (2, 12))) """ we can generate centroids we also have eulidean distance generate clusters get the distances of ever data point compared to every centroid """ def calculate_distances(data_point, centroids): """ what are all of the distances between this data point and the centroids (eventually... we'll find the min distance, which will identity nearest centroid) """ distances = [] for centroid_index, centroid_value in enumerate(centroids): distances.append(distance(data_point, centroid_value)) return distances print(calculate_distances([12], [[5],[10],[15]])) def calculate_distances(data_point, centroids): return list(map(lambda centroid_value: distance(data_point, centroid_value), centroids)) print(calculate_distances([12], [[5],[10],[15]])) """ actual feature values \/ centroids = [[16], [12]] <--- size is k list of indexes in the original incoming data \/ cluster = [[1, 6, 3]... ] <--- size is als k """ def generate_clusters(k, centroids, data): # where to store clusters? # initialize clusters to list of empty lists clusters = [[] for i in range(k)] # go through every data point for data_index, data_point in enumerate(data): # get all of the distances for that data point """what is the size of distances going to be?""" distances = calculate_distances(data_point, centroids) min_distance = min(distances) min_index = distances.index(min_distance) clusters[min_index].append(data_index) """ centroids [[] ... k] 0 distances [[] ... k] 0 clusters [[3, 1 ,4] ... k] """ return clusters print(generate_clusters(5, [[90], [34], [76], [87], [78]], d)) """ x created inital centroids x we've clusters x generate new centroids generate_new_centroids for cluster in clusters for data_point in cluster for feature in data point add feature values together go through all sums of features divide by number of data points in cluster """ def generate_new_centroids(clusters, data): for cluster_index, cluster in enumerate(clusters): # initialize a bunch of 0's # based on how many features we have per data point sum_features = [0] * len(data[0]) for data_point_i, data_index in enumerate(cluster): data_point = data[data_index]
#!/usr/bin/python import math def prime(n): if n < 4: return True max = int(math.floor(math.sqrt(float(n)))) for i in xrange(max+1): if i < 2: continue if (n % i == 0): return False return True x = 600851475143 out = -1 max = int(math.floor(math.sqrt(x))) best = -1 for i in xrange(1,max+1): if (x % i == 0): other = x / i if (prime(other)): out = other break if (prime(i)): best = i if out == -1: print best else: print out
from traits.api import Str, Int, Float, Bool, Enum import enaml from enaml.stdlib.sessions import show_simple_view from Instrument import Instrument class MicrowaveSource(Instrument): address = Str('', desc='Address of unit as GPIB or I.P.') power = Float(0.0, desc='Output power in dBm') frequency = Float(5.0, desc='Frequency in GHz') output = Bool(False, desc='Whether the output is on.') mod = Bool(False, desc='Whether output is modulated') alc = Bool(False, desc='Whether automatic level control is on') pulse = Bool(False, desc='Whether pulse modulation is on') pulseSource = Enum('Internal', 'External', desc='Source of pulse modulation') #For blanking the source we need to know the maximum rate and the delay gateBuffer = Float(0.0) gateMinWidth = Float(0.0) gateDelay = Float(0.0) class AgilentN5183A(MicrowaveSource): gateBuffer = Float(20e-9) gateMinWidth = Float(100e-9) gateDelay = Float(-60e-9) class HolzworthHS9000(MicrowaveSource): gateBuffer = Float(20e-9) gateMinWidth = Float(100e-9) gateDelay = Float(-60e-9) class Labbrick(MicrowaveSource): refSource = Enum('Internal' , 'External', desc='Source of 10MHz ref.') gateBuffer = Float(20e-9) gateMinWidth = Float(100e-9) gateDelay = Float(-60e-9) class Labbrick64(MicrowaveSource): gateBuffer = Float(20e-9) gateMinWidth = Float(100e-9) gateDelay = Float(-60e-9) class HP8673B(MicrowaveSource): pass class HP8340B(MicrowaveSource): pass #List of possible sources for other views MicrowaveSourceList = [AgilentN5183A, HolzworthHS9000, Labbrick, Labbrick64, HP8673B, HP8340B] if __name__ == "__main__": from MicrowaveSources import AgilentN5183A uwSource = AgilentN5183A(name='Agilent1') with enaml.imports(): from MicrowaveSourcesView import MicrowaveSourceView session = show_simple_view(MicrowaveSourceView(uwSource=uwSource))
wow = str(raw_input('enter a word to do it twice: ')) def do_twice(f): f() f() def print_wow(): print'wow' def do_four(do_twice): do_twice(print_wow) do_twice(print_wow) do_four(do_twice)
from django.shortcuts import render def index(request): return render(request, 'mainApp/index.html') def contacts(request): return render(request, 'mainApp/contacts.html') def about(request): return render(request, 'mainApp/about.html') def wrong(request): return render(request, 'feedback/wrong.html') def thanks(request): return render(request, 'feedback/thanks.html')
# Generated by Django 3.0.2 on 2020-01-26 07:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('subject', '0003_remove_subject_teacher'), ] operations = [ migrations.AddField( model_name='subject', name='name', field=models.CharField(default=None, max_length=50), preserve_default=False, ), ]
# In this assignment you must do a Twitter search on any term # of your choice. # Deliverables: # 1) Print each tweet # 2) Print the average subjectivity of the results # 3) Print the average polarity of the results # Be prepared to change the search term during demo. import tweepy from textblob import TextBlob import sys # Boilerplate code here auth = tweepy.OAuthHandler(consumer_key,consumer_secret) auth.set_access_token(access_token,access_token_secret) # Sets a variable with tweepy API. api = tweepy.API(auth) # Receives an input from the user public_tweets = api.search(input("Please give a Twitter search: ")) count = 0 #Count for getting the average polarcount = 0 #Counts every polar (adds the polarity) subjectcount = 0 #Counts every subject (adds the subjectivity) # Code that was provided by GSI to allow tweets to be printed def uprint(*objects, sep='', end='\n', file=sys.stdout): enc = file.encoding if enc == 'UTF-8': print(*objects, sep=sep, end=end, file=file) else: f = lambda obj: str(obj).encode(enc, errors='backslashreplace') print(*map(f, objects), sep=sep, end=end, file=file) for tweet in public_tweets: uprint(tweet.text) analysis = TextBlob(tweet.text) #Receives the polarity counts polarcount += analysis.sentiment.polarity #Receives the subjectivity counts subjectcount += analysis.sentiment.subjectivity count += 1 #Finding the average for both polarity and subjectivity polaravg = polarcount / count subjectavg = subjectcount / count #You can use sentiment.polarity or sentiment.subjectivity #polarity -- measures how positive or negative #subjectivity -- measures how factual. # tweetz = input("Please do a Twitter search: ") print("Average subjectivity is ", subjectavg) print("Average polarity is ", polaravg)
def test(a, b): x = a // b y = a % b # 一般情况下,一个函数最多只会执行一个return语句 # 特殊情况(finally语句)下,一个函数可能会执行多个return语句,但是会存在覆盖的情况 # return x #return语句表示一个函数的结束 # return {'x':x,'y':y} # return [x,y] # return (x,y) #推荐使用 return x,y #返回的本质是一个元组 result = test(13, 5) print("商是{},余数是{}".format(result[0], result[1])) shang, yushu = test(16, 3) print("商是{},余数是{}".format(shang, yushu)) # print("商是{},余数是{}".format(result['x'], result['y']))
import pytest import simplejson from django.core.urlresolvers import reverse from adserving.types import Decimal @pytest.mark.parametrize('user_data, results', [ (('user_1', '123'), ('$30.00', '$30.00', 2)), (('user_2', '123'), ('$0.00', None, 0)), ]) def test_billing_info_auth(client, billing_app, user_data, results): ''' Checks if user has access to proper data of billing and checks if proper values are returned ''' username, password = user_data client.login(username=username, password=password) request = client.get(reverse('billing_info')) content = simplejson.loads(request.content) assert content['account_balance'] == results[0] assert content['last_payment'] == results[1] assert len(content['transactions']) == results[2] @pytest.mark.parametrize('budget_spent, balance', [ (Decimal('30'), '$0.00'), (Decimal('40.25'), '-$10.25'), (Decimal('20.75'), '$9.25') ]) def test_account_balance(client, billing_app, budget_spent, balance): ''' Checks if account balance is properly counted for positive, zero and negative values. ''' # Save money spent in campaign campaign = billing_app.setup.models['campaign']['campaign_1'] campaign.budget_spent = budget_spent campaign.save() # Get billing info data client.login(username='user_1', password='123') request = client.get(reverse('billing_info')) content = simplejson.loads(request.content) # Check if account has a proper value returned assert content['account_balance'] == balance
import sqlite3 Conexion = sqlite3.connect("Jugador") Puntero = Conexion.cursor() Jugadores = [ ("Manu", "soymanu44", 15), ("Silvio", "manuputo", 15) ] Puntero.executemany("INSERT INTO Jugadores VALUES(NULL, ?, ?, ?)", Jugadores) Conexion.commit() Conexion.close()
import pygame from pygame.sprite import Group import config from .game_state import GameState from states.ready import Ready from .high_score import HighScore from animation import StaticAnimation from starfield import Starfield import sounds class Menu(GameState): TitleSize = 64 MenuItemSize = 32 MenuItemSpacing = 16 def __init__(self, input_state, starfield=None): super().__init__(input_state) self.font = pygame.font.SysFont(None, Menu.TitleSize) self.starfield = starfield or Starfield() self.title = Group() # create "Space Invaders" logo # green "SPACE" space_title = StaticAnimation(self.font.render("SPACE", True, config.green_color)) space_title.rect.centerx = config.screen_rect.centerx space_title.rect.centery = config.screen_height // 8 # white "INVADERS" self.font = pygame.font.SysFont(None, Menu.TitleSize // 2) invaders_title = StaticAnimation(self.font.render("INVADERS", True, pygame.Color('white'))) invaders_title.rect.left = space_title.rect.left + space_title.rect.width // 8 invaders_title.rect.top = space_title.rect.bottom + 10 self.title.add(space_title, invaders_title) last_y = config.screen_height - config.screen_height // 3 self.options = Group() self.font = pygame.font.SysFont(None, Menu.MenuItemSize) # create options for option in [("Play Space Invaders", self._play_game), ("High Scores", self._view_high_scores), ("Quit", self._quit)]: option_sprite = StaticAnimation(self.font.render(option[0], True, config.text_color)) option_sprite.callback = option[1] option_sprite.rect.centerx = config.screen_width // 2 option_sprite.rect.top = last_y last_y = option_sprite.rect.bottom + Menu.MenuItemSpacing self.options.add(option_sprite) # create a small sprite to use as menu item selector left_selector = config.atlas.load_static("selector") # need to flip the arrow... right_selector = StaticAnimation(pygame.transform.flip(left_selector.image, True, False)) right_selector.rect.left = config.screen_width self.selectors = Group(left_selector, right_selector) # point values for aliens self.aliens = Group() y_pos = invaders_title.rect.bottom + 50 for alien_stats in config.alien_stats: alien = config.atlas.load_animation(alien_stats.sprite_name).frames[0] spr = self._create_point_sprite(alien, alien_stats.points, y_pos) self.aliens.add(spr) y_pos = spr.rect.bottom + 10 ufo = config.atlas.load_animation("ufo").frames[0] spr = self._create_point_sprite(ufo, "???", y_pos) self.aliens.add(spr) # finish creating state values self.next_state = None self._set_selected(0) pygame.mouse.set_visible(True) sounds.play_music(sounds.menu_music_name) def update(self, elapsed): self.starfield.update(elapsed) self.options.update(elapsed) self.selectors.update(elapsed) self.aliens.update(elapsed) # handle selected item if not self._handle_mouse_clicks(): self._handle_arrow_keys() def draw(self, screen): screen.fill(config.bg_color) self.starfield.draw(screen) self.title.draw(screen) self.aliens.draw(screen) self.options.draw(screen) self.selectors.draw(screen) @property def finished(self): return self.next_state is not None def get_next(self): return self.next_state def _play_game(self): self.next_state = Ready(self.input_state) def _view_high_scores(self): self.next_state = HighScore(self.input_state, self.starfield) def _quit(self): self.input_state.quit = True def _handle_arrow_keys(self): for key_code in self.input_state.key_codes: if key_code == pygame.K_RETURN or key_code == pygame.K_KP_ENTER: self.options.sprites()[self.selected_index].callback() if self.input_state.up and self.input_state.down: return # both up and down at once, just do nothing if self.input_state.up: self._set_selected(self.selected_index - 1) self.input_state.up = False # don't allow repeating elif self.input_state.down: self._set_selected(self.selected_index + 1) self.input_state.down = False def _handle_mouse_clicks(self): idx = 0 for option in self.options.sprites(): if option.rect.collidepoint(self.input_state.mouse_pos): # highlight this option self._set_selected(idx) if self.input_state.left_down: option.callback() self.input_state.left_down = False return True idx += 1 def _set_selected(self, idx): while idx < 0: idx += len(self.options.sprites()) idx = idx % len(self.options.sprites()) if hasattr(self, "selected_index") and idx != self.selected_index: sounds.play("select") self.selected_index = idx # align selectors to current option for selector in self.selectors.sprites(): option_rect = self.options.sprites()[idx].rect selector.rect.centery = option_rect.centery if selector.rect.x < config.screen_width // 2: # must be left selector selector.rect.right = option_rect.left - 6 else: # right selector selector.rect.left = option_rect.right + 6 def _create_point_sprite(self, alien_surf, point_value, top_coord): point_value = self.font.render("{} Points".format(point_value), True, config.text_color) alien_rect = alien_surf.get_rect() surf = pygame.Surface((alien_rect.width + point_value.get_width() + 20, max(alien_rect.height, point_value.get_height()))) surf = surf.convert_alpha(pygame.display.get_surface()) # want 32 bit surface for per-pixel alpha surf.fill((0, 0, 0, 0)) # fill with transparent, note no color key # center alien rect vertically alien_rect.centery = surf.get_height() // 2 surf.blit(alien_surf, alien_rect) r = point_value.get_rect() r.left = alien_rect.width + 20 r.centery = alien_rect.centery surf.blit(point_value, r) sprite = StaticAnimation(surf) sprite.rect.top = top_coord sprite.rect.centerx = config.screen_rect.centerx return sprite
import sqlalchemy class Database: def __init__(self, username="root", password="", host="localhost", port=3306, database=None): if database is None: raise ValueError("Key database is required") if type(database) is not str: raise TypeError("The key database must be a string") if type(username) is not str: raise TypeError("The key username must be a string") if type(password) is not str: raise TypeError("The key password must be a string") if type(host) is not str: raise TypeError("The key host must be a string") if type(port) is not int: raise TypeError("The key port must be an integer") self._username = username self._password = password self._host = host self._port = port self._database = database def initialize(self): return sqlalchemy.create_engine( "mysql+pymysql://{username}:{password}@{host}:{port}/{database}" .format(username=self._username, password=self._password, host=self._host, port=self._port, database=self._database) )
class TreeNode(object): def __init__(self, init_data=None): self.data = init_data self.left = None self.right = None def __str__(self): return str(self.data) def traverse(root): if not root: return traverse(root.left) print(root, end=' ') traverse(root.right)
import numpy as np import math class metronomo: def __init__(self, nota, tempo, metrica): self.nota = nota self.tempo = tempo self.metrica = metrica self.tiempo = float(60/float(tempo)) def metrono(self): array = [] note=0 if self.nota == 'c': note=261.63 if self.nota == 'c#': note=277.18 if self.nota == 'd': note=293.66 if self.nota == 'd#': note=211.13 if self.nota == 'e': note=329.63 if self.nota == 'f': note=349.23 if self.nota == 'f#': note=369.99 if self.nota == 'g': note=392 if self.nota == 'g#': note=415.3 if self.nota == 'a': note=440 if self.nota == 'a#': note=466.16 if self.nota == 'b': note=493.88 if self.metrica == '24.wav': for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '34.wav': for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '44.wav': for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '54.wav': for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*self.tiempo)): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '28.wav': for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '68.wav': for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '78.wav': for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val if self.metrica == '98.wav': for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) for i in range(0, int(44100*0.001)): valores = math.sin((2*math.pi*0*i)/44100.0) array.append(valores) for i in range(0, int(44100*(self.tiempo/2.0))): valores = math.sin((2*math.pi*note*i)/44100.0) array.append(valores) val= np.asanyarray(array) return val def niveldeaudio(self, nivel, info): VaP=max(abs(info)) valornivel=(10**(nivel/20.0))*((2**16)/2) valorajustado=valornivel/float(VaP) infoajustada=info*valorajustado return infoajustada