def test_grid_shape(self): """ Make sure the grid shapes of the exec configs are correct. """ tot_threads = lambda gs, bs: (gs[0] * bs[0], gs[1] * bs[1]) for case in self.cases: space.initialize_space(case['shape']) z = Out(case['dtype']) fun = Kernel('', ('z', 'out', z.dtype)) for cfg in fun.exec_configs: for ind in range(2): self.assertTrue(cfg['grid_shape'][ind] * \ cfg['block_shape'][ind] >= \ case['shape'][ind+1]) self.assertTrue((cfg['grid_shape'][ind]-1) * \ cfg['block_shape'][ind] < \ case['shape'][ind+1]) # One padded case. fun = Kernel('', ('z', 'out', z.dtype), padding=(1, 2, 3, 4)) pad = [3, 7] for cfg in fun.exec_configs: for ind in range(2): self.assertTrue(cfg['grid_shape'][ind] * \ (cfg['block_shape'][ind]-pad[ind]) >= \ case['shape'][ind+1]) self.assertTrue((cfg['grid_shape'][ind]-1) * \ (cfg['block_shape'][ind]-pad[ind]) < \ case['shape'][ind+1])
def __init__(self, name, assignable_names, kernel_func_rgb, kernel_func_of, kernel_func_depth, kernel_func_concatenate, C_mkl, C_rgb=None, C_of=None, C_depth=None, C_concatenate=None, lam_mkl=None): self.name = name self.assignable_names = [ assignable_name.lower() for assignable_name in assignable_names ] self.kernel_rgb = Kernel(kernel_func_rgb, name, 'rgb') self.kernel_of = Kernel(kernel_func_of, name, 'of') self.kernel_depth = Kernel(kernel_func_depth, name, 'depth') self.kernel_concatenate = Kernel(kernel_func_concatenate, name, ['(rgb-of)', '(rgb-of-depth)']) self.C_mkl = C_mkl self.C_rgb = C_rgb if C_rgb is not None else C_mkl self.C_of = C_of if C_of is not None else C_mkl self.C_depth = C_depth if C_depth is not None else C_mkl self.C_concatenate = C_concatenate if C_concatenate is not None else C_mkl self.lam_mkl = lam_mkl
def test_create_kernel(): _kernel_1 = Kernel(simulated_interfaces=False, log=None, log_id="", table_name="main") _kernel_2 = Kernel(simulated_interfaces=False, log=None, log_id="", table_name=3)
def test_init(self): """ Just make sure we can initialize the kernel. """ for case in self.cases: # Form data to work on. space.initialize_space(case['shape']) x_np = np.random.randn(*case['shape']).astype(case['dtype']) x = Grid(x_np) fun = Kernel('', ('x', 'grid', x.dtype)) fun = Kernel('', ('x', 'grid', x.dtype), shape_filter='all') fun = Kernel('', ('x', 'grid', x.dtype), shape_filter='skinny') fun = Kernel('', ('x', 'grid', x.dtype), shape_filter='square') self.assertRaises(TypeError, Kernel, '', ('x', 'grid', x.dtype), \ shape_filter1='all') self.assertRaises(TypeError, Kernel, '', ('x', 'grid', x.dtype), \ shape_filter='blah')
def new_kernels(teacher, record, kernel_n, alpha=opt.co_alpha, beta=opt.co_beta, gamma=opt.co_gamma): start_time = time.time() kernels = [] for i in range(kernel_n): kernel = Kernel(teacher.rep, 0.0) indices = [] for j in range(record.n): if random.random() < gamma: indices.append(j) if len(indices) > 0: x = [record.x[i] for i in indices] indices = torch.tensor(indices, dtype=torch.long, device=opt.device) y = torch.index_select(record.y, 0, indices) kernel.add_batch(x, y) ma = 0.0 for j in range(100): ll = kernel.opt_step() opt.writer.add_scalar( 'step_%d/kernel_%d_loglikelihood' % (opt.i, i), ll, j) ma = (alpha * ll + (1 - alpha) * ma) if j > 0 else ll if j > 5 and abs(ma - ll) < beta: break kernels.append(kernel) opt.writer.add_scalar('compression/kernel_time', time.time() - start_time, opt.i) return kernels
def __create_iso_install_kernel_and_initrd(self): boot_path = self.media_dir + '/boot/x86_64/loader' Path.create(boot_path) kernel = Kernel(self.boot_image_task.boot_root_directory) if kernel.get_kernel(): kernel.copy_kernel(boot_path, '/linux') else: raise KiwiInstallBootImageError( 'No kernel in boot image tree %s found' % self.boot_image_task.boot_root_directory ) if self.machine and self.machine.get_domain() == 'dom0': if kernel.get_xen_hypervisor(): kernel.copy_xen_hypervisor(boot_path, '/xen.gz') else: raise KiwiInstallBootImageError( 'No hypervisor in boot image tree %s found' % self.boot_image_task.boot_root_directory ) self.boot_image_task.create_initrd(self.mbrid) Command.run( [ 'mv', self.boot_image_task.initrd_filename, boot_path + '/initrd' ] )
def addmoney(): kernel=Kernel() role=chkroleloggedin('adult') if request.method=="POST": if role != "!!": if role: child=request.form["child"] sqlstr='select * from users' cur=conn.execute(sqlstr) rows=cur.fetchall() nowdollar=kernel.getmoney(child) if nowdollar == "D": flash("The child account you entered either is not an valid account or is not a child.") return redirect(url_for("addmoney")) else: enckey=EncryptPass() addmoney1=request.form["dollars"] session["add"]=enckey.encrypt(sessionid[session["sessionid"]],str(addmoney1)) session["child"]=enckey.encrypt(sessionid[session["sessionid"]],child) session["cm"]=enckey.encrypt(sessionid[session["sessionid"]],nowdollar) session["notes"]=enckey.encrypt(sessionid[session["sessionid"]],request.form["notes"]) #print(session["add"]) #flash("Success!") return redirect(url_for("add_now")) else: flash(lang["msg6"]) return redirect(url_for("home")) else: return redirect(url_for("logout")) else: if role != "!!": return render_template("nano/add.html",productname=productname,year=year,action="Add") else: flash(lang["msg7"]) return redirect(url_for("logout"))
def __copy_first_boot_files_to_system_image(self): log.info('Copy boot files to system image') kernel = Kernel(self.boot_image_task.boot_root_directory) if kernel.get_kernel(): log.info('--> boot image kernel as first boot linux.vmx') kernel.copy_kernel( self.root_dir, '/boot/linux.vmx' ) else: raise KiwiDiskBootImageError( 'No kernel in boot image tree %s found' % self.boot_image_task.boot_root_directory ) if self.machine and self.machine.get_domain() == 'dom0': if kernel.get_xen_hypervisor(): log.info('--> boot image Xen hypervisor as xen.gz') kernel.copy_xen_hypervisor( self.root_dir, '/boot/xen.gz' ) else: raise KiwiDiskBootImageError( 'No hypervisor in boot image tree %s found' % self.boot_image_task.boot_root_directory ) log.info('--> initrd archive as first boot initrd.vmx') Command.run( [ 'mv', self.boot_image_task.initrd_filename, self.root_dir + '/boot/initrd.vmx' ] )
def main(): print('Starting main...') print('Instantiating world...') mundo = Mundo() print('Done instatiating world') k = Kernel() k.loop() print('Kernel started')
def start(args): """Starting the program. Parameters ---------- args : dict Command line arguments. Returns ------- None """ image = cv2.imread(args["image"]) if image is None: print("\033[91;1mImage not found\033[0m") return # Converting the image to 1 channel grayscale ndarray. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying gaussian filter. print("\033[97;1mApplying \033[93;1mGaussian filter\033[0m") data = Kernel(GAUSSIAN).roll(image) # Applying sobel operator. print("\033[97;1mApplying \033[93;1mSobel operator\033[0m") data_x, data_y = [Kernel(model).roll(data) for model in [SOBEL_X, SOBEL_Y]] gradient = np.sqrt(np.square(data_x) + np.square(data_y)) angles = np.arctan2(data_y, data_x) # Starting canny edge detection. img = canny.start(gradient, angles, *args["threshold"]) # Applying color. if args["colored"]: colored = color.applycolor(img, angles, args["stroke"]) else: colored = cv2.merge((img, img, img)) output_name = f"{args['image'].split('.')[0]}_output.png" cv2.imwrite(output_name, colored) print("\033[92;1mDone\033[0m")
def __init__(self, db, ratio_split, lbd, kernel="raw_kernel", k=None, C=1, nkp=False): self.n = int(len(db)*ratio_split) self.lbd = lbd self.k = Kernel(self.lbd,k) self.ker = getattr(self.k, kernel) self.X, self.y = db[:,0], db[:,1]#shuffle(db[:,0], db[:,1]) self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(db[:,0], db[:,1], train_size=ratio_split, random_state=42, stratify=db[:,1]) self.svc = SVC(kernel='precomputed', C=1) self.nkp = nkp
def __init__(self, features=[], target_value=0.0): self.features = copy.deepcopy(features) # 样本的特征向量 self.target_value = target_value # e.g. +1, -1 self.label = target_value # e.g. +1, -1, 0, 2, 3, (使用多分类) self.alpha_value = 0.0 self.error_value = 0.0 self.tolerance_error = 0.001 self.index = 0 # Outside index number within samples of parent-class self.kernel = Kernel(Method.Linear) # 预设使用线性分割(Linear)
def login(): global conn stmt = """SELECT count(*) FROM sqlite_master WHERE type='table' AND name='users';""" cur=conn.execute(stmt) result = cur.fetchone() if result[0] == 0: flash("Your Server Haven't Been Setup Yet.") return redirect(url_for("oobe.start")) else: #print(chklogin("a","a")) #Kernel Module Implemented cor=False if request.method == "POST": #hasher=Hashing() #session.permanent = True user = request.form["nm"] passwd = request.form["pass"] kernel=Kernel() if user == "" or passwd=="": flash(lang["msg12"]) return redirect(url_for("login")) if kernel.checkuser(user,passwd)[0]==True: session["user"] = user session["role"] = kernel.checkuser(user,passwd)[1][2] gensession() flash(lang["msg2"]) return redirect(url_for("home")) #sqlstr='select * from users' #tmp=conn.execute(sqlstr) #print(tmp) #rows=tmp.fetchall() #print(rows) #print(rows[5][0]) #for row in rows: #print('!') #if hasher.check(passwd,row[1]) and user == row[0]: #else: #session["user"] = user #session["role"] = row[2] #gensession() #cor=True #flash(lang["msg2"]) #return redirect(url_for("home")) #else: #pass else: flash(lang["msg1"]) return redirect(url_for("login")) else: if "role" in session: user = session["user"] flash(lang["msg3"]) return redirect(url_for("home")) else: return render_template("nano/login.html",productname=productname,year=year)
def __init__(self, image_shape, kernel_shape, kernels=None): self.image_shape = image_shape self.kernel_shape = kernel_shape self.output_shape = (kernel_shape[0], image_shape[1]-kernel_shape[2]+1, image_shape[2]-kernel_shape[3]+1) if kernels is not None: self.kernels = kernels else: self.kernels = [] for x in range(kernel_shape[0]): self.kernels.append(Kernel(kernel_shape[1:]))
def testDiffuseKernel(self): correct_heats, s = parseHeats(TEST_DIFFUSED_SOLN) input_heats, input_signs = parseHeats(TEST_INPUT) diffuser = Kernel(TEST_KERNEL) diffused = diffuser.diffuse(input_heats, reverse=False) for (key, val) in diffused.iteritems(): if val < 1: self.assertAlmostEqual(val, correct_heats[key], places=5) else: self.assertAlmostEqual(val, correct_heats[key], places=3)
def test_put_del_route_errors(): kern = Kernel(simulated_interfaces=False, log=None, log_id="", table_name="main") if not kern.platform_supported: return # Attempt to add route with nonsense next-hop interface prefix = make_ip_prefix("99.99.99.99/32") nhops = [NextHop(False, "nonsense", None, None)] rte = FibRoute(prefix, nhops) assert not kern.put_route(rte)
def remove_now2(): #Remove Now! kernel=Kernel() if request.method == "POST": if "add" in session and "child" in session and "cm" in session and "notes" in session: #session["add"] if chkroleloggedin(None) == "!!": return redirect(url_for("logout")) enckey=EncryptPass() if enckey.decrypt(sessionid[session["sessionid"]],session["step"]) !="2": return redirect(url_for('removemoney')) else: chklogin1=kernel.checkuser(request.form['nm'],request.form['pass']) if chklogin1[0]: if chklogin1[1][2] == "child" and request.form['nm'] == enckey.decrypt(sessionid[session["sessionid"]],session["child"]): #PREP THE COMMAND #enckey=EncryptPass() child=enckey.decrypt(sessionid[session["sessionid"]],session["child"]) adder=enckey.decrypt(sessionid[session["sessionid"]],session["add"]) nowdollar=enckey.decrypt(sessionid[session["sessionid"]],session["cm"]) notes=enckey.decrypt(sessionid[session["sessionid"]],session["notes"]) popadds() #Remake KEY regen() #cmd='UPDATE users SET "Money" = "'+str(int(nowdollar)-int(adder))+'" WHERE Name="'+child+'"' #curs = conn.cursor() #curs.execute(cmd) #conn.commit() #History Module #Coming Soon :> kernel.removemoney(child,session["user"],session["role"],adder,notes) flash(lang["success"]) return redirect(url_for("home")) else: popadds() flash(lang["msg1"]+"/"+lang["msg8"]+"/ Your User is not the specified user.") return redirect(url_for("home")) else: flash(lang["msg1"]+"/"+lang["msg8"]+"/ Your User is not the specified user.") popadds() return redirect(url_for("home")) else: flash("Unknown Error.") popadds() return redirect(url_for("removemoney")) else: if "add" in session and "child" in session and "cm" in session and "step" in session: flash(lang["msg11"]) return render_template("nano/login.html",productname=productname,year=year) else: flash(lang["msg10"]) popadds() return redirect(url_for("logout"))
def handle(self): self.kernel = Kernel() sock = self.request.makefile(mode='rw') self.console = Console(self.kernel, sock, sock) self.kernel.start() self.console.start() try: self.kernel.join() except KeyboardInterrupt: self.kernel.shutdown() self.kernel.join(1.0) self.console.join(1.0)
def learn(self, source_data, target_data, kernel=None): """Launch learning process.""" if kernel is None: kernel = Kernel(kernel_str='linear') if self.verbose: print('Building kernel matrix.') data_matrix = np.vstack((source_data.X, target_data.X)) label_vector = np.hstack( (source_data.Y, np.zeros(target_data.get_nb_examples()))) kernel_matrix = kernel.create_matrix(data_matrix) alpha_vector = self.learn_on_kernel_matrix(kernel_matrix, label_vector) return KernelClassifier(kernel, data_matrix, alpha_vector)
def mainLoading(filename): env = simpy.Environment() kernel = Kernel(env) loader = Loader(filename) loader.load(kernel) kernel.buildTransports() kernel.buildPassengers(1000) kernel.run() env.run(until=1000)
def __init__(self, dataset, labels, C=1.0, tolerance=1e-4, maxIter=10000, kernelTup=('linear', )): self.dataset = dataset self.labels = labels self.C = C self.tolerance = tolerance self.maxIter = maxIter self.kern = Kernel(kernelTup=kernelTup) self.m = len(dataset) self.alphaArr = np.zeros((self.m, 1)) self.b = 0
def calcfitness(pop, params): ''' Reads the data of type params['type'] and with the data path params['data'], then fits the SVC or SVR model depending on the params['type'] with the custom kernel, determined by the "pop" parameter. Calculates the resulting metrics for the input population. :param pop: Population, which will determine the custom kernel for SVM model :param params: Parameters, containing the info about population and about the task we are solving :return: -MSE for regression task, Accuracy * 100 for the binary and multi classification tasks ''' models = [] fitness = [] #if params['type'] == 'binary': # here to return all code i wrote for Arabic Sentiment ##################################3 to not repeat ################## trainX = params['trainX'] testX = params['testX'] trainY = params['trainY'] testY = params['testY'] ##################################### end of not repeat ################ shapetrainX = trainX.shape shapetrainY = trainY.shape for i in range(params['popSize']): ind = pop[ i] # Population consists of params['popSize'] kernel variations k = Kernel(ind) # k.kernel #svm1 = SVC(max_iter=MAX_ITER, kernel='linear', probability=True) # create an SVM model with custom kernel svm = SVC(max_iter=MAX_ITER, kernel=k.kernel, probability=True) svm.fit(trainX, trainY) label = svm.predict(testX) models.append(svm) #L = np.sum(label != testY) / len(testY) L = np.sum((label - testY)**2) / len(testY) print(f'The value of loss {L}\n') #fitness = accuracy_score(testY, label) * 100 #mse = (100 - fitness) / 100 # removed from pranthesis fitness.append((100 - (accuracy_score(testY, label) * 100))) print(f'Accuracy : {fitness}\n') #fitness.append(mse) return fitness, models, testX, testY
def genapi(user,passwd): kernel=Kernel() cor=kernel.checkuser(user,passwd)[0] if cor: row=kernel.checkuser(user,passwd)[1] if cor: global apis cor=True letters = string.ascii_letters letters=letters+string.digits apikey = ''.join(random.choice(letters) for i in range(64)) apis[apikey]=user #{'APIKEY':[Username,Role]} print("[Debug Information] API KEY LIST = "+str(apis)) return {'value':apikey} if not cor: return {'value':'0x00000'}
def add_now(): #Add Now! kernel=Kernel() if request.method == "POST": if "add" in session and "child" in session and "cm" in session and "notes" in session: #session["add"] if chkroleloggedin(None) == "!!": return redirect(url_for("logout")) else: chklogin1=chklogin(request.form['nm'],request.form['pass']) if chklogin1[0]: if chklogin1[2] == "adult": #PREP THE COMMAND enckey=EncryptPass() child=enckey.decrypt(sessionid[session["sessionid"]],session["child"]) adder=enckey.decrypt(sessionid[session["sessionid"]],session["add"]) nowdollar=enckey.decrypt(sessionid[session["sessionid"]],session["cm"]) notes=enckey.decrypt(sessionid[session["sessionid"]],session["notes"]) popadds() #cmd='UPDATE users SET "Money" = "'+str(int(nowdollar)+int(adder))+'" WHERE Name="'+child+'"' #curs = conn.cursor() #curs.execute(cmd) #conn.commit() kernel.addmoney(child,session["user"],session["role"],adder,notes) #Remake KEY #History Module #Coming Soon :> regen() flash(lang["success"]) return redirect(url_for("home")) else: popadds() flash(lang["msg1"]+"/"+lang["msg8"]) return redirect(url_for("home")) else: popadds() return redirect(url_for("addmoney")) else: #Get if "add" in session and "child" in session and "cm" in session and "notes" in session: flash(lang["msg9"]) return render_template("nano/login.html",productname=productname,year=year) else: flash(lang["msg10"]) return redirect(url_for("logout"))
def test_put_del_route(): kern = Kernel(simulated_interfaces=False, log=None, log_id="", table_name="5") if not kern.platform_supported: return # Put route with one next-hop (with interface but no address) prefix = make_ip_prefix("99.99.99.99/32") nhops = [NextHop(False, "lo", None, None)] rte = FibRoute(prefix, nhops) assert kern.put_route(rte) # Delete route just added assert kern.del_route(prefix) # Put route with one next-hop (with interface and address) prefix = make_ip_prefix("99.99.99.99/32") address = make_ip_address("127.0.0.1") nhops = [NextHop(False, "lo", address, None)] rte = FibRoute(prefix, nhops) assert kern.put_route(rte) # Delete route just added assert kern.del_route(prefix) # Put ECMP route with multiple next-hop (with interface and address) prefix = make_ip_prefix("99.99.99.99/32") address1 = make_ip_address("127.0.0.1") address2 = make_ip_address("127.0.0.2") nhops = [ NextHop(False, "lo", address1, None), NextHop(False, "lo", address2, None) ] rte = FibRoute(prefix, nhops) assert kern.put_route(rte) # Do we display the ECMP route properly? tab_str = kern.cli_route_prefix_table(5, prefix).to_string() pattern = (r"[|] Table +[|] 5 +[|]\n" r"[|] Address Family +[|] IPv4 +[|]\n" r"[|] Destination +[|] 99\.99\.99\.99/32 +[|]\n" r"[|] Type +[|] Unicast +[|]\n" r"[|] Protocol +[|] RIFT +[|]\n" r"[|] Scope +[|] Universe +[|]\n" r"[|] Next-hops +[|] lo 127\.0\.0\.1 1 +[|]\n" r"[|] +[|] lo 127\.0\.0\.2 1 +[|]\n") assert re.search(pattern, tab_str) is not None # Delete route just added assert kern.del_route(prefix)
def __init__(self): self.label = float("inf") # 预设是 Float 最大值, 代表这是一个标准只处理 2 分类的 SVM Model # Label 的原意思是用在多分类上,看这一个 Model 主要是用来分类哪一种【正样本】 的。 self.samples = [] # Sample Object, from sample.py self.weights = [] self.bias = 0.0 # bias 只有 1 个 self.groups = {} # 分到正样本(+1)或负样本(-1)群里:[target value] = group self.const_value = 0.0 self.tolerance_error = 0.0 self.max_iteration = 100 self.kernel = Kernel(Method.Linear) # 预设使用线性分割(Linear) self.iteration_callback = None self.completion_callback = None self.examine_all = False # 是否遍历全部的点 self._create_groups([1, -1]) # 建立 +1, -1 这 2 个分类群,之后多分类会用到 self.split_index = 0 self.iteration_update_count = 0
def __init__(self, input_shape, kernel_shape, kernels=None, activation_function=RELU): super(ConvLayer, self).__init__( input_shape=input_shape, output_shape=(kernel_shape[0], input_shape[1] - kernel_shape[2] + 1, input_shape[2] - kernel_shape[3] + 1), activation_function=activation_function) self.kernel_shape = kernel_shape if kernels is not None: self.kernels = kernels else: self.kernels = [] for x in range(kernel_shape[0]): self.kernels.append(Kernel(kernel_shape[1:]))
def create_kernel_from_file(self, pre_computed_kernel_url): """ Input: pre_computed_kernel_file - filename of tab delemited kernel file, as made by KernelGenerator """ ker = [] start = True labels = list() for line in csv.reader(urllib2.urlopen(pre_computed_kernel_url), delimiter='\t'): if start: labels = line[1:] start = False else: ker.append([float(x) for x in line[1:]]) kernel = csc_matrix(np.asarray(ker)) return Kernel(kernel=kernel, labels=labels, index2node=None)
def run(self): LOG.info("Emulator started") kernel = Kernel(core=self.__core, screen=self.__screen) msg = [ord(c) for c in "HELLO WORLD!"] msg.append(0x00) LOG.debug(len(msg)) addr = stdlib.malloc(len(msg)) length = len(msg) self.__core.EAX = 4 # sys_write self.__core.EBX = 1 # stdout self.__core.ECX = addr self.__core.EDX = length self.__core.set_memory_range(addr, msg) kernel.interrupt(0x80) # handover to kernel stdlib.free(addr)
def chklogin(user,pw): global conn cor=False if "a" == "a": hasher=Hashing() session.permanent = True user = user passwd = pw sqlstr='select * from users' cur=conn.execute(sqlstr) rows=cur.fetchall() #print(rows) #print(rows[5][0]) kernel=Kernel() tmp=kernel.checkuser(user, pw) if tmp[0] == False: return [False,0] else: return [tmp[0],tmp[1][0],tmp[1][2]]