def run(): # Make sure necessary directories exist if not os.path.exists('tracks'): os.makedirs('tracks') if not os.path.exists('figures'): os.makedirs('figures') overallstartdate = datetime(2004, 1, 1, 0, 1) overallstopdate = datetime(2004, 1, 2, 0, 1) # overallstopdate = datetime(2014, 7, 1, 4, 1) date = overallstartdate # Start from the beginning and add days on for loop # keep running until we hit the next month while date < overallstopdate: name = date.isoformat()[0:13] # If the particle trajectories have not been run, run them if not os.path.exists('tracks/' + name + '.nc') and \ not os.path.exists('tracks/' + name + 'gc.nc'): # Read in simulation initialization tp, lon0, lat0 = init(name) # Run tracpy # Save directly to grid coordinates lonp, latp, zp, t, T0, U, V = tracpy.run.run(tp, date, lon0, lat0) # Increment by 24 hours for next loop, to move through more quickly date = date + timedelta(hours=24)
def run(): # Make sure necessary directories exist if not os.path.exists('tracks'): os.makedirs('tracks') if not os.path.exists('tracks/driftcards'): os.makedirs('tracks/driftcards') if not os.path.exists('figures'): os.makedirs('figures') if not os.path.exists('figures/driftcards'): os.makedirs('figures/driftcards') grid = tracpy.inout.readgrid(loc) ndriftmodel = 1000 # do 1000 drifters for each set of driftcards # Read in deployment info and eliminate outside domain ndrift = 3490 # number of driftcards deployed # These are drift cards that start in numerical domain startdate, startlon, startlat, idnum = readThenReduce(grid, ndrift) # Find unique start dates and indices for start dates dates, idates = np.unique(startdate, return_index=True) # Loop through deployments for i, date in enumerate(dates): idate = idates[i] # Index in arrays lon0 = np.ones(ndriftmodel)*startlon[idate] lat0 = np.ones(ndriftmodel)*startlat[idate] # pdb.set_trace() # Initialize parameters nsteps, N, ndays, ff, tseas, ah, av, z0, zpar, \ do3d, doturb, dostream, T0, U, V = init(grid, date, lon0, lat0) # pdb.set_trace() date = netCDF.num2date(date, units) # # start drifters in chunks of exact same date/time # # idrift = 0 # # tdrift = startdate[idrift] #drifter time # idrifts = find(startdate==startdate[find(~np.isnan(startdate))[0]]) # all drifters with same start date/time # lon0 = startlon[idrifts] # lat0 = startlat[idrifts] # date = netCDF.num2date(startdate[idrifts][0], units) # pdb.set_trace() name = 'driftcards/' + date.isoformat() # Run tracpy lonp, latp, zp, t, grid, T0, U, V \ = tracpy.run.run(loc, nsteps, ndays, ff, date, tseas, ah, av, \ lon0, lat0, z0, zpar, do3d, doturb, name, N=N, \ grid=grid, dostream=dostream, T0=T0, U=U, V=V)
def run(rootdir, ndrifters): # Start date in date time formatting date = datetime(2013, 12, 19, 0) # Simulation initialization itime = time.time() tp, x0, y0 = init(rootdir, ndrifters) print '\nAdditional time for initialization:%4.4f\n' % (time.time() - itime) xp, yp, zp, t, T0, U, V = tracpy.run.run(tp, date, x0, y0)
def main(): black = (0, 0, 0) size = width, height = 800, 600 print 'Initializing pygame...' screen = init(size) settings = Settings() player = Player(None) window = MainMenu(player) if PROFILE: pr = cProfile.Profile() pr.enable() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: window.key_pressed(event.key) elif event.type == pygame.KEYUP: window.key_released(event.key) window.update() screen.fill(black) window.display(screen) pygame.display.flip() if window.child is not None: window = window.child if window.done: window = window.parent if window is None: running = False if PROFILE: pr.disable() sort_by = 'cumulative' ps = pstats.Stats(pr).strip_dirs().sort_stats(sort_by) ps.print_stats() ps.print_callers() pygame.quit()
def main(): global font black = (0, 0, 0) red = (255, 0, 0) blue = (0, 0, 255) white = (255, 255, 255) size = width, height = 800, 600 screen = init(size) settings = Settings() global_font = pygame.font.Font(pygame.font.get_default_font(), FONT_SIZE) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False screen.fill(black) pygame.draw.line(screen, blue, (0, 0), (width, height)) pygame.draw.line(screen, blue, (0, height), (width, 0)) pos = pygame.mouse.get_pos() vec = vector(pos) - vector(size) / 2 dir = get_dir(size, vec) intersection = get_intersection(size, vec) dims = vector(10, 10) rect = intersection - dims / 2 rect = rect.list() + dims.list() center = (width / 2, height / 2) pygame.draw.rect(screen, red, rect, 1) pygame.draw.line(screen, red, center, intersection.list()) draw_string(screen, dir, (10, 10), white) pygame.display.flip() pygame.quit()
def run(): # Make sure necessary directories exist if not os.path.exists('tracks'): os.makedirs('tracks') if not os.path.exists('tracks/gyre'): os.makedirs('tracks/gyre') if not os.path.exists('figures'): os.makedirs('figures') if not os.path.exists('figures/gyre'): os.makedirs('figures/gyre') # Location of TXLA model output loc = 'projects/gyre/'# 'http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc' # Read in grid grid = tracpy.inout.readgrid(loc) # Read in simulation initialization nsteps, ndays, ff, tseas, ah, av, lon0, lat0, \ z0, zpar, do3d, doturb, dostream, name = init() # Create gyre field velocities if don't exist yet uv(grid, ndays) # Start from the beginning and add days on for loop date = datetime(2012, 5, 23, 0, 0) # pdb.set_trace() # Run tracpy loc = 'projects/gyre/' # loc for model output lonp, latp, zp, t, grid \ = tracpy.run.run(loc, nsteps, ndays, ff, date, tseas, ah, av, \ lon0, lat0, z0, zpar, do3d, doturb, name, \ grid=grid, dostream=dostream) # Read in and plot tracks d = netCDF.Dataset('tracks/' + name + '.nc') lonp = d.variables['lonp'][:] latp = d.variables['latp'][:] tracpy.plotting.tracks(lonp, latp, name, grid=grid) tracpy.plotting.hist(lonp, latp, name, grid=grid, which='hexbin') d.close()
def fitShape(self, img): if img is None: print "invalid img!" return if self.__mPfCalcLocalProfile is None: print "unkown local profile Caculator!You should define or specify it." print "use ::setLocalProfileFun(pfCalcLocalProfile)" return self.__mImg = img minProfileDist = 1000000 scale = 1.0 (h, w, channel) = img.shape minSumDist = 10000000 bestScale = 0.0 bestShape = None for i in range(3): curImg = cv2.resize(img, (int(scale * w), int(scale * h))) curMeanShape = copy.deepcopy(self.meanShape) * scale curPcaMatrix = copy.deepcopy(self.pcaMatrix) * scale initShape = init(curImg, self.face_cascade, self.eye_cascade, curMeanShape) targetShape, sumDist = self.__match(curImg, initShape, curMeanShape, self.average_profile[i], self.sgVec[i], curPcaMatrix, self.__mSeachWindowWd, 1.0) if sumDist < minSumDist: bestScale = scale minSumDist = sumDist bestShape = targetShape # print "scale:",scale," ",sumDist scale /= float(2.0) # print "Best Scale: ",bestScale self.__fittingResult = bestShape / float(bestScale) return minSumDist
def main(): num_args = len(sys.argv) if num_args < 2: print "Usage: python main.py [instance] [plot] [iterations]" sys.exit() f = sys.argv[1] output = os.path.splitext(f)[0] + '.out' draw = False iterations = 10 if num_args > 3: draw = (sys.argv[2] == "True") iterations = int(sys.argv[3]) tour_manager = init(f) def run(num): # print "Running iteration %d" % (num + 1) return ga.ga_sol(tour_manager, 100, 50, 300) result = map(run, range(iterations)) process_result(result, draw, iterations, output)
def fitShape(self,img): if img is None: print "invalid img!" return if self.__mPfCalcLocalProfile is None: print "unkown local profile Caculator!You should define or specify it." print "use ::setLocalProfileFun(pfCalcLocalProfile)" return self.__mImg=img minProfileDist=1000000 scale=1.0 (h,w,channel)=img.shape minSumDist=10000000 bestScale=0.0 bestShape=None for i in range(3): curImg=cv2.resize(img,(int(scale*w),int(scale*h))) curMeanShape=copy.deepcopy(self.meanShape)*scale curPcaMatrix=copy.deepcopy(self.pcaMatrix)*scale initShape=init(curImg,self.face_cascade,self.eye_cascade,curMeanShape) targetShape,sumDist=self.__match(curImg,initShape,curMeanShape,self.average_profile[i],self.sgVec[i],curPcaMatrix,self.__mSeachWindowWd,1.0) if sumDist<minSumDist: bestScale=scale minSumDist=sumDist bestShape=targetShape # print "scale:",scale," ",sumDist scale/=float(2.0) # print "Best Scale: ",bestScale self.__fittingResult=bestShape/float(bestScale) return minSumDist
def _main(): Lag,Nx,Ny,lx,ly,Load,Name,ds,bcd,mesh,phi_mat,Vvec=init(sys.argv[1]) eps_er, E, nu = [0.001, 1.0, 0.3] # Elasticity parameters mu,lmbda = Constant(E/(2*(1 + nu))),Constant(E*nu/((1+nu)*(1-2*nu))) # Create folder for saving files rd = os.path.join(os.path.dirname(__file__),\ Name +'/LagVol=' +str(np.int_(Lag))+'_Nx='+str(Nx)) if not os.path.isdir(rd): os.makedirs(rd) # Line search parameters beta0_init,ls,ls_max,gamma,gamma2 = [0.5,0,3,0.8,0.8] beta0 = beta0_init beta = beta0 # Stopping criterion parameters ItMax,It,stop = [int(1.5*Nx), 0, False] # Cost functional and function space J = np.zeros( ItMax ) V = FunctionSpace(mesh, 'CG', 1) VolUnit = project(Expression('1.0',degree=2),V) # to compute volume U = [0]*len(Load) # initialize U # Get vertices coordinates gdim = mesh.geometry().dim() dofsV = V.tabulate_dof_coordinates().reshape((-1, gdim)) dofsVvec = Vvec.tabulate_dof_coordinates().reshape((-1, gdim)) px,py = [(dofsV[:,0]/lx)*2*Nx, (dofsV[:,1]/ly)*2*Ny] pxvec,pyvec = [(dofsVvec[:,0]/lx)*2*Nx, (dofsVvec[:,1]/ly)*2*Ny] dofsV_max, dofsVvec_max =((Nx+1)*(Ny+1) + Nx*Ny)*np.array([1,2]) # Initialize phi phi = Function( V ) phi = _comp_lsf(px,py,phi,phi_mat,dofsV_max) # Define Omega = {phi<0} class Omega(SubDomain): def inside(self, x, on_boundary): return .0 <= x[0] <= lx and .0 <= x[1] <= ly and phi(x) < 0 domains = MeshFunction("size_t", mesh, mesh.topology().dim()) dX = Measure('dx') n = FacetNormal(mesh) # Define solver to compute descent direction th theta,xi = [TrialFunction(Vvec), TestFunction( Vvec)] av = assemble((inner(grad(theta),grad(xi)) +0.1*inner(theta,xi))*dX\ + 1.0e4*(inner(dot(theta,n),dot(xi,n)) * (ds(0)+ds(1)+ds(2))) ) solverav = LUSolver(av) #---------- MAIN LOOP ---------------------------------------------- while It < ItMax and stop == False: # Update and tag Omega = {phi<0}, then solve elasticity system. omega = Omega() domains.set_all(0) omega.mark(domains, 1) dx = Measure('dx')(subdomain_data = domains) for k in range(0,len(Load)): U[k] = _solve_pde(Vvec,dx,ds,eps_er,bcd,mu,lmbda,Load[k]) # Update cost functional compliance = 0 for u in U: eU = sym(grad(u)) S1 = 2.0*mu*inner(eU,eU) + lmbda*tr(eU)**2 compliance += assemble( eps_er*S1* dx(0) + S1*dx(1) ) vol = assemble( VolUnit*dx(1) ) J[It] = compliance + Lag * vol # ------- LINE SEARCH ------------------------------------------ if It > 0 and J[It] > J[It-1] and ls < ls_max: ls += 1 beta *= gamma phi_mat,phi = [phi_mat_old,phi_old] phi_mat = _hj(th_mat, phi_mat, lx,ly,Nx, Ny, beta) phi = _comp_lsf(px,py,phi,phi_mat,dofsV_max) print('Line search iteration : %s' % ls) else: print('************ ITERATION NUMBER %s' % It) print('Function value : %.2f' % J[It]) print('Compliance : %.2f' % compliance) print('Volume fraction : %.2f' % (vol/(lx*ly))) # Decrease or increase line search step if ls == ls_max: beta0 = max(beta0 * gamma2, 0.1*beta0_init) if ls == 0: beta0 = min(beta0 / gamma2, 1) # Reset beta and line search index ls,beta,It = [0,beta0, It+1] # Compute the descent direction th th = _shape_der(Vvec,U,eps_er,mu,lmbda,dx,solverav,Lag) th_array = th.vector().get_local() th_mat = [np.zeros((Ny+1,Nx+1)),np.zeros((Ny+1,Nx+1))] for dof in range(0, dofsVvec_max,2): if np.rint(pxvec[dof]) %2 == .0: cx,cy= np.int_(np.rint([pxvec[dof]/2,pyvec[dof]/2])) th_mat[0][cy,cx] = th_array[dof] th_mat[1][cy,cx] = th_array[dof+1] # Update level set function phi using descent direction th phi_old, phi_mat_old = [phi, phi_mat] phi_mat = _hj(th_mat, phi_mat, lx,ly,Nx,Ny, beta) if np.mod(It,5) == 0: phi_mat = _reinit(lx,ly,Nx,Ny,phi_mat) phi = _comp_lsf(px,py,phi,phi_mat,dofsV_max) #------------ STOPPING CRITERION --------------------------- if It>20 and max(abs(J[It-5:It]-J[It-1]))<2.0*J[It-1]/Nx**2: stop = True #------------ Plot Geometry -------------------------------- if np.mod(It,10)==0 or It==1 or It==ItMax or stop==True: pp.close(); ax = pp.subplot() ax.contourf(phi_mat,[-10.0,.0],extent = [.0,lx,.0,ly],\ cmap=cm.get_cmap('bone')) ax.set_aspect('equal','box') pp.show() pp.savefig(rd+'/it_'+str(It)+'.pdf',bbox_inches='tight') return
import os sim_time = 60 * 1000 * 20 upper_bound = 5 lower_bound = 1 lsw = 1 lpw = 50 cur_time = 0 CORES = 4 reliability_list = [] T_setpoint = 60 U_setpoint = 0.66 exp_funcs = extfuncs(upper_bound, lower_bound, T_setpoint) exp_system = init(CORES, sys.argv[-2]) os.system("cp ./hotspot/hotspot.sample.init ./hotspot/hotspot.init") #exp_system.print_hardware() while cur_time < sim_time: for core_idx in range(0, CORES): exp_system.core_set[core_idx].run(cur_time) if cur_time % (lsw * 1000) == 0: exp_system.DVFS(lsw, exp_funcs) if cur_time % (lsw * lpw * 1000) == 0: exp_system.get_temperature() reliability_list.append([exp_system.get_reliability(lsw), lsw]) lsw = exp_funcs.scaling_lsw(reliability_list)
from init import * from scf import * import sys import numpy if __name__ == "__main__": ao_ints, scf_params, e_ZZ_repul = init(sys.argv[1]) eps, C, D, F = scf(ao_ints, scf_params, e_ZZ_repul) H = ao_ints['T'] + ao_ints['V'] energy = get_SCF_energy(H, F, D, scf_params['unrestricted']) \ + e_ZZ_repul print("\nFINAL SCF ENERGY: {}\n".format(energy)) # mp2 if(scf_params['method'] == "MP2"): import mp2 print("SCS-MP2 Correlation Energy: {}\n".format(mp2.get_mp2_energy(\ eps, C, ao_ints['g4'], scf_params['nel'])))
for t in range(0, 2, 60): t = np.random.randint(imgCnt) t = 0 imgName = PATH_A + "\\" + fn[t] imgNameSave = PATH_A + "\\m2_" + fn[t] print t, " ", imgName img = cv2.imread(imgName) # img=cv2.imread("xicore.jpg") # img=cv2.imread("Face_3.jpg") # img=cv2.imread("Face_29.jpg") # initialized shape # drawShape(img,meanShape,(255,0,0,255)) initShape = init(img, face_cascade, left_eye_cascade, meanShape) # drawShape(img,initShape,COLOR[0]) # cv2.imshow(imgNameSave,img) # targetShape=updateModelPoints(img,initShape,average_profile,sgVec,3) # drawShape(img,targetShape,(0,0,255,255)) # targetShape=updateModelParas(img,meanShape,targetShape,pcaMatrix) targetShape = match(img, initShape, meanShape, average_profile, sgVec, pcaMatrix, 10) drawShape(img, targetShape, COLOR[2]) # cv2.imshow(imgName,img) cv2.imshow(imgNameSave, img) cv2.imwrite(imgNameSave, img) cv2.waitKey(0)
def test_double_init(): init() init() assert 1 == 1 drop()
def test_double_drop(): init() drop(with_models=True) drop(with_models=True) assert 1 == 1
#!/usr/bin/env python3 # Import modules import boto3 import botocore import argparse import objectpath import time import pprint import os import csv import re from init import * import collections from collections import defaultdict from aws_tag_resources import tag_instances, tag_root_volumes from user_input import * from banners import welcomebanner,endbanner,banner from datetime import datetime from colorama import init, deinit, Fore from list_new_instances import list_new_instances from read_account_info import read_account_info from find_vpcs import find_vpcs from aws_add_sg_list import attach_sg_list from choose_accounts import choose_accounts # Initialize the color ouput with colorama init()
print t, " ", imgName img = cv2.imread(imgName) (h, w, channel) = img.shape # img=cv2.imread("xicore.jpg") # img=cv2.imread("Face_3.jpg") # img=cv2.imread("Face_23.jpg") # img=cv2.imread("Face_9.jpg") #initialized shape # drawShape(img,meanShape,(255,0,0,255)) (h, w, channel) = img.shape scaleIndex = 0 scale = 1.0 img = cv2.resize(img, (int(scale * w), int(scale * h))) # meanShape*=scale # pcaMatrix*=scale initShape = init(img, face_cascade, left_eye_cascade, meanShape) # targetShape=updateModelPoints(img,initShape,average_profile,sgVec,3) # drawShape(img,targetShape,(0,0,255,255)) # targetShape=updateModelParas(img,meanShape,targetShape,pcaMatrix) targetShape, minProfileDist = match(img, initShape, meanShape, average_profile[0], sgVec[0], pcaMatrix, 15, scale) drawShape(img, targetShape, COLOR[2]) cv2.namedWindow(imgNameSave, flags=cv.CV_WINDOW_AUTOSIZE) #cv2.imshow(imgName,img) cv2.imshow(imgNameSave, img) cv2.imwrite(imgNameSave, img) cv2.waitKey(0)
Energy = np.zeros(nt) Magnetization = np.zeros(nt) SpecificHeat = np.zeros(nt) Susceptibility = np.zeros(nt) T = np.linspace(1, 3, nt) #temperature for m in range(len(T)): E1 = M1 = E2 = M2 = 0 E1 = np.float64(E1) M1 = np.float64(M1) E2 = np.float64(E2) M2 = np.float64(M2) init(100,1) ## This is to equilibrate the system eqSteps = 2000 config = initialstate(N) config_init = deepcopy(config) for i in range(eqSteps): mcmove(config, 1.0/T[m]) ## This part does the main calculations and the measurements mcSteps = 2000 for i in range(mcSteps): mcmove(config, 1.0/T[m]) # monte carlo moves Ene = calcEnergy(config) # calculate the energy Mag = calcMag(config) # calculate the magnetisation
def getSolution(config): A = init() U, nconf = mod2solver(A.copy(), config.copy()) firstSolution = mod2result(U.copy(), nconf.copy()) minimumSolution = minSolution(firstSolution) return minimumSolution
from PyQt5.QtWidgets import QHBoxLayout from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtGui import QPen from PyQt5.QtGui import QPainter from window_size import * import pickle import copy window_width, window_height = get_window_size() thumbnail_label_width = int(window_width * 9 / 10) thumbnail_label_height = int(window_height * 1 / 8) rect_width = int(window_width * 3 / 4) id, dll = init() all_point = [] tmp_point = [] all_mark_text = [] tmp_all_mark_text = [] tmp_all_point = [] tmp_mark_text = [] tmp_tmp_point = [] tmp_tmp_mark_text = [] ratio = 0 original_img_height = 0 original_img_width = 0 control_button_height = 64 control_button_width = 64 thumbnail_x = 0 all_start = 0
savefig = 0 vmin = 0 vmax = 0.6 # #ncoeff=[1e-3,5e-3,1e-2,1.5e-2,2e-2,2.5e-2,3e-2]#5e-4 ncoeff = [1e-3] E, disp1, Tens, matTens, triangles, vertices, fxy = openfile(filename) N = len(E) solmatf = np.zeros((N, len(ncoeff))) pnoiselevel = np.zeros(len(ncoeff)) psnr = np.zeros(len(ncoeff)) for j, ymeas_noise_coef in enumerate(ncoeff): print('j is:', j) um, Ntlevel, SNR = addnoise(disp1, ymeas_noise_coef) pnoiselevel[j] = Ntlevel psnr[j] = SNR x1 = init(um, disp1, E, vertices, ymeas_noise_coef, Randinit, MA, scale) solmatf[:, j] = proxsolve(E, um, matTens, Tens, triangles, vertices, fxy, ymeas_noise_coef, x1, vmin, vmax, filename, Ntlevel, SNR, Itr1, Itr2, savefig, MA) # sio.savemat('one5E_sol_Itr1' + str(Itr1) + 'Itr2' + str(Itr2) + 'step03.mat', { 'sol': solmatf, 'pnl': pnoiselevel, 'psnr': psnr }) Data = loadmat('one5E_sol_img2bw0.12_MA0.mat') solmat = Data['sol'] pnl = Data['pnl'][0] psnr = Data['psnr'][0] x = np.array(vertices[:, 0]) y = np.array(vertices[:, 1])
def optimize_with_size(outer, major, coil, halton, m_batches, m_error, neutrons): gp, points, leak, leak_err = init(outer, major, coil, halton, m_batches, m_error, neutrons) print('GP model calculated') print('Optimizing...', multiprocessing.cpu_count(), 'cores.') if __name__ == "__main__": class my_problem(): global outer global coil def fitness(self, x): leak, error = gp([(x[0], x[1])]) ci1 = -(x[1] - x[0]) return (leak[0], ci1) def get_nic(self): return 1 def get_nobj(self): return 1 def get_bounds(self): lb = [coil, coil] ub = [coil + outer - 0.01, coil + outer - 0.001] return (lb, ub) gen = 10 size = 1000 algo = algorithm( sga(gen=1, mutation='uniform', crossover='sbx', cr=0.50, m=0.10)) prob = unconstrain(prob=my_problem(), method='death penalty') gp_leak = [] pbar = tqdm(total=len(points)) for k in range(len(points)): pop = population(prob, size) for i in range(gen): pop = algo.evolve(pop) leakage, leakage_error = shield(pop.champion_x, major, coil, False, outer, m_batches, m_error, neutrons) points[k] = pop.champion_x leak[k] = leakage leak_err[k] = leakage_error gp_leak.append(pop.champion_f[0]) gp = GpRegressor(points, leak, leak_err) pbar.update(1) pbar.close() opt = leak.index(min(leak)) shield(points[opt], major, coil, False, outer, m_batches, m_error, neutrons) print(bcolors.BOLD + '---------------') print('OPTIMIZATION FINISHED') print('BEST SOLUTION FOUND') print('////////////////////') print('R1:', points[opt][0], 'R2:', points[opt][1]) print('Score (GP) %:', gp_leak[opt]) print('Score (MC) %:', leak[opt]) print('Score error (MC) %:', leak_err[opt]) print('Relative error (MC) %:', leak_err[opt] / leak[opt] * 100) print('////////////////////' + bcolors.ENDC)
Df[p, Nr - 1 - i, j] = xray_transform(obj, ys[:, p], theta[Nr - 1 - i, j], phase) return Df if __name__ == '__main__': # reference coordiante system i = np.array([1.0, 0.0, 0.0], dtype=TYPE) j = np.array([0.0, 1.0, 0.0], dtype=TYPE) k = np.array([0.0, 0.0, 1.0], dtype=TYPE) # geometry parameters: source trajectory and detector parameters conf = {} conf = init(conf) # object parameters obj = {} obj = init_obj(obj, plot=False) # geometry parameters: source trajectory R = conf['source_trajectory']['radius'] P = conf['source_trajectory']['pitch'] N = conf['source_trajectory']['number_turns'] ds = conf['source_trajectory']['delta_s'] D = conf['detector']['DSD'] H = conf['detector']['height'] Nr = conf['detector']['number_rows'] Nc = conf['detector']['number_columns'] delta_w = conf['detector']['pixel_height'] # detector element height arc_alpha = conf['detector']['pixel_width'] # detector element width (arc)
print(args.cdns) return scripts, args.cdns, args.base, args.shuffle def copy_file_to_file(from_handler, to_handler): # gets two handlers of files. copies contents of the first one to second for line in from_handler: print(line, file=to_handler, end='') scripts, cdns, base, shuffle = get_args() output_file_name = 'Tizex_analyze.js' file_out = open(output_file_name, 'w') # new file # output_file = open(output_file_name, 'w') init(file_out) # this function creates a tmp file which beautified version of original code for i in range(len(scripts)): script = scripts[i] if i in cdns: if type(script) == str: # when only js file is specified in args type of script is string f = open(script) for line in f: print(line, file=file_out) elif script.attrs.get('src'): # beautifulSoup obj. a script with src attribute. src = script.attrs.get('src').strip() if src.startswith('http') or (base and base.startswith('http')): if base and not src.startswith('http'): src = os.path.join(base, src)
import pygame,sys import mpc from init import * from pygame.locals import * import PlayScreen def init(): pygame.init() pygame.font.init pygame.time.set_timer(pygame.USEREVENT, 500) # -------------- Main ------------- init() mpc = mpc.mpc() playScreen = PlayScreen.PlayScreen(mpc) screen = None if FULLSCREEN==True: screen=pygame.display.set_mode(SCREEN_SIZE,pygame.FULLSCREEN,32) else: screen=pygame.display.set_mode(SCREEN_SIZE,0,32) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_q:
def game(name): global ground totalDir = 0 init() ground = pygame.image.load("images/foreground1.png").convert_alpha() groundx = 0 timerBuff = 0 buffText = "" buffT = "" font = pygame.font.Font("fonts/vcr.ttf", 40) loadbackground(0) perso = Perso() all_sprite_list.add(perso) getSpritesVisible(all_sprite_visible, 0, all_sprite_list, perso) lvl = 0 transition = 0 score = 0 ctrldir = 0 ctrlnuage = 0 dir = 0 #dir = 1 > droite dir = -1 > gauche vis = 0 #BOUCLE INFINIE start_ticks = pygame.time.get_ticks() #starter tick continuer = 1 while continuer: # Limitation de vitesse de la boucle pygame.time.Clock().tick(fps) #pour gerer la colision oldpbottom = perso.hitb.rect.bottom oldpy = perso.hitb.rect.y #events for event in pygame.event.get(): if event.type == QUIT: raise Exception("QUIT") if event.type == KEYDOWN: if event.key == K_RIGHT: ctrldir = perso.vh elif event.key == K_LEFT: ctrldir = -perso.vh if event.key == K_UP: ctrlnuage = 1 elif event.key == K_DOWN: ctrlnuage = -1 elif event.key == K_r: init() elif event.key == K_ESCAPE: raise Exception("BACK") if event.type == KEYUP: if event.key == K_RIGHT and ctrldir == perso.vh or event.key == K_LEFT and ctrldir == -perso.vh: ctrldir = 0 if event.key == K_UP and ctrlnuage == 1 or event.key == K_DOWN and ctrlnuage == -1: ctrlnuage = 0 dir = ctrldir perso.bondir(ctrlnuage) #update des pos du fond et des elems for i in range(len(fonds)): fondsx[i] = fondsx[i] - (dir * vitessebackground[i]) groundx = groundx - dir score = max(score + dir, 0) totalDir = totalDir + dir for e in all_sprite_list: e.deplacer(dir) #collision platform corrdir = 0 block_hit_list = pygame.sprite.spritecollide(perso.hitb, platforms_list, False) for block in block_hit_list: if perso.hitb.rect.right <= block.rect.x + dir * 2: corrdir = (block.rect.x - perso.hitb.rect.right) elif perso.hitb.rect.x >= block.rect.right + dir * 2: corrdir = -(perso.hitb.rect.x - block.rect.right) elif oldpbottom <= block.rect.y: perso.v = -vitesse perso.rect.y = block.rect.y - 110 #print(perso.rect.x) perso.hitb.updt(perso) elif oldpy >= block.rect.bottom: perso.v = -perso.v perso.rect.top = block.rect.bottom - 30 perso.hitb.updt(perso) perso.changeimg() if len(block_hit_list) > 0: # update des pos du fond et des elems for i in range(len(fonds)): fondsx[i] = fondsx[i] - (corrdir * vitessebackground[i]) groundx = groundx - corrdir score = score + corrdir totalDir = totalDir + corrdir for e in all_sprite_list: e.deplacer(corrdir) #collision buffs block_hit_list = pygame.sprite.spritecollide(perso.hitb, blocksBuff_list, True) for block in block_hit_list: if block.typeBuff == "r" or block.typeBuff == "a" or block.typeBuff == "g": if perso.addBuff(block.typeBuff ) == 1: #retourne vrai si le buff est activé if block.typeBuff == "r" or block.typeBuff == "a" or block.typeBuff == "g": if ctrldir > 0: ctrldir = perso.vh elif ctrldir < 0: ctrldir = -perso.vh else: timerBuff = pygame.time.get_ticks() if block.typeBuff == "-": score = score + malusPoints buffT = str(malusPoints) elif block.typeBuff == "+": score = score + bonusPoints buffT = "+ " + str(bonusPoints) elif block.typeBuff == "++": score = score + bonusPoints1 buffT = "+ " + str(bonusPoints1) elif block.typeBuff == "t": #tp transition = 600 #affichage des fonds for i in range(len(fonds)): fondxi = fondsx[i] if fondxi <= -2 * width or fondxi >= 2 * width: fondxi = 0 fondsx[i] = 0 if fondxi < -width: fenetre.blit(fonds[i], ((fondxi) + (2 * width), 0)) elif fondxi > 0: fenetre.blit(fonds[i], ((fondxi) - (2 * width), 0)) fenetre.blit(fonds[i], (fondxi, 0)) # affichage du sol if groundx <= -2 * width or groundx >= 2 * width: groundx = 0 if groundx < -width: fenetre.blit(ground, (groundx + (2 * width), height - 148)) elif groundx > 0: fenetre.blit(ground, (groundx - (2 * width), height - 148)) fenetre.blit(ground, (groundx, height - 148)) #pygame.draw.rect(fenetre, (153, 70, 0), pygame.Rect(0, height - 148, width, 148)) #affichage des sprites all_sprite_visible.draw(fenetre) #verif et affichage du buff buffText = "" if perso.buff != "": duraBuff = 5 - (pygame.time.get_ticks() - perso.startBuff ) / 1000 # calculate how many seconds if duraBuff < 0: #on enleve le buff perso.deBuff() if ctrldir > 0: ctrldir = perso.vh elif ctrldir < 0: ctrldir = -perso.vh if perso.buff == "r": color = (0, 200, 0) buffText = font.render("SLOW", True, color) elif perso.buff == "g": color = (200, 200, 200) buffText = font.render("LEVITATION", True, color) else: color = (0, 0, 200) buffText = font.render("SPEED", True, color) buffHud = pygame.Rect(0, 0, duraBuff * 50, 20) buffHud.centerx = width / 2 pygame.draw.rect(fenetre, color, buffHud) text_r = buffText.get_rect() text_r.centerx = width / 2 # align to right to 150px text_r.top = 25 fenetre.blit(buffText, text_r) #affichage bonus if (2 - (pygame.time.get_ticks() - timerBuff) / 1000) > 0: textB = font.render(buffT, True, (255, 255, 255)) textB_rect = textB.get_rect() textB_rect.right = width - 10 # align to right to 150px textB_rect.y = 50 fenetre.blit(textB, textB_rect) #affichage du niveau text = font.render("FLOOR " + str(-lvl), True, (255, 255, 255)) text_rect = text.get_rect() text_rect.centerx = width / 2 # align to right to 150px text_rect.y = height - 80 fenetre.blit(text, text_rect) #affichege du score text = font.render(str(int(score)), True, (255, 255, 255)) text_rect = text.get_rect() text_rect.right = width - 10 # align to right to 150px text_rect.y = 10 fenetre.blit(text, text_rect) #affichage du timer seconds = 180 - (pygame.time.get_ticks() - start_ticks) / 1000 # calculate how many seconds min = int(seconds / 60) seconds = int(seconds % 60) if seconds <= 0 and min == 0: saveNew(name, int(score)) raise Exception("END") if seconds >= 10: seconds = str(seconds) else: seconds = "0" + str(seconds) text = font.render(str(min) + ":" + seconds, True, (255, 255, 255)) fenetre.blit(text, (10, 10)) #transition if transition > 0: while transition > -height - 148: #affichage du fond if transition == 0: tp(int(block.dest)) totalDir = totalDir + block.dest init() for e in all_sprite_list: e.deplacer(totalDir) else: for i in range(len(fonds)): fondxi = fondsx[i] if fondxi <= -2 * width or fondxi >= 2 * width: fondxi = 0 fondsx[i] = 0 if fondxi < -width: fenetre.blit(fonds[i], ((fondxi) + (2 * width), 0)) elif fondxi > 0: fenetre.blit(fonds[i], ((fondxi) - (2 * width), 0)) fenetre.blit(fonds[i], (fondxi, 0)) #affichage du sol if transition > -height: if groundx < -width: fenetre.blit(ground, (groundx + (2 * width), transition)) elif groundx > 0: fenetre.blit(ground, (groundx - (2 * width), transition)) fenetre.blit(ground, (groundx, transition)) else: if groundx < -width: fenetre.blit(ground, (groundx + (2 * width), transition + 2 * height)) elif groundx > 0: fenetre.blit(ground, (groundx - (2 * width), transition + 2 * height)) fenetre.blit(ground, (groundx, transition + 2 * height)) pygame.display.flip() if transition == 0: lvl = int(totalDir / 100000) loadbackground(lvl) #all_sprite_visible.draw(fenetre) transition -= 60 pygame.time.Clock().tick(fps) pygame.display.flip() getSpritesVisible(all_sprite_visible, score, all_sprite_list, perso) pygame.display.flip() if dir != 0: getSpritesVisible(all_sprite_visible, score, all_sprite_list, perso) return int(score)
def test_drop(): init() drop(with_models=True) assert len(dm().all()) == cnt_base_decks assert len(ms().all()) == cnt_base_models
jika test == Benar : vprint ( " SQLi vuln! -> " + url, " cyan " , " info " ) uji elif == " keluar " : istirahat lain : lulus cetak " - " * 20 def main (): '' ' Fungsi utama ' '' if len (sys.argv) == 3 dan sys.argv [ 1 ] di [ ' -t ' , ' --target ' ]: url = sys.argv [ - 1 ] vprint ( " Situs web Target: " + url, " yellow " , " info " ) rIp (url) merangkak() sC () lain : pemakaian() if __name__ == " __main__ " : init ( autoreset = True ) logo() vprint ( " Program dimulai " , " hijau " , " info " ) utama() vprint ( " Program mematikan " , " kuning " , " info " )
# convert an array of values into a dataset matrix def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset) - look_back - 1): a = dataset[i:(i + look_back), 0] dataX.append(a) dataY.append(dataset[i + look_back, 0]) return numpy.array(dataX), numpy.array(dataY) numpy.random.seed(7) # load the dataset df = init() dataset = pandas.DataFrame(df, columns=['btc_market_price']) dataset = dataset.values dataset = dataset.astype('float32') # normalize the dataset scaler = MinMaxScaler(feature_range=(0, 1)) dataset = scaler.fit_transform(dataset) # split into train and test sets, 80:20 split train_size = int(len(dataset) * 0.80) test_size = len(dataset) - train_size train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :] # reshape into X=t and Y=t+1 look_back = 3
''' Using Multiple Linear Regression to predict the next day's closing values of Bitcoin's market price in USD. ''' import pandas, sklearn, numpy from sklearn import linear_model from init import * ipdata = init() def correlation(dataset_arg, threshold, toprint=False): ''' Return a copy of 'dataset_arg' without the columns that have correlation > threshold ''' dataset = dataset_arg.copy(deep=True) col_corr = set() # Set of all the names of deleted columns corr_matrix = dataset.corr() for i in range(len(corr_matrix.columns)): for j in range(i): if corr_matrix.iloc[i, j] >= threshold: colname = corr_matrix.columns[i] # getting the name of column col_corr.add(colname) if colname in dataset.columns: del dataset[ colname] # deleting the column from the dataset if toprint: print(dataset) return dataset
def test_init(): init() assert len(dm().all()) == cnt_base_decks + len(conf.decks) assert len(ms().all()) == cnt_base_models + len(conf.models) assert len(tg().all()) == len(conf.tags) drop()
from DLDA import * from init import * from numpy import matrix training_file="../Data/Training_Data.txt" training=matrix(init(training_file)) testing_file="../Data/Testing_Data.txt" testing=matrix(init(testing_file)) total_gene=70 ex_range=3 ex_search=exhaustive_search(total_gene,ex_range) minerror=1.0 for i in ex_search: parameters = DLDA_training(training[:,i],len(i)-2) mean0=parameters[0] mean1=parameters[1] cov0 = parameters[2] cov1=parameters[3] N0=parameters[4] N1=parameters[5] label = DLDA_testing(testing[:,i], mean0,mean1,cov0,cov1,N0,N1) error =0.0 for j in range(0,len(testing)): if testing[j,-1]!=label[j]: error =error+1 error=float(error/len(testing)) if error<minerror: minerror = error feture_selected = i print error print feture_selected