id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
9650342
import os import torch.utils.data import numpy as np import torch.nn as nn import torch.utils.data import torch.optim as optim import matplotlib.pyplot as plt import DataPreprocessing as DP from training import training from Network import MLP, CNN, CNN2 DP.gpu_setting(gpu_num=0) # hyper-parameter setting learning_rate = 1e-5 batchSize = 20 start_epoch = 0 num_epoch = 50 # file path datapath = os.getcwd() # Picture memory # datatype = './PM_PSD_24H/' # Location memory datatype='./LM_PSD_24H/' # 1D x_datapath = 'x_data/' y_datapath = 'y_data/' # 2D mesh (only CNN) # x_datapath = 'x_2Ddata/' # y_datapath = 'y_2Ddata/' x_filepath = datapath + datatype + x_datapath y_filepath = datapath + datatype + y_datapath x_filelist = os.listdir(x_filepath) y_filelist = os.listdir(y_filepath) # sort x_filelist.sort() y_filelist.sort() # file load x_data = [] y_data = [] for i in range(len(x_filelist)): x_data.append(DP.preprocess_data(x_filepath, x_filelist[i])) y_data.append(DP.load_header(y_filepath, y_filelist[i])) acc_mean = [] kappa_mean = [] conf_matrix_kappa_max = [] for fold in range(len(x_data)): [trainx, trainy, testx, testy] = DP.split_train_test(x_data, y_data, fold) # CNN trainx = np.transpose(trainx, (3, 2, 0, 1)) testx = np.transpose(testx, (3, 2, 0, 1)) # MLP trainx = np.transpose(trainx, (1, 0)) testx = np.transpose(testx, (1, 0)) trainx = torch.FloatTensor(trainx).cuda() testx = torch.FloatTensor(testx).cuda() trainy = torch.LongTensor(trainy).cuda() testy = torch.LongTensor(testy).cuda() train = torch.utils.data.TensorDataset(trainx, trainy) test = torch.utils.data.TensorDataset(testx, testy) # batch iterator trainloader = torch.utils.data.DataLoader(train, batch_size=batchSize, shuffle=True) testloader = torch.utils.data.DataLoader(test, batch_size=batchSize, shuffle=False) # model define net = CNN(2) # outputsize net.cuda() # loss define (cross-entropy) criterion = nn.CrossEntropyLoss() # Optimizer define optimizer = optim.SGD(net.parameters(), lr=learning_rate, weight_decay=1e-9) # scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epoch) setting = {'net': net, 'trainloader': trainloader, 'testloader': testloader, 'optimizer': optimizer, # 'scheduler': scheduler, 'loss': criterion, 'max_epoch': num_epoch, 'fold': fold } [training_losses, kappa_epoch, test_losses, acc_epoch, conf_matrix_all] = training(setting) # loss plt.figure() plt.plot(training_losses, label='Training loss') plt.plot(test_losses, label='Test loss') plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend(frameon=False) plt.savefig(datatype+'results_MLP/Training'+str(fold)+'.png') plt.close() # Acc plt.figure() plt.plot(acc_epoch, label='Val Accuracy/Epochs') plt.legend("") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend(frameon=False) plt.savefig(datatype+'results_MLP/Acc'+str(fold)+'.png') plt.close() # kappa plt.figure() plt.plot(kappa_epoch, label='Val Kappa Score/Epochs') plt.legend("") plt.xlabel("Epochs") plt.ylabel("Kappa Score") plt.legend(frameon=False) plt.savefig(datatype+'results_MLP/Kappa'+str(fold)+'.png') plt.close() print('[MAX Accuracy] %.3f(%d), [MAX Kappa] %.3f(%d)' % (np.max(acc_epoch), np.argmax(acc_epoch), np.max(kappa_epoch), np.argmax(kappa_epoch))) # acc / kappa acc_mean.append(np.max(acc_epoch)) kappa_mean.append(np.max(kappa_epoch)) # confusion matrix conf_matrix_kappa_max.append(conf_matrix_all[np.argmax(kappa_epoch)]) # average accuracy Acc_avg = np.mean(acc_mean) Acc_std = np.std(acc_mean) # kappa accuracy kappa_avg = np.mean(kappa_mean) kappa_std = np.std(kappa_mean) # confusion matrix conf_max = sum(conf_matrix_kappa_max) print(conf_max) print(conf_max.astype('float') / conf_max.sum(1)[:, None]) print('[Average Acc] %.3f(%.3f), [Average Kappa] %.3f(%.3f)' % (Acc_avg, Acc_std, kappa_avg, kappa_std))
StarcoderdataPython
146482
# import only necessary functions from modules to reduce load from fdtd_venv import fdtd_mod as fdtd from numpy import arange, array, where from matplotlib.pyplot import subplot, plot, xlabel, ylabel, legend, title, suptitle, show, ylim, figure from scipy.optimize import curve_fit from os import path from sys import argv from time import time def fit_func(x, a, b, c): return a*x**2 + b*x + c start_time = time() animate = False run_time = 400 saveStuff = False results = True transmit_detectors = 32 # grid grid = fdtd.Grid(shape=(200, 15.5e-6, 1), grid_spacing=77.5e-9) if saveStuff: grid.save_simulation(argv[1] if len(argv) > 1 else None) # objects # source #grid[15, 99, 0] = fdtd.PointSource(period = 1550e-9 / (3e8), name="source1") grid[15, 100, 0] = fdtd.PointSource(period = 1550e-9 / (3e8), name="source2") # detectors #grid[80:200, 80:120, 0] = fdtd.BlockDetector(name="BlockDetector") #grid[80:200, 100, 0] = fdtd.LineDetector(name="LineDetectorVert") grid[19, 75:125, 0] = fdtd.LineDetector(name="LineDetectorHorIncident") for i in range(transmit_detectors): grid[30+5*i, 75:125, 0] = fdtd.LineDetector(name="LineDetectorHorEmergent_"+str(30+5*i)) # x boundaries grid[0:10, :, :] = fdtd.PML(name="pml_xlow") grid[-10:, :, :] = fdtd.PML(name="pml_xhigh") # y boundaries grid[:, 0:10, :] = fdtd.PML(name="pml_ylow") grid[:, -10:, :] = fdtd.PML(name="pml_yhigh") # Saving grid geometry if saveStuff: with open(path.join("./fdtd_output", grid.folder, "grid.txt"), "w") as f: f.write(str(grid)) wavelength = 3e8/grid.source.frequency wavelengthUnits = wavelength/grid.grid_spacing GD = array([grid.x, grid.y, grid.z]) gridRange = [arange(x/grid.grid_spacing) for x in GD] objectRange = array([[gridRange[0][x.x], gridRange[1][x.y], gridRange[2][x.z]] for x in grid.objects]).T f.write("\n\nGrid details (in wavelength scale):") f.write("\n\tGrid dimensions: ") f.write(str(GD/wavelength)) f.write("\n\tSource dimensions: ") f.write(str(array([grid.source.x[-1] - grid.source.x[0] + 1, grid.source.y[-1] - grid.source.y[0] + 1, grid.source.z[-1] - grid.source.z[0] + 1])/wavelengthUnits)) f.write("\n\tObject dimensions: ") f.write(str([(max(map(max, x)) - min(map(min, x)) + 1)/wavelengthUnits for x in objectRange])) if animate: if run_time > 0: for i in range(run_time): grid.run(total_time=1) if saveStuff: grid.visualize(z=0, animate=True, index=i, save=True, folder=grid.folder) else: grid.visualize(z=0, animate=True) if saveStuff: grid.generate_video(delete_frames=True) grid.save_data() else: if run_time > 0: grid.run(total_time=run_time) if saveStuff: grid.visualize(z=0, show=True, index=0, save=True, folder=grid.folder) grid.save_data() else: grid.visualize(z=0, show=True) if results: phase_profile_incident = [] phase_profile_emergent = [[] for j in range(transmit_detectors)] # number of trasmit side detectors det_vals_incident = array(grid.detectors[0].detector_values()['E'][-grid.sources[0].period:]) det_vals_emergent = [array(grid.detectors[i].detector_values()['E'][-grid.sources[0].period:]) for i in range(1, len(phase_profile_emergent)+1)] for i in range(len(grid.detectors[0].x)): period_phase = grid.sources[0].period - where(det_vals_incident[:, i, 2] == max(det_vals_incident[:, i, 2]))[-1][-1] phase_profile_incident.append(((grid.sources[0].period/4 + period_phase)/grid.sources[0].period)%1) for j in range(len(phase_profile_emergent)): period_phase = grid.sources[0].period - where(det_vals_emergent[j][:, i, 2] == max(det_vals_emergent[j][:, i, 2]))[-1][-1] phase_profile_emergent[j].append(((grid.sources[0].period/4 + period_phase)/grid.sources[0].period)%1) xdata = array([x for x in range(-25, 25)]) #phase_difference = (-array(phase_profile_emergent) + array(phase_profile_incident) + 2*pi)%(2*pi) #popt, _ = curve_fit(fit_func, xdata, phase_difference) figure(num="phase_profile") plot(xdata/grid.sources[0].period, phase_profile_incident, label="Incident phase") for j in range(len(phase_profile_emergent)): plot(xdata/grid.sources[0].period, phase_profile_emergent[j], label="Emergent phase"+str(j)) #plot(xdata/grid.sources[0].period, phase_difference, label="Phase difference") #plot(xdata/grid.sources[0].period, fit_func(xdata, *popt), label="Curve-fit for Phase difference") for j in range(len(phase_profile_emergent)): popt, _ = curve_fit(fit_func, xdata, phase_profile_emergent[j]) plot(xdata/grid.sources[0].period, fit_func(xdata, *popt), label="Curve-fit for Phase in detector"+str(j)) #print(popt) xlabel("x/lambda") ylabel("phase/2pi") legend() #title("Curve-fit Phase difference: %5.6f*x**2 + %5.6f*x + %5.6f" % tuple(popt)) show() figure(num="phase_profile_curve_fit") for j in range(len(phase_profile_emergent)): if j%4 == 0: subplot(2, 4, j/4+1) title("Detectors %1i to %2i" % tuple([j, j+3])) xlabel("x/lambda") ylabel("phase/2pi") ylim(0, 1) popt, _ = curve_fit(fit_func, xdata, phase_profile_emergent[j]) plot(xdata/grid.sources[0].period, fit_func(xdata, *popt), label="Curve-fit for Phase in detector"+str(j)) print(popt) #legend() suptitle("Curve-fiting (Consecutive order of detectors in each plot, blue: 1, orange: 2, green: 3, red: 4)") show() figure(num="phase_bent") plot([x for x in range(30, 30+5*len(phase_profile_emergent), 5)], [detector[len(detector)//2] - detector[0] for detector in phase_profile_emergent], label="Phase profile 'bent'") plot([x for x in range(30, 30+5*len(phase_profile_emergent), 5)], [0 for x in range(len(phase_profile_emergent))], label="Zero line") xlabel("detector position") title("Measure of 'bent' of different phase profiles as difference of phases at mid and at end of each detector") legend() show() end_time = time() print("Runtime:", end_time-start_time)
StarcoderdataPython
11203870
import tensorflow as tf import numpy as np import datetime as time # class for the core of the architecture class GNN: def __init__(self, net, input_dim, output_dim, state_dim, max_it=50, optimizer=tf.train.AdamOptimizer, learning_rate=0.01, threshold=0.01, graph_based=False, param=str(time.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')), config=None, tensorboard=False, mask_flag=False): """ create GNN instance. Feed this parameters: :net: Net instance - it contains state network, output network, initialized weights, loss function and metric; :input_dim: dimension of the input :output_dim: dimension of the output :state_dim: dimension for the state :max_it: maximum number of iteration of the state convergence procedure :optimizer: optimizer instance :learning_rate: learning rate value :threshold: value to establish the state convergence :graph_based: flag to denote a graph based problem :param: name of the experiment :config: ConfigProto protocol buffer object, to set configuration options for a session :tensorboard: boolean flag to activate tensorboard """ np.random.seed(0) tf.set_random_seed(0) self.tensorboard = tensorboard self.max_iter = max_it self.net = net self.optimizer = optimizer(learning_rate, name="optim") self.state_threshold = threshold self.input_dim = input_dim self.output_dim = output_dim self.state_dim = state_dim self.graph_based = graph_based self.mask_flag = mask_flag self.build() self.session = tf.Session(config=config) #self.session = tf.Session() self.session.run(tf.global_variables_initializer()) self.init_l = tf.local_variables_initializer() # parameter to monitor the learning via tensorboard and to save the model if self.tensorboard: self.merged_all = tf.summary.merge_all(key='always') self.merged_train = tf.summary.merge_all(key='train') self.merged_val = tf.summary.merge_all(key='val') self.writer = tf.summary.FileWriter('tmp/' + param, self.session.graph) # self.saver = tf.train.Saver() # self.save_path = "tmp/" + param + "saves/model.ckpt" def VariableState(self): '''Define placeholders for input, output, state, state_old, arch-node conversion matrix''' # placeholder for input and output self.comp_inp = tf.placeholder(tf.float32, shape=(None, self.input_dim), name="input") self.y = tf.placeholder(tf.float32, shape=(None, self.output_dim), name="target") if self.mask_flag: self.mask = tf.placeholder(tf.float32, name="mask") # state(t) & state(t-1) self.state = tf.placeholder(tf.float32, shape=(None, self.state_dim), name="state") self.state_old = tf.placeholder(tf.float32, shape=(None, self.state_dim), name="old_state") # arch-node conversion matrix self.ArcNode = tf.sparse_placeholder(tf.float32, name="ArcNode") # node-graph conversion matrix if self.graph_based: self.NodeGraph = tf.sparse_placeholder(tf.float32, name="NodeGraph") else: self.NodeGraph = tf.placeholder(tf.float32, name="NodeGraph") def build(self): '''build the architecture, setting variable, loss, training''' # network self.VariableState() self.loss_op = self.Loop() # loss with tf.variable_scope('loss'): if self.mask_flag: self.loss = self.net.Loss(self.loss_op[0], self.y, mask=self.mask) self.val_loss = self.net.Loss(self.loss_op[0], self.y, mask=self.mask) else: self.loss = self.net.Loss(self.loss_op[0], self.y) # val loss self.val_loss = self.net.Loss(self.loss_op[0], self.y) if self.tensorboard: self.summ_loss = tf.summary.scalar('loss', self.loss, collections=['train']) self.summ_val_loss = tf.summary.scalar('val_loss', self.val_loss, collections=['val']) # optimizer with tf.variable_scope('train'): self.grads = self.optimizer.compute_gradients(self.loss) self.train_op = self.optimizer.apply_gradients(self.grads, name='train_op') if self.tensorboard: for index, grad in enumerate(self.grads): tf.summary.histogram("{}-grad".format(self.grads[index][1].name), self.grads[index], collections=['always']) # metrics with tf.variable_scope('metrics'): if self.mask_flag: self.metrics = self.net.Metric(self.y, self.loss_op[0], mask=self.mask) else: self.metrics = self.net.Metric(self.y, self.loss_op[0]) # val metric with tf.variable_scope('val_metric'): if self.mask_flag: self.val_met = self.net.Metric(self.y, self.loss_op[0], mask=self.mask) else: self.val_met = self.net.Metric(self.y, self.loss_op[0]) if self.tensorboard: self.summ_val_met = tf.summary.scalar('val_metric', self.val_met, collections=['always']) def convergence(self, a, state, old_state, k): with tf.variable_scope('Convergence'): # body of the while cicle used to iteratively calculate state # assign current state to old state old_state = state # grub states of neighboring node gat = tf.gather(old_state, tf.cast(a[:, 1], tf.int32)) # slice to consider only label of the node and that of it's neighbor # sl = tf.slice(a, [0, 1], [tf.shape(a)[0], tf.shape(a)[1] - 1]) # equivalent code sl = a[:, 2:] # concat with retrieved state inp = tf.concat([sl, gat], axis=1) # evaluate next state and multiply by the arch-node conversion matrix to obtain per-node states layer1 = self.net.netSt(inp) state = tf.sparse_tensor_dense_matmul(self.ArcNode, layer1) # update the iteration counter k = k + 1 return a, state, old_state, k def condition(self, a, state, old_state, k): # evaluate condition on the convergence of the state with tf.variable_scope('condition'): # evaluate distance by state(t) and state(t-1) outDistance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(state, old_state)), 1) + 0.00000000001) # vector showing item converged or not (given a certain threshold) checkDistanceVec = tf.greater(outDistance, self.state_threshold) c1 = tf.reduce_any(checkDistanceVec) c2 = tf.less(k, self.max_iter) return tf.logical_and(c1, c2) def Loop(self): # call to loop for the state computation and compute the output # compute state with tf.variable_scope('Loop'): k = tf.constant(0) res, st, old_st, num = tf.while_loop(self.condition, self.convergence, [self.comp_inp, self.state, self.state_old, k]) if self.tensorboard: self.summ_iter = tf.summary.scalar('iteration', num, collections=['always']) if self.graph_based: # stf = tf.transpose(tf.matmul(tf.transpose(st), self.NodeGraph)) stf = tf.sparse_tensor_dense_matmul(self.NodeGraph, st) else: stf = st out = self.net.netOut(stf) return out, num def Train(self, inputs, ArcNode, target, step, nodegraph=0.0, mask=None): ''' train methods: has to receive the inputs, arch-node matrix conversion, target, and optionally nodegraph indicator ''' # Creating a SparseTEnsor with the feeded ArcNode Matrix arcnode_ = tf.SparseTensorValue(indices=ArcNode.indices, values=ArcNode.values, dense_shape=ArcNode.dense_shape) if self.graph_based: nodegraph = tf.SparseTensorValue(indices=nodegraph.indices, values=nodegraph.values, dense_shape=nodegraph.dense_shape) if self.mask_flag: fd = {self.NodeGraph: nodegraph, self.comp_inp: inputs, self.state: np.zeros((ArcNode.dense_shape[0], self.state_dim)), self.state_old: np.ones((ArcNode.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_, self.y: target, self.mask: mask} else: fd = {self.NodeGraph: nodegraph, self.comp_inp: inputs, self.state: np.zeros((ArcNode.dense_shape[0], self.state_dim)), self.state_old: np.ones((ArcNode.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_, self.y: target} if self.tensorboard: _, loss, loop, merge_all, merge_tr = self.session.run( [self.train_op, self.loss, self.loss_op, self.merged_all, self.merged_train], feed_dict=fd) if step % 100 == 0: self.writer.add_summary(merge_all, step) self.writer.add_summary(merge_tr, step) else: _, loss, loop = self.session.run( [self.train_op, self.loss, self.loss_op], feed_dict=fd) return loss, loop[1] def Validate(self, inptVal, arcnodeVal, targetVal, step, nodegraph=0.0, mask=None): """ Takes care of the validation of the model - it outputs, regarding the set given as input, the loss value, the accuracy (custom defined in the Net file), the number of iteration in the convergence procedure """ arcnode_ = tf.SparseTensorValue(indices=arcnodeVal.indices, values=arcnodeVal.values, dense_shape=arcnodeVal.dense_shape) if self.graph_based: nodegraph = tf.SparseTensorValue(indices=nodegraph.indices, values=nodegraph.values, dense_shape=nodegraph.dense_shape) if self.mask_flag: fd_val = {self.NodeGraph: nodegraph, self.comp_inp: inptVal, self.state: np.zeros((arcnodeVal.dense_shape[0], self.state_dim)), self.state_old: np.ones((arcnodeVal.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_, self.y: targetVal, self.mask: mask} else: fd_val = {self.NodeGraph: nodegraph, self.comp_inp: inptVal, self.state: np.zeros((arcnodeVal.dense_shape[0], self.state_dim)), self.state_old: np.ones((arcnodeVal.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_, self.y: targetVal} if self.tensorboard: loss_val, loop, merge_all, merge_val, metr = self.session.run( [self.val_loss, self.loss_op, self.merged_all, self.merged_val, self.metrics], feed_dict=fd_val) self.writer.add_summary(merge_all, step) self.writer.add_summary(merge_val, step) else: loss_val, loop, metr = self.session.run( [self.val_loss, self.loss_op, self.metrics], feed_dict=fd_val) return loss_val, metr, loop[1] def Evaluate(self, inputs, st, st_old, ArcNode, target): '''evaluate method with initialized state -- not used for the moment: has to receive the inputs, initialization for state(t) and state(t-1), arch-node matrix conversion, target -- gives as output the accuracy on the set given as input''' arcnode_ = tf.SparseTensorValue(indices=ArcNode.indices, values=ArcNode.values, dense_shape=ArcNode.dense_shape) fd = {self.comp_inp: inputs, self.state: st, self.state_old: st_old, self.ArcNode: arcnode_, self.y: target} _ = self.session.run([self.init_l]) met = self.session.run([self.metrics], feed_dict=fd) return met def Evaluate(self, inputs, ArcNode, target, nodegraph=0.0): '''evaluate methods: has to receive the inputs, arch-node matrix conversion, target -- gives as output the accuracy on the set given as input''' arcnode_ = tf.SparseTensorValue(indices=ArcNode.indices, values=ArcNode.values, dense_shape=ArcNode.dense_shape) if self.graph_based: nodegraph = tf.SparseTensorValue(indices=nodegraph.indices, values=nodegraph.values, dense_shape=nodegraph.dense_shape) fd = {self.NodeGraph: nodegraph, self.comp_inp: inputs, self.state: np.zeros((ArcNode.dense_shape[0], self.state_dim)), self.state_old: np.ones((ArcNode.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_, self.y: target} _ = self.session.run([self.init_l]) met = self.session.run([self.metrics], feed_dict=fd) return met def Predict(self, inputs, st, st_old, ArcNode): ''' predict methods with initialized state -- not used for the moment:: has to receive the inputs, initialization for state(t) and state(t-1), arch-node matrix conversion -- gives as output the output values of the output function (all the nodes output for all the graphs (if node-based) or a single output for each graph (if graph based) ''' arcnode_ = tf.SparseTensorValue(indices=ArcNode.indices, values=ArcNode.values, dense_shape=ArcNode.dense_shape) fd = {self.comp_inp: inputs, self.state: st, self.state_old: st_old, self.ArcNode: arcnode_} pr = self.session.run([self.loss_op], feed_dict=fd) return pr[0] def Predict(self, inputs, ArcNode, nodegraph=0.0): ''' predict methods: has to receive the inputs, arch-node matrix conversion -- gives as output the output values of the output function (all the nodes output for all the graphs (if node-based) or a single output for each graph (if graph based) ''' arcnode_ = tf.SparseTensorValue(indices=ArcNode.indices, values=ArcNode.values, dense_shape=ArcNode.dense_shape) fd = {self.comp_inp: inputs, self.state: np.zeros((ArcNode.dense_shape[0], self.state_dim)), self.state_old: np.ones((ArcNode.dense_shape[0], self.state_dim)), self.ArcNode: arcnode_} pr = self.session.run([self.loss_op], feed_dict=fd) return pr[0]
StarcoderdataPython
6471431
# coding: utf-8 """ Main window creation code. """ import sys import gi gi.require_version('Adw', '1') gi.require_version('Gtk', '4.0') from gi.repository import Adw, Gtk, Gio, GObject from .views.assistant import AssistantContent # noqa: F401 from .views.skills import SkillsContent # noqa: F401 from .views.preferences import LapelPreferences from .daemon import start_daemon, get_daemon @Gtk.Template(resource_path='/org/dithernet/lapel/ui/window.ui') class LapelWindow(Adw.ApplicationWindow): """Main window for the program.""" __gtype_name__ = 'LapelWindow' content_stack = Gtk.Template.Child() skill_search_button = Gtk.Template.Child() assistant_page = Gtk.Template.Child() no_connection = Gtk.Template.Child() no_connection_status = Gtk.Template.Child() skills_content = Gtk.Template.Child() view_switcher = Gtk.Template.Child() def __init__(self, **kwargs): super().__init__(**kwargs) self.daemon = get_daemon() self.daemon.client.on('error', self.handle_error) self.daemon.client.on('mycroft.ready', self.ready) self.no_connection.hide() self.daemon.refresh_skills() self.content_stack.connect('notify::visible-child', self.show_search_icon) self.skill_search_button.bind_property( 'active', self.skills_content.search_bar, 'search-mode-enabled', flags=GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE ) def show_search_icon(self, *args): """ Shows/hides the search icon based on whether the skill list is shown or not. """ if self.content_stack.get_visible_child_name() == 'skills': vadjust = self.skills_content.skills_list.get_vadjustment() vadjust.set_value(vadjust.get_lower()) self.skill_search_button.set_visible(True) else: self.skills_content.selection.set_selected(0) self.skill_search_button.set_visible(False) self.skill_search_button.set_active(False) def handle_error(self, error): """Handles errors.""" print(error) self.no_connection.show() self.no_connection.set_reveal_child(True) self.assistant_page.get_child().content_flap.set_reveal_flap(False) self.view_switcher.set_sensitive(False) def ready(self, *args): """Recovers after an error.""" self.no_connection.set_receives_default(False) self.no_connection.set_reveal_child(False) self.no_connection.hide() self.view_switcher.set_sensitive(True) self.daemon.refresh_skills() @Gtk.Template(resource_path='/org/dithernet/lapel/ui/about.ui') class AboutDialog(Gtk.AboutDialog): """Main about dialog for Assistant.""" __gtype_name__ = 'AboutDialog' def __init__(self, parent): Gtk.AboutDialog.__init__(self) self.props.version = "0.1.0" self.set_transient_for(parent) class Application(Adw.Application): def __init__(self): super().__init__( application_id='org.dithernet.lapel', flags=Gio.ApplicationFlags.FLAGS_NONE, resource_base_path='/org/dithernet/lapel/' ) start_daemon() def do_activate(self): win = self.props.active_window if not win: win = LapelWindow(application=self) self.create_action('about', self.on_about_action) self.create_action('preferences', self.on_preferences_action) win.present() def on_about_action(self, widget, _): about = AboutDialog(self.props.active_window) about.present() def on_preferences_action(self, widget, _): preferences = LapelPreferences() preferences.present() def create_action(self, name, callback): """Add an action and connect it to a callback.""" action = Gio.SimpleAction.new(name, None) action.connect("activate", callback) self.add_action(action) def main(version): app = Application() return app.run(sys.argv)
StarcoderdataPython
11349669
<reponame>djfurman/aws_alb_serverless_status<filename>alb_response/responder.py import json as py_json from http import HTTPStatus def alb_response( http_status, data=None, json=None, headers=None, is_base64_encoded=False ): response_headers = {} status_code = HTTPStatus(http_status) status_description = build_status_description(int(status_code)) if json: response_headers["content-type"] = "application/json" if headers is not None: response_headers.update(headers) if isinstance(json, str): payload = json else: payload = py_json.dumps(json) else: payload = data if headers is None: response_headers["content-type"] = "text/plain" else: response_headers.update(headers) response = { "isBase64Encoded": is_base64_encoded, "statusCode": int(http_status), "statusDescription": status_description, "headers": response_headers } if payload: response["body"] = payload return response def build_status_description(status_code): """Creates the strange format of status description required by the AWS ALB feature for serverless applications Arguments: status_code {int} -- http status code Returns: str -- AWS ALB compliant status description """ status = HTTPStatus(status_code) return f"{int(status)} {str(status).split('.')[1].replace('_', ' ')}"
StarcoderdataPython
6664487
<filename>monorun/core/__init__.py from .bbox_3d import * from .evaluation import * from .visualizer import *
StarcoderdataPython
3509259
# -*- coding: utf-8 -*- """ GUI from tkinter 逻辑层 """ # 设置GUI root = Tk() w = Label(root, text = "Guess Number Game") w.pack() # 欢迎消息 mb.showinfo("Welcome", "Welcome to Guess Number Game") # 处理信息 number = 59 while True: # 让用户输入信息: guess = dl.askinteger("Number", "What's your guess?") if guess == number: output = 'Bingo! you guessed it right, but you do not win any prizes!' mb.showinfo("Hint: ", output) break elif guess < number: output = 'No, the number is a higer than that' mb.showinfo("Hint: ", output) else: output = 'No, the number is a lower than that' mb.showinfo("Hint: ", output) print('Done')
StarcoderdataPython
1711976
"""Loads All Image Resources""" import os import glob from PySide6 import QtGui # pylint: disable=no-name-in-module # GitHub Actions cant import Qt modules class ImageManager: """Loads Image Files Attributes: images (Dict{str: QtGui.QPixmap}): Dictionary of QPixmap objects """ def __init__(self): self.images = {} def load_images(self): """Recusively loads all Images in resources/""" resource_folder = os.path.dirname(os.path.abspath(__file__)) for item in glob.glob(os.path.join(resource_folder, '**', '*'), recursive=True): filename, ext = os.path.splitext(os.path.basename(item)) if ext in ['.png', '.jpg']: self.images[filename] = QtGui.QPixmap(item) def get_image(self, name): """Get Image Object for selected filename""" return self.images.get(name, QtGui.QPixmap())
StarcoderdataPython
3576155
<filename>run.py import cv2 def mail(): import time import smtplib from email.message import EmailMessage Address = "27-17-43/1, Sector 12, <NAME>" msg = EmailMessage() msg["Subject"] = "Fire Outbreak Detected" msg["From"] = "<EMAIL>" msg["To"] = "<EMAIL>" msg.set_content(f"I'm FireDetectionSys,\nData:\nAddress - {Address}\nTime - {time.ctime()}") with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: smtp.login("<EMAIL>", "<PASSWORD>") smtp.send_message(msg) smtp.close() def alarm(): from playsound import playsound print("Fire Detected") playsound("Alert.mp3") def shutdown(): import time import sys print("System Shutting Down in ETA: 3s") time.sleep(1) print("1...") time.sleep(1) print("2...") time.sleep(1) print("3...") time.sleep(1) print("Shutting Down...") sys.exit() if __name__ == '__main__': firedetector = cv2.CascadeClassifier('FDSys.xml') capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) capture.set(3,640) capture.set(4,480) while (True): ret, frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) fire = firedetector.detectMultiScale(frame, 1.2, 5) for (x,y,w,h) in fire: cv2.destroyAllWindows() alarm() mail() shutdown() cv2.imshow('window', frame) if cv2.waitKey(1) == ord('q'): break
StarcoderdataPython
5094589
<gh_stars>0 import calendar from datetime import datetime, timedelta WEEKDAY_NAME_LIST = list(calendar.day_name) def add_time(start_time, duration, start_day_name=None): # Parsing "start_time" parameter's hours and miniutes values and, # creating datetime obj with those data. parsed_start_datetime = datetime.strptime(start_time, "%I:%M %p") current_datetime = datetime.now() start_datetime = current_datetime.replace( hour=parsed_start_datetime.hour, minute=parsed_start_datetime.minute, second=0, microsecond=0, ) # Manually parsing "duration" param's hours and miniutes values and, # creating timedelta obj with those data. duration_hours, duration_minutes = duration.split(":") duration_delta = timedelta( hours=int(duration_hours), minutes=int(duration_minutes), ) # New datetime object witch point to future date. (According to provided duration.) future_datetime = start_datetime + duration_delta # Calculating how many days to future date. duration_diff_as_days = duration_delta.days if duration_delta.days > 0 and duration_delta.seconds > 0: # When there is some days + hours available. duration_diff_as_days = duration_delta.days + 1 # Custom string, that show in how many days, future day occur. custom_duration_representation = "" if duration_diff_as_days == 0 and start_datetime.day != future_datetime.day: # When there is no 24 Hour difference, But hour difference pass above 12:00 PM which makes it next day. custom_duration_representation = " (next day)" elif duration_diff_as_days == 1: custom_duration_representation = " (next day)" elif duration_diff_as_days > 1: custom_duration_representation = ( f" ({duration_diff_as_days} days later)" ) # When custom start date is proviced (If not default is considered today), # in here we calculate in which week day name, future day will be. if start_day_name is not None: start_day_index = WEEKDAY_NAME_LIST.index(start_day_name.title()) future_day_index = (start_day_index + duration_diff_as_days) % 7 custom_duration_representation = ( ", " + WEEKDAY_NAME_LIST[future_day_index] + custom_duration_representation ) # Formatting future date in certain format. return future_datetime.strftime( f"%-I:%M %p{custom_duration_representation}" )
StarcoderdataPython
1672975
<reponame>ersilia-os/ersilia-automl-chem from setuptools import setup, find_packages with open("README.md", "r", encoding="utf8") as fh: long_description = fh.read() with open("requirements.txt") as f: install_requires = f.read().splitlines() install_requires += [ "melloddy_tuner @ git+git://github.com/melloddy/MELLODDY-TUNER#egg=melloddy_tuner" ] setup( name="zairachem", version="0.0.1", author="<NAME>", author_email="<EMAIL>", url="https://github.com/ersilia-os/zaira-chem", description="Automated QSAR modeling for chemistry", long_description=long_description, long_description_content_type="text/markdown", license="MIT", python_requires=">=3.7", install_requires=install_requires, packages=find_packages(exclude=("utilities")), entry_points={"console_scripts": ["zairachem=zairachem.cli:cli"]}, classifiers=[ "Programming Language :: Python :: 3.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], keywords="qsar machine-learning chemistry computer-aided-drug-design", project_urls={"Source Code": "https://github.com/ersilia-os/zaira-chem"}, include_package_data=True, )
StarcoderdataPython
11360977
<filename>marsyas-vamp/marsyas/src/qt5apps/MarGrid2/test-send-osc-to-margrid.py #!/usr/bin/python import osc def myTest(): """ a simple function that creates the necesary sockets and enters an endless loop sending and receiving OSC """ osc.init() import time i = 0 while 1: i = i % 4 print i osc.sendMsg("/x0", [i], "127.0.0.1", 9005) osc.sendMsg("/y0", [i+1], "127.0.0.1", 9005) osc.sendMsg("/x1", [i+2], "127.0.0.1", 9005) osc.sendMsg("/y1", [i+3], "127.0.0.1", 9005) osc.sendMsg("/update", [1], "127.0.0.1", 9005) bundle = osc.createBundle() time.sleep(1) i += 1 osc.dontListen() if __name__ == '__main__': myTest()
StarcoderdataPython
3361069
<reponame>BillyDoo/scrumboard<gh_stars>0 # Generated by Django 2.2 on 2019-04-17 13:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('scrumboard', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='card', name='story_points', ), ]
StarcoderdataPython
11336555
""" Copyright 2022 RPANBot Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from nextcord import Colour, Embed, Message from typing import Union from utils.settings import Settings class RPANEmbed(Embed): def __init__( self, title: str, description: str = "", url: str = "", colour: Union[int, Colour] = 0x00688B, fields: dict = None, thumbnail: str = None, user=None, footer_text: str = None, bot=None, message: Message = None, ) -> None: """ Generates a standard bot embed. :param title: The embed's title. :param description: The embed's description. :param url: The URL permalink used in the title. :param colour: The colour of the embed. :param fields: The embed's fields (given as a dict). :param thumbnail: The thumbnail that the embed should use. :param user: The user who has requested a command (if any). :param footer_text: Text that should be used in the embed's footer. :param bot: The bot instance. This is used to get the custom prefix. :param message: The message. This is used to get the custom prefix. :return: An embed generated to the specifications. """ if fields is None: fields = {} if not isinstance(colour, Colour): colour = Colour(colour) super().__init__( title=title, description=description, url=url, colour=colour, ) for key, value in fields.items(): self.add_field(name=key, value=value) if thumbnail: self.set_thumbnail(url=thumbnail) if user: requested_by_text = f"Requested by {user}" if footer_text: footer_text = requested_by_text + " ● " + footer_text else: footer_text = requested_by_text if footer_text: if message: self.set_footer(text=f"{footer_text} ● {Settings().links.site}") else: self.set_footer(text=footer_text) else: if message: self.set_footer(text=f"{Settings().links.site}")
StarcoderdataPython
6647695
<reponame>mithro/chromium-infra # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is govered by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """View objects to help display users and groups in UI templates.""" import logging class GroupView(object): """Class to make it easier to display user group metadata.""" def __init__(self, name, num_members, group_settings, group_id): self.name = name self.num_members = num_members self.who_can_view_members = str(group_settings.who_can_view_members) self.group_id = group_id self.detail_url = '/g/%s/' % group_id
StarcoderdataPython
6690865
class ShaderNodeLightFalloff: pass
StarcoderdataPython
3294173
<filename>triplinker/chat/views/all_views.py # This module is needed to pass all functions(views) to the app's urls module. # !Triplinker modules: # Current app modules. from chat.views.dialog_views.views import * from chat.views.group_chat_views.views import *
StarcoderdataPython
9647310
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from ...flash.flash import Flash from ...coresight.coresight_target import CoreSightTarget from ...core.memory_map import (FlashRegion, RamRegion, MemoryMap) from ...debug.svd.loader import SVDFile import logging FLASH_ALGO = { 'load_address' : 0x10000000, 'instructions' : [ 0xE00ABE00, 0x062D780D, 0x24084068, 0xD3000040, 0x1E644058, 0x1C49D1FA, 0x2A001E52, 0x4770D1F2, 0x47700b00, 0x2200483b, 0x21016302, 0x63426341, 0x63816341, 0x20024937, 0x70083940, 0x47704610, 0x47702000, 0xb08bb5f0, 0x25002032, 0x466a260f, 0xa905c261, 0x460f4c30, 0x47a04668, 0x28009805, 0x2034d10a, 0xc1614669, 0x9003482c, 0x46684639, 0x980547a0, 0xd0002800, 0xb00b2001, 0xb570bdf0, 0x0b04b08a, 0xa9052032, 0x4d239000, 0x460e9401, 0x46689402, 0x980547a8, 0xd10b2800, 0x90002034, 0x9003481e, 0x94029401, 0x46684631, 0x980547a8, 0xd0002800, 0xb00a2001, 0xb5f0bd70, 0x0b004604, 0x460eb08b, 0x91002132, 0x90029001, 0x4f12a905, 0x46684615, 0x47b8910a, 0x28009805, 0x2033d117, 0x02360a36, 0xc1714669, 0x9004480c, 0x990a4668, 0x980547b8, 0xd10a2800, 0x46692038, 0x4807c171, 0x46689004, 0x47b8990a, 0x28009805, 0x2001d0b5, 0x0000e7b3, 0x40048040, 0x1fff1ff1, 0x00002ee0, 0x00000000, ], 'pc_init' : 0x10000025, 'pc_eraseAll' : 0x10000045, 'pc_erase_sector' : 0x1000007F, 'pc_program_page' : 0x100000BB, 'static_base' : 0x10000120, 'begin_data' : 0x10000400, # Analyzer uses a max of 1 KB data (256 pages * 4 bytes / page) # disable double buffering, no enought RAM 'begin_stack' : 0x10001800, 'min_program_length' : 256, 'analyzer_supported' : True, 'analyzer_address' : 0x10001800 # Analyzer 0x10001800..0x10001E00 }; class LPC11U35(CoreSightTarget): VENDOR = "NXP" MEMORY_MAP = MemoryMap( FlashRegion( start=0x00000000, length=0x00010000, blocksize=0x1000, is_boot_memory=True, algo=FLASH_ALGO), RamRegion(name='sram1', start=0x10000000, length=0x2000), RamRegion(name='sram2', start=0x20000000, length=0x0800) ) def __init__(self, link): super(LPC11U35, self).__init__(link, self.MEMORY_MAP) self._svd_location = SVDFile.from_builtin("LPC11Uxx_v7.svd") def reset_stop_on_reset(self, software_reset=None, map_to_user=True): super(LPC11U35, self).reset_stop_on_reset(software_reset) # Remap to use flash and set SP and SP accordingly if map_to_user: self.write_memory(0x40048000, 0x2, 32) sp = self.read_memory(0x0) pc = self.read_memory(0x4) self.write_core_register('sp', sp) self.write_core_register('pc', pc)
StarcoderdataPython
3565840
from typing import Optional, Union, Iterable, Sequence, Callable from torch import Tensor from torch.nn import ModuleList from ..neko_module import NekoModule from ..layer import Linear from ..util import generate_inf_seq, ModuleFactory, compose class MLP(NekoModule): """ The MLP module is a sequential module with multiple linear layers. The activation, normalization and dropout are only applied to hidden layers. Args: neurons (``Sequence[int]``): The list of neurons for the MLP. bias (``bool | Iterable[bool]``, optional): The bias option of Linear layers. Default ``True``. build_activation (``() -> Module | Iterable[() -> Module]``, optional): The activation builder for linear layers. Specify single module builder will apply to all linear layers except the final one. Default ``None``. build_normalization (``() -> Module | Iterable[() -> Module]``, optional): The normalization builder for linear layers. Specify single module builder will apply to all linear layers except the final one. Default ``None``. normalization_after_activation (``bool``, optional): Set True then applying normalization after activation. Default ``False``. dropout_rate (``float``, optional): The dropout rate for this linear layer. 0 means no dropout applied. Default ``0``. Attributes: layers (:class:`~torch.nn.ModuleList`): The module list of :class:`~tensorneko.layer.Linear` layers. Examples: Create a MLP module with 4 layers, with neurons 768 -> 1024 -> 512 -> 10. Contains ReLU, BatchNorm and 0.5 Dropout. .. code-block:: python mlp = tensorneko.module.MLP( neurons=[784, 1024, 512, 10], build_activation=torch.nn.ReLU, build_normalization=[ lambda: torch.nn.BatchNorm1d(1024), lambda: torch.nn.BatchNorm1d(512) ], dropout_rate=0.5 ) """ def __init__(self, neurons: Sequence[int], bias: Union[bool, Iterable[bool]] = True, build_activation: Optional[Union[ModuleFactory, Iterable[ModuleFactory]]] = None, build_normalization: Optional[Union[ModuleFactory, Iterable[ModuleFactory]]] = None, normalization_after_activation: bool = False, dropout_rate: float = 0. ): super().__init__() n_features = neurons[1:] if type(bias) is bool: bias = generate_inf_seq([bias]) if isinstance(build_activation, Callable) or build_activation is None: build_activation = generate_inf_seq([build_activation]) if isinstance(build_normalization, Callable) or build_normalization is None: build_normalization = generate_inf_seq([build_normalization]) self.layers: ModuleList[Linear] = ModuleList( [Linear(neurons[i], neurons[i + 1], bias[i], build_activation[i], build_normalization[i], normalization_after_activation, dropout_rate ) for i in range(len(n_features) - 1) ] + [ Linear(neurons[-2], neurons[-1], bias[len(neurons) - 2]) ] ) def forward(self, x: Tensor) -> Tensor: f = compose(self.layers) return f(x)
StarcoderdataPython
6440283
<gh_stars>0 import sys import time import os import subprocess import string import random import jk_utils import jk_mounting from .AbstractBackupConnector import AbstractBackupConnector from .ThaniyaIO import ThaniyaIO from .ThaniyaBackupContext import ThaniyaBackupContext from .utils.temp import writeTempFile class BackupConnector_CIFSMount(AbstractBackupConnector): SMB_CLIENT_PATH = "/usr/bin/smbclient" MOUNT_PATH = "/bin/mount" SUDO_PATH = "/usr/bin/sudo" UMOUNT_PATH = "/bin/umount" def __init__(self): self.__targetDirPath = None self.__bIsMounted = False # def initialize(self, ctx:ThaniyaBackupContext, targetDirPath:str, nExpectedNumberOfBytesToWrite:int, parameters:dict): self.__targetDirPath = targetDirPath self._cifs_hostAddress = parameters.get("cifs_hostAddress") self._cifs_login = parameters.get("cifs_login") self._cifs_password = parameters.get("cifs_password") #self._cifs_port = parameters.get("cifs_port", 445) self._cifs_version = parameters.get("cifs_version") self._cifs_shareName = parameters.get("cifs_shareName") self._mountCIFS( self.__targetDirPath, self._cifs_hostAddress, #self._cifs_port, self._cifs_shareName, self._cifs_login, self._cifs_password, self._cifs_version) self.__bIsMounted = True # def deinitialize(self, ctx:ThaniyaBackupContext, bError:bool, statsContainer:dict): if self.__bIsMounted: # let's do 5 unmount attempts. for i in range(0, 4): time.sleep(1) try: self._umount(self.__targetDirPath) return except Exception as ee: pass time.sleep(1) self._umount(self.__targetDirPath) # @property def isReady(self) -> bool: return self.__bIsMounted # @property def targetDirPath(self) -> str: return self.__targetDirPath # def dump(self): print("BackupConnector_CIFSMount") #for key in [ "_sessionID", # "mountPoint" ]: # print("\t" + key, "=", getattr(self, key)) # def _mountCIFS(self, localDirPath:str, cifsHostAddress:str, #cifsPort:int, cifsShareName:str, cifsLogin:str, cifsPassword:str, cifsVersion:str) -> bool: assert isinstance(localDirPath, str) assert os.path.isdir(localDirPath) localDirPath = os.path.abspath(localDirPath) mounter = jk_mounting.Mounter() mip = mounter.getMountInfoByMountPoint(localDirPath) if mip is not None: raise Exception("Directory " + repr(localDirPath) + " already used by mount!") credentialFilePath = writeTempFile("rw-------", "username=" + cifsLogin + "\npassword=" + cifsPassword + "\n" ) try: options = [ "user=", cifsLogin, ",credentials=", credentialFilePath, ",rw", ] if cifsVersion: options.append(",vers=") options.append(cifsVersion) cmd = [ BackupConnector_CIFSMount.MOUNT_PATH, "-t", "cifs", "-o", "".join(options), "//" + cifsHostAddress + "/" + cifsShareName, localDirPath, ] # print(" ".join(cmd)) p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) p.stdin.write((cifsPassword + "\n").encode("utf-8")) (stdout, stderr) = p.communicate(timeout=3) if p.returncode != 0: returnCode1 = p.returncode stdOutData1 = stdout.decode("utf-8") stdErrData1 = stderr.decode("utf-8") print("Mount attempt 1:") print("\tcmd =", cmd) print("\treturnCode =", returnCode1) print("\tstdOutData =", repr(stdOutData1)) print("\tstdErrData =", repr(stdErrData1)) raise Exception("Failed to mount device!") return False else: return True finally: try: os.unlink(credentialFilePath) except: pass # def _umount(self, localDirPath:str, throwExceptionOnError:bool = True) -> bool: assert isinstance(localDirPath, str) assert isinstance(throwExceptionOnError, bool) cmd = [ BackupConnector_CIFSMount.UMOUNT_PATH, localDirPath, ] p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate(timeout=10) if p.returncode != 0: returnCode = p.returncode stdOutData = stdout.decode("utf-8") stdErrData = stderr.decode("utf-8") print("Unmount attempt:") print("\treturnCode =", returnCode) print("\tstdOutData =", repr(stdOutData)) print("\tstdErrData =", repr(stdErrData)) if throwExceptionOnError: raise Exception("Failed to umount device!") return False else: return True # #
StarcoderdataPython
12853024
import common.assertions as assertions def run(cfg): assertions.validateAdminPassword(cfg)
StarcoderdataPython
9799461
<gh_stars>100-1000 # coding: utf-8 from __future__ import print_function import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]="1" from six.moves import xrange import os import tensorflow as tf import numpy as np import tensorflow.contrib.layers as ly from tensorflow.examples.tutorials.mnist import input_data from functools import partial from lib.deform_conv_op import deform_conv_op def lrelu(x, leak=0.3, name="lrelu"): with tf.variable_scope(name): f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * abs(x) def deform_conv_2d(img, num_outputs, kernel_size=3, stride=2, normalizer_fn=ly.batch_norm, activation_fn=lrelu, name=''): img_shape = img.shape.as_list() assert(len(img_shape) == 4) N, C, H, W = img_shape with tf.variable_scope('deform_conv' + '_' + name): offset = ly.conv2d(img, num_outputs=2 * kernel_size**2, kernel_size=3, stride=2, activation_fn=None, data_format='NCHW') kernel = tf.get_variable(name='d_kernel', shape=(num_outputs, C, kernel_size, kernel_size), initializer=tf.random_normal_initializer(0, 0.02)) res = deform_conv_op(img, filter=kernel, offset=offset, rates=[1, 1, 1, 1], padding='SAME', strides=[1, 1, stride, stride], num_groups=1, deformable_group=1) if normalizer_fn is not None: res = normalizer_fn(res) if activation_fn is not None: res = activation_fn(res) return res batch_size = 64 z_dim = 128 learning_rate_ger = 5e-5 learning_rate_dis = 5e-5 device = '/gpu:0' # update Citers times of critic in one iter(unless i < 25 or i % 500 == 0, # i is iterstep) Citers = 5 # the upper bound and lower bound of parameters in critic clamp_lower = -0.01 clamp_upper = 0.01 # whether to use adam for parameter update, if the flag is set False, use tf.train.RMSPropOptimizer # as recommended in paper is_adam = False # whether to use SVHN or MNIST, set false and MNIST is used dataset_type = "mnist" # img size s = 32 channel = 1 # 'gp' for gp WGAN and 'regular' for vanilla mode = 'regular' # if 'gp' is chosen the corresponding lambda must be filled lam = 10. s2, s4, s8, s16 = int(s / 2), int(s / 4), int(s / 8), int(s / 16) # hidden layer size if mlp is chosen, ignore if otherwise ngf = 64 ndf = 64 # directory to store log, including loss and grad_norm of generator and critic log_dir = './log_wgan' ckpt_dir = './ckpt_wgan' if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) # max iter step, note the one step indicates that a Citers updates of # critic and one update of generator max_iter_step = 20000 # In[5]: def generator_conv(z): train = ly.fully_connected( z, 4 * 4 * 512, activation_fn=lrelu, normalizer_fn=ly.batch_norm) train = tf.reshape(train, (-1, 4, 4, 512)) train = ly.conv2d_transpose(train, 256, 3, stride=2, activation_fn=tf.nn.relu, normalizer_fn=ly.batch_norm, padding='SAME', weights_initializer=tf.random_normal_initializer(0, 0.02)) train = ly.conv2d_transpose(train, 128, 3, stride=2, activation_fn=tf.nn.relu, normalizer_fn=ly.batch_norm, padding='SAME', weights_initializer=tf.random_normal_initializer(0, 0.02)) train = ly.conv2d_transpose(train, 64, 3, stride=2, activation_fn=tf.nn.relu, normalizer_fn=ly.batch_norm, padding='SAME', weights_initializer=tf.random_normal_initializer(0, 0.02)) train = ly.conv2d_transpose(train, 1, 3, stride=1, activation_fn=tf.nn.tanh, padding='SAME', weights_initializer=tf.random_normal_initializer(0, 0.02)) print(train.name) return train # In[7]: def critic_conv(img, reuse=False): with tf.variable_scope('critic') as scope: if reuse: scope.reuse_variables() size = 64 img = tf.transpose(img, [0, 3, 1, 2]) img = deform_conv_2d(img, num_outputs=size, kernel_size=3, stride=2, activation_fn=lrelu, name='conv3') img = deform_conv_2d(img, num_outputs=size * 2, kernel_size=3, stride=2, activation_fn=lrelu, normalizer_fn=ly.batch_norm, name='conv4') img = ly.conv2d(img, num_outputs=size * 4, kernel_size=3, stride=2, activation_fn=lrelu, normalizer_fn=ly.batch_norm, data_format="NCHW") img = ly.conv2d(img, num_outputs=size * 8, kernel_size=3, stride=2, activation_fn=lrelu, normalizer_fn=ly.batch_norm, data_format="NCHW") logit = ly.fully_connected(tf.reshape( img, [batch_size, -1]), 1, activation_fn=None) return logit # In[9]: def build_graph(): # z = tf.placeholder(tf.float32, shape=(batch_size, z_dim)) noise_dist = tf.contrib.distributions.Normal(0., 1.) z = noise_dist.sample((batch_size, z_dim)) generator = generator_mlp if is_mlp else generator_conv critic = critic_mlp if is_mlp else critic_conv with tf.variable_scope('generator'): train = generator(z) real_data = tf.placeholder( dtype=tf.float32, shape=(batch_size, s, s, channel)) print(real_data.shape) print(train.shape) true_logit = critic(real_data) fake_logit = critic(train, reuse=True) c_loss = tf.reduce_mean(fake_logit - true_logit) if mode is 'gp': alpha_dist = tf.contrib.distributions.Uniform(low=0., high=1.) alpha = alpha_dist.sample((batch_size, 1, 1, 1)) interpolated = real_data + alpha * (train - real_data) inte_logit = critic(interpolated, reuse=True) gradients = tf.gradients(inte_logit, [interpolated, ])[0] grad_l2 = tf.sqrt(tf.reduce_sum(tf.square(gradients), axis=[1, 2, 3])) gradient_penalty = tf.reduce_mean((grad_l2 - 1)**2) gp_loss_sum = tf.summary.scalar("gp_loss", gradient_penalty) grad = tf.summary.scalar("grad_norm", tf.nn.l2_loss(gradients)) c_loss += lam * gradient_penalty g_loss = tf.reduce_mean(-fake_logit) g_loss_sum = tf.summary.scalar("g_loss", g_loss) c_loss_sum = tf.summary.scalar("c_loss", c_loss) img_sum = tf.summary.image("img", train, max_outputs=10) theta_g = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator') theta_c = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope='critic') counter_g = tf.Variable(trainable=False, initial_value=0, dtype=tf.int32) opt_g = ly.optimize_loss(loss=g_loss, learning_rate=learning_rate_ger, optimizer=partial( tf.train.AdamOptimizer, beta1=0.5, beta2=0.9) if is_adam is True else tf.train.RMSPropOptimizer, variables=theta_g, global_step=counter_g, summaries=['gradient_norm'], clip_gradients=100.) counter_c = tf.Variable(trainable=False, initial_value=0, dtype=tf.int32) opt_c = ly.optimize_loss(loss=c_loss, learning_rate=learning_rate_dis, optimizer=partial( tf.train.AdamOptimizer, beta1=0.5, beta2=0.9) if is_adam is True else tf.train.RMSPropOptimizer, variables=theta_c, global_step=counter_c, summaries=['gradient_norm'], clip_gradients=100.) if mode is 'regular': clipped_var_c = [tf.assign(var, tf.clip_by_value( var, clamp_lower, clamp_upper)) for var in theta_c] # merge the clip operations on critic variables with tf.control_dependencies([opt_c]): opt_c = tf.tuple(clipped_var_c) if not mode in ['gp', 'regular']: raise(NotImplementedError('Only two modes')) return opt_g, opt_c, real_data # In[ ]: def main(): dataset = input_data.read_data_sets('MNIST_data', one_hot=True) with tf.device(device): opt_g, opt_c, real_data = build_graph() merged_all = tf.summary.merge_all() saver = tf.train.Saver() config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True) config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.8 def next_feed_dict(): train_img = dataset.train.next_batch(batch_size)[0] train_img = 2 * train_img - 1 train_img = np.reshape(train_img, (-1, 28, 28)) npad = ((0, 0), (2, 2), (2, 2)) train_img = np.pad(train_img, pad_width=npad, mode='constant', constant_values=-1) train_img = np.expand_dims(train_img, -1) feed_dict = {real_data: train_img} return feed_dict with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) summary_writer = tf.summary.FileWriter(log_dir, sess.graph) for i in range(max_iter_step): if i < 25 or i % 500 == 0: citers = 100 else: citers = Citers for j in range(citers): feed_dict = next_feed_dict() if i % 100 == 99 and j == 0: run_options = tf.RunOptions( trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() _, merged = sess.run([opt_c, merged_all], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) summary_writer.add_summary(merged, i) summary_writer.add_run_metadata( run_metadata, 'critic_metadata {}'.format(i), i) else: sess.run(opt_c, feed_dict=feed_dict) feed_dict = next_feed_dict() if i % 100 == 99: _, merged = sess.run([opt_g, merged_all], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) summary_writer.add_summary(merged, i) summary_writer.add_run_metadata( run_metadata, 'generator_metadata {}'.format(i), i) else: sess.run(opt_g, feed_dict=feed_dict) if i % 1000 == 999: saver.save(sess, os.path.join( ckpt_dir, "model.ckpt"), global_step=i) main()
StarcoderdataPython
4963667
import boto3 import pytest from tests.helper_functions import set_boto_credentials # pylint: disable=unused-import from tests.sagemaker.mock import mock_sagemaker @pytest.fixture def sagemaker_client(): return boto3.client("sagemaker", region_name="us-west-2") def create_sagemaker_model(sagemaker_client, model_name): return sagemaker_client.create_model( ExecutionRoleArn='arn:aws:iam::012345678910:role/sample-role', ModelName=model_name, PrimaryContainer={ 'Image': '012345678910.dkr.ecr.us-west-2.amazonaws.com/sample-container', } ) def create_endpoint_config(sagemaker_client, endpoint_config_name, model_name): return sagemaker_client.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=[ { 'VariantName': 'sample-variant', 'ModelName': model_name, 'InitialInstanceCount': 1, 'InstanceType': 'ml.m4.xlarge', 'InitialVariantWeight': 1.0, }, ], ) @mock_sagemaker def test_created_model_is_listed_by_list_models_function(sagemaker_client): model_name = "sample-model" create_sagemaker_model( sagemaker_client=sagemaker_client, model_name=model_name) models_response = sagemaker_client.list_models() assert "Models" in models_response models = models_response["Models"] assert all(["ModelName" in model for model in models]) assert model_name in [model["ModelName"] for model in models] @mock_sagemaker def test_create_model_returns_arn_containing_model_name(sagemaker_client): model_name = "sample-model" model_create_response = create_sagemaker_model( sagemaker_client=sagemaker_client, model_name=model_name) assert "ModelArn" in model_create_response assert model_name in model_create_response["ModelArn"] @mock_sagemaker def test_creating_model_with_name_already_in_use_raises_exception(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) with pytest.raises(ValueError): create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) @mock_sagemaker def test_all_models_are_listed_after_creating_many_models(sagemaker_client): model_names = [] for i in range(100): model_name = "sample-model-{idx}".format(idx=i) model_names.append(model_name) create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) listed_models = sagemaker_client.list_models()["Models"] listed_model_names = [model["ModelName"] for model in listed_models] for model_name in model_names: assert model_name in listed_model_names @mock_sagemaker def test_describe_model_response_contains_expected_attributes(sagemaker_client): model_name = "sample-model" execution_role_arn = "arn:aws:iam::012345678910:role/sample-role" primary_container = { "Image": "012345678910.dkr.ecr.us-west-2.amazonaws.com/sample-container", } sagemaker_client.create_model( ModelName=model_name, ExecutionRoleArn=execution_role_arn, PrimaryContainer=primary_container, ) describe_model_response = sagemaker_client.describe_model(ModelName=model_name) assert "CreationTime" in describe_model_response assert "ModelArn" in describe_model_response assert "ExecutionRoleArn" in describe_model_response assert describe_model_response["ExecutionRoleArn"] == execution_role_arn assert "ModelName" in describe_model_response assert describe_model_response["ModelName"] == model_name assert "PrimaryContainer" in describe_model_response assert describe_model_response["PrimaryContainer"] == primary_container @mock_sagemaker def test_describe_model_throws_exception_for_nonexistent_model(sagemaker_client): with pytest.raises(ValueError): sagemaker_client.describe_model(ModelName="nonexistent-model") @mock_sagemaker def test_model_is_no_longer_listed_after_deletion(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) sagemaker_client.delete_model(ModelName=model_name) listed_models = sagemaker_client.list_models()["Models"] listed_model_names = [model["ModelName"] for model in listed_models] assert model_name not in listed_model_names @mock_sagemaker def test_created_endpoint_config_is_listed_by_list_endpoints_function(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_configs_response = sagemaker_client.list_endpoint_configs() assert "EndpointConfigs" in endpoint_configs_response endpoint_configs = endpoint_configs_response["EndpointConfigs"] assert all([ "EndpointConfigName" in endpoint_config for endpoint_config in endpoint_configs]) assert endpoint_config_name in [ endpoint_config["EndpointConfigName"] for endpoint_config in endpoint_configs ] @mock_sagemaker def test_create_endpoint_config_returns_arn_containing_config_name( sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_config_response = create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) assert "EndpointConfigArn" in create_config_response assert endpoint_config_name in create_config_response["EndpointConfigArn"] @mock_sagemaker def test_creating_endpoint_config_with_name_already_in_use_raises_exception(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) with pytest.raises(ValueError): create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) @mock_sagemaker def test_all_endpoint_configs_are_listed_after_creating_many_configs(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_names = [] for i in range(100): endpoint_config_name = "sample-config-{idx}".format(idx=i) endpoint_config_names.append(endpoint_config_name) create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) listed_endpoint_configs = sagemaker_client.list_endpoint_configs()["EndpointConfigs"] listed_endpoint_config_names = [ endpoint_config["EndpointConfigName"] for endpoint_config in listed_endpoint_configs] for endpoint_config_name in endpoint_config_names: assert endpoint_config_name in listed_endpoint_config_names @mock_sagemaker def test_describe_endpoint_config_response_contains_expected_attributes(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" production_variants = [ { 'VariantName': 'sample-variant', 'ModelName': model_name, 'InitialInstanceCount': 1, 'InstanceType': 'ml.m4.xlarge', 'InitialVariantWeight': 1.0, }, ] sagemaker_client.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) describe_endpoint_config_response = sagemaker_client.describe_endpoint_config( EndpointConfigName=endpoint_config_name) assert "CreationTime" in describe_endpoint_config_response assert "EndpointConfigArn" in describe_endpoint_config_response assert "EndpointConfigName" in describe_endpoint_config_response assert describe_endpoint_config_response["EndpointConfigName"] == endpoint_config_name assert "ProductionVariants" in describe_endpoint_config_response assert describe_endpoint_config_response["ProductionVariants"] == production_variants @mock_sagemaker def test_describe_endpoint_config_throws_exception_for_nonexistent_config(sagemaker_client): with pytest.raises(ValueError): sagemaker_client.describe_endpoint_config(EndpointConfigName="nonexistent-config") @mock_sagemaker def test_endpoint_config_is_no_longer_listed_after_deletion(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) sagemaker_client.delete_endpoint_config(EndpointConfigName=endpoint_config_name) listed_endpoint_configs = sagemaker_client.list_endpoint_configs()["EndpointConfigs"] listed_endpoint_config_names = [ endpoint_config["EndpointConfigName"] for endpoint_config in listed_endpoint_configs ] assert endpoint_config_name not in listed_endpoint_config_names @mock_sagemaker def test_created_endpoint_is_listed_by_list_endpoints_function(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, Tags=[ { "Key": "Some Key", "Value": "Some Value", }, ], ) endpoints_response = sagemaker_client.list_endpoints() assert "Endpoints" in endpoints_response endpoints = endpoints_response["Endpoints"] assert all(["EndpointName" in endpoint for endpoint in endpoints]) assert endpoint_name in [endpoint["EndpointName"] for endpoint in endpoints] @mock_sagemaker def test_create_endpoint_returns_arn_containing_endpoint_name( sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" create_endpoint_response = sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, Tags=[ { "Key": "Some Key", "Value": "Some Value", }, ], ) assert "EndpointArn" in create_endpoint_response assert endpoint_name in create_endpoint_response["EndpointArn"] @mock_sagemaker def test_creating_endpoint_with_name_already_in_use_raises_exception(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, Tags=[ { "Key": "Some Key", "Value": "Some Value", }, ], ) with pytest.raises(ValueError): sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, Tags=[ { "Key": "Some Key", "Value": "Some Value", }, ], ) @mock_sagemaker def test_all_endpoint_are_listed_after_creating_many_endpoints(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_names = [] for i in range(100): endpoint_name = "sample-endpoint-{idx}".format(idx=i) endpoint_names.append(endpoint_name) sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, Tags=[ { "Key": "Some Key", "Value": "Some Value", }, ], ) listed_endpoints = sagemaker_client.list_endpoints()["Endpoints"] listed_endpoint_names = [endpoint["EndpointName"] for endpoint in listed_endpoints] for endpoint_name in endpoint_names: assert endpoint_name in listed_endpoint_names @mock_sagemaker def test_describe_endpoint_response_contains_expected_attributes(sagemaker_client): model_name = "sample-model" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" production_variants = [ { 'VariantName': 'sample-variant', 'ModelName': model_name, 'InitialInstanceCount': 1, 'InstanceType': 'ml.m4.xlarge', 'InitialVariantWeight': 1.0, }, ] sagemaker_client.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name, ) describe_endpoint_response = sagemaker_client.describe_endpoint(EndpointName=endpoint_name) assert "CreationTime" in describe_endpoint_response assert "LastModifiedTime" in describe_endpoint_response assert "EndpointArn" in describe_endpoint_response assert "EndpointStatus" in describe_endpoint_response assert "ProductionVariants" in describe_endpoint_response @mock_sagemaker def test_describe_endpoint_throws_exception_for_nonexistent_endpoint(sagemaker_client): with pytest.raises(ValueError): sagemaker_client.describe_endpoint(EndpointName="nonexistent-endpoint") @mock_sagemaker def test_endpoint_is_no_longer_listed_after_deletion(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, ) sagemaker_client.delete_endpoint(EndpointName=endpoint_name) listed_endpoints = sagemaker_client.list_endpoints()["Endpoints"] listed_endpoint_names = [endpoint["EndpointName"] for endpoint in listed_endpoints] assert endpoint_name not in listed_endpoint_names @mock_sagemaker def test_update_endpoint_modifies_config_correctly(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) first_endpoint_config_name = "sample-config-1" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=first_endpoint_config_name, model_name=model_name) second_endpoint_config_name = "sample-config-2" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=second_endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointConfigName=first_endpoint_config_name, EndpointName=endpoint_name, ) first_describe_endpoint_response = sagemaker_client.describe_endpoint( EndpointName=endpoint_name) assert first_describe_endpoint_response["EndpointConfigName"] == first_endpoint_config_name sagemaker_client.update_endpoint( EndpointName=endpoint_name, EndpointConfigName=second_endpoint_config_name) second_describe_endpoint_response = sagemaker_client.describe_endpoint( EndpointName=endpoint_name) assert second_describe_endpoint_response["EndpointConfigName"] == second_endpoint_config_name @mock_sagemaker def test_update_endpoint_with_nonexistent_config_throws_exception(sagemaker_client): model_name = "sample-model-name" create_sagemaker_model(sagemaker_client=sagemaker_client, model_name=model_name) endpoint_config_name = "sample-config" create_endpoint_config( sagemaker_client=sagemaker_client, endpoint_config_name=endpoint_config_name, model_name=model_name) endpoint_name = "sample-endpoint" sagemaker_client.create_endpoint( EndpointConfigName=endpoint_config_name, EndpointName=endpoint_name, ) with pytest.raises(ValueError): sagemaker_client.update_endpoint( EndpointName=endpoint_name, EndpointConfigName="nonexistent-config")
StarcoderdataPython
5145260
<filename>string concordinate.py a=str(input("Enter the first string: \n")) b=str(input("Enter the second string; \n")) print(a+" "+b)
StarcoderdataPython
1966911
import random import heapq import datetime import networkx as nx import math import argparse import matplotlib.pyplot as plt import time import pickle import numpy as np import operator save_dir = '../datasets/Flickr/' dimension = 4 nodeDic = {} edgeDic = {} degree = [] G = pickle.load(open(save_dir+'Small_Final_SubG.G', 'rb')) nodeDic = pickle.load(open(save_dir+'Small_nodeFeatures.dic', 'rb')) for u in G.nodes(): for v in G[u]: edgeDic[(u,v)] = np.outer(nodeDic[u][1], nodeDic[v][0]).reshape(-1) pickle.dump(edgeDic, open(save_dir+'Small_edgeFeatures.dic', "wb" ))
StarcoderdataPython
1638589
import cv2 import numpy as np before = cv2.imread('2.png') b, g, r = cv2.split(before) np.multiply(b, 1.5, out=b, casting="unsafe") np.multiply(g, .75, out=g, casting="unsafe") np.multiply(r, 1.25, out=r, casting="unsafe") after = cv2.merge([b, g, r]) cv2.imshow('before', before) cv2.imshow('after', after) cv2.waitKey()
StarcoderdataPython
6418362
import copy import itertools from django import template register = template.Library() def previous_current_next(items): """ From http://www.wordaligned.org/articles/zippy-triples-served-with-python Creates an iterator which returns (previous, current, next) triples, with ``None`` filling in when there is no previous or next available. """ extend = itertools.chain([None], items, [None]) previous, current, next = itertools.tee(extend, 3) try: current.next() next.next() next.next() except StopIteration: pass return itertools.izip(previous, current, next) <EMAIL> def tree_structure(forums): structure = {} for previous, current, next in previous_current_next(forums): if previous: structure['new_level'] = previous.level < current.level else: structure['new_level'] = True if next: structure['closed_levels'] = range(current.level, next.level, -1) else: structure['closed_levels'] = range(current.level, -1, -1) yield current, copy.deepcopy(structure) register.filter(tree_structure) #<EMAIL>.inclusion_tag('forum/render_forum_list.html') def render_forum_list(forum_list): return {'forum_list': forum_list} register.inclusion_tag('forum/render_forum_list.html')(render_forum_list) #@<EMAIL>.inclusion_tag('forum/render_reply_form.html') def render_reply_form(thread, form): return {'thread': thread, 'form': form} register.inclusion_tag('forum/render_reply_form.html')(render_reply_form) #@<EMAIL>.inclusion_tag('forum/render_parent_list.html') def render_parent_list(parent_list): return {'parent_list': parent_list} register.inclusion_tag('forum/render_parent_list.html')(render_parent_list)
StarcoderdataPython
1604846
<gh_stars>1-10 import base64 import json import platform import sys import uuid from typing import Dict, List import attr import requests from .version import __version__ @attr.s class DbtRpcClient(object): host: str = attr.ib(default="0.0.0.0") port: int = attr.ib(validator=attr.validators.instance_of(int), default=8580) jsonrpc_version: str = attr.ib(validator=attr.validators.instance_of(str), default="2.0") url: str = attr.ib(init=False) def __attrs_post_init__(self): self.url = f"http://{self.host}:{self.port}/jsonrpc" @staticmethod def _construct_user_agent() -> str: '''Constructs a standard User Agent string to be used in headers for HTTP requests.''' client = f"dbt-rpc-client/{__version__}" python_version = f"Python/{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" system_info = f"{platform.system()}/{platform.release()}" user_agent = " ".join([python_version, client, system_info]) return user_agent def _construct_headers(self) -> Dict: '''Constructs a standard set of headers for HTTP requests.''' headers = requests.utils.default_headers() headers["User-Agent"] = self._construct_user_agent() headers["Content-Type"] = "application/json" headers["Accept"] = "application/json" return headers def _post(self, data: str = None) -> requests.Response: '''Constructs a standard way of making a POST request to the dbt RPC server.''' headers = self._construct_headers() response = requests.post(self.url, headers=headers, data=data) response.raise_for_status() return response def _default_request(self, method: str) -> Dict: data = { "jsonrpc": self.jsonrpc_version, "method": method, "id": str(uuid.uuid1()), "params": {} } return data def _selection(self, *, models: List[str] = None, select: List[str] = None, exclude: List[str] = None) -> Dict: params = {} if models is not None: params["models"] = ' '.join(set(models)) if select is not None: params["select"] = ' '.join(set(select)) if exclude is not None: params["exclude"] = ' '.join(set(exclude)) return params def status(self) -> requests.Response: data = self._default_request(method='status') return self._post(data=json.dumps(data)) def poll(self, *, request_token: str, logs: bool = False, logs_start: int = 0) -> requests.Response: data = self._default_request(method='poll') data["params"] = { "request_token": request_token, "logs": logs, "logs_start": logs_start } return self._post(data=json.dumps(data)) def ps(self, *, completed: bool = False) -> requests.Response: 'Lists running and completed processes executed by the RPC server.' data = self._default_request(method='ps') data["params"] = { "completed": completed } return self._post(data=json.dumps(data)) def kill(self, *, task_id: str) -> requests.Response: 'Terminates a running RPC task.' data = self._default_request(method='kill') data["params"] = { "task_id": task_id } return self._post(data=json.dumps(data)) def cli(self, *, cli_args: str, **kwargs) -> requests.Response: 'Terminates a running RPC task.' data = self._default_request(method='cli_args') data["params"] = { "cli_args": cli_args } if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def compile(self, *, models: List[str] = None, exclude: List[str] = None, **kwargs) -> requests.Response: 'Runs a dbt compile command.' data = self._default_request(method='compile') data["params"].update(self._selection(models=models, exclude=exclude)) if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def run(self, *, models: List[str] = None, exclude: List[str] = None, **kwargs) -> requests.Response: 'Runs a dbt run command.' data = self._default_request(method='run') data["params"].update(self._selection(models=models, exclude=exclude)) if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def snapshot(self, *, select: List[str] = None, exclude: List[str] = None, **kwargs) -> requests.Response: 'Runs a dbt snapshot command.' data = self._default_request(method='snapshot') data["params"].update(self._selection(select=select, exclude=exclude)) if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def test(self, *, models: List[str] = None, exclude: List[str] = None, data: bool = True, schema: bool = True, **kwargs) -> requests.Response: payload = self._default_request(method='test') payload["params"] = { "data": data, "schema": schema } payload["params"].update(self._selection(models=models, exclude=exclude)) if kwargs is not None: payload["params"]["task_tags"] = kwargs return self._post(data=json.dumps(payload)) def seed(self, *, show: bool = False, **kwargs) -> requests.Response: data = self._default_request(method='seed') data["params"] = { "show": show } if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def generate_docs(self, *, models: List[str] = None, exclude: List[str] = None, compile: bool = False, **kwargs) -> requests.Response: data = self._default_request(method='docs.generate') data["params"] = { "compile": compile } data["params"].update(self._selection(models=models, exclude=exclude)) if kwargs is not None: data["params"]["task_tags"] = kwargs return self._post(data=json.dumps(data)) def run_operation(self, *, macro: str) -> requests.Response: data = self._default_request(method='run-operation') data["params"] = { "macro": macro } return self._post(data=json.dumps(data)) def compile_sql(self, *, sql: str, name: str, timeout: int = 60) -> requests.Response: data = self._default_request(method='compile_sql') data["params"] = { "sql": str(base64.b64encode(bytes(sql, 'utf-8'))), "timeout": timeout, "name": name } return self._post(data=json.dumps(data)) def run_sql(self, *, sql: str, name: str, timeout: int = 60) -> requests.Response: data = self._default_request(method='run_sql') data["params"] = { "sql": str(base64.b64encode(bytes(sql, 'utf-8'))), "timeout": timeout, "name": name } return self._post(data=json.dumps(data))
StarcoderdataPython
4854806
# Copyright 2015 Huawei Technologies Co., Ltd. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron_lib.plugins.ml2 import api from tricircle.common import constants class LocalTypeDriver(api.TypeDriver): def get_type(self): return constants.NT_LOCAL def initialize(self): pass def is_partial_segment(self, segment): return False def validate_provider_segment(self, segment): pass def reserve_provider_segment(self, context, segment): return segment def allocate_tenant_segment(self, context): return {api.NETWORK_TYPE: constants.NT_LOCAL} def release_segment(self, context, segment): pass def get_mtu(self, physical): pass
StarcoderdataPython
1873492
from pydantic import BaseModel, Field, validator class RegistrationModel(BaseModel): login: str = Field(min_length=6) password: str = Field(min_length=8) @validator("login") def validate_login(cls, login: str) -> str: assert " " not in login, "No spaces allowed in login" return login class BaseUserModel(BaseModel): id: str login: str class UserModel(BaseUserModel): followers: int follows: int
StarcoderdataPython
8015076
<reponame>Algue-Rythme/GAT-Skim-Gram import warnings import numpy as np import pygsp as gsp from pygsp import graphs, filters, reduction import scipy as sp from scipy import sparse from sortedcontainers import SortedList from loukas_coarsening.maxWeightMatching import maxWeightMatching import loukas_coarsening.graph_utils as graph_utils try: import matplotlib import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D except ImportError: warnings.warn('Warning: plotting functions unavailable') def coarsen(G, K=10, r=0.5, max_levels=20, method='variation_edges', algorithm='greedy', Uk=None, lk=None, max_level_r=0.99): """ This function provides a common interface for coarsening algorithms that contract subgraphs Parameters ---------- G : pygsp Graph K : int The size of the subspace we are interested in preserving. r : float between (0,1) The desired reduction defined as 1 - n/N. Returns ------- C : np.array of size n x N The coarsening matrix. Gc : pygsp Graph The smaller graph. Call : list of np.arrays Coarsening matrices for each level Gall : list of (n_levels+1) pygsp Graphs All graphs involved in the multilevel coarsening Example ------- C, Gc, Call, Gall = coarsen(G, K=10, r=0.8) """ r = np.clip(r, 0, 0.999) N = G.N #TODO(lbethune): fix this heuristic K = max(1, min(K, N - 2)) n, n_target = N, max(2, np.ceil((1-r)*N)) C = sp.sparse.eye(N, format='csc') Gc = G Call, Gall = [], [] Gall.append(G) iC = None for level in range(1,max_levels+1): if n <= n_target: break G = Gc # how much more we need to reduce the current graph r_cur = np.clip(1-n_target/n, 0.0, max_level_r) if 'variation' in method: if level == 1: if (Uk is not None) and (lk is not None) and (len(lk)>= K): mask = lk<1e-10; lk[mask] = 1; lsinv = lk**(-0.5); lsinv[mask] = 0 B = Uk[:,:K] @ np.diag(lsinv[:K]) else: offset = 2*np.max(G.dw) T = offset*sp.sparse.eye(G.N, format='csc') - G.L lk, Uk = sp.sparse.linalg.eigsh(T, k=K, which='LM', tol=1e-5) lk = (offset-lk)[::-1] Uk = Uk[:,::-1] mask = lk<1e-10; lk[mask] = 1 lsinv = lk**(-1/2) lsinv[mask] = 0 B = Uk @ np.diag(lsinv) A = B else: B = iC.dot(B) d, V = np.linalg.eig(B.T @ (G.L).dot(B)) mask = np.isclose(d, np.zeros(shape=d.shape)) d[mask] = 1 dinvsqrt = d**(-1/2) dinvsqrt[mask] = 0 A = B @ np.diag(dinvsqrt) @ V if method == 'variation_edges': coarsening_list = contract_variation_edges(G, K=K, A=A, r=r_cur, algorithm=algorithm) else: coarsening_list = contract_variation_linear(G, K=K, A=A, r=r_cur, mode=method) else: weights = get_proximity_measure(G, method, K=K) if algorithm == 'optimal': # the edge-weight should be light at proximal edges weights = -weights if 'rss' not in method: weights -= min(weights) coarsening_list = matching_optimal(G, weights=weights, r=r_cur) elif algorithm == 'greedy': coarsening_list = matching_greedy(G, weights=weights, r=r_cur) iC = get_coarsening_matrix(G, coarsening_list) if iC.shape[1] - iC.shape[0] <= 2: break # avoid too many levels for so few nodes C = iC.dot(C) Call.append(iC) Wc = graph_utils.zero_diag(coarsen_matrix(G.W, iC)) # coarsen and remove self-loops Wc = (Wc + Wc.T) / 2 # this is only needed to avoid pygsp complaining for tiny errors if not hasattr(G, 'coords'): Gc = gsp.graphs.Graph(Wc) else: Gc = gsp.graphs.Graph(Wc, coords=coarsen_vector(G.coords, iC)) Gall.append(Gc) n = Gc.N return C, Gc, Call, Gall ################################################################################ # General coarsening utility functions ################################################################################ def coarsen_vector(x, C): return (C.power(2)).dot(x) def lift_vector(x, C): #Pinv = C.T; Pinv[Pinv>0] = 1 D = sp.sparse.diags(np.array(1/np.sum(C,0))[0]) Pinv = (C.dot(D)).T return Pinv.dot(x) def coarsen_matrix(W, C): #Pinv = C.T; #Pinv[Pinv>0] = 1 D = sp.sparse.diags(np.array(1/np.sum(C,0))[0]) Pinv = (C.dot(D)).T return (Pinv.T).dot(W.dot(Pinv)) def lift_matrix(W, C): P = C.power(2) return (P.T).dot(W.dot(P)) def get_coarsening_matrix(G, partitioning): """ This function should be called in order to build the coarsening matrix C. Parameters ---------- G : the graph to be coarsened partitioning : a list of subgraphs to be contracted Returns ------- C : the new coarsening matrix Example ------- C = contract(gsp.graphs.sensor(20),[0,1]) ?? """ #C = np.eye(G.N) C = sp.sparse.eye(G.N, format='lil') rows_to_delete = [] for subgraph in partitioning: nc = len(subgraph) # add v_j's to v_i's row C[subgraph[0],subgraph] = 1/np.sqrt(nc) #np.ones((1,nc))/np.sqrt(nc) rows_to_delete.extend(subgraph[1:]) # delete vertices #C = np.delete(C,rows_to_delete,0) C.rows = np.delete(C.rows, rows_to_delete) C.data = np.delete(C.data, rows_to_delete) C._shape = (G.N - len(rows_to_delete), G.N) C = sp.sparse.csc_matrix(C) # check that this is a projection matrix #assert sp.sparse.linalg.norm( ((C.T).dot(C))**2 - ((C.T).dot(C)) , ord='fro') < 1e-5 return C def coarsening_quality(G, C, kmax=30, Uk=None, lk=None): """ Measures how good is a coarsening. Parameters ---------- G : pygsp Graph C : np.array(n,N) The coarsening matrix kmax : int Until which eigenvalue we are interested in. Returns ------- metric : dictionary Contains all relevant metrics for coarsening quality: * error_eigenvalue : np.array(kmax) * error_subspace : np.array(kmax) * error_sintheta : np.array(kmax) * angle_matrix : np.array(kmax) * rss constants : np.array(kmax) as well as some general properties of Gc: * r : int reduction ratio * m : int number of edges """ N = G.N I = np.eye(N) if (Uk is not None) and (lk is not None) and (len(lk)>= kmax): U, l = Uk, lk elif hasattr(G, 'U'): U, l = G.U, G.e else: l, U = sp.sparse.linalg.eigsh(G.L, k=kmax, which='SM', tol=1e-3) l[0] = 1; linv = l**(-0.5); linv[0] = 0 # l[0] = 0 # avoids divide by 0 # below here, everything is C specific n = C.shape[0] Pi = C.T @ C S = graph_utils.get_S(G).T Lc = C.dot((G.L).dot(C.T)) Lp = Pi @ G.L @ Pi if kmax>n/2: [Uc,lc] = graph_utils.eig(Lc.toarray()) else: lc, Uc = sp.sparse.linalg.eigsh(Lc, k=kmax, which='SM', tol=1e-3) if not sp.sparse.issparse(Lc): print('warning: Lc should be sparse.') metrics = {'r': 1 - n / N, 'm': int((Lc.nnz-n)/2)} kmax = np.clip(kmax, 1, n) # eigenvalue relative error metrics['error_eigenvalue'] = np.abs(l[:kmax] - lc[:kmax]) / l[:kmax] metrics['error_eigenvalue'][0] = 0 # angles between eigenspaces metrics['angle_matrix'] = U.T @ C.T @ Uc # rss constants # metrics['rss'] = np.diag(U.T @ Lp @ U)/l - 1 # metrics['rss'][0] = 0 # other errors kmax = np.clip(kmax, 2, n) error_subspace = np.zeros(kmax) error_subspace_bound = np.zeros(kmax) error_sintheta = np.zeros(kmax) M = S @ Pi @ U @ np.diag(linv) # M_bound = S @ (I - Pi) @ U @ np.diag(linv) for kIdx in range(1,kmax): error_subspace[kIdx] = np.abs(np.linalg.norm( M[:,:kIdx + 1], ord=2)-1) # error_subspace_bound[kIdx] = np.linalg.norm( M_bound[:,:kIdx + 1], ord=2) error_sintheta[kIdx] = np.linalg.norm(metrics['angle_matrix'][0:kIdx+1,kIdx+1:], ord='fro')**2 metrics['error_subspace'] = error_subspace #metrics['error_subspace_bound'] = error_subspace_bound metrics['error_sintheta'] = error_sintheta return metrics def plot_coarsening(Gall, Call, size=3, edge_width=0.8, node_size=20, alpha=0.55, title='', monochrom=False): """ Plot a (hierarchical) coarsening Parameters ---------- G_all : list of pygsp Graphs Call : list of np.arrays Returns ------- fig : matplotlib figure """ # colors signify the size of a coarsened subgraph ('k' is 1, 'g' is 2, 'b' is 3, and so on) colors = ['k', 'g', 'b', 'r', 'y'] if monochrom: colors = ['b']*len(colors) n_levels = len(Gall)-1 if n_levels == 0: return None fig = plt.figure(figsize=(n_levels*size*3, size*2)) for level in range(n_levels): G = Gall[level] edges = np.array(G.get_edge_list()[0:2]) Gc = Gall[level+1] # Lc = C.dot(G.L.dot(C.T)) # Wc = sp.sparse.diags(Lc.diagonal(), 0) - Lc; # Wc = (Wc + Wc.T) / 2 # Gc = gsp.graphs.Graph(Wc, coords=(C.power(2)).dot(G.coords)) edges_c = np.array(Gc.get_edge_list()[0:2]) C = Call[level] C = C.toarray() if G.coords.shape[1] == 2: ax = fig.add_subplot(1, n_levels+1, level+1) ax.axis('off') ax.set_title(f'{title} | level = {level}, N = {G.N}') [x,y] = G.coords.T for eIdx in range(0, edges.shape[1]): ax.plot(x[edges[:,eIdx]], y[edges[:,eIdx]], color='k', alpha=alpha, lineWidth=edge_width) for i in range(Gc.N): subgraph = np.arange(G.N)[C[i,:] > 0] ax.scatter(x[subgraph], y[subgraph], c = colors[np.clip(len(subgraph)-1,0,4)], s = node_size*len(subgraph), alpha=alpha) elif G.coords.shape[1] == 3: ax = fig.add_subplot(1, n_levels+1, level+1, projection='3d') ax.axis('off') [x,y,z] = G.coords.T for eIdx in range(0, edges.shape[1]): ax.plot(x[edges[:,eIdx]], y[edges[:,eIdx]], zs=z[edges[:,eIdx]], color='k', alpha=alpha, lineWidth=edge_width) for i in range(Gc.N): subgraph = np.arange(G.N)[C[i,:] > 0] ax.scatter(x[subgraph], y[subgraph], z[subgraph], c=colors[np.clip(len(subgraph)-1,0,4)], s=node_size*len(subgraph), alpha=alpha) # the final graph Gc = Gall[-1] edges_c = np.array(Gc.get_edge_list()[0:2]) if G.coords.shape[1] == 2: ax = fig.add_subplot(1, n_levels+1, n_levels+1) ax.axis('off') [x,y] = Gc.coords.T ax.scatter(x, y, c = 'k', s = node_size, alpha=alpha) for eIdx in range(0, edges_c.shape[1]): ax.plot(x[edges_c[:,eIdx]], y[edges_c[:,eIdx]], color='k', alpha=alpha, lineWidth=edge_width) elif G.coords.shape[1] == 3: ax = fig.add_subplot(1, n_levels+1, n_levels+1, projection='3d') ax.axis('off') [x,y,z] = Gc.coords.T ax.scatter(x, y, z, c = 'k', s = node_size, alpha=alpha) for eIdx in range(0, edges_c.shape[1]): ax.plot(x[edges_c[:,eIdx]], y[edges_c[:,eIdx]], z[edges_c[:,eIdx]], color='k', alpha=alpha, lineWidth=edge_width) ax.set_title(f'{title} | level = {n_levels}, n = {Gc.N}') fig.tight_layout() return fig ################################################################################ # Variation-based contraction algorithms ################################################################################ def contract_variation_edges(G, A=None, K=10, r=0.5, algorithm='greedy'): """ Sequential contraction with local variation and edge-based families. This is a specialized implementation for the edge-based family, that works slightly faster than the contract_variation() function, which works for any family. See contract_variation() for documentation. """ N, deg, M = G.N, G.dw, G.Ne ones = np.ones(2) Pibot = np.eye(2) - np.outer(ones, ones) / 2 # cost function for the edge def subgraph_cost(G, A, edge): edge, w = edge[:2].astype(np.int), edge[2] deg_new = 2*deg[edge] - w L = np.array([[deg_new[0],-w], [-w,deg_new[1]]]) B = Pibot @ A[edge,:] return np.linalg.norm(B.T @ L @ B) # cost function for the edge def subgraph_cost_old(G, A, edge): w = G.W[edge[0], edge[1]] deg_new = 2*deg[edge] - w L = np.array([[deg_new[0],-w], [-w,deg_new[1]]]) B = Pibot @ A[edge,:] return np.linalg.norm(B.T @ L @ B) #edges = np.array(G.get_edge_list()[0:2]) edges = np.array(G.get_edge_list()) weights = np.array([subgraph_cost(G, A, edges[:,e]) for e in range(M)]) #weights = np.zeros(M) #for e in range(M): # weights[e] = subgraph_cost_old(G, A, edges[:,e]) if algorithm == 'optimal': # identify the minimum weight matching coarsening_list = matching_optimal(G, weights=weights, r=r) elif algorithm == 'greedy': # find a heavy weight matching coarsening_list = matching_greedy(G, weights=-weights, r=r) return coarsening_list def contract_variation_linear(G, A=None, K=10, r=0.5, mode='neighborhood'): """ Sequential contraction with local variation and general families. This is an implemmentation that improves running speed, at the expense of being more greedy (and thus having slightly larger error). See contract_variation() for documentation. """ N, deg, W_lil = G.N, G.dw, G.W.tolil() # The following is correct only for a single level of coarsening. # Normally, A should be passed as an argument. if A is None: lk, Uk = sp.sparse.linalg.eigsh(G.L, k=K, which='SM', tol=1e-3) # this is not optimized! lk[0] = 1 lsinv = lk**(-0.5) lsinv[0] = 0 lk[0] = 0 D_lsinv = np.diag(lsinv) A = Uk @ D_lsinv # cost function for the subgraph induced by nodes array def subgraph_cost(nodes): nc = len(nodes) ones = np.ones(nc) W = W_lil[nodes,:][:,nodes]#.tocsc() L = np.diag(2*deg[nodes] - W.dot(ones)) - W B = (np.eye(nc) - np.outer(ones, ones) / nc ) @ A[nodes,:] unnormalized_cost = np.linalg.norm(B.T @ L @ B) return unnormalized_cost / (nc-1) if nc != 1 else 0. class CandidateSet: def __init__(self, candidate_list): self.set = candidate_list self.cost = subgraph_cost(candidate_list) def __lt__(self, other): return self.cost < other.cost family = [] W_bool = G.A + sp.sparse.eye(G.N, dtype=np.bool, format='csr') if 'neighborhood' in mode: for i in range(N): #i_set = G.A[i,:].indices # get_neighbors(G, i) #i_set = np.append(i_set, i) i_set = W_bool[i,:].indices family.append(CandidateSet(i_set)) if 'cliques' in mode: import networkx as nx Gnx = nx.from_scipy_sparse_matrix(G.W) for clique in nx.find_cliques(Gnx): family.append(CandidateSet(np.array(clique))) else: if 'edges' in mode: edges = np.array(G.get_edge_list()[0:2]) for e in range(0,edges.shape[1]): family.append(CandidateSet(edges[:,e])) if 'triangles' in mode: triangles = set([]) edges = np.array(G.get_edge_list()[0:2]) for e in range(0,edges.shape[1]): [u,v] = edges[:,e] for w in range(G.N): if G.W[u,w] > 0 and G.W[v,w] > 0: triangles.add(frozenset([u,v,w])) triangles = list(map(lambda x: np.array(list(x)), triangles)) for triangle in triangles: family.append(CandidateSet(triangle)) family = SortedList(family) marked = np.zeros(G.N, dtype=np.bool) # ---------------------------------------------------------------------------- # Construct a (minimum weight) independent set. # ---------------------------------------------------------------------------- coarsening_list = [] #n, n_target = N, (1-r)*N n_reduce = np.floor(r*N) # how many nodes do we need to reduce/eliminate? while len(family) > 0: i_cset = family.pop(index=0) i_set = i_cset.set # check if marked i_marked = marked[i_set] if not any(i_marked): n_gain = len(i_set) - 1 if n_gain > n_reduce: continue # this helps avoid over-reducing # all vertices are unmarked: add i_set to the coarsening list marked[i_set] = True coarsening_list.append(i_set) #n -= len(i_set) - 1 n_reduce -= n_gain #if n <= n_target: break if n_reduce <= 0: break # may be worth to keep this set else: i_set = i_set[~i_marked] if len(i_set) > 1: # todo1: check whether to add to coarsening_list before adding to family # todo2: currently this will also select contraction sets that are disconnected # should we eliminate those? i_cset.set = i_set i_cset.cost = subgraph_cost(i_set) family.add(i_cset) return coarsening_list ################################################################################ # Edge-based contraction algorithms ################################################################################ def get_proximity_measure(G, name, K=10): N = G.N W = G.W #np.array(G.W.toarray(), dtype=np.float32) deg = G.dw #np.sum(W, axis=0) edges = np.array(G.get_edge_list()[0:2]) weights = np.array(G.get_edge_list()[2]) M = edges.shape[1] num_vectors = K #int(1*K*np.log(K)) if 'lanczos' in name: l_lan, X_lan = sp.sparse.linalg.eigsh(G.L, k=K, which='SM', tol=1e-2) elif 'cheby' in name: X_cheby = generate_test_vectors(G, num_vectors=num_vectors, method='Chebychev', lambda_cut = G.e[K+1]) elif 'JC' in name: X_jc = generate_test_vectors(G, num_vectors=num_vectors, method='JC', iterations=20) elif 'GS' in name: X_gs = generate_test_vectors(G, num_vectors=num_vectors, method='GS', iterations=1) if 'expected' in name: X = X_lan assert not np.isnan(X).any() assert X.shape[0] == N K = X.shape[1] proximity = np.zeros(M, dtype=np.float32) # heuristic for mutligrid if name == 'heavy_edge': wmax = np.array(np.max(G.W, 0).todense())[0] + 1e-5 for e in range(0,M): proximity[e] = weights[e] / max(wmax[edges[:,e]]) # select edges with large proximity return proximity # heuristic for mutligrid elif name == 'algebraic_JC': proximity += np.Inf for e in range(0,M): i,j = edges[:,e] for kIdx in range(num_vectors): xk = X_jc[:,kIdx] proximity[e] = min(proximity[e], 1 / max(np.abs(xk[i]-xk[j])**2, 1e-6) ) # select edges with large proximity return proximity # heuristic for mutligrid elif name == 'affinity_GS': c = np.zeros((N,N)) for e in range(0,M): i,j = edges[:,e] c[i,j] = (X_gs[i,:] @ X_gs[j,:].T)**2 / ( (X_gs[i,:] @ X_gs[i,:].T)**2 * (X_gs[j,:] @ X_gs[j,:].T)**2 ) # select c += c.T c -= np.diag(np.diag(c)) for e in range(0,M): i,j = edges[:,e] proximity[e] = c[i,j] / ( max(c[i,:]) * max(c[j,:]) ) return proximity for e in range(0,M): i,j = edges[:,e] if name == 'heavy_edge_degree': proximity[e] = deg[i] + deg[j] + 2*G.W[i,j] # select edges with large proximity # loose as little information as possible (custom) elif 'min_expected_loss' in name: for kIdx in range(1,K): xk = X[:,kIdx] proximity[e] = sum([proximity[e], (xk[i]-xk[j])**2 ] ) # select edges with small proximity # loose as little gradient information as possible (custom) elif name == 'min_expected_gradient_loss': for kIdx in range(1,K): xk = X[:,kIdx] proximity[e] = sum([proximity[e], (xk[i]-xk[j])**2 * (deg[i] + deg[j] + 2*G.W[i,j]) ] ) # select edges with small proximity # relaxation ensuring that K first eigenspaces are aligned (custom) elif name == 'rss': for kIdx in range(1,K): xk = G.U[:,kIdx] lk = G.e[kIdx] proximity[e] = sum([proximity[e], (xk[i]-xk[j])**2 * ((deg[i] + deg[j] + 2*G.W[i,j])/4) / lk ] ) # select edges with small proximity # fast relaxation ensuring that K first eigenspaces are aligned (custom) elif name == 'rss_lanczos': for kIdx in range(1,K): xk = X_lan[:,kIdx] lk = l_lan[kIdx] proximity[e] = sum( [proximity[e], (xk[i]-xk[j])**2 * ((deg[i] + deg[j] + 2*G.W[i,j])/4 - 0.5*(lk + lk)) / lk ] ) # select edges with small proximity # approximate relaxation ensuring that K first eigenspaces are aligned (custom) elif name == 'rss_cheby': for kIdx in range(num_vectors): xk = X_cheby[:,kIdx] lk = xk.T @ G.L @ xk proximity[e] = sum( [proximity[e], ( (xk[i]-xk[j])**2 * ((deg[i] + deg[j] + 2*G.W[i,j])/4 - 0*lk ) / lk )] ) # select edges with small proximity # heuristic for mutligrid (algebraic multigrid) elif name == 'algebraic_GS': proximity[e] = np.Inf for kIdx in range(num_vectors): xk = X_gs[:,kIdx] proximity[e] = min(proximity[e], 1 / max(np.abs(xk[i]-xk[j])**2, 1e-6) ) # select edges with large proximity if ('rss' in name) or ('expected' in name): proximity = -proximity return proximity def generate_test_vectors(G, num_vectors=10, method = 'Gauss-Seidel', iterations=5, lambda_cut=0.1): L = G.L N = G.N X = np.random.randn(N, num_vectors) / np.sqrt(N) if method == 'GS' or method == 'Gauss-Seidel': L_upper = sp.sparse.triu(L, 1, format='csc') L_lower_diag = sp.sparse.triu(L, 0, format='csc').T for j in range(num_vectors): x = X[:,j] for _ in range(iterations): x = - sp.sparse.linalg.spsolve_triangular(L_lower_diag, L_upper @ x) X[:,j] = x return X if method == 'JC' or method == 'Jacobi': deg = G.dw.astype(np.float) D = sp.sparse.diags(deg,0) deginv = deg**(-1) deginv[deginv == np.Inf] = 0 Dinv = sp.sparse.diags(deginv,0) M = Dinv.dot(D-L) for j in range(num_vectors): x = X[:,j] for _ in range(iterations): x = 0.5 * x + 0.5 * M.dot(x) X[:,j] = x return X elif method == 'Chebychev': f = filters.Filter(G, lambda x : ((x <= lambda_cut)*1).astype(np.float32)) return f.filter(X, method='chebyshev', order=50) else: raise ValueError def matching_optimal(G, weights, r=0.4): """ Generates a matching optimally with the objective of minimizing the total weight of all edges in the matching. Parameters ---------- G : pygsp graph weights : np.array(M) a weight for each edge ratio : float The desired dimensionality reduction (ratio = 1 - n/N) Notes: * The complexity of this is O(N^3) * Depending on G, the algorithm might fail to return ratios>0.3 """ N = G.N # the edge set edges = G.get_edge_list() edges = np.array(edges[0:2]) M = edges.shape[1] max_weight = 1*np.max(weights) # prepare the input for the minimum weight matching problem edge_list = [] for edgeIdx in range(M): [i,j] = edges[:,edgeIdx] if i==j: continue edge_list.append( (i, j, max_weight-weights[edgeIdx]) ) assert min(weights) >= 0 # solve it tmp = np.array(maxWeightMatching(edge_list)) # format output m = tmp.shape[0] matching = np.zeros((m,2), dtype=int) matching[:,0] = range(m) matching[:,1] = tmp # remove null edges and duplicates idx = np.where(tmp!=-1)[0] matching = matching[idx,:] idx = np.where(matching[:,0] > matching[:,1])[0] matching = matching[idx,:] assert matching.shape[0] >= 1 # if the returned matching is larger than what is requested, select the min weight subset of it matched_weights = np.zeros(matching.shape[0]) for mIdx in range(matching.shape[0]): i = matching[mIdx,0] j = matching[mIdx,1] eIdx = [e for e,t in enumerate(edges[:,:].T) if ((t==[i,j]).all() or (t==[j,i]).all()) ] matched_weights[mIdx] = weights[eIdx] keep = min(int(np.ceil(r*N)), matching.shape[0]) if keep < matching.shape[0]: idx = np.argpartition(matched_weights, keep) idx = idx[0:keep] matching = matching[idx,:] return matching def matching_greedy(G, weights, r=0.4): """ Generates a matching greedily by selecting at each iteration the edge with the largest weight and then removing all adjacent edges from the candidate set. Parameters ---------- G : pygsp graph weights : np.array(M) a weight for each edge r : float The desired dimensionality reduction (r = 1 - n/N) Notes: * The complexity of this is O(M) * Depending on G, the algorithm might fail to return ratios>0.3 """ N = G.N # the edge set edges = np.array(G.get_edge_list()[0:2]) M = edges.shape[1] idx = np.argsort(-weights) # idx = np.argsort(weights)[::-1] edges = edges[:,idx] # the candidate edge set candidate_edges = edges.T.tolist() # the matching edge set (this is a list of arrays) matching = [] # which vertices have been selected marked = np.zeros(N, dtype=np.bool) n, n_target = N, (1-r)*N while len(candidate_edges) > 0: # pop a candidate edge [i,j] = candidate_edges.pop(0) # check if marked if any(marked[[i,j]]): continue marked[[i,j]] = True n -= 1 # add it to the matching matching.append(np.array([i,j])) # termination condition if n <= n_target: break return np.array(matching) ############################################################################## # Sparsification and Kron reduction # Most of the code has been adapted from the PyGSP implementation. ############################################################################## def kron_coarsening(G, r=0.5, m=None): if not hasattr(G, 'coords'): G.set_coordinates(np.random.rand(G.N,2)) # needed by kron n_target = np.floor((1-r)*G.N) levels = int(np.ceil(np.log2(G.N/n_target))) Gs = my_graph_multiresolution(G, levels, r=r, sparsify=False, sparsify_eps=None, reduction_method='kron', reg_eps=0.01) Gk = Gs[-1] # sparsify to a target number of edges m if m is not None: M = Gk.Ne #int(Gk.W.nnz/2) epsilon = min(10/np.sqrt(G.N),.3) #1 - m/M Gc = graph_sparsify(Gk, epsilon, maxiter=10) Gc.mr = Gk.mr else: Gc = Gk return Gc, Gs[0] def kron_quality(G, Gc, kmax=30, Uk=None, lk=None): N, n = G.N, Gc.N keep_inds = Gc.mr['idx'] metrics = {'r': 1 - n / N, 'm': int(Gc.W.nnz/2), 'failed':False} kmax = np.clip(kmax, 1, n) if (Uk is not None) and (lk is not None) and (len(lk)>= kmax): U, l = Uk, lk elif hasattr(G, 'U'): U, l = G.U, G.e else: l, U = sp.sparse.linalg.eigsh(G.L, k=kmax, which='SM', tol=1e-3) l[0] = 1; linv = l**(-0.5); linv[0] = 0 # avoids divide by 0 C = np.eye(N); C = C[keep_inds,:] L = G.L.toarray() try: Phi = np.linalg.pinv(L + 0.01*np.eye(N)) Cinv = (Phi @ C.T) @ np.linalg.pinv(C @ Phi @ C.T) if kmax>n/2: [Uc,lc] = graph_utils.eig(Gc.L.toarray()) else: lc, Uc = sp.sparse.linalg.eigsh(Gc.L, k=kmax, which='SM', tol=1e-3) # eigenvalue relative error metrics['error_eigenvalue'] = np.abs(l[:kmax] - lc[:kmax]) / l[:kmax] metrics['error_eigenvalue'][0] = 0 # TODO : angles between eigenspaces # metrics['angle_matrix'] = U.T @ C.T @ Uc # other errors kmax = np.clip(kmax, 2, n) error_subspace = np.zeros(kmax) error_sintheta = np.zeros(kmax) # M = (Lsqrtm - sp.linalg.sqrtm(Cinv @ Gc.L.dot(C))) @ U @ np.diag(linv) # is this correct? M = U - sp.linalg.sqrtm(Cinv @ Gc.L.dot(C)) @ U @ np.diag(linv) # is this correct? for kIdx in range(0, kmax): error_subspace[kIdx] = np.abs(np.linalg.norm(M[:,:kIdx + 1], ord=2)-1) metrics['error_subspace'] = error_subspace metrics['error_sintheta'] = error_sintheta except: metrics['failed'] = True return metrics def kron_interpolate(G, Gc, x): return np.squeeze(reduction.interpolate(G, x, Gc.mr['idx'])) def my_graph_multiresolution(G, levels, r=0.5, sparsify=True, sparsify_eps=None, downsampling_method='largest_eigenvector', reduction_method='kron', compute_full_eigen=False, reg_eps=0.005): r"""Compute a pyramid of graphs (by Kron reduction). 'graph_multiresolution(G,levels)' computes a multiresolution of graph by repeatedly downsampling and performing graph reduction. The default downsampling method is the largest eigenvector method based on the polarity of the components of the eigenvector associated with the largest graph Laplacian eigenvalue. The default graph reduction method is Kron reduction followed by a graph sparsification step. *param* is a structure of optional parameters. Parameters ---------- G : Graph structure The graph to reduce. levels : int Number of level of decomposition lambd : float Stability parameter. It adds self loop to the graph to give the algorithm some stability (default = 0.025). [UNUSED?!] sparsify : bool To perform a spectral sparsification step immediately after the graph reduction (default is True). sparsify_eps : float Parameter epsilon used in the spectral sparsification (default is min(10/sqrt(G.N),.3)). downsampling_method: string The graph downsampling method (default is 'largest_eigenvector'). reduction_method : string The graph reduction method (default is 'kron') compute_full_eigen : bool To also compute the graph Laplacian eigenvalues and eigenvectors for every graph in the multiresolution sequence (default is False). reg_eps : float The regularized graph Laplacian is :math:`\bar{L}=L+\epsilon I`. A smaller epsilon may lead to better regularization, but will also require a higher order Chebyshev approximation. (default is 0.005) Returns ------- Gs : list A list of graph layers. Examples -------- >>> from pygsp import reduction >>> levels = 5 >>> G = graphs.Sensor(N=512) >>> G.compute_fourier_basis() >>> Gs = reduction.graph_multiresolution(G, levels, sparsify=False) >>> for idx in range(levels): ... Gs[idx].plotting['plot_name'] = 'Reduction level: {}'.format(idx) ... Gs[idx].plot() """ if sparsify_eps is None: sparsify_eps = min(10. / np.sqrt(G.N), 0.3) if compute_full_eigen: G.compute_fourier_basis() else: G.estimate_lmax() Gs = [G] Gs[0].mr = {'idx': np.arange(G.N), 'orig_idx': np.arange(G.N)} n_target = int(np.floor(G.N * (1-r))) for i in range(levels): if downsampling_method == 'largest_eigenvector': if hasattr(Gs[i], '_U'): V = Gs[i].U[:, -1] else: V = sp.sparse.linalg.eigs(Gs[i].L, 1)[1][:, 0] V *= np.sign(V[0]) n = max(int(Gs[i].N/2), n_target) ind = np.argsort(V) # np.nonzero(V >= 0)[0] ind = np.flip(ind,0) ind = ind[:n] else: raise NotImplementedError('Unknown graph downsampling method.') if reduction_method == 'kron': Gs.append(reduction.kron_reduction(Gs[i], ind)) else: raise NotImplementedError('Unknown graph reduction method.') if sparsify and Gs[i+1].N > 2: Gs[i+1] = reduction.graph_sparsify(Gs[i+1], min(max(sparsify_eps, 2. / np.sqrt(Gs[i+1].N)), 1.)) if Gs[i+1].is_directed(): W = (Gs[i+1].W + Gs[i+1].W.T)/2 Gs[i+1] = graphs.Graph(W, coords=Gs[i+1].coords) if compute_full_eigen: Gs[i+1].compute_fourier_basis() else: Gs[i+1].estimate_lmax() Gs[i+1].mr = {'idx': ind, 'orig_idx': Gs[i].mr['orig_idx'][ind], 'level': i} L_reg = Gs[i].L + reg_eps * sparse.eye(Gs[i].N) Gs[i].mr['K_reg'] = reduction.kron_reduction(L_reg, ind) Gs[i].mr['green_kernel'] = filters.Filter(Gs[i], lambda x: 1./(reg_eps + x)) return Gs def graph_sparsify(M, epsilon, maxiter=10): from pygsp import utils from scipy import stats # Test the input parameters if isinstance(M, graphs.Graph): if not M.lap_type == 'combinatorial': raise NotImplementedError L = M.L else: L = M N = np.shape(L)[0] if not 1./np.sqrt(N) <= epsilon < 1: raise ValueError('GRAPH_SPARSIFY: Epsilon out of required range') # Not sparse resistance_distances = utils.resistance_distance(L).toarray() # Get the Weight matrix if isinstance(M, graphs.Graph): W = M.W else: W = np.diag(L.diagonal()) - L.toarray() W[W < 1e-10] = 0 W = sparse.coo_matrix(W) W.data[W.data < 1e-10] = 0 W = W.tocsc() W.eliminate_zeros() start_nodes, end_nodes, weights = sparse.find(sparse.tril(W)) # Calculate the new weights. weights = np.maximum(0, weights) Re = np.maximum(0, resistance_distances[start_nodes, end_nodes]) Pe = weights * Re + 1e-4 Pe = Pe / np.sum(Pe) for _ in range(maxiter): # Rudelson, 1996 Random Vectors in the Isotropic Position # (too hard to figure out actual C0) C0 = 1 / 30. # Rudelson and Vershynin, 2007, Thm. 3.1 C = 4 * C0 q = round(N * np.log(N) * 9 * C**2 / (epsilon**2)) results = stats.rv_discrete(values=(np.arange(np.shape(Pe)[0]), Pe)).rvs(size=int(q)) spin_counts = stats.itemfreq(results).astype(int) per_spin_weights = weights / (q * Pe) counts = np.zeros(np.shape(weights)[0]) counts[spin_counts[:, 0]] = spin_counts[:, 1] new_weights = counts * per_spin_weights sparserW = sparse.csc_matrix((new_weights, (start_nodes, end_nodes)), shape=(N, N)) sparserW = sparserW + sparserW.T sparserL = sparse.diags(sparserW.diagonal(), 0) - sparserW # if graphs.Graph(W=sparserW).is_connected(): # break # elif i == maxiter - 1: # print('Despite attempts to reduce epsilon, sparsified graph is disconnected') # else: # epsilon -= (epsilon - 1/np.sqrt(N)) / 2. if isinstance(M, graphs.Graph): sparserW = sparse.diags(sparserL.diagonal(), 0) - sparserL if not M.is_directed(): sparserW = (sparserW + sparserW.T) / 2. Mnew = graphs.Graph(W=sparserW) #M.copy_graph_attributes(Mnew) else: Mnew = sparse.lil_matrix(sparserL) return Mnew ##############################################################################
StarcoderdataPython
8105612
<reponame>mateuszmidor/sla_dashboard_webapp from __future__ import annotations import logging from dataclasses import dataclass from typing import Dict, Generator from domain.geo import Coordinates from domain.types import IP, AgentID logger = logging.getLogger(__name__) @dataclass class Agent: id: AgentID = AgentID() ip: IP = IP() name: str = "" alias: str = "" coords: Coordinates = Coordinates() class Agents: def __init__(self) -> None: self._agents: Dict[AgentID, Agent] = {} self._agents_by_name: Dict[str, Agent] = {} def equals(self, other: Agents) -> bool: return sorted(self._agents.keys()) == sorted(other._agents.keys()) def get_by_id(self, agent_id: AgentID) -> Agent: return self._agents.get(agent_id, Agent()) def get_by_name(self, name: str) -> Agent: return self._agents_by_name.get(name, Agent()) def insert(self, agent: Agent) -> None: self._agents[agent.id] = agent existing = self._agents_by_name.get(agent.name) if existing: logger.warning("Duplicate agent name '%s' (ids: %s %s)", agent.name, existing.id, agent.id) _dedup_name = "{agent.name} [{agent.id}]" del self._agents_by_name[existing.name] existing.name = _dedup_name.format(agent=existing) self._agents_by_name[existing.name] = existing agent.name = _dedup_name.format(agent=agent) self._agents_by_name[agent.name] = agent logger.debug("adding agent: id: %s name: %s alias: %s", agent.id, agent.name, agent.alias) def remove(self, agent: Agent): try: del self._agents[agent.id] except KeyError: logger.warning("Agent id: %s name: %s was not in dict by id", agent.id, agent.name) try: del self._agents_by_name[agent.name] except KeyError: logger.warning("Agent id: %s name: %s was not in dict by name", agent.id, agent.name) def all(self, reverse: bool = False) -> Generator[Agent, None, None]: for n in sorted(self._agents_by_name.keys(), key=lambda x: x.lower(), reverse=reverse): yield self._agents_by_name[n] def update_names_aliases(self, src: Agents) -> None: """ Update agent names and aliases based on row data while preserving other existing agent attributes NOTE: This is an ugly hack that should be removed as soon as Kentik API becomes little bit more consistent """ logger.debug("update_names_aliases: src_agents: %d", src.count) for src_agent in src.all(): agent = self.get_by_id(src_agent.id) logger.debug("Updating agent id: %s (old name: %s new name: %s)", agent.id, agent.name, src_agent.name) if agent.id == AgentID(): agent = src_agent logging.warning("Agent %s (name: %s) was not in cache", agent.id, agent.name) self.insert(agent) else: # We need to preserve other attributes retrieved from AgentsList, so we cannot simply replace the # existing agent. However, we need to delete it from the cache and re-insert it in order to # keep dictionary by name in sync self.remove(agent) agent.name = src_agent.name agent.alias = src_agent.alias self.insert(agent) @property def count(self) -> int: return len(self._agents)
StarcoderdataPython
262071
# -*- coding: utf-8 -*- import module import fields class FanActuator(module.Base): update_rate = 10 public_name = 'Ventilateur' class fan(fields.actuator.Fan, fields.syntax.Boolean, fields.io.Readable, fields.persistant.Volatile, fields.Base): public_name = 'État du ventilateur' class speed(fields.syntax.BoundNumeric, fields.io.Readable, fields.io.Writable, fields.persistant.Volatile, fields.Base): lower_bound = 1 upper_bound = 3 public_name = 'Vitesse du ventilateur' init_value = 1
StarcoderdataPython
281642
from django.urls import path, include from . import views urlpatterns = [ path('location/', views.find_ahj_location, name='location'), path('address/', views.find_ahj_address, name='address') ]
StarcoderdataPython
6691890
import os os.environ['NO_ET'] = '1'
StarcoderdataPython
25751
<reponame>mbatchkarov/dc_evaluation __author__ = 'mmb28' import sys sys.path.append('.') sys.path.append('..') sys.path.append('../..')
StarcoderdataPython
3416021
import os from Game import Game class LoadGame(Game): def __init__(self, gamefolder): self.gamefolder = os.path.abspath(gamefolder) file = open(os.path.join(gamefolder, "sales")) self.releaseplayers = int(file.readline().rstrip("\n").split(": ")[1]) file.close() file = open(os.path.join(gamefolder, "imagelinks")) self.gameid = int(file.readline().rstrip("\n")) file.close() self.stats = self.readstats() self.players = self.releaseplayers
StarcoderdataPython
6588883
<filename>src/real_time.py import threading import time from tkinter import * from tkinter import ttk, messagebox from tkinter.font import Font import numpy import seaborn as sns import mne import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from pylsl import StreamInlet, resolve_stream # https://labstreaminglayer.readthedocs.io/ LABELS = ['A', 'B', 'C'] model_path = '../data/models/EEGNet_labels_3_accuracy_0.4166666567325592' class Application(Tk): def __init__(self): Tk.__init__(self) self.title("Serinity - Lab Streaming Layer") self.geometry("600x400") self.iconphoto(False, PhotoImage(file='../public/brain.png')) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self._start_predict = False self._mainframe = None self._state = 0 self.font = Font(family='Helvetica', size=10) self.init_theme() self.init_loading() try: self._thread = threading.Thread(target=self.init_lsl) self._thread.start() finally: return if self._state == 0: self._progress_bar.stop() self._progress_bar["mode"] = "determinate" self._progress_bar["value"] = 100 self._label["text"] = "An error as occured" else: self.input_button["text"] = "An error as occured" self.input_button["state"] = "disabled" def predict(self, data, model): data = tf.convert_to_tensor(data) probabilities = model.predict(tf.expand_dims(tf.expand_dims(tf.transpose(data[-500:, :32]), 0), 3)) predicted_indices = tf.argmax(probabilities, 1) return str(tf.gather(LABELS, predicted_indices).numpy()[0].decode('UTF-8')) def init_lsl(self): print("looking for an EEG stream...") model = tf.keras.models.load_model(model_path) streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0]) print("EEG stream located !") self.init_main_widget() data = [] while True: sample, timestamp = inlet.pull_sample() data.append(sample) if len(data) > 500: self.input_button["state"] = "normal" if self._start_predict: prediction = self.predict(data, model) self.letter_label["text"] = prediction self.sentences_label["text"] += prediction if len(self.sentences_label["text"]) % 30 == 0: self.sentences_label["text"] += "\n" self._start_predict = False self.input_button["state"] = "disabled" data = [] def callback(self): self._start_predict = True def callback_reset_button(self): self.sentences_label["text"] = "" self.letter_label["text"] = "" def init_main_widget(self): self._mainframe.destroy() self._state = 1 self._mainframe = ttk.Frame(self, borderwidth=10, relief="ridge") mainframe = self._mainframe mainframe.grid(column=0, row=0) self.input_button = ttk.Button(mainframe, command=self.callback, text="Predict") self.input_button.grid(row=3, pady=20) self.input_button["state"] = "disabled" self.reset_button = ttk.Button(mainframe, command=self.callback_reset_button, text="Reset") self.reset_button.grid(row=4) sentences_label_frame = ttk.LabelFrame(mainframe, text="Thought", labelanchor=N) sentences_label_frame.grid(row=2, padx=20, pady=25) self.sentences_label = ttk.Label(sentences_label_frame, text="", font=self.font) self.sentences_label.grid(column=0, padx=20, pady=10) self.letter_label = ttk.Label(sentences_label_frame, text="", font=Font(family='Helvetica', size=16, weight='bold')) self.letter_label.grid(row=1, padx=20, pady=10) def init_loading(self): self._mainframe = ttk.Frame(self, borderwidth=10, relief="ridge") mainframe = self._mainframe mainframe.grid(column=0, row=0) self._label = ttk.Label(mainframe, text="Looking for an EEG stream", font=self.font) self._label.grid(row=1) self._progress_bar = ttk.Progressbar(mainframe, mode="indeterminate") self._progress_bar.grid(row=2) self._progress_bar.start(10) def init_theme(self): pass if __name__ == '__main__': Application().mainloop()
StarcoderdataPython
1919344
import numpy as np import itertools # example from wikipedia #a = [[-1,1],[3,2],[2,3],[-1,0],[0,-1]] #b = [1,12,12,0,0] # example from http://web.mit.edu/16.410/www/lectures_fall04/L18-19-IP-BB.pdf a = [[6,3,5,2], [0,0,1,1], [-1,0,1,0], [0,-1,0,1], [1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1], [-1,0,0,0], [0,-1,0,0], [0,0,-1,0], [0,0,0,-1]] b = [10, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0] n = len(a) k = len(a[0]) for s in itertools.combinations(range(n),k): aa = [] bb = [] for x in s: aa.append(a[x]) bb.append(b[x]) aaa = np.array(aa) bbb = np.array(bb) try: x = np.linalg.solve(aaa,bbb) good = True for i in range(n): t = 0 for j in range(k): t += x[j] * a[i][j] if t > b[i]: good = False if good: print(s,aa,bb,x) except: pass
StarcoderdataPython
3359710
<filename>pyfeat/estimator/tram.py r""" ====================== TRAM estimator wrapper ====================== .. moduleauthor:: <NAME> <<EMAIL>> """ import pytram as pt import numpy as np class TRAM( object ): r""" I am the TRAM wrapper """ def __init__( self, C_K_ij, b_K_x, M_x, N_K_i ): r""" Initialize the TRAM object Parameters ---------- C_K_ij : numpy.ndarray( shape=(T,M,M), dtype=numpy.intc ) transition counts between the M discrete Markov states for each of the T thermodynamic ensembles b_K_x : numpy.ndarray( shape=(T,samples), dtype=numpy.float ) all samples for biases at thermodynamic state K M_x : numpy.ndarray( shape=(samples), dtype=numpy.intc ) trajectory of Markov states sampled N_K_i : numpy.ndarray( shape=(T,M), dtype=numpy.intc ) total number of counts from simulation at T in M discrete Markov state (bin) """ try: self._tram_obj = pt.TRAM( C_K_ij, b_K_x, M_x, N_K_i ) except AttributeError, e: raise NotImplementedError( "The TRAM estimator is not yet implemented in the pytram package" ) def sc_iteration( self , maxiter=100, ftol=1.0E-5, verbose=False ): r""" sc_iteration function Parameters ---------- maxiter : int maximum number of self-consistent-iteration steps ftol : float (> 0.0) convergence criterion based on the max relative change in an self-consistent-iteration step verbose : boolean Be loud and noisy """ self._tram_obj.sc_iteration( maxiter=maxiter, ftol=ftol, verbose=verbose ) @property def pi_i( self ): return self._tram_obj.pi_i @property def pi_K_i( self ): return self._tram_obj.pi_K_i @property def f_K( self ): return self._tram_obj.f_K @property def f_K_i( self ): return -np.log( self.pi_K_i ) @property def f_i( self ): return -np.log( self.pi_i ) @property def citation( self ): return self._tram_obj.citation def cite( self, pre="" ): self._tram_obj.cite( pre=pre )
StarcoderdataPython
9633886
from likeapp.views import LikeSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', LikeSet) urlpatterns = router.urls app_name = 'likeapp'
StarcoderdataPython
8063755
# -*- coding: utf-8 -*- """ #Handling Missing Values in Pandas * Tutorial: https://news.towardsai.net/hmv * Github https://github.com/towardsai/tutorials/tree/master/pandas """ #Import Required Libraries: import pandas as pd #Raw data in form of dictionary: info = {"Person":["Alan","Berta","Charlie","Danielle","Euler",pd.NA], #Name of Person. "Age":[32,45,35,28,30,pd.NA], #Age of Person. "Degree":["CS",pd.NA,pd.NA,pd.NA,"Physics",pd.NA], #Major. "Country":["USA","Mexico","USA",pd.NA,"USA",pd.NA], #Country of study. "Books":[10,pd.NA,30,pd.NA,50,60], #Books owned. "Batch Size":[200,100,50,200,50,pd.NA] #Batch Size. } #Converting the raw data into DataFrame: data = pd.DataFrame(info) #Printing the DataFrame: data #Replacing all missing values with 0: data.fillna(value=0) #Replacing values: #Values to be used for specific column: values = {"Person":"---", "Age":0, "Degree":"---","Books":0,"Batch Size":0} #Replacing the values: data.fillna(value=values) #Using method="ffill": data.fillna(method="ffill") #Using method="pad": #Same as method="ffill" data.fillna(method="pad") #Using method="ffill": #Using axis=0 (Default) data.fillna(method="ffill", axis=0) #Using method="ffill": #Using axis=1 data.fillna(method="ffill", axis=1) #Using method="bfill": data.fillna(method="bfill") #Using method="backfill": #Same as method="bfill" data.fillna(method="backfill") #Using method="bfill": #Using axis=0 (Default) data.fillna(method="bfill",axis=0) #Using method="bfill": #Using axis=1: data.fillna(method="bfill",axis=1) #Using method="ffill": #Using axis=0: #Using limit=1: data.fillna(method="ffill",axis=0, limit=1) #Using method="ffill": #Using axis=1: #Using limit=1: data.fillna(method="ffill",axis=1, limit=1) #Using method="bfill": #Using axis=0: #Using limit=1: data.fillna(method="bfill",axis=0, limit=1) #Using method="bfill": #Using axis=1: #Using limit=1: data.fillna(method="bfill",axis=1, limit=1) #Import Required Libraries: import pandas as pd #Raw data in form of dictionary: info = {"Age":[32.0,45.0,35.0,28.0,30.0,40.0], "Books":[10.0,pd.NA,30.0,40.0,50.0,60.0], "Batch Size":[200,100,50,200,50,300] } #Converting the raw data into DataFrame: data = pd.DataFrame(info) #Printing the DataFrame: data data.dtypes a = data.fillna(0,downcast="infer") a a.dtypes #Inplace=True will make changes in the original DataFrame. #It will return nothing. data.fillna(value=0,inplace=True) data #Import Required Libraries: import pandas as pd #Raw data in form of dictionary: info = {"Person":["Alan","Berta","Charlie","Danielle","Euler",pd.NA], #Name of Person. "Age":[32,45,35,28,30,pd.NA], #Age of Person. "Degree":["CS",pd.NA,pd.NA,pd.NA,"Physics",pd.NA], #Major. "Country":["USA","Mexico","USA",pd.NA,"USA",pd.NA], #Country of study. "Books":[10,pd.NA,30,pd.NA,50,60], #Books owned. "Batch Size":[200,100,50,200,50,pd.NA] #Batch Size. } #Converting the raw data into DataFrame: data = pd.DataFrame(info) #Printing the DataFrame: data #Using pd.DataFrame.bfill(): data.bfill() #Using pd.DataFrame.backfill(): data.backfill() #Using pd.DataFrame.ffill(): data.ffill() #Using pd.DataFrame.pad(): data.pad()
StarcoderdataPython
4870240
<gh_stars>10-100 """This module contains functions for conversion of coordinates and file formats""" # dependencies from astropy.coordinates import SkyCoord from astropy.table import Table from astropy.io import fits from astropy import units as u import pandas as pd def to_deg(coordinates): """Convert J2000 coordinates to degrees. Parameters ---------- coordinates : str J2000 coordinates Returns ------- tuple (ra, dec) in degrees """ # using SkyCoord function from astropy to convert HMS to degrees converted_coords = SkyCoord(coordinates, unit=(u.hourangle, u.deg)) # using string manipulation to extract coordinates from SkyCoord object coordinates = tuple( map(float, str(converted_coords).split("deg")[1].strip(">,\n, ),(").split(", ")) ) return coordinates def extract_coords(filename): """Extract J2000 coordinates from filename or filepath Parameters ---------- filename : str name or path of file Returns ------- str J2000 coordinates """ # in case path is entered as argument filename = filename.split("/")[-1] if "/" in filename else filename # to check whether declination is positive or negative plus_minus = "+" if "+" in filename else "-" # extracting right acesnsion (ra) and declination(dec) from filename filename = filename.split("_")[0].strip("J").split(plus_minus) ra_extracted = [ "".join(filename[0][0:2]), "".join(filename[0][2:4]), "".join(filename[0][4:]), ] dec_extracted = [ "".join(filename[1][0:2]), "".join(filename[1][2:4]), "".join(filename[1][4:]), ] coordinates = " ".join(ra_extracted) + " " + plus_minus + " ".join(dec_extracted) # return coordinates as a string in HH MM SS.SSS format return coordinates def header_check(file): """Checks whether the file has a header or not. Parameters ---------- file : str Filename or filepath of file to check Returns ------- int 1 if header is present 0 if not """ with open(file, "r", encoding="utf-8") as to_check: result = to_check.read(1).isalpha() return int(result) def txt_to_df(file, header): """Converts TXT lightcurve file to Pandas DataFrame. Parameters ---------- file : str Filename or filepath header : int To skip header if present. Returns ------- pandas.core.frame.DataFrame Lightcurve as a DataFrame """ cols = [ "TIME_BIN", "TIME_MIN", "TIME", "TIME_MAX", "COUNTS", "STAT_ERR", "AREA", "EXPOSURE", "COUNT_RATE", "COUNT_RATE_ERR", ] dataframe = pd.read_csv(file, skiprows=header, names=cols, sep=" ") return dataframe def fits_to_df(file): """Converts FITS lightcurve file to Pandas DataFrame. Parameters ---------- file : str Filename or filepath Returns ------- pandas.core.frame.DataFrame Lightcurve as a DataFrame """ # list of columns cols = "TIME_BIN TIME_MIN TIME TIME_MAX COUNTS STAT_ERR AREA EXPOSURE COUNT_RATE COUNT_RATE_ERR" cols = cols.split(" ") # accessing fits data hdu_list = fits.open(file, memmap=True) evt_data = Table(hdu_list[1].data) # initialising DataFrame dataframe = pd.DataFrame() # writing to dataframe for col in cols: dataframe[col] = list(evt_data[col]) return dataframe
StarcoderdataPython
11359782
<filename>src/sniffmypacketsv2/transforms/session_2_ipaddr.py #!/usr/bin/env python from common.dbconnect import mongo_connect from common.entities import pcapFile from canari.framework import configure from canari.maltego.entities import IPv4Address from canari.maltego.message import UIMessage from canari.config import config __author__ = 'catalyst256' __copyright__ = 'Copyright 2014, sniffmypacketsv2 Project' __credits__ = [] __license__ = 'GPL' __version__ = '0.1' __maintainer__ = 'catalyst256' __email__ = '<EMAIL>' __status__ = 'Development' __all__ = [ 'dotransform' ] @configure( label='Return IPv4 Address(s)', description='Return IPv4 Addresses from Session ID', uuids=['sniffMyPacketsv2.v2.session_2_ipaddr'], inputs=[('[SmP] - Sessions', pcapFile)], debug=True ) def dotransform(request, response): pcap = request.value usedb = config['working/usedb'] # Check to see if we are using the database or not if usedb == 0: return response + UIMessage('No database support configured, check your config file') else: pass x = mongo_connect() ipaddr = [] try: r = x.STREAMS.find({"File Name": pcap}).count() if r > 0: p = x.STREAMS.find({"File Name": pcap}, {"Packet.Source IP": 1, "Packet.Destination IP": 1, "_id": 0}) for i in p: sip = i['Packet']['Source IP'] dip = i['Packet']['Destination IP'] ipaddr.append(sip) ipaddr.append(dip) else: return response + UIMessage('This needs to be run from a TCP/UDP stream') except Exception as e: return response + UIMessage(str(e)) for t in ipaddr: e = IPv4Address(t) response += e return response
StarcoderdataPython
6601793
""" Django settings for password_generator project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from dotenv import load_dotenv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) load_dotenv(dotenv_path=BASE_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DJANGO_DEBUG') ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.postgres', 'health_check', 'rest_framework_swagger', 'health_check.db', # stock Django health checkers 'django_filters', 'rest_framework', 'jet', 'jet.dashboard', 'api', ] JET_SIDE_MENU_COMPACT = True JET_CHANGE_FORM_SIBLING_LINKS = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'password_generator.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'password_generator.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': os.getenv('default_engine'), 'NAME': os.getenv('default_name'), 'USER': os.getenv('default_user'), 'PASSWORD': os.getenv('default_password'), 'HOST': os.getenv('default_host'), 'PORT': os.getenv('default_port', default=5432) } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ # PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.DjangoModelPermissions', 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' # 'rest_framework.permissions.IsAdminUser', # 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'api.pagination.StandardResultsSetPagination', 'PAGE_SIZE': 100, 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } REST_FRAMEWORK_DOCS = { 'HIDE_DOCS': False } HEALTH_CHECK = { 'DISK_USAGE_MAX': 90, # percent 'MEMORY_MIN': 100, # in MB }
StarcoderdataPython
6572602
<gh_stars>0 # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from chirpstack_api.as_pb.external.api import gateway_pb2 as chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2 from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 class GatewayServiceStub(object): """GatewayService is the service managing the gateways. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Create = channel.unary_unary( '/api.GatewayService/Create', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.CreateGatewayRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.Get = channel.unary_unary( '/api.GatewayService/Get', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayRequest.SerializeToString, response_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayResponse.FromString, ) self.Update = channel.unary_unary( '/api.GatewayService/Update', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.UpdateGatewayRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.Delete = channel.unary_unary( '/api.GatewayService/Delete', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.DeleteGatewayRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.List = channel.unary_unary( '/api.GatewayService/List', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.ListGatewayRequest.SerializeToString, response_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.ListGatewayResponse.FromString, ) self.GetStats = channel.unary_unary( '/api.GatewayService/GetStats', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayStatsRequest.SerializeToString, response_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayStatsResponse.FromString, ) self.GetLastPing = channel.unary_unary( '/api.GatewayService/GetLastPing', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetLastPingRequest.SerializeToString, response_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetLastPingResponse.FromString, ) self.StreamFrameLogs = channel.unary_stream( '/api.GatewayService/StreamFrameLogs', request_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.StreamGatewayFrameLogsRequest.SerializeToString, response_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.StreamGatewayFrameLogsResponse.FromString, ) class GatewayServiceServicer(object): """GatewayService is the service managing the gateways. """ def Create(self, request, context): """Create creates the given gateway. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Get(self, request, context): """Get returns the gateway for the requested mac address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Update(self, request, context): """Update updates the gateway matching the given mac address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Delete(self, request, context): """Delete deletes the gateway matching the given mac address. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def List(self, request, context): """List lists the gateways. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetStats(self, request, context): """GetStats lists the gateway stats given the query parameters. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetLastPing(self, request, context): """GetLastPing returns the last emitted ping and gateways receiving this ping. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def StreamFrameLogs(self, request, context): """StreamFrameLogs streams the uplink and downlink frame-logs for the given gateway ID. Notes: * These are the raw LoRaWAN frames and this endpoint is intended for debugging only. * This endpoint does not work from a web-browser. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GatewayServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'Create': grpc.unary_unary_rpc_method_handler( servicer.Create, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.CreateGatewayRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Get': grpc.unary_unary_rpc_method_handler( servicer.Get, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayRequest.FromString, response_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayResponse.SerializeToString, ), 'Update': grpc.unary_unary_rpc_method_handler( servicer.Update, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.UpdateGatewayRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Delete': grpc.unary_unary_rpc_method_handler( servicer.Delete, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.DeleteGatewayRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'List': grpc.unary_unary_rpc_method_handler( servicer.List, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.ListGatewayRequest.FromString, response_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.ListGatewayResponse.SerializeToString, ), 'GetStats': grpc.unary_unary_rpc_method_handler( servicer.GetStats, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayStatsRequest.FromString, response_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetGatewayStatsResponse.SerializeToString, ), 'GetLastPing': grpc.unary_unary_rpc_method_handler( servicer.GetLastPing, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetLastPingRequest.FromString, response_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.GetLastPingResponse.SerializeToString, ), 'StreamFrameLogs': grpc.unary_stream_rpc_method_handler( servicer.StreamFrameLogs, request_deserializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.StreamGatewayFrameLogsRequest.FromString, response_serializer=chirpstack__api_dot_as__pb_dot_external_dot_api_dot_gateway__pb2.StreamGatewayFrameLogsResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'api.GatewayService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
StarcoderdataPython
9625114
<filename>position/models.py # position/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # Diagrams here: https://docs.google.com/drawings/d/1DsPnl97GKe9f14h41RPeZDssDUztRETGkXGaolXCeyo/edit from django.db import models from election_office_measure.models import CandidateCampaign, MeasureCampaign from exception.models import handle_exception, handle_exception_silently, handle_record_found_more_than_one_exception,\ handle_record_not_found_exception, handle_record_not_saved_exception from organization.models import Organization from twitter.models import TwitterUser from django.contrib.auth.models import User # from voter.models import Voter # Replace User with this once we have figured out User -> Voter object linking SUPPORT = 'SUPPORT' STILL_DECIDING = 'STILL_DECIDING' NO_STANCE = 'NO_STANCE' INFORMATION_ONLY = 'INFO_ONLY' OPPOSE = 'OPPOSE' POSITION_CHOICES = ( # ('SUPPORT_STRONG', 'Strong Supports'), # I do not believe we will be offering 'SUPPORT_STRONG' as an option (SUPPORT, 'Supports'), (STILL_DECIDING, 'Still deciding'), (NO_STANCE, 'No stance'), (INFORMATION_ONLY, 'Information only'), (OPPOSE, 'Opposes'), # ('OPPOSE_STRONG', 'Strongly Opposes'), # I do not believe we will be offering 'OPPOSE_STRONG' as an option ) class PositionEntered(models.Model): """ Any position entered by any person gets its own PositionEntered entry. We then generate Position entries that get used to display an particular org's position. """ # We are relying on built-in Python id field # The id for the generated position that this PositionEntered entry influences position_id = models.BigIntegerField(null=True, blank=True) date_entered = models.DateTimeField(verbose_name='date entered', null=True) # The organization this position is for organization_id = models.BigIntegerField(null=True, blank=True) # The voter expressing the opinion voter_id = models.BigIntegerField(null=True, blank=True) # The election this position is for election_id = models.BigIntegerField(verbose_name='election id', null=True, blank=True) # The unique We Vote id of the tweet that is the source of the position tweet_source_id = models.BigIntegerField(null=True, blank=True) # This is the voter / authenticated user who entered the position for an organization # (NOT the voter expressing opinion) voter_entering_position = models.ForeignKey( User, verbose_name='authenticated user who entered position', null=True, blank=True) # The Twitter user account that generated this position twitter_user_entered_position = models.ForeignKey(TwitterUser, null=True, verbose_name='') # This is the candidate/politician that the position refers to. # Either candidate_campaign is filled OR measure_campaign, but not both # candidate_campaign = models.ForeignKey( # CandidateCampaign, verbose_name='candidate campaign', null=True, blank=True, # related_name='positionentered_candidate') candidate_campaign_id = models.BigIntegerField(verbose_name='id of candidate_campaign', null=True, blank=True) # Useful for queries based on Politicians -- not the main table we use for ballot display though politician_id = models.BigIntegerField(verbose_name='', null=True, blank=True) # This is the measure/initiative/proposition that the position refers to. # Either measure_campaign is filled OR candidate_campaign, but not both # measure_campaign = models.ForeignKey( # MeasureCampaign, verbose_name='measure campaign', null=True, blank=True, related_name='positionentered_measure') measure_campaign_id = models.BigIntegerField(verbose_name='id of measure_campaign', null=True, blank=True) # Strategic denormalization - this is redundant but will make generating the voter guide easier. # geo = models.ForeignKey(Geo, null=True, related_name='pos_geo') # issue = models.ForeignKey(Issue, null=True, blank=True, related_name='') stance = models.CharField(max_length=15, choices=POSITION_CHOICES, default=NO_STANCE) # supporting/opposing statement_text = models.TextField(null=True, blank=True,) statement_html = models.TextField(null=True, blank=True,) # A link to any location with more information about this position more_info_url = models.URLField(blank=True, null=True, verbose_name='url with more info about this position') # Did this position come from a web scraper? from_scraper = models.BooleanField(default=False) # Was this position certified by an official with the organization? organization_certified = models.BooleanField(default=False) # Was this position certified by an official We Vote volunteer? volunteer_certified = models.BooleanField(default=False) # link = models.URLField(null=True, blank=True,) # link_title = models.TextField(null=True, blank=True, max_length=128) # link_site = models.TextField(null=True, blank=True, max_length=64) # link_txt = models.TextField(null=True, blank=True) # link_img = models.URLField(null=True, blank=True) # Set this to True after getting all the link details (title, txt, img etc) # details_loaded = models.BooleanField(default=False) # video_embed = models.URLField(null=True, blank=True) # spam_flag = models.BooleanField(default=False) # abuse_flag = models.BooleanField(default=False) # orig_json = models.TextField(blank=True) def __unicode__(self): return self.stance class Meta: ordering = ('date_entered',) def is_support(self): if self.stance == SUPPORT: return True return False def is_oppose(self): if self.stance == OPPOSE: return True return False def is_no_stance(self): if self.stance == NO_STANCE: return True return False def is_information_only(self): if self.stance == INFORMATION_ONLY: return True return False def is_still_deciding(self): if self.stance == STILL_DECIDING: return True return False def candidate_campaign(self): try: candidate_campaign = CandidateCampaign.objects.get(id=self.candidate_campaign_id) except CandidateCampaign.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e) print "position.candidate_campaign Found multiple" return None except CandidateCampaign.DoesNotExist as e: handle_exception_silently(e) print "position.candidate_campaign did not find" return None return candidate_campaign def organization(self): try: organization = Organization.objects.get(id=self.organization_id) except Organization.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e) print "position.candidate_campaign Found multiple" return None except Organization.DoesNotExist as e: handle_exception_silently(e) print "position.candidate_campaign did not find" return None return organization class Position(models.Model): """ This is a table of data generated from PositionEntered. Not all fields copied over from PositionEntered """ # We are relying on built-in Python id field # The PositionEntered entry that was copied into this entry based on verification rules position_entered_id = models.BigIntegerField(null=True, blank=True) date_entered = models.DateTimeField(verbose_name='date entered', null=True) # The organization this position is for organization_id = models.BigIntegerField(null=True, blank=True) # The election this position is for election_id = models.BigIntegerField(verbose_name='election id', null=True, blank=True) candidate_campaign = models.ForeignKey( CandidateCampaign, verbose_name='candidate campaign', null=True, blank=True, related_name='position_candidate') # Useful for queries based on Politicians -- not the main table we use for ballot display though politician_id = models.BigIntegerField(verbose_name='', null=True, blank=True) # This is the measure/initiative/proposition that the position refers to. # Either measure_campaign is filled OR candidate_campaign, but not both measure_campaign = models.ForeignKey( MeasureCampaign, verbose_name='measure campaign', null=True, blank=True, related_name='position_measure') stance = models.CharField(max_length=15, choices=POSITION_CHOICES) # supporting/opposing statement_text = models.TextField(null=True, blank=True,) statement_html = models.TextField(null=True, blank=True,) # A link to any location with more information about this position more_info_url = models.URLField(blank=True, null=True, verbose_name='url with more info about this position') def __unicode__(self): return self.name class Meta: ordering = ('date_entered',) # def display_ballot_item_name(self): # """ # Organization supports 'ballot_item_name' (which could be a campaign name, or measure name # :return: # """ # # Try to retrieve the candidate_campaign # if candidate_campaign.id: class PositionListForCandidateCampaign(models.Model): """ A way to retrieve all of the positions stated about this CandidateCampaign """ # candidate_campaign = models.ForeignKey( # CandidateCampaign, null=False, blank=False, verbose_name='candidate campaign') # position = models.ForeignKey( # PositionEntered, null=False, blank=False, verbose_name='position about candidate') def retrieve_all_positions_for_candidate_campaign(self, candidate_campaign_id, stance_we_are_looking_for): # TODO Error check stance_we_are_looking_for # Retrieve the support positions for this candidate_campaign_id organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by('date_entered') organization_position_list = organization_position_list.filter(candidate_campaign_id=candidate_campaign_id) # SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE organization_position_list = organization_position_list.filter(stance=stance_we_are_looking_for) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e) if organization_position_list_found: return organization_position_list else: organization_position_list = {} return organization_position_list def calculate_positions_followed_by_voter( self, all_positions_list_for_candidate_campaign, organizations_followed_by_voter): """ We need a list of positions that were made by an organization that this voter follows :param all_positions_list_for_candidate_campaign: :param organizations_followed_by_voter: :return: """ this_voter_id = 1 positions_followed_by_voter = [] # Only return the positions if they are from organizations the voter follows for position in all_positions_list_for_candidate_campaign: if position.voter_id == this_voter_id: # TODO DALE Is this the right way to do this? positions_followed_by_voter.append(position) elif position.organization_id in organizations_followed_by_voter: print "position {position_id} followed by voter (org {org_id})".format( position_id=position.id, org_id=position.organization_id) positions_followed_by_voter.append(position) return positions_followed_by_voter def calculate_positions_not_followed_by_voter( self, all_positions_list_for_candidate_campaign, organizations_followed_by_voter): """ We need a list of positions that were made by an organization that this voter follows :param all_positions_list_for_candidate_campaign: :param organizations_followed_by_voter: :return: """ positions_not_followed_by_voter = [] # Only return the positions if they are from organizations the voter follows for position in all_positions_list_for_candidate_campaign: # Some positions are for individual voters, so we want to filter those out if position.organization_id \ and position.organization_id not in organizations_followed_by_voter: print "position {position_id} NOT followed by voter (org {org_id})".format( position_id=position.id, org_id=position.organization_id) positions_not_followed_by_voter.append(position) return positions_not_followed_by_voter class PositionEnteredManager(models.Model): def __unicode__(self): return "PositionEnteredManager" def retrieve_organization_candidate_campaign_position(self, organization_id, candidate_campaign_id): """ Find a position based on the organization_id & candidate_campaign_id :param organization_id: :param candidate_campaign_id: :return: """ position_id = 0 voter_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_voter_candidate_campaign_position(self, voter_id, candidate_campaign_id): organization_id = 0 position_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_position_from_id(self, position_id): organization_id = 0 voter_id = 0 candidate_campaign_id = 0 measure_campaign_id = 0 position_entered_manager = PositionEnteredManager() return position_entered_manager.retrieve_position( position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id) def retrieve_position(self, position_id, organization_id, voter_id, candidate_campaign_id, measure_campaign_id): error_result = False exception_does_not_exist = False exception_multiple_object_returned = False position_on_stage = PositionEntered() try: if position_id > 0: position_on_stage = PositionEntered.objects.get(id=position_id) position_id = position_on_stage.id elif organization_id > 0 and candidate_campaign_id > 0: position_on_stage = PositionEntered.objects.get( organization_id=organization_id, candidate_campaign_id=candidate_campaign_id) # If still here, we found an existing position position_id = position_on_stage.id elif organization_id > 0 and measure_campaign_id > 0: position_on_stage = PositionEntered.objects.get( organization_id=organization_id, measure_campaign_id=measure_campaign_id) position_id = position_on_stage.id elif voter_id > 0 and candidate_campaign_id > 0: position_on_stage = PositionEntered.objects.get( voter_id=voter_id, candidate_campaign_id=candidate_campaign_id) position_id = position_on_stage.id elif voter_id > 0 and measure_campaign_id > 0: position_on_stage = PositionEntered.objects.get( voter_id=voter_id, measure_campaign_id=measure_campaign_id) position_id = position_on_stage.id except PositionEntered.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e) error_result = True exception_multiple_object_returned = True except PositionEntered.DoesNotExist as e: handle_exception_silently(e) error_result = True exception_does_not_exist = True results = { 'error_result': error_result, 'DoesNotExist': exception_does_not_exist, 'MultipleObjectsReturned': exception_multiple_object_returned, 'position_found': True if position_id > 0 else False, 'position_id': position_id, 'position': position_on_stage, 'is_support': position_on_stage.is_support(), 'is_oppose': position_on_stage.is_oppose(), 'is_no_stance': position_on_stage.is_no_stance(), 'is_information_only': position_on_stage.is_information_only(), 'is_still_deciding': position_on_stage.is_still_deciding(), } return results def toggle_on_voter_support_for_candidate_campaign(self, voter_id, candidate_campaign_id): stance = SUPPORT position_entered_manager = PositionEnteredManager() return position_entered_manager.toggle_on_voter_position_for_candidate_campaign( voter_id, candidate_campaign_id, stance) def toggle_off_voter_support_for_candidate_campaign(self, voter_id, candidate_campaign_id): stance = NO_STANCE position_entered_manager = PositionEnteredManager() return position_entered_manager.toggle_on_voter_position_for_candidate_campaign( voter_id, candidate_campaign_id, stance) def toggle_on_voter_oppose_for_candidate_campaign(self, voter_id, candidate_campaign_id): stance = OPPOSE position_entered_manager = PositionEnteredManager() return position_entered_manager.toggle_on_voter_position_for_candidate_campaign( voter_id, candidate_campaign_id, stance) def toggle_off_voter_oppose_for_candidate_campaign(self, voter_id, candidate_campaign_id): stance = NO_STANCE position_entered_manager = PositionEnteredManager() return position_entered_manager.toggle_on_voter_position_for_candidate_campaign( voter_id, candidate_campaign_id, stance) def toggle_on_voter_position_for_candidate_campaign(self, voter_id, candidate_campaign_id, stance): # Does a position from this voter already exist? position_entered_manager = PositionEnteredManager() results = position_entered_manager.retrieve_voter_candidate_campaign_position(voter_id, candidate_campaign_id) voter_position_on_stage_found = False position_id = 0 if results['position_found']: print "yay!" voter_position_on_stage = results['position'] # Update this position with new values try: voter_position_on_stage.stance = stance # voter_position_on_stage.statement_text = statement_text voter_position_on_stage.save() position_id = voter_position_on_stage.id voter_position_on_stage_found = True except Exception as e: handle_record_not_saved_exception(e) elif results['MultipleObjectsReturned']: print "delete all but one and take it over?" elif results['DoesNotExist']: try: # Create new voter_position_on_stage = PositionEntered( voter_id=voter_id, candidate_campaign_id=candidate_campaign_id, stance=stance, # statement_text=statement_text, ) voter_position_on_stage.save() position_id = voter_position_on_stage.id voter_position_on_stage_found = True except Exception as e: handle_record_not_saved_exception(e) results = { 'success': True if voter_position_on_stage_found else False, 'position_id': position_id, 'position': voter_position_on_stage, } return results
StarcoderdataPython
4883274
def repeatedString(s, n): L = len(s) return (s.count('a') * (n//L) + s[:n % L].count('a')) x = "abc" n = 8 print(repeatedString("abc", 89))
StarcoderdataPython
179644
import os, os.path, sys, wx, stat, shutil import subprocess as sp import traceback as tb opj = os.path.join global FILES_DIR, THUMB_DIR MPLAYER_DIR = "mplayer" # change if needed CONVERT_DIR = "convert" # imagemagick's convert wx.InitAllImageHandlers() def __GetThumbName(fullPath, fileType): fileSize = os.stat(fullPath).st_size (root, ext) = os.path.splitext( os.path.basename(fullPath) ) thumbName = root+str(fileSize)+ext #construct the thumb name # video files have .jpg tacked onto the end thumbName += ".jpg" return opj( THUMB_DIR, thumbName ) ### change the permission of the settings file to allow everyone to write to it def __SetWritePermissions(*files): for filePath in files: try: flags = stat.S_IWUSR | stat.S_IRUSR | stat.S_IWGRP | stat.S_IRGRP | stat.S_IROTH os.chmod(filePath, flags) except: print str(sys.exc_info()[0])+" "+str(sys.exc_info()[1])+" "+str(sys.exc_info()[2]) def makeVideoThumb(fullPath, thumbPath): print "\n", 80*"-", "\ncreating video thumbnail with command: " # must create two frames because of mplayer bug createCmd = MPLAYER_DIR+" -vo jpeg -quiet -frames 2 -ss 5 "+ fullPath print createCmd try: sp.check_call(createCmd.split()) except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) # delete one of them try: os.remove("00000001.jpg") except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) # resize it to 300x300 try: im = wx.Image("00000002.jpg") # read the original image if im.Ok(): #the image may be corrupted... im.Rescale(300, 300) # resize it im.SaveFile("00000002.jpg", wx.BITMAP_TYPE_JPEG) # save it back to a file except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) # rename the right one try: shutil.move("00000002.jpg", thumbPath) except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) def makePDFThumb(fullPath, thumbPath): print "\n", 80*"-", "\ncreating PDF thumbnail with command: " createCmd = CONVERT_DIR+" -thumbnail 300x300 "+fullPath+"[0] "+thumbPath print createCmd try: sp.check_call(createCmd.split()) except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) def makeImageThumb(fullPath, thumbPath): def __GetWxBitmapType(name): ext = os.path.splitext(name)[1] ext = ext.lower() if ext==".jpg": return wx.BITMAP_TYPE_JPEG elif ext==".png": return wx.BITMAP_TYPE_PNG elif ext==".bmp": return wx.BITMAP_TYPE_BMP elif ext==".gif": return wx.BITMAP_TYPE_GIF elif ext==".pcx": return wx.BITMAP_TYPE_PCX elif ext==".pnm": return wx.BITMAP_TYPE_PNM elif ext==".tif": return wx.BITMAP_TYPE_TIF elif ext==".tiff": return wx.BITMAP_TYPE_TIF elif ext==".xpm": return wx.BITMAP_TYPE_XPM elif ext==".ico": return wx.BITMAP_TYPE_ICO elif ext==".cur": return wx.BITMAP_TYPE_CUR else: return False try: wxImageType = __GetWxBitmapType(os.path.basename(fullPath)) if wxImageType: # some types just cant be saved by wxPython # write the thumb but name it with a filename and filesize so that they are unique #thumbPath = __GetThumbName(fullPath, "image") im = wx.Image(fullPath) # read the original image if im.Ok(): #the image may be corrupted... im.Rescale(300, 300) # resize it im.SaveFile(thumbPath, wx.BITMAP_TYPE_JPEG) # save it back to a file except: print "".join(tb.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])) def makeThumbnail(fullPath, fileType, thumbPath): if not os.path.exists(thumbPath): if fileType == "image": makeImageThumb(fullPath, thumbPath) elif fileType == "video": makeVideoThumb(fullPath, thumbPath) elif fileType == "pdf": makePDFThumb(fullPath, thumbPath) else: print "\nERROR:Don't know how to make thumbnail for:", fileType if os.path.exists(thumbPath): __SetWritePermissions(thumbPath) def main(): for d in os.listdir(FILES_DIR): if d=="image" or d=="video" or d=="pdf": for root, dirs, files in os.walk(opj(FILES_DIR, d)): for f in files: fullPath = opj(root, f) thumbPath = __GetThumbName(fullPath, d) if not os.path.exists(thumbPath): makeThumbnail(fullPath, d, thumbPath) if __name__ == '__main__': import sys, os global FILES_DIR, THUMB_DIR if len(sys.argv) < 2: print "USAGE: python makeThumbs.py path_to_file_library" else: FILES_DIR = sys.argv[1] if os.path.exists(FILES_DIR): THUMB_DIR = opj(FILES_DIR, "thumbnails") main() else: print "Given directory doesn't exist... exiting"
StarcoderdataPython
3454122
import pandas as pd import numpy as np from scipy import stats from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.metrics.pairwise import linear_kernel, cosine_similarity from surprise import Reader, Dataset, SVD, evaluate from imdbToId import converter # Configuring database import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="udolf", # your username password="<PASSWORD>", # your password db="recommendme") # name of the data base gen_md = pd.read_csv('data/gen_md.csv') # Main recommendation part for the class recommendMe(): def __init__(self): pass ''' This will return movies intially to the guest who is not logged in or haven't rated a single movie ''' def build_chart(genre, percentile=0.85): movieDb = gen_md[gen_md['genre'] == genre] vote_counts = movieDb[movieDb['vote_count'].notnull()]['vote_count'].astype('int') vote_averages = movieDb[movieDb['vote_average'].notnull()]['vote_average'].astype('int') C = vote_averages.mean() m = vote_counts.quantile(percentile) qualified = movieDb[(movieDb['vote_count'] >= m) & (movieDb['vote_count'].notnull()) & (movieDb['vote_average'].notnull())][['title','vote_count','vote_average','popularity','imdb_id']] qualified['vote_count'] = qualified['vote_count'].astype('int') qualified['vote_average'] = qualified['vote_average'].astype('int') qualified['wr'] = qualified.apply(lambda x: (x['vote_count']/(x['vote_count']+m) * x['vote_average']) + (m/(m+x['vote_count']) * C), axis=1) qualified = qualified.sort_values('wr', ascending=False).head(250) return qualified.head(7) ''' This will return movies that are top of their genre but not rated by the user ''' def build_chartP(genre,userId, percentile=0.85): cur = db.cursor() result = cur.execute('SELECT * FROM ratings WHERE userId = %s',[userId]) imdbIdsRatedAlready = [] if(result > 0): data = cur.fetchall() for singleR in data: imdbIdsRatedAlready.append(singleR[3]) cur.close() print(imdbIdsRatedAlready) movieDb = gen_md[gen_md['genre'] == genre] vote_counts = movieDb[movieDb['vote_count'].notnull()]['vote_count'].astype('int') vote_averages = movieDb[movieDb['vote_average'].notnull()]['vote_average'].astype('int') C = vote_averages.mean() m = vote_counts.quantile(percentile) qualified = movieDb[(movieDb['vote_count'] >= m) & (movieDb['vote_count'].notnull()) & (movieDb['vote_average'].notnull())][['title','vote_count','vote_average','popularity','imdb_id']] qualified['vote_count'] = qualified['vote_count'].astype('int') qualified['vote_average'] = qualified['vote_average'].astype('int') qualified['wr'] = qualified.apply(lambda x: (x['vote_count']/(x['vote_count']+m) * x['vote_average']) + (m/(m+x['vote_count']) * C), axis=1) qualified = qualified.sort_values('wr', ascending=False).head(250) qualified = qualified[~qualified.imdb_id.isin(imdbIdsRatedAlready)] return qualified.head(8) ''' This function will take user id,5 movie and 5 rating from the database that are recently added and add them to the rating dataset that will be used for training the model ''' def svdRecommender(userList,movieIdList,ratingList): # Adding the data form the user mat = [] for i in range(len(ratingList)): temp = [] temp.append(userList[i]) temp.append(movieIdList[i]) temp.append(ratingList[i]) mat.append(temp) ratings_small = pd.read_csv('data/ratings_small.csv') newData = pd.DataFrame(mat,columns = ['userId','movieId','rating']) ratings_small = ratings_small.append(newData,ignore_index = True) ratings_small.to_csv('ratings_small.csv',index = False) # Getting the recommended movies after the training movies = recommendMe.recommender(userList[0]) return movies ''' This function will take the user id and perform the svd decompostion from the rating data and after training, the trained model will we used to recommend the rating for all the movies for the user and we will remove the movies which are already rated by the user ''' def recommender(user): cur = db.cursor() # Getting the movies already rated by the user result = cur.execute('SELECT * FROM ratings WHERE userId = %s',[user]) imdbIdsRatedAlready = [] if(result > 0): data = cur.fetchall() for singleR in data: imdbIdsRatedAlready.append(singleR[3]) cur.close() print(imdbIdsRatedAlready) ratings = pd.read_csv('data/ratings_small.csv') dataFrame = ratings['movieId'].unique() movies = pd.DataFrame([dataFrame],['movieId']).transpose() # Performing the training by using surprise package reader = Reader() data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader) data.split(n_folds=2) svd = SVD() evaluate(svd, data, measures=['RMSE', 'MAE']) trainset = data.build_full_trainset() svd.fit(trainset) # Performing the prediction for each movie according to the user movies['est'] = movies['movieId'].apply(lambda x : svd.predict(int(user),x).est) movies = movies.sort_values('est', ascending=False) movies = converter.convertToimdbId(list(movies.head(100)['movieId'])) # Removing movies already rated by user print(movies) movies = movies[~movies.imdbId.isin(imdbIdsRatedAlready)] movies['imdbId'].values return movies
StarcoderdataPython
11214941
from keras.layers import Dense, Merge from keras.models import Sequential from keras.optimizers import RMSprop from keras.regularizers import l2 from objectives import cca_loss def create_model(layer_sizes1, layer_sizes2, input_size1, input_size2, learning_rate, reg_par, outdim_size, use_all_singular_values): """ builds the whole model the structure of each sub-network is defined in build_mlp_net, and it can easily get substituted with a more efficient and powerful network like CNN """ view1_model = build_mlp_net(layer_sizes1, input_size1, reg_par) view2_model = build_mlp_net(layer_sizes2, input_size2, reg_par) model = Sequential() model.add(Merge([view1_model, view2_model], mode='concat')) model_optimizer = RMSprop(lr=learning_rate) model.compile(loss=cca_loss(outdim_size, use_all_singular_values), optimizer=model_optimizer) return model def build_mlp_net(layer_sizes, input_size, reg_par): model = Sequential() for l_id, ls in enumerate(layer_sizes): if l_id == 0: input_dim = input_size else: input_dim = [] if l_id == len(layer_sizes)-1: activation = 'linear' else: activation = 'sigmoid' model.add(Dense(ls, input_dim=input_dim, activation=activation, kernel_regularizer=l2(reg_par))) return model
StarcoderdataPython
11335910
<gh_stars>0 from convertmask import baseDecorate import copy import datetime import os import random import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element import cv2 import numpy as np import skimage from convertmask.utils.auglib.optional.resize import resize_img from convertmask.utils.img2xml.processor_multiObj import img2xml_multiobj from convertmask.utils.methods.logger import logger from convertmask.utils.xml2yolo.xml2yolo import convert as x2yVert from convertmask.utils.yolo2xml.yolo2xml import convert as y2xVert from skimage import io from .resize import resizeScript def getBoxes(front: int, root1: Element, root2: Element, root3: Element, root4: Element, imgShape: tuple, heightFactor: float, widthFactor: float): root1_ = copy.deepcopy(root1) root2_ = copy.deepcopy(root2) root3_ = copy.deepcopy(root3) root4_ = copy.deepcopy(root4) if front == 1: # 1 # 2 for o in root2_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymin >= heightFactor * imgShape[0] or xmax <= imgShape[1] * ( # 1 - widthFactor): if xmax <= imgShape[1] * (1 - widthFactor): box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: # if ymin < heightFactor * imgShape[0]: # if ymax > heightFactor * imgShape[0]: # box.find('ymax').text = str(int(heightFactor * # imgShape[0])) if xmax > imgShape[1] * (1 - widthFactor): if xmin < imgShape[1] * (1 - widthFactor): box.find('xmin').text = str( int(imgShape[1] * (1 - widthFactor))) # 3 for o in root3_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymax <= (1-heightFactor) * imgShape[ # 0] or xmin >= widthFactor * imgShape[1]: if ymax <= (1 - heightFactor) * imgShape[0]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * (1 - heightFactor): if ymin < imgShape[0] * (1 - heightFactor): box.find('ymin').text = str( int(imgShape[0] * (1 - heightFactor))) # if xmin < widthFactor * imgShape[1]: # if xmax > widthFactor * imgShape[1]: # box.find('xmax').text = str(int(widthFactor * imgShape[1])) # 4 for o in root4_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if xmax <= imgShape[1] * (1 - widthFactor) or ymax <= imgShape[ 0] * (1 - heightFactor): box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * (1 - heightFactor): if ymin < imgShape[0] * (1 - heightFactor): box.find('ymin').text = str( int(imgShape[0] * (1 - heightFactor))) if xmax > imgShape[1] * (1 - widthFactor): if xmin < imgShape[1] * (1 - widthFactor): box.find('xmin').text = str( int(imgShape[1] * (1 - widthFactor))) if front == 2: # 1 for o in root1_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if ymin >= (1 - heightFactor ) * imgShape[0] or xmin >= widthFactor * imgShape[1]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymin < (1 - heightFactor) * imgShape[0]: if ymax > (1 - heightFactor) * imgShape[0]: box.find('ymax').text = str( int((1 - heightFactor) * imgShape[0])) if xmin < widthFactor * imgShape[1]: if xmax > widthFactor * imgShape[1]: box.find('xmax').text = str( int(widthFactor * imgShape[1])) # 2 # 3 for o in root3_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymax <= (1-heightFactor) * imgShape[ # 0] or xmin >= widthFactor * imgShape[1]: if ymax <= (1 - heightFactor) * imgShape[0]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * (1 - heightFactor): if ymin < imgShape[0] * (1 - heightFactor): box.find('ymin').text = str( int(imgShape[0] * (1 - heightFactor))) # if xmin < widthFactor * imgShape[1]: # if xmax > widthFactor * imgShape[1]: # box.find('xmax').text = str(int(widthFactor * imgShape[1])) # 4 for o in root4_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if xmax <= imgShape[1] * (1 - widthFactor) or ymax <= imgShape[ 0] * (1 - heightFactor): box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * (1 - heightFactor): if ymin < imgShape[0] * (1 - heightFactor): box.find('ymin').text = str( int(imgShape[0] * (1 - heightFactor))) if xmax > imgShape[1] * (1 - widthFactor): if xmin < imgShape[1] * (1 - widthFactor): box.find('xmin').text = str( int(imgShape[1] * (1 - widthFactor))) if front == 3: # 1 for o in root1_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if ymin >= heightFactor * imgShape[0] or xmin >= ( 1 - widthFactor) * imgShape[1]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymin < heightFactor * imgShape[0]: if ymax > heightFactor * imgShape[0]: box.find('ymax').text = str( int(heightFactor * imgShape[0])) if xmin < widthFactor * (1 - imgShape[1]): if xmax > widthFactor * (1 - imgShape[1]): box.find('xmax').text = str( int(widthFactor * (1 - imgShape[1]))) # 2 for o in root2_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymin >= heightFactor * imgShape[0] or xmax <= imgShape[1] * ( # 1 - widthFactor): if xmax <= imgShape[1] * (1 - widthFactor): box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: # if ymin < heightFactor * imgShape[0]: # if ymax > heightFactor * imgShape[0]: # box.find('ymax').text = str(int(heightFactor * # imgShape[0])) if xmax > imgShape[1] * (1 - widthFactor): if xmin < imgShape[1] * (1 - widthFactor): box.find('xmin').text = str( int(imgShape[1] * (1 - widthFactor))) # 3 # 4 for o in root4_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if xmax <= imgShape[1] * (1 - widthFactor) or ymax <= imgShape[ 0] * (1 - heightFactor): box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * (1 - heightFactor): if ymin < imgShape[0] * (1 - heightFactor): box.find('ymin').text = str( int(imgShape[0] * (1 - heightFactor))) if xmax > imgShape[1] * (1 - widthFactor): if xmin < imgShape[1] * (1 - widthFactor): box.find('xmin').text = str( int(imgShape[1] * (1 - widthFactor))) if front == 4: # 1 for o in root1_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) if ymin >= heightFactor * imgShape[ 0] or xmin >= widthFactor * imgShape[1]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymin < heightFactor * imgShape[0]: if ymax > heightFactor * imgShape[0]: box.find('ymax').text = str( int(heightFactor * imgShape[0])) if xmin < widthFactor * imgShape[1]: if xmax > widthFactor * imgShape[1]: box.find('xmax').text = str( int(widthFactor * imgShape[1])) # 2 for o in root2_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymin >= heightFactor * imgShape[0] or xmax <= imgShape[1] * ( # 1 - widthFactor): if xmax <= imgShape[ 1] * widthFactor or ymin >= heightFactor * imgShape[0]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymin < heightFactor * imgShape[0]: if ymax > heightFactor * imgShape[0]: box.find('ymax').text = str( int(heightFactor * imgShape[0])) if xmax > imgShape[1] * widthFactor: if xmin < imgShape[1] * widthFactor: box.find('xmin').text = str( int(imgShape[1] * widthFactor)) # 3 for o in root3_.iter('object'): box = o.find('bndbox') xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) # if ymax <= (1-heightFactor) * imgShape[ # 0] or xmin >= widthFactor * imgShape[1]: if ymax <= heightFactor * imgShape[ 0] or xmin >= widthFactor * imgShape[1]: box.find('xmin').text = str(0) box.find('xmax').text = str(0) box.find('ymin').text = str(0) box.find('ymax').text = str(0) else: if ymax > imgShape[0] * heightFactor: if ymin < imgShape[0] * heightFactor: box.find('ymin').text = str( int(imgShape[0] * heightFactor)) if xmin < widthFactor * imgShape[1]: if xmax > widthFactor * imgShape[1]: box.find('xmax').text = str( int(widthFactor * imgShape[1])) # 4 return root1_, root2_, root3_, root4_ def getMeanSize(imgs: list): height = [] width = [] for i in imgs: height.append(i.shape[0]) width.append(i.shape[1]) return int(np.mean(height)), int(np.mean(width)) def getName(xmls: list): s = str(datetime.datetime.now()) for i in xmls: s += i return str(abs(hash(s))) def mosiacScript(imgs: list, xmls: list, savePath: str, flag=False): heightFactor = random.uniform(0.3, 0.7) widthFactor = random.uniform(0.3, 0.7) if not type(imgs) is list or not type(xmls) is list: logger.error('Input must be list!') return # imgs if len(imgs) == 0: logger.error('None image found!') return if len(imgs) == 1: for _ in range(0, 3): imgs.append(imgs[0]) if len(imgs) == 2: for _ in range(0, 2): imgs.append(imgs[0]) if len(imgs) == 3: for _ in range(0, 1): imgs.append(imgs[0]) # xmls if len(xmls) == 0: logger.error('None xml found!') return if len(xmls) == 1: for _ in range(0, 3): xmls.append(xmls[0]) if len(xmls) == 2: for _ in range(0, 2): xmls.append(xmls[0]) if len(xmls) == 3: for _ in range(0, 1): xmls.append(xmls[0]) imgname = getName(xmls) folder = savePath mHeight, mWidth = getMeanSize(imgs) mosiacImg = mosiac_img(imgs, heightFactor, widthFactor) objs = [] imgshape = mosiacImg.shape for idx in range(len(xmls)): in_file = open(xmls[idx]) tree = ET.parse(in_file) root = tree.getroot() for o in root.iter('object'): obj = dict() name = o.find('name').text difficult = 0 xmlbox = o.find('bndbox') b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)) bb = x2yVert((mWidth, mHeight), b) x, y, w, h = bb[0], bb[1], bb[2], bb[3] if idx == 0: bbox = y2xVert( (imgshape[1] * widthFactor, imgshape[0] * heightFactor), x, y, w, h) elif idx == 1: bbox = y2xVert((imgshape[1] * (1 - widthFactor), imgshape[0] * heightFactor), x, y, w, h) bbox[0] = bbox[0] + int(widthFactor * imgshape[1]) bbox[1] = bbox[1] + int(widthFactor * imgshape[1]) elif idx == 2: bbox = y2xVert((imgshape[1] * widthFactor, imgshape[0] * (1 - heightFactor)), x, y, w, h) bbox[2] = bbox[2] + int(heightFactor * imgshape[0]) bbox[3] = bbox[3] + int(heightFactor * imgshape[0]) else: bbox = y2xVert((imgshape[1] * (1 - widthFactor), imgshape[0] * (1 - heightFactor)), x, y, w, h) bbox[0] = bbox[0] + int(widthFactor * imgshape[1]) bbox[2] = bbox[2] + int(heightFactor * imgshape[0]) bbox[1] = bbox[1] + int(widthFactor * imgshape[1]) bbox[3] = bbox[3] + int(heightFactor * imgshape[0]) tmp = dict() tmp['xmin'] = str(int(bbox[0])) tmp['ymin'] = str(int(bbox[2])) tmp['xmax'] = str(int(bbox[1])) tmp['ymax'] = str(int(bbox[3])) obj['name'] = name obj['difficult'] = difficult obj['bndbox'] = tmp del tmp objs.append(obj) tmpPath = savePath + os.sep + imgname + '.xml' filepath = tmpPath.replace('.xml', '.jpg') filename = imgname + '.jpg' img2xml_multiobj(tmpPath, tmpPath, folder, filename, filepath, imgshape[1], imgshape[0], objs) logger.info('Saved to {}.'.format(tmpPath)) if flag: skimage.io.imsave(filepath, mosiacImg) @baseDecorate() def mosiac_img(imgs: list, heightFactor=0.5, widthFactor=0.5): if not type(imgs) is list: logger.error('Input must be a list!') return if len(imgs) == 0: logger.error('None image found!') return if len(imgs) == 1: for _ in range(0, 3): imgs.append(imgs[0]) if len(imgs) == 2: for _ in range(0, 2): imgs.append(imgs[0]) if len(imgs) == 3: for _ in range(0, 1): imgs.append(imgs[0]) mHeight, mWidth = getMeanSize(imgs) img_left_top = resize_img( np.array(skimage.transform.resize(imgs[0], (mHeight, mWidth)) * 255).astype(np.uint8), heightFactor, widthFactor) img_right_top = resize_img( np.array(skimage.transform.resize(imgs[1], (mHeight, mWidth)) * 255).astype(np.uint8), heightFactor, 1 - widthFactor) img_left_bottom = resize_img( np.array(skimage.transform.resize(imgs[2], (mHeight, mWidth)) * 255).astype(np.uint8), 1 - heightFactor, widthFactor) img_right_bottom = resize_img( np.array(skimage.transform.resize(imgs[3], (mHeight, mWidth)) * 255).astype(np.uint8), 1 - heightFactor, 1 - widthFactor) h1 = np.hstack((img_left_top, img_right_top)) h2 = np.hstack((img_left_bottom, img_right_bottom)) return np.vstack((h1, h2)) def mosiac_img_no_reshape(imgs: list, heightFactor=0.5, widthFactor=0.5): assert type(imgs) is list and len( imgs) == 4, "input must be a list[str_or_ndarray] with length=4" img1, img2, img3, img4 = imgs[0], imgs[1], imgs[2], imgs[3] if isinstance(img1, str): img1 = io.imread(img1) if isinstance(img2, str): img2 = io.imread(img2) if isinstance(img3, str): img3 = io.imread(img3) if isinstance(img4, str): img4 = io.imread(img4) imgShape1 = img1.shape img2 = cv2.resize(img2, (imgShape1[1], imgShape1[0]), interpolation=cv2.INTER_CUBIC) img3 = cv2.resize(img3, (imgShape1[1], imgShape1[0]), interpolation=cv2.INTER_CUBIC) img4 = cv2.resize(img4, (imgShape1[1], imgShape1[0]), interpolation=cv2.INTER_CUBIC) if heightFactor < 0.5: heightFactor = 1 - heightFactor if widthFactor < 0.5: widthFactor = 1 - widthFactor maskImg = np.zeros( (int(imgShape1[0] / heightFactor), int(imgShape1[1] / widthFactor), 3)) front = random.randint(0, 3) maskShape = maskImg.shape res = [] if front == 0: maskImg[maskShape[0] - imgShape1[0]:, maskShape[1] - imgShape1[1]:] = img4 maskImg[0:imgShape1[0], maskShape[1] - imgShape1[1]:] = img2 maskImg[maskShape[0] - imgShape1[0]:, 0:imgShape1[1]] = img3 maskImg[0:imgShape1[0], 0:imgShape1[1]] = img1 res = [1, 4, 2, 3] if front == 1: maskImg[maskShape[0] - imgShape1[0]:, maskShape[1] - imgShape1[1]:] = img4 maskImg[maskShape[0] - imgShape1[0]:, 0:imgShape1[1]] = img3 maskImg[0:imgShape1[0], 0:imgShape1[1]] = img1 maskImg[0:imgShape1[0], maskShape[1] - imgShape1[1]:] = img2 res = [2, 4, 3, 1] if front == 2: maskImg[maskShape[0] - imgShape1[0]:, maskShape[1] - imgShape1[1]:] = img4 maskImg[0:imgShape1[0], maskShape[1] - imgShape1[1]:] = img2 maskImg[0:imgShape1[0], 0:imgShape1[1]] = img1 maskImg[maskShape[0] - imgShape1[0]:, 0:imgShape1[1]] = img3 res = [3, 4, 2, 1] if front == 3: maskImg[0:imgShape1[0], 0:imgShape1[1]] = img1 maskImg[0:imgShape1[0], maskShape[1] - imgShape1[1]:] = img2 maskImg[maskShape[0] - imgShape1[0]:, 0:imgShape1[1]] = img3 maskImg[maskShape[0] - imgShape1[0]:, maskShape[1] - imgShape1[1]:] = img4 res = [4, 1, 2, 3] return maskImg.astype(np.uint8), res, heightFactor, widthFactor def mosiacScript_no_reshape(imgs: list, xmls: list, savePath: str, flag=False): heightFactor = random.uniform(0.25, 0.5) # Originally it is (0.1, 0.5), i think 0.1 is too extreme widthFactor = random.uniform(0.25, 0.5) img1, img2, img3, img4 = imgs[0], imgs[1], imgs[2], imgs[3] if not type(imgs) is list or not type(xmls) is list: logger.error('Input must be list!') return imgname = getName(xmls) folder = savePath mosiacImg, res, _, _ = mosiac_img_no_reshape(imgs, heightFactor, widthFactor) front = res[0] heightFactor = min(heightFactor, 1 - heightFactor) widthFactor = min(widthFactor, 1 - widthFactor) tree1 = ET.parse(xmls[0]) tree2 = resizeScript(img2, xmls[1], heightFactor=img1.shape[0] / img2.shape[0], widthFactor=img1.shape[1] / img2.shape[1], flag=False) tree3 = resizeScript(img3, xmls[2], heightFactor=img1.shape[0] / img3.shape[0], widthFactor=img1.shape[1] / img3.shape[1], flag=False) tree4 = resizeScript(img4, xmls[3], heightFactor=img1.shape[0] / img4.shape[0], widthFactor=img1.shape[1] / img4.shape[1], flag=False) root1 = tree1.getroot() root2 = tree2.getroot() for box in root2.iter('bndbox'): xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) box.find('xmin').text = str( int(xmin + widthFactor * mosiacImg.shape[1])) box.find('xmax').text = str( int(xmax + widthFactor * mosiacImg.shape[1])) root3 = tree3.getroot() for box in root3.iter('bndbox'): xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) box.find('ymin').text = str( int(ymin + heightFactor * mosiacImg.shape[0])) box.find('ymax').text = str( int(ymax + heightFactor * mosiacImg.shape[0])) root4 = tree4.getroot() for box in root4.iter('bndbox'): xmin = float(box.find('xmin').text) ymin = float(box.find('ymin').text) xmax = float(box.find('xmax').text) ymax = float(box.find('ymax').text) box.find('xmin').text = str( int(xmin + widthFactor * mosiacImg.shape[1])) box.find('xmax').text = str( int(xmax + widthFactor * mosiacImg.shape[1])) box.find('ymin').text = str( int(ymin + heightFactor * mosiacImg.shape[0])) box.find('ymax').text = str( int(ymax + heightFactor * mosiacImg.shape[0])) boxes = [] r1, r2, r3, r4 = getBoxes(front, root1, root2, root3, root4, mosiacImg.shape, heightFactor=heightFactor, widthFactor=widthFactor) for box in r1.iter('object'): boxes.append(box) for box in r2.iter('object'): boxes.append(box) for box in r3.iter('object'): boxes.append(box) for box in r4.iter('object'): boxes.append(box) # print(len(boxes)) imgshape = mosiacImg.shape objs = [] for o in boxes: obj = dict() name = o.find('name').text difficult = 0 xmlbox = o.find('bndbox') b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)) tmp = dict() tmp['xmin'] = str(int(b[0])) tmp['ymin'] = str(int(b[2])) tmp['xmax'] = str(int(b[1])) tmp['ymax'] = str(int(b[3])) # print(tmp) if not (int(tmp['xmin']) == 0 and int(tmp['xmax']) == 0 and int(tmp['ymin']) == 0 and int(tmp['ymax']) == 0): obj['name'] = name obj['difficult'] = difficult obj['bndbox'] = tmp objs.append(obj) del tmp # print(len(objs)) tmpPath = savePath + os.sep + imgname + '.xml' filepath = tmpPath.replace('.xml', '.jpg') filename = imgname + '.jpg' img2xml_multiobj(tmpPath, tmpPath, folder, filename, filepath, imgshape[1], imgshape[0], objs) logger.info('Saved to {}.'.format(tmpPath)) if flag: skimage.io.imsave(filepath, mosiacImg)
StarcoderdataPython
8061708
empty_dictionary = {} print(empty_dictionary) empty_dictionary["key1"] = 20 print(empty_dictionary)
StarcoderdataPython
398761
<reponame>Healthedata1/Flask-PL #!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Invoice) on 2019-05-07. # 2019, SMART Health IT. from . import domainresource class Invoice(domainresource.DomainResource): """ Invoice containing ChargeItems from an Account. Invoice containing collected ChargeItems from an Account with calculated individual and total price for Billing purpose. """ resource_type = "Invoice" def __init__(self, jsondict=None, strict=True): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.account = None """ Account that is being balanced. Type `FHIRReference` (represented as `dict` in JSON). """ self.cancelledReason = None """ Reason for cancellation of this Invoice. Type `str`. """ self.date = None """ Invoice date / posting date. Type `FHIRDate` (represented as `str` in JSON). """ self.identifier = None """ Business Identifier for item. List of `Identifier` items (represented as `dict` in JSON). """ self.issuer = None """ Issuing Organization of Invoice. Type `FHIRReference` (represented as `dict` in JSON). """ self.lineItem = None """ Line items of this Invoice. List of `InvoiceLineItem` items (represented as `dict` in JSON). """ self.note = None """ Comments made about the invoice. List of `Annotation` items (represented as `dict` in JSON). """ self.participant = None """ Participant in creation of this Invoice. List of `InvoiceParticipant` items (represented as `dict` in JSON). """ self.paymentTerms = None """ Payment details. Type `str`. """ self.recipient = None """ Recipient of this invoice. Type `FHIRReference` (represented as `dict` in JSON). """ self.status = None """ draft | issued | balanced | cancelled | entered-in-error. Type `str`. """ self.subject = None """ Recipient(s) of goods and services. Type `FHIRReference` (represented as `dict` in JSON). """ self.totalGross = None """ Gross total of this Invoice. Type `Money` (represented as `dict` in JSON). """ self.totalNet = None """ Net total of this Invoice. Type `Money` (represented as `dict` in JSON). """ self.totalPriceComponent = None """ Components of Invoice total. List of `InvoiceLineItemPriceComponent` items (represented as `dict` in JSON). """ self.type = None """ Type of Invoice. Type `CodeableConcept` (represented as `dict` in JSON). """ super(Invoice, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(Invoice, self).elementProperties() js.extend([ ("account", "account", fhirreference.FHIRReference, False, None, False), ("cancelledReason", "cancelledReason", str, False, None, False), ("date", "date", fhirdate.FHIRDate, False, None, False), ("identifier", "identifier", identifier.Identifier, True, None, False), ("issuer", "issuer", fhirreference.FHIRReference, False, None, False), ("lineItem", "lineItem", InvoiceLineItem, True, None, False), ("note", "note", annotation.Annotation, True, None, False), ("participant", "participant", InvoiceParticipant, True, None, False), ("paymentTerms", "paymentTerms", str, False, None, False), ("recipient", "recipient", fhirreference.FHIRReference, False, None, False), ("status", "status", str, False, None, True), ("subject", "subject", fhirreference.FHIRReference, False, None, False), ("totalGross", "totalGross", money.Money, False, None, False), ("totalNet", "totalNet", money.Money, False, None, False), ("totalPriceComponent", "totalPriceComponent", InvoiceLineItemPriceComponent, True, None, False), ("type", "type", codeableconcept.CodeableConcept, False, None, False), ]) return js from . import backboneelement class InvoiceLineItem(backboneelement.BackboneElement): """ Line items of this Invoice. Each line item represents one charge for goods and services rendered. Details such as date, code and amount are found in the referenced ChargeItem resource. """ resource_type = "InvoiceLineItem" def __init__(self, jsondict=None, strict=True): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.chargeItemCodeableConcept = None """ Reference to ChargeItem containing details of this line item or an inline billing code. Type `CodeableConcept` (represented as `dict` in JSON). """ self.chargeItemReference = None """ Reference to ChargeItem containing details of this line item or an inline billing code. Type `FHIRReference` (represented as `dict` in JSON). """ self.priceComponent = None """ Components of total line item price. List of `InvoiceLineItemPriceComponent` items (represented as `dict` in JSON). """ self.sequence = None """ Sequence number of line item. Type `int`. """ super(InvoiceLineItem, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(InvoiceLineItem, self).elementProperties() js.extend([ ("chargeItemCodeableConcept", "chargeItemCodeableConcept", codeableconcept.CodeableConcept, False, "chargeItem", True), ("chargeItemReference", "chargeItemReference", fhirreference.FHIRReference, False, "chargeItem", True), ("priceComponent", "priceComponent", InvoiceLineItemPriceComponent, True, None, False), ("sequence", "sequence", int, False, None, False), ]) return js class InvoiceLineItemPriceComponent(backboneelement.BackboneElement): """ Components of total line item price. The price for a ChargeItem may be calculated as a base price with surcharges/deductions that apply in certain conditions. A ChargeItemDefinition resource that defines the prices, factors and conditions that apply to a billing code is currently under development. The priceComponent element can be used to offer transparency to the recipient of the Invoice as to how the prices have been calculated. """ resource_type = "InvoiceLineItemPriceComponent" def __init__(self, jsondict=None, strict=True): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.amount = None """ Monetary amount associated with this component. Type `Money` (represented as `dict` in JSON). """ self.code = None """ Code identifying the specific component. Type `CodeableConcept` (represented as `dict` in JSON). """ self.factor = None """ Factor used for calculating this component. Type `float`. """ self.type = None """ base | surcharge | deduction | discount | tax | informational. Type `str`. """ super(InvoiceLineItemPriceComponent, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(InvoiceLineItemPriceComponent, self).elementProperties() js.extend([ ("amount", "amount", money.Money, False, None, False), ("code", "code", codeableconcept.CodeableConcept, False, None, False), ("factor", "factor", float, False, None, False), ("type", "type", str, False, None, True), ]) return js class InvoiceParticipant(backboneelement.BackboneElement): """ Participant in creation of this Invoice. Indicates who or what performed or participated in the charged service. """ resource_type = "InvoiceParticipant" def __init__(self, jsondict=None, strict=True): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.actor = None """ Individual who was involved. Type `FHIRReference` (represented as `dict` in JSON). """ self.role = None """ Type of involvement in creation of this Invoice. Type `CodeableConcept` (represented as `dict` in JSON). """ super(InvoiceParticipant, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(InvoiceParticipant, self).elementProperties() js.extend([ ("actor", "actor", fhirreference.FHIRReference, False, None, True), ("role", "role", codeableconcept.CodeableConcept, False, None, False), ]) return js import sys try: from . import annotation except ImportError: annotation = sys.modules[__package__ + '.annotation'] try: from . import codeableconcept except ImportError: codeableconcept = sys.modules[__package__ + '.codeableconcept'] try: from . import fhirdate except ImportError: fhirdate = sys.modules[__package__ + '.fhirdate'] try: from . import fhirreference except ImportError: fhirreference = sys.modules[__package__ + '.fhirreference'] try: from . import identifier except ImportError: identifier = sys.modules[__package__ + '.identifier'] try: from . import money except ImportError: money = sys.modules[__package__ + '.money']
StarcoderdataPython
5016806
#!usr/bin/env python import os import sys ###################################### # Command-line arguments ###################################### print(sys.argv) # python reading_data.py first,second,3 ==> ['reading_data.py', 'first,second,3'] # python reading_data.py first, second, 3 ==> ['reading_data.py', 'first,', 'second,', '3'] # python reading_data.py first second 3 ==> ['reading_data.py', 'first', 'second', '3'] ###################################### # Exit status ###################################### filename=sys.argv[1] if not os.path.exists(filename): with open(filename,"w") as f: f.write("New file created\n") else: print("Error: file {} already exists".format(filename)) sys.exit(1) ###################################### # Environment variables ###################################### print("HOME:",os.environ.get("HOME","")) # dictionary.get() ==> if None then return 2nd parameter print("SHELL:",os.environ.get("SHELL","")) print("FRUIT:",os.environ.get("FRUIT","")) ###################################### # input() ###################################### name=input("Please enter name: ") getal=int(input("Please enter number: ")) print("Hello,",name, "number:",getal) # In Python2: use raw_input() instead of input(). input() == eval(raw_input(x)) ###################################### # STD streams ###################################### data=input("This is STDIN: ") print("Write to STDOUT: "+data) print("Generate error to STDERR: "+ data +1) # Concatenate string + int raises Type error
StarcoderdataPython
1653331
#!python import logging import sys import traceback from PyQt5.QtWidgets import QApplication from hdfinspect.display.view import HDFInspectMain def initialise_logging(default_level=logging.DEBUG): global _log_formatter _log_formatter = logging.Formatter( "%(asctime)s [%(name)s:L%(lineno)d] %(levelname)s: %(message)s") # Add a very verbose logging level logging.addLevelName(5, 'TRACE') # Capture all warnings logging.captureWarnings(True) # Remove default handlers root_logger = logging.getLogger() root_logger.handlers = [] # Stdout handler console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(_log_formatter) root_logger.addHandler(console_handler) # Default log level root_logger.setLevel(default_level) # Don't ever print all the debug logging from Qt logging.getLogger('PyQt5').setLevel(logging.INFO) def main(): initialise_logging(logging.DEBUG) log = logging.getLogger(__name__) sys.excepthook = lambda exc_type, exc_value, exc_traceback: log.error( "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))) app = QApplication(sys.argv) view = HDFInspectMain() view.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
StarcoderdataPython
11209324
#!/usr/bin/env bash #SBATCH --job-name=mlcommons-science-earthquake-a100 #SBATCH --output=mlcommons-science-earthquake-a100.out #SBATCH --error=mlcommons-science-earthquake-a100.err #SBATCH --partition=gpu #SBATCH --cpus-per-task=6 #SBATCH --mem=32G #SBATCH --time=06:00:00 #SBATCH --gres=gpu:a100:1 #SBATCH --account=ds6011-sp22-002 # record top ond gpustat output # ./sampleTop2.sh thf2bn ${SLURM_JOB_ID} 10 & GPU_TYPE="a100" PYTHON_VERSION="3.10.2" RESOURCE_DIR="/project/ds6011-sp22-002" # BASE=/scratch/$USER/${GPU_TYPE} BASE=${RESOURCE_DIR}/$USER/${GPU_TYPE} HOME=${BASE} REV="mar2022" VARIANT="-gregor" echo "Working in <$(pwd)>" echo "Base directory in <${BASE}>" echo "Overridden home in <${HOME}>" echo "Revision: <${REV}>" echo "Variant: <${VARIANT}>" echo "Python: <${PYTHON_VERSION}>" echo "GPU: <${GPU_TYPE}>" module load cuda cudnn nvidia-smi mkdir -p ${BASE} cd ${BASE} if [ ! -e "${BASE}/.local/python/${PYTHON_VESRION}" ] ; then tar Jxvf "${RESOURCE_DIR}/python-${PYTHON_VERSION}.tar.xz" -C "${BASE}" fi export LD_LIBRARY_PATH=${BASE}/.local/ssl/lib:$LD_LIBRARY_PATH echo "Python setup" if [ ! -e "${BASE}/ENV3/bin/activate" ]; then ${BASE}/.local/python/${PYTHON_VERSION}/bin/python3.10 -m venv ${BASE}/ENV3 fi echo "ENV3 Setup" source ${BASE}/ENV3/bin/activate python -m pip install -U pip wheel papermill if [ ! -e "${BASE}/mlcommons-data-earthquake" ]; then git clone https://github.com/laszewsk/mlcommons-data-earthquake.git "${BASE}/mlcommons-data-earthquake" else (cd ${BASE}/mlcommons-data-earthquake ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e "${BASE}/mlcommons" ]; then git clone https://github.com/laszewsk/mlcommons.git "${BASE}/mlcommons" else (cd ${BASE}/mlcommons ; \ git fetch origin ; \ git checkout main ; \ git reset --hard origin/main ; \ git clean -d --force) fi if [ ! -e ${BASE}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020 ]; then tar Jxvf ${BASE}/mlcommons-data-earthquake/data.tar.xz \ -C ${BASE}/mlcommons/benchmarks/earthquake mkdir -p ${BASE}/mlcommons/benchmarks/earthquake/data/EarthquakeDec2020/outputs fi (cd ${BASE}/mlcommons/benchmarks/earthquake/${REV} && \ python -m pip install -r requirements.txt) # prg >> xyz.out & (cd ${BASE}/mlcommons/benchmarks/earthquake/${REV} && \ cp "FFFFWNPFEARTHQ_newTFTv29${VARIANT}.ipynb" FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb) (cd mlcommons/benchmarks/earthquake/mar2022 && \ papermill FFFFWNPFEARTHQ_newTFTv29-$USER.ipynb FFFFWNPFEARTHQ_newTFTv29-$USER-$GPU_TYPE.ipynb --no-progress-bar --log-output --log-level INFO)
StarcoderdataPython
4916421
#!/usr/bin/env python # _*_coding:utf-8_*_ from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from handlers.base import engine BaseModel = declarative_base() # 新建表 def init_db(): BaseModel.metadata.create_all(engine) # 删除表 def drop_db(): BaseModel.metadata.drop_all(engine) # ---------------------------------------公司---------------------------------------------------- # 多对多 用户组--设备组 userGroup_deviceGroup = Table('userGroup_deviceGroup', BaseModel.metadata, Column('userGroup_id', ForeignKey('userGroup.id'), primary_key=True), Column('deviceGroup_id', ForeignKey('deviceGroup.id'), primary_key=True) ) # 多对多 用户组--资源组 userGroup_resGroup = Table('userGroup_resGroup', BaseModel.metadata, Column('userGroup_id', ForeignKey('userGroup.id'), primary_key=True), Column('resGroup_id', ForeignKey('resGroup.id'), primary_key=True) ) # 公司表 class Company(BaseModel): __tablename__ = 'company' id = Column(Integer, Sequence('company_id_seq'), primary_key=True) # id code = Column(String(11), unique=True, nullable=True) # 公司编码 name = Column(String(32)) # 公司名称 address = Column(String(64)) # 公司地址 parent = Column(String(11)) # 公司母公司 data = Column(DATE) # 新建时间 user_group = relationship("UserGroup", backref="company") # 对应的用户组 user = relationship("User", backref="company") # 对应的用户 devices = relationship("Device", backref="company") # 对应的设备 device_time_switch = relationship("DeviceTimeSwitch", backref="company") # 对应的定时开关机表 device_week = relationship("DeviceWeek", backref="company") # 对应的定时开关每周 device_day = relationship("DeviceDay", backref="company") # 对应的定时开关机每天 device_group = relationship("DeviceGroup", backref="company") # 对应的设备组 resources_group = relationship("ResGroup", backref="company") # 对应的资源组 res_text = relationship("ResText", backref="company") # 对应的文字资源 res_image = relationship("ResImage", backref="company") # 对应的图片资源 res_video = relationship("ResVideo", backref="company") # 对应的视频资源 my_task = relationship("MyTask", backref="company") # 对应的任务 # ---------------------------------------用户---------------------------------------------------- # 多对多 用户--用户组 user_userGroup = Table('user_userGroup', BaseModel.metadata, Column('user_id', ForeignKey('user.id'), primary_key=True), Column('userGroup_id', ForeignKey('userGroup.id'), primary_key=True) ) # 用户组表 class UserGroup(BaseModel): __tablename__ = 'userGroup' id = Column(Integer, Sequence('userGroup_id_seq'), primary_key=True) # id name = Column(String(32)) # 用户组名称 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 user = relationship('User', secondary=user_userGroup, back_populates='userGroup') deviceGroup = relationship('DeviceGroup', secondary=userGroup_deviceGroup, back_populates='userGroup') resGroup = relationship('ResGroup', secondary=userGroup_resGroup, back_populates='userGroup') # 用户表 class User(BaseModel): __tablename__ = 'user' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id username = Column(String(32)) # 用户名 password = Column(CHAR(64)) # 密码 email = Column(String(32)) # 邮箱 is_active = Column(BOOLEAN) # 是否激活 is_admin = Column(BOOLEAN) # 是否管理员 data = Column(DATE) # 新建时间 tell_phone = Column(CHAR(11)) # 电话号码 my_task = relationship("MyTask", backref="user") # 对应的任务 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') # ---------------------------------------设备---------------------------------------------------- # 设备分屏数量 class DeviceScreenNumber(BaseModel): __tablename__ = 'deviceScreenNumber' id = Column(Integer, Sequence('deviceScreenNumber_id_seq'), primary_key=True) # id name = Column(String(32)) # 设备分屏名称 value = Column(String(32)) # 设备分屏值 # 设备组表 class DeviceGroup(BaseModel): __tablename__ = 'deviceGroup' id = Column(Integer, Sequence('deviceGroup_id_seq'), primary_key=True) # id name = Column(String(32)) # 设备组名称 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 device_time_switch_id = Column(Integer, ForeignKey('device_timeSwitch.id')) # 外键 公司 resGroup_id = Column(Integer, ForeignKey('resGroup.id')) # 外键 资源组 device = relationship("Device", backref="deviceGroup") # 对应设备 userGroup = relationship('UserGroup', secondary=userGroup_deviceGroup, back_populates='deviceGroup') # 设备表 class Device(BaseModel): __tablename__ = 'device' device_id = Column(String(64), primary_key=True) # 设备id device_id_s = Column(CHAR(6)) # 设备预留码 device_name = Column(String(32)) # 设备名称 status = Column(String(16)) # 设备状态 是否审核 ip = Column(String(64)) # 服务器ip port = Column(String(6)) # 服务器端口号 data = Column(DATE) # 新建时间 device_audio = Column(String(16)) # 设备音量 model = Column(String(32)) # 设备型号 board_model = Column(String(32)) # 主板型号 screen_size = Column(String(32)) # 屏幕尺寸 screen_resolution = Column(String(32)) # 屏幕分辨率 screen_number = Column(String(32)) # 分屏数量 cpu_model = Column(String(32)) # cpu型号 cpu_num = Column(String(32)) # cpu数量 ram_model = Column(String(32)) # 内存型号 ram_size = Column(String(32)) # 内存大小 mac_address = Column(String(32)) # mac地址 power_type = Column(String(32)) # 供电形式 1、电源 2、电池 3、电源+电池 voltage = Column(String(32)) # 供电电压 power_consumption = Column(String(32)) # 耗电量 device_position = Column(String(32)) # 设备安装位置 is_horn = Column(String(16)) # 是否有喇叭 device_use = Column(String(32)) # 设备用途 ad_environment = Column(String(32)) # 广告机安装环境 manufacturer = Column(String(32)) # 广告机生产商 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 deviceGroup_id = Column(Integer, ForeignKey('deviceGroup.id')) # 外键 设备组 # ---------------------------------------资源---------------------------------------------------- # 多对多 文字资源--资源组 resText_resGroup = Table('resText_resGroup', BaseModel.metadata, Column('resText_id', ForeignKey('resText.id'), primary_key=True), Column('resGroup_id', ForeignKey('resGroup.id'), primary_key=True) ) # 多对多 图片资源--资源组 resImage_resGroup = Table('resImage_resGroup', BaseModel.metadata, Column('resImage_id', ForeignKey('resImage.id'), primary_key=True), Column('resGroup_id', ForeignKey('resGroup.id'), primary_key=True) ) # 多对多 视频资源--资源组 resVideo_resGroup = Table('resVideo_resGroup', BaseModel.metadata, Column('resVideo_id', ForeignKey('resVideo.id'), primary_key=True), Column('resGroup_id', ForeignKey('resGroup.id'), primary_key=True) ) # 多对多 网站资源--资源组 resWeb_resGroup = Table('resWeb_resGroup', BaseModel.metadata, Column('resWeb_id', ForeignKey('resWeb.id'), primary_key=True), Column('resGroup_id', ForeignKey('resGroup.id'), primary_key=True) ) # 资源组表 class ResGroup(BaseModel): __tablename__ = 'resGroup' id = Column(Integer, Sequence('resGroup_id_seq'), primary_key=True) # id name = Column(String(32)) # 资源组名称 data = Column(DATE) # 新建时间 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 resText = relationship('ResText', secondary=resText_resGroup, back_populates='resGroup') resImage = relationship('ResImage', secondary=resImage_resGroup, back_populates='resGroup') resVideo = relationship('ResVideo', secondary=resVideo_resGroup, back_populates='resGroup') resWeb = relationship('ResWeb', secondary=resWeb_resGroup, back_populates='resGroup') userGroup = relationship('UserGroup', secondary=userGroup_resGroup, back_populates='resGroup') deviceGroup = relationship("DeviceGroup", backref="resGroup") # 对应的设备组 # 文字资源表 class ResText(BaseModel): __tablename__ = 'resText' id = Column(Integer, Sequence('resText_id_seq'), primary_key=True) # 资源id name = Column(String(32)) # 资源名称 content = Column(String(255)) # 资源内容 memo = Column(String(255)) # 资源备注 data = Column(DATE) # 资源新建时间 is_able = Column(String(16)) # 是否审批通过 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 resGroup = relationship('ResGroup', secondary=resText_resGroup, back_populates='resText') # 图片资源表 class ResImage(BaseModel): __tablename__ = 'resImage' id = Column(Integer, Sequence('resImage_id_seq'), primary_key=True) # 资源id name = Column(String(32)) # 资源名称 path = Column(String(128)) # 资源路径 memo = Column(String(255)) # 资源备注 data = Column(DATE) # 资源新建时间 is_able = Column(String(16)) # 是否审批通过 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 resGroup = relationship('ResGroup', secondary=resImage_resGroup, back_populates='resImage') # 视频资源表 class ResVideo(BaseModel): __tablename__ = 'resVideo' id = Column(Integer, Sequence('resVideo_id_seq'), primary_key=True) # 资源id name = Column(String(32)) # 资源名称 path = Column(String(128)) # 资源路径 memo = Column(String(255)) # 资源备注 data = Column(DATE) # 资源新建时间 is_able = Column(String(16)) # 是否审批通过 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 resGroup = relationship('ResGroup', secondary=resVideo_resGroup, back_populates='resVideo') # 网站资源 class ResWeb(BaseModel): __tablename__ = 'resWeb' id = Column(Integer, Sequence('resWeb_id_seq'), primary_key=True) # 资源id name = Column(String(32)) # 资源名称 content = Column(String(128)) # 资源内容 memo = Column(String(255)) # 资源备注 data = Column(DATE) # 资源新建时间 is_able = Column(String(16)) # 是否审批通过 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 resGroup = relationship('ResGroup', secondary=resWeb_resGroup, back_populates='resWeb') # ---------------------------------------定时器表---------------------------------------------------- # 定时开关机表 class DeviceTimeSwitch(BaseModel): __tablename__ = 'device_timeSwitch' id = Column(Integer, Sequence('device_timeSwitch_id_seq'), primary_key=True) # id name = Column(String(32)) # 名称 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 device_week = relationship("DeviceWeek", backref="device_timeSwitch", cascade="delete, delete-orphan", single_parent=True) # 对应的定时开关每周 device_group = relationship("DeviceGroup", backref="device_timeSwitch") # 对应的设备组 # 定时开关机--周(单位/天) class DeviceWeek(BaseModel): __tablename__ = 'device_week' id = Column(Integer, Sequence('device_week_id_seq'), primary_key=True) # id name = Column(String(32)) # 资源名称 device_timeSwitch_id = Column(Integer, ForeignKey('device_timeSwitch.id')) # 外键 定时开关机表 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 device_day = relationship("DeviceDay", backref="device_week", cascade="delete, delete-orphan", single_parent=True) # 对应的定时开关机每天 # 定时开关机--天(单位/小时) class DeviceDay(BaseModel): __tablename__ = 'device_day' id = Column(Integer, Sequence('device_day_id_seq'), primary_key=True) # id name = Column(String(32)) # 资源名称 time = Column(Time) # 时间 screen = Column(String(32)) # 设备屏幕 开,关 device_week_id = Column(Integer, ForeignKey('device_week.id')) # 外键 定时开关机--周 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # 任务 class MyTask(BaseModel): __tablename__ = 'my_task' id = Column(Integer, Sequence('my_task_id_seq'), primary_key=True) # id name = Column(String(32)) # 任务名称 time = Column(DateTime) # 时间 type = Column(String(16)) # 任务类型 user_id = Column(Integer, ForeignKey('user.id')) # 外键 用户 company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 my_task_content = relationship("MyTaskContent", backref="my_task", cascade="delete, delete-orphan", single_parent=True) # 对应的任务内容 # 任务内容 class MyTaskContent(BaseModel): __tablename__ = 'my_task_content' id = Column(Integer, Sequence('my_task_content_id_seq'), primary_key=True) # id device_id = Column(String(64)) # 设备id from_user = Column(String(32)) # 用户名 memo = Column(String(255)) # 备注 new_time = Column(DateTime) # 新建时间 send_time = Column(DateTime) # 发送时间 send_data = Column(Text) # 发送的数据 request_data = Column(Text) # 返回的数据 request_time = Column(DateTime) # 返回的时间 my_task_id = Column(Integer, ForeignKey('my_task.id')) # 外键 任务 # drop_db() # init_db()
StarcoderdataPython
8012189
""" Python program to determine whether someone has diabetes or not. """ #taking inputs glucose_conc = int(input("Enter your glucose concentration: ")) #main working tree if glucose_conc < 100: bMi = int(input("Enter your BMI: ")) if bMi < 30: Age = int(input("Enter your Age: ")) if Age < 31: if glucose_conc < 127: print("Patient is not diabetic") else: blood_pressure = int(input("Enter blood pressure: ")) if blood_pressure >= 61: print("Patient is diabetic") else: print("Patient is not Diabetic") else: diab_pedi = int(input("Enter your diabetes pedigree: ")) if diab_pedi <1: if Age > 49: skin_thik = int(input("Enter your skin thickness: ")) if skin_thik > 27: print("Patient is diabetic.") else: print("Pateint is not diabetic") else: print("Patient is not diabetic") else: print("Paitent is diabetic") elif glucose_conc > 167: print("Patient is diabetic") else: no_of_times_admiited = int("Enter the number of times admitted: ") if no_of_times_admiited > 0: print("Patient is diabetic") else: hr2_serum_ins = int(input("Enter number of mLs taken: ")) if hr2_serum_ins > 138: bMi = int(input("Enter your BMI: ")) if bMi > 31: print("Patient is diabetics") else: print("Patient is not diabetic") else: print("Patient is not diabetic")
StarcoderdataPython
3226349
<reponame>IvLabs/udacity-self-driving-car<gh_stars>10-100 #parsing command line arguments import argparse #decoding camera images import base64 #for frametimestamp saving from datetime import datetime #reading and writing files import os #high level file operations import shutil #matrix math import numpy as np #real-time server import socketio #concurrent networking import eventlet #web server gateway interface import eventlet.wsgi #image manipulation from PIL import Image #web framework from flask import Flask #input output from io import BytesIO #load our saved model import tflearn from tflearn.layers.conv import conv_2d from tflearn.layers.core import fully_connected, input_data, flatten from tflearn.layers.normalization import batch_normalization from tflearn.layers.estimator import regression #helper class import utils #model #model # X_train=X_train.reshape([-1,66,200,3]) # Y_train=Y_train.reshape([-1,1]) #input layer network=input_data(shape=[None,66,200,3], name='input') #convolutional layers network=conv_2d(network, 24, activation='elu', strides=2, filter_size=5) # network=batch_normalization(network) network=conv_2d(network, 36, activation='elu', strides=2, filter_size=5) # network=batch_normalization(network) network=conv_2d(network, 48, activation='elu', strides=2, filter_size=5) # network=batch_normalization(network) network=conv_2d(network, 64, activation='elu', filter_size=3) # network=batch_normalization(network) network=conv_2d(network, 64, activation='elu', filter_size=3) # network=batch_normalization(network) #fully connected layers network=fully_connected(network, 100, activation='elu') # network=batch_normalization(network) network=fully_connected(network, 50, activation='elu') # network=batch_normalization(network) network=fully_connected(network, 10, activation='elu') # network=batch_normalization(network) network=fully_connected(network, 1) network=regression(network,optimizer='adam', learning_rate=0.0001, loss='mean_square', name='targets') model=tflearn.DNN(network) #initialize our server sio = socketio.Server() #our flask (web) app app = Flask(__name__) #init our model and image array as empty prev_image_array = None #set min/max speed for our autonomous car MAX_SPEED = 25 MIN_SPEED = 10 #and a speed limit speed_limit = MAX_SPEED #registering event handler for the server @sio.on('telemetry') def telemetry(sid, data): if data: # The current steering angle of the car steering_angle = float(data["steering_angle"]) # The current throttle of the car, how hard to push peddle throttle = float(data["throttle"]) # The current speed of the car speed = float(data["speed"]) # The current image from the center camera of the car image = Image.open(BytesIO(base64.b64decode(data["image"]))) try: image = np.asarray(image) # from PIL image to numpy array image = utils.preprocess(image) # apply the preprocessing image = np.array([image]) # the model expects 4D array image=image.reshape([-1,66,200,3]) # predict the steering angle for the image steering_angle = float(model.predict(image)) # lower the throttle as the speed increases # if the speed is above the current speed limit, we are on a downhill. # make sure we slow down first and then go back to the original max speed. global speed_limit if speed > speed_limit: speed_limit = MIN_SPEED # slow down else: speed_limit = MAX_SPEED throttle = 1.0 - steering_angle**2 - (speed/speed_limit)**2 print('{} {} {}'.format(steering_angle, throttle, speed)) send_control(steering_angle, throttle) except Exception as e: print(e) # save frame if args.image_folder != '': timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3] image_filename = os.path.join(args.image_folder, timestamp) image.save('{}.jpg'.format(image_filename)) else: sio.emit('manual', data={}, skip_sid=True) @sio.on('connect') def connect(sid, environ): print("connect ", sid) send_control(0, 0) def send_control(steering_angle, throttle): sio.emit( "steer", data={ 'steering_angle': steering_angle.__str__(), 'throttle': throttle.__str__() }, skip_sid=True) if __name__ == '__main__': #load model model.load("autonomous-driving-car.tflearn") app = socketio.Middleware(sio, app) # deploy as an eventlet WSGI server eventlet.wsgi.server(eventlet.listen(('', 4567)), app)
StarcoderdataPython
9708190
import csv from django.core.management.base import BaseCommand from operaQuizbot.helpers import facebook_get_json from operaQuizbot.models import FacebookPage, OperaCategory class Command(BaseCommand): help = "Adds the operas from a CSV file." def add_arguments(self, parser): pass def handle(self, *args, **options): with open('operaQuizbot/management/commands/fbpages.csv', 'r') as f: # Open the opera categories CSV dr = csv.DictReader(f, dialect='excel') dr = [x for x in dr] for x in dr: print(x) for row in dr: if row['name']: res = facebook_get_json('search', params={"type": "page", "q": row['name']}) print(res) page, _ = FacebookPage.objects.get_or_create(facebook_id=res["data"][0]["id"], name=res["data"][0]["name"]) categories = row['categories'].split("/") categories = [OperaCategory.objects.get_or_create(name=x)[0] for x in categories] for x in categories: x.save() page.categories.add(x) self.stdout.write(self.style.SUCCESS("Imported the Facebook Pages!"))
StarcoderdataPython
8088523
import numpy as np import pandas as pd from ploomber.testing import pandas as pd_t def test_nulls_in_columns(tmp_directory): df = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10)}) df.to_csv('data.csv', index=False) assert not pd_t.nulls_in_columns(['x', 'y'], 'data.csv') df = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10)}) df.iloc[0, 0] = np.nan df.to_csv('data.csv', index=False) assert pd_t.nulls_in_columns(['x', 'y'], 'data.csv') def test_distinct_values_in_column(tmp_directory): df = pd.DataFrame({'x': range(5)}) df.to_csv('data.csv', index=False) assert pd_t.distinct_values_in_column('x', 'data.csv') == set(range(5)) def test_duplicates_in_column(tmp_directory): df = pd.DataFrame({'x': np.random.randint(0, 5, size=10)}) df.to_csv('data.csv', index=False) assert pd_t.duplicates_in_column('x', 'data.csv') df = pd.DataFrame({'x': range(10)}) df.to_csv('data.csv', index=False) assert not pd_t.duplicates_in_column('x', 'data.csv') def test_range_in_column(tmp_directory): df = pd.DataFrame({'x': range(5)}) df.to_csv('data.csv', index=False) assert pd_t.range_in_column('x', 'data.csv') == (0, 4)
StarcoderdataPython
4801656
<filename>usaspending_api/broker/helpers/delete_fabs_transactions.py import logging from usaspending_api.common.helpers.timing_helpers import timer from usaspending_api.broker.helpers.delete_stale_fabs import delete_stale_fabs from usaspending_api.broker.helpers.store_deleted_fabs import store_deleted_fabs logger = logging.getLogger("console") def delete_fabs_transactions(ids_to_delete, do_not_log_deletions): """ ids_to_delete are afa_generated_unique ids """ if ids_to_delete: if do_not_log_deletions is False: store_deleted_fabs(ids_to_delete) with timer("deleting stale FABS data", logger.info): update_award_ids = delete_stale_fabs(ids_to_delete) else: update_award_ids = [] logger.info("Nothing to delete...") return update_award_ids
StarcoderdataPython
5032012
<reponame>psavery/HPCCloud import os, time from wslink import register as exportRpc from paraview import simple, servermanager from paraview.web import protocols as pv_protocols from vtkmodules.vtkCommonCore import vtkUnsignedCharArray, vtkCollection from vtkmodules.vtkCommonDataModel import vtkImageData from vtkmodules.vtkPVClientServerCoreRendering import vtkPVRenderView from vtkmodules.vtkPVServerManagerRendering import vtkSMPVRepresentationProxy, vtkSMTransferFunctionProxy, vtkSMTransferFunctionManager from vtkmodules.vtkWebCore import vtkDataEncoder class ParaViewLite(pv_protocols.ParaViewWebProtocol): def __init__(self, **kwargs): super(pv_protocols.ParaViewWebProtocol, self).__init__() self.lineContext = None @exportRpc("paraview.lite.proxy.name") def getProxyName(self, pid): proxy = self.mapIdToProxy(pid) if not proxy: return { 'id': pid, 'error': 'No proxy for id %s' % pid, } return { 'id': pid, 'group': proxy.GetXMLGroup(), 'name': proxy.GetXMLName(), 'label': proxy.GetXMLLabel(), } @exportRpc("paraview.lite.camera.get") def getCamera(self, viewId): view = self.getView(viewId) bounds = [-1, 1, -1, 1, -1, 1] if view and view.GetClientSideView().GetClassName() == 'vtkPVRenderView': rr = view.GetClientSideView().GetRenderer() bounds = rr.ComputeVisiblePropBounds() return { 'id': viewId, 'bounds': bounds, 'position': tuple(view.CameraPosition), 'viewUp': tuple(view.CameraViewUp), 'focalPoint': tuple(view.CameraFocalPoint), 'centerOfRotation': tuple(view.CenterOfRotation), } @exportRpc("paraview.lite.lut.get") def getLookupTableForArrayName(self, name, numSamples = 255): lutProxy = simple.GetColorTransferFunction(name) lut = lutProxy.GetClientSideObject() dataRange = lut.GetRange() delta = (dataRange[1] - dataRange[0]) / float(numSamples) colorArray = vtkUnsignedCharArray() colorArray.SetNumberOfComponents(3) colorArray.SetNumberOfTuples(numSamples) rgb = [ 0, 0, 0 ] for i in range(numSamples): lut.GetColor(dataRange[0] + float(i) * delta, rgb) r = int(round(rgb[0] * 255)) g = int(round(rgb[1] * 255)) b = int(round(rgb[2] * 255)) colorArray.SetTuple3(i, r, g, b) # Add the color array to an image data imgData = vtkImageData() imgData.SetDimensions(numSamples, 1, 1) aIdx = imgData.GetPointData().SetScalars(colorArray) # Use the vtk data encoder to base-64 encode the image as png, using no compression encoder = vtkDataEncoder() # two calls in a row crash on Windows - bald timing hack to avoid the crash. time.sleep(0.01); b64Str = encoder.EncodeAsBase64Jpg(imgData, 100) return { 'image': 'data:image/jpg;base64,' + b64Str, 'range': dataRange, 'name': name } @exportRpc("paraview.lite.lut.range.update") def updateLookupTableRange(self, arrayName, dataRange): lutProxy = simple.GetColorTransferFunction(arrayName) vtkSMTransferFunctionProxy.RescaleTransferFunction(lutProxy.SMProxy, dataRange[0], dataRange[1], False) self.getApplication().InvokeEvent('UpdateEvent') @exportRpc("paraview.lite.lut.preset") def getLookupTablePreset(self, presetName, numSamples = 512): lutProxy = simple.GetColorTransferFunction('__PRESET__') lutProxy.ApplyPreset(presetName, True) lut = lutProxy.GetClientSideObject() dataRange = lut.GetRange() delta = (dataRange[1] - dataRange[0]) / float(numSamples) colorArray = vtkUnsignedCharArray() colorArray.SetNumberOfComponents(3) colorArray.SetNumberOfTuples(numSamples) rgb = [ 0, 0, 0 ] for i in range(numSamples): lut.GetColor(dataRange[0] + float(i) * delta, rgb) r = int(round(rgb[0] * 255)) g = int(round(rgb[1] * 255)) b = int(round(rgb[2] * 255)) colorArray.SetTuple3(i, r, g, b) # Add the color array to an image data imgData = vtkImageData() imgData.SetDimensions(numSamples, 1, 1) aIdx = imgData.GetPointData().SetScalars(colorArray) # Use the vtk data encoder to base-64 encode the image as png, using no compression encoder = vtkDataEncoder() # two calls in a row crash on Windows - bald timing hack to avoid the crash. time.sleep(0.01); b64Str = encoder.EncodeAsBase64Jpg(imgData, 100) return { 'name': presetName, 'image': 'data:image/jpg;base64,' + b64Str } @exportRpc("paraview.lite.lut.set.preset") def applyPreset(self, arrayName, presetName): lutProxy = simple.GetColorTransferFunction(arrayName) lutProxy.ApplyPreset(presetName, True) self.getApplication().InvokeEvent('UpdateEvent') @exportRpc("paraview.lite.context.line.set") def updateLineContext(self, visible = False, p1 = [0, 0, 0], p2 = [1, 1, 1]): if not self.lineContext: self.lineContext = servermanager.extended_sources.HighResolutionLineSource(Resolution=2, Point1=p1, Point2=p2) self.lineRepresentation = simple.Show(self.lineContext) self.lineRepresentation.Visibility = 1 if visible else 0 self.lineContext.Point1 = p1 self.lineContext.Point2 = p2 self.getApplication().InvokeEvent('UpdateEvent') return self.lineContext.GetGlobalIDAsString()
StarcoderdataPython
6527458
# encoding: utf-8 # pylint: disable=C0103 # pylint: disable=too-many-arguments """ Clustering ========== Clustering and manifold learning -------------------------------- .. autosummary:: :toctree: generated/ rhythmic_patterns manifold_learning """ from sklearn import cluster from sklearn import manifold __all__ = ['rhythmic_patterns', 'manifold_learning'] def rhythmic_patterns(data, n_clusters=4, method='kmeans'): """Clustering of rhythmic patterns from feature map. Parameters ---------- data : np.ndarray feature map n_clusters : int number of clusters method : str clustering method Returns ------- c_labs : np.ndarray cluster labels for each data point c_centroids : np.ndarray cluster centroids c_method : sklearn.cluster sklearn cluster method object Notes -------- Based on the feature map clustering analysis introduced in [1]. References -------- .. [1] Rocamora, <NAME> "Tools for detection and classification of piano drum patterns from candombe recordings." 9th Conference on Interdisciplinary Musicology (CIM), Berlin, Germany. 2014. See Also -------- sklearn.cluster.KMeans """ if method == 'kmeans': # initialize k-means algorithm c_method = cluster.KMeans(n_clusters=n_clusters, init='k-means++', n_init=10) # cluster data using k-means c_method.fit(data) # cluster centroids c_centroids = c_method.cluster_centers_ # predict cluster for each data point c_labs = c_method.predict(data) else: raise AttributeError("Clustering method not implemented.") return c_labs, c_centroids, c_method def manifold_learning(data, method='isomap', n_neighbors=7, n_components=3): """Manifold learning for dimensionality reduction of rhythmic patterns data. Parameters ---------- data : np.array feature map method : (check) (check) n_neighbors : int number of neighbors for each dat point n_components : int number of coordinates for the manifold Returns ------- embedding : np.array lower-dimensional embedding of the data Notes -------- Based on the dimensionality reduction for rhythmic patterns introduced in [1]. References -------- .. [1] Rocamora, Jure, Biscainho "Tools for detection and classification of piano drum patterns from candombe recordings." 9th Conference on Interdisciplinary Musicology (CIM), Berlin, Germany. 2014. """ if method == 'isomap': # fit manifold from data using isomap algorithm method = manifold.Isomap(n_neighbors=n_neighbors, n_components=n_components).fit(data) # transform data to low-dimension representation embedding = method.transform(data) else: raise AttributeError("Manifold learning method not implemented.") return embedding
StarcoderdataPython
320264
""" Sponge Knowledge Base Processors metadata """ from org.openksavi.sponge.examples import PowerEchoMetadataAction class UpperEchoAction(Action): def onConfigure(self): self.withFeatures({"visibility":False}) def onCall(self, text): return None def onLoad(): sponge.enableJava(PowerEchoMetadataAction)
StarcoderdataPython
9622763
<gh_stars>0 """ Purpose: Mapquest Helpers This library is used to wrap mapquest API calls and handle authentication """ # Python Library Imports import logging import os import re import requests ### # Properties ### mapquest_api_headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "accept-encoding": "gzip, deflate, sdch, br", "accept-language": "en-US,en;q=0.9", "cache-control": "no-cache", "pragma": "no-cache", "referer": "http://www.mapquestapi.com/", "upgrade-insecure-requests": "1", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", } ### # Mapquest Helpers ### def get_mapquest_api_key(public_key_file="~/.mapquest/public_key.txt"): """ Purpose: Get the mapquest API from the environment Args: public_key_file (String): filename of the public key token file Return: mapquest_api_key (String): MapQuest public key """ public_key_file = os.path.expanduser(public_key_file) try: with open(public_key_file, "r") as public_key_file_obj: mapquest_api_key = public_key_file_obj.read().strip("\n") except Exception as err: raise Exception(f"Failed to Get Public Key for Mapquest: {public_key_file}") return mapquest_api_key def get_directions_between_two_addresses(mapquest_api_key, address_1, address_2): """ Purpose: Get directions between two addresses Leverages Mapquest API: https://developer.mapquest.com/documentation/directions-api/route/get/ Args: address_1 (String): Address to use as start point of travel address_2 (String): Address to use as end destination of travel Return: directions (Dict): Dict of the directions between the two locations """ mapquest_direcions_url = ( f"http://www.mapquestapi.com/directions/v2/route?key={mapquest_api_key}" f"&from={address_1}&to={address_2}" ) logging.info(f"Fetching Directions: {mapquest_direcions_url}") mapquest_direcions_response = requests.get( mapquest_direcions_url, headers=mapquest_api_headers ) if mapquest_direcions_response.status_code == 200: raw_mapquest_direcions = mapquest_direcions_response.json() else: logging.error( "Got Failure Response from Indeed.com: " f"{mapquest_direcions_response.status_code}" ) raw_mapquest_direcions = {} return raw_mapquest_direcions
StarcoderdataPython
3410362
# Generated by Django 3.0.7 on 2020-06-23 01:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('draft', '0002_auto_20200612_0522'), ] operations = [ migrations.RenameField( model_name='draft', old_name='abstract', new_name='description', ), ]
StarcoderdataPython
5093312
<reponame>vilhelmprytz/Kanmail<filename>kanmail/version.py import json from functools import lru_cache from os import path from typing import Dict from kanmail.settings.constants import CLIENT_ROOT @lru_cache(maxsize=1) def get_version_data() -> Dict[str, str]: version_filename = path.join(CLIENT_ROOT, 'static', 'dist', 'version.json') if not path.exists(version_filename): return { 'version': '0.0.0dev', 'channel': 'alpha', } with open(version_filename, 'r') as f: version_data = f.read() return json.loads(version_data) def get_version() -> str: version_data = get_version_data() return version_data['version']
StarcoderdataPython
197107
# -*- coding: utf-8 -*- from django.test import TestCase, RequestFactory from django.test.utils import override_settings from django.urls import reverse from django.contrib.auth.models import AnonymousUser from django.http import HttpResponseRedirect, HttpResponse from django.conf import settings from .. import middleware from . import utils as test_utils class XForwardedForMiddlewareTests(TestCase): def test_meta(self): """ Should add remote addr to request meta data """ req = RequestFactory().get('/') req.META['REMOTE_ADDR'] = '' self.assertEqual(req.META['REMOTE_ADDR'], '') http_x_fwd_for = 'evil.ip, foo.ip, org.ip' req.META['HTTP_X_FORWARDED_FOR'] = http_x_fwd_for self.assertEqual(req.META['HTTP_X_FORWARDED_FOR'], http_x_fwd_for) self.assertIsNone( middleware.XForwardedForMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) self.assertEqual(req.META['HTTP_X_FORWARDED_FOR'], http_x_fwd_for) self.assertEqual(req.META['REMOTE_ADDR'], 'org.ip') def test_meta_weird_format(self): """ Should add remote addr to request meta data """ req = RequestFactory().get('/') req.META['REMOTE_ADDR'] = '' self.assertEqual(req.META['REMOTE_ADDR'], '') http_x_fwd_for = 'evil.ip, foo.ip,,bar.ip, baz.ip, org.ip ' req.META['HTTP_X_FORWARDED_FOR'] = http_x_fwd_for self.assertEqual(req.META['HTTP_X_FORWARDED_FOR'], http_x_fwd_for) self.assertIsNone( middleware.XForwardedForMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) self.assertEqual(req.META['HTTP_X_FORWARDED_FOR'], http_x_fwd_for) self.assertEqual(req.META['REMOTE_ADDR'], 'org.ip') MIDDLEWARE_WITH_X_FWD = settings.MIDDLEWARE[:] if 'spirit.core.middleware.XForwardedForMiddleware' not in settings.MIDDLEWARE: MIDDLEWARE_WITH_X_FWD.append('spirit.core.middleware.XForwardedForMiddleware') @override_settings(MIDDLEWARE=MIDDLEWARE_WITH_X_FWD) def test_on_client(self): """ Should be called on a request """ class XForwardedForMiddlewareMock(middleware.XForwardedForMiddleware): _mock_calls = [] def process_request(self, request): self._mock_calls.append(request) return super(XForwardedForMiddlewareMock, self).process_request(request) org_mid, middleware.XForwardedForMiddleware = ( middleware.XForwardedForMiddleware, XForwardedForMiddlewareMock) try: self.client.get( reverse('spirit:index'), HTTP_X_FORWARDED_FOR='evil.ip, org.ip') finally: middleware.XForwardedForMiddleware = org_mid self.assertEqual(len(XForwardedForMiddlewareMock._mock_calls), 1) self.assertEqual( XForwardedForMiddlewareMock._mock_calls[0].META['REMOTE_ADDR'], 'org.ip') class PrivateForumMiddlewareTests(TestCase): def setUp(self): test_utils.cache_clear() self.user = test_utils.create_user() @override_settings(ST_PRIVATE_FORUM=True) def test_anonym_user(self): """ Should restrict the URL """ req = RequestFactory().get(reverse('spirit:index')) req.user = AnonymousUser() resp = ( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) self.assertIsInstance(resp, HttpResponseRedirect) self.assertEqual( resp['Location'], reverse(settings.LOGIN_URL) + '?next=/') @override_settings(ST_PRIVATE_FORUM=False) def test_anonym_user_non_private(self): """ Should not restrict the URL """ req = RequestFactory().get(reverse('spirit:index')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) @override_settings(ST_PRIVATE_FORUM=True) def test_authenticated_user(self): """ Should not restrict authenticated users """ req = RequestFactory().get(reverse('spirit:index')) req.user = self.user self.assertTrue(self.user.is_authenticated) self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) @override_settings(ST_PRIVATE_FORUM=False) def test_authenticated_user_not_private(self): """ Should not restrict authenticated users """ req = RequestFactory().get(reverse('spirit:index')) req.user = self.user self.assertTrue(self.user.is_authenticated) self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) @override_settings(ST_PRIVATE_FORUM=True) def test_auth_paths(self): """ Should not restrict auth paths """ req = RequestFactory().get(reverse('spirit:index')) req.user = AnonymousUser() self.assertIsInstance( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req), HttpResponseRedirect) req = RequestFactory().get(reverse('spirit:user:auth:login')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) req = RequestFactory().get(reverse('spirit:user:auth:register')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) req = RequestFactory().get(reverse('spirit:user:auth:logout')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) req = RequestFactory().get(reverse('spirit:user:auth:resend-activation')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) @override_settings(ST_PRIVATE_FORUM=True) def test_not_spirit(self): """ Should not restrict other apps URLs """ req = RequestFactory().get(reverse('spirit:index')) req.user = AnonymousUser() self.assertIsInstance( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req), HttpResponseRedirect) req = RequestFactory().get(reverse('admin:index')) req.user = AnonymousUser() self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) req = RequestFactory().get(reverse('admin:index')) req.user = self.user self.assertIsNone( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) @override_settings(ST_PRIVATE_FORUM=True) def test_on_client(self): """ Should be called on a request """ response = self.client.get(reverse('spirit:index')) self.assertEqual(response.status_code, 302) self.assertIsInstance(response, HttpResponseRedirect) self.assertTrue( reverse(settings.LOGIN_URL) + '?next=/' in response['Location']) test_utils.login(self) self.assertEqual( self.client.get(reverse('spirit:index')).status_code, 200) @override_settings(ST_PRIVATE_FORUM=False) def test_on_client_not_private(self): """ Should be called on a request """ self.assertEqual( self.client.get(reverse('spirit:index')).status_code, 200) @override_settings(ST_PRIVATE_FORUM=True) def test_restrict_apps(self): """ Should restrict the URLs """ url_names = [ 'spirit:topic:index-active', 'spirit:topic:private:index', 'spirit:category:index'] for url_name in url_names: url = reverse(url_name) req = RequestFactory().get(url) req.user = AnonymousUser() resp = ( middleware.PrivateForumMiddleware(lambda req: HttpResponse(status=500)) .process_request(req)) self.assertIsInstance(resp, HttpResponseRedirect) self.assertEqual( resp['Location'], reverse(settings.LOGIN_URL) + '?next=' + url)
StarcoderdataPython
1886792
__all__ = [ "cimac_id_to_cimac_participant_id", "get_property", "identity", "MetadataModel", "with_default_session", ] from functools import wraps from typing import Any, Dict, Optional, Tuple from flask import current_app from sqlalchemy.orm import Session from ...config.db import BaseModel # some simple functions to handle common process_as cases # the parameters for all process_as functions are # value : Any, context : dict[Column, Any] identity = lambda v, _: v cimac_id_to_cimac_participant_id = lambda cimac_id, _: cimac_id[:7] # this is a special-case handler, where any property in context # can be retrieved by using get_property(< key >) as a process_as function # # created to get the `object_url` of files after GCS URI formatting get_property = lambda prop: lambda _, context: ( [v for k, v in context.items() if k.name == prop] + [None] )[0] def with_default_session(f): """ For some `f` expecting a database session instance as a keyword argument, set the default value of the session keyword argument to the current app's database driver's session. We need to do this in a decorator rather than inline in the function definition because the current app is only available once the app is running and an application context has been pushed. """ @wraps(f) def wrapped(*args, **kwargs): if "session" not in kwargs: kwargs["session"] = current_app.extensions["sqlalchemy"].db.session return f(*args, **kwargs) return wrapped class MetadataModel(BaseModel): __abstract__ = True def primary_key_values(self) -> Optional[Tuple[Any]]: """ Returns a tuple of the values of the primary key values Special value None if all of the pk columns are None """ pk_map = self.primary_key_map() return tuple(pk_map.values()) if pk_map is not None else None def primary_key_map(self) -> Optional[Dict[str, Any]]: """ Returns a dict of Column: value for any primary key column. Special value None if all of the pk columns are None """ from .utils import _all_bases columns_to_check = [c for c in self.__table__.columns] for c in _all_bases(type(self)): if hasattr(c, "__table__"): columns_to_check.extend(c.__table__.columns) primary_key_values = {} for column in columns_to_check: if column.primary_key: value = getattr(self, column.name) primary_key_values[column] = value if all(v is None for v in primary_key_values.values()): return None # special value return primary_key_values def unique_field_values(self) -> Optional[Tuple[Any]]: """ Returns a tuple of all values that are uniquely constrained (pk or unique). Special value None if all of the unique columns are None """ from .utils import _all_bases columns_to_check = [c for c in self.__table__.columns] for c in _all_bases(type(self)): if hasattr(c, "__table__"): columns_to_check.extend(c.__table__.columns) unique_field_values = [] for column in columns_to_check: # column.primary_key == True for 1+ column guaranteed if column.unique or column.primary_key: value = getattr(self, column.name) unique_field_values.append(value) if all(v is None for v in unique_field_values): return None # special value return tuple(unique_field_values) def merge(self, other): """Merge column values from other into self, raising an error on conflicts between non-null fields.""" if self.__class__ != other.__class__: raise Exception( f"cannot merge {self.__class__} instance with {other.__class__} instance" ) # also need to handle columns for all superclasses from .utils import _all_bases for column in self.__table__.columns + [ c for b in _all_bases(type(self)) if hasattr(b, "__table__") for c in b.__table__.columns ]: if hasattr(self, column.name): current = getattr(self, column.name) incoming = getattr(other, column.name) if current is None: setattr(self, column.name, incoming) elif incoming is not None and current != incoming: pks = { col.name: value for col, value in self.primary_key_map().items() } raise Exception( f"found conflicting values for {self.__class__.__name__} {pks} for {column.name} : {current}!={incoming}" ) def to_dict(self) -> Dict[str, Any]: """Returns a dict of all non-null columns (by name) and their values""" # avoid circular imports from .utils import _all_bases columns_to_check = [c for c in type(self).__table__.columns] for b in _all_bases(type(self)): if hasattr(b, "__table__"): columns_to_check.extend(b.__table__.columns) ret = { c.name: getattr(self, c.name) for c in columns_to_check if hasattr(self, c.name) } ret = {k: v for k, v in ret.items() if v is not None} return ret @classmethod @with_default_session def get_by_id(cls, *id, session: Session): """ Returns an instance of this class with given the primary keys if it exists Special value None if no instance in the table matches the given values """ with current_app.app_context(): ret = session.query(cls).get(id) return ret
StarcoderdataPython
4841771
# <NAME> #This code integrates the 2 bhr files, but for those which don't have similar sameAs linke, but similar URI. #the sameAs links are integrated into the new file #30/04/2018 #Ver. 01 import rdflib from rdflib import Namespace, URIRef, Graph , Literal from SPARQLWrapper import SPARQLWrapper2, XML , RDF , JSON from rdflib.namespace import RDF, FOAF , SKOS ,RDFS import os os.chdir('C:\Users\Maral\Desktop') #sparql = SPARQLWrapper2("http://localhost:3030/Datasets/sparql") foaf = Namespace("http://xmlns.com/foaf/0.1/") skos = Namespace("http://www.w3.org/2004/02/skos/core#") gndo = Namespace("http://d-nb.info/standards/elementset/gnd#") jl = Namespace("http://data.judaicalink.org/ontology/") owl = Namespace ("http://www.w3.org/2002/07/owl#") edm = Namespace("http://www.europeana.eu/schemas/edm/") dc = Namespace ("http://purl.org/dc/elements/1.1/") graph= Graph() graph.parse('C:\\Users\\Maral\\Desktop\\bhr-new-enrich.rdf', format="turtle") dicsame = {} spar= """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX gndo: <http://d-nb.info/standards/elementset/gnd#> PREFIX pro: <http://purl.org/hpi/patchr#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX edm: <http://www.europeana.eu/schemas/edm/> PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dblp: <http://dblp.org/rdf/schema-2015-01-26#> PREFIX dcterms: <http://purl.org/dc/terms/> PREFIX dbpedia: <http://dbpedia.org/resource/> SELECT ?x ?desc ?abst #?pub where { ?x a foaf:Person. ?x jl:describedAt ?desc. ?x jl:hasAbstract ?abst. #?x jl:hasPublication ?pub #?x owl:sameAs ?same. } """ results = graph.query(spar) graph2= Graph() #graph2.parse('C:\\Users\\Maral\\Desktop\\bhr-final-02.ttl', format="turtle") graph2.parse('C:\\Users\\Maral\\Desktop\\bhr-final-03.ttl', format="turtle") graph2.bind('foaf',foaf) graph2.bind('skos',skos) graph2.bind('owl',owl) graph2.bind('jl',jl) spar2= """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX gndo: <http://d-nb.info/standards/elementset/gnd#> PREFIX pro: <http://purl.org/hpi/patchr#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX edm: <http://www.europeana.eu/schemas/edm/> PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dblp: <http://dblp.org/rdf/schema-2015-01-26#> PREFIX dcterms: <http://purl.org/dc/terms/> PREFIX dbpedia: <http://dbpedia.org/resource/> SELECT ?x where { ?x a foaf:Person. } """ results2 = graph2.query(spar2) for item2 in results2: #print item2 uri2org=item2[0] uri2 = uri2org.strip().lower() for item in results: uriorg = item[0] uri = item[0].strip().lower() desc = item[1].value abst = item[2].value #pub = item[3].value #print item if uri2 == uri: graph2.add((URIRef(uri2org) , jl.describedAt , Literal(desc))) graph2.add((URIRef(uri2org) , jl.hasAbstract , Literal(abst))) #graph2.add((URIRef(uri2org) , jl.hasPublication , Literal(pub))) #graph2.serialize(destination='bhr-final-03.ttl', format="turtle") graph2.serialize(destination='bhr-final-04.ttl', format="turtle")
StarcoderdataPython
6575177
<reponame>bcho/cached-property # -*- coding: utf-8 -*- """ test_threaded_cache_property.py ---------------------------------- Tests for `cached-property` module, threaded_cache_property. """ from time import sleep from threading import Thread, Lock import unittest from cached_property import threaded_cached_property class TestCachedProperty(unittest.TestCase): def test_cached_property(self): class Check(object): def __init__(self): self.total1 = 0 self.total2 = 0 @property def add_control(self): self.total1 += 1 return self.total1 @threaded_cached_property def add_cached(self): self.total2 += 1 return self.total2 c = Check() # The control shows that we can continue to add 1. self.assertEqual(c.add_control, 1) self.assertEqual(c.add_control, 2) # The cached version demonstrates how nothing new is added self.assertEqual(c.add_cached, 1) self.assertEqual(c.add_cached, 1) def test_reset_cached_property(self): class Check(object): def __init__(self): self.total = 0 @threaded_cached_property def add_cached(self): self.total += 1 return self.total c = Check() # Run standard cache assertion self.assertEqual(c.add_cached, 1) self.assertEqual(c.add_cached, 1) # Reset the cache. del c.add_cached self.assertEqual(c.add_cached, 2) self.assertEqual(c.add_cached, 2) def test_none_cached_property(self): class Check(object): def __init__(self): self.total = None @threaded_cached_property def add_cached(self): return self.total c = Check() # Run standard cache assertion self.assertEqual(c.add_cached, None) class TestThreadingIssues(unittest.TestCase): def test_threads(self): """ How well does this implementation work with threads?""" class Check(object): def __init__(self): self.total = 0 self.lock = Lock() @threaded_cached_property def add_cached(self): sleep(1) # Need to guard this since += isn't atomic. with self.lock: self.total += 1 return self.total c = Check() threads = [] for x in range(10): thread = Thread(target=lambda: c.add_cached) thread.start() threads.append(thread) for thread in threads: thread.join() self.assertEqual(c.add_cached, 1)
StarcoderdataPython
135752
n1 = int (input()) s1 = set(map(int,input().split())) n2 = int (input()) s2 = set(map(int,input().split())) print(len(s1.intersection(s2)))
StarcoderdataPython
6587014
<reponame>risk-frontiers/OasisIntegration import struct import sqlite3 import os import logging import complex_model.DefaultSettings as DS import time """ Implementation of ktool item/coverage/loss bin stream conversion tool including complex item data serialized with msgpack. """ _DEBUG = DS.RF_DEBUG_MODE if "RF_DEBUG_MODE" in os.environ: if isinstance(os.environ["RF_DEBUG_MODE"], str) and os.environ["RF_DEBUG_MODE"].lower() == "true": _DEBUG = True logging.basicConfig(level=logging.DEBUG if _DEBUG else logging.INFO, filename=DS.WORKER_LOG_FILE, format='[%(asctime)s: %(levelname)s/%(filename)s] %(message)s') SUPPORTED_GUL_STREAMS = {"item": (1, 1), "coverage": (1, 2), "loss": (2, 1)} DEFAULT_GUL_STREAM = SUPPORTED_GUL_STREAMS["loss"] def gulcalc_sqlite_fp_to_bin(working_dir, db_fp, output, num_sample, stream_id=DEFAULT_GUL_STREAM, oasis_event_batch=None): """This transforms a sqlite result table (rf format) into oasis loss binary stream :param working_dir: working directory :param db_fp: path to the sqlite database :param output: output stream where results will be written to :param num_sample: number of samples in result :param stream_id: item, coverage or loss stream id :param oasis_event_batch: event batch id attached to this process :return: OASIS compliant item or coverage binary stream """ start = time.time() logging.info("STARTED: Transforming sqlite losses into gulcalc item/loss binary stream for oasis_event_batch " + str(oasis_event_batch)) gulcalc_create_header(output, num_sample, stream_id) con = sqlite3.connect(db_fp) cur = con.cursor() cur.execute("SELECT count(*) FROM event_batches") num_partial = cur.fetchone()[0] cur.execute("SELECT batch_id FROM event_batches ORDER BY batch_id") add_first_separator = False rc = 0 for batch_id in cur.fetchall(): logging.info("RUNNING: Streaming partial loss " + str(1 + int(batch_id[0])) + "/" + str(num_partial) + " for oasis_event_batch " + str(oasis_event_batch)) batch_res_fp = os.path.join(working_dir, "oasis_loss_{0}.db".format(batch_id[0])) batch_res_con = sqlite3.connect(batch_res_fp) rc = rc + gulcalc_sqlite_to_bin(batch_res_con, output, add_first_separator) add_first_separator = True con.close() hours, rem = divmod(time.time() - start, 3600) minutes, seconds = divmod(rem, 60) exec_time = "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds) logging.info("COMPLETED: Successfully generated losses as gulcalc binary stream for event batch " + str(oasis_event_batch) + ": " + str(rc) + " rows were streamed in " + exec_time) def cursor_iterator(cursor, batchsize=100000): """An iterator that uses fetchmany to keep memory usage down :param cursor: a sqlite db cursor :param batchsize: size of the batch to be fetched :return: a generator constructed from fetchmany """ while True: results = cursor.fetchmany(batchsize) if not results: break for result in results: yield result def gulcalc_create_header(output, num_sample, stream_id=DEFAULT_GUL_STREAM): if stream_id not in list(SUPPORTED_GUL_STREAMS.values()) or not num_sample > 0: return stream_id = (stream_id[0] << 24) | stream_id[1] output.write(struct.pack('i', stream_id)) output.write(struct.pack('i', num_sample)) def gulcalc_sqlite_to_bin(con, output, add_first_separator): """This transforms a sqlite result table (rf format) into oasis loss binary stream :param con: sqlite connection to result batch :param output: output stream where results will be written to :param add_first_separator: boolean flag to add separator 0/0 for second, third, ... batches :return: OASIS compliant item or coverage binary stream """ cur = con.cursor() cur.execute("SELECT event_id, loc_id, sample_id, loss FROM oasis_loss ORDER BY event_id, loc_id, sample_id") last_key = (0, 0) rc = 0 for row in cursor_iterator(cur): current_key = (int(row[0]), int(row[1])) if not last_key == current_key: if not last_key == (0, 0) or add_first_separator: output.write(struct.pack('Q', 0)) # sidx/loss 0/0 as separator output.write(struct.pack('II', current_key[0], current_key[1])) last_key = (int(row[0]), int(row[1])) output.write(struct.pack('if', int(row[2]), float(row[3]))) rc = rc + 1 return rc if __name__ == "__main__": import sys if len(sys.argv) <= 1: print("missing working directory") else: working_directory = sys.argv[1] debug_output = sys.stdout.buffer samples = 1 if len(sys.argv) > 2: debug_output = open(sys.argv[2], 'w+b') if len(sys.argv) > 3: samples = int(sys.argv[2]) stream = (2, 1) if len(sys.argv) > 4: stream = int(sys.argv[3]) db_path = os.path.join(working_directory, 'riskfrontiersdbAUS_v2_6.db') gulcalc_sqlite_fp_to_bin(working_directory, db_path, debug_output, samples, stream)
StarcoderdataPython
5190506
import re import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc from urllib import urlencode import csv from product_spiders.items import Product, ProductLoaderWithNameStrip as ProductLoader from scrapy import log HERE = os.path.abspath(os.path.dirname(__file__)) REP = [',', '.', ':', '-', '&', '?', '(', ')', '/', '"', '+', '[', ']'] def normalized_name(name): name = name.replace("'", '') for r in REP: name = name.replace(r, ' ') name = ' '.join(name.split()).strip() name = '-'.join(name.split()) return name class KalahariSpider(BaseSpider): name = 'kalahari.com' allowed_domains = ['kalahari.com'] def start_requests(self): with open(os.path.join(HERE, 'products.csv')) as f: reader = csv.DictReader(f) for row in reader: sku = row['ProdCode'] prod_id = row['k_sku'] name = normalized_name(row['Title']) url = 'http://www.kalahari.com/home/%s/%s.aspx' url = url % (name, prod_id) yield Request(url, meta={'sku': sku, 'url': url}) def parse(self, response): if '500.html' in response.url: retries = response.meta.get('retries', 0) if retries < 3: yield Request(response.meta['url'], dont_filter=True, meta={'sku': response.meta['sku'], 'retries': retries + 1}) hxs = HtmlXPathSelector(response) if hxs.select('//p[@class="stock_status" and text()="Out of stock"]'): return loader = ProductLoader(item=Product(), response=response) loader.add_xpath('name', '//h1[@class="page_heading"]/text()') loader.add_value('url', response.url) loader.add_xpath('price', '//tr[@class="our_price"]//td[@class="amount"]/text()') loader.add_xpath('price', '//span[@class="price"]/text()') loader.add_value('sku', response.meta['sku']) yield loader.load_item()
StarcoderdataPython
4923580
import os import sys import numpy as np import open3d as o3d import torch import smplx def update_render_cam(cam_param, trans): ### NOTE: trans is the trans relative to the world coordinate!!! cam_R = np.transpose(trans[:-1, :-1]) cam_T = -trans[:-1, -1:] cam_T = np.matmul(cam_R, cam_T) #!!!!!! T is applied in the rotated coord cam_aux = np.array([[0,0,0,1]]) mat = np.concatenate([cam_R, cam_T],axis=-1) mat = np.concatenate([mat, cam_aux],axis=0) cam_param.extrinsic = mat return cam_param def create_lineset(x_range, y_range, z_range): gp_lines = o3d.geometry.LineSet() gp_pcd = o3d.geometry.PointCloud() points = np.stack(np.meshgrid(x_range, y_range, z_range), axis=-1) lines = [] for ii in range( x_range.shape[0]-1): for jj in range(y_range.shape[0]-1): lines.append(np.array([ii*x_range.shape[0]+jj, ii*x_range.shape[0]+jj+1])) lines.append(np.array([ii*x_range.shape[0]+jj, ii*x_range.shape[0]+jj+y_range.shape[0]])) points = np.reshape(points, [-1,3]) colors = np.random.rand(len(lines), 3)*0.5+0.5 gp_lines.points = o3d.utility.Vector3dVector(points) gp_lines.colors = o3d.utility.Vector3dVector(colors) gp_lines.lines = o3d.utility.Vector2iVector(np.stack(lines,axis=0)) gp_pcd.points = o3d.utility.Vector3dVector(points) return gp_lines, gp_pcd def color_hex2rgb(hex): h = hex.lstrip('#') return np.array( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) )/255 def get_body_model(type, gender, batch_size,device='cpu'): ''' type: smpl, smplx smplh and others. Refer to smplx tutorial gender: male, female, neutral batch_size: an positive integar ''' body_model_path = '/home/yzhang/body_models/VPoser' body_model = smplx.create(body_model_path, model_type=type, gender=gender, ext='npz', num_pca_comps=12, create_global_orient=True, create_body_pose=True, create_betas=True, create_left_hand_pose=True, create_right_hand_pose=True, create_expression=True, create_jaw_pose=True, create_leye_pose=True, create_reye_pose=True, create_transl=True, batch_size=batch_size ) if device == 'cuda': return body_model.cuda() else: return body_model
StarcoderdataPython
302897
# -*- coding: UTF-8 -*- class CustomBaseException(Exception): def __init__(self, prefix: str, arg: str, code: int, addition=""): self._prefix = prefix self._arg = arg self._code = code self._addition = addition def __str__(self): if not self._prefix == "": string = "{0}: " else: string = "" string += "{1} 。CODE: {2}" string = string.format(self._prefix, self._arg, str(self._code)) if not self._addition == "": string += "\nADDITION:\n{0}".format(self._addition) return string class NoArgumentException(CustomBaseException): def __init__(self, arg: str): self._prefix = "不完整的命令行参数" self._arg = arg self._code = 10 self._addition = "" class UnknownArgumentException(CustomBaseException): def __init__(self, arg: str): self._prefix = "未知的命令行参数" self._arg = arg self._code = 11 self._addition = "" class AnotherException(CustomBaseException): def __init__(self, addition: str): self._prefix = "" self._arg = "其它类型的错误." self._code = 5 self._addition = addition class InvalidCompoundException(CustomBaseException): def __init__(self, arg: str): self._prefix = "无效的参数组合" self._arg = arg self._code = 12 self._addition = "" class InvalidPathException(CustomBaseException): def __init__(self, target: str, arg: str): self._prefix = "无效的{0}目录".format(target) self._arg = arg self._code = 13 self._addition = "" class CannotCreatePathException(CustomBaseException): def __init__(self, target: str, addition: str): self._prefix = "无法创建的目录或文件" self._arg = target self._code = 14 self._addition = addition class LoginFailedException(CustomBaseException): def __init__(self, arg: str): self._prefix = "登陆失败" self._arg = arg self._code = 21 self._addition = "" class NoValidFileWarning(CustomBaseException): def __init__(self, url=""): self._prefix = "" self._arg = "未找到有效文件" if url: self._arg += "。请自行前往论坛查看" else: self._arg += "。请检查是否有缓存/下载目录的读写权限或目录是否存在" self._code = 101 self._addition = url class WatchdogTimeoutWarning(CustomBaseException): def __init__(self): self._prefix = "" self._arg = "文件监听等待超时" self._code = 102 self._addition = ""
StarcoderdataPython
4944571
queries = { "postgresql": { "table": """ SELECT c.relname as "Name", CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'partitioned table' WHEN 'I' THEN 'partitioned index' END as "Type", pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as "Size", fields.fields FROM pg_catalog.pg_class c JOIN (SELECT a.attrelid, string_agg(a.attname::text, ', ') fields FROM (select * from pg_catalog.pg_attribute order by attnum) a WHERE a.attnum > 0 AND NOT a.attisdropped group by 1) fields on c.oid = fields.attrelid LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','p','v','m','S','f','') AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast' AND pg_catalog.pg_table_is_visible(c.oid) ORDER BY 1,2; """, "field": """ WITH getoid as ( SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = %s AND pg_catalog.pg_table_is_visible(c.oid) ) SELECT a.attname "Field", pg_catalog.format_type(a.atttypid, a.atttypmod) "Type", pg_catalog.col_description(a.attrelid, a.attnum) "Description" FROM pg_catalog.pg_attribute a WHERE a.attrelid in (select oid from getoid) AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum; """, }, "sqlite": { "table": """ SELECT name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'; """, "field": """ SELECT name, upper(case when type = '' then 'TEXT' else type end) type FROM PRAGMA_TABLE_INFO(?) """, }, }
StarcoderdataPython
12810854
""" Quantifies the difference in occurrence of one (or more mutations) between two sets of isolates. TODO: 1. Use DualDataProvider and implement getPoints locally so have same data plotted as is analyzed """ from microbepy.common import constants as cn from microbepy.common import util from microbepy.common.range_constraint import RangeConstraint from microbepy.data import util_data as ud from microbepy.data import model_data_provider from microbepy.plot.phenotype_plot import PhenotypePlot from microbepy.plot.util_plot import PlotParms from collections import namedtuple import math import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import pandas as pd LOW = 0.0 # Depvar is less than 0 RC_LOW = RangeConstraint(lower=-10, upper=-LOW) # Units of standard deviation # Depvar is greater than 0 RC_HIGH = RangeConstraint(lower=LOW, upper=10) ###################################### # CLASSES ###################################### # Knobs are the protrusions from points Knob = namedtuple('Knob', ['angle', 'color']) Point = namedtuple('Point', ['x', 'y']) class MutationDifferential(object): def __init__(self, depvar, mutation_column, rc_low=RC_LOW, rc_high=RC_HIGH, is_median=False, **kwargs ): """ The sets of isolates are specified by a range of values of the dependent variable. :param str depvar: :param str mutation_column: :param RangeConstraint rc_low: Defines the low isolates :param RangeConstraint rc_high: Defines the high isolates :param Boolean is_median: use the median as 0 if True :param dict **kwargs: arguments to provider """ def shiftRC(rc, shift): return RangeConstraint(rc.lower + shift, rc.upper + shift) # self._depvar = depvar self._mutation_column = mutation_column self._rc_low = rc_low self._rc_high = rc_high if not "constraints" in kwargs: kwargs["constraints"] = None self._constraints = kwargs["constraints"] # Obtain the data self.provider = model_data_provider.makeTransformedData( data_cls=model_data_provider.ModelDataDualProvider, mutation_column=self._mutation_column, **kwargs) self.provider.do() self.df_y = self.provider.df_ys[depvar].rename( columns={depvar: cn.VALUE}) self.df_X = self.provider.df_X # Adjust the range constraints if the median is used if is_median: median = np.median(self.df_y[cn.VALUE]) self._rc_low = shiftRC(self._rc_low, median) self._rc_high = shiftRC(self._rc_high, median) # Mutation counts for low range isolates self._ser_low, self._tot_low = self._makeCounts(self._rc_low) # Mutation counts for high range isolates self._ser_high, self._tot_high = self._makeCounts(self._rc_high) def _makeCounts(self, range_constraint): """ :param RangeConstraint range_constraint: :return pd.Series, int: pd.Series: index is mutation; values is count int: count of isolates """ sel = range_constraint.isSatisfiedRows(self.df_y) df = self.df_X.loc[sel] return df.sum(axis=0), len(sel) @staticmethod def _calcProb(num_low, num_high, tot_low, tot_high): """ Caculates the probability of having a mutation that occurs num_low times in the low isolates and num_high times in the high isolates. :param int num_low: Number in low slots :param int num_high: Number in high slots :param int tot_low: total low slots :param int tot_high: total high slots :return float: """ tot = tot_low + tot_high result = util.nCr(tot_low, num_low) result *= util.nCr(tot_high, num_high) result /= 1.0*util.nCr(tot, num_low + num_high) return result def _calcSL(self, num_low, num_high): """ Calculates the significance level for a mutation that has num_low mutations in the low isolates in num_high in the high isolates. Two cases are considered: (1) The mutation is unusual in its occurrence in the high isolates; (2) the mutation is unusual in its absence in the high isolates. :param int num_low: :param int num_high: :return float: """ # Significance for mutation present in high # Find the tail by moving lows to high prob_tail_high = 0 upper = num_low + 1 for num in range(0, upper): n_high = num_high + num if n_high > self._tot_high: break n_low = num_low - num prob_tail_high += MutationDifferential._calcProb( n_low, n_high, self._tot_low, self._tot_high) # Find the tail by moving highs prob_tail_low = 0 upper = num_high + 1 for num in range(0, upper): n_high = num_high - num n_low = num_low + num if n_low > self._tot_low: break prob_tail_low += MutationDifferential._calcProb( n_low, n_high, self._tot_low, self._tot_high) # sl = min(prob_tail_high, prob_tail_low) return sl def makeDF(self): """ A significance level is calculated for preferentially occurring the in the high (low) set. :param int num_replications: :return pd.DataFrame: sorted by increasing value of cn.SIGLVL indexed by cn.MUTATION cn.SIGLVL - float significance level for the occurrence of the mutation being preferentially in the high (low) group. cn.VALUE - joint significance level of mutations with up this mutation in list cn.COUNT1 - number low cn.COUNT2 - number high """ # Calculate significance levels sls = [self._calcSL(int(l), int(h)) for l, h in zip(self._ser_low, self._ser_high)] # Construct the dataframe df_result = pd.DataFrame({ cn.MUTATION: self.df_X.columns.tolist(), cn.COUNT1: self._ser_low, cn.COUNT2: self._ser_high, cn.SIGLVL: sls, }) df_result = df_result.set_index(cn.MUTATION) df_result = df_result.sort_values(cn.SIGLVL) # Compute joint significance level joint_prob = 1 values = [] for _, row in df_result.iterrows(): joint_prob *= (1 - row[cn.SIGLVL]) values.append(1 - joint_prob) df_result[cn.VALUE] = values # return df_result def scatterKnob(self, is_plot=True, parms=PlotParms(), max_sl=0.1): """ Plots isolates in phenotype space with knob marks that indicate mutations that are statistically significant. :param boolean is_plot: plot if True :param PlotParms parms: plot parameters :param float max_sl: TODO: 1. Partition graph with dotted line along the cutting axis 2. Legend with mutations """ def plotKnob(point, knob, length, y_adjust): """ Plots the knob for the point :param Point point: :param Knob knob: :param float length: length of knob :param float y_adjust: adjust to y because of x, y scales """ # find the end point endy = y_adjust*length * math.sin( math.radians(knob.angle)) + point.y endx = length * math.cos( math.radians(knob.angle)) + point.x plt.plot([point.x, endx], [point.y, endy], color=knob.color, linewidth=3) # knobs = [ Knob(angle=0, color='r'), Knob(angle=90, color='g'), Knob(angle=180, color='b'), Knob(angle=270, color='y'), Knob(angle=45, color='m'), Knob(angle=135, color='k'), ] num_knobs = len(knobs) # Construct the base plot plot = PhenotypePlot(provider=self.provider, constraints=self._constraints, is_plot=False) parms.setattr(cn.PLT_XLIM, [-2, 2]) parms.setattr(cn.PLT_YLIM, [-3.5, 3.5]) plot.scatter(colors='kkk', legend=[], parms=parms) df_point = plot.getPoints() # Add knobs for significant mutations df_mutation = self.makeDF() # Significant mutations df_sig = df_mutation[df_mutation[cn.SIGLVL] < max_sl].copy() mutations = df_sig.index.tolist()[:num_knobs] siglvls = ["%1.4f" % s for s in df_sig[cn.SIGLVL]] # length = 0.08 y_adjust = parms[cn.PLT_YLIM][1]/(1.0*parms[cn.PLT_XLIM][1]) for idx, mutation in enumerate(mutations): ser = self.df_X[mutation] pairs = [i for v,i in zip(ser.tolist(), ser.index.tolist()) if v == 1] df_isolates = pd.DataFrame( [r for p,r in df_point.iterrows() if p in pairs] ) points = [Point(x=r[cn.RATE], y=r[cn.YIELD]) for _, r in df_isolates.iterrows()] for point in points: plotKnob(point, knobs[idx], length, y_adjust) # Add the line dividing the isolates being compared vals = [self._rc_low.upper, self._rc_high.lower] if self._depvar == cn.RATE: xs = vals ys = parms[cn.PLT_YLIM] else: # cn.YIELD ys = vals xs = parms[cn.PLT_XLIM] plt.plot(xs, ys, dashes=[10, 5, 20, 5], linewidth=1, color='black') # Add the legend if not cn.PLT_LEGEND in parms.keys(): entries = [] for idx, mutation in enumerate(mutations): label = "%s (%s)" % (mutations[idx], siglvls[idx]) entries.append(mpatches.Patch(color=knobs[idx].color, label=label)) else: entries = parms[cn.PLT_LEGEND] # Position the legend to get it out of view plt.legend(handles=entries, loc='lower left') # Show the plot parms.do(is_plot=is_plot)
StarcoderdataPython
5097925
<reponame>brl0/bripy from queue import Queue from threading import Thread from time import sleep from bripy.bllb.logging import logger, DBG def unloadq(q, stop, limit=2000, rest=.1, check=100): i = limit loops = 0 results = [] while True and ((i and not stop()) or q.qsize()): loops += 1 if loops % check == 0: DBG(i, loops, len(results)) if q.qsize(): x = q.get() DBG(x) results.append(x) i = min(i + 1, limit) else: i -= 1 if i % check == 0: DBG(i) sleep(rest) return results def multiplex(n, q, **kwargs): """ Convert one queue into several equivalent Queues >>> q1, q2, q3 = multiplex(3, in_q) """ out_queues = [Queue(**kwargs) for i in range(n)] def f(): while True: x = q.get() for out_q in out_queues: out_q.put(x) t = Thread(target=f) t.daemon = True t.start() return out_queues def push(in_q, out_q): while True: x = in_q.get() out_q.put(x) def merge(*in_qs, **kwargs): """ Merge multiple queues together >>> out_q = merge(q1, q2, q3) """ out_q = Queue(**kwargs) threads = [Thread(target=push, args=(q, out_q)) for q in in_qs] for t in threads: t.daemon = True t.start() return out_q def iterq(q): while q.qsize(): yield q.get() def get_q(q): results = [] while not q.empty() or q.qsize(): item = q.get() if item == 'STOP': DBG('STOP get_q') q.task_done() break DBG(item) if item: results.append(item) q.task_done() return results
StarcoderdataPython
1854297
# @lc app=leetcode id=640 lang=python3 # # [640] Solve the Equation # # https://leetcode.com/problems/solve-the-equation/description/ # # algorithms # Medium (43.07%) # Likes: 319 # Dislikes: 642 # Total Accepted: 30K # Total Submissions: 69.5K # Testcase Example: '"x+5-3+x=6+x-2"' # # Solve a given equation and return the value of 'x' in the form of a string # "x=#value". The equation contains only '+', '-' operation, the variable 'x' # and its coefficient. You should return "No solution" if there is no solution # for the equation, or "Infinite solutions" if there are infinite solutions for # the equation. # # If there is exactly one solution for the equation, we ensure that the value # of 'x' is an integer. # # # Example 1: # Input: equation = "x+5-3+x=6+x-2" # Output: "x=2" # Example 2: # Input: equation = "x=x" # Output: "Infinite solutions" # Example 3: # Input: equation = "2x=x" # Output: "x=0" # Example 4: # Input: equation = "2x+3x-6x=x+2" # Output: "x=-1" # Example 5: # Input: equation = "x=x+2" # Output: "No solution" # # # Constraints: # # # 3 <= equation.length <= 1000 # equation has exactly one '='. # equation consists of integers with an absolute value in the range [0, 100] # without any leading zeros, and the variable 'x'. # # # # @lc tags=math # @lc imports=start from imports import * # @lc imports=end # @lc idea=start # # 解方程。 # 简单解析公式字符串。 # # @lc idea=end # @lc group= # @lc rank= # @lc code=start class Solution: def solveEquation(self, equation: str) -> str: l, r = equation.split('=') def parse(s): s += '+' pre = '' xn = 0 cn = 0 for c in s: if c == '+' or c == '-': if len(pre) != 0: if pre[-1] == 'x': pre = pre[:len(pre) - 1] if len(pre) == 0: xn += 1 else: if pre == '+' or pre == '-': pre += '1' xn += int(pre) else: cn += int(pre) pre = '' pre += c return xn, cn lxn, lcn = parse(l) rxn, rcn = parse(r) xn = lxn - rxn cn = rcn - lcn if xn == 0: if cn == 0: return "Infinite solutions" else: return "No solution" else: value = cn // xn return 'x={}'.format(value) # @lc code=end # @lc main=start if __name__ == '__main__': print('Example 1:') print('Input : ') print('equation = "x+5-3+x=6+x-2"') print('Exception :') print('"x=2"') print('Output :') print(str(Solution().solveEquation("x+5-3+x=6+x-2"))) print() print('Example 2:') print('Input : ') print('equation = "x=x"') print('Exception :') print('"Infinite solutions"') print('Output :') print(str(Solution().solveEquation("x=x"))) print() print('Example 3:') print('Input : ') print('equation = "2x=x"') print('Exception :') print('"x=0"') print('Output :') print(str(Solution().solveEquation("2x=x"))) print() print('Example 4:') print('Input : ') print('equation = "2x+3x-6x=x+2"') print('Exception :') print('"x=-1"') print('Output :') print(str(Solution().solveEquation("2x+3x-6x=x+2"))) print() print('Example 5:') print('Input : ') print('equation = "x=x+2"') print('Exception :') print('"No solution"') print('Output :') print(str(Solution().solveEquation("x=x+2"))) print() pass # @lc main=end
StarcoderdataPython
1950993
<gh_stars>0 import argparse import tools.find_mxnet import mxnet as mx import os import sys from train.train_net import train_net def parse_args(): parser = argparse.ArgumentParser(description='Train a Single-shot detection network') parser.add_argument('--dataset', dest='dataset', help='which dataset to use', default='pascal', type=str) parser.add_argument('--image-set', dest='image_set', help='train set, can be trainval or train', default='trainval', type=str) parser.add_argument('--year', dest='year', help='can be 2007, 2012', default='2007,2012', type=str) parser.add_argument('--val-image-set', dest='val_image_set', help='validation set, can be val or test', default='test', type=str) parser.add_argument('--val-year', dest='val_year', help='can be 2007, 2010, 2012', default='2007', type=str) parser.add_argument('--devkit-path', dest='devkit_path', help='VOCdevkit path', default=os.path.join(os.getcwd(), 'data', 'VOCdevkit'), type=str) parser.add_argument('--network', dest='network', type=str, default='vgg16_reduced', choices=['vgg16_reduced'], help='which network to use') parser.add_argument('--batch-size', dest='batch_size', type=int, default=32, help='training batch size') parser.add_argument('--resume', dest='resume', type=int, default=-1, help='resume training from epoch n') parser.add_argument('--finetune', dest='finetune', type=int, default=-1, help='finetune from epoch n, rename the model before doing this') parser.add_argument('--pretrained', dest='pretrained', help='pretrained model prefix', default=os.path.join(os.getcwd(), 'model', 'vgg16_reduced'), type=str) parser.add_argument('--epoch', dest='epoch', help='epoch of pretrained model', default=1, type=int) parser.add_argument('--prefix', dest='prefix', help='new model prefix', default=os.path.join(os.getcwd(), 'model', 'ssd'), type=str) parser.add_argument('--gpus', dest='gpus', help='GPU devices to train with', default='0', type=str) parser.add_argument('--begin-epoch', dest='begin_epoch', help='begin epoch of training', default=0, type=int) parser.add_argument('--end-epoch', dest='end_epoch', help='end epoch of training', default=1000, type=int) parser.add_argument('--frequent', dest='frequent', help='frequency of logging', default=20, type=int) parser.add_argument('--data-shape', dest='data_shape', type=int, default=300, help='set image shape') parser.add_argument('--lr', dest='learning_rate', type=float, default=0.001, help='learning rate') parser.add_argument('--momentum', dest='momentum', type=float, default=0.9, help='momentum') parser.add_argument('--wd', dest='weight_decay', type=float, default=0.00005, help='weight decay') parser.add_argument('--mean-r', dest='mean_r', type=float, default=123, help='red mean value') parser.add_argument('--mean-g', dest='mean_g', type=float, default=117, help='green mean value') parser.add_argument('--mean-b', dest='mean_b', type=float, default=104, help='blue mean value') parser.add_argument('--lr-epoch', dest='lr_refactor_epoch', type=int, default=1000000, help='refactor learning rate every N epoch') parser.add_argument('--lr-ratio', dest='lr_refactor_ratio', type=float, default=0.5, help='ratio to refactor learning rate') parser.add_argument('--log', dest='log_file', type=str, default="train.log", help='save training log to file') parser.add_argument('--monitor', dest='monitor', type=int, default=0, help='log network parameters every N iters if larger than 0') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() ctx = [mx.gpu(int(i)) for i in args.gpus.split(',')] ctx = mx.cpu() if not ctx else ctx # resume args.prefix = os.path.join(os.getcwd(), 'model', 'ssd') args.resume = 376 train_net(args.network, args.dataset, args.image_set, args.year, args.devkit_path, args.batch_size, args.data_shape, (args.mean_r, args.mean_g, args.mean_b), args.resume, args.finetune, args.pretrained, args.epoch, args.prefix, ctx, args.begin_epoch, args.end_epoch, args.frequent, args.learning_rate, args.momentum, args.weight_decay, args.val_image_set, args.val_year, args.lr_refactor_epoch, args.lr_refactor_ratio, args.monitor, args.log_file)
StarcoderdataPython
5079142
<gh_stars>0 import csv import shutil import requests from stationtz import AIRPORT_SOURCE_FILE, MANUAL_STATION_SOURCE_FILE DATA_SOURCE_URL = 'https://raw.githubusercontent.com/opentraveldata/opentraveldata/master/opentraveldata/optd_por_public.csv' def create_stations(file, **kwargs): """ Manually specify stations""" with open(file, "rt") as f: reader = csv.DictReader(f) for row in reader: assert (row.get("icao_code") or row.get("iata_code")) and row.get("timezone") print(f"Copying file to {MANUAL_STATION_SOURCE_FILE}") shutil.copyfile(file, MANUAL_STATION_SOURCE_FILE) def update_airports(*args, **requests_kwargs): """ Update the ori_por_public.csv file directly from source. :param requests_kwargs: any kwargs you would like to pass to the requests.get method proxy={'http': '', 'https': ''} <- might be useful if you are requesting within proxy server """ r = requests.get(DATA_SOURCE_URL, **requests_kwargs) print(f"Updating {AIRPORT_SOURCE_FILE}") with open(AIRPORT_SOURCE_FILE, 'wt', encoding='utf-8') as f: f.write(r.text) if __name__ == '__main__': import argparse scripts = ["update_airports", "create_stations"] parser = argparse.ArgumentParser( description="Utility to set data used by this library.") parser.add_argument("script", help=f"Choose the script to run: {scripts}", type=str) parser.add_argument("--arg", help=f"Any argument required by the script", type=str) parser.add_argument("--kwarg", help=f"Any keyword argument used by the script", type=str) args = parser.parse_args() if args.script in scripts: arg = args.arg if args.arg else [] kwarg = {args.kwarg.split("=")[0]: args.kwarg.split("=")[1]} if args.kwarg else {} eval(args.script)(arg, **kwarg) else: raise Exception(f"Valid values for script are: {scripts}")
StarcoderdataPython
1985228
<reponame>AlexandreSoaresValerio/Pycharm t = int(input('Escolha uma tabuada:')) for c in range(0, 11): print('{} x {} = {}'.format(t, c, t*c))
StarcoderdataPython
6619690
<reponame>jwbaldwin/novu-note from django.test import TestCase from django.contrib.auth.models import User from rest_framework.test import APIClient from rest_framework import status from django.urls import reverse from ..models import Note class ViewTestCase(TestCase): """Test suite for the api views.""" def setUp(self): """Define the test client and other test variables.""" # Initialize client and force it to use authentication self.user = User.objects.create(username="nerd") self.client = APIClient() self.client.force_authenticate(user=self.user) # Create a JSON POST request self.url = reverse('create') self.sample_note_data = { 'text': 'A new idea!', 'category_tags': ['django', 'testing'], 'creator': self.user.id } self.response = self.client.post( self.url, self.sample_note_data, format='json') def test_api_can_create_a_note(self): """POST: Test the api has note creation capability.""" self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) self.assertEqual(Note.objects.count(), 1) self.assertEqual(Note.objects.get().text, self.sample_note_data.get('text')) self.assertEqual(Note.objects.get().category_tags, self.sample_note_data.get('category_tags')) def test_api_can_get_a_note(self): """GET: Test the api can get a given note.""" note = Note.objects.get() response = self.client.get( reverse('details', kwargs= { 'pk': note.id }), format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, note) def test_api_can_update_note(self): """PUT: Test the api can update a given note.""" note = Note.objects.get() modified_note = { 'text': 'A modified new idea!', 'category_tags': ['rest', 'test'], 'creator': self.user.id } response = self.client.put( reverse('details', kwargs= { 'pk': note.id }), modified_note, format='json' ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(Note.objects.get().category_tags, modified_note.get('category_tags')) def test_api_can_delete_note(self): """DELETE: Test the api can delete a note.""" note = Note.objects.get() response = self.client.delete( reverse('details', kwargs={ 'pk': note.id }), format='json', follow=True) self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(Note.objects.count(), 0)
StarcoderdataPython
9704033
<filename>emergency_contact/models.py from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_telepon(value): if (not value.isdigit()): raise ValidationError( _('%(value)s bukan nomor telepon yang valid'), params={'value': value}, ) class Daerah(models.Model): daerah = models.CharField(max_length=15, unique=True, default='') def __str__(self): return self.daerah class RumahSakit(models.Model): nama = models.CharField(max_length=40, unique=True) alamat = models.CharField(max_length=60) telepon = models.CharField(max_length=25, validators=[validate_telepon]) daerah = models.ForeignKey(Daerah, on_delete=models.CASCADE, null=True, default='') def __str__(self): return self.nama
StarcoderdataPython
227068
# 形態素の解析結果格納用 class Morph(): def __init__(self, m_id, line): self.id = 0 # 形態素のid self.surface = "" # 形態素の表層 self.pos = "" # 品詞,品詞細分類1,品詞細分類2,品詞細分類3 self.pos1 = "" self.pos2 = "" self.pos3 = "" self.pos4 = "" self.base = "" # 基本形 self.read = "" # 読み self.cform = "" # 活用形 self.ctype = "" # 活用型 self.ne = "" # 固有表現解析 self.tree = [] self.chunk = None self.forms = [] self.initMorph(m_id, line) def initMorph(self, m_id, line): div1 = line.split("\t") div2 = div1[1].split(",") self.id = m_id self.surface = div1[0] if div2[0] != "*": self.pos1 = div2[0] if div2[1] != "*": self.pos2 = div2[1] if div2[2] != "*": self.pos3 = div2[2] if div2[3] != "*": self.pos4 = div2[3] if div2[4] != "*": self.cform = div2[4] if div2[5] != "*": self.ctype = div2[5] self.pos = self.getPos() self.base = div2[6] if len(div2) >= 8: self.read = div2[7] self.ne = div1[2] def getPos(self): pos = "" if self.pos1 != "": pos = pos + self.pos1 if self.pos2 != "": pos = pos + "," + self.pos2 if self.pos3 != "": pos = pos + "," + self.pos3 if self.pos4 != "": pos = pos + "," + self.pos4 return pos
StarcoderdataPython
8031694
import sys import tensorflow as tf from time import time from src.tftools.shift_layer import ShiftLayer from src.tftools.scale_layer import ScaleLayer from src.tftools.rotation_layer import RotationLayer # from src.tftools.radial_distortion_layer import RDistortionLayer # from src.tftools.radial_distortion_layer_2 import RDistortionLayer2 # from src.tftools.radial_distortion_layer_3 import RDistortionLayer3 from src.tftools.radial_distortion_complete import RDCompleteLayer # from src.tftools.shear_layer import ShearLayer from src.tftools.idx2pixel_layer import Idx2PixelLayer, reset_visible from src.tftools.idx2pixel_layer_bc import Idx2PixelBCLayer, reset_visible from src.tftools.transform_metric import ShiftMetrics, ScaleMetrics, RotationMetrics, DistortionMetrics, RDMetrics from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau from src.logging.verbose import Verbose from src.tftools.optimizer_builder import build_optimizer from src.config.tools import get_config, get_or_default import numpy as np from termcolor import colored from src.data.ann.input_preprocessor import training_batch_selection, blur_preprocessing from src.tftools.optimizer_builder import build_refining_optimizer import datetime import matplotlib.pyplot as plt MODEL_FILE = "best_model.tmp.h5" tf.keras.utils.Progbar(target=None, width=100) def __train_networks(inputs, outputs, reg_layer_data, optimizer, refiner, config, layers=None, train_set_size=50000, batch_size=256, stages={ "type": "polish", "epochs": 50 }): """ This method builds ANN with all layers - some layers for registration other layers for information gain computation and processes the training. :param inputs: input coordinates (will be randomized) :param outputs: output image pixel intensity values :param reg_layer_data: first layer data - transformation of coords to pixel intensity value :param layers: not used now - this will define IG layers in the future :param train_set_size: number of pixels used for training, default is 50k :param batch_size: number of pixels computed in one batch :param epochs: number of learning epochs :return: trained model and training history """ Verbose.print('Selecting ' + str(train_set_size) + ' samples randomly for use by algorithm.') selection = training_batch_selection(train_set_size, reg_layer_data) indexes = inputs[selection, :] # define model print('Adding input layer, width =', indexes.shape[1]) # TODO: revisit shear layer input_layer = tf.keras.layers.Input(shape=(indexes.shape[1],), dtype=tf.float32, name='InputLayer') shift_layer = ShiftLayer(name='ShiftLayer')(input_layer) scale_layer = ScaleLayer(name='ScaleLayer')(shift_layer) rotation_layer = RotationLayer(name='RotationLayer')(scale_layer) radial_distortion_layer = RDCompleteLayer(name='RDistortionLayer')(rotation_layer) # radial_distortion_layer = RDistortionLayer(name='RDistortionLayer')(rotation_layer) # radial_distortion_layer_2 = RDistortionLayer2(name='RDistortionLayer2')(radial_distortion_layer) # radial_distortion_layer_3 = RDistortionLayer3(name='RDistortionLayer3')(radial_distortion_layer_2) layer = Idx2PixelLayer(visible=reg_layer_data, name='Idx2PixelLayer')(radial_distortion_layer) # TODO: Add InformationGain layers here when necessary print('Adding ReLU output layer, width =', outputs.shape[1]) output_layer = tf.keras.layers.ReLU(max_value=1, name='Output', trainable=False)(layer) model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer) # compile model start_time = time() model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mean_squared_error'] ) # Set initial transformation as identity elapsed_time = time() - start_time print("Compiling model took {:.4f}'s.".format(elapsed_time)) # train model start_time = time() tf.compat.v1.keras.backend.get_session().run(tf.compat.v1.global_variables_initializer()) model.layers[1].set_weights([np.array([0, 0])]) # shift model.layers[2].set_weights([np.array([0, 0])]) # scale model.layers[3].set_weights([np.array([0])]) # rotation # model.load_weights(MODEL_FILE) # TODO: better names for stages config = get_config() for stage in stages: if stage['type'] == 'blur': output = blur_preprocessing(outputs, reg_layer_data.shape, stage['params']) __set_train_registration(model, True) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mean_squared_error']) elif stage['type'] == 'refine': output = outputs __set_train_registration(model, True, target="shift") model.compile(loss='mean_squared_error', optimizer=refiner, metrics=['mean_squared_error']) elif stage['type'] == 'polish': output = outputs __set_train_registration(model, True) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mean_squared_error']) else: stage_params = stage['type'].split('_') if stage_params[0] == 'adam': opt_type = 'optimizer' opt = build_optimizer(config["train"][opt_type], config["train"]["batch_size"]) elif stage_params[0] == 'sgd': opt_type = 'refiner' opt = build_refining_optimizer(config["train"][opt_type]) if stage_params[1] == 'rd': targ = "rd" output = outputs __set_train_registration(model, True, target=targ) model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mean_squared_error']) reset_visible(output) output = output[selection, :] shift_metric = ShiftMetrics() scale_metric = ScaleMetrics() rotation_metric = RotationMetrics() # distortion_metric = DistortionMetrics() distortion_metric = RDMetrics() mcp_save = ModelCheckpoint(MODEL_FILE, save_best_only=True, monitor='val_loss', mode='min') checkpoint_filepath = MODEL_FILE model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_filepath, save_weights_only=True, monitor='val_loss', mode='min', save_best_only=True) # lr_reduction = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=100, verbose=0, mode='auto', # min_delta=0.0001, cooldown=0, min_lr=0) log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1) callbacks = [shift_metric, scale_metric, rotation_metric, distortion_metric, tensorboard_callback, model_checkpoint_callback] history = model.fit(indexes, output, epochs=stage['epochs'], validation_split=0.2, verbose=1, callbacks=[shift_metric, scale_metric, rotation_metric, distortion_metric, model_checkpoint_callback ], batch_size=batch_size ) coef_1 = [x[0][0]*config["layer_normalization"]["radial_distortion"] for x in distortion_metric.bias_history] coef_2 = [x[1][0]*config["layer_normalization"]["radial_distortion_2"] for x in distortion_metric.bias_history] coef_3 = [x[2][0]*config["layer_normalization"]["radial_distortion_3"] for x in distortion_metric.bias_history] plt.plot(coef_1, label="1") plt.plot(coef_2, label="2") plt.plot(coef_3, label="3") model.load_weights(checkpoint_filepath) plt.title("Transformation %f %f %f " % (coef_1[-1], coef_2[-1], coef_3[-1])) plt.legend() plt.show() elapsed_time = time() - start_time num_epochs = len(history.history['loss']) print("{:.4f}'s time per epoch. Epochs:".format(elapsed_time / num_epochs), num_epochs, sep="") print("Total time {:.4f}'s".format(elapsed_time)) # calculate gain and save best model so far model.load_weights(checkpoint_filepath) gain = abs(outputs[selection, :] - model.predict(indexes, batch_size=batch_size)) / (outputs.shape[0] * outputs.shape[1]) information_gain_max = gain.flatten().max() print('Gain: {:1.4e}'.format(information_gain_max)) return model, history, shift_metric.bias_history def __set_train_registration(model, value, target="registration"): """ For various stages of training registration should not be trainable (we are looking for base mutual setup). This method allows enabling/disabling of trainability of first three layers of ANN. :param model: ANN :param value: boolean """ if target == "registration": model.layers[1].trainable = value model.layers[2].trainable = value model.layers[3].trainable = value model.layers[4].trainable = (not value) model.layers[5].trainable = (not value) model.layers[6].trainable = (not value) model.layers[7].trainable = (not value) model.layers[8].trainable = (not value) elif target == "all": model.layers[1].trainable = value model.layers[2].trainable = value model.layers[3].trainable = value model.layers[4].trainable = value model.layers[5].trainable = value model.layers[6].trainable = value model.layers[7].trainable = value model.layers[8].trainable = value elif target == "shift": model.layers[1].trainable = value model.layers[2].trainable = not value model.layers[3].trainable = not value model.layers[4].trainable = not value model.layers[5].trainable = not value model.layers[6].trainable = not value model.layers[7].trainable = not value model.layers[8].trainable = not value elif target == "rd": model.layers[1].trainable = not value model.layers[2].trainable = not value model.layers[3].trainable = not value model.layers[4].trainable = value model.layers[5].trainable = value model.layers[6].trainable = value def __information_gain(coords, target, visible, optimizer, refiner, train_config, layers=None, train_set_size: int = 25000, batch_size=256, stages={ "type": "polish", "epochs": 50 }): if coords.shape[0] != target.shape[0] * visible.shape[1]: sys.exit("Error: dimension mismatch between 'target' and 'visible'") if len(target.shape) == 2: target = target.reshape((target.shape[0], target.shape[1], 1)) if train_set_size is None: # use the whole image for training, evaluation and test train_set_size = visible.shape[0] * visible.shape[1] outputs = target.reshape((target.shape[0] * target.shape[1], target.shape[2])) # train ANN model, history, bias_history = __train_networks(coords, outputs, reg_layer_data=visible, optimizer=optimizer, refiner=refiner, config=train_config, layers=layers, train_set_size=train_set_size, batch_size=batch_size, stages=stages ) # print(model.get_weights()) # model.load_weights(MODEL_FILE) # print(model.get_weights()) # show output of the first two layers extrapolation = model.predict(coords, batch_size=batch_size) extrapolation = extrapolation.reshape(target.shape[0], target.shape[1], 1) ig = target - extrapolation return ig, extrapolation, model, bias_history def run(inputs, outputs, visible): config = get_config() ig, extrapolation, model, bias_history = \ __information_gain(inputs, outputs, visible=visible, optimizer=build_optimizer(config["train"]["optimizer"], config["train"]["batch_size"]), refiner=build_refining_optimizer(config["train"]["refiner"]), train_config=config["train"], layers=get_or_default("layers", 1), batch_size=config["train"]["batch_size"], stages=config["train"]["stages"] ) # print model summary to stdout model.summary() layer_dict = dict([(layer.name, layer) for layer in model.layers]) bias = layer_dict['ShiftLayer'].get_weights() Verbose.print("Shift: " + colored(str((bias[0])*config["layer_normalization"]["shift"]), "green"), Verbose.always) bias = layer_dict['RotationLayer'].get_weights() Verbose.print("Rotation: " + colored(str(bias[0]*config["layer_normalization"]["rotation"]*180/np.pi), "green"), Verbose.always) bias = layer_dict['ScaleLayer'].get_weights() Verbose.print("Scale: " + colored(str(bias[0]*config["layer_normalization"]["scale"] + 1), "green"), Verbose.always) k1 = layer_dict['RDistortionLayer'].get_weights()[0][0] * config["layer_normalization"]["radial_distortion"] k2 = layer_dict['RDistortionLayer'].get_weights()[1][0] * config["layer_normalization"]["radial_distortion_2"] k3 = layer_dict['RDistortionLayer'].get_weights()[2][0] * config["layer_normalization"]["radial_distortion_3"] exp_k1 = -k1 exp_k2 = 3*k1*k1 - k2 exp_k3 = -12*k1*k1*k1 + 8*k1*k2 - k3 Verbose.print("coefs computed: " + colored(str([k1, k2, k3]), "green"), Verbose.always) # Verbose.print("coefs inverse: " + colored(str([exp_k1, exp_k2, exp_k3]), "green"), Verbose.always) bias = [k1, k2, k3] # bias = layer_dict['ShearLayer'].get_weights() # Verbose.print("Shear: " + colored(str(bias[0]*0.1), "green"), Verbose.always) return model, bias, bias_history
StarcoderdataPython
6623067
<filename>zdiscord/service/integration/chat/discord/macros/General.py from zdiscord.service.messaging.Events import IEvent async def help_msg(help_msg: str,event: IEvent): await event.context['message_object'].channel.send(help_msg)
StarcoderdataPython
3566024
# -*- coding: utf-8 -*- """ The parallel running version of APE. To run APE in parallel through its API, first get a freq output file from Qchem, then call the .execute. For example: ape = Parallel_APE(input_file) ape.execute() """ import os import csv import time import shutil import numpy as np import subprocess import rmgpy.constants as constants from ape.main import APE #from ape.torsion import HinderedRotor #from ape.sampling import SolvEig, sampling_along_torsion, sampling_along_vibration from ape.FitPES import from_sampling_result,cubic_spline_interpolations from ape.thermo import ThermoJob from ape.exceptions import InputError, JobError from parallel_ape.job import ParallelJob from parallel_ape.PBS import check_job_status, delete_job class Parallel_APE(APE): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def sampling(self, thresh=0.05, save_result=True, scan_res=10, sampling_mode=None): xyz_dict = {} energy_dict = {} mode_dict = {} mode = sampling_mode if mode is None: raise InputError('No specified sampling mode in parallel APE. Please assign one specific sampling mode number') if not os.path.exists(self.project_directory): os.makedirs(self.project_directory) path = os.path.join(self.project_directory,'output_file', self.name) if not os.path.exists(path): os.makedirs(path) if self.protocol == 'UMVT' and self.n_rotors != 0: n_vib = self.n_vib if self.is_QM_MM_INTERFACE: n_vib -= 6 # due to frustrated translation and rotation rotor = HinderedRotor(self.symbols, self.cart_coords, self.hessian, self.rotors_dict, self.conformer.mass.value_si, n_vib, self.imaginary_bonds) projected_hessian = rotor.projectd_hessian() vib_freq, unweighted_v = SolvEig(projected_hessian, self.conformer.mass.value_si, self.n_vib) print('Frequencies(cm-1) from projected Hessian:',vib_freq) if mode-1 in range(self.n_rotors): if self.is_QM_MM_INTERFACE: XyzDictOfEachMode, EnergyDictOfEachMode, ModeDictOfEachMode, min_elect = sampling_along_torsion(self.symbols, self.cart_coords, mode, self.internal, self.conformer, rotor, self.rotors_dict, scan_res, path, thresh, self.ncpus, self.charge, self.multiplicity, self.level_of_theory, self.basis, \ self.is_QM_MM_INTERFACE, self.nHcap, self.QM_USER_CONNECT, self.QM_ATOMS, self.force_field_params, self.fixed_molecule_string, self.opt, self.number_of_fixed_atoms) else: XyzDictOfEachMode, EnergyDictOfEachMode, ModeDictOfEachMode, min_elect = sampling_along_torsion(self.symbols, self.cart_coords, mode, self.internal, self.conformer, rotor, self.rotors_dict, scan_res, path, thresh, self.ncpus, self.charge, self.multiplicity, self.level_of_theory, self.basis) elif self.protocol == 'UMN': vib_freq, unweighted_v = SolvEig(self.hessian, self.conformer.mass.value_si, self.n_vib) print('Vibrational frequencies of normal modes: ',vib_freq) if mode-1 in range(self.nmode)[self.n_rotors:]: vector=unweighted_v[sampling_mode-1-self.n_rotors] freq = vib_freq[sampling_mode-1-self.n_rotors] magnitude = np.linalg.norm(vector) reduced_mass = magnitude ** -2 / constants.amu # in amu step_size = np.sqrt(constants.hbar / (reduced_mass * constants.amu) / (freq * 2 * np.pi * constants.c * 100)) * 10 ** 10 # in angstrom normalizes_vector = vector/magnitude qj = np.matmul(self.internal.B, normalizes_vector) P = np.ones(self.internal.B.shape[0],dtype=int) n_rotors = len(self.rotors_dict) if n_rotors != 0: P[-n_rotors:] = 0 P = np.diag(P) qj = P.dot(qj).reshape(-1,) if self.is_QM_MM_INTERFACE: XyzDictOfEachMode, EnergyDictOfEachMode, ModeDictOfEachMode, min_elect = sampling_along_vibration(self.symbols, self.cart_coords, mode, self.internal, qj, freq, reduced_mass, step_size, path, thresh, self.ncpus, self.charge, self.multiplicity, self.level_of_theory, self.basis, \ self.is_QM_MM_INTERFACE, self.nHcap, self.QM_USER_CONNECT, self.QM_ATOMS, self.force_field_params, self.fixed_molecule_string, self.opt, self.number_of_fixed_atoms) else: XyzDictOfEachMode, EnergyDictOfEachMode, ModeDictOfEachMode, min_elect = sampling_along_vibration(self.symbols, self.cart_coords, mode, self.internal, qj, freq, reduced_mass, step_size, path, thresh, self.ncpus, self.charge, self.multiplicity, self.level_of_theory, self.basis) xyz_dict[mode] = XyzDictOfEachMode energy_dict[mode] = EnergyDictOfEachMode mode_dict[mode] = ModeDictOfEachMode # add the ground-state energy (including zero-point energy) of the conformer self.e_elect = min_elect # in Hartree/particle e0 = self.e_elect * constants.E_h * constants.Na + self.zpe # in J/mol self.conformer.E0 = (e0, "J/mol") if save_result: self.write_samping_result_to_csv_file(self.csv_path, mode_dict, energy_dict) path = os.path.join(self.project_directory, 'plot', self.name) if not os.path.exists(path): os.makedirs(path) self.write_sampling_displaced_geometries(path, energy_dict, xyz_dict) return XyzDictOfEachMode, EnergyDictOfEachMode, ModeDictOfEachMode def run(self): if not os.path.exists(self.project_directory): os.makedirs(self.project_directory) job_dir = os.path.join(self.project_directory,'job') if not os.path.exists(job_dir): os.makedirs(job_dir) job_status_dict = {} freq_output = self.input_file ncpus = self.ncpus protocol = self.protocol imaginary_bonds_string = '' if self.imaginary_bonds is not None: for i, bond in enumerate(self.imaginary_bonds): imaginary_bonds_string += str(bond[0]) + '-' + str(bond[1]) if i != len(self.imaginary_bonds) - 1: imaginary_bonds_string += ',' for i in range(self.nmode): mode = i + 1 submit_filename = 'mode_{}.q.job'.format(mode) job_path = os.path.join(job_dir,'mode_{}'.format(mode)) job = ParallelJob(job_path=job_path,input_file=freq_output,ncpus=ncpus,protocol=protocol,imaginary_bonds=imaginary_bonds_string) job.write_submit_file(submit_filename, sampling_mode=mode) job_status, job_id = job.submit(submit_filename) job_status_dict[job_id] = job_status if job_status == 'errored': for ID in job_status_dict.keys(): delete_job(ID) raise JobError('The submitting job, whose id is {job_id}, is errored.'.format(job_id=job_id)) # write job status csv to track job progress csv_job_status_path = os.path.join(self.project_directory,'job.csv') self.write_job_status_csv(csv_job_status_path, job_status_dict) # Check jobs' status till every submitted jobs are finished properly. # Possible status: `done`, `running`, `queue`, `errored` Job_finished = False while not Job_finished: time.sleep(60) # check jobs status every minute for job_id in job_status_dict.keys(): job_status = check_job_status(job_id) if job_status_dict[job_id] != job_status: if job_status == 'done': mode = sorted(job_status_dict.keys()).index(job_id) + 1 path = os.path.join(self.project_directory, 'plot', self.name, 'mode_{}.txt'.format(mode)) if not os.path.exists(path): job_status = 'errored' job_status_dict[job_id] = job_status # update jobs-tracking csv file self.write_job_status_csv(csv_job_status_path, job_status_dict) if job_status == 'errored': for ID in job_status_dict.keys(): delete_job(ID) raise JobError('An error appears in {job_id} job'.format(job_id=job_id)) job_status_set = set(job_status_dict.values()) if len(job_status_set) == 1 and job_status_set == {'done'}: Job_finished = True #shutil.rmtree(job_dir) # delete the job folder def write_job_status_csv(self, csv_path, job_status_dict): with open(csv_path, 'w') as f: writer = csv.writer(f) writer.writerow(['mode', 'Job_id', 'status']) for i, ID in enumerate(sorted(job_status_dict.keys())): mode = i+1 status = job_status_dict[ID] writer.writerow([mode, ID, status]) f.close() def execute(self): """ Execute APE in parallel. """ if os.path.exists(self.csv_path): os.remove(self.csv_path) self.parse() self.run() mode_dict, energy_dict, _ = from_sampling_result(csv_path=self.csv_path) # Solve SE of 1-D PES and calculate E S G Cp polynomial_dict = cubic_spline_interpolations(energy_dict,mode_dict) thermo = ThermoJob(self.conformer, polynomial_dict, mode_dict, energy_dict, T=298.15, P=100000) if self.is_QM_MM_INTERFACE: thermo.calcQMMMThermo() else: thermo.calcThermo(print_HOhf_result=True, zpe_of_Hohf=self.zpe)
StarcoderdataPython
1787017
<reponame>Element-s/pyisync #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-9-14 @author: Elem ''' import re import time import threading import subprocess from collections import deque from pyinotify import WatchManager, ThreadedNotifier, \ ProcessEvent, ExcludeFilter, IN_DELETE, IN_CREATE, \ IN_CLOSE_WRITE, IN_MOVED_FROM, IN_MOVED_TO from utils import SyncFiles from common import SyncConf from isync_logger import logger_init LOGGER = logger_init('pyisync.sync_utils') class RetryThread(threading.Thread): """ sync retry thread """ def __init__(self, name, retryq, remote_ip_lst=None, retry_interval=120, crontab=3600): """ init func @param name: thread name @type name: str @param retryq: retry cmf queue @type retryq: Queue @param retry_interval: retry interval time @type retry_interval: int @param crontab: full sync crontab, default 1 hour @type crontab: int """ threading.Thread.__init__(self, name=name) self.retryq = retryq if remote_ip_lst is None: self.remote_ip_lst = [] self.remote_ip_lst = remote_ip_lst self.retry_interval = retry_interval self.crontab_interval = crontab self.crontab_start = int(time.time()) # 定时开始时间 self._stop_event = threading.Event() self.full_threads = {} def stop(self): """ Stop retry's loop. Join the thread. """ LOGGER.info('Thread %s stop', self.name) self._stop_event.set() threading.Thread.join(self, 8) def run(self): self.loop() def loop(self): """ execute sync cmd loop """ while not self._stop_event.isSet(): try: now_time = int(time.time()) if self.retryq.empty(): if now_time - self.crontab_start > self.crontab_interval: # full sync self.crontab_start = now_time LOGGER.info('Start files full sync!peer ip:%s', str(self.remote_ip_lst)) for remote_ip in self.remote_ip_lst: full_thread = self.full_threads.get(remote_ip) if full_thread is not None \ and full_thread.isAlive(): full_thread.stop() self.full_threads[remote_ip] = None self.full_threads[remote_ip] = FullSyncThread(remote_ip) self.full_threads[remote_ip].setDaemon(True) self.full_threads[remote_ip].start() time.sleep(0.5) else: sync_dict = self.retryq.get(True) old_time = sync_dict['time'] if now_time - old_time > self.retry_interval: sync_cmd = sync_dict['time'] process = subprocess.Popen(sync_cmd, shell=True, stderr=subprocess.PIPE) retcode = process.wait() if retcode != 0: LOGGER.warning('Retry cmd failed:%s', sync_cmd) LOGGER.warning('execute cmd failed:%s', process.stderr.read()) self.retryq.task_done() except Exception, exp: LOGGER.warning("Retry thead exception: %s", str(exp)) finally: time.sleep(0.01) class SyncThreadManager(object): """ sync thread manager, create and manage sync threads """ def __init__(self, thread_num=5, cond=None, eventq=None, retryq=None, remote_ip_lst=None): self.threads = [] self.__init_thread_pool(thread_num, cond, eventq, retryq, remote_ip_lst) def __init_thread_pool(self, thread_num, cond, eventq, retryq, remote_ip_lst): """ init thread pool """ for i in range(thread_num): thread_name = "syncthread%d" % i self.threads.append(SyncThread(thread_name, cond=cond, eventq=eventq, retryq=retryq, remote_ip_lst=remote_ip_lst)) def start_all(self): """ start all sync threads """ for item in self.threads: item.setDaemon(True) item.start() def wait_allcomplete(self): """ wait all threads finished """ for item in self.threads: if item.isAlive(): item.join() def stop_all(self): """ stop all threads """ for item in self.threads: if item.isAlive(): item.stop() class SyncThread(threading.Thread): """ Sync cmd thread ,get event from sync queue.(consumer thread) When sync failed, insert event into retry queue. """ def __init__(self, name, **kwargs): threading.Thread.__init__(self, name=name) self.my_init(**kwargs) def my_init(self, cond=None, eventq=None, retryq=None, remote_ip_lst=None): """init vars @param cond: condition var @type cond: threading.Condition @param eventq: event queue @type eventq: collections.deque @param retryq: retry queue @type retryq: Queue.Queue """ self.cond = cond self.eventq = eventq self.retryq = retryq # 同步重试命令队列 self.remote_ip_lst = remote_ip_lst self._stop_event = threading.Event() self.sync_files = SyncFiles() self.encrypt_set = self.sync_files.encrypt_set def sync_file(self, event): """sync file or directory @param event: event @type event: pyinotify.Event """ sync_cmds = [] if event.mask & (IN_DELETE | IN_MOVED_FROM): # get sync delete remote file cmd for remote_ip in self.remote_ip_lst: sync_cmd = self.sync_files.combine_del_cmd(remote_ip, event.pathname, event.dir) sync_cmds.append(sync_cmd) else: # get sync create or modify file cmd is_crypt = self.sync_files.is_encrypt_file(event.pathname, self.encrypt_set) for remote_ip in self.remote_ip_lst: sync_cmd = self.sync_files.combine_other_cmd(remote_ip, event.pathname, event.dir, is_crypt) sync_cmds.append(sync_cmd) LOGGER.debug('sync_cmds: %s', sync_cmds) for sync_cmd in sync_cmds: if sync_cmd: process = subprocess.Popen(sync_cmd, shell=True, stderr=subprocess.PIPE) retcode = process.wait() if retcode != 0: LOGGER.warning('sync failed:%s.Insert cmd into retry queue!', process.stderr.read()) sync_dict = {} sync_dict['cmd'] = sync_cmd sync_dict['time'] = int(time.time()) self.retryq.put(sync_dict) def stop(self): """ Stop sync's loop. Join the thread. """ LOGGER.info('Thread %s stop', self.name) self._stop_event.set() self.cond.acquire() self.cond.notify_all() self.cond.release() threading.Thread.join(self, 8) def loop(self): while not self._stop_event.isSet(): self.cond.acquire() try: if not self.eventq: LOGGER.debug("Nothing in queue, sync consumer %s is waiting.", self.name) self.cond.wait() LOGGER.debug("Producer added something to queue and notified" " the consumer %s", self.name) else: event = self.eventq.popleft() self.cond.notify() self.sync_file(event) LOGGER.debug("%s is consuming. %s in the queue is consumed!/n" \ % (self.getName(), event.pathname)) finally: self.cond.release() time.sleep(0.01) LOGGER.info("Thread %s exit monitoring", self.name) while 1: self.cond.acquire() try: if not self.eventq: self.cond.notifyAll() time.sleep(0.5) break else: event = self.eventq.popleft() self.sync_file(event) time.sleep(0.01) LOGGER.debug("%s:%s is consuming. %s in the queue is consumed!/n" \ % (time.ctime(), self.name, event.pathname)) self.cond.notify() finally: self.cond.release() def run(self): self.loop() class EventHandler(ProcessEvent): """ files event's handler """ def my_init(self, cond=None, eventq=None, sync_list=None): """init func @param cond: condition var @type cond: Condition @param eventq: event queeu @type eventq: deque """ self.cond = cond self.eventq = eventq self.sync_list = sync_list def insert_events(self, event): """insert event into queue @param event: event @type event: pyinotify.Event """ self.cond.acquire() try: if event.name is not None and event.name.startswith('.wh..wh.'): # '.wh..wh.user.1bbc' temp file not insert into queue return is_sync = False for sync_path in self.sync_list: if event.pathname.startswith(sync_path) \ and event.pathname != (sync_path + '+') \ and event.pathname != (sync_path + '-') \ and event.pathname != (sync_path + '.lock'): # '+’,'-'和'.lock' temp file,such as: # /etc/passwd+ or /etc/passwd-,not sync; # file in sync files list, set is_sync is True pattern = "^%s\.\d+$" % sync_path match_obj = re.match(pattern, event.pathname) if match_obj is None: # "/etc/group.9869" temp file, not sync is_sync = True break if is_sync: # filter event if event.dir and (event.mask & (IN_DELETE | IN_MOVED_FROM)): eventq_tmp = deque() eventq_tmp.extend(self.eventq) dir_path = event.pathname + "/" for elem in eventq_tmp: if elem.pathname.startswith(dir_path): # dir_path is parent, remove its sub file or dir event LOGGER.debug("insert event pathname:%s, maskname:%s", elem.pathname, elem.maskname) self.eventq.remove(elem) search_distance = 0 is_insert = True for elem in self.eventq: search_distance += 1 if search_distance < SyncConf.MAX_SEARCH_LENGTH \ and elem.pathname == event.pathname: # update event's mask LOGGER.debug("update event pathname:%s, maskname:%s", event.pathname, event.maskname) elem.mask = event.mask elem.maskname = event.maskname is_insert = False break if is_insert: # insert into event if len(self.eventq) == SyncConf.MAX_QUEUE_LENGTH: self.cond.wait() LOGGER.debug("insert event pathname:%s, maskname:%s", event.pathname, event.maskname) self.eventq.append(event) self.cond.notify() finally: self.cond.release() def process_event(self, event): """process event""" self.insert_events(event) def process_IN_CREATE(self, event): LOGGER.debug("CREATE event:%s", event.pathname) self.process_event(event) def process_IN_DELETE(self, event): LOGGER.debug("DELETE event:%s", event.pathname) self.process_event(event) def process_IN_CLOSE_WRITE(self, event): LOGGER.debug("CLOSE_WRITE event:%s", event.pathname) self.process_event(event) def process_IN_MOVED_FROM(self, event): LOGGER.debug("MOVED_FROM event:%s", event.pathname) self.process_event(event) def process_IN_MOVED_TO(self, event): LOGGER.debug("MOVED_TO event:%s", event.pathname) self.process_event(event) def process_default(self, event): LOGGER.debug('defalut eventmask:%s, pathname:%s' \ % (event.maskname, event.pathname)) class FullSyncThread(threading.Thread): """Sync full files thread """ def __init__(self, remote_ip, name='FullSyncThread'): threading.Thread.__init__(self, name=name) self.remote_ip = remote_ip self.is_stoped = False def run(self): LOGGER.info('Start Full sync thread...') try: def full_sync(remote_ip): LOGGER.debug('Start full sync...') sync_files = SyncFiles() sync_files.sync_full_files(remote_ip) sub_thread = threading.Thread(target=full_sync, args=(self.remote_ip,)) sub_thread.setDaemon(True) sub_thread.start() except Exception, exp: LOGGER.info('Full sync except') LOGGER.exception(exp) while not self.is_stoped: sub_thread.join(1) if not sub_thread.is_alive(): break LOGGER.info('End Full sync thread...') def stop(self): LOGGER.info('Thread %s stop', self.name) self.is_stoped = True threading.Thread.join(self, 8)
StarcoderdataPython
8070797
""" CLI for Ray Tracer Challenge """ def cli(): pass
StarcoderdataPython
26970
<filename>sendmail.py import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart SMTP_URL = "example.com" def send_verification_code(recipient, recipient_name, verification_code): sender_email = "<EMAIL>" with open('.smtp_passwd') as password_file: password = password_file.read() message = MIMEMultipart("alternative") message["Subject"] = "Email Verification" message["From"] = sender_email message["To"] = recipient # Create the plain-text and HTML version of your message with open('verification_template.html', 'r') as templateobj: html = templateobj.read() html = html.replace('$$name', recipient_name) html = html.replace('$$verification_code', verification_code) # Turn these into plain/html MIMEText objects # part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first # message.attach(part1) message.attach(part2) # Create secure connection with server and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(SMTP_URL, 465, context=context) as server: server.login(sender_email, password) server.sendmail( sender_email, recipient, message.as_string() ) def send_thread_notif(recipient, recipient_name, forum, author, content): sender_email = "<EMAIL>" with open('.smtp_passwd') as password_file: password = password_file.read() message = MIMEMultipart("alternative") message["Subject"] = f"New message on {forum}" message["From"] = sender_email message["To"] = recipient # Create the plain-text and HTML version of your message with open('forum_notif_template.html', 'r') as templateobj: html = templateobj.read() html = html.replace('$$name', recipient_name) html = html.replace('$$forum', forum) html = html.replace('$$author', author) html = html.replace('$$content', content) # Turn these into plain/html MIMEText objects # part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first # message.attach(part1) message.attach(part2) # Create secure connection with server and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(SMTP_URL, 465, context=context) as server: server.login(sender_email, password) server.sendmail( sender_email, recipient, message.as_string() )
StarcoderdataPython
11350543
<reponame>fullstack-lumberjack/lumberjack<gh_stars>1-10 #!/usr/bin/env python3 import sys from easy_table import EasyTable myTable = EasyTable myTable.setTableCorners("/", "\\", "/", "\\") myTable.setTableBorder("|", "-") myTable.setTableInnerStructure("|", "-", "+") myTable.setColumns(["ID #", "Name", "Age"]) data = [["0","Jeff","31"],["1","Bill", "22"], ["2", "Tim", "33"], ["3", "Timothy", "41"]] myTable.setData(data) myTable.displayTable()
StarcoderdataPython
5043718
<reponame>lw0/dfaccto<filename>cfg/tb_streamtest.py<gh_stars>0 Inc('sim.py', abs='sim') Inc('streamtest.py') with EntTestbench( SimPort.Sys('sys', T('Sys', 'dfaccto')), SimPort.Source('stmSrc', T('LongStream')), SimPort.Sink('stmBufIn', T('LongStream')), SimPort.Source('stmBufOut', T('LongStream')), SimPort.Sink('stmSnk', T('LongStream'))): Ins('Streamtest', None, MapPort('sys', S('sys')), MapPort('stmSrc', S('stmSrc')), MapPort('stmBufIn', S('stmBufIn')), MapPort('stmBufOut', S('stmBufOut')), MapPort('stmSnk', S('stmSnk')))
StarcoderdataPython
4832330
<reponame>daniktl/task-scheduler-put-project<filename>tests/test_machine.py<gh_stars>1-10 from task_scheduler.machine import * from task_scheduler.task import * import random def test_machine_basic(test_machine: Machine): assert test_machine.speed == 1.2 def test_machine_tasks(test_machine: Machine): assert test_machine.get_time_available() == 0 task = Task(1, 2, 3) assert test_machine.check_time_ready(task) == 5.4 test_machine.add_task(task) assert test_machine.get_time_available() == 5.4 def test_machine_get_tasks(test_machine: Machine, test_tasks: list): tasks = list(sorted(test_tasks, key=lambda x: x.r_time)) for task in tasks: test_machine.add_task(task) assert isinstance(test_machine.get_tasks(id_only=True), list) assert len(test_machine.get_tasks(id_only=True)) == len(test_tasks) def test_machine_count_mode_3(): machines_number = 3 tasks_number = 5 # p_times == [4, 5, 6] # d_time == 7 # w == 8 machines = [Machine(machine_id=i, speed=1) for i in range(machines_number)] tasks = [Task() for _ in range(tasks_number)] [task.parse_input(task_id=task_id, input_str="4 5 6 7 8") for task_id, task in enumerate(tasks)] for machine_id, machine in enumerate(machines): for task_id, task in enumerate(tasks): machine.add_task( task, p_time=task.p_times[machine_id], min_start_time=machines[machine_id - 1].get_time_available(task_id) if machine_id else 0) assert machines[-1].get_time_over_weighted() == 800.0
StarcoderdataPython
3301031
"`fastai.layers` provides essential functions to building and modifying `model` architectures" from .torch_core import * __all__ = ['AdaptiveConcatPool2d', 'CrossEntropyFlat', 'Debugger', 'Flatten', 'Lambda', 'PoolFlatten', 'ResizeBatch', 'StdUpsample', 'bn_drop_lin', 'conv2d', 'conv2d_relu', 'conv2d_trans', 'conv_layer', 'get_embedding', 'simple_cnn', 'std_upsample_head', 'trunc_normal_'] class Lambda(nn.Module): "An easy way to create a pytorch layer for a simple `func`." def __init__(self, func:LambdaFunc): "create a layer that simply calls `func` with `x`" super().__init__() self.func=func def forward(self, x): return self.func(x) def ResizeBatch(*size:int) -> Tensor: "Layer that resizes x to `size`, good for connecting mismatched layers." return Lambda(lambda x: x.view((-1,)+size)) def Flatten()->Tensor: "Flattens `x` to a single dimension, often used at the end of a model." return Lambda(lambda x: x.view((x.size(0), -1))) def PoolFlatten()->nn.Sequential: "Apply `nn.AdaptiveAvgPool2d` to `x` and then flatten the result." return nn.Sequential(nn.AdaptiveAvgPool2d(1), Flatten()) def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0., actn:Optional[nn.Module]=None): "`n_in`->bn->dropout->linear(`n_in`,`n_out`)->`actn`" layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(nn.Linear(n_in, n_out)) if actn is not None: layers.append(actn) return layers def conv2d(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias=False) -> nn.Conv2d: "Create `nn.Conv2d` layer: `ni` inputs, `nf` outputs, `ks` kernel size. `padding` defaults to `k//2`." if padding is None: padding = ks//2 return nn.Conv2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias) def conv_layer(ni:int, nf:int, ks:int=3, stride:int=1)->nn.Sequential: "Create Conv2d->BatchNorm2d->LeakyReLu layer: `ni` input, `nf` out filters, `ks` kernel, `stride`:stride." return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks//2), nn.BatchNorm2d(nf), nn.LeakyReLU(negative_slope=0.1, inplace=True)) def conv2d_relu(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bn:bool=False, bias:bool=False) -> nn.Sequential: """Create a `conv2d` layer with `nn.ReLU` activation and optional(`bn`) `nn.BatchNorm2d`: `ni` input, `nf` out filters, `ks` kernel, `stride`:stride, `padding`:padding, `bn`: batch normalization.""" layers = [conv2d(ni, nf, ks=ks, stride=stride, padding=padding, bias=bias), nn.ReLU()] if bn: layers.append(nn.BatchNorm2d(nf)) return nn.Sequential(*layers) def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0) -> nn.ConvTranspose2d: "Create `nn.ConvTranspose2d` layer: `ni` inputs, `nf` outputs, `ks` kernel size, `stride`: stride. `padding` defaults to 0." return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding) class AdaptiveConcatPool2d(nn.Module): "Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`." def __init__(self, sz:Optional[int]=None): "Output will be 2*sz or 2 if sz is None" super().__init__() sz = sz or 1 self.ap,self.mp = nn.AdaptiveAvgPool2d(sz), nn.AdaptiveMaxPool2d(sz) def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1) class Debugger(nn.Module): "A module to debug inside a model." def forward(self,x:Tensor) -> Tensor: set_trace() return x class StdUpsample(nn.Module): "Increases the dimensionality of our data by applying a transposed convolution layer." def __init__(self, n_in:int, n_out:int): super().__init__() self.conv = conv2d_trans(n_in, n_out) self.bn = nn.BatchNorm2d(n_out) def forward(self, x:Tensor) -> Tensor: return self.bn(F.relu(self.conv(x))) def std_upsample_head(c, *nfs:Collection[int]) -> Model: "Create a sequence of upsample layers." return nn.Sequential( nn.ReLU(), *(StdUpsample(nfs[i],nfs[i+1]) for i in range(4)), conv2d_trans(nfs[-1], c) ) class CrossEntropyFlat(nn.CrossEntropyLoss): "Same as `nn.CrossEntropyLoss`, but flattens input and target." def forward(self, input:Tensor, target:Tensor) -> Rank0Tensor: n,c,*_ = input.shape return super().forward(input.view(n, c, -1), target.view(n, -1)) def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None) -> nn.Sequential: "CNN with `conv2d_relu` layers defined by `actns`, `kernel_szs` and `strides`." nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) strides = ifnone(strides , [2]*nl) layers = [conv2d_relu(actns[i], actns[i+1], kernel_szs[i], stride=strides[i]) for i in range_of(strides)] layers.append(PoolFlatten()) return nn.Sequential(*layers) def trunc_normal_(x:Tensor, mean:float=0., std:float=1.) -> Tensor: "Truncated normal initialization." # From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12 return x.normal_().fmod_(2).mul_(std).add_(mean) def get_embedding(ni:int,nf:int) -> Model: "Create an embedding layer." emb = nn.Embedding(ni, nf) # See https://arxiv.org/abs/1711.09160 with torch.no_grad(): trunc_normal_(emb.weight, std=0.01) return emb
StarcoderdataPython
166180
<reponame>GiantTreeLP/porth-jvm from jawa.assemble import Label from jawa.attributes.bootstrap import BootstrapMethod, BootstrapMethodsAttribute from jawa.constants import MethodHandleKind from extensions.DeduplicatingClassFile import DeduplicatingClassFile from jvm.intrinsics import OperandType from jvm.intrinsics.stack import Stack cf = DeduplicatingClassFile.create("Test") cf.attributes.create(BootstrapMethodsAttribute) def test_aaload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("anewarray", cf.constants.create_class("java/lang/String"), 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[0] == OperandType.Reference assert stack._stack[1] == OperandType.Integer stack.update_stack("aaload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_aastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("anewarray", cf.constants.create_class("java/lang/String"), 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[0] == OperandType.Reference assert stack._stack[1] == OperandType.Integer stack.update_stack("ldc", cf.constants.create_string("Hello, World!")) assert len(stack._stack) == 3 assert stack._stack[0] == OperandType.Reference assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Reference stack.update_stack("aastore") assert len(stack._stack) == 0 def test_aconst_null(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_aload(): stack = Stack() stack.update_stack("aload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack = Stack() stack.update_stack("aload_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack = Stack() stack.update_stack("aload_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack = Stack() stack.update_stack("aload_2") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack = Stack() stack.update_stack("aload_3") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_anewarray(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("anewarray", cf.constants.create_class("java/lang/String"), 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_areturn(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("areturn") assert len(stack._stack) == 0 def test_arraylength(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("anewarray", cf.constants.create_class("java/lang/String"), 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("arraylength") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_astore(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("astore") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("astore_0") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("astore_1") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("astore_2") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("astore_3") assert len(stack._stack) == 0 def test_athrow(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("athrow") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_baload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Byte.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("baload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Byte def test_bastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Byte.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_0") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("bastore") assert len(stack._stack) == 0 def test_bipush(): stack = Stack() stack.update_stack("bipush", 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_caload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Char.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("caload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Char def test_castore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Char.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_0") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("castore") assert len(stack._stack) == 0 def test_checkcast(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("checkcast", cf.constants.create_class("java/lang/String")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_d2f(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("d2f") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_d2i(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("d2i") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_d2l(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("d2l") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_dadd(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("dadd") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_daload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Double.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("daload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Double.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("dconst_0") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Double stack.update_stack("dastore") assert len(stack._stack) == 0 def test_dcmpg(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("dcmpg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_dcmpl(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("dcmpl") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_dconst(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack = Stack() stack.update_stack("dconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_ddiv(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("ddiv") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dload(): stack = Stack() stack.update_stack("dload", 0) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack = Stack() stack.update_stack("dload_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack = Stack() stack.update_stack("dload_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack = Stack() stack.update_stack("dload_2") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack = Stack() stack.update_stack("dload_3") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dmul(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("dmul") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dneg(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dneg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_drem(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("drem") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dreturn(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dreturn") assert len(stack._stack) == 0 def test_dstore(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dstore", 0) assert len(stack._stack) == 0 stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dstore_0") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dstore_1") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dstore_2") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dstore_3") assert len(stack._stack) == 0 def test_dsub(): stack = Stack() stack.update_stack("dconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double stack.update_stack("dconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Double stack.update_stack("dsub") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_dup(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("dup") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer def test_dup_x1(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("dup_x1") assert len(stack._stack) == 3 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer def test_dup_x2(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("dup_x2") assert len(stack._stack) == 4 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer assert stack._stack[3] == OperandType.Integer stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("dup_x2") assert len(stack._stack) == 3 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Long assert stack._stack[2] == OperandType.Integer def test_dup2(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("dup2") assert len(stack._stack) == 4 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer assert stack._stack[3] == OperandType.Integer stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("dup2") assert len(stack._stack) == 2 assert stack._stack[0] == OperandType.Long assert stack._stack[1] == OperandType.Long def test_dup2_x1(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("dup2_x1") assert len(stack._stack) == 5 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer assert stack._stack[3] == OperandType.Integer assert stack._stack[4] == OperandType.Integer stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("lconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("dup2_x1") assert len(stack._stack) == 3 assert stack._stack[0] == OperandType.Long assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Long def test_dup2_x2(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("iconst_3") assert len(stack._stack) == 4 assert stack._stack[3] == OperandType.Integer stack.update_stack("dup2_x2") assert len(stack._stack) == 6 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer assert stack._stack[3] == OperandType.Integer assert stack._stack[4] == OperandType.Integer assert stack._stack[5] == OperandType.Integer stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("lconst_1") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Long stack.update_stack("dup2_x2") assert len(stack._stack) == 4 assert stack._stack[0] == OperandType.Long assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Integer assert stack._stack[3] == OperandType.Long stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("dup2_x2") assert len(stack._stack) == 5 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer assert stack._stack[2] == OperandType.Long assert stack._stack[3] == OperandType.Integer assert stack._stack[4] == OperandType.Integer stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("dup2_x2") assert len(stack._stack) == 3 assert stack._stack[0] == OperandType.Long assert stack._stack[1] == OperandType.Long assert stack._stack[2] == OperandType.Long def test_f2d(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("f2d") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_f2i(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("f2i") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_f2l(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("f2l") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_fadd(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fadd") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_faload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Float.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("faload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_fastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Float.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("fconst_0") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Float stack.update_stack("fastore") assert len(stack._stack) == 0 def test_fcmpg(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fcmpg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_fcmpl(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fcmpl") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_fconst(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fconst_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Float def test_fdiv(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fdiv") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_fload(): stack = Stack() stack.update_stack("fload_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fload_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fload_2") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Float stack.update_stack("fload_3") assert len(stack._stack) == 4 assert stack._stack[3] == OperandType.Float def test_fmul(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fmul") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_fneg(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fneg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_frem(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("frem") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_freturn(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("freturn") assert len(stack._stack) == 0 def test_fstore(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fstore_0") assert len(stack._stack) == 0 stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fstore_1") assert len(stack._stack) == 0 stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fstore_2") assert len(stack._stack) == 0 stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fstore_3") assert len(stack._stack) == 0 def test_fsub(): stack = Stack() stack.update_stack("fconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack.update_stack("fconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Float stack.update_stack("fsub") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_getfield(): stack = Stack() stack.update_stack("new", cf.constants.create_class("java/lang/String")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("getfield", cf.constants.create_field_ref("java/lang/System", "out", "Ljava/io/PrintStream;")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_getstatic(): stack = Stack() stack.update_stack("getstatic", cf.constants.create_field_ref("java/lang/System", "out", "Ljava/io/PrintStream;")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_goto(): stack = Stack() stack.update_stack("goto", Label("label")) assert len(stack._stack) == 0 def test_goto_w(): stack = Stack() stack.update_stack("goto_w", Label("label")) assert len(stack._stack) == 0 def test_i2b(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2b") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Byte def test_i2c(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2c") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Char def test_i2d(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2d") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_i2f(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2f") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_i2l(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2l") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_i2s(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("i2s") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Short def test_iadd(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iadd") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_iaload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Integer.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iaload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_iand(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iand") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_iastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Integer.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("iastore") assert len(stack._stack) == 0 def test_iconst(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iconst_2") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iconst_3") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iconst_4") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iconst_5") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_idiv(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("idiv") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_if_acmp(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("aconst_null") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Reference stack.update_stack("if_acmpeq") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("aconst_null") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Reference stack.update_stack("if_acmpne") assert len(stack._stack) == 0 def test_if_icmp(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmpeq") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmpne") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmplt") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmpge") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmpgt") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("if_icmple") assert len(stack._stack) == 0 def test_if(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ifne") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ifeq") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iflt") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ifge") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ifgt") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ifle") assert len(stack._stack) == 0 def test_ifnonnull(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("ifnonnull") assert len(stack._stack) == 0 def test_ifnull(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("ifnull") assert len(stack._stack) == 0 def test_iinc(): stack = Stack() stack.update_stack("iinc", 0, 0) assert len(stack._stack) == 0 def test_iload(): stack = Stack() stack.update_stack("iload", 0) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iload_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iload_2") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("iload_3") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_imul(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("imul") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_ineg(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ineg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_instanceof(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("instanceof", cf.constants.create_class("java/lang/String")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Boolean def test_invokedynamic(): method_handle = cf.constants.create_method_handle( MethodHandleKind.INVOKE_STATIC, "java/lang/invoke/StringConcatFactory", "makeConcatWithConstants", "(Ljava/lang/invoke/MethodHandles$Lookup;" "Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)" "Ljava/lang/invoke/CallSite;" ) cf.bootstrap_methods.append( BootstrapMethod(method_handle.index, (cf.constants.create_string("\1=\1\0").index,))) make_concat_with_constants = cf.constants.create_invoke_dynamic( len(cf.bootstrap_methods) - 1, "makeConcatWithConstants", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;" ) stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("aconst_null") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Reference stack.update_stack("invokedynamic", make_concat_with_constants, 0, 0) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_invokeinterface(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("invokeinterface", cf.constants.create_method_ref( "java/lang/CharSequence", "length", "()I" ), 0) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_invokespecial(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("invokespecial", cf.constants.create_method_ref( "java/lang/Object", "<init>", "()V" )) assert len(stack._stack) == 0 def test_invokestatic(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("invokestatic", cf.constants.create_method_ref( "java/lang/System", "exit", "(I)V" )) assert len(stack._stack) == 0 def test_invokevirtual(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("invokevirtual", cf.constants.create_method_ref( "java/lang/Object", "toString", "()Ljava/lang/String;" )) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_ior(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("ior") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_irem(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("irem") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_ireturn(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("ireturn") assert len(stack._stack) == 0 def test_ishl(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("ishl") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_ishr(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("ishr") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_istore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("istore", 0) assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("istore_0") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("istore_1") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("istore_2") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("istore_3") def test_isub(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("isub") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_iushr(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iushr") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_ixor(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("ixor") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_jsr(): stack = Stack() stack.update_stack("jsr") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_jsr_w(): stack = Stack() stack.update_stack("jsr_w") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_l2d(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("l2d") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_l2f(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("l2f") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float def test_l2i(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("l2i") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_ladd(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("ladd") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_laload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Long.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("laload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_land(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("land") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Long.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("lconst_0") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Long stack.update_stack("lastore") assert len(stack._stack) == 0 def test_lcmp(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lcmp") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_lconst(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("lconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_ldc(): stack = Stack() stack.update_stack("ldc", cf.constants.create_integer(1)) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack = Stack() stack.update_stack("ldc", cf.constants.create_float(1.0)) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Float stack = Stack() stack.update_stack("ldc", cf.constants.create_string("test")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack = Stack() stack.update_stack("ldc", cf.constants.create_class("java/lang/String")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_ldc2_w(): stack = Stack() stack.update_stack("ldc2_w", cf.constants.create_long(1)) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("ldc2_w", cf.constants.create_double(1.0)) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Double def test_ldiv(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("ldiv") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lload(): stack = Stack() stack.update_stack("lload", 0) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("lload_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("lload_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("lload_2") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack = Stack() stack.update_stack("lload_3") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lmul(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lmul") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lneg(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lneg") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lookupswitch(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("lookupswitch") assert len(stack._stack) == 0 def test_lor(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lor") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lrem(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lrem") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lreturn(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lreturn") assert len(stack._stack) == 0 def test_lshl(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("lshl") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lshr(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("lshr") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lstore(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lstore", 0) assert len(stack._stack) == 0 stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lstore_0") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lstore_1") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lstore_2") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lstore_3") assert len(stack._stack) == 0 def test_lsub(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lsub") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lushr(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("lushr") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_lxor(): stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("lconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Long stack.update_stack("lxor") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long def test_monitorenter(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("monitorenter") assert len(stack._stack) == 0 def test_monitorexit(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("monitorexit") assert len(stack._stack) == 0 def test_multianewarray(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("multianewarray", cf.constants.create_class("java/lang/String"), 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_new(): stack = Stack() stack.update_stack("new", cf.constants.create_class("java/lang/String")) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_newarray(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Integer.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference def test_nop(): stack = Stack() stack.update_stack("nop") assert len(stack._stack) == 0 def test_pop(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("pop") assert len(stack._stack) == 0 def test_pop2(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("pop2") assert len(stack._stack) == 0 stack = Stack() stack.update_stack("lconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Long stack.update_stack("pop2") assert len(stack._stack) == 0 def test_putfield(): stack = Stack() stack.update_stack("aconst_null") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("putfield", cf.constants.create_field_ref("java/lang/String", "value", "I")) assert len(stack._stack) == 0 def test_putstatic(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("putstatic", cf.constants.create_field_ref("java/lang/String", "value", "I")) assert len(stack._stack) == 0 def test_ret(): stack = Stack() stack.update_stack("ret") assert len(stack._stack) == 0 def test_return(): stack = Stack() stack.update_stack("return") assert len(stack._stack) == 0 def test_saload(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Short.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("saload") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Short def test_sastore(): stack = Stack() stack.update_stack("iconst_1") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("newarray", OperandType.Short.array_type) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Reference stack.update_stack("iconst_0") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 3 assert stack._stack[2] == OperandType.Integer stack.update_stack("sastore") assert len(stack._stack) == 0 def test_sipush(): stack = Stack() stack.update_stack("sipush", 1) assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer def test_swap(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("iconst_1") assert len(stack._stack) == 2 assert stack._stack[1] == OperandType.Integer stack.update_stack("swap") assert len(stack._stack) == 2 assert stack._stack[0] == OperandType.Integer assert stack._stack[1] == OperandType.Integer def test_tableswitch(): stack = Stack() stack.update_stack("iconst_0") assert len(stack._stack) == 1 assert stack._stack[0] == OperandType.Integer stack.update_stack("tableswitch", 0, 0, 0, 0) assert len(stack._stack) == 0
StarcoderdataPython
5149077
<reponame>pbipin/amicable_numbers """ Author: <NAME>. (mailto: <EMAIL>) http://iambipin.com 101010101 10 101010101 10 101 10 101010101 1010101010 10 1010101010 10 1010 10 1010101010 10 101 10 10 101 10 10 01 10 10 101 10 101 10 10 101 10 10 10 10 10 101 1010101010 10 1010101010 10 10 01 10 1010101010 1010101010 10 101010101 10 10 1010 101010101 10 101 10 10 10 10 010 10 10 101 10 10 10 10 10 10 1010101010 10 10 10 10 10 10 101010101 10 10 10 10 10 10 10 Amicable Numbers: Python program to find amicable numbers within a range. Two numbers are classified as amicable numbers if the sum of proper divisors of one number is equal to the other number, and vice versa. For example, 220 and 280 are amicable numbers for the above-mentioned reason. 220 - 1+2+4+5+10+11+20+22+44+55+110 = 284 284 - 1+2+4+71+142 = 220 """ def amicableNum(i): """ Function to create a set of amicable numbers """ global amicable j = 1 sumofdiv = 0 if(i % 2 == 0): #for even numbers while(j < (i/2)+1): if(i % j == 0): sumofdiv += j j += 1 else: #for odd numbers while(j < (i/3)+1): if(i % j == 0): sumofdiv += j j += 1 k = 1 ssum = 0 while(k < sumofdiv): if(sumofdiv % k == 0): ssum += k k += 1 if(ssum == i) and (sumofdiv != i): #condition for amicable numbers amicable.add(i) amicable.add(sumofdiv) try: num = int(input('Enter the number within which amicable numbers are to be found: ')) if(num <= 2): raise ValueError indexList = [] amicable = set() numrange = range(2, num) for i in range(2, num): amicableNum(i) amicList = list(amicable) #conversion from set to list amicList.sort() #list is sorted #list slicing(based on even and odd positions of elements) with zip() to convert in to list of #tuples(for printing as pairs) amicList = zip(amicList[::2], amicList[1::2]) aster = '*' print(aster * 60) print('The pair(s) of amicable numbers within {0} are:' .format(num)) print(*amicList) print(aster * 60) except(ValueError): print('Please enter a valid integer number greater than 2')
StarcoderdataPython