How to use method method in sinon

Best JavaScript code snippet using sinon

vtkMethodParser.py

Source:vtkMethodParser.py Github

copy

Full Screen

1"""2This python module provides functionality to parse the methods of a3VTK object.4Created by Prabhu Ramachandran. Committed in Apr, 2002.5"""6import string, re, sys7import types8# set this to 1 if you want to see debugging messages - very useful if9# you have problems10DEBUG=011def debug (msg):12 if DEBUG:13 print msg14class VtkDirMethodParser:15 """ Parses the methods from dir(vtk_obj). """16 def initialize_methods (self, vtk_obj):17 debug ("VtkDirMethodParser:: initialize_methods ()")18 self.methods = dir (vtk_obj)[:]19 # stores the <blah>On methods20 self.toggle_meths = []21 # stores the Set<blah>To<blah> methods22 self.state_meths = []23 # stores the methods that have a Get<blah> and Set<blah>24 # only the <blah> is stored25 self.get_set_meths = []26 # pure get methods27 self.get_meths = []28 self.state_patn = re.compile ("To[A-Z0-9]")29 def parse_methods (self, vtk_obj):30 debug ("VtkDirMethodParser:: parse_methods()")31 self.initialize_methods (vtk_obj) 32 debug ("VtkDirMethodParser:: parse_methods() - initialized methods")33 34 for method in self.methods[:]:35 # finding all the methods that set the state.36 if string.find (method[:3], "Set") >= 0 and \37 self.state_patn.search (method) is not None :38 try:39 eval ("vtk_obj.Get%s"%method[3:])40 except AttributeError:41 self.state_meths.append (method)42 self.methods.remove (method)43 # finding all the On/Off toggle methods44 elif string.find (method[-2:], "On") >= 0:45 try:46 self.methods.index ("%sOff"%method[:-2])47 except ValueError:48 pass49 else:50 self.toggle_meths.append (method)51 self.methods.remove (method)52 self.methods.remove ("%sOff"%method[:-2])53 # finding the Get/Set methods.54 elif string.find (method[:3], "Get") == 0:55 set_m = "Set"+method[3:]56 try:57 self.methods.index (set_m)58 except ValueError:59 pass60 else:61 self.get_set_meths.append (method[3:])62 self.methods.remove (method)63 self.methods.remove (set_m)64 self.clean_up_methods (vtk_obj)65 def clean_up_methods (self, vtk_obj):66 self.clean_get_set (vtk_obj)67 self.clean_state_methods (vtk_obj)68 self.clean_get_methods (vtk_obj)69 def clean_get_set (self, vtk_obj):70 debug ("VtkDirMethodParser:: clean_get_set()")71 # cleaning up the Get/Set methods by removing the toggle funcs.72 for method in self.toggle_meths:73 try:74 self.get_set_meths.remove (method[:-2])75 except ValueError:76 pass77 # cleaning them up by removing any methods that are responsible for78 # other vtkObjects79 for method in self.get_set_meths[:]:80 try:81 eval ("vtk_obj.Get%s ().GetClassName ()"%method)82 except (TypeError, AttributeError):83 pass84 else:85 self.get_set_meths.remove (method)86 continue87 try:88 val = eval ("vtk_obj.Get%s ()"%method)89 except (TypeError, AttributeError):90 self.get_set_meths.remove (method)91 else:92 if val is None:93 self.get_set_meths.remove (method)94 95 def clean_state_methods (self, vtk_obj):96 debug ("VtkDirMethodParser:: clean_state_methods()")97 # Getting the remaining pure GetMethods98 for method in self.methods[:]:99 if string.find (method[:3], "Get") == 0:100 self.get_meths.append (method)101 self.methods.remove (method)102 # Grouping similar state methods103 if len (self.state_meths) != 0:104 tmp = self.state_meths[:]105 self.state_meths = []106 state_group = [tmp[0]]107 end = self.state_patn.search (tmp[0]).start ()108 # stores the method type common to all similar methods109 m = tmp[0][3:end]110 for i in range (1, len (tmp)):111 if string.find (tmp[i], m) >= 0:112 state_group.append (tmp[i])113 else:114 self.state_meths.append (state_group)115 state_group = [tmp[i]] 116 end = self.state_patn.search (tmp[i]).start ()117 m = tmp[i][3:end]118 try: # remove the corresponding set method in get_set119 val = self.get_set_meths.index (m)120 except ValueError:121 pass122 else:123 del self.get_set_meths[val]124 #self.get_meths.append ("Get"+m)125 clamp_m = "Get" + m + "MinValue"126 try: # remove the GetNameMax/MinValue in get_meths127 val = self.get_meths.index (clamp_m)128 except ValueError:129 pass130 else:131 del self.get_meths[val]132 val = self.get_meths.index ("Get" + m + "MaxValue")133 del self.get_meths[val]134 if len (state_group) > 0:135 self.state_meths.append (state_group)136 def clean_get_methods (self, vtk_obj):137 debug ("VtkDirMethodParser:: clean_get_methods()")138 for method in self.get_meths[:]:139 debug (method)140 try:141 res = eval ("vtk_obj.%s ()"%method)142 except (TypeError, AttributeError):143 self.get_meths.remove (method)144 continue145 else:146 try:147 eval ("vtk_obj.%s ().GetClassName ()"%method)148 except AttributeError:149 pass150 else:151 self.get_meths.remove (method)152 continue153 if string.find (method[-8:], "MaxValue") > -1:154 self.get_meths.remove( method)155 elif string.find (method[-8:], "MinValue") > -1:156 self.get_meths.remove( method)157 self.get_meths.sort ()158 def toggle_methods (self):159 return self.toggle_meths160 def state_methods (self):161 return self.state_meths162 def get_set_methods (self):163 return self.get_set_meths164 def get_methods (self):165 return self.get_meths166class VtkPrintMethodParser:167 """ This class finds the methods for a given vtkObject. It uses168 the output from vtkObject->Print() (or in Python str(vtkObject))169 and output from the VtkDirMethodParser to obtain the methods. """170 def parse_methods (self, vtk_obj):171 "Parse for the methods."172 debug ("VtkPrintMethodParser:: parse_methods()")173 if self._initialize_methods (vtk_obj):174 # if David Gobbi's improvements are in this version of VTK175 # then I need to go no further.176 return177 for method in self.methods[:]:178 # removing methods that have nothing to the right of the ':'179 if (method[1] == '') or \180 (string.find (method[1], "none") > -1) :181 self.methods.remove (method)182 for method in self.methods:183 # toggle methods are first identified184 if (method[1] == "On") or (method[1] == "Off"):185 try:186 val = eval ("vtk_obj.Get%s ()"%method[0])187 if val == 1:188 eval ("vtk_obj.%sOn ()"%method[0])189 elif val == 0:190 eval ("vtk_obj.%sOff ()"%method[0])191 except AttributeError:192 pass193 else:194 self.toggle_meths.append (method[0]+"On") 195 else: # see it it is get_set or get or a state method196 found = 0197 # checking if it is a state func.198 # figure out the long names from the dir_state_meths199 for sms in self.dir_state_meths[:]:200 if string.find (sms[0], method[0]) >= 0:201 self.state_meths.append (sms)202 self.dir_state_meths.remove (sms)203 found = 1204 if found:205 self.get_meths.append ("Get"+method[0])206 try:207 t = eval ("vtk_obj.Get%sAsString ()"%method[0])208 except AttributeError:209 pass210 else:211 self.get_meths.append ("Get"+method[0]+"AsString")212 else:213 # the long name is inherited or it is not a state method214 try:215 t = eval ("vtk_obj.Get%s ().GetClassName ()"%216 method[0])217 except AttributeError:218 pass219 else:220 continue 221 val = 0222 try:223 val = eval ("vtk_obj.Get%s ()"%method[0])224 except (TypeError, AttributeError):225 pass226 else:227 try:228 f = eval ("vtk_obj.Set%s"%method[0])229 except AttributeError:230 self.get_meths.append ("Get"+method[0])231 else:232 try:233 apply (f, val)234 except TypeError:235 try:236 apply (f, (val, ))237 except TypeError:238 self.get_meths.append ("Get"+method[0])239 else:240 self.get_set_meths.append (method[0])241 else:242 self.get_set_meths.append (method[0])243 self._clean_up_methods (vtk_obj)244 def _get_str_obj (self, vtk_obj):245 debug ("VtkPrintMethodParser:: _get_str_obj()")246 self.methods = str (vtk_obj)247 self.methods = string.split (self.methods, "\n")248 del self.methods[0]249 def _initialize_methods (self, vtk_obj):250 "Do the basic parsing and setting up"251 debug ("VtkPrintMethodParser:: _initialize_methods()")252 dir_p = VtkDirMethodParser ()253 dir_p.parse_methods (vtk_obj)254 # testing if this version of vtk has David Gobbi's cool255 # stuff. If it does then no need to do other things.256 try:257 junk = vtk_obj.__class__258 except AttributeError:259 pass260 else:261 self.toggle_meths = dir_p.toggle_methods ()262 self.state_meths = dir_p.state_methods ()263 self.get_set_meths = dir_p.get_set_methods ()264 self.get_meths = dir_p.get_methods ()265 return 1266 self.dir_toggle_meths = dir_p.toggle_methods ()267 self.dir_state_meths = dir_p.state_methods ()268 self.dir_get_set_meths = dir_p.get_set_methods ()269 self.dir_get_meths = dir_p.get_methods ()270 self._get_str_obj (vtk_obj)271 patn = re.compile (" \S")272 for method in self.methods[:]:273 if not patn.match (method):274 self.methods.remove (method)275 for method in self.methods[:]:276 if string.find (method, ":") == -1:277 self.methods.remove (method)278 for i in range (0, len (self.methods)):279 strng = self.methods[i]280 strng = string.replace (strng, " ", "")281 self.methods[i] = string.split (strng, ":")282 self.toggle_meths = []283 self.state_meths = []284 self.get_set_meths = []285 self.get_meths = []286 return 0287 def _clean_up_methods (self, vtk_obj):288 "Merge dir and str methods. Finish up."289 debug ("VtkPrintMethodParser:: _clean_up_methods()")290 for meth_list in ((self.dir_toggle_meths, self.toggle_meths),\291 (self.dir_get_set_meths, self.get_set_meths),\292 (self.dir_get_meths, self.get_meths)):293 for method in meth_list[0]:294 try:295 meth_list[1].index (method)296 except ValueError:297 meth_list[1].append (method)298 # Remove all get_set methods that are already in toggle_meths299 # This case can happen if the str produces no "On/Off" but300 # dir does and str produces a get_set instead.301 for method in self.toggle_meths:302 try:303 self.get_set_meths.remove (method[:-2])304 except ValueError:305 pass306 self.toggle_meths.sort ()307 self.state_meths.sort ()308 self.get_set_meths.sort ()309 self.get_meths.sort ()310 def toggle_methods (self):311 return self.toggle_meths312 def state_methods (self):313 return self.state_meths314 def get_set_methods (self):315 return self.get_set_meths316 def get_methods (self):...

Full Screen

Full Screen

test_algebraic_connectivity.py

Source:test_algebraic_connectivity.py Github

copy

Full Screen

...81 assert_equal(nx.algebraic_connectivity(G), 0)82 assert_raises(nx.NetworkXError, nx.fiedler_vector, G,83 method=method)84 @preserve_random_state85 def test_unrecognized_method(self):86 G = nx.path_graph(4)87 assert_raises(nx.NetworkXError, nx.algebraic_connectivity, G,88 method='unknown')89 assert_raises(nx.NetworkXError, nx.fiedler_vector, G, method='unknown')90 @preserve_random_state91 def test_two_nodes(self):92 G = nx.Graph()93 G.add_edge(0, 1, weight=1)94 A = nx.laplacian_matrix(G)95 for method in self._methods:96 assert_almost_equal(nx.algebraic_connectivity(97 G, tol=1e-12, method=method), 2)98 x = nx.fiedler_vector(G, tol=1e-12, method=method)99 check_eigenvector(A, 2, x)100 G = nx.MultiGraph()101 G.add_edge(0, 0, spam=1e8)102 G.add_edge(0, 1, spam=1)103 G.add_edge(0, 1, spam=-2)104 A = -3 * nx.laplacian_matrix(G, weight='spam')105 for method in self._methods:106 assert_almost_equal(nx.algebraic_connectivity(107 G, weight='spam', tol=1e-12, method=method), 6)108 x = nx.fiedler_vector(G, weight='spam', tol=1e-12, method=method)109 check_eigenvector(A, 6, x)110 @preserve_random_state111 def test_path(self):112 G = nx.path_graph(8)113 A = nx.laplacian_matrix(G)114 sigma = 2 - sqrt(2 + sqrt(2))115 for method in self._methods:116 assert_almost_equal(nx.algebraic_connectivity(117 G, tol=1e-12, method=method), sigma)118 x = nx.fiedler_vector(G, tol=1e-12, method=method)119 check_eigenvector(A, sigma, x)120 @preserve_random_state121 def test_cycle(self):122 G = nx.cycle_graph(8)123 A = nx.laplacian_matrix(G)124 sigma = 2 - sqrt(2)125 for method in self._methods:126 assert_almost_equal(nx.algebraic_connectivity(127 G, tol=1e-12, method=method), sigma)128 x = nx.fiedler_vector(G, tol=1e-12, method=method)129 check_eigenvector(A, sigma, x)130 @preserve_random_state131 def test_buckminsterfullerene(self):132 G = nx.Graph(133 [(1, 10), (1, 41), (1, 59), (2, 12), (2, 42), (2, 60), (3, 6),134 (3, 43), (3, 57), (4, 8), (4, 44), (4, 58), (5, 13), (5, 56),135 (5, 57), (6, 10), (6, 31), (7, 14), (7, 56), (7, 58), (8, 12),136 (8, 32), (9, 23), (9, 53), (9, 59), (10, 15), (11, 24), (11, 53),137 (11, 60), (12, 16), (13, 14), (13, 25), (14, 26), (15, 27),138 (15, 49), (16, 28), (16, 50), (17, 18), (17, 19), (17, 54),139 (18, 20), (18, 55), (19, 23), (19, 41), (20, 24), (20, 42),140 (21, 31), (21, 33), (21, 57), (22, 32), (22, 34), (22, 58),141 (23, 24), (25, 35), (25, 43), (26, 36), (26, 44), (27, 51),142 (27, 59), (28, 52), (28, 60), (29, 33), (29, 34), (29, 56),143 (30, 51), (30, 52), (30, 53), (31, 47), (32, 48), (33, 45),144 (34, 46), (35, 36), (35, 37), (36, 38), (37, 39), (37, 49),145 (38, 40), (38, 50), (39, 40), (39, 51), (40, 52), (41, 47),146 (42, 48), (43, 49), (44, 50), (45, 46), (45, 54), (46, 55),147 (47, 54), (48, 55)])148 for normalized in (False, True):149 if not normalized:150 A = nx.laplacian_matrix(G)151 sigma = 0.2434017461399311152 else:153 A = nx.normalized_laplacian_matrix(G)154 sigma = 0.08113391537997749155 for method in methods:156 try:157 assert_almost_equal(nx.algebraic_connectivity(158 G, normalized=normalized, tol=1e-12, method=method),159 sigma)160 x = nx.fiedler_vector(G, normalized=normalized, tol=1e-12,161 method=method)162 check_eigenvector(A, sigma, x)163 except nx.NetworkXError as e:164 if e.args not in (('Cholesky solver unavailable.',),165 ('LU solver unavailable.',)):166 raise167 _methods = ('tracemin', 'lanczos', 'lobpcg')168class TestSpectralOrdering(object):169 numpy = 1170 @classmethod171 def setupClass(cls):172 global numpy173 try:174 import numpy.linalg175 import scipy.sparse176 except ImportError:177 raise SkipTest('SciPy not available.')178 @preserve_random_state179 def test_nullgraph(self):180 for graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):181 G = graph()182 assert_raises(nx.NetworkXError, nx.spectral_ordering, G)183 @preserve_random_state184 def test_singleton(self):185 for graph in (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph):186 G = graph()187 G.add_node('x')188 assert_equal(nx.spectral_ordering(G), ['x'])189 G.add_edge('x', 'x', weight=33)190 G.add_edge('x', 'x', weight=33)191 assert_equal(nx.spectral_ordering(G), ['x'])192 @preserve_random_state193 def test_unrecognized_method(self):194 G = nx.path_graph(4)195 assert_raises(nx.NetworkXError, nx.spectral_ordering, G,196 method='unknown')197 @preserve_random_state198 def test_three_nodes(self):199 G = nx.Graph()200 G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1)],201 weight='spam')202 for method in self._methods:203 order = nx.spectral_ordering(G, weight='spam', method=method)204 assert_equal(set(order), set(G))205 ok_(set([1, 3]) in (set(order[:-1]), set(order[1:])))206 G = nx.MultiDiGraph()207 G.add_weighted_edges_from([(1, 2, 1), (1, 3, 2), (2, 3, 1), (2, 3, 2)])...

Full Screen

Full Screen

test_method.py

Source:test_method.py Github

copy

Full Screen

1import WebIDL2def WebIDLTest(parser, harness):3 parser.parse("""4 interface TestMethods {5 void basic();6 static void basicStatic();7 void basicWithSimpleArgs(boolean arg1, byte arg2, unsigned long arg3);8 boolean basicBoolean();9 static boolean basicStaticBoolean();10 boolean basicBooleanWithSimpleArgs(boolean arg1, byte arg2, unsigned long arg3);11 void optionalArg(optional byte? arg1, optional sequence<byte> arg2);12 void variadicArg(byte?... arg1);13 object getObject();14 void setObject(object arg1);15 void setAny(any arg1);16 float doFloats(float arg1);17 };18 """)19 results = parser.finish()20 harness.ok(True, "TestMethods interface parsed without error.")21 harness.check(len(results), 1, "Should be one production.")22 iface = results[0]23 harness.ok(isinstance(iface, WebIDL.IDLInterface),24 "Should be an IDLInterface")25 harness.check(iface.identifier.QName(), "::TestMethods", "Interface has the right QName")26 harness.check(iface.identifier.name, "TestMethods", "Interface has the right name")27 harness.check(len(iface.members), 12, "Expect 12 members")28 methods = iface.members29 def checkArgument(argument, QName, name, type, optional, variadic):30 harness.ok(isinstance(argument, WebIDL.IDLArgument),31 "Should be an IDLArgument")32 harness.check(argument.identifier.QName(), QName, "Argument has the right QName")33 harness.check(argument.identifier.name, name, "Argument has the right name")34 harness.check(str(argument.type), type, "Argument has the right return type")35 harness.check(argument.optional, optional, "Argument has the right optional value")36 harness.check(argument.variadic, variadic, "Argument has the right variadic value")37 def checkMethod(method, QName, name, signatures,38 static=False, getter=False, setter=False, creator=False,39 deleter=False, legacycaller=False, stringifier=False):40 harness.ok(isinstance(method, WebIDL.IDLMethod),41 "Should be an IDLMethod")42 harness.ok(method.isMethod(), "Method is a method")43 harness.ok(not method.isAttr(), "Method is not an attr")44 harness.ok(not method.isConst(), "Method is not a const")45 harness.check(method.identifier.QName(), QName, "Method has the right QName")46 harness.check(method.identifier.name, name, "Method has the right name")47 harness.check(method.isStatic(), static, "Method has the correct static value")48 harness.check(method.isGetter(), getter, "Method has the correct getter value")49 harness.check(method.isSetter(), setter, "Method has the correct setter value")50 harness.check(method.isCreator(), creator, "Method has the correct creator value")51 harness.check(method.isDeleter(), deleter, "Method has the correct deleter value")52 harness.check(method.isLegacycaller(), legacycaller, "Method has the correct legacycaller value")53 harness.check(method.isStringifier(), stringifier, "Method has the correct stringifier value")54 harness.check(len(method.signatures()), len(signatures), "Method has the correct number of signatures")55 sigpairs = zip(method.signatures(), signatures)56 for (gotSignature, expectedSignature) in sigpairs:57 (gotRetType, gotArgs) = gotSignature58 (expectedRetType, expectedArgs) = expectedSignature59 harness.check(str(gotRetType), expectedRetType,60 "Method has the expected return type.")61 for i in range(0, len(gotArgs)):62 (QName, name, type, optional, variadic) = expectedArgs[i]63 checkArgument(gotArgs[i], QName, name, type, optional, variadic)64 checkMethod(methods[0], "::TestMethods::basic", "basic", [("Void", [])])65 checkMethod(methods[1], "::TestMethods::basicStatic", "basicStatic",66 [("Void", [])], static=True)67 checkMethod(methods[2], "::TestMethods::basicWithSimpleArgs",68 "basicWithSimpleArgs",69 [("Void",70 [("::TestMethods::basicWithSimpleArgs::arg1", "arg1", "Boolean", False, False),71 ("::TestMethods::basicWithSimpleArgs::arg2", "arg2", "Byte", False, False),72 ("::TestMethods::basicWithSimpleArgs::arg3", "arg3", "UnsignedLong", False, False)])])73 checkMethod(methods[3], "::TestMethods::basicBoolean", "basicBoolean", [("Boolean", [])])74 checkMethod(methods[4], "::TestMethods::basicStaticBoolean", "basicStaticBoolean", [("Boolean", [])], static=True)75 checkMethod(methods[5], "::TestMethods::basicBooleanWithSimpleArgs",76 "basicBooleanWithSimpleArgs",77 [("Boolean",78 [("::TestMethods::basicBooleanWithSimpleArgs::arg1", "arg1", "Boolean", False, False),79 ("::TestMethods::basicBooleanWithSimpleArgs::arg2", "arg2", "Byte", False, False),80 ("::TestMethods::basicBooleanWithSimpleArgs::arg3", "arg3", "UnsignedLong", False, False)])])81 checkMethod(methods[6], "::TestMethods::optionalArg",82 "optionalArg",83 [("Void",84 [("::TestMethods::optionalArg::arg1", "arg1", "ByteOrNull", True, False),85 ("::TestMethods::optionalArg::arg2", "arg2", "ByteSequence", True, False)])])86 checkMethod(methods[7], "::TestMethods::variadicArg",87 "variadicArg",88 [("Void",89 [("::TestMethods::variadicArg::arg1", "arg1", "ByteOrNull", True, True)])])90 checkMethod(methods[8], "::TestMethods::getObject",91 "getObject", [("Object", [])])92 checkMethod(methods[9], "::TestMethods::setObject",93 "setObject",94 [("Void",95 [("::TestMethods::setObject::arg1", "arg1", "Object", False, False)])])96 checkMethod(methods[10], "::TestMethods::setAny",97 "setAny",98 [("Void",99 [("::TestMethods::setAny::arg1", "arg1", "Any", False, False)])])100 checkMethod(methods[11], "::TestMethods::doFloats",101 "doFloats",102 [("Float",103 [("::TestMethods::doFloats::arg1", "arg1", "Float", False, False)])])104 parser = parser.reset()105 threw = False106 try:107 parser.parse("""108 interface A {109 void foo(optional float bar = 1);110 };111 """)112 results = parser.finish()113 except Exception, x:114 threw = True115 harness.ok(not threw, "Should allow integer to float type corecion")116 parser = parser.reset()117 threw = False118 try:119 parser.parse("""120 interface A {121 [GetterThrows] void foo();122 };123 """)124 results = parser.finish()125 except Exception, x:126 threw = True127 harness.ok(threw, "Should not allow [GetterThrows] on methods")128 parser = parser.reset()129 threw = False130 try:131 parser.parse("""132 interface A {133 [SetterThrows] void foo();134 };135 """)136 results = parser.finish()137 except Exception, x:138 threw = True139 harness.ok(threw, "Should not allow [SetterThrows] on methods")140 parser = parser.reset()141 threw = False142 try:143 parser.parse("""144 interface A {145 [Throw] void foo();146 };147 """)148 results = parser.finish()149 except Exception, x:150 threw = True151 harness.ok(threw, "Should spell [Throws] correctly on methods")152 parser = parser.reset()153 threw = False154 try:155 parser.parse("""156 interface A {157 void __noSuchMethod__();158 };159 """)160 results = parser.finish()161 except Exception, x:162 threw = True...

Full Screen

Full Screen

methods.py

Source:methods.py Github

copy

Full Screen

...74 cls, arith_method, comp_method, bool_method, special=True75 )76 # inplace operators (I feel like these should get passed an `inplace=True`77 # or just be removed78 def _wrap_inplace_method(method):79 """80 return an inplace wrapper for this method81 """82 def f(self, other):83 result = method(self, other)84 if (85 self.ndim == 186 and result._indexed_same(self)87 and is_dtype_equal(result.dtype, self.dtype)88 ):89 # GH#36498 this inplace op can _actually_ be inplace.90 self._values[:] = result._values91 return self92 # Delete cacher93 self._reset_cacher()94 # this makes sure that we are aligned like the input95 # we are updating inplace so we want to ignore is_copy96 self._update_inplace(97 result.reindex_like(self, copy=False), verify_is_copy=False98 )99 return self100 name = method.__name__.strip("__")101 f.__name__ = f"__i{name}__"102 return f103 new_methods.update(104 dict(105 __iadd__=_wrap_inplace_method(new_methods["__add__"]),106 __isub__=_wrap_inplace_method(new_methods["__sub__"]),107 __imul__=_wrap_inplace_method(new_methods["__mul__"]),108 __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),109 __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]),110 __imod__=_wrap_inplace_method(new_methods["__mod__"]),111 __ipow__=_wrap_inplace_method(new_methods["__pow__"]),112 )113 )114 new_methods.update(115 dict(116 __iand__=_wrap_inplace_method(new_methods["__and__"]),117 __ior__=_wrap_inplace_method(new_methods["__or__"]),118 __ixor__=_wrap_inplace_method(new_methods["__xor__"]),119 )120 )121 _add_methods(cls, new_methods=new_methods)122def add_flex_arithmetic_methods(cls):123 """124 Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``)125 to the class.126 Parameters127 ----------128 cls : class129 flex methods will be defined and pinned to this class130 """131 flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls)132 new_methods = _create_methods(133 cls, flex_arith_method, flex_comp_method, bool_method=None, special=False134 )135 new_methods.update(136 dict(137 multiply=new_methods["mul"],138 subtract=new_methods["sub"],139 divide=new_methods["div"],140 )141 )142 # opt out of bool flex methods for now143 assert not any(kname in new_methods for kname in ("ror_", "rxor", "rand_"))144 _add_methods(cls, new_methods=new_methods)145def _create_methods(cls, arith_method, comp_method, bool_method, special):146 # creates actual methods based upon arithmetic, comp and bool method147 # constructors.148 have_divmod = issubclass(cls, ABCSeries)149 # divmod is available for Series150 new_methods = dict(151 add=arith_method(cls, operator.add, special),152 radd=arith_method(cls, radd, special),153 sub=arith_method(cls, operator.sub, special),154 mul=arith_method(cls, operator.mul, special),155 truediv=arith_method(cls, operator.truediv, special),156 floordiv=arith_method(cls, operator.floordiv, special),157 mod=arith_method(cls, operator.mod, special),158 pow=arith_method(cls, operator.pow, special),159 # not entirely sure why this is necessary, but previously was included160 # so it's here to maintain compatibility161 rmul=arith_method(cls, rmul, special),162 rsub=arith_method(cls, rsub, special),163 rtruediv=arith_method(cls, rtruediv, special),164 rfloordiv=arith_method(cls, rfloordiv, special),165 rpow=arith_method(cls, rpow, special),166 rmod=arith_method(cls, rmod, special),167 )168 new_methods["div"] = new_methods["truediv"]169 new_methods["rdiv"] = new_methods["rtruediv"]170 if have_divmod:171 # divmod doesn't have an op that is supported by numexpr172 new_methods["divmod"] = arith_method(cls, divmod, special)173 new_methods["rdivmod"] = arith_method(cls, rdivmod, special)174 new_methods.update(175 dict(176 eq=comp_method(cls, operator.eq, special),177 ne=comp_method(cls, operator.ne, special),178 lt=comp_method(cls, operator.lt, special),179 gt=comp_method(cls, operator.gt, special),180 le=comp_method(cls, operator.le, special),181 ge=comp_method(cls, operator.ge, special),182 )183 )184 if bool_method:185 new_methods.update(186 dict(187 and_=bool_method(cls, operator.and_, special),188 or_=bool_method(cls, operator.or_, special),189 xor=bool_method(cls, operator.xor, special),190 rand_=bool_method(cls, rand_, special),191 ror_=bool_method(cls, ror_, special),192 rxor=bool_method(cls, rxor, special),193 )194 )195 if special:196 dunderize = lambda x: f"__{x.strip('_')}__"197 else:198 dunderize = lambda x: x199 new_methods = {dunderize(k): v for k, v in new_methods.items()}200 return new_methods201def _add_methods(cls, new_methods):202 for name, method in new_methods.items():...

Full Screen

Full Screen

pydocfodder.py

Source:pydocfodder.py Github

copy

Full Screen

1"""Something just to look at via pydoc."""23class A_classic:4 "A classic class."5 def A_method(self):6 "Method defined in A."7 def AB_method(self):8 "Method defined in A and B."9 def AC_method(self):10 "Method defined in A and C."11 def AD_method(self):12 "Method defined in A and D."13 def ABC_method(self):14 "Method defined in A, B and C."15 def ABD_method(self):16 "Method defined in A, B and D."17 def ACD_method(self):18 "Method defined in A, C and D."19 def ABCD_method(self):20 "Method defined in A, B, C and D."212223class B_classic(A_classic):24 "A classic class, derived from A_classic."25 def AB_method(self):26 "Method defined in A and B."27 def ABC_method(self):28 "Method defined in A, B and C."29 def ABD_method(self):30 "Method defined in A, B and D."31 def ABCD_method(self):32 "Method defined in A, B, C and D."33 def B_method(self):34 "Method defined in B."35 def BC_method(self):36 "Method defined in B and C."37 def BD_method(self):38 "Method defined in B and D."39 def BCD_method(self):40 "Method defined in B, C and D."4142class C_classic(A_classic):43 "A classic class, derived from A_classic."44 def AC_method(self):45 "Method defined in A and C."46 def ABC_method(self):47 "Method defined in A, B and C."48 def ACD_method(self):49 "Method defined in A, C and D."50 def ABCD_method(self):51 "Method defined in A, B, C and D."52 def BC_method(self):53 "Method defined in B and C."54 def BCD_method(self):55 "Method defined in B, C and D."56 def C_method(self):57 "Method defined in C."58 def CD_method(self):59 "Method defined in C and D."6061class D_classic(B_classic, C_classic):62 "A classic class, derived from B_classic and C_classic."63 def AD_method(self):64 "Method defined in A and D."65 def ABD_method(self):66 "Method defined in A, B and D."67 def ACD_method(self):68 "Method defined in A, C and D."69 def ABCD_method(self):70 "Method defined in A, B, C and D."71 def BD_method(self):72 "Method defined in B and D."73 def BCD_method(self):74 "Method defined in B, C and D."75 def CD_method(self):76 "Method defined in C and D."77 def D_method(self):78 "Method defined in D."798081class A_new(object):82 "A new-style class."8384 def A_method(self):85 "Method defined in A."86 def AB_method(self):87 "Method defined in A and B."88 def AC_method(self):89 "Method defined in A and C."90 def AD_method(self):91 "Method defined in A and D."92 def ABC_method(self):93 "Method defined in A, B and C."94 def ABD_method(self):95 "Method defined in A, B and D."96 def ACD_method(self):97 "Method defined in A, C and D."98 def ABCD_method(self):99 "Method defined in A, B, C and D."100101 def A_classmethod(cls, x):102 "A class method defined in A."103 A_classmethod = classmethod(A_classmethod)104105 def A_staticmethod():106 "A static method defined in A."107 A_staticmethod = staticmethod(A_staticmethod)108109 def _getx(self):110 "A property getter function."111 def _setx(self, value):112 "A property setter function."113 def _delx(self):114 "A property deleter function."115 A_property = property(fdel=_delx, fget=_getx, fset=_setx,116 doc="A sample property defined in A.")117118 A_int_alias = int119120class B_new(A_new):121 "A new-style class, derived from A_new."122123 def AB_method(self):124 "Method defined in A and B."125 def ABC_method(self):126 "Method defined in A, B and C."127 def ABD_method(self):128 "Method defined in A, B and D."129 def ABCD_method(self):130 "Method defined in A, B, C and D."131 def B_method(self):132 "Method defined in B."133 def BC_method(self):134 "Method defined in B and C."135 def BD_method(self):136 "Method defined in B and D."137 def BCD_method(self):138 "Method defined in B, C and D."139140class C_new(A_new):141 "A new-style class, derived from A_new."142143 def AC_method(self):144 "Method defined in A and C."145 def ABC_method(self):146 "Method defined in A, B and C."147 def ACD_method(self):148 "Method defined in A, C and D."149 def ABCD_method(self):150 "Method defined in A, B, C and D."151 def BC_method(self):152 "Method defined in B and C."153 def BCD_method(self):154 "Method defined in B, C and D."155 def C_method(self):156 "Method defined in C."157 def CD_method(self):158 "Method defined in C and D."159160class D_new(B_new, C_new):161 """A new-style class, derived from B_new and C_new.162 """163164 def AD_method(self):165 "Method defined in A and D."166 def ABD_method(self):167 "Method defined in A, B and D."168 def ACD_method(self):169 "Method defined in A, C and D."170 def ABCD_method(self):171 "Method defined in A, B, C and D."172 def BD_method(self):173 "Method defined in B and D."174 def BCD_method(self):175 "Method defined in B, C and D."176 def CD_method(self):177 "Method defined in C and D."178 def D_method(self):179 "Method defined in D."180181class FunkyProperties(object):182 """From SF bug 472347, by Roeland Rengelink.183184 Property getters etc may not be vanilla functions or methods,185 and this used to make GUI pydoc blow up.186 """187188 def __init__(self):189 self.desc = {'x':0}190191 class get_desc:192 def __init__(self, attr): ...

Full Screen

Full Screen

test_special_methods.py

Source:test_special_methods.py Github

copy

Full Screen

1import WebIDL2def WebIDLTest(parser, harness):3 parser.parse("""4 interface SpecialMethods {5 getter long long (unsigned long index);6 setter long long (unsigned long index, long long value);7 creator long long (unsigned long index, long long value);8 getter boolean (DOMString name);9 setter boolean (DOMString name, boolean value);10 creator boolean (DOMString name, boolean value);11 deleter boolean (DOMString name);12 readonly attribute unsigned long length;13 };14 interface SpecialMethodsCombination {15 setter creator long long (unsigned long index, long long value);16 getter deleter boolean (DOMString name);17 setter creator boolean (DOMString name, boolean value);18 };19 """)20 results = parser.finish()21 def checkMethod(method, QName, name,22 static=False, getter=False, setter=False, creator=False,23 deleter=False, legacycaller=False, stringifier=False):24 harness.ok(isinstance(method, WebIDL.IDLMethod),25 "Should be an IDLMethod")26 harness.check(method.identifier.QName(), QName, "Method has the right QName")27 harness.check(method.identifier.name, name, "Method has the right name")28 harness.check(method.isStatic(), static, "Method has the correct static value")29 harness.check(method.isGetter(), getter, "Method has the correct getter value")30 harness.check(method.isSetter(), setter, "Method has the correct setter value")31 harness.check(method.isCreator(), creator, "Method has the correct creator value")32 harness.check(method.isDeleter(), deleter, "Method has the correct deleter value")33 harness.check(method.isLegacycaller(), legacycaller, "Method has the correct legacycaller value")34 harness.check(method.isStringifier(), stringifier, "Method has the correct stringifier value")35 harness.check(len(results), 2, "Expect 2 interfaces")36 iface = results[0]37 harness.check(len(iface.members), 8, "Expect 8 members")38 checkMethod(iface.members[0], "::SpecialMethods::__indexedgetter", "__indexedgetter",39 getter=True)40 checkMethod(iface.members[1], "::SpecialMethods::__indexedsetter", "__indexedsetter",41 setter=True)42 checkMethod(iface.members[2], "::SpecialMethods::__indexedcreator", "__indexedcreator",43 creator=True)44 checkMethod(iface.members[3], "::SpecialMethods::__namedgetter", "__namedgetter",45 getter=True)46 checkMethod(iface.members[4], "::SpecialMethods::__namedsetter", "__namedsetter",47 setter=True)48 checkMethod(iface.members[5], "::SpecialMethods::__namedcreator", "__namedcreator",49 creator=True)50 checkMethod(iface.members[6], "::SpecialMethods::__nameddeleter", "__nameddeleter",51 deleter=True)52 iface = results[1]53 harness.check(len(iface.members), 3, "Expect 3 members")54 checkMethod(iface.members[0], "::SpecialMethodsCombination::__indexedsettercreator",55 "__indexedsettercreator", setter=True, creator=True)56 checkMethod(iface.members[1], "::SpecialMethodsCombination::__namedgetterdeleter",57 "__namedgetterdeleter", getter=True, deleter=True)58 checkMethod(iface.members[2], "::SpecialMethodsCombination::__namedsettercreator",59 "__namedsettercreator", setter=True, creator=True)60 parser = parser.reset();61 threw = False62 try:63 parser.parse(64 """65 interface IndexedDeleter {66 deleter void(unsigned long index);67 };68 """)69 parser.finish()70 except:71 threw = True72 harness.ok(threw, "There are no indexed deleters")73 ...

Full Screen

Full Screen

constants.py

Source:constants.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3kodiswift.constants4--------------------5This module contains some helpful constants which ease interaction6with Kodi.7:copyright: (c) 2012 by Jonathan Beluch8:license: GPLv3, see LICENSE for more details.9"""10from __future__ import absolute_import11from kodiswift import xbmcplugin12__all__ = ['SortMethod']13class SortMethod(object):14 """Static class to hold all of the available sort methods. The prefix15 of 'SORT_METHOD_' is stripped.16 e.g. SORT_METHOD_TITLE becomes SortMethod.TITLE17 """18 ALBUM = xbmcplugin.SORT_METHOD_ALBUM19 ALBUM_IGNORE_THE = xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE20 ARTIST = xbmcplugin.SORT_METHOD_ARTIST21 ARTIST_IGNORE_THE = xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE22 BITRATE = xbmcplugin.SORT_METHOD_BITRATE23 CHANNEL = xbmcplugin.SORT_METHOD_CHANNEL24 COUNTRY = xbmcplugin.SORT_METHOD_COUNTRY25 DATE = xbmcplugin.SORT_METHOD_DATE26 DATEADDED = xbmcplugin.SORT_METHOD_DATEADDED27 DATE_TAKEN = xbmcplugin.SORT_METHOD_DATE_TAKEN28 DRIVE_TYPE = xbmcplugin.SORT_METHOD_DRIVE_TYPE29 DURATION = xbmcplugin.SORT_METHOD_DURATION30 EPISODE = xbmcplugin.SORT_METHOD_EPISODE31 FILE = xbmcplugin.SORT_METHOD_FILE32 FULLPATH = xbmcplugin.SORT_METHOD_FULLPATH33 GENRE = xbmcplugin.SORT_METHOD_GENRE34 LABEL = xbmcplugin.SORT_METHOD_LABEL35 LABEL_IGNORE_FOLDERS = xbmcplugin.SORT_METHOD_LABEL_IGNORE_FOLDERS36 LABEL_IGNORE_THE = xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE37 LASTPLAYED = xbmcplugin.SORT_METHOD_LASTPLAYED38 LISTENERS = xbmcplugin.SORT_METHOD_LISTENERS39 MPAA_RATING = xbmcplugin.SORT_METHOD_MPAA_RATING40 NONE = xbmcplugin.SORT_METHOD_NONE41 PLAYCOUNT = xbmcplugin.SORT_METHOD_PLAYCOUNT42 PLAYLIST_ORDER = xbmcplugin.SORT_METHOD_PLAYLIST_ORDER43 PRODUCTIONCODE = xbmcplugin.SORT_METHOD_PRODUCTIONCODE44 PROGRAM_COUNT = xbmcplugin.SORT_METHOD_PROGRAM_COUNT45 SIZE = xbmcplugin.SORT_METHOD_SIZE46 SONG_RATING = xbmcplugin.SORT_METHOD_SONG_RATING47 STUDIO = xbmcplugin.SORT_METHOD_STUDIO48 STUDIO_IGNORE_THE = xbmcplugin.SORT_METHOD_STUDIO_IGNORE_THE49 TITLE = xbmcplugin.SORT_METHOD_TITLE50 TITLE_IGNORE_THE = xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE51 TRACKNUM = xbmcplugin.SORT_METHOD_TRACKNUM52 UNSORTED = xbmcplugin.SORT_METHOD_UNSORTED53 VIDEO_RATING = xbmcplugin.SORT_METHOD_VIDEO_RATING54 VIDEO_RUNTIME = xbmcplugin.SORT_METHOD_VIDEO_RUNTIME55 VIDEO_SORT_TITLE = xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE56 VIDEO_SORT_TITLE_IGNORE_THE = xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE57 VIDEO_TITLE = xbmcplugin.SORT_METHOD_VIDEO_TITLE58 VIDEO_USER_RATING = xbmcplugin.SORT_METHOD_VIDEO_USER_RATING59 VIDEO_YEAR = xbmcplugin.SORT_METHOD_VIDEO_YEAR60 @classmethod61 def from_string(cls, sort_method):62 """Returns the sort method specified. sort_method is case insensitive.63 Will raise an AttributeError if the provided sort_method does not64 exist.65 >>> SortMethod.from_string('title')66 """...

Full Screen

Full Screen

xbmcplugin.py

Source:xbmcplugin.py Github

copy

Full Screen

1# -*- code: utf-8 -*-2SORT_METHOD_ALBUM = 143SORT_METHOD_ALBUM_IGNORE_THE = 154SORT_METHOD_ARTIST = 115SORT_METHOD_ARTIST_IGNORE_THE = 136SORT_METHOD_BITRATE = 427SORT_METHOD_CHANNEL = 408SORT_METHOD_COUNTRY = 179SORT_METHOD_DATE = 310SORT_METHOD_DATEADDED = 2111SORT_METHOD_DATE_TAKEN = 4312SORT_METHOD_DRIVE_TYPE = 613SORT_METHOD_DURATION = 814SORT_METHOD_EPISODE = 2415SORT_METHOD_FILE = 516SORT_METHOD_FULLPATH = 3417SORT_METHOD_GENRE = 1618SORT_METHOD_LABEL = 119SORT_METHOD_LABEL_IGNORE_FOLDERS = 3520SORT_METHOD_LABEL_IGNORE_THE = 221SORT_METHOD_LASTPLAYED = 3622SORT_METHOD_LISTENERS = 3823SORT_METHOD_MPAA_RATING = 3024SORT_METHOD_NONE = 025SORT_METHOD_PLAYCOUNT = 3726SORT_METHOD_PLAYLIST_ORDER = 2327SORT_METHOD_PRODUCTIONCODE = 2828SORT_METHOD_PROGRAM_COUNT = 2229SORT_METHOD_SIZE = 430SORT_METHOD_SONG_RATING = 2931SORT_METHOD_STUDIO = 3232SORT_METHOD_STUDIO_IGNORE_THE = 3333SORT_METHOD_TITLE = 934SORT_METHOD_TITLE_IGNORE_THE = 1035SORT_METHOD_TRACKNUM = 736SORT_METHOD_UNSORTED = 3937SORT_METHOD_VIDEO_RATING = 1938SORT_METHOD_VIDEO_RUNTIME = 3139SORT_METHOD_VIDEO_SORT_TITLE = 2640SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE = 2741SORT_METHOD_VIDEO_TITLE = 2542SORT_METHOD_VIDEO_USER_RATING = 20...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var expect = require('chai').expect;3var foo = {4 setBar: function(value) {5 this.bar = value;6 }7};8var bar = {9 setFoo: function(value) {10 this.foo = value;11 }12};13describe('Test Sinon', function() {14 beforeEach(function() {15 this.sandbox = sinon.sandbox.create();16 });17 afterEach(function() {18 this.sandbox.restore();19 });20 it('should replace a method', function() {21 var stub = this.sandbox.stub(foo, 'setBar');22 foo.setBar(123);23 expect(stub.calledOnce).to.be.true;24 });25 it('should replace a method with a custom implementation', function() {26 var stub = this.sandbox.stub(foo, 'setBar', function(value) {27 this.bar = 'baz';28 });29 foo.setBar(123);30 expect(stub.calledOnce).to.be.true;31 expect(foo.bar).to.equal('baz');32 });33 it('should replace a method with a spy', function() {34 var spy = this.sandbox.spy();35 bar.setFoo = spy;36 bar.setFoo();37 expect(spy.calledOnce).to.be.true;38 });39});40 3 passing (8ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var myObj = { myMethod: function() {} };3var spy = sinon.spy(myObj, 'myMethod');4myObj.myMethod();5console.log(spy.called);6var sinon = require('sinon');7var myObj = { myMethod: function() {} };8var spy = sinon.spy(myObj, 'myMethod');9myObj.myMethod();10console.log(spy.called);11var sinon = require('sinon');12var myObj = { myMethod: function() {} };13var spy = sinon.spy(myObj, 'myMethod');14myObj.myMethod();15console.log(spy.called);16var sinon = require('sinon');17var myObj = { myMethod: function() {} };18var spy = sinon.spy(myObj, 'myMethod');19myObj.myMethod();20console.log(spy.called);21var sinon = require('sinon');22var myObj = { myMethod: function() {} };23var spy = sinon.spy(myObj, 'myMethod');24myObj.myMethod();25console.log(spy.called);26var sinon = require('sinon');27var myObj = { myMethod: function() {} };28var spy = sinon.spy(myObj, 'myMethod');29myObj.myMethod();30console.log(spy.called);31var sinon = require('sinon');32var myObj = { myMethod: function() {} };33var spy = sinon.spy(myObj, 'myMethod');34myObj.myMethod();35console.log(spy.called);36var sinon = require('sinon');37var myObj = { myMethod: function() {} };38var spy = sinon.spy(myObj, 'myMethod');39myObj.myMethod();40console.log(spy.called);41var sinon = require('sinon');

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var assert = require('assert');3var obj = {4 method: function () {5 return 'result';6 }7};8var spy = sinon.spy(obj, 'method');9obj.method();10assert(spy.called);

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run sinon automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful