input
stringlengths
11
7.65k
target
stringlengths
22
8.26k
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def debug_instance( self, ) -> Callable[[appengine.DebugInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the debug instance method over gRPC. Enables debugging on a VM instance. This allows you to use the SSH command to connect to the virtual machine where the instance lives. While in "debug mode", the instance continues to serve live traffic. You should delete the instance when you are done debugging and then allow the system to take over and determine if another instance should be started. Only applicable for instances in App Engine flexible environment. Returns: Callable[[~.DebugInstanceRequest], ~.Operation]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "debug_instance" not in self._stubs: self._stubs["debug_instance"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Instances/DebugInstance", request_serializer=appengine.DebugInstanceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["debug_instance"]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def close(self): self.grpc_channel.close()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def reset(cls): cls.info = [ [ "Keyboard Control:", " auto repeat: on key click percent: 0 LED mask: 00000002", " XKB indicators:", " 00: Caps Lock: off 01: Num Lock: on 02: Scroll Lock: off", " 03: Compose: off 04: Kana: off 05: Sleep: off", ], [ "Keyboard Control:", " auto repeat: on key click percent: 0 LED mask: 00000002", " XKB indicators:", " 00: Caps Lock: on 01: Num Lock: on 02: Scroll Lock: off", " 03: Compose: off 04: Kana: off 05: Sleep: off", ], ] cls.index = 0 cls.is_error = False
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def call_process(cls, cmd): if cls.is_error: raise subprocess.CalledProcessError(-1, cmd=cmd, output="Couldn't call xset.") if cmd[1:] == ["q"]: track = cls.info[cls.index] output = "\n".join(track) return output
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def patched_cnli(monkeypatch): MockCapsNumLockIndicator.reset() monkeypatch.setattr( "libqtile.widget.caps_num_lock_indicator.subprocess", MockCapsNumLockIndicator ) monkeypatch.setattr( "libqtile.widget.caps_num_lock_indicator.subprocess.CalledProcessError", subprocess.CalledProcessError, ) monkeypatch.setattr( "libqtile.widget.caps_num_lock_indicator.base.ThreadPoolText.call_process", MockCapsNumLockIndicator.call_process, ) return caps_num_lock_indicator
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_cnli(fake_qtile, patched_cnli, fake_window): widget = patched_cnli.CapsNumLockIndicator() fakebar = FakeBar([widget], window=fake_window) widget._configure(fake_qtile, fakebar) text = widget.poll() assert text == "Caps off Num on"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_cnli_caps_on(fake_qtile, patched_cnli, fake_window): widget = patched_cnli.CapsNumLockIndicator() # Simulate Caps on MockCapsNumLockIndicator.index = 1 fakebar = FakeBar([widget], window=fake_window) widget._configure(fake_qtile, fakebar) text = widget.poll() assert text == "Caps on Num on"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def draw_axis(img, charuco_corners, charuco_ids, board): vecs = np.load("./calib.npz") # I already calibrated the camera mtx, dist, _, _ = [vecs[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')] ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard( charuco_corners, charuco_ids, board, mtx, dist) if ret is not None and ret is True: cv2.aruco.drawAxis(img, mtx, dist, rvec, tvec, 0.1)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_image(camera): ret, img = camera.read() return img
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def make_grayscale(img): ret = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return ret
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def main(): camera = cv2.VideoCapture(0) img = get_image(camera) while True: cv2.imshow('calibration', img) cv2.waitKey(10) img = get_image(camera) gray = make_grayscale(img) corners, ids, rejected = cv2.aruco.detectMarkers(gray, aruco_dict, corners, ids) cv2.aruco.drawDetectedMarkers(img, corners, ids) if ids is not None and corners is not None \ and len(ids) > 0 and len(ids) == len(corners): diamond_corners, diamond_ids = \ cv2.aruco.detectCharucoDiamond(img, corners, ids, 0.05 / 0.03, cameraMatrix=mtx, distCoeffs=dist) cv2.aruco.drawDetectedDiamonds(img, diamond_corners, diamond_ids) '''if diamond_ids is not None and len(diamond_ids) >= 4: break''' board = cv2.aruco.CharucoBoard_create(9, 6, 0.05, 0.03, aruco_dict) if diamond_corners is not None and diamond_ids is not None \ and len(diamond_corners) == len(diamond_ids): count, char_corners, char_ids = \ cv2.aruco.interpolateCornersCharuco(diamond_corners, diamond_ids, gray, board) if count >= 3: draw_axis(img, char_corners, char_ids, board)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def process_weight(sym, arg, aux): for stride in RpnParam.anchor_generate.stride: add_anchor_to_arg( sym, arg, aux, RpnParam.anchor_generate.max_side, stride, RpnParam.anchor_generate.scale, RpnParam.anchor_generate.ratio)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): self.generate = self._generate()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): self.stride = (4, 8, 16, 32, 64) self.short = (200, 100, 50, 25, 13) self.long = (334, 167, 84, 42, 21)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def do_register_opts(opts, group=None, ignore_errors=False): try: cfg.CONF.register_opts(opts, group=group) except: if not ignore_errors: raise
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def do_register_cli_opts(opt, ignore_errors=False): # TODO: This function has broken name, it should work with lists :/ if not isinstance(opt, (list, tuple)): opts = [opt] else: opts = opt try: cfg.CONF.register_cli_opts(opts) except: if not ignore_errors: raise
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def new_tool_type(request): if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=Tool_Type()) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm() add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/new_tool_type.html', {'tform': tform})
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, "voir", "view") self.schema = "<cle>" self.aide_courte = "affiche le détail d'un chemin" self.aide_longue = \ "Cette commande permet d'obtenir plus d'informations sur " \ "un chemin (ses flags actifs, ses salles et sorties...)."
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def edit_tool_type(request, ttid): tool_type = Tool_Type.objects.get(pk=ttid) if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=tool_type) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm(instance=tool_type) add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/edit_tool_type.html', { 'tform': tform, })
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def ajouter(self): """Méthode appelée lors de l'ajout de la commande à l'interpréteur""" cle = self.noeud.get_masque("cle") cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def make_data(cuda=False): train_x = torch.linspace(0, 1, 100) train_y = torch.sin(train_x * (2 * pi)) train_y.add_(torch.randn_like(train_y), alpha=1e-2) test_x = torch.rand(51) test_y = torch.sin(test_x * (2 * pi)) if cuda: train_x = train_x.cuda() train_y = train_y.cuda() test_x = test_x.cuda() test_y = test_y.cuda() return train_x, train_y, test_x, test_y
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, train_x, train_y, likelihood): super(GPRegressionModel, self).__init__(train_x, train_y, likelihood) self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5)) self.base_covar_module = ScaleKernel(RBFKernel(lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1))) self.covar_module = InducingPointKernel( self.base_covar_module, inducing_points=torch.linspace(0, 1, 32), likelihood=likelihood )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return MultivariateNormal(mean_x, covar_x)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setUp(self): if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false": self.rng_state = torch.get_rng_state() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) random.seed(0)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def tearDown(self): if hasattr(self, "rng_state"): torch.set_rng_state(self.rng_state)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_sgpr_mean_abs_error(self): # Suppress numerical warnings warnings.simplefilter("ignore", NumericalWarning) train_x, train_y, test_x, test_y = make_data() likelihood = GaussianLikelihood() gp_model = GPRegressionModel(train_x, train_y, likelihood) mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) for _ in range(30): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() test_preds = likelihood(gp_model(test_x)).mean mean_abs_error = torch.mean(torch.abs(test_y - test_preds)) self.assertLess(mean_abs_error.squeeze().item(), 0.05)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_sgpr_fast_pred_var(self): # Suppress numerical warnings warnings.simplefilter("ignore", NumericalWarning) train_x, train_y, test_x, test_y = make_data() likelihood = GaussianLikelihood() gp_model = GPRegressionModel(train_x, train_y, likelihood) mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) for _ in range(50): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() with gpytorch.settings.max_preconditioner_size(5), gpytorch.settings.max_cg_iterations(50): with gpytorch.settings.fast_pred_var(True): fast_var = gp_model(test_x).variance fast_var_cache = gp_model(test_x).variance self.assertLess(torch.max((fast_var_cache - fast_var).abs()), 1e-3) with gpytorch.settings.fast_pred_var(False): slow_var = gp_model(test_x).variance self.assertLess(torch.max((fast_var_cache - slow_var).abs()), 1e-3)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_sgpr_mean_abs_error_cuda(self): # Suppress numerical warnings warnings.simplefilter("ignore", NumericalWarning) if not torch.cuda.is_available(): return with least_used_cuda_device(): train_x, train_y, test_x, test_y = make_data(cuda=True) likelihood = GaussianLikelihood().cuda() gp_model = GPRegressionModel(train_x, train_y, likelihood).cuda() mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) optimizer.n_iter = 0 for _ in range(25): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.n_iter += 1 optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() test_preds = likelihood(gp_model(test_x)).mean mean_abs_error = torch.mean(torch.abs(test_y - test_preds)) self.assertLess(mean_abs_error.squeeze().item(), 0.02)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_subclass(self): class X(Structure): _fields_ = [("a", c_int)] class Y(X): _fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)])
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_subclass_delayed(self): class X(Structure): pass self.assertEqual(sizeof(X), 0) X._fields_ = [("a", c_int)] class Y(X): pass self.assertEqual(sizeof(Y), sizeof(X)) Y._fields_ = [("b", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [("a", c_int)]) self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)])
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_simple_structs(self): for code, tp in self.formats.items(): class X(Structure): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("c%c0%c" % (code, code)), code))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_unions(self): for code, tp in self.formats.items(): class X(Union): _fields_ = [("x", c_char), ("y", tp)] self.assertEqual((sizeof(X), code), (calcsize("%c" % (code)), code))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_struct_alignment(self): class X(Structure): _fields_ = [("x", c_char * 3)] self.assertEqual(alignment(X), calcsize("s")) self.assertEqual(sizeof(X), calcsize("3s")) class Y(Structure): _fields_ = [("x", c_char * 3), ("y", c_int)] self.assertEqual(alignment(Y), calcsize("i")) self.assertEqual(sizeof(Y), calcsize("3si")) class SI(Structure): _fields_ = [("a", X), ("b", Y)] self.assertEqual(alignment(SI), max(alignment(Y), alignment(X))) self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i")) class IS(Structure): _fields_ = [("b", Y), ("a", X)] self.assertEqual(alignment(SI), max(alignment(X), alignment(Y))) self.assertEqual(sizeof(IS), calcsize("3si 3s 0i")) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), alignment(X)) self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_emtpy(self): # I had problems with these # # Although these are patological cases: Empty Structures! class X(Structure): _fields_ = [] class Y(Union): _fields_ = [] # Is this really the correct alignment, or should it be 0? self.assertTrue(alignment(X) == alignment(Y) == 1) self.assertTrue(sizeof(X) == sizeof(Y) == 0) class XX(Structure): _fields_ = [("a", X), ("b", X)] self.assertEqual(alignment(XX), 1) self.assertEqual(sizeof(XX), 0)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, sizeof(c_int)) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) class X(Union): _fields_ = [("x", c_int), ("y", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, 0) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92) # XXX Should we check nested data types also? # offset is always relative to the class...
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_packed(self): class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 1 self.assertEqual(sizeof(X), 9) self.assertEqual(X.b.offset, 1) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 2 self.assertEqual(sizeof(X), 10) self.assertEqual(X.b.offset, 2) class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 4 self.assertEqual(sizeof(X), 12) self.assertEqual(X.b.offset, 4) import struct longlong_size = struct.calcsize("q") longlong_align = struct.calcsize("bq") - longlong_size class X(Structure): _fields_ = [("a", c_byte), ("b", c_longlong)] _pack_ = 8 self.assertEqual(sizeof(X), longlong_align + longlong_size) self.assertEqual(X.b.offset, min(8, longlong_align)) d = {"_fields_": [("a", "b"), ("b", "q")], "_pack_": -1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) # Issue 15989 d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.INT_MAX + 1} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) d = {"_fields_": [("a", c_byte)], "_pack_": _testcapi.UINT_MAX + 2} self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_initializers(self): class Person(Structure): _fields_ = [("name", c_char*6), ("age", c_int)] self.assertRaises(TypeError, Person, 42) self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj") self.assertRaises(TypeError, Person, "Name", "HI") # short enough self.assertEqual(Person(b"12345", 5).name, b"12345") # exact fit self.assertEqual(Person(b"123456", 5).name, b"123456") # too long self.assertRaises(ValueError, Person, b"1234567", 5)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_conflicting_initializers(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] # conflicting positional and keyword args self.assertRaises(TypeError, POINT, 2, 3, x=4) self.assertRaises(TypeError, POINT, 2, 3, y=4) # too many initializers self.assertRaises(TypeError, POINT, 2, 3, 4)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_keyword_initializers(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] pt = POINT(1, 2) self.assertEqual((pt.x, pt.y), (1, 2)) pt = POINT(y=2, x=1) self.assertEqual((pt.x, pt.y), (1, 2))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_invalid_field_types(self): class POINT(Structure): pass self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def declare_with_name(name): class S(Structure): _fields_ = [(name, c_int)]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_intarray_fields(self): class SomeInts(Structure): _fields_ = [("a", c_int * 4)] # can use tuple to initialize array (but not list!) self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0]) self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2]) self.assertEqual(SomeInts((1, 2)).a[6:4:-1], []) self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) # too long # XXX Should raise ValueError?, not RuntimeError self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_nested_initializers(self): # test initializing nested structures class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] p = Person(b"Someone", (b"1234", b"5678"), 5) self.assertEqual(p.name, b"Someone") self.assertEqual(p.phone.areacode, b"1234") self.assertEqual(p.phone.number, b"5678") self.assertEqual(p.age, 5)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_structures_with_wchar(self): try: c_wchar except NameError: return # no unicode class PersonW(Structure): _fields_ = [("name", c_wchar * 12), ("age", c_int)] p = PersonW("Someone \xe9") self.assertEqual(p.name, "Someone \xe9") self.assertEqual(PersonW("1234567890").name, "1234567890") self.assertEqual(PersonW("12345678901").name, "12345678901") # exact fit self.assertEqual(PersonW("123456789012").name, "123456789012") #too long self.assertRaises(ValueError, PersonW, "1234567890123")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_init_errors(self): class Phone(Structure): _fields_ = [("areacode", c_char*6), ("number", c_char*12)] class Person(Structure): _fields_ = [("name", c_char * 12), ("phone", Phone), ("age", c_int)] cls, msg = self.get_except(Person, b"Someone", (1, 2)) self.assertEqual(cls, RuntimeError) self.assertEqual(msg, "(Phone) <class 'TypeError'>: " "expected string, int found") cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c")) self.assertEqual(cls, RuntimeError) if issubclass(Exception, object): self.assertEqual(msg, "(Phone) <class 'TypeError'>: too many initializers") else: self.assertEqual(msg, "(Phone) TypeError: too many initializers")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def create_class(length): class S(Structure): _fields_ = [('x' * length, c_int)]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_except(self, func, *args): try: func(*args) except Exception as detail: return detail.__class__, str(detail)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_abstract_class(self): class X(Structure): _abstract_ = "something" # try 'X()' cls, msg = self.get_except(eval, "X()", locals()) self.assertEqual((cls, msg), (TypeError, "abstract class"))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_methods(self):
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_positional_args(self): # see also http://bugs.python.org/issue5042 class W(Structure): _fields_ = [("a", c_int), ("b", c_int)] class X(W): _fields_ = [("c", c_int)] class Y(X): pass class Z(Y): _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)] z = Z(1, 2, 3, 4, 5, 6) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 2, 3, 4, 5, 6)) z = Z(1) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 0, 0, 0, 0, 0)) self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test(self): # a Structure with a POINTER field class S(Structure): _fields_ = [("array", POINTER(c_int))] s = S() # We can assign arrays of the correct type s.array = (c_int * 3)(1, 2, 3) items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) # The following are bugs, but are included here because the unittests # also describe the current behaviour. # # This fails with SystemError: bad arg to internal function # or with IndexError (with a patch I have) s.array[0] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [42, 2, 3]) s.array[0] = 1
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_none_to_pointer_fields(self): class S(Structure): _fields_ = [("x", c_int), ("p", POINTER(c_int))] s = S() s.x = 12345678 s.p = None self.assertEqual(s.x, 12345678)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_contains_itself(self): class Recursive(Structure): pass try: Recursive._fields_ = [("next", Recursive)] except AttributeError as details: self.assertTrue("Structure or union cannot contain itself" in str(details)) else: self.fail("Structure or union cannot contain itself")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_vice_versa(self): class First(Structure): pass class Second(Structure): pass First._fields_ = [("second", Second)] try: Second._fields_ = [("first", First)] except AttributeError as details: self.assertTrue("_fields_ is final" in str(details)) else: self.fail("AttributeError not raised")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def config(self): settings = { # Use SYSTEMMPI since openfoam-org doesn't have USERMPI 'mplib': 'SYSTEMMPI', # Add links into bin/, lib/ (eg, for other applications) 'link': False, } # OpenFOAM v2.4 and earlier lacks WM_LABEL_OPTION if self.spec.satisfies('@:2.4'): settings['label-size'] = False return settings
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self,title,richtext,text): self.title=title self.richtext=richtext self.text=text
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setup_run_environment(self, env): bashrc = self.prefix.etc.bashrc try: env.extend(EnvironmentModifications.from_sourcing_file( bashrc, clean=True )) except Exception as e: msg = 'unexpected error when sourcing OpenFOAM bashrc [{0}]' tty.warn(msg.format(str(e)))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): self.factory = yui.YUI.widgetFactory() self.dialog = self.factory.createPopupDialog() mainvbox = self.factory.createVBox(self.dialog) frame = self.factory.createFrame(mainvbox,"Test frame") HBox = self.factory.createHBox(frame) self.aboutbutton = self.factory.createPushButton(HBox,"&About") self.closebutton = self.factory.createPushButton(self.factory.createRight(HBox), "&Close")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setup_dependent_build_environment(self, env, dependent_spec): """Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of previous versions. """ env.set('FOAM_PROJECT_DIR', self.projectdir)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def ask_YesOrNo(self, info): yui.YUI.widgetFactory mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga")) dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO) dlg.setTitle(info.title) dlg.setText(info.text, info.richtext) dlg.setButtonLabel("Yes", yui.YMGAMessageBox.B_ONE) dlg.setButtonLabel("No", yui.YMGAMessageBox.B_TWO) dlg.setMinSize(50, 5); return dlg.show() == yui.YMGAMessageBox.B_ONE
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setup_dependent_run_environment(self, env, dependent_spec): """Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of previous versions. """ env.set('FOAM_PROJECT_DIR', self.projectdir)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def aboutDialog(self): yui.YUI.widgetFactory; mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga")) dlg = mgafactory.createAboutDialog("About dialog title example", "1.0.0", "GPLv3", "Angelo Naselli", "This beautiful test example shows how it is easy to play with libyui bindings", "") dlg.show();
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def projectdir(self): """Absolute location of project directory: WM_PROJECT_DIR/""" return self.prefix # <- install directly under prefix
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def handleevent(self): """ Event-handler for the 'widgets' demo """ while True: event = self.dialog.waitForEvent() if event.eventType() == yui.YEvent.CancelEvent: self.dialog.destroy() break if event.widget() == self.closebutton: info = Info("Quit confirmation", 1, "Are you sure you want to quit?") if self.ask_YesOrNo(info): self.dialog.destroy() break if event.widget() == self.aboutbutton: self.aboutDialog()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def foam_arch(self): if not self._foam_arch: self._foam_arch = OpenfoamOrgArch(self.spec, **self.config) return self._foam_arch
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def archbin(self): """Relative location of architecture-specific executables""" return join_path('platforms', self.foam_arch, 'bin')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def archlib(self): """Relative location of architecture-specific libraries""" return join_path('platforms', self.foam_arch, 'lib')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def rename_source(self): """This is fairly horrible. The github tarfiles have weird names that do not correspond to the canonical name. We need to rename these, but leave a symlink for spack to work with. """ # Note that this particular OpenFOAM requires absolute directories # to build correctly! parent = os.path.dirname(self.stage.source_path) original = os.path.basename(self.stage.source_path) target = 'OpenFOAM-{0}'.format(self.version) # Could also grep through etc/bashrc for WM_PROJECT_VERSION with working_dir(parent): if original != target and not os.path.lexists(target): os.rename(original, target) os.symlink(target, original) tty.info('renamed {0} -> {1}'.format(original, target))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def patch(self): """Adjust OpenFOAM build for spack. Where needed, apply filter as an alternative to normal patching.""" self.rename_source() add_extra_files(self, self.common, self.assets) # Avoid WM_PROJECT_INST_DIR for ThirdParty, site or jobControl. # Use openfoam-site.patch to handle jobControl, site. # # Filtering: bashrc,cshrc (using a patch is less flexible) edits = { 'WM_THIRD_PARTY_DIR': r'$WM_PROJECT_DIR/ThirdParty #SPACK: No separate third-party', 'WM_VERSION': str(self.version), # consistency 'FOAMY_HEX_MESH': '', # This is horrible (unset variable?) } rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path('etc', 'bashrc'), cshell=join_path('etc', 'cshrc'))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def configure(self, spec, prefix): """Make adjustments to the OpenFOAM configuration files in their various locations: etc/bashrc, etc/config.sh/FEATURE and customizations that don't properly fit get placed in the etc/prefs.sh file (similiarly for csh). """ # Filtering bashrc, cshrc edits = {} edits.update(self.foam_arch.foam_dict()) rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path('etc', 'bashrc'), cshell=join_path('etc', 'cshrc')) # MPI content, with absolute paths user_mpi = mplib_content(spec) # Content for etc/prefs.{csh,sh} self.etc_prefs = { r'MPI_ROOT': spec['mpi'].prefix, # Absolute r'MPI_ARCH_FLAGS': '"%s"' % user_mpi['FLAGS'], r'MPI_ARCH_INC': '"%s"' % user_mpi['PINC'], r'MPI_ARCH_LIBS': '"%s"' % user_mpi['PLIBS'], } # Content for etc/config.{csh,sh}/ files self.etc_config = { 'CGAL': {}, 'scotch': {}, 'metis': {}, 'paraview': [], 'gperftools': [], # Currently unused } if True: self.etc_config['scotch'] = { 'SCOTCH_ARCH_PATH': spec['scotch'].prefix, # For src/parallel/decompose/Allwmake 'SCOTCH_VERSION': 'scotch-{0}'.format(spec['scotch'].version), } if '+metis' in spec: self.etc_config['metis'] = { 'METIS_ARCH_PATH': spec['metis'].prefix, } # Write prefs files according to the configuration. # Only need prefs.sh for building, but install both for end-users if self.etc_prefs: write_environ( self.etc_prefs, posix=join_path('etc', 'prefs.sh'), cshell=join_path('etc', 'prefs.csh')) # Adjust components to use SPACK variants for component, subdict in self.etc_config.items(): # Versions up to 3.0 used an etc/config/component.sh naming # convention instead of etc/config.sh/component if spec.satisfies('@:3.0'): write_environ( subdict, posix=join_path('etc', 'config', component) + '.sh', cshell=join_path('etc', 'config', component) + '.csh') else: write_environ( subdict, posix=join_path('etc', 'config.sh', component), cshell=join_path('etc', 'config.csh', component))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def build(self, spec, prefix): """Build using the OpenFOAM Allwmake script, with a wrapper to source its environment first. Only build if the compiler is known to be supported. """ self.foam_arch.has_rule(self.stage.source_path) self.foam_arch.create_rules(self.stage.source_path, self) args = [] if self.parallel: # Build in parallel? - pass via the environment os.environ['WM_NCOMPPROCS'] = str(make_jobs) builder = Executable(self.build_script) builder(*args)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def install(self, spec, prefix): """Install under the projectdir""" mkdirp(self.projectdir) projdir = os.path.basename(self.projectdir) # Filtering: bashrc, cshrc edits = { 'WM_PROJECT_INST_DIR': os.path.dirname(self.projectdir), 'WM_PROJECT_DIR': join_path('$WM_PROJECT_INST_DIR', projdir), } # All top-level files, except spack build info and possibly Allwmake if '+source' in spec: ignored = re.compile(r'^spack-.*') else: ignored = re.compile(r'^(Allwmake|spack-).*') files = [ f for f in glob.glob("*") if os.path.isfile(f) and not ignored.search(f) ] for f in files: install(f, self.projectdir) # Having wmake and ~source is actually somewhat pointless... # Install 'etc' before 'bin' (for symlinks) # META-INFO for 1812 and later (or backported) dirs = ['META-INFO', 'etc', 'bin', 'wmake'] if '+source' in spec: dirs.extend(['applications', 'src', 'tutorials']) for d in dirs: if os.path.isdir(d): install_tree( d, join_path(self.projectdir, d), symlinks=True) dirs = ['platforms'] if '+source' in spec: dirs.extend(['doc']) # Install platforms (and doc) skipping intermediate targets relative_ignore_paths = ['src', 'applications', 'html', 'Guides'] ignore = lambda p: p in relative_ignore_paths for d in dirs: install_tree( d, join_path(self.projectdir, d), ignore=ignore, symlinks=True) etc_dir = join_path(self.projectdir, 'etc') rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path(etc_dir, 'bashrc'), cshell=join_path(etc_dir, 'cshrc')) self.install_links()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def install_links(self): """Add symlinks into bin/, lib/ (eg, for other applications)""" # Make build log visible - it contains OpenFOAM-specific information with working_dir(self.projectdir): os.symlink( join_path(os.path.relpath(self.install_log_path)), join_path('log.' + str(self.foam_arch))) if not self.config['link']: return # ln -s platforms/linux64GccXXX/lib lib with working_dir(self.projectdir): if os.path.isdir(self.archlib): os.symlink(self.archlib, 'lib') # (cd bin && ln -s ../platforms/linux64GccXXX/bin/* .) with working_dir(join_path(self.projectdir, 'bin')): for f in [ f for f in glob.glob(join_path('..', self.archbin, "*")) if os.path.isfile(f) ]: os.symlink(f, os.path.basename(f))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def linear_search(lst,size,value): i = 0 while i < size: if lst[i] == value: return i i = i + 1 return -1
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def main(): lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782] size = len(lst) original_list = "" value = int(input("\nInput a value to search for: ")) print("\nOriginal Array: ") for i in lst: original_list += str(i) + " " print(original_list) print("\nLinear Search Big O Notation:\n--> Best Case: O(1)\n--> Average Case: O(n)\n--> Worst Case: O(n)\n") index = linear_search(lst,size,value) if index == -1: print(str(value) + " was not found in that array\n") else: print(str(value) + " was found at index " + str(index))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setUp(self): self.credentials = { 'username': 'testuser', 'password': 'test1234', 'email': 'test@mail.com'} # Create a test Group my_group, created = Group.objects.get_or_create(name='test_group') # Add user to test Group User.objects.get(pk=1).groups.add(my_group)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, *args, **kwargs): BaseConverter.__init__(self, *args, **kwargs) self.type_ = "string" self.regex = '[^(/;)]+'
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_user_login(self): c = Client() # User points the browser to the landing page res = c.post('/', follow=True) # the user is not logged in self.assertFalse(res.context['user'].is_authenticated) # and is redirected to the login page self.assertRedirects(res, '/login/') # The login page is being rendered by the correct template self.assertTemplateUsed(res, 'registration/login.html') # asks the user to login using a set of valid credentials res = c.post('/login/', data=self.credentials, follow=True) # The system acknowledges him self.assertTrue(res.context['user'].is_authenticated) # and moves him at the dashboard self.assertTemplateUsed(res, 'app/dashboard.html')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, *args, **kwargs): FloatConverter.__init__(self, *args, **kwargs) self.type_ = "float" self.regex = '-?\\d+(\\.\\d+)?'
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_public_views(client, expectedStatus): res = client.get('/public/task/{}/map/'.format(task.id)) self.assertTrue(res.status_code == expectedStatus) res = client.get('/public/task/{}/3d/'.format(task.id)) self.assertTrue(res.status_code == expectedStatus) res = client.get('/public/task/{}/iframe/3d/'.format(task.id)) self.assertTrue(res.status_code == expectedStatus) res = client.get('/public/task/{}/iframe/map/'.format(task.id)) self.assertTrue(res.status_code == expectedStatus) res = client.get('/public/task/{}/json/'.format(task.id)) self.assertTrue(res.status_code == expectedStatus)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_admin_views(self): c = Client() c.login(username='testsuperuser', password='test1234') settingId = Setting.objects.all()[0].id # During tests, sometimes this is != 1 themeId = Theme.objects.all()[0].id # During tests, sometimes this is != 1 # Can access admin menu items admin_menu_items = ['/admin/app/setting/{}/change/'.format(settingId), '/admin/app/theme/{}/change/'.format(themeId), '/admin/', '/admin/app/plugin/', '/admin/auth/user/', '/admin/auth/group/', ] for url in admin_menu_items: res = c.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) # Cannot access dev tools (not in dev mode) settings.DEV = False self.assertEqual(c.get('/dev-tools/').status_code, status.HTTP_404_NOT_FOUND) settings.DEV = True
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, *args, **kwargs): PathConverter.__init__(self, *args, **kwargs) self.type_ = "string"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_default_group(self): # It exists self.assertTrue(Group.objects.filter(name='Default').count() == 1) # Verify that all new users are assigned to default group u = User.objects.create_user(username="default_user") u.refresh_from_db() self.assertTrue(u.groups.filter(name='Default').count() == 1)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, *args, **kwargs): BaseConverter.__init__(self, *args, **kwargs) self.type_ = "string"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_projects(self): # Get a normal user user = User.objects.get(username="testuser") self.assertFalse(user.is_superuser) # Create a new project p = Project.objects.create(owner=user, name="test") # Have the proper permissions been set? self.assertTrue(user.has_perm("view_project", p)) self.assertTrue(user.has_perm("add_project", p)) self.assertTrue(user.has_perm("change_project", p)) self.assertTrue(user.has_perm("delete_project", p)) # Get a superuser superUser = User.objects.get(username="testsuperuser") self.assertTrue(superUser.is_superuser) # He should also have permissions, although not explicitly set self.assertTrue(superUser.has_perm("delete_project", p)) # Get another user anotherUser = User.objects.get(username="testuser2") self.assertFalse(anotherUser.is_superuser) # Should not have permission self.assertFalse(anotherUser.has_perm("delete_project", p))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, api, name): super(V1Routing, self).__init__(api, name, description='Current version of navitia API', status='current', index_endpoint='index')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def looks_like_hash(sha): return bool(HASH_REGEX.match(sha))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _get_unique_constraints(self, table): """Retrieve information about existing unique constraints of the table This feature is needed for _recreate_table() to work properly. Unfortunately, it's not available in sqlalchemy 0.7.x/0.8.x. """ data = table.metadata.bind.execute( """SELECT sql FROM sqlite_master WHERE type='table' AND name=:table_name""", table_name=table.name ).fetchone()[0] UNIQUE_PATTERN = "CONSTRAINT (\w+) UNIQUE \(([^\)]+)\)" return [ UniqueConstraint( *[getattr(table.columns, c.strip(' "')) for c in cols.split(",")], name=name ) for name, cols in re.findall(UNIQUE_PATTERN, data) ]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_base_rev_args(rev): return [rev]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _recreate_table(self, table, column=None, delta=None, omit_uniques=None): """Recreate the table properly Unlike the corresponding original method of sqlalchemy-migrate this one doesn't drop existing unique constraints when creating a new one. """ table_name = self.preparer.format_table(table) # we remove all indexes so as not to have # problems during copy and re-create for index in table.indexes: index.drop() # reflect existing unique constraints for uc in self._get_unique_constraints(table): table.append_constraint(uc) # omit given unique constraints when creating a new table if required table.constraints = set([ cons for cons in table.constraints if omit_uniques is None or cons.name not in omit_uniques ]) self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name) self.execute() insertion_string = self._modify_table(table, column, delta) table.create(bind=self.connection) self.append(insertion_string % {'table_name': table_name}) self.execute() self.append('DROP TABLE migration_tmp') self.execute()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def is_immutable_rev_checkout(self, url, dest): # type: (str, str) -> bool _, rev_options = self.get_url_rev_options(hide_url(url)) if not rev_options.rev: return False if not self.is_commit_id_equal(dest, rev_options.rev): # the current commit is different from rev, # which means rev was something else than a commit hash return False # return False in the rare case rev is both a commit hash # and a tag or a branch; we don't want to cache in that case # because that branch/tag could point to something else in the future is_tag_or_branch = bool( self.get_revision_sha(dest, rev_options.rev)[0] ) return not is_tag_or_branch
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _visit_migrate_unique_constraint(self, *p, **k): """Drop the given unique constraint The corresponding original method of sqlalchemy-migrate just raises NotImplemented error """ self.recreate_table(p[0].table, omit_uniques=[p[0].name])
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_git_version(self): VERSION_PFX = 'git version ' version = self.run_command( ['version'], show_stdout=False, stdout_only=True ) if version.startswith(VERSION_PFX): version = version[len(VERSION_PFX):].split()[0] else: version = '' # get first 3 positions of the git version because # on windows it is x.y.z.windows.t, and this parses as # LegacyVersion which always smaller than a Version. version = '.'.join(version.split('.')[:3]) return parse_version(version)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def patch_migrate(): """A workaround for SQLite's inability to alter things SQLite abilities to alter tables are very limited (please read http://www.sqlite.org/lang_altertable.html for more details). E. g. one can't drop a column or a constraint in SQLite. The workaround for this is to recreate the original table omitting the corresponding constraint (or column). sqlalchemy-migrate library has recreate_table() method that implements this workaround, but it does it wrong: - information about unique constraints of a table is not retrieved. So if you have a table with one unique constraint and a migration adding another one you will end up with a table that has only the latter unique constraint, and the former will be lost - dropping of unique constraints is not supported at all The proper way to fix this is to provide a pull-request to sqlalchemy-migrate, but the project seems to be dead. So we can go on with monkey-patching of the lib at least for now. """ # this patch is needed to ensure that recreate_table() doesn't drop # existing unique constraints of the table when creating a new one helper_cls = sqlite.SQLiteHelper helper_cls.recreate_table = _recreate_table helper_cls._get_unique_constraints = _get_unique_constraints # this patch is needed to be able to drop existing unique constraints constraint_cls = sqlite.SQLiteConstraintDropper constraint_cls.visit_migrate_unique_constraint = \ _visit_migrate_unique_constraint constraint_cls.__bases__ = (ansisql.ANSIColumnDropper, sqlite.SQLiteConstraintGenerator)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_current_branch(cls, location): """ Return the current branch, or None if HEAD isn't at a branch (e.g. detached HEAD). """ # git-symbolic-ref exits with empty stdout if "HEAD" is a detached # HEAD rather than a symbolic ref. In addition, the -q causes the # command to exit with status code 1 instead of 128 in this case # and to suppress the message to stderr. args = ['symbolic-ref', '-q', 'HEAD'] output = cls.run_command( args, extra_ok_returncodes=(1, ), show_stdout=False, stdout_only=True, cwd=location, ) ref = output.strip() if ref.startswith('refs/heads/'): return ref[len('refs/heads/'):] return None
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True): """Upgrade or downgrade a database. Function runs the upgrade() or downgrade() functions in change scripts. :param engine: SQLAlchemy engine instance for a given database :param abs_path: Absolute path to migrate repository. :param version: Database will upgrade/downgrade until this version. If None - database will update to the latest available version. :param init_version: Initial database version :param sanity_check: Require schema sanity checking for all tables """ if version is not None: try: version = int(version) except ValueError: raise exception.DbMigrationError( message=_("version should be an integer")) current_version = db_version(engine, abs_path, init_version) repository = _find_migrate_repo(abs_path) if sanity_check: _db_schema_sanity_check(engine) if version is None or version > current_version: return versioning_api.upgrade(engine, repository, version) else: return versioning_api.downgrade(engine, repository, version)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def export(self, location, url): # type: (str, HiddenText) -> None """Export the Git repository at the url to the destination location""" if not location.endswith('/'): location = location + '/' with TempDirectory(kind="export") as temp_dir: self.unpack(temp_dir.path, url=url) self.run_command( ['checkout-index', '-a', '-f', '--prefix', location], show_stdout=False, cwd=temp_dir.path )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _db_schema_sanity_check(engine): """Ensure all database tables were created with required parameters. :param engine: SQLAlchemy engine instance for a given database """ if engine.name == 'mysql': onlyutf8_sql = ('SELECT TABLE_NAME,TABLE_COLLATION ' 'from information_schema.TABLES ' 'where TABLE_SCHEMA=%s and ' 'TABLE_COLLATION NOT LIKE "%%utf8%%"') table_names = [res[0] for res in engine.execute(onlyutf8_sql, engine.url.database)] if len(table_names) > 0: raise ValueError(_('Tables "%s" have non utf8 collation, ' 'please make sure all tables are CHARSET=utf8' ) % ','.join(table_names))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_revision_sha(cls, dest, rev): """ Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. """ # Pass rev to pre-filter the list. output = cls.run_command( ['show-ref', rev], cwd=dest, show_stdout=False, stdout_only=True, on_returncode='ignore', ) refs = {} for line in output.strip().splitlines(): try: sha, ref = line.split() except ValueError: # Include the offending line to simplify troubleshooting if # this error ever occurs. raise ValueError('unexpected show-ref line: {!r}'.format(line)) refs[ref] = sha branch_ref = 'refs/remotes/origin/{}'.format(rev) tag_ref = 'refs/tags/{}'.format(rev) sha = refs.get(branch_ref) if sha is not None: return (sha, True) sha = refs.get(tag_ref) return (sha, False)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def db_version(engine, abs_path, init_version): """Show the current version of the repository. :param engine: SQLAlchemy engine instance for a given database :param abs_path: Absolute path to migrate repository :param version: Initial database version """ repository = _find_migrate_repo(abs_path) try: return versioning_api.db_version(engine, repository) except versioning_exceptions.DatabaseNotControlledError: meta = sqlalchemy.MetaData() meta.reflect(bind=engine) tables = meta.tables if len(tables) == 0 or 'alembic_version' in tables: db_version_control(engine, abs_path, version=init_version) return versioning_api.db_version(engine, repository) else: raise exception.DbMigrationError( message=_( "The database is not under version control, but has " "tables. Please stamp the current version of the schema " "manually."))