Best Python code snippet using pytest-play_python
variables.py
Source:variables.py
1class VariablesDict:2 """3 A VariablesDict is a sort of dictionary with special4 features, created to manage the variables of a monomial.5 In this case, we'll call keys variables and6 values exponents.7 Its main features are:8 - A VariablesDict is immutable9 - The default exponent is 0; therefore, variables with exponent 0 aren't stored10 - Variables aren't case sensitive11 - Variables must be letters from the latin alphabet and one-character long12 - Exponents must be positive integer13 """14 def __init__(self, variables=None, **kwargs):15 """16 Initialize the VariablesDict by giving it17 the pairs variable: exponent storing them18 in a dict (variables) or as keyword arguments:19 >>> VariablesDict({'x': 5, 'y': 3})20 {'x': 5, 'y': 3}21 >>> VariablesDict(x=5, y=3)22 {'x': 5, 'y': 3}23 NB: Variables are sorted24 >>> VariablesDict(k=2, b=3)25 {'b': 3, 'k': 2}26 As said above, variables aren't case sensitive, so27 they're always made lowercase28 >>> VariablesDict(X=2)29 {'x': 2}30 It also converts the exponent in integer if it's a whole number31 >>> VariablesDict(x=3.0)32 {'x': 3}33 It can raise an error if:34 - `variable` is not a string35 >>> VariablesDict({9: 9})36 Traceback (most recent call last):37 ...38 TypeError: variable's name must be a string39 - `variable` is too long40 >>> VariablesDict(xy=3)41 Traceback (most recent call last):42 ...43 ValueError: variable's name length must be one44 - `variable` is not alphabetical45 >>> VariablesDict(x2=9)46 Traceback (most recent call last):47 ...48 ValueError: variable's name must be alphabetical49 - `exponent` is not an integer (or a whole number)50 >>> VariablesDict(k=[])51 Traceback (most recent call last):52 ...53 TypeError: variable's exponent must be int54 >>> VariablesDict(z=7.13)55 Traceback (most recent call last):56 ...57 TypeError: variable's exponent must be a whole number58 - `exponent` is negative59 >>> VariablesDict(f=-3)60 Traceback (most recent call last):61 ...62 ValueError: variable's exponent must be positive63 It also checks if the dict is empty:64 >>> VariablesDict(a=2, b=8, c=3).is_empty65 False66 >>> VariablesDict(x=0).is_empty67 True68 :raise: TypeError, ValueError69 """70 # look for variables71 if not variables:72 variables = kwargs73 items = {}74 for variable, exponent in variables.items():75 # Check variable's name76 if not isinstance(variable, str):77 raise TypeError("variable's name must be a string")78 elif not variable.isalpha():79 raise ValueError("variable's name must be alphabetical")80 elif len(variable) > 1:81 raise ValueError("variable's name length must be one")82 # Check variable's exponent83 if not isinstance(exponent, (int, float)):84 raise TypeError("variable's exponent must be int")85 elif isinstance(exponent, float) and not exponent.is_integer():86 raise TypeError("variable's exponent must be a whole number")87 elif exponent < 0:88 raise ValueError("variable's exponent must be positive")89 # Add it to the items90 if not exponent == 0:91 items[variable.lower()] = int(exponent)92 # Set items93 self.__items = tuple(sorted((v, e) for v, e in items.items()))94 # Check if it's empty95 self.is_empty = not bool(len(self))96 ### Items97 def __getitem__(self, variable):98 """99 Returns the exponent for the given variable100 >>> VariablesDict(a=2)['a']101 2102 It returns 0 if that variable does not exists103 >>> VariablesDict(a=2)['b']104 0105 It can return an error if:106 - `variable` is not a string107 >>> VariablesDict({9: 9})108 Traceback (most recent call last):109 ...110 TypeError: variable's name must be a string111 - `variable` is too long112 >>> VariablesDict(xy=3)113 Traceback (most recent call last):114 ...115 ValueError: variable's name length must be one116 - `variable` is not alphabetical117 >>> VariablesDict(x2=9)118 Traceback (most recent call last):119 ...120 ValueError: variable's name must be alphabetical121 :type variable: string122 :rtype: int123 """124 # Check if kye is valid125 if not isinstance(variable, str):126 raise TypeError("variable's name must be a string")127 elif not variable.isalpha():128 raise ValueError("variable's name must be alphabetical")129 elif len(variable) > 1:130 raise ValueError("variable's name length must be one")131 variable = variable.lower()132 # Look if there is that variable in the dict133 for item in self.__items:134 if item[0] == variable:135 return item[1]136 # Otherwise return 0137 return 0138 def exponents(self):139 """140 Returns the exponents of the VariablesDict141 as a tuple142 >>> VariablesDict(a=2, b=3).exponents()143 (2, 3)144 :rtype: tuple145 """146 return tuple(item[1] for item in self.__items)147 def items(self):148 """149 Returns the pairs variable-exponent of the150 VariablesDict as a tuple of tuples151 >>> VariablesDict(a=2, b=3).items()152 (('a', 2), ('b', 3))153 :rtype: tuple154 """155 return self.__items156 def __iter__(self):157 """158 Returns the iterator of the VariablesDict159 >>> iter(VariablesDict(a=2, b=3))160 {'a': 2, 'b': 3}161 For more informations see :func:`VariablesDict.__next__()`.162 :rtype: VariablesDict163 """164 self.itern = 0165 return self166 def __next__(self):167 """168 Gets the next variable in the VariablesDict169 >>> i = iter(VariablesDict(a=2, b=3))170 >>> next(i)171 'a'172 >>> next(i)173 'b'174 >>> next(i)175 Traceback (most recent call last):176 ...177 StopIteration178 :rtype: str179 :raise: StopIteration180 """181 try:182 variable = self.__items[self.itern][0]183 self.itern += 1184 return variable185 except IndexError:186 raise StopIteration187 def __len__(self):188 """189 Returns the dict's len190 >>> len(VariablesDict(a=2, b=3))191 2192 :rtype: int193 """194 return len(self.__items)195 # Representation196 def __str__(self):197 """198 Returns the VariablesDict as a string, like a normal dict199 >>> str(VariablesDict(x=2, y=3))200 "{'x': 2, 'y': 3}"201 :rtype: str202 """203 return str({item[0]: item[1] for item in self.__items})204 def __repr__(self):205 """206 Returns the VariablesDict as a string207 >>> repr(VariablesDict(y=5))208 "{'y': 5}"209 For more informations see :func:`VariablesDict.__str__()`.210 :rtype: str211 """212 return self.__str__()213 # Operations214 def __add__(self, other):215 """216 Sums two VariablesDict, returning a VariablesDict217 whose exponents are the sum of the starting VariablesDicts' ones218 >>> VariablesDict(x=5, y=3) + VariablesDict(y=5)219 {'x': 5, 'y': 8}220 It raises a TypeError if `other` is not a VariablesDict221 >>> VariablesDict(x=1) + 3222 Traceback (most recent call last):223 ...224 TypeError: unsupported operand type(s) for +: 'VariablesDict' and 'int'225 :type other: VariablesDict226 :rtype: VariablesDict227 :raise: TypeError228 """229 # check if other is a VariablesDict230 if not isinstance(other, VariablesDict):231 raise TypeError(f"unsupported operand type(s) for +: 'VariablesDict' and '{other.__class__.__name__}'")232 result = {}233 # sum the variables' exponents234 for variable in set(self) | set(other):235 result[variable] = self[variable] + other[variable]236 return VariablesDict(result)237 def __sub__(self, other):238 """239 Return a VariablesDict whose values are the difference240 between the starting VariablesDicts' ones241 >>> VariablesDict(x=5, y=3) - VariablesDict(x=1, y=2)242 {'x': 4, 'y': 1}243 If any exponent becomes negative, a ValueError244 will be raised instead:245 >>> VariablesDict(c=2) - VariablesDict(c=3)246 Traceback (most recent call last):247 ...248 ValueError: variable's exponent must be positive249 It raises a TypeError if `other` is not a VariablesDict250 >>> VariablesDict(x=1) - 3251 Traceback (most recent call last):252 ...253 TypeError: unsupported operand type(s) for -: 'VariablesDict' and 'int'254 :type other: VariablesDict255 :rtype: VariablesDict256 :raise: ValueError, TypeError257 """258 if not isinstance(other, VariablesDict):259 raise TypeError(f"unsupported operand type(s) for -: 'VariablesDict' and '{other.__class__.__name__}'")260 result = {}261 # compute difference262 for variable in set(self) | set(other):263 result[variable] = self[variable] - other[variable]264 return VariablesDict(result)265 def __mul__ (self, other):266 """267 Returns a VariablesDict whose exponents are268 this one's, multiplied by a given (integer) number269 >>> VariablesDict(a=2, b= 5) * 3270 {'a': 6, 'b': 15}271 If the number is negative, a ValueError is272 raised273 >>> VariablesDict() * (-15)274 Traceback (most recent call last):275 ...276 ValueError: can't multiply a VariablesDict by a negative number277 It raises a TypeError if `other` is not an integer278 >>> VariablesDict(x=1) * '3'279 Traceback (most recent call last):280 ...281 TypeError: unsupported operand type(s) for *: 'VariablesDict' and 'str'282 :type other: int283 :rtype: VariablesDict284 :raise: TypeError, ValueError285 """286 # check other's type287 if not isinstance(other, int):288 raise TypeError(f"unsupported operand type(s) for *: 'VariablesDict' and '{other.__class__.__name__}'")289 elif other < 0:290 raise ValueError("can't multiply a VariablesDict by a negative number")291 variables = {}292 # multiply exponents293 for variable in self:294 variables[variable] = self[variable] * other295 return VariablesDict(variables)296 def __truediv__ (self, other):297 """298 Returns a VariablesDict whose values are299 this one's divided by a given (integer) number300 >>> VariablesDict(a=4, b=2) / 2301 {'a': 2, 'b': 1}302 If the VariableDict is not divisible303 by the given number, it will raise a ValueError304 >>> VariablesDict(x=7) / 3305 Traceback (most recent call last):306 ...307 ValueError: can't divide this VariablesDict by 3308 To see if a VariablesDict is divisible by a number,309 you can use modulus operator (see more at :func:`VariablesDict.__mod__()`):310 It raises a TypeError if `other` is not an integer311 >>> VariablesDict(x=1) / '3'312 Traceback (most recent call last):313 ...314 TypeError: unsupported operand type(s) for /: 'VariablesDict' and 'str'315 :type other: int316 :rtype: VariablesDict317 :raises: ValueError, TypeError318 """319 if not isinstance(other, int):320 raise TypeError(f"unsupported operand type(s) for /: 'VariablesDict' and '{other.__class__.__name__}'")321 if not self % other:322 raise ValueError(f"can't divide this VariablesDict by {other}")323 return VariablesDict(dict(map(lambda k: (k, self[k] / other), self)))324 def __mod__ (self, other):325 """326 Checks if the VariablesDict can be divided by a number327 (True => can be divided by `other`).328 >>> VariablesDict(a=2, b=4) % 2329 True330 >>> VariablesDict(a=2, b=4) % 3331 False332 It raises ValueError if `other` isn't a positive integer333 >>> VariablesDict(k=2) % (-7)334 Traceback (most recent call last):335 ...336 ValueError: can't use modulus with VariablesDict and negative numbers337 It raises a TypeError if `other` is not an integer338 >>> VariablesDict(x=1) % '3'339 Traceback (most recent call last):340 ...341 TypeError: unsupported operand type(s) for %: 'VariablesDict' and 'str'342 :type other: int343 :rtype: bool344 :raise: TypeError, ValueError345 """346 if not isinstance(other, int):347 raise TypeError(f"unsupported operand type(s) for %: 'VariablesDict' and '{other.__class__.__name__}'")348 elif other < 0:349 raise ValueError("can't use modulus with VariablesDict and negative numbers")350 return all(l % other == 0 for l in self.exponents())351 def __eq__(self, other):352 """353 Checks if two variablesDict are equivalent354 >>> VariablesDict(a=2, b=4) == VariablesDict(b=4, a=2)355 True356 If `other` is not a VariablesDict it always returns False357 >>> VariablesDict(a=2, b=4) == 3358 False359 :type other: VariablesDict360 :rtype: bool361 """362 if not isinstance(other, VariablesDict):363 return False364 return set(self.items()) == set(other.items())365 def __hash__(self):366 """367 Returns the hash of the VariablesDict by hashing368 the result of :func:`VariablesDict.items()`.369 :rtype: int370 """371 return hash(self.__items)372 def __bool__(self):373 """374 Returns the opposite of `is_empty`.375 >>> VariablesDict().is_empty376 True377 >>> bool(VariablesDict())378 False379 :rtype: int380 """...
variables_helper_tf1_test.py
Source:variables_helper_tf1_test.py
...23from object_detection.utils import tf_version24from object_detection.utils import variables_helper25@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only test.')26class FilterVariablesTest(test_case.TestCase):27 def _create_variables(self):28 return [tf.Variable(1.0, name='FeatureExtractor/InceptionV3/weights'),29 tf.Variable(1.0, name='FeatureExtractor/InceptionV3/biases'),30 tf.Variable(1.0, name='StackProposalGenerator/weights'),31 tf.Variable(1.0, name='StackProposalGenerator/biases')]32 def test_return_all_variables_when_empty_regex(self):33 variables = self._create_variables()34 out_variables = variables_helper.filter_variables(variables, [''])35 self.assertCountEqual(out_variables, variables)36 def test_return_variables_which_do_not_match_single_regex(self):37 variables = self._create_variables()38 out_variables = variables_helper.filter_variables(variables,39 ['FeatureExtractor/.*'])40 self.assertCountEqual(out_variables, variables[2:])41 def test_return_variables_which_do_not_match_any_regex_in_list(self):42 variables = self._create_variables()43 out_variables = variables_helper.filter_variables(variables, [44 'FeatureExtractor.*biases', 'StackProposalGenerator.*biases'45 ])46 self.assertCountEqual(out_variables, [variables[0], variables[2]])47 def test_return_variables_matching_empty_regex_list(self):48 variables = self._create_variables()49 out_variables = variables_helper.filter_variables(50 variables, [''], invert=True)51 self.assertCountEqual(out_variables, [])52 def test_return_variables_matching_some_regex_in_list(self):53 variables = self._create_variables()54 out_variables = variables_helper.filter_variables(55 variables,56 ['FeatureExtractor.*biases', 'StackProposalGenerator.*biases'],57 invert=True)58 self.assertCountEqual(out_variables, [variables[1], variables[3]])59@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only test.')60class MultiplyGradientsMatchingRegexTest(tf.test.TestCase):61 def _create_grads_and_vars(self):62 return [(tf.constant(1.0),63 tf.Variable(1.0, name='FeatureExtractor/InceptionV3/weights')),64 (tf.constant(2.0),65 tf.Variable(2.0, name='FeatureExtractor/InceptionV3/biases')),66 (tf.constant(3.0),67 tf.Variable(3.0, name='StackProposalGenerator/weights')),68 (tf.constant(4.0),69 tf.Variable(4.0, name='StackProposalGenerator/biases'))]70 def test_multiply_all_feature_extractor_variables(self):71 grads_and_vars = self._create_grads_and_vars()72 regex_list = ['FeatureExtractor/.*']73 multiplier = 0.074 grads_and_vars = variables_helper.multiply_gradients_matching_regex(75 grads_and_vars, regex_list, multiplier)76 exp_output = [(0.0, 1.0), (0.0, 2.0), (3.0, 3.0), (4.0, 4.0)]77 init_op = tf.global_variables_initializer()78 with self.test_session() as sess:79 sess.run(init_op)80 output = sess.run(grads_and_vars)81 self.assertCountEqual(output, exp_output)82 def test_multiply_all_bias_variables(self):83 grads_and_vars = self._create_grads_and_vars()84 regex_list = ['.*/biases']85 multiplier = 0.086 grads_and_vars = variables_helper.multiply_gradients_matching_regex(87 grads_and_vars, regex_list, multiplier)88 exp_output = [(1.0, 1.0), (0.0, 2.0), (3.0, 3.0), (0.0, 4.0)]89 init_op = tf.global_variables_initializer()90 with self.test_session() as sess:91 sess.run(init_op)92 output = sess.run(grads_and_vars)93 self.assertCountEqual(output, exp_output)94@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only test.')95class FreezeGradientsMatchingRegexTest(test_case.TestCase):96 def _create_grads_and_vars(self):97 return [(tf.constant(1.0),98 tf.Variable(1.0, name='FeatureExtractor/InceptionV3/weights')),99 (tf.constant(2.0),100 tf.Variable(2.0, name='FeatureExtractor/InceptionV3/biases')),101 (tf.constant(3.0),102 tf.Variable(3.0, name='StackProposalGenerator/weights')),103 (tf.constant(4.0),104 tf.Variable(4.0, name='StackProposalGenerator/biases'))]105 def test_freeze_all_feature_extractor_variables(self):106 grads_and_vars = self._create_grads_and_vars()107 regex_list = ['FeatureExtractor/.*']108 grads_and_vars = variables_helper.freeze_gradients_matching_regex(109 grads_and_vars, regex_list)110 exp_output = [(3.0, 3.0), (4.0, 4.0)]111 init_op = tf.global_variables_initializer()112 with self.test_session() as sess:113 sess.run(init_op)114 output = sess.run(grads_and_vars)115 self.assertCountEqual(output, exp_output)116@unittest.skipIf(tf_version.is_tf2(), 'Skipping TF1.X only test.')117class GetVariablesAvailableInCheckpointTest(test_case.TestCase):118 def test_return_all_variables_from_checkpoint(self):119 with tf.Graph().as_default():...
test_variable_command.py
Source:test_variable_command.py
...31 def setUpClass(cls):32 cls.dagbag = models.DagBag(include_examples=True)33 cls.parser = cli_parser.get_parser()34 def setUp(self):35 clear_db_variables()36 def tearDown(self):37 clear_db_variables()38 def test_variables_set(self):39 """Test variable_set command"""40 variable_command.variables_set(self.parser.parse_args(['variables', 'set', 'foo', 'bar']))41 self.assertIsNotNone(Variable.get("foo"))42 self.assertRaises(KeyError, Variable.get, "foo1")43 def test_variables_get(self):44 Variable.set('foo', {'foo': 'bar'}, serialize_json=True)45 with redirect_stdout(io.StringIO()) as stdout:46 variable_command.variables_get(self.parser.parse_args(['variables', 'get', 'foo']))47 self.assertEqual('{\n "foo": "bar"\n}\n', stdout.getvalue())48 def test_get_variable_default_value(self):49 with redirect_stdout(io.StringIO()) as stdout:50 variable_command.variables_get(51 self.parser.parse_args(['variables', 'get', 'baz', '--default', 'bar'])...
test_term_variables.py
Source:test_term_variables.py
1import py2from prolog.interpreter.test.tool import assert_true, assert_false, prolog_raises3from prolog.interpreter.test.tool import get_engine4def test_basic_term_variables():5 assert_true("term_variables(X, [X]).")6 assert_false("term_variables(X, []).")7 assert_true("term_variables(f(X, Y), [X, Y]).")8 assert_true("term_variables(a, []).")9 assert_true("term_variables(123, []).")10 assert_true("term_variables(f(Z, g(X), Y), [Z, X, Y]).")11 assert_false("term_variables(a, a).")12def test_more_advanced_term_variables():13 assert_true("term_variables([Y,Y,X,X],[Y,X]).")14 assert_true("term_variables([X, Y, a, f(g(A), X)], [X, Y, A]).")15 assert_true("term_variables((A :- B, C, A), [A,B,C]).")16 assert_true("term_variables(f(X, f(X)), [X]).")17 assert_true("X = 1, term_variables(f(X, Y), L), L == [Y], Y = 2.")18 assert_true("X = Y, term_variables(f(X, Y), L), L == [Y], Y = 2.")19def test_var_binding():20 assert_true("X = a, term_variables(X, []).")21 assert_true("term_variables(X, L), X = a, L = [a].")22 assert_true("X = f(A,B), term_variables(X, [A,B]).")23def test_term_variables_huge_list():24 py.test.skip("")25 e = get_engine("""26 make_triple_list(0, _, []).27 make_triple_list(X, Y, [Y, Y, Y | T]) :-28 X > 0, X1 is X - 1,29 make_triple_list(X1, Y, T).30 """)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!