language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
ansible__ansible
lib/ansible/module_utils/facts/namespace.py
{ "start": 2001, "end": 2313 }
class ____(FactNamespace): def __init__(self, namespace_name, prefix=None): super(PrefixFactNamespace, self).__init__(namespace_name) self.prefix = prefix def transform(self, name): new_name = self._underscore(name) return '%s%s' % (self.prefix, new_name)
PrefixFactNamespace
python
pytorch__pytorch
benchmarks/tensorexpr/elementwise.py
{ "start": 240, "end": 5619 }
class ____(benchmark.Benchmark): # List of customization class variables. op_str = None binary_op_pt_func = None binary_op_np_func = None unary_op_pt_func = None unary_op_np_func = None split_input = True def __init__(self, mode, device, dtype, N): super().__init__(mode, device, dtype) self.N = N self.d1 = self.rand( [N], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.d2 = self.rand( [N], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.d3 = self.rand( [N], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.d4 = self.rand( [N], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.inputs = [self.d1, self.d2, self.d3, self.d4] self.deterministic = "rand" not in self.op_str def _eval(self, d1, d2, d3, d4, binary_op, unary_op): if not binary_op: def binary_op(x, y): return x + y if not unary_op: def unary_op(x): return x if self.split_input: d1 = unary_op(d1) d2 = unary_op(d2) d3 = unary_op(d3) d4 = unary_op(d4) else: d2 = unary_op(d1 + 0.001) d3 = unary_op(d1 + 0.002) d4 = unary_op(d1 + 0.003) d1 = unary_op(d1) a = binary_op(d1, d2) b = binary_op(d3, d4) c = a + b return c def forward(self, d1, d2, d3, d4): binary_op = self.__class__.binary_op_pt_func unary_op = self.__class__.unary_op_pt_func return self._eval(d1, d2, d3, d4, binary_op, unary_op) def reference(self): binary_op = self.__class__.binary_op_np_func unary_op = self.__class__.unary_op_np_func [d1, d2, d3, d4] = [self.numpy(d) for d in [self.d1, self.d2, self.d3, self.d4]] return self._eval(d1, d2, d3, d4, binary_op, unary_op) def config(self): return [self.N] @classmethod def module(cls): return "element_" + cls.op_str def memory_workload(self): input_count = len(self.inputs) if self.mode == "fwd": if self.split_input: sol_count = input_count + 1 algorithmic_count = input_count + 1 else: sol_count = 1 + 1 algorithmic_count = 1 + 1 if "rand" in self.op_str: sol_count = 1 algorithmic_count = 1 else: if self.split_input: sol_count = (input_count + 1) + (1 + input_count) algorithmic_count = (input_count + 1) + ((2 + 1) * input_count) else: sol_count = 1 + 1 algorithmic_count = 1 + 1 if "rand" in self.op_str: sol_count = 1 algorithmic_count = 1 buffer_size = self.N return { "sol": buffer_size * sol_count, "algorithmic": buffer_size * algorithmic_count, } @staticmethod def default_configs(): return [[1 << 25]] def register_element_ops(): binary_op_list = [ ["mul", operator.mul], ["add", operator.add], ["sub", operator.sub], ["div", lambda a, b: a / (b + 1e-4)], [ "pow", torch.pow, np.power, ], # no fuson triggered ["max", torch.max, np.maximum], ["min", torch.min, np.minimum], ] unary_op_list = [ ["erf", torch.erf, scipy.special.erf], ["exp", torch.exp, np.exp], ["sin", torch.sin, np.sin], ["cos", torch.cos, np.cos], ["rand_like", torch.rand_like, lambda x: np.random.rand(*x.shape)], ] for split_input, binary_op in itertools.product([True, False], binary_op_list): # Make a copy of ElementBench if len(binary_op) == 2: [op_str, op_pt_func] = binary_op op_np_func = op_pt_func elif len(binary_op) == 3: [op_str, op_pt_func, op_np_func] = binary_op split_str = "split" if split_input else "shared" op_str = split_str + "_" + op_str bm_cls = type("ElementBench_" + op_str, (ElementBench,), {}) bm_cls.op_str = op_str bm_cls.binary_op_pt_func = op_pt_func bm_cls.binary_op_np_func = op_np_func bm_cls.split_input = split_input benchmark.register_benchmark_class(bm_cls) for split_input, unary_op in itertools.product([True, False], unary_op_list): # Make a copy of ElementBench if len(unary_op) == 2: [op_str, op_pt_func] = unary_op op_np_func = op_pt_func elif len(unary_op) == 3: [op_str, op_pt_func, op_np_func] = unary_op split_str = "split" if split_input else "shared" op_str = split_str + "_" + op_str bm_cls = type("ElementBench_" + op_str, (ElementBench,), {}) bm_cls.op_str = op_str bm_cls.unary_op_pt_func = op_pt_func bm_cls.unary_op_np_func = op_np_func bm_cls.split_input = split_input benchmark.register_benchmark_class(bm_cls) # benchmark.register_benchmark_class(ElementMulBench) register_element_ops()
ElementBench
python
django__django
tests/postgres_tests/test_search.py
{ "start": 3625, "end": 5242 }
class ____(GrailTestData, PostgreSQLTestCase): def test_simple(self): searched = Line.objects.filter(dialogue__search="elbows") self.assertSequenceEqual(searched, [self.verse1]) def test_non_exact_match(self): self.check_default_text_search_config() searched = Line.objects.filter(dialogue__search="hearts") self.assertSequenceEqual(searched, [self.verse2]) def test_search_two_terms(self): self.check_default_text_search_config() searched = Line.objects.filter(dialogue__search="heart bowel") self.assertSequenceEqual(searched, [self.verse2]) def test_search_two_terms_with_partial_match(self): searched = Line.objects.filter(dialogue__search="Robin killed") self.assertSequenceEqual(searched, [self.verse0]) def test_search_query_config(self): searched = Line.objects.filter( dialogue__search=SearchQuery("nostrils", config="simple"), ) self.assertSequenceEqual(searched, [self.verse2]) def test_search_with_F_expression(self): # Non-matching query. LineSavedSearch.objects.create(line=self.verse1, query="hearts") # Matching query. match = LineSavedSearch.objects.create(line=self.verse1, query="elbows") for query_expression in [F("query"), SearchQuery(F("query"))]: with self.subTest(query_expression): searched = LineSavedSearch.objects.filter( line__dialogue__search=query_expression, ) self.assertSequenceEqual(searched, [match])
SimpleSearchTest
python
numba__numba
numba/core/errors.py
{ "start": 21372, "end": 21540 }
class ____(TypingError): """ For signalling that a function's typing requires a constant value for some of its arguments. """ pass
RequireLiteralValue
python
protocolbuffers__protobuf
python/google/protobuf/internal/message_test.py
{ "start": 67421, "end": 79978 }
class ____(unittest.TestCase): def testFieldPresence(self): message = unittest_pb2.TestAllTypes() self.assertFalse(message.HasField('optional_int32')) self.assertFalse(message.HasField('optional_bool')) self.assertFalse(message.HasField('optional_nested_message')) with self.assertRaises(ValueError): message.HasField('field_doesnt_exist') with self.assertRaises(ValueError): message.HasField('repeated_int32') with self.assertRaises(ValueError): message.HasField('repeated_nested_message') self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) # Fields are set even when setting the values to default values. message.optional_int32 = 0 message.optional_bool = False message.optional_nested_message.bb = 0 self.assertTrue(message.HasField('optional_int32')) self.assertTrue(message.HasField('optional_bool')) self.assertTrue(message.HasField('optional_nested_message')) self.assertIn('optional_int32', message) self.assertIn('optional_bool', message) self.assertIn('optional_nested_message', message) # Set the fields to non-default values. message.optional_int32 = 5 message.optional_bool = True message.optional_nested_message.bb = 15 self.assertTrue(message.HasField(u'optional_int32')) self.assertTrue(message.HasField('optional_bool')) self.assertTrue(message.HasField('optional_nested_message')) # Clearing the fields unsets them and resets their value to default. message.ClearField('optional_int32') message.ClearField(u'optional_bool') message.ClearField('optional_nested_message') self.assertFalse(message.HasField('optional_int32')) self.assertFalse(message.HasField('optional_bool')) self.assertFalse(message.HasField('optional_nested_message')) self.assertNotIn('optional_int32', message) self.assertNotIn('optional_bool', message) self.assertNotIn('optional_nested_message', message) self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) def testDel(self): msg = unittest_pb2.TestAllTypes() # Fields cannot be deleted. with self.assertRaises(AttributeError): del msg.optional_int32 with self.assertRaises(AttributeError): del msg.optional_bool with self.assertRaises(AttributeError): del msg.repeated_nested_message def testAssignInvalidEnum(self): """Assigning an invalid enum number is not allowed for closed enums.""" m = unittest_pb2.TestAllTypes() # Can not assign unknown enum to closed enums. with self.assertRaises(ValueError) as _: m.optional_nested_enum = 1234567 self.assertRaises(ValueError, m.repeated_nested_enum.append, 1234567) # Assignment is a different code path than append for the C++ impl. m.repeated_nested_enum.append(2) m.repeated_nested_enum[0] = 2 with self.assertRaises(ValueError): m.repeated_nested_enum[0] = 123456 # Unknown enum value can be parsed but is ignored. m2 = unittest_proto3_arena_pb2.TestAllTypes() m2.optional_nested_enum = 1234567 m2.repeated_nested_enum.append(7654321) serialized = m2.SerializeToString() m3 = unittest_pb2.TestAllTypes() m3.ParseFromString(serialized) self.assertFalse(m3.HasField('optional_nested_enum')) # 1 is the default value for optional_nested_enum. self.assertEqual(1, m3.optional_nested_enum) self.assertEqual(0, len(m3.repeated_nested_enum)) m2.Clear() m2.ParseFromString(m3.SerializeToString()) self.assertEqual(1234567, m2.optional_nested_enum) self.assertEqual(7654321, m2.repeated_nested_enum[0]) def testUnknownEnumMap(self): m = map_proto2_unittest_pb2.TestEnumMap() m.known_map_field[123] = 0 with self.assertRaises(ValueError): m.unknown_map_field[1] = 123 def testDeepCopyClosedEnum(self): m = map_proto2_unittest_pb2.TestEnumMap() m.known_map_field[123] = 0 m2 = copy.deepcopy(m) self.assertEqual(m, m2) def testExtensionsErrors(self): msg = unittest_pb2.TestAllTypes() self.assertRaises(AttributeError, getattr, msg, 'Extensions') def testMergeFromExtensions(self): msg1 = more_extensions_pb2.TopLevelMessage() msg2 = more_extensions_pb2.TopLevelMessage() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual( 0, msg1.submessage.Extensions[more_extensions_pb2.optional_int_extension]) self.assertFalse(msg1.HasField('submessage')) msg2.submessage.Extensions[more_extensions_pb2.optional_int_extension] = 123 # Make sure cmessage and extensions pointing to a mutable message # after merge instead of the lazily created message. msg1.MergeFrom(msg2) self.assertEqual( 123, msg1.submessage.Extensions[more_extensions_pb2.optional_int_extension]) def testCopyFromAll(self): message = unittest_pb2.TestAllTypes() test_util.SetAllFields(message) copy = unittest_pb2.TestAllTypes() copy.CopyFrom(message) self.assertEqual(message, copy) message.repeated_nested_message.add().bb = 123 self.assertNotEqual(message, copy) def testCopyFromAllExtensions(self): all_set = unittest_pb2.TestAllExtensions() test_util.SetAllExtensions(all_set) copy = unittest_pb2.TestAllExtensions() copy.CopyFrom(all_set) self.assertEqual(all_set, copy) all_set.Extensions[unittest_pb2.repeatedgroup_extension].add().a = 321 self.assertNotEqual(all_set, copy) def testCopyFromAllPackedExtensions(self): all_set = unittest_pb2.TestPackedExtensions() test_util.SetAllPackedExtensions(all_set) copy = unittest_pb2.TestPackedExtensions() copy.CopyFrom(all_set) self.assertEqual(all_set, copy) all_set.Extensions[unittest_pb2.packed_float_extension].extend([61.0, 71.0]) self.assertNotEqual(all_set, copy) def testPickleIncompleteProto(self): golden_message = unittest_pb2.TestRequired(a=1) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message) self.assertEqual(unpickled_message.a, 1) # This is still an incomplete proto - so serializing should fail self.assertRaises(message.EncodeError, unpickled_message.SerializeToString) # TODO: this isn't really a proto2-specific test except that this # message has a required field in it. Should probably be factored out so # that we can test the other parts with proto3. def testParsingMerge(self): """Check the merge behavior when a required or optional field appears multiple times in the input. """ messages = [ unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes() ] messages[0].optional_int32 = 1 messages[1].optional_int64 = 2 messages[2].optional_int32 = 3 messages[2].optional_string = 'hello' merged_message = unittest_pb2.TestAllTypes() merged_message.optional_int32 = 3 merged_message.optional_int64 = 2 merged_message.optional_string = 'hello' generator = unittest_pb2.TestParsingMerge.RepeatedFieldsGenerator() generator.field1.extend(messages) generator.field2.extend(messages) generator.field3.extend(messages) generator.ext1.extend(messages) generator.ext2.extend(messages) generator.group1.add().field1.MergeFrom(messages[0]) generator.group1.add().field1.MergeFrom(messages[1]) generator.group1.add().field1.MergeFrom(messages[2]) generator.group2.add().field1.MergeFrom(messages[0]) generator.group2.add().field1.MergeFrom(messages[1]) generator.group2.add().field1.MergeFrom(messages[2]) data = generator.SerializeToString() parsing_merge = unittest_pb2.TestParsingMerge() parsing_merge.ParseFromString(data) # Required and optional fields should be merged. self.assertEqual(parsing_merge.required_all_types, merged_message) self.assertEqual(parsing_merge.optional_all_types, merged_message) self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types, merged_message) self.assertEqual( parsing_merge.Extensions[unittest_pb2.TestParsingMerge.optional_ext], merged_message) # Repeated fields should not be merged. self.assertEqual(len(parsing_merge.repeated_all_types), 3) self.assertEqual(len(parsing_merge.repeatedgroup), 3) self.assertEqual( len(parsing_merge.Extensions[ unittest_pb2.TestParsingMerge.repeated_ext]), 3) def testPythonicInit(self): message = unittest_pb2.TestAllTypes( optional_int32=100, optional_fixed32=200, optional_float=300.5, optional_bytes=b'x', optionalgroup={'a': 400}, optional_nested_message={'bb': 500}, optional_foreign_message={}, optional_nested_enum='BAZ', repeatedgroup=[{ 'a': 600 }, { 'a': 700 }], repeated_nested_enum=['FOO', unittest_pb2.TestAllTypes.BAR], default_int32=800, oneof_string='y') self.assertIsInstance(message, unittest_pb2.TestAllTypes) self.assertEqual(100, message.optional_int32) self.assertEqual(200, message.optional_fixed32) self.assertEqual(300.5, message.optional_float) self.assertEqual(b'x', message.optional_bytes) self.assertEqual(400, message.optionalgroup.a) self.assertIsInstance(message.optional_nested_message, unittest_pb2.TestAllTypes.NestedMessage) self.assertEqual(500, message.optional_nested_message.bb) self.assertTrue(message.HasField('optional_foreign_message')) self.assertEqual(message.optional_foreign_message, unittest_pb2.ForeignMessage()) self.assertEqual(unittest_pb2.TestAllTypes.BAZ, message.optional_nested_enum) self.assertEqual(2, len(message.repeatedgroup)) self.assertEqual(600, message.repeatedgroup[0].a) self.assertEqual(700, message.repeatedgroup[1].a) self.assertEqual(2, len(message.repeated_nested_enum)) self.assertEqual(unittest_pb2.TestAllTypes.FOO, message.repeated_nested_enum[0]) self.assertEqual(unittest_pb2.TestAllTypes.BAR, message.repeated_nested_enum[1]) self.assertEqual(800, message.default_int32) self.assertEqual('y', message.oneof_string) self.assertFalse(message.HasField('optional_int64')) self.assertEqual(0, len(message.repeated_float)) self.assertEqual(42, message.default_int64) message = unittest_pb2.TestAllTypes(optional_nested_enum=u'BAZ') self.assertEqual(unittest_pb2.TestAllTypes.BAZ, message.optional_nested_enum) with self.assertRaises(ValueError): unittest_pb2.TestAllTypes( optional_nested_message={'INVALID_NESTED_FIELD': 17}) with self.assertRaises(TypeError): unittest_pb2.TestAllTypes( optional_nested_message={'bb': 'INVALID_VALUE_TYPE'}) with self.assertRaises(ValueError): unittest_pb2.TestAllTypes(optional_nested_enum='INVALID_LABEL') with self.assertRaises(ValueError): unittest_pb2.TestAllTypes(repeated_nested_enum='FOO') m1 = unittest_pb2.TestAllTypes( repeated_foreign_message=[{'c': 1}] ) with self.assertRaises(TypeError): unittest_pb2.TestAllTypes( repeated_nested_message=m1.repeated_foreign_message ) def testPythonicInitWithDict(self): # Both string/unicode field name keys should work. kwargs = { 'optional_int32': 100, u'optional_fixed32': 200, } msg = unittest_pb2.TestAllTypes(**kwargs) self.assertEqual(100, msg.optional_int32) self.assertEqual(200, msg.optional_fixed32) def test_documentation(self): # Also used by the interactive help() function. doc = pydoc.html.document(unittest_pb2.TestAllTypes, 'message') self.assertIn('class TestAllTypes', doc) self.assertIn('SerializePartialToString', doc) if api_implementation.Type() != 'upb': self.assertIn('repeated_float', doc) base = unittest_pb2.TestAllTypes.__bases__[0] self.assertRaises(AttributeError, getattr, base, '_extensions_by_name') # Class to test proto3-only features/behavior (updated field presence & enums) @testing_refleaks.TestCase
Proto2Test
python
matplotlib__matplotlib
lib/matplotlib/backends/registry.py
{ "start": 41, "end": 245 }
class ____(Enum): """ Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin` .. versionadded:: 3.9 """ INTERACTIVE = 0 NON_INTERACTIVE = 1
BackendFilter
python
walkccc__LeetCode
solutions/2319. Check if Matrix Is X-Matrix/2319.py
{ "start": 0, "end": 332 }
class ____: def checkXMatrix(self, grid: list[list[int]]) -> bool: n = len(grid) for i in range(n): for j in range(n): if i == j or i + j == n - 1: # in diagonal if grid[i][j] == 0: return False elif grid[i][j]: # not in diagonal return False return True
Solution
python
psf__black
src/black/report.py
{ "start": 183, "end": 244 }
class ____(Enum): NO = 0 CACHED = 1 YES = 2
Changed
python
joke2k__faker
faker/providers/isbn/isbn.py
{ "start": 1627, "end": 2676 }
class ____(ISBN): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.check_digit = self._check_digit() def _check_digit(self) -> str: """Calculate the check digit for ISBN-10. See https://en.wikipedia.org/wiki/International_Standard_Book_Number for calculation. """ weights = range(1, 10) body = "".join([part for part in [self.group, self.registrant, self.publication] if part is not None]) remainder = sum(int(b) * w for b, w in zip(body, weights)) % 11 check_digit = "X" if remainder == 10 else str(remainder) return str(check_digit) def format(self, separator: str = "") -> str: return separator.join( [ part for part in [ self.group, self.registrant, self.publication, self.check_digit, ] if part is not None ] )
ISBN10
python
jazzband__django-waffle
test_app/views.py
{ "start": 3443, "end": 3524 }
class ____(WaffleSwitchMixin, BaseWaffleView): waffle_switch = 'foo'
SwitchView
python
cython__cython
Cython/Build/Inline.py
{ "start": 998, "end": 15933 }
class ____(EnvTransform, SkipDeclarations): def __init__(self): super(EnvTransform, self).__init__(context=None) self.unbound = set() def visit_NameNode(self, node): if not self.current_env().lookup(node.name): self.unbound.add(node.name) return node def __call__(self, node): super().__call__(node) return self.unbound @cached_function def unbound_symbols(code, context=None): if context is None: context = Context([], get_directive_defaults(), options=CompilationOptions(default_options)) from ..Compiler.ParseTreeTransforms import AnalyseDeclarationsTransform tree = parse_from_strings('(tree fragment)', code) for phase in Pipeline.create_pipeline(context, 'pyx'): if phase is None: continue tree = phase(tree) if isinstance(phase, AnalyseDeclarationsTransform): break import builtins return tuple(UnboundSymbols()(tree) - set(dir(builtins))) def unsafe_type(arg, context=None): py_type = type(arg) if py_type is int: return 'long' else: return safe_type(arg, context) def safe_type(arg, context=None): py_type = type(arg) if py_type in (list, tuple, dict, str): return py_type.__name__ elif py_type is complex: return 'double complex' elif py_type is float: return 'double' elif py_type is bool: return 'bint' elif 'numpy' in sys.modules and isinstance(arg, sys.modules['numpy'].ndarray): return 'numpy.ndarray[numpy.%s_t, ndim=%s]' % (arg.dtype.name, arg.ndim) else: for base_type in py_type.__mro__: if base_type.__module__ in ('__builtin__', 'builtins'): return 'object' module = context.find_module(base_type.__module__, need_pxd=False) if module: entry = module.lookup(base_type.__name__) if entry.is_type: return '%s.%s' % (base_type.__module__, base_type.__name__) return 'object' def _get_build_extension(): dist = Distribution() # Ensure the build respects distutils configuration by parsing # the configuration files config_files = dist.find_config_files() dist.parse_config_files(config_files) build_extension = build_ext(dist) build_extension.finalize_options() return build_extension @cached_function def _create_context(cython_include_dirs): return Context( list(cython_include_dirs), get_directive_defaults(), options=CompilationOptions(default_options) ) _cython_inline_cache = {} _cython_inline_default_context = _create_context(('.',)) def _populate_unbound(kwds, unbound_symbols, locals=None, globals=None): for symbol in unbound_symbols: if symbol not in kwds: if locals is None or globals is None: calling_frame = inspect.currentframe().f_back.f_back.f_back if locals is None: locals = calling_frame.f_locals if globals is None: globals = calling_frame.f_globals if not isinstance(locals, dict): # FrameLocalsProxy is stricter than dict on how it looks up keys # and this means our "EncodedStrings" don't match the keys in locals. # Therefore copy to a dict. locals = dict(locals) if symbol in locals: kwds[symbol] = locals[symbol] elif symbol in globals: kwds[symbol] = globals[symbol] else: print("Couldn't find %r" % symbol) def _inline_key(orig_code, arg_sigs, language_level): key = orig_code, arg_sigs, sys.version_info, sys.executable, language_level, Cython.__version__ return hashlib.sha256(str(key).encode('utf-8')).hexdigest() def cython_inline(code, get_type=unsafe_type, lib_dir=os.path.join(get_cython_cache_dir(), 'inline'), cython_include_dirs=None, cython_compiler_directives=None, force=False, quiet=False, locals=None, globals=None, language_level=None, **kwds): if get_type is None: get_type = lambda x: 'object' ctx = _create_context(tuple(cython_include_dirs)) if cython_include_dirs else _cython_inline_default_context cython_compiler_directives = dict(cython_compiler_directives) if cython_compiler_directives else {} if language_level is None and 'language_level' not in cython_compiler_directives: language_level = '3' if language_level is not None: cython_compiler_directives['language_level'] = language_level key_hash = None # Fast path if this has been called in this session. _unbound_symbols = _cython_inline_cache.get(code) if _unbound_symbols is not None: _populate_unbound(kwds, _unbound_symbols, locals, globals) args = sorted(kwds.items()) arg_sigs = tuple([(get_type(value, ctx), arg) for arg, value in args]) key_hash = _inline_key(code, arg_sigs, language_level) invoke = _cython_inline_cache.get((code, arg_sigs, key_hash)) if invoke is not None: arg_list = [arg[1] for arg in args] return invoke(*arg_list) orig_code = code code, literals = strip_string_literals(code) code = strip_common_indent(code) if locals is None: locals = inspect.currentframe().f_back.f_back.f_locals if globals is None: globals = inspect.currentframe().f_back.f_back.f_globals try: _cython_inline_cache[orig_code] = _unbound_symbols = unbound_symbols(code) _populate_unbound(kwds, _unbound_symbols, locals, globals) except AssertionError: if not quiet: # Parsing from strings not fully supported (e.g. cimports). print("Could not parse code as a string (to extract unbound symbols).") cimports = [] for name, arg in list(kwds.items()): if arg is cython_module: cimports.append('\ncimport cython as %s' % name) del kwds[name] arg_names = sorted(kwds) arg_sigs = tuple([(get_type(kwds[arg], ctx), arg) for arg in arg_names]) if key_hash is None: key_hash = _inline_key(orig_code, arg_sigs, language_level) module_name = "_cython_inline_" + key_hash if module_name in sys.modules: module = sys.modules[module_name] else: build_extension = None if cython_inline.so_ext is None: # Figure out and cache current extension suffix build_extension = _get_build_extension() cython_inline.so_ext = build_extension.get_ext_filename('') lib_dir = os.path.abspath(lib_dir) module_path = os.path.join(lib_dir, module_name + cython_inline.so_ext) if not os.path.exists(lib_dir): os.makedirs(lib_dir) if force or not os.path.isfile(module_path): cflags = [] define_macros = [] c_include_dirs = [] qualified = re.compile(r'([.\w]+)[.]') for type, _ in arg_sigs: m = qualified.match(type) if m: cimports.append('\ncimport %s' % m.groups()[0]) # one special case if m.groups()[0] == 'numpy': import numpy c_include_dirs.append(numpy.get_include()) define_macros.append(("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")) # cflags.append('-Wno-unused') module_body, func_body = extract_func_code(code) params = ', '.join(['%s %s' % a for a in arg_sigs]) module_code = """ %(module_body)s %(cimports)s def __invoke(%(params)s): %(func_body)s return locals() """ % {'cimports': '\n'.join(cimports), 'module_body': module_body, 'params': params, 'func_body': func_body } for key, value in literals.items(): module_code = module_code.replace(key, value) pyx_file = os.path.join(lib_dir, module_name + '.pyx') fh = open(pyx_file, 'w') try: fh.write(module_code) finally: fh.close() extension = Extension( name=module_name, sources=[pyx_file], include_dirs=c_include_dirs or None, extra_compile_args=cflags or None, define_macros=define_macros or None, ) if build_extension is None: build_extension = _get_build_extension() build_extension.extensions = cythonize( [extension], include_path=cython_include_dirs or ['.'], compiler_directives=cython_compiler_directives, quiet=quiet) build_extension.build_temp = os.path.dirname(pyx_file) build_extension.build_lib = lib_dir build_extension.run() if sys.platform == 'win32': with os.add_dll_directory(os.path.abspath(lib_dir)): module = load_dynamic(module_name, module_path) else: module = load_dynamic(module_name, module_path) _cython_inline_cache[orig_code, arg_sigs, key_hash] = module.__invoke arg_list = [kwds[arg] for arg in arg_names] return module.__invoke(*arg_list) # The code template used for cymeit benchmark runs. # We keep the benchmark repetition separate from the benchmarked code # to prevent the C compiler from doing unhelpful loop optimisations. _CYMEIT_TEMPLATE = """ def __PYX_repeat_benchmark(benchmark, timer, size_t number): cdef size_t i t0 = timer() for i in range(number): benchmark() t1 = timer() return t1 - t0 def __PYX_make_benchmark(): {setup_code} def __PYX_run_benchmark(): {benchmark_code} return __PYX_run_benchmark """ def cymeit(code, setup_code=None, import_module=None, directives=None, timer=time.perf_counter, repeat=9): """Benchmark a Cython code string similar to 'timeit'. 'setup_code': string of setup code that will be run before taking the timings. 'import_module': a module namespace to run the benchmark in (usually a compiled Cython module). 'directives': Cython directives to use when compiling the benchmark code. 'timer': The timer function. Defaults to 'time.perf_counter', returning float seconds. Nanosecond timers are detected (and can only be used) if they return integers. 'repeat': The number of timings to take and return. Returns a tuple: (list of single-loop timings, number of loops run for each) """ import textwrap # Compile the benchmark code as an inline closure function. setup_code = strip_common_indent(setup_code) if setup_code else '' code = strip_common_indent(code) if code.strip() else 'pass' module_namespace = __import__(import_module).__dict__ if import_module else None cymeit_code = _CYMEIT_TEMPLATE.format( setup_code=textwrap.indent(setup_code, ' '*4).strip(), benchmark_code=textwrap.indent(code, ' '*8).strip(), ) namespace = cython_inline( cymeit_code, cython_compiler_directives=directives, locals=module_namespace, ) make_benchmark = namespace['__PYX_make_benchmark'] repeat_benchmark = namespace['__PYX_repeat_benchmark'] # Based on 'timeit' in CPython 3.13. def timeit(number): benchmark = make_benchmark() gcold = gc.isenabled() gc.disable() try: timing = repeat_benchmark(benchmark, timer, number) finally: if gcold: gc.enable() return timing # Find a sufficiently large number of loops, warm up the system. timer_returns_nanoseconds = isinstance(timer(), int) one_second = 1_000_000_000 if timer_returns_nanoseconds else 1.0 # Run for at least 0.2 seconds, either as integer nanoseconds or floating point seconds. min_runtime = one_second // 5 if timer_returns_nanoseconds else one_second / 5 def autorange(): i = 1 while True: for j in 1, 2, 5: number = i * j time_taken = timeit(number) assert isinstance(time_taken, int if timer_returns_nanoseconds else float) if time_taken >= min_runtime: return number elif timer_returns_nanoseconds and (time_taken < 10 and number >= 10): # Arbitrary sanity check to prevent endless loops for non-ns timers. raise RuntimeError(f"Timer seems to return non-ns timings: {timer}") i *= 10 autorange() # warmup number = autorange() # Run and repeat the benchmark. timings = [ timeit(number) for _ in range(repeat) ] half = number // 2 # for integer rounding timings = [ (timing + half) // number if timer_returns_nanoseconds else timing / number for timing in timings ] return (timings, number) # Cached suffix used by cython_inline above. None should get # overridden with actual value upon the first cython_inline invocation cython_inline.so_ext = None _find_non_space = re.compile(r'\S').search def strip_common_indent(code): min_indent = None lines = code.splitlines() for line in lines: match = _find_non_space(line) if not match: continue # blank indent = match.start() if line[indent] == '#': continue # comment if min_indent is None or min_indent > indent: min_indent = indent for ix, line in enumerate(lines): match = _find_non_space(line) if not match or not line or line[indent:indent+1] == '#': continue lines[ix] = line[min_indent:] return '\n'.join(lines) module_statement = re.compile(r'^((cdef +(extern|class))|cimport|(from .+ cimport)|(from .+ import +[*]))') def extract_func_code(code): module = [] function = [] current = function code = code.replace('\t', ' ') lines = code.split('\n') for line in lines: if not line.startswith(' '): if module_statement.match(line): current = module else: current = function current.append(line) return '\n'.join(module), ' ' + '\n '.join(function) def get_body(source): ix = source.index(':') if source[:5] == 'lambda': return "return %s" % source[ix+1:] else: return source[ix+1:] # Lots to be done here... It would be especially cool if compiled functions # could invoke each other quickly.
UnboundSymbols
python
kamyu104__LeetCode-Solutions
Python/concatenation-of-array.py
{ "start": 29, "end": 247 }
class ____(object): def getConcatenation(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.extend(nums) return nums # Time: O(n) # Space: O(1)
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/instrumentation.py
{ "start": 2495, "end": 18004 }
class ____( HasMemoized, Dict[str, "QueryableAttribute[Any]"], Generic[_O], EventTarget, ): """Tracks state information at the class level.""" dispatch: dispatcher[ClassManager[_O]] MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR STATE_ATTR = base.DEFAULT_STATE_ATTR _state_setter = staticmethod(util.attrsetter(STATE_ATTR)) expired_attribute_loader: _ExpiredAttributeLoaderProto "previously known as deferred_scalar_loader" init_method: Optional[Callable[..., None]] original_init: Optional[Callable[..., None]] = None factory: Optional[_ManagerFactory] declarative_scan: Optional[weakref.ref[_MapperConfig]] = None registry: _RegistryType if not TYPE_CHECKING: # starts as None during setup registry = None class_: Type[_O] _bases: List[ClassManager[Any]] @property @util.deprecated( "1.4", message="The ClassManager.deferred_scalar_loader attribute is now " "named expired_attribute_loader", ) def deferred_scalar_loader(self): return self.expired_attribute_loader @deferred_scalar_loader.setter @util.deprecated( "1.4", message="The ClassManager.deferred_scalar_loader attribute is now " "named expired_attribute_loader", ) def deferred_scalar_loader(self, obj): self.expired_attribute_loader = obj def __init__(self, class_): self.class_ = class_ self.info = {} self.new_init = None self.local_attrs = {} self.originals = {} self._finalized = False self.factory = None self.init_method = None self._bases = [ mgr for mgr in cast( "List[Optional[ClassManager[Any]]]", [ opt_manager_of_class(base) for base in self.class_.__bases__ if isinstance(base, type) ], ) if mgr is not None ] for base_ in self._bases: self.update(base_) cast( "InstanceEvents", self.dispatch._events )._new_classmanager_instance(class_, self) for basecls in class_.__mro__: mgr = opt_manager_of_class(basecls) if mgr is not None: self.dispatch._update(mgr.dispatch) self.manage() if "__del__" in class_.__dict__: util.warn( "__del__() method on class %s will " "cause unreachable cycles and memory leaks, " "as SQLAlchemy instrumentation often creates " "reference cycles. Please remove this method." % class_ ) def _update_state( self, finalize: bool = False, mapper: Optional[Mapper[_O]] = None, registry: Optional[_RegistryType] = None, declarative_scan: Optional[_MapperConfig] = None, expired_attribute_loader: Optional[ _ExpiredAttributeLoaderProto ] = None, init_method: Optional[Callable[..., None]] = None, ) -> None: if mapper: self.mapper = mapper # if registry: registry._add_manager(self) if declarative_scan: self.declarative_scan = weakref.ref(declarative_scan) if expired_attribute_loader: self.expired_attribute_loader = expired_attribute_loader if init_method: assert not self._finalized, ( "class is already instrumented, " "init_method %s can't be applied" % init_method ) self.init_method = init_method if not self._finalized: self.original_init = ( self.init_method if self.init_method is not None and self.class_.__init__ is object.__init__ else self.class_.__init__ ) if finalize and not self._finalized: self._finalize() def _finalize(self) -> None: if self._finalized: return self._finalized = True self._instrument_init() _instrumentation_factory.dispatch.class_instrument(self.class_) def __hash__(self) -> int: # type: ignore[override] return id(self) def __eq__(self, other: Any) -> bool: return other is self @property def is_mapped(self) -> bool: return "mapper" in self.__dict__ @HasMemoized.memoized_attribute def _all_key_set(self): return frozenset(self) @HasMemoized.memoized_attribute def _collection_impl_keys(self): return frozenset( [attr.key for attr in self.values() if attr.impl.collection] ) @HasMemoized.memoized_attribute def _scalar_loader_impls(self): return frozenset( [ attr.impl for attr in self.values() if attr.impl.accepts_scalar_loader ] ) @HasMemoized.memoized_attribute def _loader_impls(self): return frozenset([attr.impl for attr in self.values()]) @util.memoized_property def mapper(self) -> Mapper[_O]: # raises unless self.mapper has been assigned raise exc.UnmappedClassError(self.class_) def _all_sqla_attributes(self, exclude=None): """return an iterator of all classbound attributes that are implement :class:`.InspectionAttr`. This includes :class:`.QueryableAttribute` as well as extension types such as :class:`.hybrid_property` and :class:`.AssociationProxy`. """ found: Dict[str, Any] = {} # constraints: # 1. yield keys in cls.__dict__ order # 2. if a subclass has the same key as a superclass, include that # key as part of the ordering of the superclass, because an # overridden key is usually installed by the mapper which is going # on a different ordering # 3. don't use getattr() as this fires off descriptors for supercls in self.class_.__mro__[0:-1]: inherits = supercls.__mro__[1] for key in supercls.__dict__: found.setdefault(key, supercls) if key in inherits.__dict__: continue val = found[key].__dict__[key] if ( isinstance(val, interfaces.InspectionAttr) and val.is_attribute ): yield key, val def _get_class_attr_mro(self, key, default=None): """return an attribute on the class without tripping it.""" for supercls in self.class_.__mro__: if key in supercls.__dict__: return supercls.__dict__[key] else: return default def _attr_has_impl(self, key: str) -> bool: """Return True if the given attribute is fully initialized. i.e. has an impl. """ return key in self and self[key].impl is not None def _subclass_manager(self, cls: Type[_T]) -> ClassManager[_T]: """Create a new ClassManager for a subclass of this ClassManager's class. This is called automatically when attributes are instrumented so that the attributes can be propagated to subclasses against their own class-local manager, without the need for mappers etc. to have already pre-configured managers for the full class hierarchy. Mappers can post-configure the auto-generated ClassManager when needed. """ return register_class(cls, finalize=False) def _instrument_init(self): self.new_init = _generate_init(self.class_, self, self.original_init) self.install_member("__init__", self.new_init) @util.memoized_property def _state_constructor(self) -> Type[state.InstanceState[_O]]: return state.InstanceState def manage(self): """Mark this instance as the manager for its class.""" setattr(self.class_, self.MANAGER_ATTR, self) @util.hybridmethod def manager_getter(self): return _default_manager_getter @util.hybridmethod def state_getter(self): """Return a (instance) -> InstanceState callable. "state getter" callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance. """ return _default_state_getter @util.hybridmethod def dict_getter(self): return _default_dict_getter def instrument_attribute( self, key: str, inst: QueryableAttribute[Any], propagated: bool = False, ) -> None: if propagated: if key in self.local_attrs: return # don't override local attr with inherited attr else: self.local_attrs[key] = inst self.install_descriptor(key, inst) self._reset_memoizations() self[key] = inst for cls in self.class_.__subclasses__(): manager = self._subclass_manager(cls) manager.instrument_attribute(key, inst, True) def subclass_managers(self, recursive): for cls in self.class_.__subclasses__(): mgr = opt_manager_of_class(cls) if mgr is not None and mgr is not self: yield mgr if recursive: yield from mgr.subclass_managers(True) def post_configure_attribute(self, key): _instrumentation_factory.dispatch.attribute_instrument( self.class_, key, self[key] ) def uninstrument_attribute(self, key, propagated=False): if key not in self: return if propagated: if key in self.local_attrs: return # don't get rid of local attr else: del self.local_attrs[key] self.uninstall_descriptor(key) self._reset_memoizations() del self[key] for cls in self.class_.__subclasses__(): manager = opt_manager_of_class(cls) if manager: manager.uninstrument_attribute(key, True) def unregister(self) -> None: """remove all instrumentation established by this ClassManager.""" for key in list(self.originals): self.uninstall_member(key) self.mapper = None self.dispatch = None # type: ignore self.new_init = None self.info.clear() for key in list(self): if key in self.local_attrs: self.uninstrument_attribute(key) if self.MANAGER_ATTR in self.class_.__dict__: delattr(self.class_, self.MANAGER_ATTR) def install_descriptor( self, key: str, inst: QueryableAttribute[Any] ) -> None: if key in (self.STATE_ATTR, self.MANAGER_ATTR): raise KeyError( "%r: requested attribute name conflicts with " "instrumentation attribute of the same name." % key ) setattr(self.class_, key, inst) def uninstall_descriptor(self, key: str) -> None: delattr(self.class_, key) def install_member(self, key: str, implementation: Any) -> None: if key in (self.STATE_ATTR, self.MANAGER_ATTR): raise KeyError( "%r: requested attribute name conflicts with " "instrumentation attribute of the same name." % key ) self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR)) setattr(self.class_, key, implementation) def uninstall_member(self, key: str) -> None: original = self.originals.pop(key, None) if original is not DEL_ATTR: setattr(self.class_, key, original) else: delattr(self.class_, key) def instrument_collection_class( self, key: str, collection_class: Type[Collection[Any]] ) -> _CollectionFactoryType: return collections._prepare_instrumentation(collection_class) def initialize_collection( self, key: str, state: InstanceState[_O], factory: _CollectionFactoryType, ) -> Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol]: user_data = factory() impl = self.get_impl(key) assert _is_collection_attribute_impl(impl) adapter = collections.CollectionAdapter(impl, state, user_data) return adapter, user_data def is_instrumented(self, key: str, search: bool = False) -> bool: if search: return key in self else: return key in self.local_attrs def get_impl(self, key: str) -> _AttributeImpl: return self[key].impl @property def attributes(self) -> Iterable[Any]: return iter(self.values()) # InstanceState management def new_instance(self, state: Optional[InstanceState[_O]] = None) -> _O: # here, we would prefer _O to be bound to "object" # so that mypy sees that __new__ is present. currently # it's bound to Any as there were other problems not having # it that way but these can be revisited instance = self.class_.__new__(self.class_) if state is None: state = self._state_constructor(instance, self) self._state_setter(instance, state) return instance def setup_instance( self, instance: _O, state: Optional[InstanceState[_O]] = None ) -> None: if state is None: state = self._state_constructor(instance, self) self._state_setter(instance, state) def teardown_instance(self, instance: _O) -> None: delattr(instance, self.STATE_ATTR) def _serialize( self, state: InstanceState[_O], state_dict: Dict[str, Any] ) -> _SerializeManager: return _SerializeManager(state, state_dict) def _new_state_if_none( self, instance: _O ) -> Union[Literal[False], InstanceState[_O]]: """Install a default InstanceState if none is present. A private convenience method used by the __init__ decorator. """ if hasattr(instance, self.STATE_ATTR): return False elif self.class_ is not instance.__class__ and self.is_mapped: # this will create a new ClassManager for the # subclass, without a mapper. This is likely a # user error situation but allow the object # to be constructed, so that it is usable # in a non-ORM context at least. return self._subclass_manager( instance.__class__ )._new_state_if_none(instance) else: state = self._state_constructor(instance, self) self._state_setter(instance, state) return state def has_state(self, instance: _O) -> bool: return hasattr(instance, self.STATE_ATTR) def has_parent( self, state: InstanceState[_O], key: str, optimistic: bool = False ) -> bool: """TODO""" return self.get_impl(key).hasparent(state, optimistic=optimistic) def __bool__(self) -> bool: """All ClassManagers are non-zero regardless of attribute state.""" return True def __repr__(self) -> str: return "<%s of %r at %x>" % ( self.__class__.__name__, self.class_, id(self), )
ClassManager
python
huggingface__transformers
examples/pytorch/question-answering/run_seq2seq_qa.py
{ "start": 3655, "end": 31748 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. """ dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) context_column: Optional[str] = field( default="context", metadata={"help": "The name of the column in the datasets containing the contexts (for question answering)."}, ) question_column: Optional[str] = field( default="question", metadata={"help": "The name of the column in the datasets containing the questions (for question answering)."}, ) answer_column: Optional[str] = field( default="answers", metadata={"help": "The name of the column in the datasets containing the answers (for question answering)."}, ) train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."}) validation_file: Optional[str] = field( default=None, metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}, ) test_file: Optional[str] = field( default=None, metadata={"help": "An optional input test data file to evaluate the perplexity on (a text file)."}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_seq_length: int = field( default=384, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) max_answer_length: int = field( default=30, metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) }, ) val_max_answer_length: Optional[int] = field( default=None, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. Will default to `max_answer_length`. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) pad_to_max_length: bool = field( default=True, metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. If False, will pad the samples dynamically when" " batching to the maximum length in the batch (which can be faster on GPU but will be slower on TPU)." ) }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) }, ) version_2_with_negative: bool = field( default=False, metadata={"help": "If true, some of the examples do not have an answer."} ) null_score_diff_threshold: float = field( default=0.0, metadata={ "help": ( "The threshold used to select the null answer: if the best answer has a score that is less than " "the score of the null answer minus this threshold, the null answer is selected for this example. " "Only useful when `version_2_with_negative=True`." ) }, ) doc_stride: int = field( default=128, metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}, ) n_best_size: int = field( default=20, metadata={"help": "The total number of n-best predictions to generate when looking for an answer."}, ) num_beams: Optional[int] = field( default=None, metadata={ "help": ( "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, " "which is used during ``evaluate`` and ``predict``." ) }, ) ignore_pad_token_for_loss: bool = field( default=True, metadata={ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not." }, ) def __post_init__(self): if ( self.dataset_name is None and self.train_file is None and self.validation_file is None and self.test_file is None ): raise ValueError("Need either a dataset name or a training/validation file/test_file.") else: if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." if self.test_file is not None: extension = self.test_file.split(".")[-1] assert extension in ["csv", "json"], "`test_file` should be a csv or a json file." if self.val_max_answer_length is None: self.val_max_answer_length = self.max_answer_length question_answering_column_name_mapping = { "squad_v2": ("question", "context", "answer"), } def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) else: data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file extension = data_args.train_file.split(".")[-1] if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file extension = data_args.validation_file.split(".")[-1] if data_args.test_file is not None: data_files["test"] = data_args.test_file extension = data_args.test_file.split(".")[-1] raw_datasets = load_dataset( extension, data_files=data_files, field="data", cache_dir=model_args.cache_dir, token=model_args.token, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) model = AutoModelForSeq2SeqLM.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch # on a small vocab and want a smaller embedding size, remove this test. embedding_size = model.get_input_embeddings().weight.shape[0] if len(tokenizer) > embedding_size: model.resize_token_embeddings(len(tokenizer)) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") # Preprocessing the datasets. # We need to generate and tokenize inputs and targets. if training_args.do_train: column_names = raw_datasets["train"].column_names elif training_args.do_eval: column_names = raw_datasets["validation"].column_names elif training_args.do_predict: column_names = raw_datasets["test"].column_names else: logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.") return # Get the column names for input/target. dataset_columns = question_answering_column_name_mapping.get(data_args.dataset_name) if data_args.question_column is None: question_column = dataset_columns[0] if dataset_columns is not None else column_names[0] else: question_column = data_args.question_column if question_column not in column_names: raise ValueError( f"--question_column' value '{data_args.question_column}' needs to be one of: {', '.join(column_names)}" ) if data_args.context_column is None: context_column = dataset_columns[1] if dataset_columns is not None else column_names[1] else: context_column = data_args.context_column if context_column not in column_names: raise ValueError( f"--context_column' value '{data_args.context_column}' needs to be one of: {', '.join(column_names)}" ) if data_args.answer_column is None: answer_column = dataset_columns[2] if dataset_columns is not None else column_names[2] else: answer_column = data_args.answer_column if answer_column not in column_names: raise ValueError( f"--answer_column' value '{data_args.answer_column}' needs to be one of: {', '.join(column_names)}" ) # Temporarily set max_answer_length for training. max_answer_length = data_args.max_answer_length padding = "max_length" if data_args.pad_to_max_length else False if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"): logger.warning( "label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for " f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory" ) if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the " f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) def preprocess_squad_batch( examples, question_column: str, context_column: str, answer_column: str, ) -> tuple[list[str], list[str]]: questions = examples[question_column] contexts = examples[context_column] answers = examples[answer_column] def generate_input(_question, _context): return " ".join(["question:", _question.lstrip(), "context:", _context.lstrip()]) inputs = [generate_input(question, context) for question, context in zip(questions, contexts)] targets = [answer["text"][0] if len(answer["text"]) > 0 else "" for answer in answers] return inputs, targets def preprocess_function(examples): inputs, targets = preprocess_squad_batch(examples, question_column, context_column, answer_column) model_inputs = tokenizer(inputs, max_length=max_seq_length, padding=padding, truncation=True) # Tokenize targets with text_target=... labels = tokenizer(text_target=targets, max_length=max_answer_length, padding=padding, truncation=True) # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore # padding in the loss. if padding == "max_length" and data_args.ignore_pad_token_for_loss: labels["input_ids"] = [ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] ] model_inputs["labels"] = labels["input_ids"] return model_inputs # Validation preprocessing def preprocess_validation_function(examples): inputs, targets = preprocess_squad_batch(examples, question_column, context_column, answer_column) model_inputs = tokenizer( inputs, max_length=max_seq_length, padding=padding, truncation=True, return_overflowing_tokens=True, return_offsets_mapping=True, ) # Tokenize targets with the `text_target` keyword argument labels = tokenizer(text_target=targets, max_length=max_answer_length, padding=padding, truncation=True) # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore # padding in the loss. if padding == "max_length" and data_args.ignore_pad_token_for_loss: labels["input_ids"] = [ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] ] # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. sample_mapping = model_inputs.pop("overflow_to_sample_mapping") # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. model_inputs["example_id"] = [] # Augment the overflowing tokens to the labels labels_out = [] for i in range(len(model_inputs["input_ids"])): # One example can give several spans, this is the index of the example containing this span of text. sample_index = sample_mapping[i] model_inputs["example_id"].append(examples["id"][sample_index]) labels_out.append(labels["input_ids"][sample_index]) model_inputs["labels"] = labels_out return model_inputs if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: # We will select sample from whole data if argument is specified max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) # Create train feature from dataset with training_args.main_process_first(desc="train dataset map pre-processing"): train_dataset = train_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on train dataset", ) if data_args.max_train_samples is not None: # Number of samples might increase during Feature Creation, We select only specified max samples max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_examples = raw_datasets["validation"] if data_args.max_eval_samples is not None: # We will select sample from whole data max_eval_samples = min(len(eval_examples), data_args.max_eval_samples) eval_examples = eval_examples.select(range(max_eval_samples)) # Validation Feature Creation with training_args.main_process_first(desc="validation dataset map pre-processing"): eval_dataset = eval_examples.map( preprocess_validation_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on validation dataset", ) if data_args.max_eval_samples is not None: # During Feature creation dataset samples might increase, we will select required samples again max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) if training_args.do_predict: if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_examples = raw_datasets["test"] if data_args.max_predict_samples is not None: # We will select sample from whole data predict_examples = predict_examples.select(range(data_args.max_predict_samples)) # Predict Feature Creation with training_args.main_process_first(desc="prediction dataset map pre-processing"): predict_dataset = predict_examples.map( preprocess_validation_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on prediction dataset", ) if data_args.max_predict_samples is not None: # During Feature creation dataset samples might increase, we will select required samples again max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples) predict_dataset = predict_dataset.select(range(max_predict_samples)) # Data collator label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id data_collator = DataCollatorForSeq2Seq( tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if training_args.fp16 else None, ) metric = evaluate.load( "squad_v2" if data_args.version_2_with_negative else "squad", cache_dir=model_args.cache_dir ) def compute_metrics(p: EvalPrediction): return metric.compute(predictions=p.predictions, references=p.label_ids) # Post-processing: def post_processing_function( examples: datasets.Dataset, features: datasets.Dataset, outputs: EvalLoopOutput, stage="eval" ): # Decode the predicted tokens. preds = outputs.predictions if isinstance(preds, tuple): preds = preds[0] # Replace -100s used for padding as we can't decode them preds = np.where(preds != -100, preds, tokenizer.pad_token_id) decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) # Build a map example to its corresponding features. example_id_to_index = {k: i for i, k in enumerate(examples["id"])} feature_per_example = {example_id_to_index[feature["example_id"]]: i for i, feature in enumerate(features)} predictions = {} # Let's loop over all the examples! for example_index, example in enumerate(examples): # This is the index of the feature associated to the current example. feature_index = feature_per_example[example_index] predictions[example["id"]] = decoded_preds[feature_index] # Format the result to the format the metric expects. if data_args.version_2_with_negative: formatted_predictions = [ {"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items() ] else: formatted_predictions = [{"id": k, "prediction_text": v} for k, v in predictions.items()] references = [{"id": ex["id"], "answers": ex[answer_column]} for ex in examples] return EvalPrediction(predictions=formatted_predictions, label_ids=references) # Initialize our Trainer trainer = QuestionAnsweringSeq2SeqTrainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, eval_examples=eval_examples if training_args.do_eval else None, processing_class=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics if training_args.predict_with_generate else None, post_process_function=post_processing_function, ) # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the tokenizer too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation results = {} max_length = ( training_args.generation_max_length if training_args.generation_max_length is not None else data_args.val_max_answer_length ) num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval") max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # Prediction if training_args.do_predict: logger.info("*** Predict ***") results = trainer.predict(predict_dataset, predict_examples) metrics = results.metrics max_predict_samples = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset) ) metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset)) trainer.log_metrics("predict", metrics) trainer.save_metrics("predict", metrics) if training_args.push_to_hub: kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "question-answering"} if data_args.dataset_name is not None: kwargs["dataset_tags"] = data_args.dataset_name if data_args.dataset_config_name is not None: kwargs["dataset_args"] = data_args.dataset_config_name kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" else: kwargs["dataset"] = data_args.dataset_name trainer.push_to_hub(**kwargs) def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
DataTrainingArguments
python
ansible__ansible
test/units/module_utils/facts/test_ansible_collector.py
{ "start": 18127, "end": 18523 }
class ____(TestCollectedFacts): gather_subset = ['pkg_mgr'] min_fact_count = 1 max_fact_count = 20 expected_facts = ['gather_subset', 'module_setup', 'pkg_mgr'] collected_facts = { "ansible_distribution": "Fedora", "ansible_distribution_major_version": "28", "ansible_os_family": "RedHat" }
TestPkgMgrFacts
python
spyder-ide__spyder
spyder/utils/color_system.py
{ "start": 222, "end": 562 }
class ____: B0 = '#000000' B10 = '#064738' B20 = '#055C49' B30 = '#007A5E' B40 = '#008760' B50 = '#019D70' B60 = '#02BA85' B70 = '#20C997' B80 = '#44DEB0' B90 = '#3BEBB7' B100 = '#88F2D3' B110 = '#B0F5E1' B120 = '#D1FBEE' B130 = '#E4FFF7' B140 = '#F5FFFD' B150 = '#FFFFFF'
Green
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_single.py
{ "start": 71372, "end": 80657 }
class ____( fixtures.DeclarativeMappedTest, AssertsCompiledSQL ): __dialect__ = "default" @classmethod def setup_classes(cls, with_polymorphic=None, include_sub_defaults=False): Base = cls.DeclarativeBasic class Employee(Base): __tablename__ = "employee" id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(50)) __mapper_args__ = { "polymorphic_identity": "employee", "polymorphic_on": type, } class Engineer(Employee): __tablename__ = "engineer" id = Column(Integer, ForeignKey("employee.id"), primary_key=True) engineer_info = Column(String(50)) manager_id = Column(ForeignKey("manager.id")) __mapper_args__ = {"polymorphic_identity": "engineer"} class Manager(Employee): __tablename__ = "manager" id = Column(Integer, ForeignKey("employee.id"), primary_key=True) manager_data = Column(String(50)) __mapper_args__ = {"polymorphic_identity": "manager"} class Boss(Manager): __mapper_args__ = {"polymorphic_identity": "boss"} def _with_poly_fixture(self): employee = self.classes.Employee.__table__ engineer = self.classes.Engineer.__table__ manager = self.classes.Manager.__table__ poly = ( select( employee.c.id, employee.c.type, employee.c.name, manager.c.manager_data, null().label("engineer_info"), null().label("manager_id"), ) .select_from(employee.join(manager)) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .union_all( select( employee.c.id, employee.c.type, employee.c.name, null().label("manager_data"), engineer.c.engineer_info, engineer.c.manager_id, ) .select_from(employee.join(engineer)) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) ) .alias() ) return poly def test_wpoly_single_inh_subclass(self): poly = with_polymorphic( self.classes.Employee, [self.classes.Boss, self.classes.Manager, self.classes.Engineer], self._with_poly_fixture(), ) s = fixture_session() q = s.query(poly.Boss) self.assert_compile( q, "SELECT " "anon_1.employee_id AS anon_1_employee_id, " "anon_1.employee_name AS anon_1_employee_name, " "anon_1.employee_type AS anon_1_employee_type, " "anon_1.manager_manager_data AS anon_1_manager_manager_data " "FROM " "(SELECT " "employee.id AS employee_id, employee.type AS employee_type, " "employee.name AS employee_name, " "manager.manager_data AS manager_manager_data, " "NULL AS engineer_info, NULL AS manager_id FROM employee " "JOIN manager ON employee.id = manager.id " "UNION ALL " "SELECT employee.id AS employee_id, " "employee.type AS employee_type, " "employee.name AS employee_name, NULL AS manager_data, " "engineer.engineer_info AS engineer_engineer_info, " "engineer.manager_id AS engineer_manager_id " "FROM employee JOIN engineer ON employee.id = engineer.id) " "AS anon_1", ) def test_query_wpoly_single_inh_subclass(self): Boss = self.classes.Boss poly = self._with_poly_fixture() s = fixture_session() wp = with_polymorphic(Boss, [], poly) q = s.query(wp) self.assert_compile( q, "SELECT anon_1.employee_id AS anon_1_employee_id, " "anon_1.employee_name AS anon_1_employee_name, " "anon_1.employee_type AS anon_1_employee_type, " "anon_1.manager_manager_data AS anon_1_manager_manager_data " "FROM (SELECT employee.id AS employee_id, employee.type " "AS employee_type, employee.name AS employee_name, " "manager.manager_data AS manager_manager_data, " "NULL AS engineer_info, NULL AS manager_id FROM employee " "JOIN manager ON employee.id = manager.id " "UNION ALL SELECT employee.id AS employee_id, " "employee.type AS employee_type, employee.name AS employee_name, " "NULL AS manager_data, " "engineer.engineer_info AS engineer_engineer_info, " "engineer.manager_id AS engineer_manager_id " "FROM employee JOIN engineer ON employee.id = engineer.id) " "AS anon_1 WHERE anon_1.employee_type IN (__[POSTCOMPILE_type_1])", ) @testing.combinations((True,), (False,), argnames="autoalias") def test_single_inh_subclass_join_joined_inh_subclass(self, autoalias): Boss, Engineer = self.classes("Boss", "Engineer") s = fixture_session() if autoalias: q = s.query(Boss).join(Engineer, Engineer.manager_id == Boss.id) else: e1 = aliased(Engineer, flat=True) q = s.query(Boss).join(e1, e1.manager_id == Boss.id) with ( _aliased_join_warning(r"Mapper\[Engineer\(engineer\)\]") if autoalias else nullcontext() ): self.assert_compile( q, "SELECT manager.id AS manager_id, employee.id AS employee_id, " "employee.name AS employee_name, " "employee.type AS employee_type, " "manager.manager_data AS manager_manager_data " "FROM employee JOIN manager ON employee.id = manager.id " "JOIN (employee AS employee_1 JOIN engineer AS engineer_1 " "ON employee_1.id = engineer_1.id) " "ON engineer_1.manager_id = manager.id " "WHERE employee.type IN (__[POSTCOMPILE_type_1])", ) def test_single_inh_subclass_join_wpoly_joined_inh_subclass(self): Boss = self.classes.Boss poly = with_polymorphic( self.classes.Employee, [self.classes.Boss, self.classes.Manager, self.classes.Engineer], self._with_poly_fixture(), ) s = fixture_session() q = s.query(Boss).join( poly.Engineer, poly.Engineer.manager_id == Boss.id ) self.assert_compile( q, "SELECT manager.id AS manager_id, employee.id AS employee_id, " "employee.name AS employee_name, employee.type AS employee_type, " "manager.manager_data AS manager_manager_data " "FROM employee JOIN manager ON employee.id = manager.id " "JOIN (SELECT employee.id AS employee_id, " "employee.type AS employee_type, employee.name AS employee_name, " "manager.manager_data AS manager_manager_data, " "NULL AS engineer_info, NULL AS manager_id " "FROM employee JOIN manager ON employee.id = manager.id " "UNION ALL " "SELECT employee.id AS employee_id, " "employee.type AS employee_type, employee.name AS employee_name, " "NULL AS manager_data, " "engineer.engineer_info AS engineer_engineer_info, " "engineer.manager_id AS engineer_manager_id " "FROM employee " "JOIN engineer ON employee.id = engineer.id) AS anon_1 " "ON anon_1.manager_id = manager.id " "WHERE employee.type IN (__[POSTCOMPILE_type_1])", ) @testing.combinations((True,), (False,), argnames="autoalias") def test_joined_inh_subclass_join_single_inh_subclass(self, autoalias): Engineer = self.classes.Engineer Boss = self.classes.Boss s = fixture_session() if autoalias: q = s.query(Engineer).join(Boss, Engineer.manager_id == Boss.id) else: b1 = aliased(Boss, flat=True) q = s.query(Engineer).join(b1, Engineer.manager_id == b1.id) with ( _aliased_join_warning(r"Mapper\[Boss\(manager\)\]") if autoalias else nullcontext() ): self.assert_compile( q, "SELECT engineer.id AS engineer_id, " "employee.id AS employee_id, " "employee.name AS employee_name, " "employee.type AS employee_type, " "engineer.engineer_info AS engineer_engineer_info, " "engineer.manager_id AS engineer_manager_id " "FROM employee JOIN engineer ON employee.id = engineer.id " "JOIN (employee AS employee_1 JOIN manager AS manager_1 " "ON employee_1.id = manager_1.id) " "ON engineer.manager_id = manager_1.id " "AND employee_1.type IN (__[POSTCOMPILE_type_1])", )
SingleFromPolySelectableTest
python
pola-rs__polars
py-polars/src/polars/io/partition.py
{ "start": 3919, "end": 7577 }
class ____: def __init__( self, base_path: str | Path, *, file_path_provider: Callable[ [KeyedPartitionContext], Path | str | IO[bytes] | IO[str] ] | None = None, partition_by: str | Expr | Sequence[str | Expr] | Mapping[str, Expr] | None = None, partition_keys_sorted: bool | None = None, include_keys: bool | None = None, per_partition_sort_by: str | Expr | Sequence[str | Expr] | None = None, per_file_sort_by: str | Expr | Sequence[str | Expr] | None = None, max_rows_per_file: int | None = None, finish_callback: Callable[[DataFrame], None] | None = None, ) -> None: base_path = str(base_path) self._pl_sink_directory = _SinkDirectoryInner( base_path=base_path, file_path_provider=file_path_provider, partition_by=( _parse_to_pyexpr_list(partition_by) if partition_by is not None else None ), partition_keys_sorted=partition_keys_sorted, include_keys=include_keys, per_partition_sort_by=( _parse_to_pyexpr_list(per_partition_sort_by) if per_partition_sort_by is not None else None ), per_file_sort_by=( _parse_to_pyexpr_list(per_file_sort_by) if per_file_sort_by is not None else None ), max_rows_per_file=max_rows_per_file, finish_callback=( _prepare_finish_callback(finish_callback) if finish_callback is not None else None ), ) @property def _base_path(self) -> str | None: return self._pl_sink_directory.base_path def _parse_to_pyexpr_list( exprs_or_columns: str | Expr | Sequence[str | Expr] | Mapping[str, Expr], ) -> list[PyExpr]: if isinstance(exprs_or_columns, Mapping): return [e.alias(k)._pyexpr for k, e in exprs_or_columns.items()] return parse_into_list_of_expressions(exprs_or_columns) def _cast_base_file_path_cb( file_path_cb: Callable[[BasePartitionContext], Path | str | IO[bytes] | IO[str]] | None, ) -> Callable[[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]] | None: if file_path_cb is None: return None return lambda ctx: file_path_cb( BasePartitionContext( file_idx=ctx.file_idx, file_path=Path(ctx.file_path), full_path=Path(ctx.full_path), ) ) def _cast_keyed_file_path_cb( file_path_cb: Callable[[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]] | None, ) -> Callable[[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]] | None: if file_path_cb is None: return None return lambda ctx: file_path_cb( KeyedPartitionContext( file_idx=ctx.file_idx, part_idx=ctx.part_idx, in_part_idx=ctx.in_part_idx, keys=[ KeyedPartition( name=kv.name, str_value=kv.str_value, raw_value=kv.raw_value ) for kv in ctx.keys ], file_path=Path(ctx.file_path), full_path=Path(ctx.full_path), ) ) def _prepare_finish_callback( f: Callable[[DataFrame], None] | None, ) -> Callable[[PyDataFrame], None] | None: if f is None: return None def cb(pydf: PyDataFrame) -> None: nonlocal f f(DataFrame._from_pydf(pydf)) return cb
_SinkDirectory
python
Farama-Foundation__Gymnasium
tests/testing_env.py
{ "start": 1844, "end": 5318 }
class ____(gym.Env): """A generic testing environment for use in testing with modified environments are required.""" def __init__( self, action_space: spaces.Space = spaces.Box(0, 1, (1,)), observation_space: spaces.Space = spaces.Box(0, 1, (1,)), reset_func: Callable = basic_reset_func, step_func: Callable = basic_step_func, render_func: Callable = basic_render_func, metadata: dict[str, Any] = {"render_modes": []}, render_mode: str | None = None, spec: EnvSpec = EnvSpec( "TestingEnv-v0", "tests.testing_env:GenericTestEnv", max_episode_steps=100 ), ): """Generic testing environment constructor. Args: action_space: The environment action space observation_space: The environment observation space reset_func: The environment reset function step_func: The environment step function render_func: The environment render function metadata: The environment metadata render_mode: The render mode of the environment spec: The environment spec """ self.metadata = metadata self.render_mode = render_mode self.spec = spec if observation_space is not None: self.observation_space = observation_space if action_space is not None: self.action_space = action_space if reset_func is not None: self.reset = types.MethodType(reset_func, self) if step_func is not None: self.step = types.MethodType(step_func, self) if render_func is not None: self.render = types.MethodType(render_func, self) def reset( self, *, seed: int | None = None, options: dict | None = None, ) -> ObsType | tuple[ObsType, dict]: """Resets the environment.""" # If you need a default working reset function, use `basic_reset_fn` above raise NotImplementedError("TestingEnv reset_fn is not set.") def step(self, action: ActType) -> tuple[ObsType, float, bool, dict[str, Any]]: """Steps through the environment.""" raise NotImplementedError("TestingEnv step_fn is not set.") def render(self): """Renders the environment.""" raise NotImplementedError("testingEnv render_fn is not set.") def basic_vector_reset_func( self, *, seed: int | None = None, options: dict | None = None, ) -> tuple[ObsType, dict]: """A basic reset function that will pass the environment check using random actions from the observation space.""" super(GenericTestVectorEnv, self).reset(seed=seed) self.observation_space.seed(self.np_random_seed) return self.observation_space.sample(), {"options": options} def basic_vector_step_func( self, action: ActType ) -> tuple[ObsType, np.ndarray, np.ndarray, np.ndarray, dict]: """A step function that follows the basic step api that will pass the environment check using random actions from the observation space.""" obs = self.observation_space.sample() rewards = np.zeros(self.num_envs, dtype=np.float64) terminations = np.zeros(self.num_envs, dtype=np.bool_) truncations = np.zeros(self.num_envs, dtype=np.bool_) return obs, rewards, terminations, truncations, {} def basic_vector_render_func(self): """Basic render fn that does nothing.""" pass
GenericTestEnv
python
hynek__structlog
tests/test_output.py
{ "start": 5632, "end": 8669 }
class ____: def test_prints_to_stdout_by_default(self, capsys): """ Instantiating without arguments gives conveniently a logger to standard out. """ BytesLogger().msg(b"hell\xc3\xb6") out, err = capsys.readouterr() assert "hellö\n" == out assert "" == err def test_prints_to_correct_file(self, tmp_path, capsys): """ Supplied files are respected. """ p = tmp_path / "test.log" with p.open("wb") as f: BytesLogger(f).msg(b"hello") out, err = capsys.readouterr() assert "" == out == err assert "hello\n" == p.read_text() def test_repr(self): """ __repr__ makes sense. """ assert repr(BytesLogger()).startswith("<BytesLogger(file=") def test_lock(self, sio): """ Creating a logger adds a lock to WRITE_LOCKS. """ assert sio not in WRITE_LOCKS BytesLogger(sio) assert sio in WRITE_LOCKS @pytest.mark.parametrize("method", stdlib_log_methods) def test_stdlib_methods_support(self, method): """ BytesLogger implements methods of stdlib loggers. """ sio = BytesIO() getattr(BytesLogger(sio), method)(b"hello") assert b"hello" in sio.getvalue() @pytest.mark.parametrize("file", [None, stdout.buffer, stderr.buffer]) @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1)) def test_pickle(self, file, proto): """ Can be pickled and unpickled for stdout and stderr. Can't compare output because capsys et all would confuse the logic. """ pl = BytesLogger(file=file) rv = pickle.loads(pickle.dumps(pl, proto)) assert pl._file is rv._file assert pl._lock is rv._lock @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1)) def test_pickle_not_stdout_stderr(self, tmpdir, proto): """ BytesLoggers with different files than stdout/stderr raise a PickingError. """ f = tmpdir.join("file.log") f.write("") pl = BytesLogger(file=f.open()) with pytest.raises(pickle.PicklingError, match="Only BytesLoggers to"): pickle.dumps(pl, proto) def test_deepcopy(self, capsys): """ Deepcopied BytesLogger works. """ copied_logger = copy.deepcopy(BytesLogger()) copied_logger.msg(b"hello") out, err = capsys.readouterr() assert "hello\n" == out assert "" == err def test_deepcopy_no_stdout(self, tmp_path): """ Only BytesLoggers that log to stdout or stderr can be deepcopy-ed. """ p = tmp_path / "log.txt" with p.open(mode="wb") as f: logger = BytesLogger(f) logger.msg(b"hello") with pytest.raises(copy.error): copy.deepcopy(logger) assert "hello\n" == p.read_text()
TestBytesLogger
python
kamyu104__LeetCode-Solutions
Python/convert-doubly-linked-list-to-array-i.py
{ "start": 43, "end": 290 }
class ____: def toArray(self, head): """ :type head: Node :rtype: List[int] """ result = [] while head: result.append(head.val) head = head.next return result
Solution
python
tensorflow__tensorflow
tensorflow/python/keras/testing_utils.py
{ "start": 19771, "end": 22655 }
class ____(models.Model): """A Keras subclass model that uses a custom build method.""" def __init__(self, layer_generating_func, *args, **kwargs): super(_SubclassModelCustomBuild, self).__init__(*args, **kwargs) self.all_layers = None self._layer_generating_func = layer_generating_func def build(self, input_shape): model_layers = [] for layer in self._layer_generating_func(): model_layers.append(layer) self.all_layers = model_layers def call(self, inputs, **kwargs): x = inputs for layer in self.all_layers: x = layer(x) return x def get_model_from_layers(model_layers, input_shape=None, input_dtype=None, name=None, input_ragged=None, input_sparse=None, model_type=None): """Builds a model from a sequence of layers. Args: model_layers: The layers used to build the network. input_shape: Shape tuple of the input or 'TensorShape' instance. input_dtype: Datatype of the input. name: Name for the model. input_ragged: Boolean, whether the input data is a ragged tensor. input_sparse: Boolean, whether the input data is a sparse tensor. model_type: One of "subclass", "subclass_custom_build", "sequential", or "functional". When None, defaults to `get_model_type`. Returns: A Keras model. """ if model_type is None: model_type = get_model_type() if model_type == 'subclass': inputs = None if input_ragged or input_sparse: inputs = layers.Input( shape=input_shape, dtype=input_dtype, ragged=input_ragged, sparse=input_sparse) return _SubclassModel(model_layers, name=name, input_tensor=inputs) if model_type == 'subclass_custom_build': layer_generating_func = lambda: model_layers return _SubclassModelCustomBuild(layer_generating_func, name=name) if model_type == 'sequential': model = models.Sequential(name=name) if input_shape: model.add( layers.InputLayer( input_shape=input_shape, dtype=input_dtype, ragged=input_ragged, sparse=input_sparse)) for layer in model_layers: model.add(layer) return model if model_type == 'functional': if not input_shape: raise ValueError('Cannot create a functional model from layers with no ' 'input shape.') inputs = layers.Input( shape=input_shape, dtype=input_dtype, ragged=input_ragged, sparse=input_sparse) outputs = inputs for layer in model_layers: outputs = layer(outputs) return models.Model(inputs, outputs, name=name) raise ValueError('Unknown model type {}'.format(model_type))
_SubclassModelCustomBuild
python
openai__openai-python
src/openai/types/responses/response_function_shell_call_output_content.py
{ "start": 451, "end": 732 }
class ____(BaseModel): exit_code: int """The exit code returned by the shell process.""" type: Literal["exit"] """The outcome type. Always `exit`.""" Outcome: TypeAlias = Annotated[Union[OutcomeTimeout, OutcomeExit], PropertyInfo(discriminator="type")]
OutcomeExit
python
urllib3__urllib3
src/urllib3/response.py
{ "start": 2446, "end": 5171 }
class ____(ContentDecoder): def __init__(self) -> None: self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) self._state = GzipDecoderState.FIRST_MEMBER def decompress(self, data: bytes) -> bytes: ret = bytearray() if self._state == GzipDecoderState.SWALLOW_DATA or not data: return bytes(ret) while True: try: ret += self._obj.decompress(data) except zlib.error: previous_state = self._state # Ignore data after the first error self._state = GzipDecoderState.SWALLOW_DATA if previous_state == GzipDecoderState.OTHER_MEMBERS: # Allow trailing garbage acceptable in other gzip clients return bytes(ret) raise data = self._obj.unused_data if not data: return bytes(ret) self._state = GzipDecoderState.OTHER_MEMBERS self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) def flush(self) -> bytes: return self._obj.flush() if brotli is not None: class BrotliDecoder(ContentDecoder): # Supports both 'brotlipy' and 'Brotli' packages # since they share an import name. The top branches # are for 'brotlipy' and bottom branches for 'Brotli' def __init__(self) -> None: self._obj = brotli.Decompressor() if hasattr(self._obj, "decompress"): setattr(self, "decompress", self._obj.decompress) else: setattr(self, "decompress", self._obj.process) def flush(self) -> bytes: if hasattr(self._obj, "flush"): return self._obj.flush() # type: ignore[no-any-return] return b"" try: if sys.version_info >= (3, 14): from compression import zstd else: from backports import zstd except ImportError: HAS_ZSTD = False else: HAS_ZSTD = True class ZstdDecoder(ContentDecoder): def __init__(self) -> None: self._obj = zstd.ZstdDecompressor() def decompress(self, data: bytes) -> bytes: if not data: return b"" data_parts = [self._obj.decompress(data)] while self._obj.eof and self._obj.unused_data: unused_data = self._obj.unused_data self._obj = zstd.ZstdDecompressor() data_parts.append(self._obj.decompress(unused_data)) return b"".join(data_parts) def flush(self) -> bytes: if not self._obj.eof: raise DecodeError("Zstandard data is incomplete") return b""
GzipDecoder
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 17102, "end": 17755 }
class ____(nn.Module): """ `ClvpGatedLinearUnit` uses the second half of the `hidden_states` to act as a gate for the first half of the `hidden_states` which controls the flow of data from the first of the tensor. """ def __init__(self, config): super().__init__() self.activation_fn = ACT2FN[config.hidden_act] self.proj = nn.Linear(config.hidden_size, config.intermediate_size * 2) def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor: hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1) return hidden_states * self.activation_fn(gate)
ClvpGatedLinearUnit
python
Farama-Foundation__Gymnasium
tests/envs/registration/test_env_spec.py
{ "start": 6001, "end": 6099 }
class ____: def __getstate__(self): raise RuntimeError("Cannot pickle me!")
Unpickleable
python
google__pytype
pytype/tests/test_list2.py
{ "start": 798, "end": 5157 }
class ____(test_base.BaseTest): """Tests for builtins.list in Python 3.""" def test_byte_unpack_ex(self): ty = self.Infer(""" from typing import List a, *b, c, d = 1, 2, 3, 4, 5, 6, 7 i, *j = 1, 2, 3, "4" *k, l = 4, 5, 6 m, *n, o = [4, 5, "6", None, 7, 8] p, *q, r = 4, 5, "6", None, 7, 8 vars = None # type : List[int] s, *t, u = vars """) self.assertTypesMatchPytd( ty, """ from typing import List, Optional, Union a = ... # type: int b = ... # type: List[int] c = ... # type: int d = ... # type: int i = ... # type: int j = ... # type: List[Union[int, str]] k = ... # type: List[int] l = ... # type: int m = ... # type: int n = ... # type: List[Optional[Union[int, str]]] o = ... # type: int p = ... # type: int q = ... # type: List[Optional[Union[int, str]]] r = ... # type: int s = ... # type: int t = ... # type: List[int] u = ... # type: int vars = ... # type: List[int] """, ) def test_getitem_slot(self): ty, _ = self.InferWithErrors(""" a = [1, '2', 3, 4] p = a[1] q = 1 if __random__ else 2 r = a[q] s = a["s"] # unsupported-operands t = a[-1] """) self.assertTypesMatchPytd( ty, """ from typing import Any, List, Union a = ... # type: List[Union[int, str]] p = ... # type: str q = ... # type: int r = ... # type: Union[int, str] s = ... # type: Any t = ... # type: int """, ) def test_slice_returntype(self): # each of the superclasses of list should return their own type when sliced. ty = self.Infer(""" from typing import Sequence, MutableSequence a: Sequence[int] = [1] b = a[0:1] c: MutableSequence[int] = [1] d = c[0:1] e = [2] f = e[0:1] """) self.assertTypesMatchPytd( ty, """ from typing import List, MutableSequence, Sequence a = ... # type: Sequence[int] b = ... # type: Sequence[int] c = ... # type: MutableSequence[int] d = ... # type: MutableSequence[int] e = ... # type: List[int] f = ... # type: List[int] """, ) @test_base.skip("Requires more precise slice objects") def test_getitem_slice(self): # Python 3 uses __getitem__ with slice objects instead of __getslice__. # Pytype doesn't support slice objects well, so a lot of results here are # imprecise. It also means wrong-arg-types won't be detected. ty, _ = self.InferWithErrors(""" a = [1, '2', 3, 4] b = a[:] c = 1 if __random__ else 2 d = a[c:2] e = a[c:] f = a[2:] g = a[2:None] h = a[None:2] i = a[None:None] j = a[int:str] # wrong-arg-types k = a["s":] # wrong-arg-types m = a[1:-1] n = a[0:0] o = a[1:1] p = a[1:2] """) self.assertTypesMatchPytd( ty, """ from typing import Any, List, Union a = ... # type: List[Union[int, str]] b = ... # type: List[Union[int, str]] c = ... # type: int d = ... # type: List[str] e = ... # type: List[Union[int, str]] f = ... # type: List[int] g = ... # type: List[int] h = ... # type: List[Union[int, str]] i = ... # type: List[Union[int, str]] j = ... # type: Any k = ... # type: Any m = ... # type: List[Union[int, str]] n = ... # type: List[nothing] o = ... # type: List[nothing] p = ... # type: List[str] """, ) def test_appends(self): # Regression test for a crash involving list appends and accesses for a # variable with multiple bindings. self.Check(""" from typing import List def f(): lst1: List[List[str]] = [] lst2: List[List[str]] = [] if __random__: x, lst1 = __any_object__ else: x = lst2[-1] lst1.append(x) lst2.append(lst1[-1]) """) def test_clear(self): ty = self.Infer(""" a = [0] a.clear() """) self.assertTypesMatchPytd( ty, """ from typing import List a = ... # type: List[int] """, ) if __name__ == "__main__": test_base.main()
ListTest
python
Pylons__pyramid
tests/test_traversal.py
{ "start": 1426, "end": 3142 }
class ____(unittest.TestCase): def _callFUT(self, path): from pyramid.traversal import traversal_path_info return traversal_path_info(path) def test_path_startswith_endswith(self): self.assertEqual(self._callFUT('/foo/'), (text_('foo'),)) def test_empty_elements(self): self.assertEqual(self._callFUT('foo///'), (text_('foo'),)) def test_onedot(self): self.assertEqual( self._callFUT('foo/./bar'), (text_('foo'), text_('bar')) ) def test_twodots(self): self.assertEqual(self._callFUT('foo/../bar'), (text_('bar'),)) def test_twodots_at_start(self): self.assertEqual(self._callFUT('../../bar'), (text_('bar'),)) def test_segments_are_unicode(self): result = self._callFUT('/foo/bar') self.assertEqual(type(result[0]), str) self.assertEqual(type(result[1]), str) def test_same_value_returned_if_cached(self): result1 = self._callFUT('/foo/bar') result2 = self._callFUT('/foo/bar') self.assertEqual(result1, (text_('foo'), text_('bar'))) self.assertEqual(result2, (text_('foo'), text_('bar'))) def test_unicode_simple(self): path = text_('/abc') self.assertEqual(self._callFUT(path), (text_('abc'),)) def test_highorder(self): la = b'La Pe\xc3\xb1a' latin1 = text_(la) result = self._callFUT(latin1) self.assertEqual(result, (text_(la, 'utf-8'),)) def test_highorder_undecodeable(self): from pyramid.exceptions import URLDecodeError notlatin1 = text_(b'La Pe\xc3\xb1a', 'utf-8') self.assertRaises(URLDecodeError, self._callFUT, notlatin1)
TraversalPathInfoTests
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/focus_component_class.py
{ "start": 680, "end": 944 }
class ____(App[None]): def compose(self) -> ComposeResult: yield Header() with VerticalScroll(): for n in range(40): yield Tester(n) yield Footer() if __name__ == "__main__": StyleBugApp().run()
StyleBugApp
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_submit_pipeline_execution.py
{ "start": 558, "end": 13801 }
class ____(Config): conn_string: str port: int @python_client_test_suite def test_job_success(mock_client: MockClient): mock_client.mock_gql_client.execute.return_value = launch_job_success_response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={"ops": {"foo": dict(conn_string="my_conn", port=4253)}}, ) assert actual_run_id == EXPECTED_RUN_ID @python_client_test_suite def test_job_success_run_config(mock_client: MockClient): mock_client.mock_gql_client.execute.return_value = launch_job_success_response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config=RunConfig(ops={"foo": AnOpConfig(conn_string="my_conn", port=4253)}), ) assert actual_run_id == EXPECTED_RUN_ID @python_client_test_suite def test_job_tags_success(mock_client: MockClient): mock_client.mock_gql_client.execute.return_value = launch_job_success_response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quuz", tags={"my_tag": "a", "my_other_tag": "b"}, ) assert actual_run_id == EXPECTED_RUN_ID @python_client_test_suite def test_job_subset_success(mock_client: MockClient): mock_client.mock_gql_client.execute.return_value = launch_job_success_response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quuz", op_selection=["foobar"], ) assert actual_run_id == EXPECTED_RUN_ID # Check if the op_selection argument is properly passed to the GraphQL query execute_call_args = mock_client.mock_gql_client.execute.call_args selector = execute_call_args[1]["variable_values"]["executionParams"]["selector"] assert selector["solidSelection"] == ["foobar"] @python_client_test_suite def test_job_asset_subset_success(mock_client: MockClient): mock_client.mock_gql_client.execute.return_value = launch_job_success_response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quuz", asset_selection=[["foo", "bar"], "quux"], ) assert actual_run_id == EXPECTED_RUN_ID # Check if the asset_selection argument is properly passed to the GraphQL query execute_call_args = mock_client.mock_gql_client.execute.call_args selector = execute_call_args[1]["variable_values"]["executionParams"]["selector"] assert "assetSelection" in selector assert selector["assetSelection"] == [ AssetKey(["foo", "bar"]).to_graphql_input(), AssetKey(["quux"]).to_graphql_input(), ] @python_client_test_suite def test_complex_tags_success(mock_client: MockClient): response = { "launchPipelineExecution": { "__typename": "LaunchRunSuccess", "run": {"runId": EXPECTED_RUN_ID}, } } mock_client.mock_gql_client.execute.return_value = response actual_run_id = mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quuz", run_config={}, tags={"my_tag": {"I'm": {"a JSON-encodable": "thing"}}}, ) assert actual_run_id == EXPECTED_RUN_ID @python_client_test_suite def test_invalid_tags_failure(mock_client: MockClient): class SomeWeirdObject: pass with pytest.raises(DagsterInvalidDefinitionError): mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quuz", run_config={}, tags={"my_invalid_tag": SomeWeirdObject()}, ) @python_client_test_suite def test_no_location_or_repo_provided_success(mock_client: MockClient): repo_loc_name, repo_name, job_name = "bar", "baz", "quux" other_repo_name, other_job_name = "other repo", "my_job" get_locations_and_names_response = { "repositoriesOrError": { "__typename": "RepositoryConnection", "nodes": [ { "name": repo_name, "location": {"name": repo_loc_name}, "pipelines": [{"name": job_name}, {"name": other_job_name}], }, { "name": other_repo_name, "location": {"name": repo_loc_name}, "pipelines": [{"name": "fun pipeline"}, {"name": other_job_name}], }, ], } } submit_execution_response = { "launchPipelineExecution": { "__typename": "LaunchRunSuccess", "run": {"runId": EXPECTED_RUN_ID}, } } mock_client.mock_gql_client.execute.side_effect = [ get_locations_and_names_response, submit_execution_response, ] actual_run_id = mock_client.python_client.submit_job_execution(job_name, run_config={}) assert actual_run_id == EXPECTED_RUN_ID def no_location_or_repo_provided_duplicate_pipeline_mock_config(mock_client: MockClient): repo_loc_name, repo_name, job_name = "bar", "baz", "quux" other_repo_name = "other repo" get_locations_and_names_response = { "repositoriesOrError": { "__typename": "RepositoryConnection", "nodes": [ { "name": repo_name, "location": {"name": repo_loc_name}, "pipelines": [{"name": job_name}], }, { "name": other_repo_name, "location": {"name": repo_loc_name}, "pipelines": [{"name": job_name}], }, ], } } submit_execution_response = { "launchPipelineExecution": { "__typename": "LaunchRunSuccess", "run": {"runId": EXPECTED_RUN_ID}, } } mock_client.mock_gql_client.execute.side_effect = [ get_locations_and_names_response, submit_execution_response, ] return job_name @python_client_test_suite def test_no_location_or_repo_provided_duplicate_job_failure(mock_client: MockClient): job_name = no_location_or_repo_provided_duplicate_pipeline_mock_config(mock_client) with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution(job_name, run_config={}) assert exc_info.value.args[0].find(f"multiple jobs with the name {job_name}") != -1 def no_location_or_repo_provided_mock_config(mock_client): repo_loc_name, repo_name, job_name = "bar", "baz", "quux" get_locations_and_names_response = { "repositoriesOrError": { "__typename": "RepositoryConnection", "nodes": [ { "name": repo_name, "location": {"name": repo_loc_name}, "pipelines": [{"name": job_name}], } ], } } submit_execution_response = { "launchPipelineExecution": { "__typename": "LaunchRunSuccess", "run": {"runId": EXPECTED_RUN_ID}, } } mock_client.mock_gql_client.execute.side_effect = [ get_locations_and_names_response, submit_execution_response, ] @python_client_test_suite def test_no_location_or_repo_provided_no_job_failure(mock_client: MockClient): no_location_or_repo_provided_mock_config(mock_client) with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution("123", run_config={}) assert exc_info.value.args[0] == "JobNotFoundError" @python_client_test_suite def test_failure_with_invalid_step_error(mock_client: MockClient): error_type, invalid_step_key = "InvalidStepError", "1234" response = { "launchPipelineExecution": { "__typename": error_type, "invalidStepKey": invalid_step_key, } } mock_client.mock_gql_client.execute.return_value = response with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) exc_args = exc_info.value.args assert exc_args[0] == error_type assert exc_args[1] == invalid_step_key @python_client_test_suite def test_failure_with_invalid_output_error(mock_client: MockClient): error_type, step_key, invalid_output_name = "InvalidOutputError", "1234", "some output" response = { "launchPipelineExecution": { "__typename": error_type, "stepKey": step_key, "invalidOutputName": invalid_output_name, } } mock_client.mock_gql_client.execute.return_value = response with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) assert exc_info.value.args == (error_type,) assert exc_info.value.body == InvalidOutputErrorInfo( step_key=step_key, invalid_output_name=invalid_output_name ) @python_client_test_suite def test_failure_with_job_config_invalid(mock_client: MockClient): error_type = "RunConfigValidationInvalid" errors = [ { "__typename": "some_error", "message": "AWS warehouse got hit by a meteor", "path": [], "reason": "Network failure", } ] response = {"launchPipelineExecution": {"__typename": error_type, "errors": errors}} mock_client.mock_gql_client.execute.return_value = response with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) exc_args = exc_info.value.args assert exc_args[0] == error_type assert exc_args[1] == errors @python_client_test_suite def test_failure_with_python_error(mock_client: MockClient): error_type, message = "PythonError", "some catastrophic error" response = { "launchPipelineExecution": { "__typename": error_type, "message": message, } } mock_client.mock_gql_client.execute.return_value = response with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) exc_args = exc_info.value.args assert exc_args[0] == error_type assert exc_args[1] == message @python_client_test_suite def test_failure_with_unauthorized_error(mock_client: MockClient): error_type, message = "UnauthorizedError", "permissions failure" response = { "launchPipelineExecution": { "__typename": error_type, "message": message, } } mock_client.mock_gql_client.execute.return_value = response with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) exc_args = exc_info.value.args assert exc_args[0] == error_type assert exc_args[1] == message def failure_with_job_run_conflict_mock_config(mock_client: MockClient): error_type, message = "RunConflict", "some conflict" response = { "launchPipelineExecution": { "__typename": error_type, "message": message, } } mock_client.mock_gql_client.execute.return_value = response @python_client_test_suite def test_failure_with_job_run_conflict(mock_client: MockClient): failure_with_job_run_conflict_mock_config(mock_client) with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) exc_args = exc_info.value.args assert exc_args[0] == "RunConflict" assert exc_args[1] == "some conflict" @python_client_test_suite def test_failure_with_query_error(mock_client: MockClient): mock_client.mock_gql_client.side_effect = Exception("foo") with pytest.raises(DagsterGraphQLClientError) as exc_info: mock_client.python_client.submit_job_execution( "bar", repository_location_name="baz", repository_name="quux", run_config={}, ) assert exc_info.value.args[0].endswith("failed GraphQL validation")
AnOpConfig
python
doocs__leetcode
solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/Solution.py
{ "start": 0, "end": 305 }
class ____: def missingInteger(self, nums: List[int]) -> int: s, j = nums[0], 1 while j < len(nums) and nums[j] == nums[j - 1] + 1: s += nums[j] j += 1 vis = set(nums) for x in count(s): if x not in vis: return x
Solution
python
getsentry__sentry-python
tests/integrations/langgraph/test_langgraph.py
{ "start": 1699, "end": 1804 }
class ____: def __init__(self): self.nodes = {"tools": MockToolsNode()}
MockGraphRepresentation
python
numba__numba
numba/cuda/tests/cudadrv/test_is_fp16.py
{ "start": 105, "end": 394 }
class ____(CUDATestCase): def test_is_fp16_supported(self): self.assertTrue(cuda.is_float16_supported()) @skip_on_cudasim @skip_unless_cc_53 def test_device_supports_float16(self): self.assertTrue(cuda.get_current_device().supports_float16)
TestIsFP16Supported
python
rapidsai__cudf
python/cudf/cudf/core/resample.py
{ "start": 3470, "end": 15882 }
class ____(_Grouping): bin_labels: Index def __init__(self, obj, by=None, level=None): self._freq = getattr(by, "freq", None) super().__init__(obj, by, level) def copy(self, deep=True): out = super().copy(deep=deep) result = _ResampleGrouping.__new__(_ResampleGrouping) result.names = out.names result._named_columns = out._named_columns result._key_columns = out._key_columns result.bin_labels = self.bin_labels.copy(deep=deep) result._freq = self._freq return result @property def keys(self): index = super().keys if self._freq is not None and isinstance(index, cudf.DatetimeIndex): return cudf.DatetimeIndex._from_column( index._column, name=index.name, freq=self._freq ) return index def serialize(self): header, frames = super().serialize() labels_head, labels_frames = self.bin_labels.serialize() header["__bin_labels"] = labels_head header["__bin_labels_count"] = len(labels_frames) header["_freq"] = self._freq frames.extend(labels_frames) return header, frames @classmethod def deserialize(cls, header, frames): names = header["names"] _named_columns = header["_named_columns"] key_columns = deserialize_columns( header["columns"], frames[: -header["__bin_labels_count"]] ) out = _ResampleGrouping.__new__(_ResampleGrouping) out.names = names out._named_columns = _named_columns out._key_columns = key_columns out.bin_labels = cudf.Index.deserialize( header["__bin_labels"], frames[-header["__bin_labels_count"] :] ) out._freq = header["_freq"] return out def _handle_frequency_grouper(self, by): # if `by` is a time frequency grouper, we bin the key column # using bin intervals specified by `by.freq`, then use *that* # as the groupby key freq = by.freq label = by.label closed = by.closed if isinstance(freq, (cudf.DateOffset, pd.DateOffset)): raise NotImplementedError( "Resampling by DateOffset objects is not yet supported." ) if not isinstance(freq, str): raise TypeError( f"Unsupported type for freq: {type(freq).__name__}" ) # convert freq to a pd.DateOffset: offset = pd.tseries.frequencies.to_offset(freq) if offset.freqstr == "M" or offset.freqstr.startswith("W-"): label = "right" if label is None else label closed = "right" if closed is None else closed else: label = "left" if label is None else label closed = "left" if closed is None else closed # determine the key column if by.key is None and by.level is None: # then assume that the key is the index of `self._obj`: self._handle_index(self._obj.index) elif by.key: self._handle_label(by.key) elif by.level: self._handle_level(by.level) if not len(self._key_columns) == 1: raise ValueError("Must resample on exactly one column") key_column = self._key_columns[0] if not key_column.dtype.kind == "M": raise TypeError( f"Can only resample on a DatetimeIndex or datetime column, " f"got column of type {key_column.dtype}" ) # get the start and end values that will be used to generate # the bin labels min_date = key_column._reduce("min") max_date = key_column._reduce("max") start, end = _get_timestamp_range_edges( pd.Timestamp(min_date), pd.Timestamp(max_date), offset, closed=closed, ) # in some cases, an extra time stamp is required in order to # bin all the values. It's OK if we generate more labels than # we need, as we remove any unused labels below end += offset # generate the labels for binning the key column: bin_labels = cudf.date_range( start=start, end=end, freq=freq, ) # We want the (resampled) column of timestamps in the result # to have a resolution closest to the resampling # frequency. For example, if resampling from '1T' to '1s', we # want the resulting timestamp column to by of dtype # 'datetime64[s]'. libcudf requires the bin labels and key # column to have the same dtype, so we compute a `result_type` # and cast them both to that type. if offset.rule_code.lower() in {"d", "h"}: # unsupported resolution (we don't support resolutions >s) result_type = np.dtype("datetime64[s]") else: try: result_type = np.dtype(f"datetime64[{offset.rule_code}]") # TODO: Ideally, we can avoid one cast by having `date_range` # generate timestamps of a given dtype. Currently, it can # only generate timestamps with 'ns' precision except TypeError: # unsupported resolution (we don't support resolutions >s) # fall back to using datetime64[s] result_type = np.dtype("datetime64[s]") cast_key_column = key_column.astype(result_type) cast_bin_labels = bin_labels.astype(result_type) # bin the key column: bin_numbers = cast_key_column.label_bins( left_edge=cast_bin_labels[:-1]._column, left_inclusive=closed == "left", right_edge=cast_bin_labels[1:]._column, right_inclusive=closed == "right", ) if label == "right": cast_bin_labels = cast_bin_labels[1:] else: cast_bin_labels = cast_bin_labels[:-1] # if we have more labels than bins, remove the extras labels: nbins = bin_numbers.max() + 1 if len(cast_bin_labels) > nbins: cast_bin_labels = cast_bin_labels[:nbins] cast_bin_labels.name = self.names[0] if isinstance(cast_bin_labels, cudf.DatetimeIndex): cast_bin_labels = cudf.DatetimeIndex._from_data( data=cast_bin_labels._data, name=cast_bin_labels.name, freq=freq, ) self.bin_labels = cast_bin_labels # replace self._key_columns with the binned key column: self._key_columns = [ cast_bin_labels._gather( bin_numbers, check_bounds=False )._column.astype(result_type) ] # NOTE: this function is vendored from Pandas def _get_timestamp_range_edges( first, last, freq, closed="left", origin="start_day", offset=None ): """ Adjust the `first` Timestamp to the preceding Timestamp that resides on the provided offset. Adjust the `last` Timestamp to the following Timestamp that resides on the provided offset. Input Timestamps that already reside on the offset will be adjusted depending on the type of offset and the `closed` parameter. Parameters ---------- first : pd.Timestamp The beginning Timestamp of the range to be adjusted. last : pd.Timestamp The ending Timestamp of the range to be adjusted. freq : pd.DateOffset The dateoffset to which the Timestamps will be adjusted. closed : {'right', 'left'}, default None Which side of bin interval is closed. origin : {'epoch', 'start', 'start_day'} or Timestamp, default 'start_day' The timestamp on which to adjust the grouping. The timezone of origin must match the timezone of the index. If a timestamp is not used, these values are also supported: - 'epoch': `origin` is 1970-01-01 - 'start': `origin` is the first value of the timeseries - 'start_day': `origin` is the first day at midnight of the timeseries offset : pd.Timedelta, default is None An offset timedelta added to the origin. Returns ------- A tuple of length 2, containing the adjusted pd.Timestamp objects. """ from pandas.tseries.offsets import Day, Tick if isinstance(freq, Tick): index_tz = first.tz if isinstance(origin, pd.Timestamp) and (origin.tz is None) != ( index_tz is None ): raise ValueError( "The origin must have the same timezone as the index." ) elif origin == "epoch": # set the epoch based on the timezone to have similar bins results # when resampling on the same kind of indexes on different # timezones origin = pd.Timestamp("1970-01-01", tz=index_tz) if isinstance(freq, Day): # _adjust_dates_anchored assumes 'D' means 24H, but first/last # might contain a DST transition (23H, 24H, or 25H). # So "pretend" the dates are naive when adjusting the endpoints first = first.tz_localize(None) last = last.tz_localize(None) if isinstance(origin, pd.Timestamp): origin = origin.tz_localize(None) first, last = _adjust_dates_anchored( first, last, freq, closed=closed, origin=origin, offset=offset ) if isinstance(freq, Day): first = first.tz_localize(index_tz) last = last.tz_localize(index_tz) else: if first is not pd.NaT: first = first.normalize() if last is not pd.NaT: last = last.normalize() if closed == "left": first = pd.Timestamp(freq.rollback(first)) else: first = pd.Timestamp(first - freq) last = pd.Timestamp(last + freq) return first, last # NOTE: this function is vendored from Pandas def _adjust_dates_anchored( first, last, freq, closed="right", origin="start_day", offset=None ): # First and last offsets should be calculated from the start day to fix an # error cause by resampling across multiple days when a one day period is # not a multiple of the frequency. See GH 8683 # To handle frequencies that are not multiple or divisible by a day we let # the possibility to define a fixed origin timestamp. See GH 31809 if first is pd.NaT and last is pd.NaT: return first, last origin_nanos = 0 # origin == "epoch" if origin == "start_day": origin_nanos = first.normalize().value elif origin == "start": origin_nanos = first.value elif isinstance(origin, pd.Timestamp): origin_nanos = origin.value origin_nanos += offset.value if offset else 0 # GH 10117 & GH 19375. If first and last contain timezone information, # Perform the calculation in UTC in order to avoid localizing on an # Ambiguous or Nonexistent time. first_tzinfo = first.tzinfo last_tzinfo = last.tzinfo if first_tzinfo is not None: first = first.tz_convert("UTC") if last_tzinfo is not None: last = last.tz_convert("UTC") foffset = (first.value - origin_nanos) % freq.nanos loffset = (last.value - origin_nanos) % freq.nanos if closed == "right": if foffset > 0: # roll back fresult = first.value - foffset else: fresult = first.value - freq.nanos if loffset > 0: # roll forward lresult = last.value + (freq.nanos - loffset) else: # already the end of the road lresult = last.value else: # closed == 'left' if foffset > 0: fresult = first.value - foffset else: # start of the road fresult = first.value if loffset > 0: # roll forward lresult = last.value + (freq.nanos - loffset) else: lresult = last.value + freq.nanos fresult = pd.Timestamp(fresult) lresult = pd.Timestamp(lresult) if first_tzinfo is not None: fresult = fresult.tz_localize("UTC").tz_convert(first_tzinfo) if last_tzinfo is not None: lresult = lresult.tz_localize("UTC").tz_convert(last_tzinfo) return fresult, lresult
_ResampleGrouping
python
sympy__sympy
sympy/stats/drv_types.py
{ "start": 3533, "end": 5031 }
class ____(SingleDiscreteDistribution): _argnames = ('a',) set = S.Naturals @staticmethod def check(a): _value_check((0 < a, a < 1), "a must be between 0 and 1") def pdf(self, k): a = self.a return (a**2 * k * (1 - a)**(k - 1)) def _characteristic_function(self, t): a = self.a return a**2*exp(I*t)/((1 + (a - 1)*exp(I*t))**2) def _moment_generating_function(self, t): a = self.a return a**2*exp(t)/((1 + (a - 1)*exp(t))**2) def FlorySchulz(name, a): r""" Create a discrete random variable with a FlorySchulz distribution. The density of the FlorySchulz distribution is given by .. math:: f(k) := (a^2) k (1 - a)^{k-1} Parameters ========== a : A real number between 0 and 1 Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, E, variance, FlorySchulz >>> from sympy import Symbol, S >>> a = S.One / 5 >>> z = Symbol("z") >>> X = FlorySchulz("x", a) >>> density(X)(z) (4/5)**(z - 1)*z/25 >>> E(X) 9 >>> variance(X) 40 References ========== https://en.wikipedia.org/wiki/Flory%E2%80%93Schulz_distribution """ return rv(name, FlorySchulzDistribution, a) #------------------------------------------------------------------------------- # Geometric distribution ------------------------------------------------------------
FlorySchulzDistribution
python
pyinstaller__pyinstaller
PyInstaller/building/makespec.py
{ "start": 5353, "end": 5770 }
class ____(_RemovedFlagAction): def __call__(self, *args, **kwargs): from PyInstaller.exceptions import RemovedWinSideBySideSupportError raise RemovedWinSideBySideSupportError("Please remove your --win-no-prefer-redirects argument.") # An object used in place of a "path string", which knows how to repr() itself using variable names instead of # hard-coded paths.
_RemovedWinNoPreferRedirectsAction
python
boto__boto3
tests/integration/test_session.py
{ "start": 637, "end": 1911 }
class ____(unittest.TestCase): def setUp(self): self.botocore_session = botocore.session.get_session() self.session = boto3.session.Session( region_name='us-west-2', botocore_session=self.botocore_session ) self.actual_user_agent = None self.botocore_session.register( 'request-created', self.record_user_agent ) def record_user_agent(self, request, **kwargs): self.actual_user_agent = request.headers['User-Agent'] def test_client_user_agent(self): client = self.session.client('s3') client.list_buckets() self.assertIn('Boto3', self.actual_user_agent) self.assertIn('Botocore', self.actual_user_agent) self.assertIn('Python', self.actual_user_agent) # We should *not* have any mention of resource # when using clients directly. self.assertNotIn('Resource', self.actual_user_agent) def test_resource_user_agent_has_customization(self): resource = self.session.resource('s3') list(resource.buckets.all()) # We should have customized the user agent for # resource calls with "Resource". self.assertTrue(self.actual_user_agent.endswith(' Resource'))
TestUserAgentCustomizations
python
sqlalchemy__sqlalchemy
test/orm/test_syntax_extensions.py
{ "start": 1054, "end": 1321 }
class ____(SyntaxExtension, ClauseElement): _traverse_internals = [] def apply_to_select(self, select_stmt): select_stmt.apply_syntax_extension_point( lambda existing: [*existing, self], "pre_columns", )
PreColumnsClause
python
python__mypy
mypy/visitor.py
{ "start": 401, "end": 5136 }
class ____(Generic[T]): @abstractmethod def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T: pass @abstractmethod def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T: pass @abstractmethod def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T: pass @abstractmethod def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T: pass @abstractmethod def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T: pass @abstractmethod def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T: pass @abstractmethod def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T: pass @abstractmethod def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T: pass @abstractmethod def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T: pass @abstractmethod def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T: pass @abstractmethod def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T: pass @abstractmethod def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T: pass @abstractmethod def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T: pass @abstractmethod def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T: pass @abstractmethod def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T: pass @abstractmethod def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T: pass @abstractmethod def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T: pass @abstractmethod def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T: pass @abstractmethod def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T: pass @abstractmethod def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T: pass @abstractmethod def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T: pass @abstractmethod def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T: pass @abstractmethod def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T: pass @abstractmethod def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T: pass @abstractmethod def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T: pass @abstractmethod def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T: pass @abstractmethod def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T: pass @abstractmethod def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T: pass @abstractmethod def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T: pass @abstractmethod def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T: pass @abstractmethod def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T: pass @abstractmethod def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T: pass @abstractmethod def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T: pass @abstractmethod def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T: pass @abstractmethod def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T: pass @abstractmethod def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T: pass @abstractmethod def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T: pass @abstractmethod def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T: pass @abstractmethod def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T: pass @abstractmethod def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T: pass @abstractmethod def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T: pass @abstractmethod def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T: pass @abstractmethod def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T: pass @abstractmethod def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T: pass @abstractmethod def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T: pass @trait @mypyc_attr(allow_interpreted_subclasses=True)
ExpressionVisitor
python
huggingface__transformers
src/transformers/models/modernbert_decoder/modeling_modernbert_decoder.py
{ "start": 15090, "end": 16949 }
class ____(GradientCheckpointingLayer): def __init__(self, config: ModernBertDecoderConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.attention_type = config.layer_types[layer_idx] self.attn_norm = ( nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias) if layer_idx != 0 else nn.Identity() ) self.attn = ModernBertDecoderAttention(config=config, layer_idx=layer_idx) self.mlp_norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias) self.mlp = ModernBertDecoderMLP(config) def forward( self, hidden_states: torch.Tensor, position_embeddings: torch.Tensor = None, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states hidden_states = self.attn_norm(hidden_states) # Self Attention attn_outputs = self.attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, past_key_values=past_key_values, cache_position=cache_position, **kwargs, ) hidden_states = attn_outputs[0] # Add residual connection hidden_states = residual + hidden_states # MLP residual = hidden_states hidden_states = self.mlp_norm(hidden_states) mlp_output = self.mlp(hidden_states) hidden_states = residual + mlp_output return hidden_states
ModernBertDecoderLayer
python
pytorch__pytorch
tools/code_coverage/package/tool/parser/gcov_coverage_parser.py
{ "start": 106, "end": 1643 }
class ____: """ Accepts a parsed json produced by gcov --json-format -- typically, representing a single C++ test and produces a list of CoverageRecord(s). """ def __init__(self, llvm_coverage: dict[str, Any]) -> None: self._llvm_coverage = llvm_coverage @staticmethod def _skip_coverage(path: str) -> bool: """ Returns True if file path should not be processed. This is repo-specific and only makes sense for the current state of ovrsource. """ return "third-party" in path def parse(self) -> list[CoverageRecord]: # The JSON format is described in the gcov source code # https://gcc.gnu.org/onlinedocs/gcc/Invoking-Gcov.html records: list[CoverageRecord] = [] for file_info in self._llvm_coverage["files"]: filepath = file_info["file"] if self._skip_coverage(filepath): continue # parse json file covered_lines: set[int] = set() uncovered_lines: set[int] = set() for line in file_info["lines"]: line_number = line["line_number"] count = line["count"] if count == 0: uncovered_lines.update([line_number]) else: covered_lines.update([line_number]) records.append( CoverageRecord(filepath, sorted(covered_lines), sorted(uncovered_lines)) ) return records
GcovCoverageParser
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/endpoint_service.py
{ "start": 20263, "end": 24056 }
class ____(GoogleCloudBaseOperator): """ Undeploys a Model from an Endpoint, removing a DeployedModel from it, and freeing all used resources. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param endpoint_id: Required. The ID of the Endpoint resource from which to undeploy a Model. :param deployed_model_id: Required. The ID of the DeployedModel to be undeployed from the Endpoint. :param traffic_split: If this field is provided, then the Endpoint's [traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split] will be overwritten with it. If last DeployedModel is being undeployed from the Endpoint, the [Endpoint.traffic_split] will always end up empty when this call returns. A DeployedModel will be successfully undeployed only if it doesn't have any traffic assigned to it when this method executes, or if this field unassigns any traffic to it. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields = ("region", "endpoint_id", "deployed_model_id", "project_id", "impersonation_chain") def __init__( self, *, region: str, project_id: str, endpoint_id: str, deployed_model_id: str, traffic_split: Sequence | dict | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.region = region self.project_id = project_id self.endpoint_id = endpoint_id self.deployed_model_id = deployed_model_id self.traffic_split = traffic_split self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = EndpointServiceHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) self.log.info("Removing a DeployedModel %s", self.deployed_model_id) operation = hook.undeploy_model( project_id=self.project_id, region=self.region, endpoint=self.endpoint_id, deployed_model_id=self.deployed_model_id, traffic_split=self.traffic_split, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) hook.wait_for_operation(timeout=self.timeout, operation=operation) self.log.info("DeployedModel was removed successfully")
UndeployModelOperator
python
tensorflow__tensorflow
tensorflow/lite/python/lite_test.py
{ "start": 115485, "end": 119026 }
class ____(TestModels, parameterized.TestCase): def testConstantFolding(self): ops.disable_eager_execution() # Constant folding handles the tf.broadcast_to operation which was not # supported by the TFLite at the time this test was added. with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[3, 3], dtype=dtypes.float32) y_const = constant_op.constant([1., 2., 3.]) y_broadcast = array_ops.broadcast_to(y_const, [3, 3]) out_tensor = math_ops.matmul(in_tensor, y_broadcast, name='output') sess = session.Session() # Convert model. converter = lite.TFLiteConverter.from_session(sess, [in_tensor], [out_tensor]) tflite_model = converter.convert() # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEqual('Placeholder', input_details[0]['name']) self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([3, 3], input_details[0]['shape']) output_details = interpreter.get_output_details() self.assertLen(output_details, 1) self.assertEqual('output', output_details[0]['name']) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([3, 3], output_details[0]['shape']) def testInputNodeIsNotFolded(self): ops.disable_eager_execution() # Constant folding handles the tf.broadcast_to operation which was not # supported by the TFLite at the time this test was added. with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[3], dtype=dtypes.float32) y_const = constant_op.constant([1., 2., 3.]) y_add = y_const + y_const out_tensor = in_tensor * y_add sess = session.Session() # Convert model. converter = lite.TFLiteConverter.from_session(sess, [in_tensor, y_const], [out_tensor]) tflite_model = converter.convert() # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 2) self.assertEqual('Placeholder', input_details[0]['name']) self.assertEqual('Const', input_details[1]['name']) def testGrapplerConstFolding(self): # Constant folding converts the following add operation to tf.broadcast_to # operation which was not supported by the TFLite at the time this test was # added. @def_function.function def plus_placeholder(x, placeholder): return x + placeholder with ops.Graph().as_default(): in_tensor = array_ops.placeholder(shape=[2, 2], dtype=dtypes.float32) out_tensor = plus_placeholder( array_ops.zeros([2, 2, 2]), array_ops.reshape(in_tensor, shape=[2, 2])) sess = session.Session() # Convert model. converter = lite.TFLiteConverter.from_session(sess, [in_tensor], [out_tensor]) tflite_model = converter.convert() # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEqual('Placeholder', input_details[0]['name'])
GrapplerTest
python
doocs__leetcode
solution/3700-3799/3736.Minimum Moves to Equal Array Elements III/Solution.py
{ "start": 0, "end": 157 }
class ____: def minMoves(self, nums: List[int]) -> int: n = len(nums) mx = max(nums) s = sum(nums) return mx * n - s
Solution
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 2644, "end": 4142 }
class ____(Benchmark): param_names = ['sparse_type', 'name', 'format'] params = [ ['spmatrix', 'sparray'], ['Identity', 'Poisson5pt', 'Block2x2', 'Block3x3'], ['dia', 'csr', 'csc', 'dok', 'lil', 'coo', 'bsr'], ] def setup(self, sparse_type, name, format): if name == 'Identity': if format in ('lil', 'dok'): raise NotImplementedError() if sparse_type == "sparray": self.A = sparse.eye_array(10000, format=format) else: self.A = sparse.eye(10000, format=format) elif name == 'Poisson5pt': self.A = poisson2d(300, format=format, sparse_type=sparse_type) elif name == 'Block2x2': if format not in ('csr', 'bsr'): raise NotImplementedError() b = (2, 2) self.A = sparse.kron(poisson2d(150, sparse_type=sparse_type), np.ones(b)).tobsr(blocksize=b).asformat(format) elif name == 'Block3x3': if format not in ('csr', 'bsr'): raise NotImplementedError() b = (3, 3) self.A = sparse.kron(poisson2d(100, sparse_type=sparse_type), np.ones(b)).tobsr(blocksize=b).asformat(format) else: raise NotImplementedError() self.x = np.ones(self.A.shape[1], dtype=float) def time_matvec(self, sparse_type, name, format): self.A @ self.x
Matvec
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/softmax_op_test.py
{ "start": 1158, "end": 11252 }
class ____(test.TestCase): def _npSoftmax(self, features, dim=-1, log=False): if dim == -1: dim = len(features.shape) - 1 one_only_on_dim = list(features.shape) one_only_on_dim[dim] = 1 is_fp16 = features.dtype == np.float16 if is_fp16: # Do the compute in fp32 and cast the input back to fp32. features = features.astype(np.float32) e = np.exp(features - np.reshape( np.amax( features, axis=dim), one_only_on_dim)) softmax = e / np.reshape(np.sum(e, axis=dim), one_only_on_dim) if log: res = np.log(softmax) else: res = softmax if is_fp16: res = res.astype(np.float16) return res def _testSoftmax(self, np_features, dim=-1, log=False, dtype=None, use_gpu=False): # A previous version of the code checked the op name rather than the op type # to distinguish between log and non-log. Use an arbitrary name to catch # this bug in future. name = "arbitrary" np_softmax = self._npSoftmax(np_features, dim=dim, log=log) with self.cached_session(use_gpu=use_gpu): if dtype is not None: np_features = math_ops.cast(np_features, dtype=dtype) if log: tf_softmax = nn_ops.log_softmax(np_features, axis=dim, name=name) else: tf_softmax = nn_ops.softmax(np_features, axis=dim, name=name) out = self.evaluate(tf_softmax) self.assertAllCloseAccordingToType(np_softmax, out) self.assertShapeEqual(np_softmax, tf_softmax) if not log and dtype is None: # Bonus check: the softmaxes should add to one in dimension dim. sum_along_dim = np.sum(out, axis=dim) self.assertAllCloseAccordingToType( np.ones(sum_along_dim.shape), sum_along_dim) def _testAll(self, features, dtype=None): self._testSoftmax(features, dtype=dtype, use_gpu=True) self._testSoftmax(features, dtype=dtype, log=True, use_gpu=True) self._testOverflow(use_gpu=True) def testNpSoftmax(self): features = [[1., 1., 1., 1.], [1., 2., 3., 4.]] # Batch 0: All exps are 1. The expected result is # Softmaxes = [0.25, 0.25, 0.25, 0.25] # LogSoftmaxes = [-1.386294, -1.386294, -1.386294, -1.386294] # # Batch 1: # exps = [1., 2.718, 7.389, 20.085] # sum = 31.192 # Softmaxes = exps / sum = [0.0320586, 0.08714432, 0.23688282, 0.64391426] # LogSoftmaxes = [-3.44019 , -2.44019 , -1.44019 , -0.44019] np_sm = self._npSoftmax(np.array(features)) self.assertAllClose( np.array([[0.25, 0.25, 0.25, 0.25], [0.0320586, 0.08714432, 0.23688282, 0.64391426]]), np_sm, rtol=1.e-5, atol=1.e-5) np_lsm = self._npSoftmax(np.array(features), log=True) self.assertAllClose( np.array([[-1.386294, -1.386294, -1.386294, -1.386294], [-3.4401897, -2.4401897, -1.4401897, -0.4401897]]), np_lsm, rtol=1.e-5, atol=1.e-5) def _testOverflow(self, use_gpu=False): if use_gpu: type = np.float32 # pylint: disable=redefined-builtin else: type = np.float64 # pylint: disable=redefined-builtin max = np.finfo(type).max # pylint: disable=redefined-builtin features = np.array([[1., 1., 1., 1.], [max, 1., 2., 3.]]).astype(type) with self.cached_session(use_gpu=use_gpu): tf_log_softmax = nn_ops.log_softmax(features) out = self.evaluate(tf_log_softmax) self.assertAllClose( np.array([[-1.386294, -1.386294, -1.386294, -1.386294], [0, -max, -max, -max]]), out, rtol=1.e-5, atol=1.e-5) def testFloat(self): self._testAll( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32)) @unittest.skipUnless(test.is_built_with_gpu_support(), "Test only applicable when running on GPUs") def testFloatGPU(self): if test.is_gpu_available(cuda_only=True): rows = [2**x + np.random.randint(0, 16) for x in range(1, 4)] cols = [2**x + np.random.randint(0, 16) for x in range(1, 4)] for row, col in zip(rows, cols): logging.info("Testing softmax float dtype in shape [%d, %d]", row, col) data = np.random.rand(row, col) self._testAll(data.astype(np.float32)) def testHalf(self): self._testAll( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16)) @unittest.skipUnless(test.is_built_with_gpu_support(), "Test only applicable when running on GPUs") def testHalfGPU(self): if test.is_gpu_available(cuda_only=True): rows = [2**x + np.random.randint(0, 16) for x in range(1, 4)] cols = [2**x + np.random.randint(0, 16) for x in range(1, 4)] for row, col in zip(rows, cols): logging.info("Testing softmax half dtype in shape [%d, %d]", row, col) data = np.random.rand(row, col) self._testAll(data.astype(np.float16)) def testDouble(self): self._testSoftmax( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64)) self._testOverflow() @unittest.skipUnless(test.is_built_with_gpu_support(), "Test only applicable when running on GPUs") def testDoubleGPU(self): if test.is_gpu_available(cuda_only=True): rows = [2**x + np.random.randint(0, 16) for x in range(1, 4)] cols = [2**x + np.random.randint(0, 16) for x in range(1, 4)] for row, col in zip(rows, cols): logging.info("Testing softmax float dtype in shape [%d, %d]", row, col) data = np.random.rand(row, col) self._testAll(data.astype(np.float64)) def testBfloat16(self): self._testAll( np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32), dtype=dtypes.bfloat16) @unittest.skipUnless(test.is_built_with_gpu_support(), "Test only applicable when running on GPUs") def testBfloat16GPU(self): if test.is_gpu_available(cuda_only=True): rows = [2**x + np.random.randint(0, 16) for x in range(1, 4)] cols = [2**x + np.random.randint(0, 16) for x in range(1, 4)] for row, col in zip(rows, cols): logging.info("Testing softmax bfloat16 dtype in shape [%d, %d]", row, col) data = np.random.rand(row, col) self._testAll(data.astype(dtypes.bfloat16.as_numpy_dtype)) def test1DTensorAsInput(self): self._testSoftmax( np.array([3., 2., 3., 9.]).astype(np.float64), use_gpu=False) self._testOverflow(use_gpu=False) def test1DTensorAsInputNoReshape(self): self._testSoftmax( np.array([3., 2., 3., 9.]).astype(np.float64), use_gpu=False) self._testOverflow(use_gpu=False) def test3DTensorAsInput(self): self._testSoftmax( np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32), use_gpu=False) self._testOverflow(use_gpu=False) def test3DTensorAsInputNoReshape(self): self._testSoftmax( np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32), use_gpu=False) self._testOverflow(use_gpu=False) def testAlongFirstDimension(self): self._testSoftmax( np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32), dim=0, use_gpu=False) self._testOverflow(use_gpu=False) def testAlongSecondDimension(self): self._testSoftmax( np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32), dim=1, use_gpu=False) self._testOverflow(use_gpu=False) def testAlongNegativeDimension(self): self._testSoftmax( np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32), dim=-2, use_gpu=False) self._testOverflow(use_gpu=False) def testShapeInference(self): op = nn_ops.softmax([[[1., 1., 1., 1.], [1., 2., 3., 4.]], [[2., 3., 4., 5.], [6., 7., 8., 9.]], [[5., 4., 3., 2.], [1., 2., 3., 4.]]]) self.assertEqual([3, 2, 4], op.get_shape()) def testEmptyInput(self): x = array_ops.ones(shape=[0, 3], dtype=dtypes.float32) y = np.zeros(shape=[0, 3], dtype=np.float32) self.assertEqual(0, self.evaluate(array_ops.size(x))) self.assertAllEqual(y, self.evaluate(nn_ops.softmax(x, axis=0))) def testDimTooLarge(self): with self.cached_session(): # Use placeholder to make sure we get runtime error instead of shape # inference error. dim = array_ops.placeholder_with_default(100, shape=[]) with self.assertRaises(errors_impl.InvalidArgumentError): nn_ops.softmax([1., 2., 3., 4.], axis=dim).eval() def testInvalidAxis(self): # Test case for GitHub issue 22793. with self.cached_session(): ones = array_ops.ones(shape=[2, 3]) with self.assertRaises(errors_impl.InvalidArgumentError): nn_ops.softmax(ones, axis=2).eval() def testLargeDims(self): # Make sure that we properly handle large inputs. See # https://github.com/tensorflow/tensorflow/issues/4425 for details for dims in [129, 256]: ones = np.random.rand(dims, dims).astype(np.float32) np_softmax = self._npSoftmax(ones) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(ones) y = nn_ops.softmax(x) tf_softmax = self.evaluate(y) self.assertAllClose(tf_softmax, np_softmax) if __name__ == "__main__": test.main()
SoftmaxTest
python
getsentry__sentry
tests/sentry/plugins/bases/test_issue2.py
{ "start": 603, "end": 738 }
class ____(IssueTrackingPlugin2): slug = "test-plugin-without-fields" conf_key = slug issue_fields = None
PluginWithoutFields
python
redis__redis-py
redis/commands/core.py
{ "start": 213557, "end": 216306 }
class ____: """ An executable Lua script object returned by ``register_script`` """ def __init__(self, registered_client: "redis.client.Redis", script: ScriptTextT): self.registered_client = registered_client self.script = script # Precalculate and store the SHA1 hex digest of the script. if isinstance(script, str): # We need the encoding from the client in order to generate an # accurate byte representation of the script encoder = self.get_encoder() script = encoder.encode(script) self.sha = hashlib.sha1(script).hexdigest() def __call__( self, keys: Union[Sequence[KeyT], None] = None, args: Union[Iterable[EncodableT], None] = None, client: Union["redis.client.Redis", None] = None, ): """Execute the script, passing any required ``args``""" keys = keys or [] args = args or [] if client is None: client = self.registered_client args = tuple(keys) + tuple(args) # make sure the Redis server knows about the script from redis.client import Pipeline if isinstance(client, Pipeline): # Make sure the pipeline can register the script before executing. client.scripts.add(self) try: return client.evalsha(self.sha, len(keys), *args) except NoScriptError: # Maybe the client is pointed to a different server than the client # that created this instance? # Overwrite the sha just in case there was a discrepancy. self.sha = client.script_load(self.script) return client.evalsha(self.sha, len(keys), *args) def get_encoder(self): """Get the encoder to encode string scripts into bytes.""" try: return self.registered_client.get_encoder() except AttributeError: # DEPRECATED # In version <=4.1.2, this was the code we used to get the encoder. # However, after 4.1.2 we added support for scripting in clustered # redis. ClusteredRedis doesn't have a `.connection_pool` attribute # so we changed the Script class to use # `self.registered_client.get_encoder` (see above). # However, that is technically a breaking change, as consumers who # use Scripts directly might inject a `registered_client` that # doesn't have a `.get_encoder` field. This try/except prevents us # from breaking backward-compatibility. Ideally, it would be # removed in the next major release. return self.registered_client.connection_pool.get_encoder()
Script
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-data-science/llama_index/llms/oci_data_science/client.py
{ "start": 6188, "end": 12081 }
class ____(ABC): """ Base class for invoking models via HTTP requests with retry logic. Attributes: endpoint (str): The URL endpoint to send the request. auth (Any): The authentication signer for the requests. retries (int): The number of retry attempts for the request. backoff_factor (float): The factor to determine the delay between retries. timeout (Union[float, Tuple[float, float]]): The timeout setting for the HTTP request. kwargs (Dict): Additional keyword arguments. """ def __init__( self, endpoint: str, auth: Optional[Any] = None, retries: Optional[int] = DEFAULT_RETRIES, backoff_factor: Optional[float] = DEFAULT_BACKOFF_FACTOR, timeout: Optional[Union[float, Tuple[float, float]]] = None, **kwargs: Any, ) -> None: """ Initialize the BaseClient. Args: endpoint (str): The URL endpoint to send the request. auth (Optional[Any]): The authentication signer for the requests. retries (Optional[int]): The number of retry attempts for the request. backoff_factor (Optional[float]): The factor to determine the delay between retries. timeout (Optional[Union[float, Tuple[float, float]]]): The timeout setting for the HTTP request. **kwargs: Additional keyword arguments. """ self.endpoint = endpoint self.retries = retries or DEFAULT_RETRIES self.backoff_factor = backoff_factor or DEFAULT_BACKOFF_FACTOR self.timeout = timeout or TIMEOUT self.kwargs = kwargs # Use default signer from ADS if `auth` not provided if not auth: try: from ads.common import auth as authutil auth = auth or authutil.default_signer() except ImportError as ex: raise ImportError( "The authentication signer for the requests was not provided. " "Use `auth` attribute to provide the signer. " "The authentication methods supported for LlamaIndex are equivalent to those " "used with other OCI services and follow the standard SDK authentication methods, " "specifically API Key, session token, instance principal, and resource principal. " "For more details, refer to the documentation: " "`https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html`. " "Alternatively you can use the `oracle-ads` package. " "Please install it with `pip install oracle-ads` and follow the example provided here: " "`https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html#authentication`." ) from ex # Validate auth object if not callable(auth.get("signer")): raise ValueError("Auth object must have a 'signer' callable attribute.") self.auth = OCIAuth(auth["signer"]) logger.debug( f"Initialized {self.__class__.__name__} with endpoint={self.endpoint}, " f"retries={self.retries}, backoff_factor={self.backoff_factor}, timeout={self.timeout}" ) def _parse_streaming_line( self, line: Union[bytes, str] ) -> Optional[Dict[str, Any]]: """ Parse a single line from the streaming response. Args: line (Union[bytes, str]): A line of the response in bytes or string format. Returns: Optional[Dict[str, Any]]: Parsed JSON object, or None if the line is to be ignored. Raises: Exception: Raised if the line contains an error object. json.JSONDecodeError: Raised if the line cannot be decoded as JSON. """ logger.debug(f"Parsing streaming line: {line}") if isinstance(line, bytes): line = line.decode(DEFAULT_ENCODING) line = line.strip() if line.lower().startswith("data:"): line = line[5:].lstrip() if not line or line.startswith("[DONE]"): logger.debug("Received end of stream signal or empty line.") return None try: json_line = json.loads(line) logger.debug(f"Parsed JSON line: {json_line}") except json.JSONDecodeError as e: logger.debug(f"Error decoding JSON from line: {line}") raise json.JSONDecodeError( f"Error decoding JSON from line: {e!s}", e.doc, e.pos ) from e if json_line.get("object") == "error": # Raise an error for error objects in the stream error_message = json_line.get("message", "Unknown error") logger.debug(f"Error in streaming response: {error_message}") raise Exception(f"Error in streaming response: {error_message}") return json_line def _prepare_headers( self, stream: bool, headers: Optional[Dict[str, str]] = None, ) -> Dict[str, str]: """ Construct and return the headers for a request. Args: stream (bool): Whether to use streaming for the response. headers (Optional[Dict[str, str]]): HTTP headers to include in the request. Returns: Dict[str, str]: The prepared headers. """ default_headers = { "Content-Type": "application/json", "Accept": "text/event-stream" if stream else "application/json", } if stream: default_headers["enable-streaming"] = "true" if headers: default_headers.update(headers) logger.debug(f"Prepared headers: {default_headers}") return default_headers
BaseClient
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/io_ops/parsing_ops_test.py
{ "start": 84505, "end": 88087 }
class ____(test.TestCase): def _decode_v1(self, words): with self.cached_session(): examples = np.array(words) example_tensor = constant_op.constant( examples, shape=examples.shape, dtype=dtypes.string) byte_tensor = parsing_ops.decode_raw_v1(example_tensor, dtypes.uint8) return self.evaluate(byte_tensor) def _decode_v2( self, words, fixed_length=None, dtype=dtypes.uint8, little_endian=True ): with self.cached_session(): examples = np.array(words) byte_tensor = parsing_ops.decode_raw( examples, dtype, little_endian=little_endian, fixed_length=fixed_length, ) return self.evaluate(byte_tensor) def _ordinalize(self, words, fixed_length=None): outputs = [] if fixed_length is None: fixed_length = len(words[0]) for word in words: output = [] for i in range(fixed_length): if i < len(word): output.append(ord(word[i])) else: output.append(0) outputs.append(output) return np.array(outputs) def testDecodeRawV1EqualLength(self): words = ["string1", "string2"] observed = self._decode_v1(words) expected = self._ordinalize(words) self.assertAllEqual(expected.shape, observed.shape) self.assertAllEqual(expected, observed) def testDecodeRawV2FallbackEqualLength(self): words = ["string1", "string2"] observed = self._decode_v2(words) expected = self._ordinalize(words) self.assertAllEqual(expected.shape, observed.shape) self.assertAllEqual(expected, observed) def testDecodeRawV1VariableLength(self): words = ["string", "longer_string"] with self.assertRaises(errors_impl.InvalidArgumentError): self._decode_v1(words) def testDecodeRawV2FallbackVariableLength(self): words = ["string", "longer_string"] with self.assertRaises(errors_impl.InvalidArgumentError): self._decode_v2(words) def testDecodeRawV2VariableLength(self): words = ["string", "longer_string"] observed = self._decode_v2(words, fixed_length=8) expected = self._ordinalize(words, fixed_length=8) self.assertAllEqual(expected.shape, observed.shape) self.assertAllEqual(expected, observed) def testDecodeRawInvalidFixedLengthSize(self): input_bytes = ["1"] # Different error messages depending on shape inference vs kernel. with self.assertRaisesRegex( (ValueError, errors_impl.InvalidArgumentError), "must be a multiple of|evenly divisible by", ): self.evaluate( self._decode_v2(input_bytes, fixed_length=7, dtype=dtypes.float32) ) def testDecodeRawExtendedInputBytesLittleEndian(self): # Input bytes properly padded internally to at least dtype size. input_bytes = ["\x01\x23"] observed = self._decode_v2( input_bytes, fixed_length=8, dtype=dtypes.int32, little_endian=True ) expected = np.array([[0x00002301, 0]], dtype=np.int32) self.assertAllEqual(expected.shape, observed.shape) self.assertAllEqual(expected, observed) def testDecodeRawExtendedInputBytesBigEndian(self): # Input bytes properly padded internally to at least dtype size. input_bytes = [b"\x01\x23"] observed = self._decode_v2( input_bytes, fixed_length=8, dtype=dtypes.int32, little_endian=False ) expected = np.array([[0x01230000, 0]], dtype=np.int32) self.assertAllEqual(expected.shape, observed.shape) self.assertAllEqual(expected, observed) @test_util.run_all_in_graph_and_eager_modes
DecodeRawTest
python
pytorch__pytorch
test/test_fx_reinplace_pass.py
{ "start": 530, "end": 14496 }
class ____(TestCase): def test_reinplace_basic(self): # Basic test: the out-of-place add() call should be converted # into add_() def f(x): a = x.clone() b = a.add(1) return b inpt = torch.ones(2) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, x_1): clone = torch.ops.aten.clone.default(x_1); x_1 = None add = torch.ops.aten.add_.Tensor(clone, 1); add = None return clone """) def test_reinplace_with_view(self): def f(x): a = x.clone() a_view = a.view(-1) # We shouldn't re-inplace the first add(), because an alias of a is reused later in the program b = a.add(1) # noqa: F841 # Second add() is fine to re-inplace c = a_view.add(1) return c inpt = torch.ones(2) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, x_1): clone = torch.ops.aten.clone.default(x_1); x_1 = None view = torch.ops.aten.view.default(clone, [-1]) add = torch.ops.aten.add.Tensor(clone, 1); clone = add = None add_1 = torch.ops.aten.add_.Tensor(view, 1); add_1 = None return view """) def test_reinplace_different_metadata(self): def f(a_): a = a_.clone() b = a + 1 # Naively, we shouldn't try to inplace the .ge() call, # because that would require resizing "b" (from a float to a bool tensor). c = torch.ge(b, a) return c inpt = torch.ones(4) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) # The .ge() should not be reinplaced. self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None add = torch.ops.aten.add.Tensor(clone, 1) ge = torch.ops.aten.ge.Tensor(add, clone); add = clone = None return ge """) def test_reinplace_overlapping_memory(self): def f(a_): a = a_.clone() b = a.expand(4, 4) # Can't reinplace because b has overlapping memory. c = b.add(1) return c inpt = torch.ones(1) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None expand = torch.ops.aten.expand.default(clone, [4, 4]); clone = None add = torch.ops.aten.add.Tensor(expand, 1); expand = None return add """) # This test won't actually run in CI, because it requires functionalize() from functorch. # I'm planning on testing more comprehensively with torchbench models, # but we can make this testing better once functorch moves into pytorch/pytorch. def test_reinplace_scatter_op(self): def f(a_): # for now, don't test mutations to inputs a = a_.clone() e = a.view(-1) b = a.view(-1) c = b[0] d = c.view(-1) d.add_(1) return a + e if not HAS_FUNCTIONALIZATION: return inpt = torch.ones(4) f2 = reinplace(make_fx(functionalize(f))(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) # NOTE: one slight pessimization here is the fact that # there are a bunch of redundant views in the graph. # Technically, half of these views are duplicates that we could de-dup. # This shouldn't really hurt performance though, since creating an extra view # is effectively just moving some metadata around (and allocating a new TensorImpl). # We can/should update the pass in the future to clean this up. self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None view = torch.ops.aten.view.default(clone, [-1]); view = None view_1 = torch.ops.aten.view.default(clone, [-1]) select = torch.ops.aten.select.int(view_1, 0, 0); view_1 = None view_2 = torch.ops.aten.view.default(select, [-1]); select = None add = torch.ops.aten.add_.Tensor(view_2, 1); add = None view_3 = torch.ops.aten.view.default(clone, [-1]); clone = None select_1 = torch.ops.aten.select.int(view_3, 0, 0); select_1 = None view_4 = torch.ops.aten.view.default(view_2, []); view_2 = view_4 = None view_5 = torch.ops.aten.view.default(view_3, [4]); view_3 = None view_6 = torch.ops.aten.view.default(view_5, [-1]) select_2 = torch.ops.aten.select.int(view_6, 0, 0); view_6 = None view_7 = torch.ops.aten.view.default(select_2, [-1]); select_2 = view_7 = None view_8 = torch.ops.aten.view.default(view_5, [-1]) add_1 = torch.ops.aten.add_.Tensor(view_5, view_8); view_8 = add_1 = None return view_5 """) def test_reinplace_scatter_twice(self): def f(a_): # for now, don't test mutations to inputs a = a_.clone() b = a[:, 1] c = b[1] c.add_(1) return a if not HAS_FUNCTIONALIZATION: return inpt = torch.ones(4, 4) f2 = reinplace(make_fx(functionalize(f))(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None select = torch.ops.aten.select.int(clone, 1, 1) select_1 = torch.ops.aten.select.int(select, 0, 1); select = None add = torch.ops.aten.add_.Tensor(select_1, 1); select_1 = add = None select_2 = torch.ops.aten.select.int(clone, 1, 1); select_2 = None select_3 = torch.ops.aten.select.int(clone, 1, 1) select_4 = torch.ops.aten.select.int(select_3, 0, 1); select_3 = select_4 = None return clone """) def test_reinplace_scatter_twice_with_different_view_op_valid(self): def f(a_): a = a_.clone() b = a[:, 1] c = b[1] c_updated = c.add(1) good_mirror_of_b = a.as_strided((4,), (4,), 1) # good_mirror_of_b points to the same region of memory as b. # and this scatter op below tries to scatter c_updated into the same region # that c currently takes up. # reinplacing logic checks this by confirming that: # c_updated # good_mirror_of_b.select(0, 1) # have the same size/stride/storage_offset. b_updated = torch.select_scatter(good_mirror_of_b, c_updated, 0, 1) return b_updated inpt = torch.ones(4, 4) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None select = torch.ops.aten.select.int(clone, 1, 1) select_1 = torch.ops.aten.select.int(select, 0, 1); select = None add = torch.ops.aten.add_.Tensor(select_1, 1); select_1 = add = None as_strided = torch.ops.aten.as_strided.default(clone, [4], [4], 1); clone = None return as_strided """) # Test example where we have a scatter op, where the base tensor # has the same size/stride/storage offset (even though it is a different view), # making it valid to re-inplace def test_reinplace_scatter_twice_with_different_view_op_invalid(self): def f(a_): a = a_.clone() b = a[:, 1] c = b[1] c_updated = c.add(1) good_mirror_of_b = a.as_strided((4,), (4,), 1) # The first arg to select_scatter is an equivalent view to b. # However, the select_scatter call below tries to put c_updated # into a different slice of "b" than what "c" currently occupies. # b_updated = torch.select_scatter(good_mirror_of_b, c_updated, 0, 0) return b_updated inpt = torch.ones(4, 4) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) actual_out = f2(inpt) self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None select = torch.ops.aten.select.int(clone, 1, 1) select_1 = torch.ops.aten.select.int(select, 0, 1); select = None add = torch.ops.aten.add.Tensor(select_1, 1); select_1 = None as_strided = torch.ops.aten.as_strided.default(clone, [4], [4], 1); clone = None select_int = torch.ops.aten.select.int(as_strided, 0, 0) copy__default = torch.ops.aten.copy_.default(select_int, add); select_int = add = copy__default = None return as_strided """) # noqa: B950 def test_reinplace_scatter_twice_with_different_view_op_invalid2(self): def f(a_): a = a_.clone() b = a[:, 1] c = b[1] c_updated = c.add(1) bad_mirror_of_b = a.as_strided((4,), (4,), 0) # The first arg to select_scatter points to a different than c's base. # This makes it invalid to re-inplace. b_updated = torch.select_scatter(bad_mirror_of_b, c_updated, 0, 1) return b_updated inpt = torch.ones(4, 4) f2 = reinplace(make_fx(f)(inpt), inpt) expected_out = f(inpt) # noqa: F841 actual_out = f2(inpt) # noqa: F841 # self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self, a__1): clone = torch.ops.aten.clone.default(a__1); a__1 = None select = torch.ops.aten.select.int(clone, 1, 1) select_1 = torch.ops.aten.select.int(select, 0, 1); select = None add = torch.ops.aten.add.Tensor(select_1, 1); select_1 = None as_strided = torch.ops.aten.as_strided.default(clone, [4], [4], 0); clone = None select_int = torch.ops.aten.select.int(as_strided, 0, 1) copy__default = torch.ops.aten.copy_.default(select_int, add); select_int = add = copy__default = None return as_strided """) # noqa: B950 def test_out_node_updated(self): def f(): x = torch.zeros(2, 2) y = x.diagonal() y_updated = y.add(1) z = torch.diagonal_scatter(x, y_updated) # reinplace needs to know to replace output [z] with [x] return [z] if not HAS_FUNCTIONALIZATION: return f2 = reinplace(make_fx(functionalize(f))()) expected_out = f() actual_out = f2() self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self): zeros = torch.ops.aten.zeros.default([2, 2], device = device(type='cpu'), pin_memory = False) diagonal = torch.ops.aten.diagonal.default(zeros) add = torch.ops.aten.add_.Tensor(diagonal, 1); diagonal = add = None return [zeros] """) def test_reinplace_index_mutation(self): def f(): a = torch.zeros(4, 4, 4) a[:, 2:] = torch.ones(4, 2, 4) return a if not HAS_FUNCTIONALIZATION: return f2 = reinplace(make_fx(functionalize(f))()) expected_out = f() actual_out = f2() self.assertEqual(actual_out, expected_out) self.assertExpectedInline(f2.code, """\ def forward(self): zeros = torch.ops.aten.zeros.default([4, 4, 4], device = device(type='cpu'), pin_memory = False) ones = torch.ops.aten.ones.default([4, 2, 4], device = device(type='cpu'), pin_memory = False) slice_1 = torch.ops.aten.slice.Tensor(zeros, 1, 2, 9223372036854775807) copy = torch.ops.aten.copy_.default(slice_1, ones); slice_1 = ones = copy = None slice_2 = torch.ops.aten.slice.Tensor(zeros, 1, 2, 9223372036854775807); slice_2 = None return zeros """) def test_reinplace_sym_input(self): # Symbolic input test: the out-of-place add() call should be converted # into add_(), and symbolic input won't cause any error. def f(x, index): a = torch.select(x, 0, index) clone = a.clone() b = clone.add(1) return b x = torch.randn((4, 8, 16, 16), requires_grad=False) index = 2 shape_env = ShapeEnv() symbol = shape_env.create_symbol(index, source=ConstantSource( f"__testing_only{len(shape_env.var_to_val)}")) sym_index = torch.SymInt(SymNode(symbol, shape_env, int, hint=index)) inpt = [x, sym_index] f2 = reinplace(make_fx(f)(*inpt), *inpt) real_inpt = [x, index] expected_out = f(*real_inpt) actual_out = f2(*real_inpt) self.assertEqual(actual_out, expected_out) print(f2.code) self.assertExpectedInline(f2.code, """\ def forward(self, x_1, index_1): select = torch.ops.aten.select.int(x_1, 0, index_1); x_1 = index_1 = None clone = torch.ops.aten.clone.default(select); select = None add = torch.ops.aten.add_.Tensor(clone, 1); add = None return clone """) if __name__ == '__main__': run_tests()
TestReinplacePass
python
numba__numba
numba/parfors/parfor.py
{ "start": 24808, "end": 54340 }
class ____(object): """Holds parfor diagnostic info, this is accumulated throughout the PreParforPass and ParforPass, also in the closure inlining! """ def __init__(self): # holds ref to the function for which this is providing diagnostics self.func = None # holds a map of the replaced functions self.replaced_fns = dict() # used to identify "internal" parfor functions self.internal_name = '__numba_parfor_gufunc' self.fusion_info = defaultdict(list) self.nested_fusion_info = defaultdict(list) self.fusion_reports = [] self.hoist_info = {} self.has_setup = False def setup(self, func_ir, fusion_enabled): self.func_ir = func_ir self.name = self.func_ir.func_id.func_qualname self.line = self.func_ir.loc self.fusion_enabled = fusion_enabled if self.internal_name in self.name: self.purpose = 'Internal parallel function' else: self.purpose = 'Function %s, %s' % (self.name, self.line) # we store a reference to the parfors prior to fusion etc, the parfors # do get mangled in the fusion process but in a predetermined manner # and by holding a reference here the "before" state can be printed self.initial_parfors = self.get_parfors() self.has_setup = True @property def has_setup(self): return self._has_setup @has_setup.setter def has_setup(self, state): self._has_setup = state def count_parfors(self, blocks=None): return len(self.get_parfors()) def _get_nested_parfors(self, parfor, parfors_list): blocks = wrap_parfor_blocks(parfor) self._get_parfors(blocks, parfors_list) unwrap_parfor_blocks(parfor) def _get_parfors(self, blocks, parfors_list): for label, blk in blocks.items(): for stmt in blk.body: if isinstance(stmt, Parfor): parfors_list.append(stmt) self._get_nested_parfors(stmt, parfors_list) def get_parfors(self): parfors_list = [] self._get_parfors(self.func_ir.blocks, parfors_list) return parfors_list def hoisted_allocations(self): allocs = [] for pf_id, data in self.hoist_info.items(): stmt = data.get('hoisted', []) for inst in stmt: if isinstance(inst.value, ir.Expr): if inst.value.op == 'call': call = guard(find_callname, self.func_ir, inst.value) if call is not None and call == ('empty', 'numpy'): allocs.append(inst) return allocs def compute_graph_info(self, _a): """ compute adjacency list of the fused loops and find the roots in of the lists """ a = copy.deepcopy(_a) if a == {}: return [], set() vtx = set() for v in a.values(): for x in v: vtx.add(x) # find roots potential_roots = set(a.keys()) roots = potential_roots - vtx if roots is None: roots = set() # populate rest of adjacency list not_roots = set() for x in range(max(set(a.keys()).union(vtx)) + 1): val = a.get(x) if val is not None: a[x] = val elif val == []: not_roots.add(x) # debug only else: a[x] = [] # fold adjacency list into an actual list ordered # by vtx l = [] for x in sorted(a.keys()): l.append(a[x]) return l, roots #, not_roots def get_stats(self, fadj, nadj, root): """ Computes the number of fused and serialized loops based on a fusion adjacency list `fadj` and a nested parfors adjacency list `nadj` for the root, `root` """ def count_root(fadj, nadj, root, nfused, nserial): for k in nadj[root]: nserial += 1 if nadj[k] == []: nfused += len(fadj[k]) else: nf, ns = count_root(fadj, nadj, k, nfused, nserial) nfused += nf nserial = ns return nfused, nserial nfused, nserial = count_root(fadj, nadj, root, 0, 0) return nfused, nserial def reachable_nodes(self, adj, root): """ returns a list of nodes reachable in an adjacency list from a specified root """ fusers = [] fusers.extend(adj[root]) for k in adj[root]: if adj[k] != []: fusers.extend(self.reachable_nodes(adj, k)) return fusers def sort_pf_by_line(self, pf_id, parfors_simple): """ pd_id - the parfors id parfors_simple - the simple parfors map """ # this sorts parfors by source line number pf = parfors_simple[pf_id][0] pattern = pf.patterns[0] line = max(0, pf.loc.line - 1) # why are these out by 1 ?! filename = self.func_ir.loc.filename nadj, nroots = self.compute_graph_info(self.nested_fusion_info) fadj, froots = self.compute_graph_info(self.fusion_info) graphs = [nadj, fadj] # If the parfor is internal, like internal prange, then the # default line number is from its location in the numba source # To get a more accurate line number, this first checks the # adjacency graph for fused parfors that might not be internal # and uses the minimum line number from there. If that fails # (case where there's just a single internal parfor) the IR # is walked backwards from the parfor location and the first non # parfor statement line number is used. if isinstance(pattern, tuple): if pattern[1] == 'internal': reported_loc = pattern[2][1] if reported_loc.filename == filename: return max(0, reported_loc.line - 1) else: # first recurse and check the adjacency list for # something that is not an in internal parfor tmp = [] for adj in graphs: if adj: # graph may be empty, e.g. no nesting for k in adj[pf_id]: tmp.append(self.sort_pf_by_line(k, parfors_simple)) if tmp: return max(0, min(tmp) - 1) # second run through the parfor block to see if there's # and reference to a line number in the user source for blk in pf.loop_body.values(): for stmt in blk.body: if stmt.loc.filename == filename: return max(0, stmt.loc.line - 1) # finally run through the func_ir and look for the # first non-parfor statement prior to this one and # grab the line from that for blk in self.func_ir.blocks.values(): try: idx = blk.body.index(pf) for i in range(idx - 1, 0, -1): stmt = blk.body[i] if not isinstance(stmt, Parfor): line = max(0, stmt.loc.line - 1) break except ValueError: pass return line def get_parfors_simple(self, print_loop_search): parfors_simple = dict() # print in line order, parfors loop id is based on discovery order for pf in sorted(self.initial_parfors, key=lambda x: x.loc.line): # use 0 here, the parfors are mutated by the time this routine # is called, however, fusion appends the patterns so we can just # pull in the first as a "before fusion" emulation r_pattern = pf.patterns[0] pattern = pf.patterns[0] loc = pf.loc if isinstance(pattern, tuple): if pattern[0] == 'prange': if pattern[1] == 'internal': replfn = '.'.join(reversed(list(pattern[2][0]))) loc = pattern[2][1] r_pattern = '%s %s' % (replfn, '(internal parallel version)') elif pattern[1] == 'user': r_pattern = "user defined prange" elif pattern[1] == 'pndindex': r_pattern = "internal pndindex" #FIXME: trace this! else: assert 0 fmt = 'Parallel for-loop #%s: is produced from %s:\n %s\n \n' if print_loop_search: print_wrapped(fmt % (pf.id, loc, r_pattern)) parfors_simple[pf.id] = (pf, loc, r_pattern) return parfors_simple def get_all_lines(self, parfors_simple): # ensure adjacency lists are the same size for both sets of info # (nests and fusion may not traverse the same space, for # convenience [] is used as a condition to halt recursion) fadj, froots = self.compute_graph_info(self.fusion_info) nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) if len(fadj) > len(nadj): lim = len(fadj) tmp = nadj else: lim = len(nadj) tmp = fadj for x in range(len(tmp), lim): tmp.append([]) # This computes the roots of true loop nests (i.e. loops containing # loops opposed to just a loop that's a root). nroots = set() if _nroots: for r in _nroots: if nadj[r] != []: nroots.add(r) all_roots = froots ^ nroots # This computes all the parfors at the top level that are either: # - roots of loop fusion # - roots of true loop nests # it then combines these based on source line number for ease of # producing output ordered in a manner similar to the code structure froots_lines = {} for x in froots: line = self.sort_pf_by_line(x, parfors_simple) froots_lines[line] = 'fuse', x, fadj nroots_lines = {} for x in nroots: line = self.sort_pf_by_line(x, parfors_simple) nroots_lines[line] = 'nest', x, nadj all_lines = froots_lines.copy() all_lines.update(nroots_lines) return all_lines def source_listing(self, parfors_simple, purpose_str): filename = self.func_ir.loc.filename count = self.count_parfors() func_name = self.func_ir.func_id.func try: lines = inspect.getsource(func_name).splitlines() except OSError: # generated function lines = None if lines and parfors_simple: src_width = max([len(x) for x in lines]) map_line_to_pf = defaultdict(list) # parfors can alias lines for k, v in parfors_simple.items(): # TODO: do a better job of tracking parfors that are not in # this file but are referred to, e.g. np.arange() if parfors_simple[k][1].filename == filename: match_line = self.sort_pf_by_line(k, parfors_simple) map_line_to_pf[match_line].append(str(k)) max_pf_per_line = max([1] + [len(x) for x in map_line_to_pf.values()]) width = src_width + (1 + max_pf_per_line * (len(str(count)) + 2)) newlines = [] newlines.append('\n') newlines.append('Parallel loop listing for %s' % purpose_str) newlines.append(width * '-' + '|loop #ID') fmt = '{0:{1}}| {2}' # why are these off by 1? lstart = max(0, self.func_ir.loc.line - 1) for no, line in enumerate(lines, lstart): pf_ids = map_line_to_pf.get(no, None) if pf_ids is not None: pfstr = '#' + ', '.join(pf_ids) else: pfstr = '' stripped = line.strip('\n') srclen = len(stripped) if pf_ids: l = fmt.format(width * '-', width, pfstr) else: l = fmt.format(width * ' ', width, pfstr) newlines.append(stripped + l[srclen:]) print('\n'.join(newlines)) else: print("No source available") def print_unoptimised(self, lines): # This prints the unoptimised parfors state sword = '+--' fac = len(sword) fadj, froots = self.compute_graph_info(self.fusion_info) nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) if len(fadj) > len(nadj): lim = len(fadj) tmp = nadj else: lim = len(nadj) tmp = fadj for x in range(len(tmp), lim): tmp.append([]) def print_nest(fadj_, nadj_, theroot, reported, region_id): def print_g(fadj_, nadj_, nroot, depth): print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, nroot, '(parallel)')) for k in nadj_[nroot]: if nadj_[k] == []: msg = [] msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, k, '(parallel)')) if fadj_[k] != [] and k not in reported: fused = self.reachable_nodes(fadj_, k) for i in fused: msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, i, '(parallel)')) reported.append(k) print_wrapped('\n'.join(msg)) else: print_g(fadj_, nadj_, k, depth + 1) if nadj_[theroot] != []: print_wrapped("Parallel region %s:" % region_id) print_g(fadj_, nadj_, theroot, 0) print("\n") region_id = region_id + 1 return region_id def print_fuse(ty, pf_id, adj, depth, region_id): msg = [] print_wrapped("Parallel region %s:" % region_id) msg.append(fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel)')) if adj[pf_id] != []: fused = sorted(self.reachable_nodes(adj, pf_id)) for k in fused: msg.append(fac * depth * ' ' + '%s%s %s' % (sword, k, '(parallel)')) region_id = region_id + 1 print_wrapped('\n'.join(msg)) print("\n") return region_id # Walk the parfors by src line and print optimised structure region_id = 0 reported = [] for line, info in sorted(lines.items()): opt_ty, pf_id, adj = info if opt_ty == 'fuse': if pf_id not in reported: region_id = print_fuse('f', pf_id, adj, 0, region_id) elif opt_ty == 'nest': region_id = print_nest(fadj, nadj, pf_id, reported, region_id) else: assert 0 def print_optimised(self, lines): # This prints the optimised output based on the transforms that # occurred during loop fusion and rewriting of loop nests sword = '+--' fac = len(sword) fadj, froots = self.compute_graph_info(self.fusion_info) nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) if len(fadj) > len(nadj): lim = len(fadj) tmp = nadj else: lim = len(nadj) tmp = fadj for x in range(len(tmp), lim): tmp.append([]) summary = dict() # region : {fused, serialized} def print_nest(fadj_, nadj_, theroot, reported, region_id): def print_g(fadj_, nadj_, nroot, depth): for k in nadj_[nroot]: msg = fac * depth * ' ' + '%s%s %s' % (sword, k, '(serial') if nadj_[k] == []: fused = [] if fadj_[k] != [] and k not in reported: fused = sorted(self.reachable_nodes(fadj_, k)) msg += ", fused with loop(s): " msg += ', '.join([str(x) for x in fused]) msg += ')' reported.append(k) print_wrapped(msg) summary[region_id]['fused'] += len(fused) else: print_wrapped(msg + ')') print_g(fadj_, nadj_, k, depth + 1) summary[region_id]['serialized'] += 1 if nadj_[theroot] != []: print_wrapped("Parallel region %s:" % region_id) print_wrapped('%s%s %s' % (sword, theroot, '(parallel)')) summary[region_id] = {'root': theroot, 'fused': 0, 'serialized': 0} print_g(fadj_, nadj_, theroot, 1) print("\n") region_id = region_id + 1 return region_id def print_fuse(ty, pf_id, adj, depth, region_id): print_wrapped("Parallel region %s:" % region_id) msg = fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel') fused = [] if adj[pf_id] != []: fused = sorted(self.reachable_nodes(adj, pf_id)) msg += ", fused with loop(s): " msg += ', '.join([str(x) for x in fused]) summary[region_id] = {'root': pf_id, 'fused': len(fused), 'serialized': 0} msg += ')' print_wrapped(msg) print("\n") region_id = region_id + 1 return region_id # Walk the parfors by src line and print optimised structure region_id = 0 reported = [] for line, info in sorted(lines.items()): opt_ty, pf_id, adj = info if opt_ty == 'fuse': if pf_id not in reported: region_id = print_fuse('f', pf_id, adj, 0, region_id) elif opt_ty == 'nest': region_id = print_nest(fadj, nadj, pf_id, reported, region_id) else: assert 0 # print the summary of the fuse/serialize rewrite if summary: for k, v in sorted(summary.items()): msg = ('\n \nParallel region %s (loop #%s) had %s ' 'loop(s) fused') root = v['root'] fused = v['fused'] serialized = v['serialized'] if serialized != 0: msg += (' and %s loop(s) ' 'serialized as part of the larger ' 'parallel loop (#%s).') print_wrapped(msg % (k, root, fused, serialized, root)) else: msg += '.' print_wrapped(msg % (k, root, fused)) else: print_wrapped("Parallel structure is already optimal.") def allocation_hoist(self): found = False print('Allocation hoisting:') for pf_id, data in self.hoist_info.items(): stmt = data.get('hoisted', []) for inst in stmt: if isinstance(inst.value, ir.Expr): try: attr = inst.value.attr if attr == 'empty': msg = ("The memory allocation derived from the " "instruction at %s is hoisted out of the " "parallel loop labelled #%s (it will be " "performed before the loop is executed and " "reused inside the loop):") loc = inst.loc print_wrapped(msg % (loc, pf_id)) try: path = os.path.relpath(loc.filename) except ValueError: path = os.path.abspath(loc.filename) lines = linecache.getlines(path) if lines and loc.line: print_wrapped(" Allocation:: " + lines[0 if loc.line < 2 else loc.line - 1].strip()) print_wrapped(" - numpy.empty() is used for the allocation.\n") found = True except (KeyError, AttributeError): pass if not found: print_wrapped('No allocation hoisting found') def instruction_hoist(self): print("") print('Instruction hoisting:') hoist_info_printed = False if self.hoist_info: for pf_id, data in self.hoist_info.items(): hoisted = data.get('hoisted', None) not_hoisted = data.get('not_hoisted', None) if not hoisted and not not_hoisted: print("loop #%s has nothing to hoist." % pf_id) continue print("loop #%s:" % pf_id) if hoisted: print(" Has the following hoisted:") [print(" %s" % y) for y in hoisted] hoist_info_printed = True if not_hoisted: print(" Failed to hoist the following:") [print(" %s: %s" % (y, x)) for x, y in not_hoisted] hoist_info_printed = True if not hoist_info_printed: print_wrapped('No instruction hoisting found') print_wrapped(80 * '-') def dump(self, level=1): if not self.has_setup: raise RuntimeError("self.setup has not been called") name = self.func_ir.func_id.func_qualname line = self.func_ir.loc if self.internal_name in name: purpose_str = 'Internal parallel functions ' purpose = 'internal' else: purpose_str = ' Function %s, %s ' % (name, line) purpose = 'user' print_loop_search = False print_source_listing = False print_fusion_search = False print_fusion_summary = False print_loopnest_rewrite = False print_pre_optimised = False print_post_optimised = False print_allocation_hoist = False print_instruction_hoist = False print_internal = False # each level switches on progressively more output if level in (1, 2, 3, 4): print_source_listing = True print_post_optimised = True else: raise ValueError("Report level unknown, should be one of 1, 2, 3, 4") if level in (2, 3, 4): print_pre_optimised = True if level in (3, 4): print_allocation_hoist = True if level == 3: print_fusion_summary = True print_loopnest_rewrite = True if level == 4: print_fusion_search = True print_instruction_hoist = True print_internal = True if purpose == 'internal' and not print_internal: return print_wrapped('\n ') print_wrapped(_termwidth * "=") print_wrapped((" Parallel Accelerator Optimizing: %s " % purpose_str).center(_termwidth, '=')) print_wrapped(_termwidth * "=") print_wrapped("") #----------- search section if print_loop_search: print_wrapped('Looking for parallel loops'.center(_termwidth, '-')) parfors_simple = self.get_parfors_simple(print_loop_search) count = self.count_parfors() if print_loop_search: print_wrapped("\nFound %s parallel loops." % count) print_wrapped('-' * _termwidth) #----------- augmented source section filename = self.func_ir.loc.filename try: # Try to get a relative path # ipython/jupyter input just returns as filename path = os.path.relpath(filename) except ValueError: # Fallback to absolute path if error occurred in getting the # relative path. # This may happen on windows if the drive is different path = os.path.abspath(filename) if print_source_listing: self.source_listing(parfors_simple, purpose_str) #---------- these are used a lot here on in sword = '+--' parfors = self.get_parfors() # this is the mutated parfors parfor_ids = [x.id for x in parfors] n_parfors = len(parfor_ids) #----------- loop fusion section if print_fusion_search or print_fusion_summary: if not sequential_parfor_lowering: print_wrapped(' Fusing loops '.center(_termwidth, '-')) msg = ("Attempting fusion of parallel loops (combines loops " "with similar properties)...\n") print_wrapped(msg) else: msg = "Performing sequential lowering of loops...\n" print_wrapped(msg) print_wrapped(_termwidth * '-') # if there are some parfors, print information about them! if n_parfors > -1: def dump_graph_indented(a, root_msg, node_msg): fac = len(sword) def print_graph(adj, roots): def print_g(adj, root, depth): for k in adj[root]: print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, k, node_msg)) if adj[k] != []: print_g(adj, k, depth + 1) for r in roots: print_wrapped('%s%s %s' % (sword, r, root_msg)) print_g(l, r, 1) print_wrapped("") l, roots = self.compute_graph_info(a) print_graph(l, roots) if print_fusion_search: for report in self.fusion_reports: l1, l2, msg = report print_wrapped(" Trying to fuse loops #%s and #%s:" % (l1, l2)) print_wrapped(" %s" % msg) if self.fusion_info != {}: if print_fusion_summary: print_wrapped("\n \nFused loop summary:\n") dump_graph_indented(self.fusion_info, 'has the following loops fused into it:', '(fused)') if print_fusion_summary: if self.fusion_enabled: after_fusion = "Following the attempted fusion of parallel for-loops" else: after_fusion = "With fusion disabled" print_wrapped(('\n{} there are {} parallel for-loop(s) (originating from loops labelled: {}).').format( after_fusion, n_parfors, ', '.join(['#%s' % x for x in parfor_ids]))) print_wrapped(_termwidth * '-') print_wrapped("") #----------- loop nest section if print_loopnest_rewrite: if self.nested_fusion_info != {}: print_wrapped((" Optimising loop nests ").center(_termwidth, '-')) print_wrapped("Attempting loop nest rewrites (optimising for the largest parallel loops)...\n ") root_msg = 'is a parallel loop' node_msg = '--> rewritten as a serial loop' dump_graph_indented(self.nested_fusion_info, root_msg, node_msg) print_wrapped(_termwidth * '-') print_wrapped("") #---------- compute various properties and orderings in the data for subsequent use all_lines = self.get_all_lines(parfors_simple) if print_pre_optimised: print(' Before Optimisation '.center(_termwidth,'-')) self.print_unoptimised(all_lines) print(_termwidth * '-') if print_post_optimised: print(' After Optimisation '.center(_termwidth,'-')) self.print_optimised(all_lines) print(_termwidth * '-') print_wrapped("") print_wrapped(_termwidth * '-') print_wrapped("\n ") #----------- LICM section if print_allocation_hoist or print_instruction_hoist: print_wrapped('Loop invariant code motion'.center(80, '-')) if print_allocation_hoist: self.allocation_hoist() if print_instruction_hoist: self.instruction_hoist() else: # there are no parfors print_wrapped('Function %s, %s, has no parallel for-loops.'.format(name, line)) def __str__(self): r = "ParforDiagnostics:\n" r += repr(self.replaced_fns) return r def __repr__(self): r = "ParforDiagnostics" return r
ParforDiagnostics
python
sympy__sympy
sympy/core/singleton.py
{ "start": 1009, "end": 7370 }
class ____(Registry): """ The registry for the singleton classes (accessible as ``S``). Explanation =========== This class serves as two separate things. The first thing it is is the ``SingletonRegistry``. Several classes in SymPy appear so often that they are singletonized, that is, using some metaprogramming they are made so that they can only be instantiated once (see the :class:`sympy.core.singleton.Singleton` class for details). For instance, every time you create ``Integer(0)``, this will return the same instance, :class:`sympy.core.numbers.Zero`. All singleton instances are attributes of the ``S`` object, so ``Integer(0)`` can also be accessed as ``S.Zero``. Singletonization offers two advantages: it saves memory, and it allows fast comparison. It saves memory because no matter how many times the singletonized objects appear in expressions in memory, they all point to the same single instance in memory. The fast comparison comes from the fact that you can use ``is`` to compare exact instances in Python (usually, you need to use ``==`` to compare things). ``is`` compares objects by memory address, and is very fast. Examples ======== >>> from sympy import S, Integer >>> a = Integer(0) >>> a is S.Zero True For the most part, the fact that certain objects are singletonized is an implementation detail that users should not need to worry about. In SymPy library code, ``is`` comparison is often used for performance purposes The primary advantage of ``S`` for end users is the convenient access to certain instances that are otherwise difficult to type, like ``S.Half`` (instead of ``Rational(1, 2)``). When using ``is`` comparison, make sure the argument is sympified. For instance, >>> x = 0 >>> x is S.Zero False This problem is not an issue when using ``==``, which is recommended for most use-cases: >>> 0 == S.Zero True The second thing ``S`` is is a shortcut for :func:`sympy.core.sympify.sympify`. :func:`sympy.core.sympify.sympify` is the function that converts Python objects such as ``int(1)`` into SymPy objects such as ``Integer(1)``. It also converts the string form of an expression into a SymPy expression, like ``sympify("x**2")`` -> ``Symbol("x")**2``. ``S(1)`` is the same thing as ``sympify(1)`` (basically, ``S.__call__`` has been defined to call ``sympify``). This is for convenience, since ``S`` is a single letter. It's mostly useful for defining rational numbers. Consider an expression like ``x + 1/2``. If you enter this directly in Python, it will evaluate the ``1/2`` and give ``0.5``, because both arguments are ints (see also :ref:`tutorial-gotchas-final-notes`). However, in SymPy, you usually want the quotient of two integers to give an exact rational number. The way Python's evaluation works, at least one side of an operator needs to be a SymPy object for the SymPy evaluation to take over. You could write this as ``x + Rational(1, 2)``, but this is a lot more typing. A shorter version is ``x + S(1)/2``. Since ``S(1)`` returns ``Integer(1)``, the division will return a ``Rational`` type, since it will call ``Integer.__truediv__``, which knows how to return a ``Rational``. """ __slots__ = () Zero: _Zero One: _One NegativeOne: _NegativeOne Half: _Half ImaginaryUnit: _ImaginaryUnit Exp1: _Exp1 Pi: _Pi GoldenRatio: _GoldenRatio TribonacciConstant: _TribonacciConstant EulerGamma: _EulerGamma Catalan: _Catalan Infinity: _Infinity NegativeInfinity: _NegativeInfinity ComplexInfinity: _ComplexInfinity NaN: _NaN true: _BooleanTrue false: _BooleanFalse # Also allow things like S(5) @overload def __call__(self, a: int, *, strict: bool = False) -> Integer: ... # type: ignore @overload def __call__(self, a: float, *, strict: bool = False) -> Float: ... @overload def __call__(self, a: Expr | complex, *, strict: bool = False) -> Expr: ... @overload def __call__(self, a: Tbasic, *, strict: bool = False) -> Tbasic: ... @overload def __call__(self, a: Any, *, strict: bool = False) -> Basic: ... def __call__(self, a, locals=None, convert_xor=True, strict=False, rational=False, evaluate=None): return sympify(a, locals=locals, convert_xor=convert_xor, strict=strict, rational=rational, evaluate=evaluate) # type: ignore def __init__(self): self._classes_to_install = {} # Dict of classes that have been registered, but that have not have been # installed as an attribute of this SingletonRegistry. # Installation automatically happens at the first attempt to access the # attribute. # The purpose of this is to allow registration during class # initialization during import, but not trigger object creation until # actual use (which should not happen until after all imports are # finished). def register(self, cls): # Make sure a duplicate class overwrites the old one if hasattr(self, cls.__name__): delattr(self, cls.__name__) self._classes_to_install[cls.__name__] = cls def __getattr__(self, name): """Python calls __getattr__ if no attribute of that name was installed yet. Explanation =========== This __getattr__ checks whether a class with the requested name was already registered but not installed; if no, raises an AttributeError. Otherwise, retrieves the class, calculates its singleton value, installs it as an attribute of the given name, and unregisters the class.""" if name not in self._classes_to_install: raise AttributeError( "Attribute '%s' was not installed on SymPy registry %s" % ( name, self)) class_to_install = self._classes_to_install[name] value_to_install = class_to_install() self.__setattr__(name, value_to_install) del self._classes_to_install[name] return value_to_install def __repr__(self): return "S" S = SingletonRegistry()
SingletonRegistry
python
huggingface__transformers
src/transformers/models/owlvit/modeling_owlvit.py
{ "start": 22935, "end": 24924 }
class ____(GradientCheckpointingLayer): def __init__(self, config: OwlViTConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = OwlViTAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = OwlViTMLP(config) self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, causal_attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.layer_norm1(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, causal_attention_mask=causal_attention_mask, output_attentions=output_attentions, ) hidden_states = residual + hidden_states residual = hidden_states hidden_states = self.layer_norm2(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs @auto_docstring
OwlViTEncoderLayer
python
doocs__leetcode
lcof/面试题49. 丑数/Solution.py
{ "start": 0, "end": 352 }
class ____: def nthUglyNumber(self, n: int) -> int: h = [1] vis = {1} ans = 1 for _ in range(n): ans = heappop(h) for v in [2, 3, 5]: nxt = ans * v if nxt not in vis: vis.add(nxt) heappush(h, nxt) return ans
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1574658, "end": 1574868 }
class ____(SelectionInitInterval): """Vector2boolean schema wrapper.""" _schema = {"$ref": "#/definitions/Vector2<boolean>"} def __init__(self, *args): super().__init__(*args)
Vector2boolean
python
falconry__falcon
falcon/testing/helpers.py
{ "start": 1956, "end": 3435 }
class ____: """Emits ASGI lifespan events to an ASGI app. This class can be used to drive a standard ASGI app callable in order to perform functional tests on the app in question. When simulating both lifespan and per-request events, each event stream will require a separate invocation of the ASGI callable; one with a lifespan event emitter, and one with a request event emitter. An asyncio :class:`~asyncio.Condition` can be used to pause the lifespan emitter until all of the desired request events have been emitted. Keyword Args: shutting_down (asyncio.Condition): An instance of :class:`asyncio.Condition` that will be awaited before emitting the final shutdown event (``'lifespan.shutdown``). """ def __init__(self, shutting_down: asyncio.Condition) -> None: self._state = 0 self._shutting_down = shutting_down async def emit(self) -> AsgiEvent: if self._state == 0: self._state += 1 return {'type': EventType.LIFESPAN_STARTUP} if self._state == 1: self._state += 1 # NOTE(kgriffs): This verifies the app ignores events it does # not recognize. return {'type': 'lifespan._nonstandard_event'} async with self._shutting_down: await self._shutting_down.wait() return {'type': EventType.LIFESPAN_SHUTDOWN} __call__ = emit
ASGILifespanEventEmitter
python
walkccc__LeetCode
solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py
{ "start": 446, "end": 1155 }
class ____: # Same as 2907. Maximum Profitable Triplets With Increasing Prices I def maxProfit(self, prices: list[int], profits: list[int]) -> int: ans = -1 maxPrice = max(prices) maxProfitTree1 = FenwickTree(maxPrice) maxProfitTree2 = FenwickTree(maxPrice) for price, profit in zip(prices, profits): # max(proftis[i]) maxProfit1 = maxProfitTree1.get(price - 1) # max(proftis[i]) + max(profits[j]) maxProfit2 = maxProfitTree2.get(price - 1) maxProfitTree1.maximize(price, profit) if maxProfit1 > 0: maxProfitTree2.maximize(price, profit + maxProfit1) if maxProfit2 > 0: ans = max(ans, profit + maxProfit2) return ans
Solution
python
PyCQA__pylint
tests/functional/e/e1101_9588_base_attr_aug_assign.py
{ "start": 241, "end": 355 }
class ____: "The base class" def __init__(self): "Set an attribute." self.e1101 = 1
BaseClass
python
walkccc__LeetCode
solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py
{ "start": 0, "end": 579 }
class ____: def __init__(self, n: int): self.count = n self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> bool: i = self._find(u) j = self._find(v) if i == j: return False if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 self.count -= 1 return True def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u]
UnionFind
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_sort.py
{ "start": 6416, "end": 7764 }
class ____(__TestCase): def test_bug453523(self): # bug 453523 -- list.sort() crasher. # If this fails, the most likely outcome is a core dump. # Mutations during a list sort should raise a ValueError. with torch._dynamo.error_on_graph_break(False): class C: def __lt__(self, other): if L and random.random() < 0.75: L.pop() else: L.append(3) return random.random() < 0.5 L = [C() for i in range(50)] self.assertRaises(ValueError, L.sort) def test_undetected_mutation(self): # Python 2.4a1 did not always detect mutation memorywaster = [] for i in range(20): def mutating_cmp(x, y): L.append(3) L.pop() return (x > y) - (x < y) L = [1,2] self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp)) def mutating_cmp(x, y): L.append(3) del L[:] return (x > y) - (x < y) self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp)) memorywaster = [memorywaster] #==============================================================================
TestBugs
python
doocs__leetcode
solution/3000-3099/3036.Number of Subarrays That Match a Pattern II/Solution.py
{ "start": 715, "end": 1086 }
class ____: def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: s = [] for i in range(1, len(nums)): if nums[i] > nums[i - 1]: s.append(1) elif nums[i] == nums[i - 1]: s.append(0) else: s.append(-1) return len(match(s, pattern))
Solution
python
getsentry__sentry
tests/sentry/seer/explorer/test_custom_tool_utils.py
{ "start": 1112, "end": 1709 }
class ____(ExplorerTool): @classmethod def get_description(cls): return "Test tool with default parameter" @classmethod def get_params(cls): return [ ExplorerToolParam(name="value", description="Value", type=StringType()), ExplorerToolParam( name="suffix", description="Suffix", type=StringType(), required=False ), ] @classmethod def execute(cls, organization, **kwargs): value = kwargs["value"] suffix = kwargs.get("suffix", "!") return value + suffix
TestToolWithDefault
python
tensorflow__tensorflow
tensorflow/python/ops/math_ops_test.py
{ "start": 40914, "end": 42447 }
class ____(test_util.TensorFlowTestCase): def testXlogyNoZero(self): for dtype in [dtypes.float16, dtypes.float32, dtypes.float64]: x = constant_op.constant([[0.1, 0.2, 3.5], [-2., -5., 30.]], dtype=dtype) y = constant_op.constant([[0.1, 0.2, 3.5], [3.1, 4., 2.]], dtype=dtype) with test_util.use_gpu(): xlogy = self.evaluate(math_ops.xlogy(x, y)) xtimeslogy = self.evaluate(x * math_ops.log(y)) self.assertAllClose(xlogy, xtimeslogy) def testXlogyWithZero(self): for dtype in [dtypes.float16, dtypes.float32, dtypes.float64]: x = constant_op.constant(np.zeros((2, 3)), dtype=dtype) y = constant_op.constant([[0.1, 0.2, 3.5], [0., 1., 2.]], dtype=dtype) with test_util.use_gpu(): xlogy_tf_np = self.evaluate(math_ops.xlogy(x, y)) zeros_np = self.evaluate(array_ops.zeros_like(y)) self.assertAllClose(xlogy_tf_np, zeros_np) def testXlogyWithZeroBroadcast(self): for dtype in [dtypes.float16, dtypes.float32, dtypes.float64]: x = constant_op.constant([[0.], [1.]], dtype=dtype) y = constant_op.constant([[0.1, 0.2, 3.5], [0., 1., 2.]], dtype=dtype) with test_util.use_gpu(): xlogy_tf_np = self.evaluate(math_ops.xlogy(x, y)) zeros_np = self.evaluate(array_ops.zeros_like(y[0])) xtimes_logy = self.evaluate(math_ops.log(y[1])) self.assertAllClose(zeros_np, xlogy_tf_np[0]) self.assertAllClose(xtimes_logy, xlogy_tf_np[1]) @test_util.run_all_in_graph_and_eager_modes
XlogyTest
python
pyodide__pyodide
src/py/pyodide/http/_exceptions.py
{ "start": 1747, "end": 1936 }
class ____(XHRError): """Timeout error for XMLHttpRequest.""" def __init__(self, timeout: int) -> None: super().__init__(f"Request timed out after {timeout}ms")
XHRTimeoutError
python
PyCQA__pydocstyle
src/pydocstyle/parser.py
{ "start": 5421, "end": 6838 }
class ____(Definition): """A Python source code function.""" _nest = staticmethod( lambda s: {'def': NestedFunction, 'class': NestedClass}[s] ) @property def is_public(self): """Return True iff this function should be considered public.""" if self.dunder_all is not None: return self.name in self.dunder_all else: return not self.name.startswith('_') @property def is_overload(self): """Return True iff the method decorated with overload.""" return any( decorator.name == "overload" for decorator in self.decorators ) def is_property(self, property_decorator_names): """Return True if the method is decorated with any property decorator.""" return any( decorator.name in property_decorator_names for decorator in self.decorators ) @property def is_test(self): """Return True if this function is a test function/method. We exclude tests from the imperative mood check, because to phrase their docstring in the imperative mood, they would have to start with a highly redundant "Test that ...". """ return self.name.startswith('test') or self.name == 'runTest' @property def param_names(self): """Return the parameter names.""" return self.callable_args
Function
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0070_migrate_remaining_anomaly_detection_alerts.py
{ "start": 1558, "end": 2149 }
class ____(Enum): EMAIL = 0 PAGERDUTY = 1 SLACK = 2 MSTEAMS = 3 SENTRY_APP = 4 SENTRY_NOTIFICATION = 5 # Use personal notification platform (src/sentry/notifications) OPSGENIE = 6 DISCORD = 7 MAX_ACTIONS = 3 ACTION_TYPE_TO_STRING = { AlertRuleTriggerActionType.PAGERDUTY.value: "PagerDuty", AlertRuleTriggerActionType.SLACK.value: "Slack", AlertRuleTriggerActionType.MSTEAMS.value: "Microsoft Teams", AlertRuleTriggerActionType.OPSGENIE.value: "Opsgenie", AlertRuleTriggerActionType.DISCORD.value: "Discord", }
AlertRuleTriggerActionType
python
scikit-learn__scikit-learn
sklearn/decomposition/_fastica.py
{ "start": 11349, "end": 26604 }
class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """FastICA: a fast algorithm for Independent Component Analysis. The implementation is based on [1]_. Read more in the :ref:`User Guide <ICA>`. Parameters ---------- n_components : int, default=None Number of components to use. If None is passed, all are used. algorithm : {'parallel', 'deflation'}, default='parallel' Specify which algorithm to use for FastICA. whiten : str or bool, default='unit-variance' Specify the whitening strategy to use. - If 'arbitrary-variance', a whitening with variance arbitrary is used. - If 'unit-variance', the whitening matrix is rescaled to ensure that each recovered source has unit variance. - If False, the data is already considered to be whitened, and no whitening is performed. .. versionchanged:: 1.3 The default value of `whiten` changed to 'unit-variance' in 1.3. fun : {'logcosh', 'exp', 'cube'} or callable, default='logcosh' The functional form of the G function used in the approximation to neg-entropy. Could be either 'logcosh', 'exp', or 'cube'. You can also provide your own function. It should return a tuple containing the value of the function, and of its derivative, in the point. The derivative should be averaged along its last dimension. Example:: def my_g(x): return x ** 3, (3 * x ** 2).mean(axis=-1) fun_args : dict, default=None Arguments to send to the functional form. If empty or None and if fun='logcosh', fun_args will take value {'alpha' : 1.0}. max_iter : int, default=200 Maximum number of iterations during fit. tol : float, default=1e-4 A positive scalar giving the tolerance at which the un-mixing matrix is considered to have converged. w_init : array-like of shape (n_components, n_components), default=None Initial un-mixing array. If `w_init=None`, then an array of values drawn from a normal distribution is used. whiten_solver : {"eigh", "svd"}, default="svd" The solver to use for whitening. - "svd" is more stable numerically if the problem is degenerate, and often faster when `n_samples <= n_features`. - "eigh" is generally more memory efficient when `n_samples >= n_features`, and can be faster when `n_samples >= 50 * n_features`. .. versionadded:: 1.2 random_state : int, RandomState instance or None, default=None Used to initialize ``w_init`` when not specified, with a normal distribution. Pass an int, for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. Attributes ---------- components_ : ndarray of shape (n_components, n_features) The linear operator to apply to the data to get the independent sources. This is equal to the unmixing matrix when ``whiten`` is False, and equal to ``np.dot(unmixing_matrix, self.whitening_)`` when ``whiten`` is True. mixing_ : ndarray of shape (n_features, n_components) The pseudo-inverse of ``components_``. It is the linear operator that maps independent sources to the data. mean_ : ndarray of shape(n_features,) The mean over features. Only set if `self.whiten` is True. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 n_iter_ : int If the algorithm is "deflation", n_iter is the maximum number of iterations run across all components. Else they are just the number of iterations taken to converge. whitening_ : ndarray of shape (n_components, n_features) Only set if whiten is 'True'. This is the pre-whitening matrix that projects data onto the first `n_components` principal components. See Also -------- PCA : Principal component analysis (PCA). IncrementalPCA : Incremental principal components analysis (IPCA). KernelPCA : Kernel Principal component analysis (KPCA). MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis. SparsePCA : Sparse Principal Components Analysis (SparsePCA). References ---------- .. [1] A. Hyvarinen and E. Oja, Independent Component Analysis: Algorithms and Applications, Neural Networks, 13(4-5), 2000, pp. 411-430. Examples -------- >>> from sklearn.datasets import load_digits >>> from sklearn.decomposition import FastICA >>> X, _ = load_digits(return_X_y=True) >>> transformer = FastICA(n_components=7, ... random_state=0, ... whiten='unit-variance') >>> X_transformed = transformer.fit_transform(X) >>> X_transformed.shape (1797, 7) """ _parameter_constraints: dict = { "n_components": [Interval(Integral, 1, None, closed="left"), None], "algorithm": [StrOptions({"parallel", "deflation"})], "whiten": [ StrOptions({"arbitrary-variance", "unit-variance"}), Options(bool, {False}), ], "fun": [StrOptions({"logcosh", "exp", "cube"}), callable], "fun_args": [dict, None], "max_iter": [Interval(Integral, 1, None, closed="left")], "tol": [Interval(Real, 0.0, None, closed="left")], "w_init": ["array-like", None], "whiten_solver": [StrOptions({"eigh", "svd"})], "random_state": ["random_state"], } def __init__( self, n_components=None, *, algorithm="parallel", whiten="unit-variance", fun="logcosh", fun_args=None, max_iter=200, tol=1e-4, w_init=None, whiten_solver="svd", random_state=None, ): super().__init__() self.n_components = n_components self.algorithm = algorithm self.whiten = whiten self.fun = fun self.fun_args = fun_args self.max_iter = max_iter self.tol = tol self.w_init = w_init self.whiten_solver = whiten_solver self.random_state = random_state def _fit_transform(self, X, compute_sources=False): """Fit the model. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. compute_sources : bool, default=False If False, sources are not computes but only the rotation matrix. This can save memory when working with big data. Defaults to False. Returns ------- S : ndarray of shape (n_samples, n_components) or None Sources matrix. `None` if `compute_sources` is `False`. """ XT = validate_data( self, X, copy=self.whiten, dtype=[np.float64, np.float32], ensure_min_samples=2, ).T fun_args = {} if self.fun_args is None else self.fun_args random_state = check_random_state(self.random_state) alpha = fun_args.get("alpha", 1.0) if not 1 <= alpha <= 2: raise ValueError("alpha must be in [1,2]") if self.fun == "logcosh": g = _logcosh elif self.fun == "exp": g = _exp elif self.fun == "cube": g = _cube elif callable(self.fun): def g(x, fun_args): return self.fun(x, **fun_args) n_features, n_samples = XT.shape n_components = self.n_components if not self.whiten and n_components is not None: n_components = None warnings.warn("Ignoring n_components with whiten=False.") if n_components is None: n_components = min(n_samples, n_features) if n_components > min(n_samples, n_features): n_components = min(n_samples, n_features) warnings.warn( "n_components is too large: it will be set to %s" % n_components ) if self.whiten: # Centering the features of X X_mean = XT.mean(axis=-1) XT -= X_mean[:, np.newaxis] # Whitening and preprocessing by PCA if self.whiten_solver == "eigh": # Faster when num_samples >> n_features d, u = linalg.eigh(XT.dot(X)) sort_indices = np.argsort(d)[::-1] eps = np.finfo(d.dtype).eps * 10 degenerate_idx = d < eps if np.any(degenerate_idx): warnings.warn( "There are some small singular values, using " "whiten_solver = 'svd' might lead to more " "accurate results." ) d[degenerate_idx] = eps # For numerical issues np.sqrt(d, out=d) d, u = d[sort_indices], u[:, sort_indices] elif self.whiten_solver == "svd": u, d = linalg.svd(XT, full_matrices=False, check_finite=False)[:2] # Give consistent eigenvectors for both svd solvers u *= np.sign(u[0]) K = (u / d).T[:n_components] # see (6.33) p.140 del u, d X1 = np.dot(K, XT) # see (13.6) p.267 Here X1 is white and data # in X has been projected onto a subspace by PCA X1 *= np.sqrt(n_samples) else: # X must be casted to floats to avoid typing issues with numpy # 2.0 and the line below X1 = as_float_array(XT, copy=False) # copy has been taken care of w_init = self.w_init if w_init is None: w_init = np.asarray( random_state.normal(size=(n_components, n_components)), dtype=X1.dtype ) else: w_init = np.asarray(w_init) if w_init.shape != (n_components, n_components): raise ValueError( "w_init has invalid shape -- should be %(shape)s" % {"shape": (n_components, n_components)} ) kwargs = { "tol": self.tol, "g": g, "fun_args": fun_args, "max_iter": self.max_iter, "w_init": w_init, } if self.algorithm == "parallel": W, n_iter = _ica_par(X1, **kwargs) elif self.algorithm == "deflation": W, n_iter = _ica_def(X1, **kwargs) del X1 self.n_iter_ = n_iter if compute_sources: if self.whiten: S = np.linalg.multi_dot([W, K, XT]).T else: S = np.dot(W, XT).T else: S = None if self.whiten: if self.whiten == "unit-variance": if not compute_sources: S = np.linalg.multi_dot([W, K, XT]).T S_std = np.std(S, axis=0, keepdims=True) S /= S_std W /= S_std.T self.components_ = np.dot(W, K) self.mean_ = X_mean self.whitening_ = K else: self.components_ = W self.mixing_ = linalg.pinv(self.components_, check_finite=False) self._unmixing = W return S @_fit_context(prefer_skip_nested_validation=True) def fit_transform(self, X, y=None): """Fit the model and recover the sources from X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. Returns ------- X_new : ndarray of shape (n_samples, n_components) Estimated sources obtained by transforming the data with the estimated unmixing matrix. """ return self._fit_transform(X, compute_sources=True) @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y=None): """Fit the model to X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Returns the instance itself. """ self._fit_transform(X, compute_sources=False) return self def transform(self, X, copy=True): """Recover the sources from X (apply the unmixing matrix). Parameters ---------- X : array-like of shape (n_samples, n_features) Data to transform, where `n_samples` is the number of samples and `n_features` is the number of features. copy : bool, default=True If False, data passed to fit can be overwritten. Defaults to True. Returns ------- X_new : ndarray of shape (n_samples, n_components) Estimated sources obtained by transforming the data with the estimated unmixing matrix. """ check_is_fitted(self) X = validate_data( self, X, copy=(copy and self.whiten), dtype=[np.float64, np.float32], reset=False, ) if self.whiten: X -= self.mean_ return np.dot(X, self.components_.T) def inverse_transform(self, X, copy=True): """Transform the sources back to the mixed data (apply mixing matrix). Parameters ---------- X : array-like of shape (n_samples, n_components) Sources, where `n_samples` is the number of samples and `n_components` is the number of components. copy : bool, default=True If False, data passed to fit are overwritten. Defaults to True. Returns ------- X_original : ndarray of shape (n_samples, n_features) Reconstructed data obtained with the mixing matrix. """ check_is_fitted(self) X = check_array(X, copy=(copy and self.whiten), dtype=[np.float64, np.float32]) X = np.dot(X, self.mixing_.T) if self.whiten: X += self.mean_ return X @property def _n_features_out(self): """Number of transformed output features.""" return self.components_.shape[0] def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.transformer_tags.preserves_dtype = ["float64", "float32"] return tags
FastICA
python
great-expectations__great_expectations
great_expectations/core/serdes.py
{ "start": 101, "end": 178 }
class ____(BaseModel): name: str id: Union[str, None]
_IdentifierBundle
python
openai__openai-python
src/openai/types/beta/threads/runs/code_interpreter_output_image.py
{ "start": 408, "end": 613 }
class ____(BaseModel): index: int """The index of the output in the outputs array.""" type: Literal["image"] """Always `image`.""" image: Optional[Image] = None
CodeInterpreterOutputImage
python
django-compressor__django-compressor
compressor/exceptions.py
{ "start": 0, "end": 100 }
class ____(Exception): """ A general error of the compressor """ pass
CompressorError
python
walkccc__LeetCode
solutions/711. Number of Distinct Islands II/711.py
{ "start": 0, "end": 1417 }
class ____: def numDistinctIslands2(self, grid: list[list[int]]) -> int: seen = set() def dfs(i: int, j: int): if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): return if grid[i][j] == 0 or (i, j) in seen: return seen.add((i, j)) island.append((i, j)) dfs(i + 1, j) dfs(i - 1, j) dfs(i, j + 1) dfs(i, j - 1) def normalize(island: list[tuple]) -> list[tuple]: # points[i] := 8 different rotations/reflections of an island points = [[] for _ in range(8)] for i, j in island: points[0].append((i, j)) points[1].append((i, -j)) points[2].append((-i, j)) points[3].append((-i, -j)) points[4].append((j, i)) points[5].append((j, -i)) points[6].append((-j, i)) points[7].append((-j, -i)) points = [sorted(p) for p in points] # Normalize each p by substracting p[1..7] with p[0]. for p in points: for i in range(1, len(island)): p[i] = (p[i][0] - p[0][0], p[i][1] - p[0][1]) p[0] = (0, 0) return sorted(points)[0] islands = set() # all the islands with different shapes for i in range(len(grid)): for j in range(len(grid[0])): island = [] dfs(i, j) if island: islands.add(frozenset(normalize(island))) return len(islands)
Solution
python
ray-project__ray
python/ray/_private/gcs_pubsub.py
{ "start": 8474, "end": 9446 }
class ____(_AioSubscriber): def __init__( self, worker_id: bytes = None, address: str = None, channel: grpc.Channel = None, ): super().__init__(pubsub_pb2.GCS_NODE_INFO_CHANNEL, worker_id, address, channel) async def poll( self, batch_size, timeout=None ) -> List[Tuple[bytes, gcs_pb2.GcsNodeInfo]]: """Polls for new node info message. Returns: A list of tuples of (node_id, GcsNodeInfo). """ await self._poll(timeout=timeout) return self._pop_node_infos(self._queue, batch_size=batch_size) @staticmethod def _pop_node_infos(queue, batch_size): if len(queue) == 0: return [] popped = 0 msgs = [] while len(queue) > 0 and popped < batch_size: msg = queue.popleft() msgs.append((msg.key_id, msg.node_info_message)) popped += 1 return msgs
GcsAioNodeInfoSubscriber
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/lookup_ops_test.py
{ "start": 2513, "end": 3372 }
class ____(test.TestCase): def getHashTable(self): if tf2.enabled(): return lookup_ops.StaticHashTable else: return lookup_ops.StaticHashTableV1 def getVocabularyTable(self): if tf2.enabled(): return lookup_ops.StaticVocabularyTable else: return lookup_ops.StaticVocabularyTableV1 def initialize_table(self, table): if not tf2.enabled(): self.evaluate(table.initializer) SKIP_ANONYMOUS_IN_TF1_REASON = ( "In v1 graph mode, each self.evaluate call will execute the handle " "creation op (e.g. AnonymousHashTable) which will create a new table " "resource unrelated to other self.evaluate calls, so we can't test " "anonymous resources with self.evaluate ." ) @parameterized.named_parameters( (f"_{is_anonymous}", is_anonymous) for is_anonymous in [False, True])
BaseLookupTableTest
python
ansible__ansible
lib/ansible/inventory/manager.py
{ "start": 30212, "end": 31743 }
class ____(_wrapt.ObjectProxy): """ Proxy wrapper around InventoryData. Allows `set_variable` calls to automatically apply template trust for plugins that don't know how. """ # declared as class attrs to signal to ObjectProxy that we want them stored on the proxy, not the wrapped value _target_plugin = None _default_origin = None def __init__(self, referent: InventoryData, target_plugin: BaseInventoryPlugin, origin: Origin) -> None: super().__init__(referent) self._target_plugin = target_plugin # fallback origin to ensure that vars are tagged with at least the file they came from self._default_origin = origin @functools.cached_property def _inspector(self) -> _json.AnsibleVariableVisitor: """ Inventory plugins can delegate to other plugins (e.g. `auto`). This hack defers sampling the target plugin's `trusted_by_default` attr until `set_variable` is called, typically inside `parse`. Trust is then optionally applied based on the plugin's declared intent via `trusted_by_default`. """ return _json.AnsibleVariableVisitor( trusted_as_template=self._target_plugin.trusted_by_default, origin=self._default_origin, encrypted_string_behavior=EncryptedStringBehavior.PRESERVE, ) def set_variable(self, entity: str, varname: str, value: t.Any) -> None: self.__wrapped__.set_variable(entity, varname, self._inspector.visit(value))
_InventoryDataWrapper
python
jina-ai__jina
tests/unit/orchestrate/deployments/test_deployments.py
{ "start": 5558, "end": 8032 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name = self.runtime_args.name @requests def foo(self, docs: DocumentArray, **kwargs): for doc in docs: doc.text = str(self.name) @pytest.mark.slow def test_pod_in_flow_activates_shards_replicas(): shards = 2 replicas = 3 args_list = ['--replicas', str(replicas), '--shards', str(shards), '--no-reduce'] args = set_deployment_parser().parse_args(args_list) args.uses = 'SetNameExecutor' with Deployment(args, include_gateway=False) as pod: assert pod.num_pods == 7 response_texts = set() # replicas and shards are used in a round robin fashion, so sending 6 requests should hit each one time for _ in range(6): response = send_request_sync( _create_test_data_message(), f'{pod.head_args.host}:{pod.head_args.port[0]}', ) response_texts.update(response.response.docs.texts) print(response_texts) assert 6 == len(response_texts) assert all( text in response_texts for text in [ f'executor/shard-{s}/rep-{r}' for s in range(shards) for r in range(replicas) ] ) Deployment(args, include_gateway=False).start().close() @pytest.mark.slow @pytest.mark.parametrize('shards', [1, 2]) @pytest.mark.parametrize('replicas', [1, 2, 3]) def test_standalone_deployment_activates_shards_replicas(shards, replicas): with Deployment( shards=shards, replicas=replicas, uses=SetNameExecutor, ) as dep: head_exists = 0 if shards == 1 else 1 assert dep.num_pods == shards * replicas + 1 + head_exists response_texts = set() # replicas and shards are used in a round robin fashion, so sending shards * replicas requests should hit each one time docs = dep.post(on='/', inputs=DocumentArray.empty(20), request_size=1) response_texts.update(docs.texts) print(response_texts) assert shards * replicas == len(response_texts) assert all( text in response_texts for text in [ f'executor/shard-{s}/rep-{r}' if shards > 1 else f'executor/rep-{r}' for s in range(shards) for r in range(replicas) ] )
SetNameExecutor
python
pytorch__pytorch
test/jit/test_convert_activation.py
{ "start": 4326, "end": 6437 }
class ____(JitTestCase): def test_inplace_to_functional_activation(self): for activation in activations: def test_basic(x): y = x + 1 activation(y, inplace=True) return y fn = torch.jit.script(test_basic) self.run_pass("inline", fn.graph) self.run_pass("constant_propagation", fn.graph) FileCheck().check(f"aten::{activation.__name__}_").run(fn.graph) self.run_pass("inplace_to_functional_activation", fn.graph) FileCheck().check_not(f"aten::{activation.__name__}_").run(fn.graph) FileCheck().check(f"aten::{activation.__name__}(").run(fn.graph) for activation in [ torch.relu_, torch.sigmoid_, torch.tanh_, ]: def test_basic(x): y = x + 1 activation(y) return y fn = torch.jit.script(test_basic) self.run_pass("inline", fn.graph) self.run_pass("constant_propagation", fn.graph) FileCheck().check(f"aten::{activation.__name__}").run(fn.graph) self.run_pass("inplace_to_functional_activation", fn.graph) FileCheck().check_not(f"aten::{activation.__name__}").run(fn.graph) FileCheck().check(f"aten::{activation.__name__[:-1]}(").run(fn.graph) inp = torch.rand([2, 2]) self.assertEqual(fn(inp), test_basic(inp)) @skipIfNoTorchVision def test_resnet18_correctness(self): model = torchvision.models.resnet18() frozen_model = torch.jit.freeze(torch.jit.script(model.eval())) ( N, C, H, W, ) = ( 10, 3, 224, 224, ) inp = torch.randn(N, C, H, W) self.run_pass("inplace_to_functional_activation", frozen_model.graph) self.assertEqual(model(inp), frozen_model(inp)) if __name__ == "__main__": raise_on_run_directly("test/test_jit.py")
TestInplaceToFunctionalActivation
python
lazyprogrammer__machine_learning_examples
unsupervised_class2/rbm.py
{ "start": 581, "end": 4520 }
class ____(object): def __init__(self, M, an_id): self.M = M self.id = an_id self.rng = RandomStreams() def fit(self, X, learning_rate=0.1, epochs=1, batch_sz=100, show_fig=False): # cast to float32 learning_rate = np.float32(learning_rate) N, D = X.shape n_batches = N // batch_sz W0 = init_weights((D, self.M)) self.W = theano.shared(W0, 'W_%s' % self.id) self.c = theano.shared(np.zeros(self.M), 'c_%s' % self.id) self.b = theano.shared(np.zeros(D), 'b_%s' % self.id) self.params = [self.W, self.c, self.b] self.forward_params = [self.W, self.c] X_in = T.matrix('X_%s' % self.id) # attach it to the object so it can be used later # must be sigmoidal because the output is also a sigmoid H = T.nnet.sigmoid(X_in.dot(self.W) + self.c) self.hidden_op = theano.function( inputs=[X_in], outputs=H, ) # we won't use this cost to do any updates # but we would like to see how this cost function changes # as we do contrastive divergence X_hat = self.forward_output(X_in) cost = -(X_in * T.log(X_hat) + (1 - X_in) * T.log(1 - X_hat)).mean() cost_op = theano.function( inputs=[X_in], outputs=cost, ) # do one round of Gibbs sampling to obtain X_sample H = self.sample_h_given_v(X_in) X_sample = self.sample_v_given_h(H) # define the objective, updates, and train function objective = T.mean(self.free_energy(X_in)) - T.mean(self.free_energy(X_sample)) # need to consider X_sample constant because you can't take the gradient of random numbers in Theano updates = [(p, p - learning_rate*T.grad(objective, p, consider_constant=[X_sample])) for p in self.params] train_op = theano.function( inputs=[X_in], updates=updates, ) costs = [] print("training rbm: %s" % self.id) for i in range(epochs): print("epoch:", i) X = shuffle(X) for j in range(n_batches): batch = X[j*batch_sz:(j*batch_sz + batch_sz)] train_op(batch) the_cost = cost_op(X) # technically we could also get the cost for Xtest here print("j / n_batches:", j, "/", n_batches, "cost:", the_cost) costs.append(the_cost) if show_fig: plt.plot(costs) plt.show() def free_energy(self, V): return -V.dot(self.b) - T.sum(T.log(1 + T.exp(V.dot(self.W) + self.c)), axis=1) def sample_h_given_v(self, V): p_h_given_v = T.nnet.sigmoid(V.dot(self.W) + self.c) h_sample = self.rng.binomial(size=p_h_given_v.shape, n=1, p=p_h_given_v) return h_sample def sample_v_given_h(self, H): p_v_given_h = T.nnet.sigmoid(H.dot(self.W.T) + self.b) v_sample = self.rng.binomial(size=p_v_given_h.shape, n=1, p=p_v_given_h) return v_sample def forward_hidden(self, X): return T.nnet.sigmoid(X.dot(self.W) + self.c) def forward_output(self, X): Z = self.forward_hidden(X) Y = T.nnet.sigmoid(Z.dot(self.W.T) + self.b) return Y @staticmethod def createFromArrays(W, c, b, an_id): rbm = AutoEncoder(W.shape[1], an_id) rbm.W = theano.shared(W, 'W_%s' % rbm.id) rbm.c = theano.shared(c, 'c_%s' % rbm.id) rbm.b = theano.shared(b, 'b_%s' % rbm.id) rbm.params = [rbm.W, rbm.c, rbm.b] rbm.forward_params = [rbm.W, rbm.c] return rbm def main(): Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST() dnn = DNN([1000, 750, 500], UnsupervisedModel=RBM) dnn.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=3) # we compare with no pretraining in autoencoder.py if __name__ == '__main__': main()
RBM
python
airbytehq__airbyte
airbyte-integrations/bases/base-normalization/normalization/destination_type.py
{ "start": 87, "end": 633 }
class ____(Enum): BIGQUERY = "bigquery" CLICKHOUSE = "clickhouse" MSSQL = "mssql" MYSQL = "mysql" ORACLE = "oracle" POSTGRES = "postgres" REDSHIFT = "redshift" SNOWFLAKE = "snowflake" TIDB = "tidb" DUCKDB = "duckdb" @classmethod def from_string(cls, string_value: str) -> "DestinationType": return DestinationType[string_value.upper()] @staticmethod def testable_destinations(): return [dest for dest in list(DestinationType) if dest != DestinationType.DUCKDB]
DestinationType
python
apache__airflow
providers/google/tests/unit/google/cloud/utils/test_field_validator.py
{ "start": 1008, "end": 11279 }
class ____: def test_validate_should_not_raise_exception_if_field_and_body_are_both_empty(self): specification = [] body = {} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_body_is_none(self): specification = [] body = None validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises( RuntimeError, match="The body to validate is `None`. Please provide a dictionary to validate." ): validator.validate(body) def test_validate_should_fail_if_specification_is_none(self): specification = None body = {} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(TypeError): validator.validate(body) def test_validate_should_raise_exception_name_attribute_is_missing_from_specs(self): specification = [dict(allow_empty=False)] body = {} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(KeyError): validator.validate(body) def test_validate_should_raise_exception_if_field_is_not_present(self): specification = [dict(name="name", allow_empty=False)] body = {} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_validate_a_single_field(self): specification = [dict(name="name", allow_empty=False)] body = {"name": "bigquery"} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_body_is_not_a_dict(self): specification = [dict(name="name", allow_empty=False)] body = [{"name": "bigquery"}] validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(AttributeError): validator.validate(body) def test_validate_should_fail_for_set_allow_empty_when_field_is_none(self): specification = [dict(name="name", allow_empty=True)] body = {"name": None} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_interpret_allow_empty_clause(self): specification = [dict(name="name", allow_empty=True)] body = {"name": ""} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_raise_if_empty_clause_is_false(self): specification = [dict(name="name", allow_empty=False)] body = {"name": None} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_raise_if_version_mismatch_is_found(self): specification = [dict(name="name", allow_empty=False, api_version="v2")] body = {"name": "value"} validator = GcpBodyFieldValidator(specification, "v1") validator.validate(body) def test_validate_should_interpret_optional_irrespective_of_allow_empty(self): specification = [dict(name="name", allow_empty=False, optional=True)] body = {"name": None} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_interpret_optional_clause(self): specification = [dict(name="name", allow_empty=False, optional=True)] body = {} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_raise_exception_if_optional_clause_is_false_and_field_not_present(self): specification = [dict(name="name", allow_empty=False, optional=False)] body = {} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_interpret_dict_type(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": {"one": "value"}} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_value_is_not_dict_as_per_specs(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": 1} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_not_allow_both_type_and_allow_empty_in_a_spec(self): specification = [dict(name="labels", optional=True, type="dict", allow_empty=True)] body = {"labels": 1} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpValidationSpecificationException): validator.validate(body) def test_validate_should_allow_type_and_optional_in_a_spec(self): specification = [dict(name="labels", optional=True, type="dict")] body = {"labels": {}} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_union_field_is_not_found(self): specification = [ dict( name="an_union", type="union", optional=False, fields=[ dict(name="variant_1", regexp=r"^.+$", optional=False, allow_empty=False), ], ) ] body = {} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_there_is_no_nested_field_for_union(self): specification = [dict(name="an_union", type="union", optional=False, fields=[])] body = {} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpValidationSpecificationException): validator.validate(body) def test_validate_should_interpret_union_with_one_field(self): specification = [ dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r"^.+$"), ], ) ] body = {"variant_1": "abc", "variant_2": "def"} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_if_both_field_of_union_is_present(self): specification = [ dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r"^.+$"), dict(name="variant_2", regexp=r"^.+$"), ], ) ] body = {"variant_1": "abc", "variant_2": "def"} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_validate_when_value_matches_regex(self): specification = [ dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r"[^a-z]"), ], ) ] body = {"variant_1": "12"} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_fail_when_value_does_not_match_regex(self): specification = [ dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r"[^a-z]"), ], ) ] body = {"variant_1": "abc"} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_raise_if_custom_validation_is_not_true(self): def _int_equal_to_zero(value): if int(value) != 0: raise GcpFieldValidationException("The available memory has to be equal to 0") specification = [dict(name="availableMemoryMb", custom_validation=_int_equal_to_zero)] body = {"availableMemoryMb": 1} validator = GcpBodyFieldValidator(specification, "v1") with pytest.raises(GcpFieldValidationException): validator.validate(body) def test_validate_should_not_raise_if_custom_validation_is_true(self): def _int_equal_to_zero(value): if int(value) != 0: raise GcpFieldValidationException("The available memory has to be equal to 0") specification = [dict(name="availableMemoryMb", custom_validation=_int_equal_to_zero)] body = {"availableMemoryMb": 0} validator = GcpBodyFieldValidator(specification, "v1") assert validator.validate(body) is None def test_validate_should_validate_group_of_specs(self): specification = [ dict(name="name", allow_empty=False), dict(name="description", allow_empty=False, optional=True), dict(name="labels", optional=True, type="dict"), dict( name="an_union", type="union", fields=[ dict(name="variant_1", regexp=r"^.+$"), dict(name="variant_2", regexp=r"^.+$", api_version="v1beta2"), dict(name="variant_3", type="dict", fields=[dict(name="url", regexp=r"^.+$")]), dict(name="variant_4"), ], ), ] body = {"variant_1": "abc", "name": "bigquery"} validator = GcpBodyFieldValidator(specification, "v1") validator.validate(body)
TestGcpBodyFieldValidator
python
walkccc__LeetCode
solutions/1129. Shortest Path with Alternating Colors/1129.py
{ "start": 77, "end": 914 }
class ____: def shortestAlternatingPaths( self, n: int, redEdges: list[list[int]], blueEdges: list[list[int]], ) -> list[int]: ans = [-1] * n graph = [[] for _ in range(n)] # graph[u] := [(v, edgeColor)] q = collections.deque([(0, Color.INIT)]) # [(u, prevColor)] for u, v in redEdges: graph[u].append((v, Color.RED)) for u, v in blueEdges: graph[u].append((v, Color.BLUE)) step = 0 while q: for _ in range(len(q)): u, prevColor = q.popleft() if ans[u] == -1: ans[u] = step for i, (v, edgeColor) in enumerate(graph[u]): if v == -1 or edgeColor == prevColor: continue q.append((v, edgeColor)) graph[u][i] = (-1, edgeColor) # Mark (u, v) as used. step += 1 return ans
Solution
python
huggingface__transformers
tests/models/electra/test_modeling_electra.py
{ "start": 23009, "end": 23791 }
class ____(unittest.TestCase): @slow def test_inference_no_head_absolute_embedding(self): model = ElectraModel.from_pretrained("google/electra-small-discriminator") input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]) attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) output = model(input_ids, attention_mask=attention_mask)[0] expected_shape = torch.Size((1, 11, 256)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [[[0.4471, 0.6821, -0.3265], [0.4627, 0.5255, -0.3668], [0.4532, 0.3313, -0.4344]]] ) torch.testing.assert_close(output[:, 1:4, 1:4], expected_slice, rtol=1e-4, atol=1e-4)
ElectraModelIntegrationTest
python
viewflow__viewflow
tests/contrib/test_contrib_admin.py
{ "start": 197, "end": 524 }
class ____(TestCase): fixtures = ['users.json'] def test_admin_viewset_entry(self): self.assertTrue(self.client.login(username='admin', password='admin')) response = self.client.get('/') self.assertRedirects(response, '/admin/') urlpatterns = [ path('', Site(viewsets=[Admin()]).urls) ]
Test
python
aimacode__aima-python
logic.py
{ "start": 3070, "end": 15626 }
class ____(KB): """A KB for propositional logic. Inefficient, with no indexing.""" def __init__(self, sentence=None): super().__init__(sentence) self.clauses = [] def tell(self, sentence): """Add the sentence's clauses to the KB.""" self.clauses.extend(conjuncts(to_cnf(sentence))) def ask_generator(self, query): """Yield the empty substitution {} if KB entails query; else no results.""" if tt_entails(Expr('&', *self.clauses), query): yield {} def ask_if_true(self, query): """Return True if the KB entails query, else return False.""" for _ in self.ask_generator(query): return True return False def retract(self, sentence): """Remove the sentence's clauses from the KB.""" for c in conjuncts(to_cnf(sentence)): if c in self.clauses: self.clauses.remove(c) # ______________________________________________________________________________ def KBAgentProgram(kb): """ [Figure 7.1] A generic logical knowledge-based agent program. """ steps = itertools.count() def program(percept): t = next(steps) kb.tell(make_percept_sentence(percept, t)) action = kb.ask(make_action_query(t)) kb.tell(make_action_sentence(action, t)) return action def make_percept_sentence(percept, t): return Expr('Percept')(percept, t) def make_action_query(t): return expr('ShouldDo(action, {})'.format(t)) def make_action_sentence(action, t): return Expr('Did')(action[expr('action')], t) return program def is_symbol(s): """A string s is a symbol if it starts with an alphabetic char. >>> is_symbol('R2D2') True """ return isinstance(s, str) and s[:1].isalpha() def is_var_symbol(s): """A logic variable symbol is an initial-lowercase string. >>> is_var_symbol('EXE') False """ return is_symbol(s) and s[0].islower() def is_prop_symbol(s): """A proposition logic symbol is an initial-uppercase string. >>> is_prop_symbol('exe') False """ return is_symbol(s) and s[0].isupper() def variables(s): """Return a set of the variables in expression s. >>> variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, 2)')) == {x, y, z} True """ return {x for x in subexpressions(s) if is_variable(x)} def is_definite_clause(s): """Returns True for exprs s of the form A & B & ... & C ==> D, where all literals are positive. In clause form, this is ~A | ~B | ... | ~C | D, where exactly one clause is positive. >>> is_definite_clause(expr('Farmer(Mac)')) True """ if is_symbol(s.op): return True elif s.op == '==>': antecedent, consequent = s.args return is_symbol(consequent.op) and all(is_symbol(arg.op) for arg in conjuncts(antecedent)) else: return False def parse_definite_clause(s): """Return the antecedents and the consequent of a definite clause.""" assert is_definite_clause(s) if is_symbol(s.op): return [], s else: antecedent, consequent = s.args return conjuncts(antecedent), consequent # Useful constant Exprs used in examples and code: A, B, C, D, E, F, G, P, Q, a, x, y, z, u = map(Expr, 'ABCDEFGPQaxyzu') # ______________________________________________________________________________ def tt_entails(kb, alpha): """ [Figure 7.10] Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. Note that the 'kb' should be an Expr which is a conjunction of clauses. >>> tt_entails(expr('P & Q'), expr('Q')) True """ assert not variables(alpha) symbols = list(prop_symbols(kb & alpha)) return tt_check_all(kb, alpha, symbols, {}) def tt_check_all(kb, alpha, symbols, model): """Auxiliary routine to implement tt_entails.""" if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else: return True else: P, rest = symbols[0], symbols[1:] return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and tt_check_all(kb, alpha, rest, extend(model, P, False))) def prop_symbols(x): """Return the set of all propositional symbols in x.""" if not isinstance(x, Expr): return set() elif is_prop_symbol(x.op): return {x} else: return {symbol for arg in x.args for symbol in prop_symbols(arg)} def constant_symbols(x): """Return the set of all constant symbols in x.""" if not isinstance(x, Expr): return set() elif is_prop_symbol(x.op) and not x.args: return {x} else: return {symbol for arg in x.args for symbol in constant_symbols(arg)} def predicate_symbols(x): """Return a set of (symbol_name, arity) in x. All symbols (even functional) with arity > 0 are considered.""" if not isinstance(x, Expr) or not x.args: return set() pred_set = {(x.op, len(x.args))} if is_prop_symbol(x.op) else set() pred_set.update({symbol for arg in x.args for symbol in predicate_symbols(arg)}) return pred_set def tt_true(s): """Is a propositional sentence a tautology? >>> tt_true('P | ~P') True """ s = expr(s) return tt_entails(True, s) def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological. >>> pl_true(P, {}) is None True """ if exp in (True, False): return exp op, args = exp.op, exp.args if is_prop_symbol(op): return model.get(exp) elif op == '~': p = pl_true(args[0], model) if p is None: return None else: return not p elif op == '|': result = False for arg in args: p = pl_true(arg, model) if p is True: return True if p is None: result = None return result elif op == '&': result = True for arg in args: p = pl_true(arg, model) if p is False: return False if p is None: result = None return result p, q = args if op == '==>': return pl_true(~p | q, model) elif op == '<==': return pl_true(p | ~q, model) pt = pl_true(p, model) if pt is None: return None qt = pl_true(q, model) if qt is None: return None if op == '<=>': return pt == qt elif op == '^': # xor or 'not equivalent' return pt != qt else: raise ValueError('Illegal operator in logic expression' + str(exp)) # ______________________________________________________________________________ # Convert to Conjunctive Normal Form (CNF) def to_cnf(s): """ [Page 253] Convert a propositional logical sentence to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) >>> to_cnf('~(B | C)') (~B & ~C) """ s = expr(s) if isinstance(s, str): s = expr(s) s = eliminate_implications(s) # Steps 1, 2 from p. 253 s = move_not_inwards(s) # Step 3 return distribute_and_over_or(s) # Step 4 def eliminate_implications(s): """Change implications into equivalent form with only &, |, and ~ as logical operators.""" s = expr(s) if not s.args or is_symbol(s.op): return s # Atoms are unchanged. args = list(map(eliminate_implications, s.args)) a, b = args[0], args[-1] if s.op == '==>': return b | ~a elif s.op == '<==': return a | ~b elif s.op == '<=>': return (a | ~b) & (b | ~a) elif s.op == '^': assert len(args) == 2 # TODO: relax this restriction return (a & ~b) | (~a & b) else: assert s.op in ('&', '|', '~') return Expr(s.op, *args) def move_not_inwards(s): """Rewrite sentence s by moving negation sign inward. >>> move_not_inwards(~(A | B)) (~A & ~B) """ s = expr(s) if s.op == '~': def NOT(b): return move_not_inwards(~b) a = s.args[0] if a.op == '~': return move_not_inwards(a.args[0]) # ~~A ==> A if a.op == '&': return associate('|', list(map(NOT, a.args))) if a.op == '|': return associate('&', list(map(NOT, a.args))) return s elif is_symbol(s.op) or not s.args: return s else: return Expr(s.op, *list(map(move_not_inwards, s.args))) def distribute_and_over_or(s): """Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ s = expr(s) if s.op == '|': s = associate('|', s.args) if s.op != '|': return distribute_and_over_or(s) if len(s.args) == 0: return False if len(s.args) == 1: return distribute_and_over_or(s.args[0]) conj = first(arg for arg in s.args if arg.op == '&') if not conj: return s others = [a for a in s.args if a is not conj] rest = associate('|', others) return associate('&', [distribute_and_over_or(c | rest) for c in conj.args]) elif s.op == '&': return associate('&', list(map(distribute_and_over_or, s.args))) else: return s def associate(op, args): """Given an associative op, return an expression with the same meaning as Expr(op, *args), but flattened -- that is, with nested instances of the same op promoted to the top level. >>> associate('&', [(A&B),(B|C),(B&C)]) (A & B & (B | C) & B & C) >>> associate('|', [A|(B|(C|(A&B)))]) (A | B | C | (A & B)) """ args = dissociate(op, args) if len(args) == 0: return _op_identity[op] elif len(args) == 1: return args[0] else: return Expr(op, *args) _op_identity = {'&': True, '|': False, '+': 0, '*': 1} def dissociate(op, args): """Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args). >>> dissociate('&', [A & B]) [A, B] """ result = [] def collect(subargs): for arg in subargs: if arg.op == op: collect(arg.args) else: result.append(arg) collect(args) return result def conjuncts(s): """Return a list of the conjuncts in the sentence s. >>> conjuncts(A & B) [A, B] >>> conjuncts(A | B) [(A | B)] """ return dissociate('&', [s]) def disjuncts(s): """Return a list of the disjuncts in the sentence s. >>> disjuncts(A | B) [A, B] >>> disjuncts(A & B) [(A & B)] """ return dissociate('|', [s]) # ______________________________________________________________________________ def pl_resolution(kb, alpha): """ [Figure 7.12] Propositional-logic resolution: say if alpha follows from KB. >>> pl_resolution(horn_clauses_KB, A) True """ clauses = kb.clauses + conjuncts(to_cnf(~alpha)) new = set() while True: n = len(clauses) pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i + 1, n)] for (ci, cj) in pairs: resolvents = pl_resolve(ci, cj) if False in resolvents: return True new = new.union(set(resolvents)) if new.issubset(set(clauses)): return False for c in new: if c not in clauses: clauses.append(c) def pl_resolve(ci, cj): """Return all clauses that can be obtained by resolving clauses ci and cj.""" clauses = [] for di in disjuncts(ci): for dj in disjuncts(cj): if di == ~dj or ~di == dj: clauses.append(associate('|', unique(remove_all(di, disjuncts(ci)) + remove_all(dj, disjuncts(cj))))) return clauses # ______________________________________________________________________________
PropKB
python
pytorch__pytorch
test/inductor/test_group_batch_fusion.py
{ "start": 9537, "end": 10394 }
class ____(torch.nn.Module): def __init__(self, device): super().__init__() self.device = device def forward(self, x): inputs = [x.to(self.device) for i in range(10)] others = [x.to(self.device) for i in range(10)] clamp_input = [x.clamp(min=-1000.1, max=1000.1) for x in inputs] clamp_other = [x.clamp(min=-1000.1, max=1000.1) for x in others] nan_to_num_input = [torch.nan_to_num(x, 0.0) for x in clamp_input] nan_to_num_other = [torch.nan_to_num(x, 0.0) for x in clamp_other] detach_input = [x.detach() for x in nan_to_num_input] detach_other = [x.detach() for x in nan_to_num_other] stack_input = torch.stack(detach_input, dim=0) stack_other = torch.stack(detach_other, dim=0) return torch.stack((stack_input, stack_other), dim=0)
TestMathOps
python
wandb__wandb
tests/system_tests/test_core/test_tb_watcher.py
{ "start": 44, "end": 1682 }
class ____: def test_simple(self): assert tb_watcher.is_tfevents_file_created_by( "out.writer.tfevents.193.me.94.5", "me", 193 ) def test_no_tfevents(self): assert ( tb_watcher.is_tfevents_file_created_by( "out.writer.tfevent.193.me.94.5", "me", 193 ) is False ) def test_short_prefix(self): assert ( tb_watcher.is_tfevents_file_created_by("tfevents.193.me.94.5", "me", 193) is True ) def test_too_early(self): assert ( tb_watcher.is_tfevents_file_created_by("tfevents.192.me.94.5", "me", 193) is False ) def test_dotted_hostname(self): assert ( tb_watcher.is_tfevents_file_created_by( "tfevents.193.me.you.us.94.5", "me.you.us", 193 ) is True ) def test_dotted_hostname_short(self): assert ( tb_watcher.is_tfevents_file_created_by( "tfevents.193.me.you", "me.you.us", 193 ) is False ) def test_invalid_time(self): assert ( tb_watcher.is_tfevents_file_created_by( "tfevents.allo!.me.you", "me.you.us", 193 ) is False ) def test_way_too_short(self): assert tb_watcher.is_tfevents_file_created_by("dir", "me.you.us", 193) is False def test_inverted(self): assert ( tb_watcher.is_tfevents_file_created_by("me.193.tfevents", "me", 193) is False )
TestIsTfEventsFileCreatedBy
python
getsentry__sentry
tests/snuba/search/test_backend.py
{ "start": 98360, "end": 114144 }
class ____(TestCase, SharedSnubaMixin, OccurrenceTestMixin): @property def backend(self): return EventsDatasetSnubaSearchBackend() def test_trends_sort_old_and_new_events(self) -> None: """Test that an issue with only one old event is ranked lower than an issue with only one new event""" new_project = self.create_project(organization=self.project.organization) base_datetime = before_now(days=3) recent_event = self.store_event( data={ "fingerprint": ["put-me-in-recent-group"], "event_id": "c" * 32, "message": "group1", "environment": "production", "tags": {"server": "example.com", "sentry:user": "event3@example.com"}, "timestamp": base_datetime.isoformat(), "stacktrace": {"frames": [{"module": "group1"}]}, }, project_id=new_project.id, ) old_event = self.store_event( data={ "fingerprint": ["put-me-in-old-group"], "event_id": "a" * 32, "message": "foo. Also, this message is intended to be greater than 256 characters so that we can put some unique string identifier after that point in the string. The purpose of this is in order to verify we are using snuba to search messages instead of Postgres (postgres truncates at 256 characters and clickhouse does not). santryrox.", "environment": "production", "tags": {"server": "example.com", "sentry:user": "old_event@example.com"}, "timestamp": (base_datetime - timedelta(days=20)).isoformat(), "stacktrace": {"frames": [{"module": "group1"}]}, }, project_id=new_project.id, ) # datetime(2017, 9, 6, 0, 0) old_event.data["timestamp"] = 1504656000.0 weights: TrendsSortWeights = { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": False, "norm": False, } results = self.make_query( sort_by="trends", projects=[new_project], aggregate_kwargs=weights, ) recent_group = Group.objects.get(id=recent_event.group.id) old_group = Group.objects.get(id=old_event.group.id) assert list(results) == [recent_group, old_group] def test_trends_sort_v2(self) -> None: """Test that the v2 formula works.""" new_project = self.create_project(organization=self.project.organization) base_datetime = before_now(days=3) recent_event = self.store_event( data={ "fingerprint": ["put-me-in-recent-group"], "event_id": "c" * 32, "message": "group1", "environment": "production", "tags": {"server": "example.com", "sentry:user": "event3@example.com"}, "timestamp": base_datetime.isoformat(), "stacktrace": {"frames": [{"module": "group1"}]}, }, project_id=new_project.id, ) old_event = self.store_event( data={ "fingerprint": ["put-me-in-old-group"], "event_id": "a" * 32, "message": "foo. Also, this message is intended to be greater than 256 characters so that we can put some unique string identifier after that point in the string. The purpose of this is in order to verify we are using snuba to search messages instead of Postgres (postgres truncates at 256 characters and clickhouse does not). santryrox.", "environment": "production", "tags": {"server": "example.com", "sentry:user": "old_event@example.com"}, "timestamp": (base_datetime - timedelta(days=20)).isoformat(), "stacktrace": {"frames": [{"module": "group1"}]}, }, project_id=new_project.id, ) # datetime(2017, 9, 6, 0, 0) old_event.data["timestamp"] = 1504656000.0 weights: TrendsSortWeights = { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": True, "norm": False, } results = self.make_query( sort_by="trends", projects=[new_project], aggregate_kwargs=weights, ) recent_group = Group.objects.get(id=recent_event.group.id) old_group = Group.objects.get(id=old_event.group.id) assert list(results) == [recent_group, old_group] def test_trends_log_level_results(self) -> None: """Test that the scoring results change when we pass in different log level weights""" base_datetime = before_now(hours=1) event1 = self.store_event( data={ "fingerprint": ["put-me-in-group1"], "event_id": "c" * 32, "timestamp": (base_datetime - timedelta(hours=1)).isoformat(), "message": "foo", "stacktrace": {"frames": [{"module": "group1"}]}, "environment": "staging", "level": "fatal", }, project_id=self.project.id, ) event2 = self.store_event( data={ "fingerprint": ["put-me-in-group2"], "event_id": "d" * 32, "timestamp": base_datetime.isoformat(), "message": "bar", "stacktrace": {"frames": [{"module": "group2"}]}, "environment": "staging", "level": "error", }, project_id=self.project.id, ) group1 = Group.objects.get(id=event1.group.id) group2 = Group.objects.get(id=event2.group.id) agg_kwargs = { "trends": { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": False, "norm": False, } } query_executor = self.backend._get_query_executor() results_zero_log_level = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score_before = results_zero_log_level[0][1] group2_score_before = results_zero_log_level[1][1] # initially group 2's score is higher since it has a more recent event assert group2_score_before > group1_score_before agg_kwargs["trends"].update({"log_level": 5}) results2 = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score_after = results2[0][1] group2_score_after = results2[1][1] # ensure fatal has a higher score than error assert group1_score_after > group2_score_after def test_trends_has_stacktrace_results(self) -> None: """Test that the scoring results change when we pass in different has_stacktrace weights""" base_datetime = before_now(hours=1) agg_kwargs = { "trends": { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": False, "norm": False, } } query_executor = self.backend._get_query_executor() no_stacktrace_event = self.store_event( data={ "event_id": "d" * 32, "message": "oh no", "timestamp": (base_datetime - timedelta(hours=1)).isoformat(), }, project_id=self.project.id, ) group1 = Group.objects.get(id=no_stacktrace_event.group.id) stacktrace_event = self.store_event( data={ "event_id": "d" * 32, "exception": { "values": [ { "type": "AnError", "value": "Bad request", "stacktrace": { "frames": [ { "module": "<my module>", }, ] }, } ] }, "timestamp": (base_datetime - timedelta(hours=1)).isoformat(), }, project_id=self.project.id, ) group2 = Group.objects.get(id=stacktrace_event.group.id) results = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score = results[0][1] group2_score = results[1][1] assert group1_score == group2_score agg_kwargs["trends"].update({"has_stacktrace": 3}) results = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score = results[0][1] group2_score = results[1][1] # check that a group with an event with a stacktrace has a higher weight than one without assert group1_score < group2_score def test_trends_event_halflife_results(self) -> None: """Test that the scoring results change when we pass in different event halflife weights""" base_datetime = before_now(hours=1) event1 = self.store_event( data={ "fingerprint": ["put-me-in-group1"], "event_id": "a" * 32, "timestamp": (base_datetime - timedelta(hours=1)).isoformat(), "message": "foo", "stacktrace": {"frames": [{"module": "group1"}]}, "environment": "staging", "level": "fatal", }, project_id=self.project.id, ) event2 = self.store_event( data={ "fingerprint": ["put-me-in-group2"], "event_id": "b" * 32, "timestamp": base_datetime.isoformat(), "message": "bar", "stacktrace": {"frames": [{"module": "group2"}]}, "environment": "staging", "level": "error", }, project_id=self.project.id, ) group1 = Group.objects.get(id=event1.group.id) group2 = Group.objects.get(id=event2.group.id) agg_kwargs = { "trends": { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": False, "norm": False, } } query_executor = self.backend._get_query_executor() results = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score_before = results[0][1] group2_score_before = results[1][1] # initially group 2's score is higher since it has a more recent event assert group2_score_before > group1_score_before agg_kwargs["trends"].update({"event_halflife_hours": 2}) results = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[group1.id, group2.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] group1_score_after = results[0][1] group2_score_after = results[1][1] assert group1_score_after < group2_score_after def test_trends_mixed_group_types(self) -> None: base_datetime = before_now(hours=1) error_event = self.store_event( data={ "fingerprint": ["put-me-in-group1"], "event_id": "a" * 32, "timestamp": (base_datetime - timedelta(hours=1)).isoformat(), "message": "foo", "stacktrace": {"frames": [{"module": "group1"}]}, "environment": "staging", "level": "fatal", }, project_id=self.project.id, ) error_group = error_event.group profile_event_id = uuid.uuid4().hex _, group_info = self.process_occurrence( event_id=profile_event_id, project_id=self.project.id, event_data={ "title": "some problem", "platform": "python", "tags": {"my_tag": "1"}, "timestamp": before_now(minutes=1).isoformat(), "received": before_now(minutes=1).isoformat(), }, ) assert group_info is not None profile_group_1 = group_info.group agg_kwargs = { "trends": { "log_level": 0, "has_stacktrace": 0, "relative_volume": 1, "event_halflife_hours": 4, "issue_halflife_hours": 24 * 7, "v2": False, "norm": False, } } query_executor = self.backend._get_query_executor() results = query_executor.snuba_search( start=None, end=None, project_ids=[self.project.id], environment_ids=[], sort_field="trends", organization=self.organization, group_ids=[profile_group_1.id, error_group.id], limit=150, aggregate_kwargs=agg_kwargs, referrer=Referrer.TESTING_TEST, )[0] error_group_score = results[0][1] profile_group_score = results[1][1] assert error_group_score > 0 assert profile_group_score > 0
EventsTrendsTest
python
allegroai__clearml
clearml/backend_api/services/v2_13/queues.py
{ "start": 67441, "end": 68744 }
class ____(Response): """ Response of queues.move_task_forward endpoint. :param position: The new position of the task entry in the queue (index, -1 represents bottom of queue) :type position: int """ _service = "queues" _action = "move_task_forward" _version = "2.13" _schema = { "definitions": {}, "properties": { "position": { "description": "The new position of the task entry in the queue (index, -1 represents bottom of queue)", "type": ["integer", "null"], } }, "type": "object", } def __init__(self, position: Optional[int] = None, **kwargs: Any) -> None: super(MoveTaskForwardResponse, self).__init__(**kwargs) self.position = position @schema_property("position") def position(self) -> Optional[int]: return self._property_position @position.setter def position(self, value: Optional[int]) -> None: if value is None: self._property_position = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "position", six.integer_types) self._property_position = value
MoveTaskForwardResponse
python
viewflow__viewflow
viewflow/workflow/nodes/job.py
{ "start": 286, "end": 2480 }
class ____(mixins.NextNodeActivationMixin, Activation): @classmethod def create(cls, flow_task, prev_activation, token, data=None, seed=None): """Instantiate and persist new flow task.""" flow_class = flow_task.flow_class task = flow_class.task_class( process=prev_activation.process, flow_task=flow_task, token=token, external_task_id=str(uuid.uuid4()), ) task.data = data if data is not None else {} task.seed = seed task.save() task.previous.add(prev_activation.task) return cls(task) @Activation.status.transition(source=STATUS.SCHEDULED, target=STATUS.STARTED) def start(self): self.task.started = timezone.now() self.task.save() @Activation.status.transition(source=STATUS.STARTED) def resume(self): pass @Activation.status.transition(source=STATUS.STARTED, target=STATUS.DONE) def complete(self): super().complete.original() @Activation.status.transition(source=STATUS.STARTED) def execute(self): self.complete() with Context(propagate_exception=False): self.activate_next() @Activation.status.transition(source=STATUS.STARTED, target=STATUS.ERROR) def error(self, exception): if not self.task.data: self.task.data = {} tb = exception.__traceback__ while tb.tb_next: tb = tb.tb_next try: serialized_locals = json.dumps( tb.tb_frame.f_locals, default=lambda obj: str(obj) ) except Exception as ex: serialized_locals = json.dumps({"_serialization_exception": str(ex)}) self.task.data["_exception"] = { "title": str(exception), "traceback": traceback.format_exc(), "locals": json.loads(serialized_locals), } self.task.finished = timezone.now() self.task.save() task_failed.send(sender=self.flow_class, process=self.process, task=self.task) def ref(self): return f"{get_flow_ref(self.flow_class)}/{self.process.pk}/{self.task.pk}"
AbstractJobActivation
python
altair-viz__altair
altair/vegalite/v6/api.py
{ "start": 22788, "end": 23562 }
class ____(TypedDict, closed=True, total=False): # type: ignore[call-arg] # https://peps.python.org/pep-0728/ # Likely a Field predicate empty: Optional[bool] param: Parameter | str test: _TestPredicateType value: Any __extra_items__: _StatementType | OneOrSeq[PrimitiveValue_T] _Condition: TypeAlias = _ConditionExtra """ A singular, *possibly* non-chainable condition produced by ``.when()``. The default **permissive** representation. Allows arbitrary additional keys that *may* be present in a `Conditional Field`_ but not a `Conditional Value`_. .. _Conditional Field: https://vega.github.io/vega-lite/docs/condition.html#field .. _Conditional Value: https://vega.github.io/vega-lite/docs/condition.html#value """
_ConditionExtra
python
huggingface__transformers
examples/modular-transformers/modular_my_new_model2.py
{ "start": 1527, "end": 1612 }
class ____(GemmaForSequenceClassification): pass
MyNewModel2ForSequenceClassification
python
kamyu104__LeetCode-Solutions
Python/similar-string-groups.py
{ "start": 99, "end": 654 }
class ____(object): def __init__(self, n): self.set = range(n) self.__size = n def find_set(self, x): if self.set[x] != x: self.set[x] = self.find_set(self.set[x]) # path compression. return self.set[x] def union_set(self, x, y): x_root, y_root = map(self.find_set, (x, y)) if x_root == y_root: return False self.set[min(x_root, y_root)] = max(x_root, y_root) self.__size -= 1 return True def size(self): return self.__size
UnionFind
python
jazzband__tablib
src/tablib/exceptions.py
{ "start": 540, "end": 635 }
class ____(TablibException, NotImplementedError): """Format not supported."""
UnsupportedFormat
python
tensorflow__tensorflow
tensorflow/lite/python/op_hint.py
{ "start": 27454, "end": 52962 }
class ____: """Represent a TensorFlow Lite custom function. This is uses to accumulate found hints in the graphdef into a single conceptual unit. Attributes: inputs: inputs to the op (hash from index # to argument) outputs: outputs to the op (hash from index # to argument) function_name: the tflite custom op name to use uuid: a unique call id for this particular call (i.e. multiple function calls would have the same function_name but different uuids. params: A param name to key value for op constant data. I.e. for axis on a reduction, strides on a convolution, etc. level: Level of the OpHint. children_inputs_mappings: If the Ophint has children, children inputs mappings indicate how their inputs & outputs are mapped. """ def __init__(self): self.inputs = {} self.outputs = {} self.function_name = None self.uuid = None self.params = {} self.level = -1 self.children_inputs_mappings = {} def flattened_inputs_and_outputs(self): """Return a list of inputs and outputs in a flattened format. Returns: Tuple of (inputs, outputs). where input and output i a list of names. """ def _flatten(input_or_output_dict): flattened_items = [] for item in input_or_output_dict.values(): flattened_items.extend(item.flatten()) return flattened_items return _flatten(self.inputs), _flatten(self.outputs) def __str__(self): def format_args(items): s = "" for idx, item in items.iteritems(): s += ("\t\t%d:\n" % idx) + str(item) return s inputs_str = "\tInputs\n" + format_args(self.inputs) outputs_str = "\tOutputs\n" + format_args(self.outputs) return ( "tflite function %s call %s level %d " "\n\tinputs:\n\t\t%s\n\toutputs:\n\t\t%s" % (self.function_name, self.uuid, self.level, inputs_str, outputs_str)) def _find_all_hints_in_nodes(nodes): """Look at the all the input nodes and return a list of LiteFuncCall objs. Args: nodes: A TensorFlow graph_def to look for LiteFuncCalls. Returns: a list of `LifeFuncCall` objects in the form """ func_calls = _collections.defaultdict(_LiteFuncCall) for node in nodes: attr = node.attr # This is an op hint if it has a FUNCTION_UUID_ATTR, otherwise skip if (OpHint.FUNCTION_UUID_ATTR not in attr or not attr[OpHint.FUNCTION_UUID_ATTR].s): continue uuid = attr[OpHint.FUNCTION_UUID_ATTR].s # Start building function call_def = func_calls[uuid] call_def.uuid = uuid call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s call_def.level = attr[OpHint.FUNCTION_LEVEL_ATTR].i # Get sorting and aggregation information sort = ( attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None) if sort == -1: sort = None aggregation = None if OpHint.FUNCTION_AGGREGATE_ATTR in attr: aggregation = _compat.as_text(attr[OpHint.FUNCTION_AGGREGATE_ATTR].s) if OpHint.CHILDREN_INPUTS_MAPPINGS in attr: call_def.children_inputs_mappings = _json.loads( _compat.as_text(attr[OpHint.CHILDREN_INPUTS_MAPPINGS].s)) # Add the input or output def put_operand(stuff, index, sort, operand, aggregation): """Add a given index into the function structure.""" if sort is None: stuff[index] = _LiteSingleOperand(operand) else: if index not in stuff: stuff[index] = _LiteAggregateOperand(aggregation) stuff[index].add(sort, operand) if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i, sort, node, aggregation) if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr: put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i, sort, node, aggregation) # Remember attributes for a in attr: if a.startswith("_tflite_attr_"): call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor return func_calls def _extract_topology_sequence_mapping(nodes): return dict( (_tensor_name_base(node.name), idx) for idx, node in enumerate(nodes)) def _find_children_hints_in_while_loop(function_def, nodes_mapping): """Find children hints and all nodes inside the while loop. Args: function_def: Function def of the while loop. nodes_mapping: While loop input_arg : real node name. Returns: Ordered children hints and all re-mapped nodes inside the while loop. """ new_nodes = [] # Make nodes inside function def inputs point to the real nodes. for node in function_def.node_def: for i, _ in enumerate(node.input): if node.input[i] in nodes_mapping: node.input[i] = nodes_mapping[node.input[i]] new_nodes.append(_copy.deepcopy(node)) name_to_seq_num = _extract_topology_sequence_mapping(function_def.node_def) children_hints = _find_all_hints_in_nodes(new_nodes) children_hints_q = [] # Ordered by the outputs. for hint in children_hints.values(): _, output_names = hint.flattened_inputs_and_outputs() seq = name_to_seq_num[output_names[0]] for output_name in output_names: seq = min(seq, name_to_seq_num[output_name]) children_hints_q.append((seq, hint)) children_hints_q.sort(key=lambda tup: tup[0]) ordered_children_hints = [x[1] for x in children_hints_q] return ordered_children_hints, new_nodes def _find_children_hints(call, graph_def): """Find all children hints. For a given OpHint, we find all children hints inside it, we also copy all the nodes inside function defs (if applicable) to the original graph_def, they are returned in a list as well. Args: call: Parent OpHint that contains children ophints. graph_def: Original graph def. Returns: Ordered children hints inside the parent ophint; new graph def that contains nodes inside function defs (if applicable); nodes inside function defs. """ name_to_input_name, _, _ = _extract_graph_summary(graph_def) input_names, output_names = call.flattened_inputs_and_outputs() reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name) reachable_by_output = _bfs_for_reachable_nodes(output_names, name_to_input_name) output_nodes_set = set(output_names) children_hints = [] out = _graph_pb2.GraphDef() out.library.CopyFrom(graph_def.library) out.versions.CopyFrom(graph_def.versions) function_def_nodes = set() for node in graph_def.node: out.node.extend([_copy.deepcopy(node)]) n = _tensor_name_base(node.name) if n in reachable_by_output: if n not in reachable_by_input and n not in output_nodes_set: # special handle for while loop function def. if node.op == "While" or node.op == "StatelessWhile": body_name = node.attr["body"].func.name inputs_outside_loop = node.input for function_def in graph_def.library.function: if function_def.signature.name == body_name: function_inputs = function_def.signature.input_arg assert len(inputs_outside_loop) == len(function_inputs) nodes_mapping = {} for i, function_input in enumerate(function_inputs): nodes_mapping[function_input.name] = inputs_outside_loop[i] (children_hints_in_loop, new_nodes) = _find_children_hints_in_while_loop( function_def, nodes_mapping) function_def_nodes.update([x.name for x in new_nodes]) children_hints.extend(children_hints_in_loop) out.node.extend(new_nodes) return children_hints, out, function_def_nodes def _tensor_name_base(full_tensor_name): """Removes the device assignment code from a tensor. e.g. _tensor_name_base("foo:3") => "foo" Args: full_tensor_name: A tensor name that is annotated with a device placement (this is what tensor flow introspection gives). Returns: A name without any device assignment. """ if full_tensor_name.startswith("^"): return full_tensor_name[1:] return full_tensor_name.split(":")[0] def _tensorflow_output_name(tensor_name, output_index): return tensor_name if output_index == 0 else "%s:%d" % (tensor_name, output_index) def _check_subgraph_closed(n, reachable_by_input, input_nodes_set, name_to_input_name): """Checks to make sure node only connects to predecessor graph through inputs. Args: n: Node to check reachable_by_input: Nodes that are reachable by all inputs of subgraph input_nodes_set: The set of nodes that are "inputs". name_to_input_name: Maps from name to the list of inputs. Raises: TypeError: If the given node uses items past inputs directly. """ next_to_visit = [n] visited = set() while next_to_visit: current_node = next_to_visit.pop() visited.add(current_node) if (current_node in reachable_by_input and current_node not in input_nodes_set): raise TypeError("Node %s uses input %s not in input_nodes." % (n, current_node)) if current_node not in input_nodes_set: next_to_visit += [ input_node for input_node in name_to_input_name[current_node] if input_node not in visited ] def _convert_single_op_hint_to_stub(call, graph_def, function_def_nodes=None, is_last_run=True): """Given a graph_def, converts `call` into a stub and returns a new graph_def. Args: call: A single function call to be converted. graph_def: A graph_def to use as input (that has call obviously). function_def_nodes: Nodes inside the function def those are not connected to the graph. is_last_run: Whether it is the last run for a given pass (for OpHint has children). Returns: A new transformed graph-def that has call as a stub (single op). Note: after this process, the graph_def can no longer be loaded into the tensorflow runtime, so all future manipulations are done in graph_def level. """ if function_def_nodes is None: function_def_nodes = set() name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( graph_def) input_names, output_names = call.flattened_inputs_and_outputs() reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name) reachable_by_output = _bfs_for_reachable_nodes(output_names, name_to_input_name) output_nodes_set = set(output_names) nodes_after_fuse = [] nodes_deleted_by_fuse = set() # Classify each node. We want to keep everything reachable by input, but # we don't know if things that are not reachable by output or input (things # after fusing). for node in graph_def.node: n = _tensor_name_base(node.name) if n in reachable_by_output: if n not in reachable_by_input and n not in output_nodes_set: nodes_deleted_by_fuse.add(n) elif n not in reachable_by_input and n not in function_def_nodes: # n is a node that after all the fusings, so keep it. nodes_after_fuse.append(n) else: # In the last run, n is a node that is randomly in the graph but not # connected to the chain of dependencies, we will delete n, otherwise # we keep them. if not is_last_run: nodes_after_fuse.append(n) # Make a new graphdef with all the pre-input and input nodes out = _graph_pb2.GraphDef() reachable_by_input_sorted = sorted( list(reachable_by_input), key=lambda n: name_to_seq_num[n]) for node in reachable_by_input_sorted: out.node.extend([_copy.deepcopy(name_to_node[node])]) # Create any stacks to aggregate arguments into to a single input # i.e. for static_rnn's. sorted_input_indices = list(call.inputs.keys()) sorted_input_indices.sort() sorted_output_indices = list(call.outputs.keys()) sorted_output_indices.sort() new_node = _node_def_pb2.NodeDef() # Delegate to each operand to produce the proper new input for this stub node. # In particular, an aggregate input will now be a Pack of some previously # non-fused things. optional_input_node = _node_def_pb2.NodeDef() optional_input_node.name = "Const" + str(_uuid.uuid1().hex) optional_input_node.op = "Const" optional_input_node.attr["dtype"].CopyFrom( _attr_value_pb2.AttrValue(type=_dtypes.float32.as_datatype_enum)) optional_input_node.attr["value"].CopyFrom( _attr_value_pb2.AttrValue( tensor=_tensor_util.make_tensor_proto([-1], _dtypes.float32, [1]))) out.node.extend([optional_input_node]) max_index = max(sorted_input_indices) + 1 for cur_index in range(max_index): if cur_index in sorted_input_indices: inputs = call.inputs[cur_index] input_name = inputs.aggregate_and_return_name_for_input(out) new_node.input.append(input_name) else: new_node.input.append(optional_input_node.name) new_node.attr[OpHint.TFLITE_INPUT_INDICES].list.i.extend(sorted_input_indices) # Create the function new_node.op = call.function_name new_node.name = call.uuid out.node.extend([new_node]) # Now call each output argument to give them a chance to make the proper # output type and add it to our new_node. output_dtypes = [] max_output_index = max(sorted_output_indices) + 1 for cur_index in range(max_output_index): if cur_index in sorted_output_indices: output = call.outputs[cur_index] output_dtype = ( output.aggregate_and_return_name_for_output(new_node.name, cur_index, out)) else: output_dtype = optional_input_node.attr["type"].i output_dtypes.append(output_dtype) new_node.attr["_output_types"].list.type[:] = output_dtypes new_node.attr["_output_quantized"].b = False # Add post output nodes that do not depend on the outputs for n in nodes_after_fuse: should_keep = True for input_name in name_to_input_name[n]: if input_name in nodes_deleted_by_fuse: should_keep = False if should_keep: out.node.extend([_copy.deepcopy(name_to_node[n])]) # Misc. graph_def data that needs copying. out.library.CopyFrom(graph_def.library) out.versions.CopyFrom(graph_def.versions) return out def _remove_one_redundant_stack_unstack(in_graph_def): """Removes a stack->unstack pattern from in_graph_def in a returned graph. Args: in_graph_def: Graph def to use as input. Returns: Simplified tuple (graph_def, changed_something) where changed_something is true if anything was done. """ name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( in_graph_def) del name_to_seq_num do_generic_pack_unpack = True out = _graph_pb2.GraphDef() out.library.CopyFrom(in_graph_def.library) out.versions.CopyFrom(in_graph_def.versions) for n in in_graph_def.node: node_name = _tensor_name_base(n.name) if not node_name.startswith("OpHintStack") and not n.op.startswith("Pack"): continue next_to_visit = [node_name] visited = set() unpack_nodes = set() pack_node = node_name # Find a pattern of unstack connected to a stack (with identities # in between. matches_pattern = True is_hint_created_stack = False while next_to_visit: current_node_name = next_to_visit[0] visited.add(current_node_name) del next_to_visit[0] node = name_to_node[current_node_name] is_op_hint_stack = node.name.startswith("OpHintStack") is_op_hint_unstack = node.name.startswith("OpHintUnstack") if (node.op == "Identity" or is_op_hint_stack or (do_generic_pack_unpack and node.op == "Pack")): is_hint_created_stack |= is_op_hint_stack next_to_visit += [ input_node for input_node in name_to_input_name[current_node_name] if input_node not in visited ] elif (is_op_hint_unstack or (do_generic_pack_unpack and node.op == "Unpack")): unpack_nodes.add(node.name) is_hint_created_stack &= is_op_hint_unstack else: matches_pattern = False break visited.add(node.name) if matches_pattern and len(unpack_nodes) == 1: pack_node = node_name # Check to see if anyone depends on the intermediate identity or the # Unstacked form no_external_dependency = True for other_n in in_graph_def.node: if other_n.name in visited: continue for input_tensor in name_to_input_name[other_n.name]: input_op = _tensor_name_base(input_tensor) if input_op in visited and input_op != pack_node: no_external_dependency = False # Proceed with the substitution if the stack/unstack pair was created # through hints, or that it was not, but nobody is consuming things # between the stack and unstack. if is_hint_created_stack or no_external_dependency: end = unpack_nodes.pop() end_input = name_to_node[end].input[0] # All nodes that depend on the final stack need to be redone to use for other_n in in_graph_def.node: node_name = _tensor_name_base(other_n.name) if node_name not in visited: new_node = _copy.deepcopy(other_n) new_node.input[:] = [ (end_input if stripped == pack_node else non_stripped) for stripped, non_stripped in zip(name_to_input_name[node_name], new_node.input[:]) ] out.node.extend([new_node]) return out, True return in_graph_def, False def _remove_redundant_stack_unstack(graph_def): curr = graph_def del graph_def changed_stuff = True while changed_stuff: curr, changed_stuff = _remove_one_redundant_stack_unstack(curr) return curr def _get_correct_mapping(original_index, nodes): # Special handle for the index is -1 case. # If it is -1, return the last index. if original_index == -1: node_indices = nodes.keys() node_indices = sorted(node_indices) return node_indices[-1] return original_index def _convert_op_hints_to_stubs_helper( graph_def, write_callback=lambda sess, graph_def: None): """Converts a graph_def to a new graph_def where all op hints are stubbed. Args: graph_def: A graph def that we should convert. write_callback: A function pointer that can be used to write intermediate steps of graph transformation (optional). Returns: A new stubbed graph_def. """ hints = _find_all_hints_in_nodes(graph_def.node) hints_q = [] for hint in hints.values(): hints_q.append((hint.level, hint.uuid)) hints_q.sort(key=lambda tup: tup[0]) for i in range(len(hints_q) - 1, -1, -1): level, hint_uuid = hints_q[i] curr_graph_def = graph_def del graph_def # prevent using graph_def again (common source of error) for i in range(len(hints_q) - 1, -1, -1): level, hint_uuid = hints_q[i] if level >= 2: children_hints, curr_graph_def, function_def_nodes = _find_children_hints( hints[hint_uuid], curr_graph_def) # pylint: disable=superfluous-parens assert (len(children_hints) > 0) # pylint: disable=g-explicit-length-test # pylint: enable=superfluous-parens # Re-wire the children hints inputs/outputs, so latter child's inputs # connect to previous child node's outputs. children_inputs_mappings = hints[hint_uuid].children_inputs_mappings for j, child_hint in enumerate(children_hints): if j == 0: for mapping in children_inputs_mappings["parent_first_child_input"]: parent_input_index = _get_correct_mapping( mapping["parent_ophint_input_index"], hints[hint_uuid].inputs) child_input_index = _get_correct_mapping( mapping["first_child_ophint_input_index"], child_hint.inputs) child_hint.inputs[child_input_index] = hints[hint_uuid].inputs[ parent_input_index] else: for mapping in children_inputs_mappings[ "internal_children_input_output"]: input_index = _get_correct_mapping(mapping["child_input_index"], child_hint.inputs) output_index = _get_correct_mapping(mapping["child_output_index"], children_hints[j - 1].outputs) child_hint.inputs[input_index] = children_hints[ j - 1].outputs[output_index] if j == len(children_hints) - 1: for mapping in children_inputs_mappings["parent_last_child_output"]: parent_output_index = _get_correct_mapping( mapping["parent_output_index"], hints[hint_uuid].outputs) child_output_index = _get_correct_mapping( mapping["child_output_index"], child_hint.outputs) child_hint.outputs[child_output_index] = hints[hint_uuid].outputs[ parent_output_index] for j, child_hint in enumerate(children_hints): curr_graph_def = _convert_single_op_hint_to_stub( child_hint, curr_graph_def, function_def_nodes, j == len(children_hints) - 1) else: curr_graph_def = _convert_single_op_hint_to_stub(hints[hint_uuid], curr_graph_def) write_callback(curr_graph_def, "initial") # The stubbing process can create stacks/unstacks in the case of LSTMs # remove them. curr_graph_def = _remove_redundant_stack_unstack(curr_graph_def) return curr_graph_def def find_all_hinted_output_nodes(session=None, graph_def=None): """Find all Ophints output nodes in the graph. This is used to get all the output nodes those are ophinted, it is important for operation like convert_variables_to_constants keep all ophints structure. Note: only one of session or graph_def should be used, not both. Why this can be useful? Some TensorFlow ops (e.g. bidirectional rnn), can generate multiple outputs for unfused subgraph. If not all output nodes are consumed, graph optimization can potentially drop the unused nodes and cause ophints in an invalid states (due to missing ophinted output nodes). So it's important for us to find all those hinted output nodes and make sure they're not discarded away. Args: session: A TensorFlow session that contains the graph to convert. graph_def: A graph def that we should convert. Returns: A list of OpHints output nodes. Raises: ValueError: If both session and graph_def are provided. """ if session is not None and graph_def is not None: raise ValueError("Provide only one of session and graph_def.") hinted_outputs_nodes = [] if session is not None: hints = _find_all_hints_in_nodes(session.graph_def.node) elif graph_def is not None: hints = _find_all_hints_in_nodes(graph_def.node) for hint in hints.values(): _, output_nodes = hint.flattened_inputs_and_outputs() hinted_outputs_nodes.extend(output_nodes) return hinted_outputs_nodes def is_ophint_converted(graph_def): if graph_def is None: raise ValueError("Must provide the graph_def.") ophint_converted = False for node in graph_def.node: attr = node.attr if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: ophint_converted = True break return ophint_converted @_tf_export(v1=["lite.experimental.convert_op_hints_to_stubs"]) @_deprecation.deprecated( None, "Please follow instructions under " "https://www.tensorflow.org/lite/convert/operation_fusion for operation" "fusion in tflite." ) def convert_op_hints_to_stubs(session=None, graph_def=None, write_callback=lambda graph_def, comments: None): """Converts a graphdef with LiteOp hints into stub operations. This is used to prepare for toco conversion of complex intrinsic usages. Note: only one of session or graph_def should be used, not both. Args: session: A TensorFlow session that contains the graph to convert. graph_def: A graph def that we should convert. write_callback: A function pointer that can be used to write intermediate steps of graph transformation (optional). Returns: A new graphdef with all ops contained in OpHints being replaced by a single op call with the right parameters. Raises: ValueError: If both session and graph_def are provided. """ if session is not None and graph_def is not None: raise ValueError("Provide only one of session and graph_def.") if session is not None: return _convert_op_hints_to_stubs_helper(session.graph_def, write_callback) elif graph_def is not None: return _convert_op_hints_to_stubs_helper(graph_def, write_callback) else: raise ValueError("Must specify session or graph_def as input.") _allowed_symbols = [ "OpHint", "convert_op_hints_to_stubs", "convert_op_hints_to_stubs_new", "find_all_hinted_output_nodes", "is_ophint_converted", ] remove_undocumented(__name__, _allowed_symbols)
_LiteFuncCall
python
kamyu104__LeetCode-Solutions
Python/remove-covered-intervals.py
{ "start": 33, "end": 427 }
class ____(object): def removeCoveredIntervals(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda x: [x[0], -x[1]]) result, max_right = 0, 0 for left, right in intervals: result += int(right > max_right) max_right = max(max_right, right) return result
Solution
python
pallets__click
src/click/types.py
{ "start": 23787, "end": 24320 }
class ____(ParamType): name = "uuid" def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: import uuid if isinstance(value, uuid.UUID): return value value = value.strip() try: return uuid.UUID(value) except ValueError: self.fail( _("{value!r} is not a valid UUID.").format(value=value), param, ctx ) def __repr__(self) -> str: return "UUID"
UUIDParameterType
python
django__django
tests/model_inheritance/models.py
{ "start": 3545, "end": 3639 }
class ____: def __init__(self): self.other_attr = 1 super().__init__()
Mixin
python
has2k1__plotnine
tests/test_layout.py
{ "start": 4992, "end": 8282 }
class ____: g = ggplot(mtcars, aes(x="wt", y="mpg", color="gear")) + geom_point() def test_outside_legend_right_bottom(self): p = self.g + theme(legend_justification=0) assert p == "outside_legend_right_bottom" def test_outside_legend_left_top(self): p = self.g + theme( legend_position="left", legend_justification=1, ) assert p == "outside_legend_left_top" def test_outside_legend_bottom_left(self): p = self.g + theme( legend_position="bottom", legend_justification=0, ) assert p == "outside_legend_bottom_left" def test_outside_legend_top_right(self): p = self.g + theme( legend_position="top", legend_justification=1, ) assert p == "outside_legend_top_right" def test_inside_legend_left(self): p = self.g + theme( legend_position="inside", legend_justification="left", ) assert p == "inside_legend_left" def test_inside_legend_left2(self): p = self.g + theme( legend_position="inside", legend_justification=(0, 0.5), ) assert p == "inside_legend_left" def test_inside_legend_top(self): p = self.g + theme( legend_position="inside", legend_justification="top", ) assert p == "inside_legend_top" def test_inside_legend_top2(self): p = self.g + theme(legend_position=(0.5, 1)) assert p == "inside_legend_top" def test_inside_legend_top_right(self): p = self.g + theme( legend_position="inside", legend_justification=(1, 1), ) assert p == "inside_legend_top_right" def test_inside_legend_top_right2(self): p = self.g + theme( legend_position="inside", legend_position_inside=(1, 1), ) assert p == "inside_legend_top_right" def test_inside_legend_top_right3(self): p = ( self.g + guides(color=guide_colorbar(position="inside")) + theme(legend_position_inside=(1, 1)) ) assert p == "inside_legend_top_right" def test_inside_legend_top_right4(self): p = self.g + guides(color=guide_colorbar(position=(1, 1))) assert p == "inside_legend_top_right" def test_inside_legend_90pct_top_right(self): # Use an equal aspect ratio to easily check that the # top-right tip of the legend is at 90% along both dimensions p = self.g + theme( aspect_ratio=1, legend_position=(0.9, 0.9), legend_justification=(1, 1), ) assert p == "inside_legend_90pct_top_right" def test_justification_with_blank_title_and_text(self): p = ( self.g + aes(shape="factor(cyl)") + guides(color=guide_colorbar(position="top")) + theme( legend_justification_top="left", legend_justification_right="top", legend_text=element_blank(), legend_title=element_blank(), ) ) assert p == "justification_with_blank_title_and_text"
TestLegendPositioning
python
getsentry__sentry
src/sentry/analytics/events/sentry_app_deleted.py
{ "start": 75, "end": 227 }
class ____(analytics.Event): user_id: int organization_id: int sentry_app: str analytics.register(SentryAppDeletedEvent)
SentryAppDeletedEvent
python
ray-project__ray
python/ray/data/tests/test_partitioning.py
{ "start": 10817, "end": 12345 }
class ____: @pytest.mark.parametrize( "relative_path", ["year=1970/country=fr/data.csv", "1970/fr/data.csv"] ) def test_read_single_file( self, relative_path, tmp_path, block_type, ray_start_regular_shared ): path = os.path.join(tmp_path, relative_path) write_csv({"number": [1, 2, 3]}, path) ds = read_csv(path, partitioning=None, block_type=block_type) # `read_csv` shouldn't include fields like `year` and `country`.` assert list(ds.to_pandas().columns) == ["number"] @pytest.mark.parametrize( "relative_paths", [ ["year=1970/country=fr/data.csv", "year=1971/language=ir/data.csv"], ["year=1970/country=fr/data.csv", "year=1971/ir/data.csv"], ["year=1970/country=fr/data.csv", "year=1971/data.csv"], ["1970/fr/data.csv", "1971/data.csv"], ], ) @pytest.mark.skip # TODO: Unskip this test once #28869 is fixed. def test_read_files_with_mismatched_fields( self, relative_paths, tmp_path, block_type, ray_start_regular_shared ): paths = [ os.path.join(tmp_path, relative_path) for relative_path in relative_paths ] for path in paths: write_csv({"number": [0, 0, 0]}) # `read_csv` shouldn't raise an error if `partitioning` is set to `None`. read_csv(paths, partitioning=None, block_type=block_type) @pytest.mark.parametrize("block_type", [pd.DataFrame, pa.Table])
TestReadUnpartitionedFiles