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
huggingface__transformers
src/transformers/tokenization_python.py
{ "start": 1395, "end": 10825 }
class ____: """ Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass Loose reference https://en.wikipedia.org/wiki/Trie """ def __init__(self, *args): self.data = {} self._tokens = set() self._termination_char = "" self.update(*args) def update(self, *args): """ Updates the Trie with new tokens provided as arguments. Args: *args: Variable number of words to be added to the Trie. """ for token in tuple(*args): self.add(token) def add(self, word: str): """ Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation. The special key `""` in `self._termination_char` is used to represent termination. This function is idempotent, adding twice the same word will leave the trie unchanged Example: ```python >>> trie = Trie() >>> trie.add("Hello 友達") >>> trie.data {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} >>> trie.add("Hello") >>> trie.data {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ``` """ if not word: # Prevent empty string return self._tokens.add(word) ref = self.data for char in word: ref[char] = ref.setdefault(char, {}) ref = ref[char] ref[self._termination_char] = 1 def split(self, text: str) -> list[str]: """ Will look for the words added to the trie within `text`. Output is the original string split along the boundaries of the words found. This trie will match the longest possible word first ! Example: ```python >>> trie = Trie() >>> trie.split("[CLS] This is a extra_id_100") ["[CLS] This is a extra_id_100"] >>> trie.add("[CLS]") >>> trie.add("extra_id_1") >>> trie.add("extra_id_100") >>> trie.split("[CLS] This is a extra_id_100") ["[CLS]", " This is a ", "extra_id_100"] ``` """ # indexes are counted left of the chars index. # "hello", index 0, is left of h, index 1 is between h and e. # index 5 is right of the "o". # States are going to capture every possible start (indexes as above) # as keys, and have as values, a pointer to the position in the trie # where we're at. This is a partial match for now. # This enables to keep track of multiple matches while we're iterating # the string # If the trie contains, "blowing", and "lower" and we encounter the # string "blower", we need to split into ["b", "lower"]. # This is where we need to keep track of multiple possible starts. states = OrderedDict() # This will contain every indices where we need # to cut. # We force to cut at offset 0 and len(text) (added later) offsets = [0] # This is used by the lookahead which needs to skip over # some text where the full match exceeded the place in the initial # for loop skip = 0 # Main loop, Giving this algorithm O(n) complexity for current, current_char in enumerate(text): if skip and current < skip: # Prevents the lookahead for matching twice # like extra_id_100 and id_100 continue # This will track every state # that stop matching, we need to stop tracking them. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then # fail on "b", we need to remove 0 from the valid states. to_remove = set() # Whenever we found a match, we need to drop everything # this is a greedy algorithm, it will match on the first found token reset = False # In this case, we already have partial matches (But unfinished) for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. # Lookahead to match longest first # Important in case of extra_id_1 vs extra_id_100 # Here we are also actively looking for other earlier partial # matches # "[CLS]", "L", we need to match CLS even if L is special for lookstart, looktrie_pointer in states.items(): if lookstart > start: # This partial match is later, we can stop looking break elif lookstart < start: # This partial match is earlier, the trie pointer # was already updated, so index is + 1 lookahead_index = current + 1 end = current + 1 else: # Here lookstart == start and # looktrie_pointer == trie_pointer # It wasn't updated yet so indices are current ones lookahead_index = current end = current next_char = text[lookahead_index] if lookahead_index < len(text) else None if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index while next_char in looktrie_pointer: looktrie_pointer = looktrie_pointer[next_char] lookahead_index += 1 if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index if lookahead_index == len(text): # End of string break next_char = text[lookahead_index] # End lookahead # Storing and resetting offsets.append(start) offsets.append(end) reset = True break elif current_char in trie_pointer: # The current character being looked at has a match within the trie # update the pointer (it will be stored back into states later). trie_pointer = trie_pointer[current_char] # Storing back the new pointer into the states. # Partial matches got longer by one. states[start] = trie_pointer else: # The new character has not match in the trie, we need # to stop keeping track of this partial match. # We can't do it directly within the loop because of how # python iteration works to_remove.add(start) # Either clearing the full start (we found a real match) # Or clearing only the partial matches that didn't work. if reset: states = {} else: for start in to_remove: del states[start] # If this character is a starting character within the trie # start keeping track of this partial match. if current >= skip and current_char in self.data: states[current] = self.data[current_char] # We have a cut at the end with states. for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. end = len(text) offsets.append(start) offsets.append(end) # Longest cut is always the one with lower start so the first # item so we need to break. break return self.cut_text(text, offsets) def cut_text(self, text, offsets): # We have all the offsets now, we just need to do the actual splitting. # We need to eventually add the first part of the string and the eventual # last part. offsets.append(len(text)) tokens = [] start = 0 for end in offsets: if start > end: logger.error( "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it" " anyway." ) continue elif start == end: # This might happen if there's a match at index 0 # we're also preventing zero-width cuts in case of two # consecutive matches continue tokens.append(text[start:end]) start = end return tokens
Trie
python
cherrypy__cherrypy
cherrypy/test/test_caching.py
{ "start": 493, "end": 14654 }
class ____(helper.CPWebCase): @staticmethod def setup_server(): @cherrypy.config(**{'tools.caching.on': True}) class Root: def __init__(self): self.counter = 0 self.control_counter = 0 self.longlock = threading.Lock() @cherrypy.expose def index(self): self.counter += 1 msg = 'visit #%s' % self.counter return msg @cherrypy.expose def control(self): self.control_counter += 1 return 'visit #%s' % self.control_counter @cherrypy.expose def a_gif(self): cherrypy.response.headers['Last-Modified'] = ( httputil.HTTPDate() ) return gif_bytes @cherrypy.expose def long_process(self, seconds='1'): try: self.longlock.acquire() time.sleep(float(seconds)) finally: self.longlock.release() return 'success!' @cherrypy.expose def clear_cache(self, path): cherrypy._cache.store[cherrypy.request.base + path].clear() @cherrypy.config( **{ 'tools.caching.on': True, 'tools.response_headers.on': True, 'tools.response_headers.headers': [ ('Vary', 'Our-Varying-Header'), ], }, ) class VaryHeaderCachingServer(object): def __init__(self): self.counter = count(1) @cherrypy.expose def index(self): return 'visit #%s' % next(self.counter) @cherrypy.config( **{ 'tools.expires.on': True, 'tools.expires.secs': 60, 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static', 'tools.staticdir.root': curdir, }, ) class UnCached(object): @cherrypy.expose @cherrypy.config(**{'tools.expires.secs': 0}) def force(self): cherrypy.response.headers['Etag'] = 'bibbitybobbityboo' self._cp_config['tools.expires.force'] = True self._cp_config['tools.expires.secs'] = 0 return 'being forceful' @cherrypy.expose def dynamic(self): cherrypy.response.headers['Etag'] = 'bibbitybobbityboo' cherrypy.response.headers['Cache-Control'] = 'private' return 'D-d-d-dynamic!' @cherrypy.expose def cacheable(self): cherrypy.response.headers['Etag'] = 'bibbitybobbityboo' return "Hi, I'm cacheable." @cherrypy.expose @cherrypy.config(**{'tools.expires.secs': 86400}) def specific(self): cherrypy.response.headers['Etag'] = ( 'need_this_to_make_me_cacheable' ) return 'I am being specific' class Foo(object): pass @cherrypy.expose @cherrypy.config(**{'tools.expires.secs': Foo()}) def wrongtype(self): cherrypy.response.headers['Etag'] = ( 'need_this_to_make_me_cacheable' ) return 'Woops' @cherrypy.config( **{ 'tools.gzip.mime_types': ['text/*', 'image/*'], 'tools.caching.on': True, 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static', 'tools.staticdir.root': curdir, }, ) class GzipStaticCache(object): pass cherrypy.tree.mount(Root()) cherrypy.tree.mount(UnCached(), '/expires') cherrypy.tree.mount(VaryHeaderCachingServer(), '/varying_headers') cherrypy.tree.mount(GzipStaticCache(), '/gzip_static_cache') cherrypy.config.update({'tools.gzip.on': True}) def testCaching(self): elapsed = 0.0 for trial in range(10): self.getPage('/') # The response should be the same every time, # except for the Age response header. self.assertBody('visit #1') if trial != 0: age = int(self.assertHeader('Age')) assert age >= elapsed elapsed = age # POST, PUT, DELETE should not be cached. self.getPage('/', method='POST') self.assertBody('visit #2') # Because gzip is turned on, the Vary header should always Vary for # content-encoding self.assertHeader('Vary', 'Accept-Encoding') # The previous request should have invalidated the cache, # so this request will recalc the response. self.getPage('/', method='GET') self.assertBody('visit #3') # ...but this request should get the cached copy. self.getPage('/', method='GET') self.assertBody('visit #3') self.getPage('/', method='DELETE') self.assertBody('visit #4') # The previous request should have invalidated the cache, # so this request will recalc the response. self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')]) self.assertHeader('Content-Encoding', 'gzip') self.assertHeader('Vary') self.assertEqual( cherrypy.lib.encoding.decompress(self.body), b'visit #5', ) # Now check that a second request gets the gzip header and gzipped body # This also tests a bug in 3.0 to 3.0.2 whereby the cached, gzipped # response body was being gzipped a second time. self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')]) self.assertHeader('Content-Encoding', 'gzip') self.assertEqual( cherrypy.lib.encoding.decompress(self.body), b'visit #5', ) # Now check that a third request that doesn't accept gzip # skips the cache (because the 'Vary' header denies it). self.getPage('/', method='GET') self.assertNoHeader('Content-Encoding') self.assertBody('visit #6') def testVaryHeader(self): self.getPage('/varying_headers/') self.assertStatus('200 OK') self.assertHeaderItemValue('Vary', 'Our-Varying-Header') self.assertBody('visit #1') # Now check that different 'Vary'-fields don't evict each other. # This test creates 2 requests with different 'Our-Varying-Header' # and then tests if the first one still exists. self.getPage( '/varying_headers/', headers=[('Our-Varying-Header', 'request 2')], ) self.assertStatus('200 OK') self.assertBody('visit #2') self.getPage( '/varying_headers/', headers=[('Our-Varying-Header', 'request 2')], ) self.assertStatus('200 OK') self.assertBody('visit #2') self.getPage('/varying_headers/') self.assertStatus('200 OK') self.assertBody('visit #1') def testExpiresTool(self): # test setting an expires header self.getPage('/expires/specific') self.assertStatus('200 OK') self.assertHeader('Expires') # test exceptions for bad time values self.getPage('/expires/wrongtype') self.assertStatus(500) self.assertInBody('TypeError') # static content should not have "cache prevention" headers self.getPage('/expires/index.html') self.assertStatus('200 OK') self.assertNoHeader('Pragma') self.assertNoHeader('Cache-Control') self.assertHeader('Expires') # dynamic content that sets indicators should not have # "cache prevention" headers self.getPage('/expires/cacheable') self.assertStatus('200 OK') self.assertNoHeader('Pragma') self.assertNoHeader('Cache-Control') self.assertHeader('Expires') self.getPage('/expires/dynamic') self.assertBody('D-d-d-dynamic!') # the Cache-Control header should be untouched self.assertHeader('Cache-Control', 'private') self.assertHeader('Expires') # configure the tool to ignore indicators and replace existing headers self.getPage('/expires/force') self.assertStatus('200 OK') # This also gives us a chance to test 0 expiry with no other headers self.assertHeader('Pragma', 'no-cache') if cherrypy.server.protocol_version == 'HTTP/1.1': self.assertHeader('Cache-Control', 'no-cache, must-revalidate') self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') # static content should now have "cache prevention" headers self.getPage('/expires/index.html') self.assertStatus('200 OK') self.assertHeader('Pragma', 'no-cache') if cherrypy.server.protocol_version == 'HTTP/1.1': self.assertHeader('Cache-Control', 'no-cache, must-revalidate') self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') # the cacheable handler should now have "cache prevention" headers self.getPage('/expires/cacheable') self.assertStatus('200 OK') self.assertHeader('Pragma', 'no-cache') if cherrypy.server.protocol_version == 'HTTP/1.1': self.assertHeader('Cache-Control', 'no-cache, must-revalidate') self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') self.getPage('/expires/dynamic') self.assertBody('D-d-d-dynamic!') # dynamic sets Cache-Control to private but it should be # overwritten here ... self.assertHeader('Pragma', 'no-cache') if cherrypy.server.protocol_version == 'HTTP/1.1': self.assertHeader('Cache-Control', 'no-cache, must-revalidate') self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') def _assert_resp_len_and_enc_for_gzip(self, uri): """ Test that after querying gzipped content it's remains valid in cache and available non-gzipped as well. """ ACCEPT_GZIP_HEADERS = [('Accept-Encoding', 'gzip')] content_len = None for _ in range(3): self.getPage(uri, method='GET', headers=ACCEPT_GZIP_HEADERS) if content_len is not None: # all requests should get the same length self.assertHeader('Content-Length', content_len) self.assertHeader('Content-Encoding', 'gzip') content_len = dict(self.headers)['Content-Length'] # check that we can still get non-gzipped version self.getPage(uri, method='GET') self.assertNoHeader('Content-Encoding') # non-gzipped version should have a different content length self.assertNoHeaderItemValue('Content-Length', content_len) def testGzipStaticCache(self): """Test that cache and gzip tools play well together when both enabled. Ref GitHub issue #1190. """ GZIP_STATIC_CACHE_TMPL = '/gzip_static_cache/{}' resource_files = ('index.html', 'dirback.jpg') for f in resource_files: uri = GZIP_STATIC_CACHE_TMPL.format(f) self._assert_resp_len_and_enc_for_gzip(uri) def testLastModified(self): self.getPage('/a.gif') self.assertStatus(200) self.assertBody(gif_bytes) lm1 = self.assertHeader('Last-Modified') # this request should get the cached copy. self.getPage('/a.gif') self.assertStatus(200) self.assertBody(gif_bytes) self.assertHeader('Age') lm2 = self.assertHeader('Last-Modified') self.assertEqual(lm1, lm2) # this request should match the cached copy, but raise 304. self.getPage('/a.gif', [('If-Modified-Since', lm1)]) self.assertStatus(304) self.assertNoHeader('Last-Modified') if not getattr(cherrypy.server, 'using_apache', False): self.assertHeader('Age') @pytest.mark.xfail(reason='#1536') def test_antistampede(self): SECONDS = 4 slow_url = '/long_process?seconds={SECONDS}'.format(**locals()) # We MUST make an initial synchronous request in order to create the # AntiStampedeCache object, and populate its selecting_headers, # before the actual stampede. self.getPage(slow_url) self.assertBody('success!') path = urllib.parse.quote(slow_url, safe='') self.getPage('/clear_cache?path=' + path) self.assertStatus(200) start = datetime.datetime.now() def run(): self.getPage(slow_url) # The response should be the same every time self.assertBody('success!') ts = [threading.Thread(target=run) for i in range(100)] for t in ts: t.start() for t in ts: t.join() finish = datetime.datetime.now() # Allow for overhead, two seconds for slow hosts allowance = SECONDS + 2 self.assertEqualDates(start, finish, seconds=allowance) def test_cache_control(self): self.getPage('/control') self.assertBody('visit #1') self.getPage('/control') self.assertBody('visit #1') self.getPage('/control', headers=[('Cache-Control', 'no-cache')]) self.assertBody('visit #2') self.getPage('/control') self.assertBody('visit #2') self.getPage('/control', headers=[('Pragma', 'no-cache')]) self.assertBody('visit #3') self.getPage('/control') self.assertBody('visit #3') time.sleep(1) self.getPage('/control', headers=[('Cache-Control', 'max-age=0')]) self.assertBody('visit #4') self.getPage('/control') self.assertBody('visit #4')
CacheTest
python
spyder-ide__spyder
spyder/plugins/pylint/tests/test_pylint_config_dialog.py
{ "start": 895, "end": 1478 }
class ____(QMainWindow): sig_editor_focus_changed = Signal(str) def __init__(self, parent): super().__init__(parent) self.editor = MagicMock() self.editor.sig_editor_focus_changed = self.sig_editor_focus_changed self.projects = MagicMock() @pytest.mark.parametrize( 'config_dialog', # [[MainWindowMock, [ConfigPlugins], [Plugins]]] [[MainWindowMock, [], [Pylint]]], indirect=True) def test_config_dialog(config_dialog): configpage = config_dialog.get_page() configpage.save_to_conf() assert configpage
MainWindowMock
python
scipy__scipy
scipy/linalg/tests/test_solvers.py
{ "start": 938, "end": 5865 }
class ____: cases = [ # empty case (np.empty((0, 0)), np.empty((0, 0))), (np.array([[1, 2], [3, 4]]), np.array([[9, 10], [11, 12]])), # a, q all complex. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a real; q complex. (np.array([[1.0, 2.0], [3.0, 5.0]]), np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])), # a complex; q real. (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]), np.array([[2.0, 2.0], [-1.0, 2.0]])), # An example from Kitagawa, 1977 (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3], [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]), np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3], [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])), # Companion matrix example. a complex; q real; a.shape[0] = 11 (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j, 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j, 0.010+0.j], [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j], [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j]]), np.eye(11)), # https://github.com/scipy/scipy/issues/4176 (matrix([[0, 1], [-1/2, -1]]), (matrix([0, 3]).T @ matrix([0, 3]).T.T)), # https://github.com/scipy/scipy/issues/4176 (matrix([[0, 1], [-1/2, -1]]), (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))), ] def test_continuous_squareness_and_shape(self): nsq = np.ones((3, 2)) sq = np.eye(3) assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq) assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq) assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2)) def check_continuous_case(self, a, q): x = solve_continuous_lyapunov(a, q) assert_array_almost_equal( np.dot(a, x) + np.dot(x, a.conj().transpose()), q) def check_discrete_case(self, a, q, method=None): x = solve_discrete_lyapunov(a, q, method=method) assert_array_almost_equal( np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q) @skip_xp_invalid_arg def test_cases(self): for case in self.cases: self.check_continuous_case(case[0], case[1]) self.check_discrete_case(case[0], case[1]) self.check_discrete_case(case[0], case[1], method='direct') self.check_discrete_case(case[0], case[1], method='bilinear') @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_q", dtypes) def test_size_0(self, dtype_a, dtype_q): rng = np.random.default_rng(234598235) a = np.zeros((0, 0), dtype=dtype_a) q = np.zeros((0, 0), dtype=dtype_q) res = solve_continuous_lyapunov(a, q) a = (rng.random((5, 5))*100).astype(dtype_a) q = (rng.random((5, 5))*100).astype(dtype_q) ref = solve_continuous_lyapunov(a, q) assert res.shape == (0, 0) assert res.dtype == ref.dtype
TestSolveLyapunov
python
django__django
tests/proxy_models/models.py
{ "start": 2478, "end": 2550 }
class ____(UserProxy): class Meta: proxy = True
UserProxyProxy
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 40961, "end": 41344 }
class ____(Base): """SQLAlchemy model of an agent""" name: Mapped[str] work_queue_id: Mapped[uuid.UUID] = mapped_column( sa.ForeignKey("work_queue.id"), index=True ) last_activity_time: Mapped[DateTime] = mapped_column( server_default=sa.func.now(), default=lambda: now("UTC") ) __table_args__: Any = (sa.UniqueConstraint("name"),)
Agent
python
huggingface__transformers
src/transformers/models/deepseek_v3/modeling_deepseek_v3.py
{ "start": 1681, "end": 2414 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ DeepseekV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
DeepseekV3RMSNorm
python
ethereum__web3.py
web3/types.py
{ "start": 13477, "end": 13600 }
class ____(TypedDict): pc: int op: str gas: int gasCost: int depth: int stack: list[HexStr]
StructLog
python
pytorch__pytorch
torch/_dynamo/output_graph.py
{ "start": 12254, "end": 13043 }
class ____: """ Stores metadata for a frame's stack and locals for the purposes of building resume functions """ num_stack: int = 0 # number of stack elements, minus removed NULLs locals_names: dict[str, int] = dc_field( default_factory=dict ) # order of locals codegen'd to the stack stack_null_idxes: list[int] = dc_field(default_factory=list) locals_null_keys: list[str] = dc_field(default_factory=list) stack_ctx_args: list[tuple[int, tuple[Any, ...]]] = dc_field(default_factory=list) stack_ctx_idxes_orig: list[int] = dc_field(default_factory=list) locals_ctx_args: list[tuple[str, tuple[Any, ...]]] = dc_field(default_factory=list) # TODO we should expand this to make it work for atribtrary in/out @dataclass
StackLocalsMetadata
python
PyCQA__flake8
tests/integration/test_plugins.py
{ "start": 404, "end": 716 }
class ____: """Extension test plugin.""" def __init__(self, tree): """Construct an instance of test plugin.""" def run(self): """Do nothing.""" @classmethod def add_options(cls, parser): """Register options.""" parser.add_option("--anopt")
ExtensionTestPlugin
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_test.py
{ "start": 8654, "end": 17015 }
class ____(test.TestCase): def test_defaults(self): a = fc.numeric_column('aaa') self.assertEqual('aaa', a.key) self.assertEqual('aaa', a.name) self.assertEqual((1,), a.shape) self.assertIsNone(a.default_value) self.assertEqual(dtypes.float32, a.dtype) self.assertIsNone(a.normalizer_fn) self.assertTrue(a._is_v2_column) def test_key_should_be_string(self): with self.assertRaisesRegex(ValueError, 'key must be a string.'): fc.numeric_column(key=('aaa',)) def test_shape_saved_as_tuple(self): a = fc.numeric_column('aaa', shape=[1, 2], default_value=[[3, 2.]]) self.assertEqual((1, 2), a.shape) def test_default_value_saved_as_tuple(self): a = fc.numeric_column('aaa', default_value=4.) self.assertEqual((4.,), a.default_value) a = fc.numeric_column('aaa', shape=[1, 2], default_value=[[3, 2.]]) self.assertEqual(((3., 2.),), a.default_value) def test_shape_and_default_value_compatibility(self): a = fc.numeric_column('aaa', shape=[2], default_value=[1, 2.]) self.assertEqual((1, 2.), a.default_value) with self.assertRaisesRegex(ValueError, 'The shape of default_value'): fc.numeric_column('aaa', shape=[2], default_value=[1, 2, 3.]) a = fc.numeric_column( 'aaa', shape=[3, 2], default_value=[[2, 3], [1, 2], [2, 3.]]) self.assertEqual(((2, 3), (1, 2), (2, 3.)), a.default_value) with self.assertRaisesRegex(ValueError, 'The shape of default_value'): fc.numeric_column( 'aaa', shape=[3, 1], default_value=[[2, 3], [1, 2], [2, 3.]]) with self.assertRaisesRegex(ValueError, 'The shape of default_value'): fc.numeric_column( 'aaa', shape=[3, 3], default_value=[[2, 3], [1, 2], [2, 3.]]) def test_default_value_type_check(self): fc.numeric_column( 'aaa', shape=[2], default_value=[1, 2.], dtype=dtypes.float32) fc.numeric_column( 'aaa', shape=[2], default_value=[1, 2], dtype=dtypes.int32) with self.assertRaisesRegex(TypeError, 'must be compatible with dtype'): fc.numeric_column( 'aaa', shape=[2], default_value=[1, 2.], dtype=dtypes.int32) with self.assertRaisesRegex(TypeError, 'default_value must be compatible with dtype'): fc.numeric_column('aaa', default_value=['string']) def test_shape_must_be_positive_integer(self): with self.assertRaisesRegex(TypeError, 'shape dimensions must be integer'): fc.numeric_column( 'aaa', shape=[ 1.0, ]) with self.assertRaisesRegex(ValueError, 'shape dimensions must be greater than 0'): fc.numeric_column( 'aaa', shape=[ 0, ]) def test_dtype_is_convertible_to_float(self): with self.assertRaisesRegex(ValueError, 'dtype must be convertible to float'): fc.numeric_column('aaa', dtype=dtypes.string) def test_scalar_default_value_fills_the_shape(self): a = fc.numeric_column('aaa', shape=[2, 3], default_value=2.) self.assertEqual(((2., 2., 2.), (2., 2., 2.)), a.default_value) def test_parse_spec(self): a = fc.numeric_column('aaa', shape=[2, 3], dtype=dtypes.int32) self.assertEqual({ 'aaa': parsing_ops.FixedLenFeature((2, 3), dtype=dtypes.int32) }, a.parse_example_spec) def test_parse_example_no_default_value(self): price = fc.numeric_column('price', shape=[2]) data = example_pb2.Example( features=feature_pb2.Features( feature={ 'price': feature_pb2.Feature( float_list=feature_pb2.FloatList(value=[20., 110.])) })) features = parsing_ops.parse_example( serialized=[data.SerializeToString()], features=fc.make_parse_example_spec_v2([price])) self.assertIn('price', features) self.assertAllEqual([[20., 110.]], self.evaluate(features['price'])) def test_parse_example_with_default_value(self): price = fc.numeric_column('price', shape=[2], default_value=11.) data = example_pb2.Example( features=feature_pb2.Features( feature={ 'price': feature_pb2.Feature( float_list=feature_pb2.FloatList(value=[20., 110.])) })) no_data = example_pb2.Example( features=feature_pb2.Features( feature={ 'something_else': feature_pb2.Feature( float_list=feature_pb2.FloatList(value=[20., 110.])) })) features = parsing_ops.parse_example( serialized=[data.SerializeToString(), no_data.SerializeToString()], features=fc.make_parse_example_spec_v2([price])) self.assertIn('price', features) self.assertAllEqual([[20., 110.], [11., 11.]], self.evaluate(features['price'])) def test_normalizer_fn_must_be_callable(self): with self.assertRaisesRegex(TypeError, 'must be a callable'): fc.numeric_column('price', normalizer_fn='NotACallable') def test_normalizer_fn_transform_feature(self): def _increment_two(input_tensor): return input_tensor + 2. price = fc.numeric_column('price', shape=[2], normalizer_fn=_increment_two) output = fc._transform_features_v2({ 'price': [[1., 2.], [5., 6.]] }, [price], None) self.assertAllEqual([[3., 4.], [7., 8.]], self.evaluate(output[price])) def test_get_dense_tensor(self): def _increment_two(input_tensor): return input_tensor + 2. price = fc.numeric_column('price', shape=[2], normalizer_fn=_increment_two) transformation_cache = fc.FeatureTransformationCache({ 'price': [[1., 2.], [5., 6.]] }) self.assertAllEqual( transformation_cache.get(price, None), price.get_dense_tensor(transformation_cache, None)) def test_sparse_tensor_not_supported(self): price = fc.numeric_column('price') transformation_cache = fc.FeatureTransformationCache({ 'price': sparse_tensor.SparseTensor( indices=[[0, 0]], values=[0.3], dense_shape=[1, 1]) }) with self.assertRaisesRegex(ValueError, 'must be a Tensor'): price.transform_feature(transformation_cache, None) def test_deep_copy(self): a = fc.numeric_column('aaa', shape=[1, 2], default_value=[[3., 2.]]) a_copy = copy.deepcopy(a) self.assertEqual(a_copy.name, 'aaa') self.assertEqual(a_copy.shape, (1, 2)) self.assertEqual(a_copy.default_value, ((3., 2.),)) def test_numpy_default_value(self): a = fc.numeric_column( 'aaa', shape=[1, 2], default_value=np.array([[3., 2.]])) self.assertEqual(a.default_value, ((3., 2.),)) def test_old_linear_model(self): price = fc.numeric_column('price') with ops.Graph().as_default(): features = {'price': [[1.], [5.]]} predictions = fc_old.linear_model(features, [price]) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias)) self.assertAllClose([[0.]], self.evaluate(price_var)) self.assertAllClose([[0.], [0.]], self.evaluate(predictions)) sess.run(price_var.assign([[10.]])) self.assertAllClose([[10.], [50.]], self.evaluate(predictions)) def test_serialization(self): def _increment_two(input_tensor): return input_tensor + 2. price = fc.numeric_column('price', normalizer_fn=_increment_two) self.assertEqual(['price'], price.parents) config = price.get_config() self.assertEqual({ 'key': 'price', 'shape': (1,), 'default_value': None, 'dtype': 'float32', 'normalizer_fn': '_increment_two' }, config) new_col = fc.NumericColumn.from_config( config, custom_objects={'_increment_two': _increment_two}) self.assertEqual(price, new_col) self.assertEqual(new_col.shape, (1,)) # Also test round trip through feature column serialization utils. new_col = serialization.deserialize_feature_column( serialization.serialize_feature_column(price), custom_objects={'_increment_two': _increment_two}) self.assertEqual(price, new_col)
NumericColumnTest
python
mlflow__mlflow
mlflow/store/_unity_catalog/registry/rest_store.py
{ "start": 6259, "end": 12667 }
class ____: """Internal class to hold parsed catalog, schema, and remaining filter.""" catalog_name: str schema_name: str remaining_filter: str | None def _require_arg_unspecified(arg_name, arg_value, default_values=None, message=None): default_values = [None] if default_values is None else default_values if arg_value not in default_values: _raise_unsupported_arg(arg_name, message) def _raise_unsupported_arg(arg_name, message=None): messages = [ f"Argument '{arg_name}' is unsupported for models in the Unity Catalog.", ] if message is not None: messages.append(message) raise MlflowException(" ".join(messages)) def _raise_unsupported_method(method, message=None): messages = [ f"Method '{method}' is unsupported for models in the Unity Catalog.", ] if message is not None: messages.append(message) raise MlflowException(" ".join(messages)) def _load_model(local_model_dir): # Import Model here instead of in the top level, to avoid circular import; the # mlflow.models.model module imports from MLflow tracking, which triggers an import of # this file during store registry initialization from mlflow.models.model import Model try: return Model.load(local_model_dir) except Exception as e: raise MlflowException( "Unable to load model metadata. Ensure the source path of the model " "being registered points to a valid MLflow model directory " "(see https://mlflow.org/docs/latest/models.html#storage-format) containing a " "model signature (https://mlflow.org/docs/latest/models.html#model-signature) " "specifying both input and output type specifications." ) from e def get_feature_dependencies(model_dir): """ Gets the features which a model depends on. This functionality is only implemented on Databricks. In OSS mlflow, the dependencies are always empty (""). """ model = _load_model(model_dir) model_info = model.get_model_info() if ( model_info.flavors.get("python_function", {}).get("loader_module") == mlflow.models.model._DATABRICKS_FS_LOADER_MODULE ): raise MlflowException( "This model was packaged by Databricks Feature Store and can only be registered on a " "Databricks cluster." ) return "" def get_model_version_dependencies(model_dir): """ Gets the specified dependencies for a particular model version and formats them to be passed into CreateModelVersion. """ from mlflow.models.resources import ResourceType model = _load_model(model_dir) model_info = model.get_model_info() dependencies = [] # Try to get model.auth_policy.system_auth_policy.resources. If that is not found or empty, # then use model.resources. if model.auth_policy: databricks_resources = model.auth_policy.get("system_auth_policy", {}).get("resources", {}) else: databricks_resources = model.resources if databricks_resources: databricks_dependencies = databricks_resources.get("databricks", {}) dependencies.extend( _fetch_langchain_dependency_from_model_resources( databricks_dependencies, ResourceType.VECTOR_SEARCH_INDEX.value, "DATABRICKS_VECTOR_INDEX", ) ) dependencies.extend( _fetch_langchain_dependency_from_model_resources( databricks_dependencies, ResourceType.SERVING_ENDPOINT.value, "DATABRICKS_MODEL_ENDPOINT", ) ) dependencies.extend( _fetch_langchain_dependency_from_model_resources( databricks_dependencies, ResourceType.FUNCTION.value, "DATABRICKS_UC_FUNCTION", ) ) dependencies.extend( _fetch_langchain_dependency_from_model_resources( databricks_dependencies, ResourceType.UC_CONNECTION.value, "DATABRICKS_UC_CONNECTION", ) ) dependencies.extend( _fetch_langchain_dependency_from_model_resources( databricks_dependencies, ResourceType.TABLE.value, "DATABRICKS_TABLE", ) ) else: # These types of dependencies are required for old models that didn't use # resources so they can be registered correctly to UC _DATABRICKS_VECTOR_SEARCH_INDEX_NAME_KEY = "databricks_vector_search_index_name" _DATABRICKS_EMBEDDINGS_ENDPOINT_NAME_KEY = "databricks_embeddings_endpoint_name" _DATABRICKS_LLM_ENDPOINT_NAME_KEY = "databricks_llm_endpoint_name" _DATABRICKS_CHAT_ENDPOINT_NAME_KEY = "databricks_chat_endpoint_name" _DB_DEPENDENCY_KEY = "databricks_dependency" databricks_dependencies = model_info.flavors.get("langchain", {}).get( _DB_DEPENDENCY_KEY, {} ) index_names = _fetch_langchain_dependency_from_model_info( databricks_dependencies, _DATABRICKS_VECTOR_SEARCH_INDEX_NAME_KEY ) dependencies.extend( {"type": "DATABRICKS_VECTOR_INDEX", "name": index_name} for index_name in index_names ) for key in ( _DATABRICKS_EMBEDDINGS_ENDPOINT_NAME_KEY, _DATABRICKS_LLM_ENDPOINT_NAME_KEY, _DATABRICKS_CHAT_ENDPOINT_NAME_KEY, ): endpoint_names = _fetch_langchain_dependency_from_model_info( databricks_dependencies, key ) dependencies.extend( {"type": "DATABRICKS_MODEL_ENDPOINT", "name": endpoint_name} for endpoint_name in endpoint_names ) return dependencies def _fetch_langchain_dependency_from_model_resources(databricks_dependencies, key, resource_type): dependencies = databricks_dependencies.get(key, []) deps = [] for dependency in dependencies: if dependency.get("on_behalf_of_user", False): continue deps.append({"type": resource_type, "name": dependency["name"]}) return deps def _fetch_langchain_dependency_from_model_info(databricks_dependencies, key): return databricks_dependencies.get(key, [])
_CatalogSchemaFilter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py
{ "start": 2855, "end": 3595 }
class ____(RkiCovidStream): """Docs: https://api.corona-zahlen.org/states/age-groups""" primary_key = None def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: if response.json(): for key, value in response.json().get("data").items(): record = {"abbreviation": key} for grp, data in value.items(): record.update({grp: data}) yield record return [{}] def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return "states/age-groups" # Basic incremental stream
GermanyStatesAgeGroups
python
tensorflow__tensorflow
tensorflow/compiler/tests/matrix_solve_op_test.py
{ "start": 1052, "end": 3222 }
class ____(xla_test.XLATestCase, parameterized.TestCase): def _verifySolve(self, x, y, adjoint): for np_type in self.float_types & {np.float32, np.float64}: tol = 1e-4 if np_type == np.float32 else 1e-12 a = x.astype(np_type) b = y.astype(np_type) np_ans = np.linalg.solve(np.swapaxes(a, -2, -1) if adjoint else a, b) with self.session() as sess: with self.test_scope(): tf_ans = linalg_ops.matrix_solve(a, b, adjoint=adjoint) out = sess.run(tf_ans) self.assertEqual(tf_ans.shape, out.shape) self.assertEqual(np_ans.shape, out.shape) self.assertAllClose(np_ans, out, atol=tol, rtol=tol) @parameterized.named_parameters( ("Scalar", 1, 1, [], [], False), ("Vector", 5, 1, [], [], False), ("MultipleRHS", 5, 4, [], [], False), ("Adjoint", 5, 4, [], [], True), ("BatchedScalar", 1, 4, [2], [2], False), ("BatchedVector", 5, 4, [2], [2], False), ("BatchedRank2", 5, 4, [7, 4], [7, 4], False), ("BatchedAdjoint", 5, 4, [7, 4], [7, 4], True), ) def testSolve(self, n, nrhs, batch_dims, rhs_batch_dims, adjoint): matrix = np.random.normal(-5.0, 5.0, batch_dims + [n, n]) rhs = np.random.normal(-5.0, 5.0, rhs_batch_dims + [n, nrhs]) self._verifySolve(matrix, rhs, adjoint=adjoint) @parameterized.named_parameters( ("Simple", False), ("Adjoint", True), ) def testConcurrent(self, adjoint): with self.session() as sess: lhs1 = random_ops.random_normal([3, 3], seed=42) lhs2 = random_ops.random_normal([3, 3], seed=42) rhs1 = random_ops.random_normal([3, 3], seed=42) rhs2 = random_ops.random_normal([3, 3], seed=42) with self.test_scope(): s1 = linalg_ops.matrix_solve(lhs1, rhs1, adjoint=adjoint) s2 = linalg_ops.matrix_solve(lhs2, rhs2, adjoint=adjoint) self.assertAllEqual(*sess.run([s1, s2])) if __name__ == "__main__": sys_details = sysconfig.get_build_info() if sys_details["is_cuda_build"]: os.environ["XLA_FLAGS"] = ( "--xla_gpu_enable_cublaslt=true " + os.environ.get("XLA_FLAGS", "") ) googletest.main()
MatrixSolveOpTest
python
sqlalchemy__sqlalchemy
test/sql/test_text.py
{ "start": 26812, "end": 27676 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def _test(self, fn, arg, offending_clause): arg = util.to_list(arg) assert_raises_message( exc.ArgumentError, r"Textual (?:SQL|column|SQL FROM) expression %(stmt)r should be " r"explicitly declared (?:with|as) text\(%(stmt)r\)" % {"stmt": util.ellipses_string(offending_clause)}, fn, *arg, ) def test_where(self): self._test(select(table1.c.myid).where, "myid == 5", "myid == 5") def test_column(self): self._test(select, ["myid"], "myid") def test_having(self): self._test(select(table1.c.myid).having, "myid == 5", "myid == 5") def test_from(self): self._test(select(table1.c.myid).select_from, "mytable", "mytable")
TextErrorsTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image27.py
{ "start": 315, "end": 844 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image27.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image("B2", self.image_dir + "mylogo.png") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
astropy__astropy
astropy/utils/masked/tests/test_masked.py
{ "start": 56788, "end": 58944 }
class ____(MaskedArraySetup): @classmethod def setup_class(cls): super().setup_class() cls.ra = cls.sa.view(np.recarray) cls.mra = Masked(cls.ra, mask=cls.mask_sa) def test_recarray_setup(self): assert isinstance(self.mra, Masked) assert isinstance(self.mra, np.recarray) assert np.all(self.mra.unmasked == self.ra) assert np.all(self.mra.mask == self.mask_sa) assert_array_equal(self.mra.view(np.ndarray), self.sa) assert isinstance(self.mra.a, Masked) assert_array_equal(self.mra.a.unmasked, self.sa["a"]) assert_array_equal(self.mra.a.mask, self.mask_sa["a"]) def test_recarray_setting(self): mra = self.mra.copy() mra.a = self.msa["b"] assert_array_equal(mra.a.unmasked, self.msa["b"].unmasked) assert_array_equal(mra.a.mask, self.msa["b"].mask) @pytest.mark.parametrize("attr", [0, "a"]) def test_recarray_field_getting(self, attr): mra_a = self.mra.field(attr) assert isinstance(mra_a, Masked) assert_array_equal(mra_a.unmasked, self.sa["a"]) assert_array_equal(mra_a.mask, self.mask_sa["a"]) @pytest.mark.parametrize("attr", [0, "a"]) def test_recarray_field_setting(self, attr): mra = self.mra.copy() mra.field(attr, self.msa["b"]) assert_array_equal(mra.a.unmasked, self.msa["b"].unmasked) assert_array_equal(mra.a.mask, self.msa["b"].mask) def test_recarray_repr(self): # Omit dtype part with endian-dependence. assert repr(self.mra).startswith( "MaskedRecarray([[(———, ———), ( 3., 4.)],\n" " [(11., ———), (———, 14.)]],\n" ) def test_recarray_represent_as_dict(self): rasd = self.mra.info._represent_as_dict() assert type(rasd["data"]) is np.ma.MaskedArray assert type(rasd["data"].base) is np.ndarray mra2 = type(self.mra).info._construct_from_dict(rasd) assert type(mra2) is type(self.mra) assert_array_equal(mra2.unmasked, self.ra) assert_array_equal(mra2.mask, self.mra.mask)
TestMaskedRecarray
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 18443, "end": 18592 }
class ____(GithubStream): """ API docs: https://docs.github.com/en/rest/issues/assignees?apiVersion=2022-11-28#list-assignees """
Assignees
python
bokeh__bokeh
tests/unit/bokeh/model/test_model.py
{ "start": 1507, "end": 1609 }
class ____(Model): a = Int(12) b = String("hello") c = List(Int, default=[1, 2, 3])
SomeModel
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 1712, "end": 2229 }
class ____: def __post_init__( self, arg1: int = (1) # comment , arg2: int = ((1)) # comment , arg2: int = (i for i in range(10)) # comment , ) -> None: pass # makes little sense, but is valid syntax def fun_with_python_syntax(): @dataclass class Foo: def __post_init__( self, bar: (int) = (yield from range(5)) # comment , ) -> None: ... return Foo @dataclass
Foo
python
doocs__leetcode
solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.py
{ "start": 192, "end": 652 }
class ____: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: def dfs(root, i): if root is None: return if len(s) == i: s.append([root.val, 1]) else: s[i][0] += root.val s[i][1] += 1 dfs(root.left, i + 1) dfs(root.right, i + 1) s = [] dfs(root, 0) return [a / b for a, b in s]
Solution
python
walkccc__LeetCode
solutions/117. Populating Next Right Pointers in Each Node II/117.py
{ "start": 0, "end": 606 }
class ____: def connect(self, root: 'Node') -> 'Node': node = root # the node that is above the current needling while node: dummy = Node(0) # a dummy node before needling # Needle the children of the node. needle = dummy while node: if node.left: # Needle the left child. needle.next = node.left needle = needle.next if node.right: # Needle the right child. needle.next = node.right needle = needle.next node = node.next node = dummy.next # Move the node to the next level. return root
Solution
python
huggingface__transformers
src/transformers/models/granitemoehybrid/configuration_granitemoehybrid.py
{ "start": 882, "end": 12337 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`GraniteMoeHybridConfig`]. It is used to instantiate an GraniteMoeHybrid model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 32000): Vocabulary size of the GraniteMoeHybrid model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`GraniteMoeHybridModel`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 11008): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_parameters (`RopeParameters`, *optional*): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. embedding_multiplier (`float`, *optional*, defaults to 1.0): embedding multiplier. logits_scaling (`float`, *optional*, defaults to 1.0): divisor for output logits. residual_multiplier (`float`, *optional*, defaults to 1.0): residual multiplier. attention_multiplier (`float`, *optional*, defaults to 1.0): attention multiplier. num_local_experts (`int`, *optional*, defaults to 8): total number of experts. num_experts_per_tok (`int`, *optional*, defaults to 2): number of experts per token. output_router_logits (`bool`, *optional*, defaults to `False`): Whether or not the router logits should be returned by the model. Enabling this will also allow the model to output the auxiliary loss. router_aux_loss_coef (`float`, *optional*, defaults to 0.001): router auxiliary loss coefficient shared_intermediate_size (`int`, *optional*, defaults to 1024): intermediate size for shared experts. layer_types (`List`, *optional*): list of strings to be used as layer types. Allowed choices: "mamba", "attention". mamba_n_heads (`int`, *optional*, defaults to 128): The number of mamba heads used. mamba_n_groups (`int`, *optional*, defaults to 1): The number of the mamba groups used. mamba_d_state (`int`, *optional*, defaults to 256): The dimension the mamba latent state space. mamba_d_head (`int`, *optional*, defaults to `"auto"`): Head embedding dimension size. mamba_d_conv (`int`, *optional*, defaults to 4): The size of the mamba convolution kernel. mamba_expand (`int`, *optional*, defaults to 2): Expanding factor (relative to hidden_size) used to determine the mamba intermediate size. mamba_chunk_size (`int`, *optional*, defaults to 256): The chunks in which to break the sequence when doing prefill/training. mamba_conv_bias (`bool`, *optional*, defaults to `True`): Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block. mamba_proj_bias (`bool`, *optional*, defaults to `False`): Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block. ```python >>> from transformers import GraniteMoeHybridModel, GraniteMoeHybridConfig >>> # Initializing a GraniteMoeHybrid config >>> configuration = GraniteMoeHybridConfig() >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "granitemoehybrid" attribute_map = { "layers_block_type": "layer_types", } keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, vocab_size: Optional[int] = 32000, hidden_size: Optional[int] = 4096, intermediate_size: Optional[int] = 11008, num_hidden_layers: Optional[int] = 32, num_attention_heads: Optional[int] = 32, num_key_value_heads: Optional[int] = None, hidden_act: Optional[str] = "silu", max_position_embeddings: Optional[int] = 2048, initializer_range: Optional[float] = 0.02, rms_norm_eps: Optional[int] = 1e-6, use_cache: Optional[bool] = True, pad_token_id: Optional[int] = None, bos_token_id: Optional[int] = 1, eos_token_id: Optional[int] = 2, tie_word_embeddings: Optional[bool] = False, rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None, attention_bias: Optional[bool] = False, attention_dropout: Optional[float] = 0.0, embedding_multiplier: Optional[float] = 1.0, logits_scaling: Optional[float] = 1.0, residual_multiplier: Optional[float] = 1.0, attention_multiplier: Optional[float] = 1.0, num_local_experts: Optional[int] = 8, num_experts_per_tok: Optional[int] = 2, output_router_logits: Optional[bool] = False, router_aux_loss_coef: Optional[float] = 0.001, shared_intermediate_size: Optional[int] = 1024, layer_types: Optional[list[str]] = None, mamba_n_heads: Optional[int] = 128, mamba_n_groups: Optional[int] = 1, mamba_d_state: Optional[int] = 256, mamba_d_head: Optional[str] = "auto", mamba_d_conv: Optional[int] = 4, mamba_expand: Optional[int] = 2, mamba_chunk_size: Optional[int] = 256, mamba_conv_bias: Optional[bool] = True, mamba_proj_bias: Optional[bool] = False, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.attention_bias = attention_bias self.embedding_multiplier = embedding_multiplier self.logits_scaling = logits_scaling self.residual_multiplier = residual_multiplier self.attention_multiplier = attention_multiplier self.attention_dropout = attention_dropout self.num_local_experts = num_local_experts self.num_experts_per_tok = num_experts_per_tok self.output_router_logits = output_router_logits self.router_aux_loss_coef = router_aux_loss_coef self.shared_intermediate_size = shared_intermediate_size self.rope_parameters = rope_parameters mamba_intermediate = mamba_expand * hidden_size if layer_types is not None and any(layer_type not in ["mamba", "attention"] for layer_type in layer_types): raise ValueError("layer_types must be a list strings in [`mamba` `attention`]") if mamba_intermediate % mamba_n_heads != 0: raise ValueError("mamba_n_heads must divide mamba_expand * hidden_size") # for the mamba_v2, must satisfy the following if mamba_d_head == "auto": mamba_d_head = mamba_intermediate // mamba_n_heads if mamba_d_head * mamba_n_heads != mamba_intermediate: raise ValueError("The dimensions for the Mamba head state do not match the model intermediate_size") self.mamba_n_heads = mamba_n_heads self.mamba_d_head = mamba_d_head self.mamba_n_groups = mamba_n_groups self.mamba_d_state = mamba_d_state self.mamba_d_conv = mamba_d_conv self.mamba_chunk_size = mamba_chunk_size self.mamba_conv_bias = mamba_conv_bias self.mamba_proj_bias = mamba_proj_bias self.mamba_expand = mamba_expand self.layer_types = layer_types super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) # overwrite the function to use in `HybridMambaAttentionDynamicCache` @property def layers_block_type(self): return self.layer_types if self.layer_types else ["mamba"] * self.num_hidden_layers __all__ = ["GraniteMoeHybridConfig"]
GraniteMoeHybridConfig
python
pytorch__pytorch
torch/_inductor/kernel_template_choice.py
{ "start": 472, "end": 3363 }
class ____: """ A class that encapsulates all the components needed to create a ChoiceCaller from a template. This class implements lazy evaluation for the choice property - the actual ChoiceCaller is only created when first accessed via the choice property. """ def __init__( self, template: Union[KernelTemplate, ExternKernelChoice], params: KernelTemplateParams, extra_kwargs: dict[str, Any], layout: Layout, inputs: KernelInputs, ): self.template = template self.params = params self.extra_kwargs = extra_kwargs self.layout = layout self.inputs = inputs self.annotations: dict[str, Any] = {"ktc": self} @property def choice(self) -> Optional[ChoiceCaller]: """ Lazily evaluate and return the ChoiceCaller for this template choice. On first access, calls template.choice_or_none() with the stored parameters. If successful, caches and returns the ChoiceCaller. If it fails, caches and returns None. Subsequent accesses return the cached value. Returns: ChoiceCaller if the template choice succeeds, None otherwise """ if not hasattr(self, "_choice"): # First time accessing choice - try to generate it kwargs = self.params.to_kwargs() self._choice = self.template.choice_or_none( **kwargs, **self.extra_kwargs, layout=self.layout, input_nodes=self.inputs.nodes(), ) if self._choice is not None: self._choice.annotations = self.annotations return self._choice def make_ktc_generator( template: Union[KernelTemplate, ExternKernelChoice], cs: Generator[KernelTemplateParams, None, None], extra_kwargs: dict[str, Any], overrides: dict[str, Any], layout: Layout, inputs: KernelInputs, ) -> Generator[KernelTemplateChoice, None, None]: """ Create a generator of KernelTemplateChoice objects for a given template. Args: template: The template object (KernelTemplate or ExternKernelChoice) cs: Generator of KernelTemplateParams from template heuristic overrides: Override kwargs for the template layout: Layout value for the template inputs: KernelInputs for the op Yields: KernelTemplateChoice objects """ for params in cs: # Apply overrides to params base_kwargs = params.to_kwargs() final_kwargs = {**base_kwargs, **overrides} final_params = DictKernelTemplateParams(final_kwargs) yield KernelTemplateChoice( template=template, params=final_params, extra_kwargs=extra_kwargs, layout=layout, inputs=inputs, )
KernelTemplateChoice
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
{ "start": 960, "end": 16489 }
class ____(FSDPTest): @property def world_size(self) -> int: return min(4, torch.get_device_module(device_type).device_count()) def _init_models_and_optims( self, reshard_after_forward: Union[bool, int], param_dtype: Optional[torch.dtype], reduce_dtype: Optional[torch.dtype], use_shard_placement_fn, ): torch.manual_seed(42) model = nn.Sequential(*[MLP(16, torch.device("cpu")) for _ in range(3)]) ref_model = copy.deepcopy(model).to(device_type) ref_optim = torch.optim.Adam(ref_model.parameters(), lr=1e-2) def _shard_placement_fn(param: nn.Parameter) -> Optional[Shard]: largest_dim = -1 largest_dim_size = -1 for dim, dim_size in enumerate(param.shape): if dim_size > largest_dim_size: largest_dim = dim largest_dim_size = dim_size assert largest_dim >= 0, f"{param.shape}" return Shard(largest_dim) mp_policy = MixedPrecisionPolicy( param_dtype=param_dtype, reduce_dtype=reduce_dtype ) shard_placement_fn = _shard_placement_fn if use_shard_placement_fn else None fully_shard_fn = functools.partial( fully_shard, reshard_after_forward=reshard_after_forward, mp_policy=mp_policy, shard_placement_fn=shard_placement_fn, ) for mlp in model: fully_shard_fn(mlp) fully_shard_fn(model) optim = torch.optim.Adam(model.parameters(), lr=1e-2, foreach=True) return ref_model, ref_optim, model, optim def _get_use_shard_placement_fn_vals_for_bf16_reduce(self): use_shard_placement_fn_vals = [False] if self.world_size == 2: # For world size >2, gradient elements get reduced in different # orders for the baseline vs. dim-1 sharding, leading to numeric # differences for bf16 reduction, so only test world size 2. use_shard_placement_fn_vals.append(True) return use_shard_placement_fn_vals @skipIfRocmVersionLessThan((7, 0)) @skip_if_lt_x_gpu(2) @requires_nccl_version((2, 10), "Need NCCL 2.10+ for bf16 collectives") def test_compute_dtype(self): use_shard_placement_fn_vals = ( self._get_use_shard_placement_fn_vals_for_bf16_reduce() ) self.run_subtests( { "param_dtype": [torch.bfloat16, torch.float16], "reshard_after_forward": [False, True, 2], "use_shard_placement_fn": use_shard_placement_fn_vals, }, self._test_compute_dtype, ) def _test_compute_dtype( self, param_dtype: torch.dtype, reshard_after_forward: Union[bool, int], use_shard_placement_fn: bool, ): ref_model, ref_optim, model, optim = self._init_models_and_optims( reshard_after_forward, param_dtype=param_dtype, reduce_dtype=None, use_shard_placement_fn=use_shard_placement_fn, ) ref_model_bf16 = copy.deepcopy(ref_model).to(param_dtype) orig_reduce_scatter = dist.reduce_scatter_tensor def assert_fn(output: torch.Tensor): self.assertEqual(output.dtype, param_dtype) reduce_scatter = functools.partial( reduce_scatter_with_assert, self, orig_reduce_scatter, assert_fn ) predivide_factor, postdivide_factor, _, _ = _get_gradient_divide_factors( self.process_group, all_reduce_group=None, reduce_dtype=param_dtype ) torch.manual_seed(42 + self.rank + 1) inp = torch.randn((4, 16), device=device_type.type, dtype=param_dtype) for iter_idx in range(10): optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) fsdp_loss = model(inp).sum() with patch_reduce_scatter(reduce_scatter): fsdp_loss.backward() optim.step() ref_optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) ref_loss = ref_model_bf16(inp.to(param_dtype)).sum() ref_loss.backward() for param in ref_model_bf16.parameters(): # Use reduce-scatter -> all-gather as all-reduce because for # world size >=4, NCCL all-reduce shows numeric differences # compared with NCCL reduce-scatter if predivide_factor is not None and predivide_factor > 1: param.grad.div_(predivide_factor) elif predivide_factor is None: param.grad.div_(self.world_size) output = torch.zeros_like(torch.chunk(param.grad, self.world_size)[0]) dist.reduce_scatter_tensor(output, param.grad) dist.all_gather_into_tensor(param.grad, output) if postdivide_factor is not None and postdivide_factor > 1: param.grad.div_(postdivide_factor) for param_fp32, param_bf16 in zip( ref_model.parameters(), ref_model_bf16.parameters() ): param_fp32.grad = param_bf16.grad.to(param_fp32.dtype) param_bf16.grad = None ref_optim.step() # fp32 optimizer step for param_fp32, param_bf16 in zip( ref_model.parameters(), ref_model_bf16.parameters() ): param_bf16.detach().copy_(param_fp32) self.assertEqual(fsdp_loss, ref_loss) check_sharded_parity(self, ref_model, model) @skipIfRocmVersionLessThan((7, 0)) @skip_if_lt_x_gpu(2) @requires_nccl_version((2, 10), "Need NCCL 2.10+ for bf16 collectives") def test_reduce_dtype(self): self.run_subtests( { "reshard_after_forward": [False, True, 2], "use_shard_placement_fn": [False, True], }, self._test_reduce_dtype_fp32_reduce, ) use_shard_placement_fn_vals = ( self._get_use_shard_placement_fn_vals_for_bf16_reduce() ) self.run_subtests( { "reshard_after_forward": [False, True, 2], "use_shard_placement_fn": use_shard_placement_fn_vals, }, self._test_reduce_dtype_bf16_reduce, ) def _test_reduce_dtype_fp32_reduce( self, reshard_after_forward: Union[bool, int], use_shard_placement_fn: bool ): if ( self.world_size > 2 and isinstance(reshard_after_forward, int) and use_shard_placement_fn ): return param_dtype, reduce_dtype = torch.bfloat16, torch.float32 ref_model, ref_optim, model, optim = self._init_models_and_optims( reshard_after_forward, param_dtype=param_dtype, reduce_dtype=reduce_dtype, use_shard_placement_fn=use_shard_placement_fn, ) ref_model_bf16 = copy.deepcopy(ref_model).to(param_dtype) orig_reduce_scatter = dist.reduce_scatter_tensor def assert_fn(output: torch.Tensor): self.assertEqual(output.dtype, reduce_dtype) reduce_scatter = functools.partial( reduce_scatter_with_assert, self, orig_reduce_scatter, assert_fn ) torch.manual_seed(42 + self.rank + 1) inp = torch.randn((4, 16), device=device_type.type, dtype=param_dtype) for iter_idx in range(10): optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) fsdp_loss = model(inp).sum() with patch_reduce_scatter(reduce_scatter): fsdp_loss.backward() optim.step() ref_optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) ref_loss = ref_model_bf16(inp.to(param_dtype)).sum() ref_loss.backward() for param in ref_model_bf16.parameters(): param.grad.data = param.grad.to(torch.float32) dist.all_reduce(param.grad) # fp32 reduction param.grad.div_(self.world_size) for param_fp32, param_bf16 in zip( ref_model.parameters(), ref_model_bf16.parameters() ): param_fp32.grad = param_bf16.grad param_bf16.grad = None ref_optim.step() # fp32 optimizer step for param_fp32, param_bf16 in zip( ref_model.parameters(), ref_model_bf16.parameters() ): param_bf16.detach().copy_(param_fp32) self.assertEqual(fsdp_loss, ref_loss) check_sharded_parity(self, ref_model, model) def _test_reduce_dtype_bf16_reduce( self, reshard_after_forward: Union[bool, int], use_shard_placement_fn: bool ): param_dtype, reduce_dtype = torch.float32, torch.bfloat16 ref_model, ref_optim, model, optim = self._init_models_and_optims( reshard_after_forward, param_dtype=param_dtype, reduce_dtype=reduce_dtype, use_shard_placement_fn=use_shard_placement_fn, ) group = dist.distributed_c10d._get_default_group() orig_reduce_scatter = dist.reduce_scatter_tensor def assert_fn(output: torch.Tensor): self.assertEqual(output.dtype, reduce_dtype) reduce_scatter = functools.partial( reduce_scatter_with_assert, self, orig_reduce_scatter, assert_fn ) torch.manual_seed(42 + self.rank + 1) inp = torch.randn((4, 16), device=device_type.type, dtype=param_dtype) for iter_idx in range(10): optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) fsdp_loss = model(inp).sum() with patch_reduce_scatter(reduce_scatter): fsdp_loss.backward() optim.step() ref_optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) ref_loss = ref_model(inp).sum() ref_loss.backward() for param in ref_model.parameters(): param_grad = param.grad.to(reduce_dtype) # Use reduce-scatter -> all-gather to implement all-reduce # since for world size >2, bf16 all-reduce and reduce-scatter # have numeric differences sharded_grad = funcol.reduce_scatter_tensor( param_grad, scatter_dim=0, reduceOp="avg", group=group ) # bf16 reduction param.grad = funcol.all_gather_tensor( sharded_grad, gather_dim=0, group=group ).to(param.dtype) # upcast to fp32 ref_optim.step() # fp32 optimizer step self.assertEqual(fsdp_loss, ref_loss) check_sharded_parity(self, ref_model, model) @skip_if_lt_x_gpu(2) def test_grad_acc_with_reduce_dtype(self): """ Tests that gradient accumulation without reduce-scatter when using bf16 compute and fp32 reduction accumulates the unsharded gradients in fp32. """ self.run_subtests( {"reshard_after_forward": [True, False]}, self._test_grad_acc_with_reduce_dtype, ) def _test_grad_acc_with_reduce_dtype(self, reshard_after_forward: bool): torch.manual_seed(42) param_dtype, reduce_dtype = (torch.bfloat16, torch.float32) mp_policy = MixedPrecisionPolicy( param_dtype=param_dtype, reduce_dtype=reduce_dtype ) model = nn.Sequential(*[MLP(16, torch.device("cpu")) for _ in range(3)]) # To emulate the mixed precision implementation where forward/backward # compute use bf16 and optimizer uses fp32, we maintain both an fp32 # and a bf16 copy of the reference model ref_model = copy.deepcopy(model).to(device_type) ref_model_compute = copy.deepcopy(ref_model).to(param_dtype) ref_optim = torch.optim.Adam(ref_model.parameters(), lr=1e-2) for mlp in model: fully_shard( mlp, reshard_after_forward=reshard_after_forward, mp_policy=mp_policy ) fully_shard( model, reshard_after_forward=reshard_after_forward, mp_policy=mp_policy ) optim = torch.optim.Adam(model.parameters(), lr=1e-2) orig_reduce_scatter = dist.reduce_scatter_tensor def assert_fn(output: torch.Tensor): self.assertEqual(output.dtype, reduce_dtype) reduce_scatter = functools.partial( reduce_scatter_with_assert, self, orig_reduce_scatter, assert_fn ) torch.manual_seed(42 + self.rank + 1) device = device_type # Train on the same input to avoid loss explosion num_microbatches = 4 inp = torch.randn((2 * num_microbatches, 16), device=device, dtype=param_dtype) for iter_idx in range(10): microbatch_inps = torch.chunk(inp, 4) for microbatch_idx in range(num_microbatches): is_last_microbatch = microbatch_idx == num_microbatches - 1 model.set_requires_gradient_sync(is_last_microbatch) model.set_reshard_after_backward( is_last_microbatch or reshard_after_forward ) losses: list[torch.Tensor] = [] for _model in (ref_model_compute, model): losses.append( _model(microbatch_inps[microbatch_idx].detach()).sum() ) self.assertEqual(losses[-1].dtype, param_dtype) with patch_reduce_scatter(reduce_scatter): losses[-1].backward() self.assertEqual(losses[0], losses[1]) # Manually accumulate gradients into the base reference model # from the compute reference model in fp32 for ref_param, ref_param_compute in zip( ref_model.parameters(), ref_model_compute.parameters() ): self.assertTrue(ref_param_compute.grad is not None) self.assertEqual(ref_param.dtype, torch.float32) if ref_param.grad is not None: ref_param.grad += ref_param_compute.grad else: ref_param.grad = ref_param_compute.grad.to(ref_param.dtype) ref_param_compute.grad = None # Manually reduce gradients for the reference model on the last # microbatch to implement data parallelism if is_last_microbatch: for ref_param in ref_model.parameters(): self.assertTrue(ref_param.grad is not None) dist.all_reduce(ref_param.grad) ref_param.grad /= self.world_size check_sharded_parity(self, ref_model, model) ref_optim.step() optim.step() ref_optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) # Manually copy parameters from the base reference model to the # compute reference model to run the optimizer step for the latter for ref_param, ref_param_compute in zip( ref_model.parameters(), ref_model_compute.parameters() ): ref_param_compute.detach().copy_(ref_param)
TestFullyShardMixedPrecisionTraining
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-reach-every-position.py
{ "start": 42, "end": 281 }
class ____(object): def minCosts(self, cost): """ :type cost: List[int] :rtype: List[int] """ for i in xrange(1, len(cost)): cost[i] = min(cost[i], cost[i-1]) return cost
Solution
python
spyder-ide__spyder
spyder/plugins/appearance/confpage.py
{ "start": 1220, "end": 24836 }
class ____(PluginConfigPage): def __init__(self, plugin, parent): super().__init__(plugin, parent) self._is_shown = False self.pre_apply_callback = self.check_color_scheme_notification # Notifications for this option are disabled when the plugin is # initialized, so we need to restore them here. CONF.restore_notifications(section='appearance', option='ui_theme') def setup_page(self): names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass custom_names = self.get_option("custom_names", []) # Interface options theme_group = QGroupBox(_("Main interface")) # Interface Widgets ui_theme_choices = [ (_('Automatic'), 'automatic'), (_('Light'), 'light'), (_('Dark'), 'dark') ] ui_theme_combo = self.create_combobox( _('Interface theme'), ui_theme_choices, 'ui_theme', restart=True ) self.ui_combobox = ui_theme_combo.combobox theme_comboboxes_layout = QGridLayout() theme_comboboxes_layout.addWidget(ui_theme_combo.label, 0, 0) theme_comboboxes_layout.addWidget(ui_theme_combo.combobox, 0, 1) theme_layout = QVBoxLayout() theme_layout.addLayout(theme_comboboxes_layout) theme_group.setLayout(theme_layout) # Syntax coloring options syntax_group = QGroupBox(_("Syntax highlighting theme")) # Syntax Widgets edit_button = QPushButton(_("Edit selected theme")) create_button = QPushButton(_("Create new theme")) self.delete_button = QPushButton(_("Delete theme")) self.reset_button = QPushButton(_("Reset to defaults")) self.stacked_widget = QStackedWidget(self) self.scheme_editor_dialog = SchemeEditor( parent=self, stack=self.stacked_widget ) self.scheme_choices_dict = {} schemes_combobox_widget = self.create_combobox( '', [('', '')], 'selected', items_elide_mode=Qt.ElideNone ) self.schemes_combobox = schemes_combobox_widget.combobox # Syntax layout syntax_layout = QGridLayout(syntax_group) if sys.platform == "darwin": # Default spacing is too big on Mac syntax_layout.setVerticalSpacing(2 * AppStyle. MarginSize) btns = [self.schemes_combobox, edit_button, self.reset_button, create_button, self.delete_button] for i, btn in enumerate(btns): syntax_layout.addWidget(btn, i, 1) syntax_layout.setColumnStretch(0, 1) syntax_layout.setColumnStretch(1, 2) syntax_layout.setColumnStretch(2, 1) syntax_layout.setContentsMargins(0, 12, 0, 12) # Fonts options fonts_group = QGroupBox(_("Fonts")) # Fonts widgets self.plain_text_font = self.create_fontgroup( option='font', title=_("Monospace"), fontfilters=QFontComboBox.MonospacedFonts, without_group=True) self.app_font = self.create_fontgroup( option='app_font', title=_("Interface"), fontfilters=QFontComboBox.ProportionalFonts, restart=True, without_group=True) # System font checkbox if sys.platform == 'darwin': system_font_tip = _("Changing the interface font does not work " "reliably on macOS") else: system_font_tip = None system_font_checkbox = self.create_checkbox( _("Use the system default interface font"), 'use_system_font', restart=True, tip=system_font_tip ) # Preview widgets preview_editor_label = QLabel(_("Editor")) self.preview_editor = SimpleCodeEditor(self) self.preview_editor.setFixedWidth(260) self.preview_editor.set_language('Python') self.preview_editor.set_text(PREVIEW_TEXT) self.preview_editor.set_blanks_enabled(False) self.preview_editor.set_scrollpastend_enabled(False) preview_interface_label = QLabel(_("Interface font")) self.preview_interface = QLabel("Sample text") self.preview_interface.setFixedWidth(260) self.preview_interface.setFixedHeight(45) self.preview_interface.setWordWrap(True) self.preview_interface.setTextInteractionFlags( Qt.TextEditorInteraction ) self.preview_interface.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) preview_interface_label_css = qstylizer.style.StyleSheet() preview_interface_label_css.QLabel.setValues( border=f"1px solid {SpyderPalette.COLOR_BACKGROUND_4}", borderRadius=SpyderPalette.SIZE_BORDER_RADIUS, backgroundColor=SpyderPalette.COLOR_BACKGROUND_2, ) self.preview_interface.setStyleSheet( preview_interface_label_css.toString() ) # Fonts layout fonts_grid_layout = QGridLayout() fonts_grid_layout.addWidget(self.plain_text_font.fontlabel, 0, 0) fonts_grid_layout.addWidget(self.plain_text_font.fontbox, 0, 1) fonts_grid_layout.addWidget(self.plain_text_font.sizebox, 0, 2) fonts_grid_layout.addWidget(self.app_font.fontlabel, 2, 0) fonts_grid_layout.addWidget(self.app_font.fontbox, 2, 1) fonts_grid_layout.addWidget(self.app_font.sizebox, 2, 2) fonts_grid_layout.setRowStretch(fonts_grid_layout.rowCount(), 1) fonts_layout = QVBoxLayout() fonts_layout.addLayout(fonts_grid_layout) fonts_layout.addSpacing(5) fonts_layout.addWidget(system_font_checkbox) fonts_group.setLayout(fonts_layout) # Left options layout options_layout = QVBoxLayout() options_layout.addWidget(theme_group) options_layout.addWidget(syntax_group) options_layout.addWidget(fonts_group) # Right previews layout preview_group = QGroupBox(_("Previews")) preview_layout = QVBoxLayout() preview_layout.addSpacing(AppStyle.MarginSize) preview_layout.addWidget(preview_editor_label) preview_layout.addWidget(self.preview_editor) preview_layout.addSpacing(2 * AppStyle.MarginSize) preview_layout.addWidget(preview_interface_label) preview_layout.addWidget(self.preview_interface) preview_group.setLayout(preview_layout) # Combined layout combined_layout = QGridLayout() combined_layout.setHorizontalSpacing(AppStyle.MarginSize * 5) combined_layout.addLayout(options_layout, 0, 0) combined_layout.addWidget(preview_group, 0, 1) # Final layout # Note: This is necessary to prevent the layout from growing downward # indefinitely. final_layout = QVBoxLayout() final_layout.addLayout(combined_layout) final_layout.addStretch() self.setLayout(final_layout) # Signals and slots create_button.clicked.connect(self.create_new_scheme) edit_button.clicked.connect(self.edit_scheme) self.reset_button.clicked.connect(self.reset_to_default) self.delete_button.clicked.connect(self.delete_scheme) self.schemes_combobox.currentIndexChanged.connect( lambda index: self.update_editor_preview() ) self.schemes_combobox.sig_popup_is_hidden.connect( self.update_editor_preview ) self.schemes_combobox.sig_item_in_popup_changed.connect( lambda scheme_name: self.update_editor_preview( scheme_name=scheme_name ) ) self.schemes_combobox.currentIndexChanged.connect(self.update_buttons) self.plain_text_font.fontbox.currentFontChanged.connect( lambda font: self.update_editor_preview() ) self.plain_text_font.fontbox.sig_popup_is_hidden.connect( self.update_editor_preview ) self.plain_text_font.fontbox.sig_item_in_popup_changed.connect( lambda font_family: self.update_editor_preview( scheme_name=None, font_family=font_family ) ) self.plain_text_font.sizebox.valueChanged.connect( lambda value: self.update_editor_preview() ) self.app_font.fontbox.currentFontChanged.connect( lambda font: self.update_interface_preview() ) self.app_font.fontbox.sig_popup_is_hidden.connect( self.update_interface_preview ) self.app_font.fontbox.sig_item_in_popup_changed.connect( self.update_interface_preview ) self.app_font.sizebox.valueChanged.connect( lambda value: self.update_interface_preview() ) system_font_checkbox.checkbox.stateChanged.connect( self.update_app_font_group ) # Setup for name in names: self.scheme_editor_dialog.add_color_scheme_stack(name) valid_custom_names = [] for name in custom_names: try: self.scheme_editor_dialog.add_color_scheme_stack( name, custom=True ) valid_custom_names.append(name) except configparser.NoOptionError: # Ignore invalid custom syntax highlighting themes # See spyder-ide/spyder#22492 pass self.set_option("custom_names", valid_custom_names) if sys.platform == 'darwin': system_font_checkbox.checkbox.setEnabled(False) self.update_app_font_group(system_font_checkbox.checkbox.isChecked()) self.update_combobox() self.update_editor_preview() def get_font(self, option): """Return global font used in Spyder.""" return get_font(option=option) def set_font(self, font, option): """Set global font used in Spyder.""" set_font(font, option=option) # The app font can't be set in place. Instead, it requires a restart if option != 'app_font': # Update fonts for all plugins plugins = self.main.widgetlist + self.main.thirdparty_plugins for plugin in plugins: plugin.update_font() def apply_settings(self): ui_theme = self.get_option('ui_theme') mismatch = self.color_scheme_and_ui_theme_mismatch( self.current_scheme, ui_theme) if ui_theme == 'automatic': if mismatch: # Ask for a restart self.changed_options.add('ui_theme') else: # Don't ask for a restart if 'ui_theme' in self.changed_options: self.changed_options.remove('ui_theme') else: if 'ui_theme' in self.changed_options: if not mismatch: # Don't ask for a restart self.changed_options.remove('ui_theme') else: if mismatch: # Ask for a restart self.changed_options.add('ui_theme') # We need to restore notifications for these options so they can be # changed when the user selects other values for them. for option in ['selected', 'ui_theme']: CONF.restore_notifications(section='appearance', option=option) self.update_combobox() self.update_editor_preview() # This applies changes to a custom color scheme to all open editors. # Fixes spyder-ide/spyder#22693 for plugin_name in PLUGIN_REGISTRY: plugin = PLUGIN_REGISTRY.get_plugin(plugin_name) plugin.update_font() return set(self.changed_options) # ---- Helpers # ------------------------------------------------------------------------- @property def current_scheme_name(self): return self.schemes_combobox.currentText() @property def current_scheme(self): return self.scheme_choices_dict[self.current_scheme_name] @property def current_scheme_index(self): return self.schemes_combobox.currentIndex() @property def current_ui_theme_index(self): return self.ui_combobox.currentIndex() # ---- Qt methods # ------------------------------------------------------------------------- def showEvent(self, event): """Adjustments when the page is shown.""" super().showEvent(event) if not self._is_shown: # Set the right interface font for Mac in the respective combobox, # so that preview_interface shows it appropriately. if sys.platform == "darwin": index = self.app_font.fontbox.findText("SF Pro") if index != -1: self.app_font.fontbox.setCurrentIndex(index) self._is_shown = True # ---- Update contents # ------------------------------------------------------------------------- def update_combobox(self): """Recreates the combobox contents.""" index = self.current_scheme_index self.schemes_combobox.blockSignals(True) names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass custom_names = self.get_option("custom_names", []) # Useful for retrieving the actual data for n in names + custom_names: # Make option value a string to prevent errors when using it # as widget text. # See spyder-ide/spyder#18929 self.scheme_choices_dict[ str(self.get_option('{0}/name'.format(n))) ] = n if custom_names: choices = names + [None] + custom_names else: choices = names combobox = self.schemes_combobox combobox.clear() for name in choices: if name is None: continue # Make option value a string to prevent errors when using it # as widget text. # See spyder-ide/spyder#18929 item_name = str(self.get_option('{0}/name'.format(name))) combobox.addItem(item_name, name) if custom_names: combobox.insertSeparator(len(names)) self.schemes_combobox.blockSignals(False) self.schemes_combobox.setCurrentIndex(index) def update_buttons(self): """Updates the enable status of delete and reset buttons.""" current_scheme = self.current_scheme names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass delete_enabled = current_scheme not in names self.delete_button.setEnabled(delete_enabled) self.reset_button.setEnabled(not delete_enabled) def update_editor_preview(self, scheme_name=None, font_family=None): """Update the color scheme of the preview editor and adds text.""" if scheme_name is None: scheme_name = self.current_scheme else: scheme_name = self.scheme_choices_dict[scheme_name] if font_family is None: plain_text_font = self.plain_text_font.fontbox.currentFont() else: plain_text_font = QFont(font_family) plain_text_font.setPointSize(self.plain_text_font.sizebox.value()) self.preview_editor.setup_editor( font=plain_text_font, color_scheme=scheme_name ) def update_interface_preview(self, font_family=None): """Update the interface preview label.""" if font_family is None: app_font = self.app_font.fontbox.currentFont() else: app_font = QFont(font_family) app_font.setPointSize(self.app_font.sizebox.value()) self.preview_interface.setFont(app_font) def update_app_font_group(self, state): """Update app font group enabled state.""" subwidgets = ['fontlabel', 'fontbox', 'sizebox'] if state: for widget in subwidgets: getattr(self.app_font, widget).setEnabled(False) else: for widget in subwidgets: getattr(self.app_font, widget).setEnabled(True) # ---- Actions # ------------------------------------------------------------------------- def create_new_scheme(self): """Creates a new color scheme with a custom name.""" names = self.get_option('names') custom_names = self.get_option('custom_names', []) # Get the available number this new color scheme counter = len(custom_names) - 1 custom_index = [int(n.split('-')[-1]) for n in custom_names] for i in range(len(custom_names)): if custom_index[i] != i: counter = i - 1 break custom_name = "custom-{0}".format(counter+1) # Add the config settings, based on the current one. custom_names.append(custom_name) self.set_option('custom_names', custom_names) for key in syntaxhighlighters.COLOR_SCHEME_KEYS: name = "{0}/{1}".format(custom_name, key) default_name = "{0}/{1}".format(self.current_scheme, key) option = self.get_option(default_name) self.set_option(name, option) self.set_option('{0}/name'.format(custom_name), custom_name) # Now they need to be loaded! how to make a partial load_from_conf? dlg = self.scheme_editor_dialog dlg.add_color_scheme_stack(custom_name, custom=True) dlg.set_scheme(custom_name) self.load_from_conf() if dlg.exec_(): # This is needed to have the custom name updated on the combobox name = dlg.get_scheme_name() self.set_option('{0}/name'.format(custom_name), name) # The +1 is needed because of the separator in the combobox index = (names + custom_names).index(custom_name) + 1 self.update_combobox() self.schemes_combobox.setCurrentIndex(index) else: # Delete the config .... custom_names.remove(custom_name) self.set_option('custom_names', custom_names) dlg.delete_color_scheme_stack(custom_name) def edit_scheme(self): """Edit current scheme.""" dlg = self.scheme_editor_dialog dlg.set_scheme(self.current_scheme) dlg.rejected.connect(lambda: self.apply_button_enabled.emit(False)) if dlg.exec_(): # Update temp scheme to reflect instant edits on the preview temporal_color_scheme = dlg.get_edited_color_scheme() for key in temporal_color_scheme: option = "temp/{0}".format(key) value = temporal_color_scheme[key] self.set_option(option, value) if not self.scheme_choices_dict.get("temp"): self.scheme_choices_dict["temp"] = "temp" self.update_editor_preview(scheme_name='temp') def delete_scheme(self): """Deletes the currently selected custom color scheme.""" scheme_name = self.current_scheme answer = QMessageBox.warning( self, _("Warning"), _("Are you sure you want to delete this theme?"), QMessageBox.Yes | QMessageBox.No, ) if answer == QMessageBox.Yes: # Put the combobox in Spyder by default, when deleting a scheme names = self.get_option('names') default_theme = 'spyder' if self.is_dark_interface(): default_theme = 'spyder/dark' self.schemes_combobox.setCurrentIndex(names.index(default_theme)) self.set_option('selected', default_theme) # Delete from custom_names custom_names = self.get_option('custom_names', []) if scheme_name in custom_names: custom_names.remove(scheme_name) self.set_option('custom_names', custom_names) # Delete config options for key in syntaxhighlighters.COLOR_SCHEME_KEYS: option = "{0}/{1}".format(scheme_name, key) CONF.remove_option(self.CONF_SECTION, option) CONF.remove_option(self.CONF_SECTION, "{0}/name".format(scheme_name)) self.update_combobox() self.update_editor_preview() def set_scheme(self, scheme_name): """ Set the current stack in the dialog to the scheme with 'scheme_name'. """ dlg = self.scheme_editor_dialog dlg.set_scheme(scheme_name) @Slot() def reset_to_default(self): """Restore initial values for default color schemes.""" # Checks that this is indeed a default scheme scheme = self.current_scheme names = self.get_option('names') if scheme in names: for key in syntaxhighlighters.COLOR_SCHEME_KEYS: option = "{0}/{1}".format(scheme, key) value = CONF.get_default(self.CONF_SECTION, option) self.set_option(option, value) self.load_from_conf() def is_dark_interface(self): """ Check if our interface is dark independently from our config system. We need to do this because when applying settings we can't detect correctly the current theme. """ return dark_color(SpyderPalette.COLOR_BACKGROUND_1) def color_scheme_and_ui_theme_mismatch(self, color_scheme, ui_theme): """ Detect if there is a mismatch between the current color scheme and UI theme. Parameters ---------- color_scheme: str Name of one of Spyder's color schemes. For instance: 'Zenburn' or 'Monokai'. ui_theme: str Name of the one of Spyder's interface themes. This can 'automatic', 'dark' or 'light'. """ # A dark color scheme is characterized by a light font and viceversa is_dark_color_scheme = not is_dark_font_color(color_scheme) if ui_theme == 'automatic': mismatch = ( (self.is_dark_interface() and not is_dark_color_scheme) or (not self.is_dark_interface() and is_dark_color_scheme) ) else: mismatch = ( (self.is_dark_interface() and ui_theme == 'light') or (not self.is_dark_interface() and ui_theme == 'dark') ) return mismatch def check_color_scheme_notification(self): """ Check if it's necessary to notify plugins to update their color scheme. """ ui_theme_map = {0: 'automatic', 1: 'light', 2: 'dark'} ui_theme = ui_theme_map[self.current_ui_theme_index] mismatch = self.color_scheme_and_ui_theme_mismatch( self.current_scheme, ui_theme) # We don't need to apply the selected color scheme if there's a # mismatch between it and the UI theme. Instead, we only we need to ask # for a restart. if mismatch: for option in ['selected', 'ui_theme']: CONF.disable_notifications(section='appearance', option=option)
AppearanceConfigPage
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 38458, "end": 42350 }
class ____(BaseAsyncRealtimeConnectionResource): async def delete(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: """Send this event when you want to remove any item from the conversation history. The server will respond with a `conversation.item.deleted` event, unless the item does not exist in the conversation history, in which case the server will respond with an error. """ await self._connection.send( cast( RealtimeClientEventParam, strip_not_given({"type": "conversation.item.delete", "item_id": item_id, "event_id": event_id}), ) ) async def create( self, *, item: ConversationItemParam, event_id: str | NotGiven = NOT_GIVEN, previous_item_id: str | NotGiven = NOT_GIVEN, ) -> None: """ Add a new Item to the Conversation's context, including messages, function calls, and function call responses. This event can be used both to populate a "history" of the conversation and to add new items mid-stream, but has the current limitation that it cannot populate assistant audio messages. If successful, the server will respond with a `conversation.item.created` event, otherwise an `error` event will be sent. """ await self._connection.send( cast( RealtimeClientEventParam, strip_not_given( { "type": "conversation.item.create", "item": item, "event_id": event_id, "previous_item_id": previous_item_id, } ), ) ) async def truncate( self, *, audio_end_ms: int, content_index: int, item_id: str, event_id: str | NotGiven = NOT_GIVEN ) -> None: """Send this event to truncate a previous assistant message’s audio. The server will produce audio faster than realtime, so this event is useful when the user interrupts to truncate audio that has already been sent to the client but not yet played. This will synchronize the server's understanding of the audio with the client's playback. Truncating audio will delete the server-side text transcript to ensure there is not text in the context that hasn't been heard by the user. If successful, the server will respond with a `conversation.item.truncated` event. """ await self._connection.send( cast( RealtimeClientEventParam, strip_not_given( { "type": "conversation.item.truncate", "audio_end_ms": audio_end_ms, "content_index": content_index, "item_id": item_id, "event_id": event_id, } ), ) ) async def retrieve(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: """ Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD. The server will respond with a `conversation.item.retrieved` event, unless the item does not exist in the conversation history, in which case the server will respond with an error. """ await self._connection.send( cast( RealtimeClientEventParam, strip_not_given({"type": "conversation.item.retrieve", "item_id": item_id, "event_id": event_id}), ) )
AsyncRealtimeConversationItemResource
python
python__mypy
mypy/test/teststubtest.py
{ "start": 1094, "end": 1350 }
class ____: def __getitem__(self, typeargs: Any) -> object: ... Callable: _SpecialForm = ... Generic: _SpecialForm = ... Protocol: _SpecialForm = ... Union: _SpecialForm = ... ClassVar: _SpecialForm = ... Final = 0 Literal = 0 TypedDict = 0
_SpecialForm
python
django__django
tests/admin_views/admin.py
{ "start": 21697, "end": 21941 }
class ____(admin.ModelAdmin): def extra(self, request): return HttpResponse() def get_urls(self): # Corner case: Don't call parent implementation return [path("extra/", self.extra, name="cable_extra")]
ReportAdmin
python
pyca__cryptography
tests/hazmat/primitives/test_xofhash.py
{ "start": 2610, "end": 3695 }
class ____: def test_shake128_variable(self, backend, subtests): vectors = _load_all_params( os.path.join("hashes", "SHAKE"), ["SHAKE128VariableOut.rsp"], load_nist_vectors, ) for vector in vectors: with subtests.test(): output_length = int(vector["outputlen"]) // 8 msg = binascii.unhexlify(vector["msg"]) shake = hashes.SHAKE128(digest_size=output_length) m = hashes.XOFHash(shake) m.update(msg) remaining = output_length data = b"" stride = random.randint(1, 128) while remaining > 0: stride = min(stride, remaining) data += m.squeeze(stride) remaining -= stride assert data == binascii.unhexlify(vector["output"]) @pytest.mark.supported( only_if=lambda backend: rust_openssl.CRYPTOGRAPHY_OPENSSL_330_OR_GREATER, skip_message="Requires backend with XOF support", )
TestXOFSHAKE128
python
getsentry__sentry
tests/sentry/models/test_team.py
{ "start": 2852, "end": 4387 }
class ____(TestCase): def test_hybrid_cloud_deletion(self) -> None: org = self.create_organization() team = self.create_team(org) base_params = { "team_id": team.id, "scope_type": "team", "scope_identifier": team.id, "value": "always", } with assume_test_silo_mode(SiloMode.CONTROL): NotificationSettingOption.objects.create(**base_params) NotificationSettingProvider.objects.create(provider="slack", **base_params) assert Team.objects.filter(id=team.id).exists() team_id = team.id with outbox_runner(): team.delete() assert not Team.objects.filter(id=team_id).exists() with assume_test_silo_mode(SiloMode.CONTROL): # cascade is asynchronous, ensure there is still related search, assert NotificationSettingOption.objects.filter(**base_params).exists() assert NotificationSettingProvider.objects.filter(**base_params).exists() # Run foreign key cascades to remove control silo state. with self.tasks(), assume_test_silo_mode(SiloMode.CONTROL): schedule_hybrid_cloud_foreign_key_jobs_control() assert not Team.objects.filter(id=team_id).exists() with assume_test_silo_mode(SiloMode.CONTROL): assert not NotificationSettingOption.objects.filter(**base_params).exists() assert not NotificationSettingProvider.objects.filter(**base_params).exists()
TeamDeletionTest
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks.py
{ "start": 1974, "end": 3024 }
class ____: """Base timer for determining when Hooks should trigger. Should not be instantiated directly. """ def __init__(self): pass def reset(self): """Resets the timer.""" pass def should_trigger_for_step(self, step): """Return true if the timer should trigger for the specified step.""" raise NotImplementedError def update_last_triggered_step(self, step): """Update the last triggered time and step number. Args: step: The current step. Returns: A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number of seconds between the current trigger and the last one (a float), and `elapsed_steps` is the number of steps between the current trigger and the last one. Both values will be set to `None` on the first trigger. """ raise NotImplementedError def last_triggered_step(self): """Returns the last triggered time step or None if never triggered.""" raise NotImplementedError @tf_export(v1=["train.SecondOrStepTimer"])
_HookTimer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1249331, "end": 1249576 }
class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData): """Audit log entry for a org.disable_oauth_app_restrictions event.""" __schema__ = github_schema __field_names__ = ()
OrgDisableOauthAppRestrictionsAuditEntry
python
kamyu104__LeetCode-Solutions
Python/maximum-level-sum-of-a-binary-tree.py
{ "start": 87, "end": 227 }
class ____(object): def __init__(self, x): self.val = x self.left = None self.right = None # dfs solution
TreeNode
python
ray-project__ray
python/ray/tests/test_runtime_env_plugin.py
{ "start": 5328, "end": 7101 }
class ____(DummyPlugin): name = HANG_PLUGIN_NAME async def create( self, uri: str, runtime_env: "RuntimeEnv", ctx: RuntimeEnvContext, logger: logging.Logger, # noqa: F821 ) -> float: await asyncio.sleep(3600) @pytest.mark.parametrize( "set_runtime_env_plugins", [ '[{"class":"' + DUMMY_PLUGIN_CLASS_PATH + '"},' '{"class":"' + HANG_PLUGIN_CLASS_PATH + '"}]', ], indirect=True, ) @pytest.mark.skipif(external_redis_test_enabled(), reason="Failing in redis mode.") def test_plugin_timeout(set_runtime_env_plugins, start_cluster): @ray.remote(num_cpus=0.1) def f(): return True refs = [ f.options( runtime_env={ HANG_PLUGIN_NAME: {"name": "f1"}, "config": {"setup_timeout_seconds": 1}, } ).remote(), f.options(runtime_env={DUMMY_PLUGIN_NAME: {"name": "f2"}}).remote(), f.options( runtime_env={ HANG_PLUGIN_NAME: {"name": "f3"}, "config": {"setup_timeout_seconds": -1}, } ).remote(), ] def condition(): good_fun_num = 0 bad_fun_num = 0 for ref in refs: try: res = ray.get(ref, timeout=1) print("result:", res) if res: good_fun_num += 1 return True except RuntimeEnvSetupError: bad_fun_num += 1 return bad_fun_num == 1 and good_fun_num == 2 wait_for_condition(condition, timeout=60) FAULT_PLUGIN_CLASS_PATH = "ray.tests.test_runtime_env_plugin.FaultPlugin" FAULT_PLUGIN_NAME = "FaultPlugin" FAULT_PLUGIN_KEY = "FAULT_PLUGIN_KEY"
HangPlugin
python
dask__dask
dask/dataframe/dask_expr/_describe.py
{ "start": 643, "end": 2406 }
class ____(Reduction): _parameters = ["frame", "split_every", "percentiles", "percentile_method"] _defaults = { "percentiles": None, "split_every": None, "percentile_method": "default", } @functools.cached_property def _meta(self): return make_meta(meta_nonempty(self.frame._meta).describe()) def _divisions(self): return (None, None) def _lower(self): frame = self.frame if self.percentiles is None: percentiles = self.percentiles or [0.25, 0.5, 0.75] else: percentiles = np.array(self.percentiles) if not PANDAS_GE_300: percentiles = np.append(percentiles, 0.5) percentiles = np.unique(percentiles) percentiles = list(percentiles) is_td_col = is_timedelta64_dtype(frame._meta.dtype) is_dt_col = is_datetime64_any_dtype(frame._meta.dtype) if is_td_col or is_dt_col: frame = ToNumeric(DropnaSeries(frame)) stats = [ frame.count(split_every=self.split_every), frame.mean(split_every=self.split_every), Sqrt(frame.var(split_every=self.split_every)), frame.min(split_every=self.split_every), SeriesQuantile(frame, q=percentiles, method=self.percentile_method), frame.max(split_every=self.split_every), ] try: unit = getattr(self.frame._meta.array, "unit", None) except AttributeError: # cudf Series has no array attribute unit = None return DescribeNumericAggregate( self.frame._meta.name, is_td_col, is_dt_col, unit, *stats, )
DescribeNumeric
python
streamlit__streamlit
lib/streamlit/runtime/caching/storage/in_memory_cache_storage_wrapper.py
{ "start": 1035, "end": 5320 }
class ____(CacheStorage): """ In-memory cache storage wrapper. This class wraps a cache storage and adds an in-memory cache front layer, which is used to reduce the number of calls to the storage. The in-memory cache is a TTL cache, which means that the entries are automatically removed if a given time to live (TTL) has passed. The in-memory cache is also an LRU cache, which means that the entries are automatically removed if the cache size exceeds a given maxsize. If the storage implements its strategy for maxsize, it is recommended (but not necessary) that the storage implement the same LRU strategy, otherwise a situation may arise when different items are deleted from the memory cache and from the storage. Notes ----- Threading: in-memory caching layer is thread safe: we hold self._mem_cache_lock for working with this self._mem_cache object. However, we do not hold this lock when calling into the underlying storage, so it is the responsibility of the that storage to ensure that it is safe to use it from multiple threads. """ def __init__( self, persist_storage: CacheStorage, context: CacheStorageContext ) -> None: self.function_key = context.function_key self.function_display_name = context.function_display_name self._ttl_seconds = context.ttl_seconds self._max_entries = context.max_entries self._mem_cache: TTLCache[str, bytes] = TTLCache( maxsize=self.max_entries, ttl=self.ttl_seconds, timer=cache_utils.TTLCACHE_TIMER, ) self._mem_cache_lock = threading.Lock() self._persist_storage = persist_storage @property def ttl_seconds(self) -> float: return self._ttl_seconds if self._ttl_seconds is not None else math.inf @property def max_entries(self) -> float: return float(self._max_entries) if self._max_entries is not None else math.inf def get(self, key: str) -> bytes: """ Returns the stored value for the key or raise CacheStorageKeyNotFoundError if the key is not found. """ try: entry_bytes = self._read_from_mem_cache(key) except CacheStorageKeyNotFoundError: entry_bytes = self._persist_storage.get(key) self._write_to_mem_cache(key, entry_bytes) return entry_bytes def set(self, key: str, value: bytes) -> None: """Sets the value for a given key.""" self._write_to_mem_cache(key, value) self._persist_storage.set(key, value) def delete(self, key: str) -> None: """Delete a given key.""" self._remove_from_mem_cache(key) self._persist_storage.delete(key) def clear(self) -> None: """Delete all keys for the in memory cache, and also the persistent storage.""" with self._mem_cache_lock: self._mem_cache.clear() self._persist_storage.clear() def get_stats(self) -> list[CacheStat]: """Returns a list of stats in bytes for the cache memory storage per item.""" with self._mem_cache_lock: return [ CacheStat( category_name="st_cache_data", cache_name=self.function_display_name, byte_length=len(item), ) for item in self._mem_cache.values() ] def close(self) -> None: """Closes the cache storage.""" self._persist_storage.close() def _read_from_mem_cache(self, key: str) -> bytes: with self._mem_cache_lock: if key in self._mem_cache: entry = bytes(self._mem_cache[key]) _LOGGER.debug("Memory cache HIT: %s", key) return entry _LOGGER.debug("Memory cache MISS: %s", key) raise CacheStorageKeyNotFoundError("Key not found in mem cache") def _write_to_mem_cache(self, key: str, entry_bytes: bytes) -> None: with self._mem_cache_lock: self._mem_cache[key] = entry_bytes def _remove_from_mem_cache(self, key: str) -> None: with self._mem_cache_lock: self._mem_cache.pop(key, None)
InMemoryCacheStorageWrapper
python
django__django
tests/utils_tests/test_duration.py
{ "start": 3405, "end": 3941 }
class ____(unittest.TestCase): def test(self): deltas = [ datetime.timedelta.max, datetime.timedelta.min, datetime.timedelta.resolution, -datetime.timedelta.resolution, datetime.timedelta(microseconds=8999999999999999), ] for delta in deltas: with self.subTest(delta=delta): self.assertEqual( datetime.timedelta(microseconds=duration_microseconds(delta)), delta )
TestDurationMicroseconds
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/matrix_logarithm_op_test.py
{ "start": 5680, "end": 6880 }
class ____(test.Benchmark): shapes = [ (4, 4), (10, 10), (16, 16), (101, 101), (256, 256), (1000, 1000), (1024, 1024), (2048, 2048), (513, 4, 4), (513, 16, 16), (513, 256, 256), ] def _GenerateMatrix(self, shape): batch_shape = shape[:-2] shape = shape[-2:] assert shape[0] == shape[1] n = shape[0] matrix = np.ones(shape).astype(np.complex64) / (2.0 * n) + np.diag( np.ones(n).astype(np.complex64)) return variables.Variable(np.tile(matrix, batch_shape + (1, 1))) def benchmarkMatrixLogarithmOp(self): for shape in self.shapes: with ops.Graph().as_default(), \ session.Session(config=benchmark.benchmark_config()) as sess, \ ops.device("/cpu:0"): matrix = self._GenerateMatrix(shape) logm = gen_linalg_ops.matrix_logarithm(matrix) self.evaluate(variables.global_variables_initializer()) self.run_op_benchmark( sess, control_flow_ops.group(logm), min_iters=25, name="matrix_logarithm_cpu_{shape}".format(shape=shape)) if __name__ == "__main__": test.main()
MatrixLogarithmBenchmark
python
django__django
django/templatetags/tz.py
{ "start": 2129, "end": 2542 }
class ____(Node): """ Template node class used by ``localtime_tag``. """ def __init__(self, nodelist, use_tz): self.nodelist = nodelist self.use_tz = use_tz def render(self, context): old_setting = context.use_tz context.use_tz = self.use_tz output = self.nodelist.render(context) context.use_tz = old_setting return output
LocalTimeNode
python
huggingface__transformers
tests/models/gptj/test_modeling_gptj.py
{ "start": 19218, "end": 24531 }
class ____(unittest.TestCase): @tooslow def test_lm_generate_gptj(self): # Marked as @tooslow due to GPU OOM for checkpointing in [True, False]: model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", revision="float16", dtype=torch.float16) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(torch_device) input_ids = torch.tensor([[464, 3290]], dtype=torch.long, device=torch_device) # The dog # The dog is a man's best friend. It is a loyal companion, and it is a friend expected_output_ids = [464, 3290, 318, 257, 582, 338, 1266, 1545, 13, 632, 318, 257, 9112, 15185, 11, 290, 340, 318, 257, 1545] # fmt: skip output_ids = model.generate(input_ids, do_sample=False) self.assertListEqual(output_ids[0].tolist(), expected_output_ids) @tooslow def test_gptj_sample(self): # Marked as @tooslow due to GPU OOM (issue #13676) tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B", revision="float16") model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", revision="float16", dtype=torch.float16) model.to(torch_device) torch.manual_seed(0) tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True) input_ids = tokenized.input_ids.to(torch_device) output_ids = model.generate(input_ids, do_sample=True) output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True) token_type_ids = tokenized.token_type_ids.to(torch_device) output_seq = model.generate(input_ids=input_ids, do_sample=True, num_return_sequences=5) output_seq_tt = model.generate( input_ids=input_ids, token_type_ids=token_type_ids, do_sample=True, num_return_sequences=5 ) output_seq_strs = tokenizer.batch_decode(output_seq, skip_special_tokens=True) output_seq_tt_strs = tokenizer.batch_decode(output_seq_tt, skip_special_tokens=True) if torch_device != "cpu": # currently this expect value is only for `cuda` EXPECTED_OUTPUT_STR = ( "Today is a nice day and I've already been enjoying it. I walked to work with my wife" ) else: EXPECTED_OUTPUT_STR = "Today is a nice day and one of those days that feels a bit more alive. I am ready" self.assertEqual(output_str, EXPECTED_OUTPUT_STR) self.assertTrue( all(output_seq_strs[idx] != output_seq_tt_strs[idx] for idx in range(len(output_seq_tt_strs))) ) # token_type_ids should change output # TODO joao, manuel: remove this in v4.62.0 @tooslow def test_contrastive_search_gptj(self): article = ( "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and " "research laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based" ) tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B") model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", revision="float16", dtype=torch.float16).to( torch_device ) input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device) outputs = model.generate( input_ids, penalty_alpha=0.6, top_k=4, max_length=256, trust_remote_code=True, custom_generate="transformers-community/contrastive-search", ) generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True) self.assertListEqual( generated_text, [ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research " "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, " "United Kingdom with offices in Mountain View, San Francisco, New York City, Paris, Tokyo, Seoul, " "Beijing, Singapore, Tel Aviv, Dublin, Sydney, and Melbourne.[1]\n\nContents\n\nIn 2010, Google's " "parent company, Alphabet, announced a $500 million investment in DeepMind, with the aim of creating " "a company that would apply deep learning to problems in healthcare, energy, transportation, and " "other areas.[2]\n\nOn April 23, 2014, Google announced that it had acquired DeepMind for $400 " "million in cash and stock.[3] The acquisition was seen as a way for Google to enter the " "fast-growing field of artificial intelligence (AI), which it had so far avoided due to concerns " 'about ethical and social implications.[4] Google co-founder Sergey Brin said that he was "thrilled" ' 'to have acquired DeepMind, and that it would "help us push the boundaries of AI even further."' "[5]\n\nDeepMind's founders, Demis Hassabis and Mustafa Suleyman, were joined by a number of Google " "employees" ], )
GPTJModelLanguageGenerationTest
python
pymupdf__PyMuPDF
pipcl.py
{ "start": 120570, "end": 130526 }
class ____: ''' Detects new/modified/updated files matching a glob pattern. Useful for detecting wheels created by pip or cubuildwheel etc. ''' def __init__(self, glob_pattern): # Find current matches of <glob_pattern>. self.glob_pattern = glob_pattern self.items0 = self._items() def get(self): ''' Returns list of new matches of <glob_pattern> - paths of files that were not present previously, or have different mtimes or have different contents. ''' ret = list() items = self._items() for path, id_ in items.items(): id0 = self.items0.get(path) if id0 != id_: ret.append(path) return ret def get_n(self, n): ''' Returns new files matching <glob_pattern>, asserting that there are exactly <n>. ''' ret = self.get() assert len(ret) == n, f'{len(ret)=}: {ret}' return ret def get_one(self): ''' Returns new match of <glob_pattern>, asserting that there is exactly one. ''' return self.get_n(1)[0] def _file_id(self, path): mtime = os.stat(path).st_mtime with open(path, 'rb') as f: content = f.read() hash_ = hashlib.md5(content).digest() # With python >= 3.11 we can do: #hash_ = hashlib.file_digest(f, hashlib.md5).digest() return mtime, hash_ def _items(self): ret = dict() for path in glob.glob(self.glob_pattern): if os.path.isfile(path): ret[path] = self._file_id(path) return ret def swig_get(swig, quick, swig_local='pipcl-swig-git'): ''' Returns <swig> or a new swig binary. If <swig> is true and starts with 'git:' (not Windows), the remaining text is passed to git_get() and we clone/update/build swig, and return the built binary. We default to the main swig repository, branch master, so for example 'git:' will return the latest swig from branch master. Otherwise we simply return <swig>. Args: swig: If starts with 'git:', passed as <text> arg to git_get(). quick: If true, we do not update/build local checkout if the binary is already present. swig_local: path to use for checkout. ''' if swig and swig.startswith('git:'): assert platform.system() != 'Windows', f'Cannot build swig on Windows.' # Note that {swig_local}/install/bin/swig doesn't work on MacOS because # {swig_local}/INSTALL is a file and the fs is case-insensitive. swig_binary = f'{swig_local}/install-dir/bin/swig' if quick and os.path.isfile(swig_binary): log1(f'{quick=} and {swig_binary=} already exists, so not downloading/building.') else: # Clone swig. swig_env_extra = None swig_local = git_get( swig_local, text=swig, remote='https://github.com/swig/swig.git', branch='master', ) if darwin(): run(f'brew install automake') run(f'brew install pcre2') run(f'brew install bison') # Default bison doesn't work, and Brew's bison is not added to $PATH. # # > bison is keg-only, which means it was not symlinked into /opt/homebrew, # > because macOS already provides this software and installing another version in # > parallel can cause all kinds of trouble. # > # > If you need to have bison first in your PATH, run: # > echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc # swig_env_extra = dict() macos_add_brew_path('bison', swig_env_extra) run(f'which bison') run(f'which bison', env_extra=swig_env_extra) # Build swig. run(f'cd {swig_local} && ./autogen.sh', env_extra=swig_env_extra) run(f'cd {swig_local} && ./configure --prefix={swig_local}/install-dir', env_extra=swig_env_extra) run(f'cd {swig_local} && make', env_extra=swig_env_extra) run(f'cd {swig_local} && make install', env_extra=swig_env_extra) assert os.path.isfile(swig_binary) return swig_binary else: return swig def macos_add_brew_path(package, env=None, gnubin=True): ''' Adds path(s) for Brew <package>'s binaries to env['PATH']. We assert-fail if the relevant directory does no exist. Args: package: Name of package. We get <package_root> of installed package by running `brew --prefix <package>`. env: The environment dict to modify. If None we use os.environ. If PATH is not in <env>, we first copy os.environ['PATH'] into <env>. gnubin: If true, we also add path to gnu binaries if it exists, <package_root>/libexe/gnubin. ''' if not darwin(): return if env is None: env = os.environ if 'PATH' not in env: env['PATH'] = os.environ['PATH'] package_root = run(f'brew --prefix {package}', capture=1).strip() log(f'{package=} {package_root=}') def add(path): log(f'{path=}') if os.path.isdir(path): log(f'Prepending to $PATH: {path}') PATH = env['PATH'] env['PATH'] = f'{path}:{PATH}' return 1 else: log(f'Not a directory: {path=}') return 0 n = 0 n += add(f'{package_root}/bin') if gnubin: n += add(f'{package_root}/libexec/gnubin') assert n, f'Failed to add to $PATH, {package=} {gnubin=}.' def _show_dict(d): ret = '' for n in sorted(d.keys()): v = d[n] ret += f' {n}: {v!r}\n' return ret def show_sysconfig(): ''' Shows contents of sysconfig.get_paths() and sysconfig.get_config_vars() dicts. ''' import sysconfig paths = sysconfig.get_paths() log0(f'show_sysconfig().') log0(f'sysconfig.get_paths():\n{_show_dict(sysconfig.get_paths())}') log0(f'sysconfig.get_config_vars():\n{_show_dict(sysconfig.get_config_vars())}') def sysconfig_python_flags(): ''' Returns include paths and library directory for Python. Uses sysconfig.*(), overridden by environment variables PIPCL_SYSCONFIG_PATH_include, PIPCL_SYSCONFIG_PATH_platinclude and PIPCL_SYSCONFIG_CONFIG_VAR_LIBDIR if set. ''' include1_ = os.environ.get('PIPCL_SYSCONFIG_PATH_include') or sysconfig.get_path('include') include2_ = os.environ.get('PIPCL_SYSCONFIG_PATH_platinclude') or sysconfig.get_path('platinclude') ldflags_ = os.environ.get('PIPCL_SYSCONFIG_CONFIG_VAR_LIBDIR') or sysconfig.get_config_var('LIBDIR') includes_ = [include1_] if include2_ != include1_: includes_.append(include2_) if windows(): includes_ = [f'/I"{i}"' for i in includes_] ldflags_ = f'/LIBPATH:"{ldflags_}"' else: includes_ = [f'-I {i}' for i in includes_] ldflags_ = f'-L {ldflags_}' includes_ = ' '.join(includes_) return includes_, ldflags_ def venv_in(path=None): ''' If path is None, returns true if we are in a venv. Otherwise returns true only if we are in venv <path>. ''' if path: return os.path.abspath(sys.prefix) == os.path.abspath(path) else: return sys.prefix != sys.base_prefix def venv_run(args, path, recreate=True, clean=False): ''' Runs Python command inside venv and returns termination code. Args: args: List of args or string command. path: Path of venv directory. recreate: If false we do not run `<sys.executable> -m venv <path>` if <path> already exists. This avoids a delay in the common case where <path> is already set up, but fails if <path> exists but does not contain a valid venv. clean: If true we first delete <path>. ''' if clean: log(f'Removing any existing venv {path}.') assert path.startswith('venv-') shutil.rmtree(path, ignore_errors=1) if recreate or not os.path.isdir(path): run(f'{sys.executable} -m venv {path}') if isinstance(args, str): args_string = args elif platform.system() == 'Windows': # shlex not reliable on Windows so we use Use crude quoting with "...". args_string = '' for i, arg in enumerate(args): assert '"' not in arg if i: args_string += ' ' args_string += f'"{arg}"' else: args_string = shlex.join(args) if platform.system() == 'Windows': command = f'{path}\\Scripts\\activate && python {args_string}' else: command = f'. {path}/bin/activate && python {args_string}' e = run(command, check=0) return e if __name__ == '__main__': # Internal-only limited command line support, used if # graal_legacy_python_config is true. # includes, ldflags = sysconfig_python_flags() if sys.argv[1] == '--doctest': import doctest if sys.argv[2:]: for f in sys.argv[2:]: ff = globals()[f] doctest.run_docstring_examples(ff, globals()) else: doctest.testmod(None) elif sys.argv[1:] == ['--graal-legacy-python-config', '--includes']: print(includes) elif sys.argv[1:] == ['--graal-legacy-python-config', '--ldflags']: print(ldflags) else: assert 0, f'Expected `--graal-legacy-python-config --includes|--ldflags` but {sys.argv=}'
NewFiles
python
django-mptt__django-mptt
mptt/forms.py
{ "start": 1839, "end": 1993 }
class ____( TreeNodeChoiceFieldMixin, forms.ModelMultipleChoiceField ): """A ModelMultipleChoiceField for tree nodes."""
TreeNodeMultipleChoiceField
python
conda__conda
conda/exceptions.py
{ "start": 20497, "end": 20856 }
class ____(CondaError): def __init__(self, prefix: PathType, package_name: str): message = dals( """ Package is not installed in prefix. prefix: %(prefix)s package name: %(package_name)s """ ) super().__init__(message, prefix=prefix, package_name=package_name)
PackageNotInstalledError
python
mlflow__mlflow
mlflow/gateway/schemas/completions.py
{ "start": 333, "end": 516 }
class ____(BaseRequestPayload, RequestModel): prompt: str model: str | None = None model_config = ConfigDict(json_schema_extra=_REQUEST_PAYLOAD_EXTRA_SCHEMA)
RequestPayload
python
viewflow__viewflow
viewflow/urls/model.py
{ "start": 7074, "end": 9521 }
class ____(metaclass=ViewsetMeta): delete_view_class = DeleteModelView def has_delete_permission(self, user, obj=None): return has_object_perm(user, "delete", self.model, obj=obj) """ Bulk delete """ bulk_delete_view_class = DeleteBulkActionView def get_bulk_delete_view_kwargs(self, **kwargs): view_kwargs = { "filterset_class": self.list_filterset_class, "filter_fields": self.list_filter_fields, **self.bulk_delete_view_kwargs, **kwargs, } return self.filter_kwargs(self.bulk_delete_view_class, **view_kwargs) @viewprop def bulk_delete_view_kwargs(self): return {} @viewprop def bulk_delete_view(self): return self.bulk_delete_view_class.as_view(**self.get_bulk_delete_view_kwargs()) @property def bulk_delete_path(self): return path("action/delete/", self.bulk_delete_view, name="bulk_delete") def get_list_bulk_actions(self, request, *actions): if self.has_delete_permission(request.user): bulk_delete_action = Action( name="Delete selected objects", url=self.reverse("bulk_delete"), icon=Icon("delete", class_="material-icons mdc-list-item__graphic"), ) actions = (bulk_delete_action, *actions) return super().get_list_bulk_actions(request, *actions) """ Delete single object """ def get_delete_view_kwargs(self, **kwargs): view_kwargs = {**self.delete_view_kwargs, **kwargs} return self.filter_kwargs(self.delete_view_class, **view_kwargs) @viewprop def delete_view_kwargs(self): return {} @viewprop def delete_view(self): return self.delete_view_class.as_view(**self.get_delete_view_kwargs()) @property def delete_path(self): return path("<path:pk>/delete/", self.delete_view, name="delete") def get_update_page_actions(self, request, obj, *actions): if self.has_delete_permission(request.user): actions = ( Action( name="Delete", url=self.reverse("delete", args=[obj.pk]), icon=Icon("delete", class_="material-icons mdc-list-item__graphic"), ), *actions, ) return super().get_update_page_actions(request, obj, *actions)
DeleteViewMixin
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 235822, "end": 242319 }
class ____: params = [ [[1, 2, 3], [1.1, 2.9, 4.2], 0.53619490753126731, -0.6864951273557258, .2], [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2], 0.00998909252078421, 4.591598691181999, .2], [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2], 0.10512380092302633, 2.832256715395378, .32], [[2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9], [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1], 0.002878909511344, -4.2461168970325, .2], [[-0.84504783, 0.13366078, 3.53601757, -0.62908581, 0.54119466, -1.16511574, -0.08836614, 1.18495416, 2.48028757, -1.58925028, -1.6706357, 0.3090472, -2.12258305, 0.3697304, -1.0415207, -0.57783497, -0.90997008, 1.09850192, 0.41270579, -1.4927376], [1.2725522, 1.1657899, 2.7509041, 1.2389013, -0.9490494, -1.0752459, 1.1038576, 2.9912821, 3.5349111, 0.4171922, 1.0168959, -0.7625041, -0.4300008, 3.0431921, 1.6035947, 0.5285634, -0.7649405, 1.5575896, 1.3670797, 1.1726023], 0.005293305834235, -3.0983317739483, .2]] @pytest.mark.parametrize("a,b,pr,tr,trim", params) def test_ttest_compare_r(self, a, b, pr, tr, trim): ''' Using PairedData's yuen.t.test method. Something to note is that there are at least 3 R packages that come with a trimmed t-test method, and comparisons were made between them. It was found that PairedData's method's results match this method, SAS, and one of the other R methods. A notable discrepancy was the DescTools implementation of the function, which only sometimes agreed with SAS, WRS2, PairedData and this implementation. For this reason, most comparisons in R are made against PairedData's method. Rather than providing the input and output for all evaluations, here is a representative example: > library(PairedData) > a <- c(1, 2, 3) > b <- c(1.1, 2.9, 4.2) > options(digits=16) > yuen.t.test(a, b, tr=.2) Two-sample Yuen test, trim=0.2 data: x and y t = -0.68649512735573, df = 3.4104431643464, p-value = 0.5361949075313 alternative hypothesis: true difference in trimmed means is not equal to 0 95 percent confidence interval: -3.912777195645217 2.446110528978550 sample estimates: trimmed mean of x trimmed mean of y 2.000000000000000 2.73333333333333 ''' statistic, pvalue = stats.ttest_ind(a, b, trim=trim, equal_var=False) assert_allclose(statistic, tr, atol=1e-15) assert_allclose(pvalue, pr, atol=1e-15) def test_compare_SAS(self): # Source of the data used in this test: # https://support.sas.com/resources/papers/proceedings14/1660-2014.pdf a = [12, 14, 18, 25, 32, 44, 12, 14, 18, 25, 32, 44] b = [17, 22, 14, 12, 30, 29, 19, 17, 22, 14, 12, 30, 29, 19] # In this paper, a trimming percentage of 5% is used. However, # in their implementation, the number of values trimmed is rounded to # the nearest whole number. However, consistent with # `scipy.stats.trimmed_mean`, this test truncates to the lower # whole number. In this example, the paper notes that 1 value is # trimmed off of each side. 9% replicates this amount of trimming. statistic, pvalue = stats.ttest_ind(a, b, trim=.09, equal_var=False) assert_allclose(pvalue, 0.514522, atol=1e-6) assert_allclose(statistic, 0.669169, atol=1e-6) def test_equal_var(self): ''' The PairedData library only supports unequal variances. To compare samples with equal variances, the multicon library is used. > library(multicon) > a <- c(2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9) > b <- c(6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1) > dv = c(a,b) > iv = c(rep('a', length(a)), rep('b', length(b))) > yuenContrast(dv~ iv, EQVAR = TRUE) $Ms N M wgt a 11 2.442857142857143 1 b 11 5.385714285714286 -1 $test stat df crit p results -4.246116897032513 12 2.178812829667228 0.00113508833897713 ''' a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9] b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1] # `equal_var=True` is default statistic, pvalue = stats.ttest_ind(a, b, trim=.2) assert_allclose(pvalue, 0.00113508833897713, atol=1e-10) assert_allclose(statistic, -4.246116897032513, atol=1e-10) @pytest.mark.parametrize('alt,pr,tr', (('greater', 0.9985605452443, -4.2461168970325), ('less', 0.001439454755672, -4.2461168970325),), ) def test_alternatives(self, alt, pr, tr): ''' > library(PairedData) > a <- c(2.7,2.7,1.1,3.0,1.9,3.0,3.8,3.8,0.3,1.9,1.9) > b <- c(6.5,5.4,8.1,3.5,0.5,3.8,6.8,4.9,9.5,6.2,4.1) > options(digits=16) > yuen.t.test(a, b, alternative = 'greater') ''' a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9] b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1] statistic, pvalue = stats.ttest_ind(a, b, trim=.2, equal_var=False, alternative=alt) assert_allclose(pvalue, pr, atol=1e-10) assert_allclose(statistic, tr, atol=1e-10) @skip_xp_backends(cpu_only=True, reason='Uses NumPy for pvalue, CI') def test_permutation_not_implement_for_xp(self, xp): message = "Use of `trim` is compatible only with NumPy arrays." a, b = xp.arange(10), xp.arange(10)+1 if is_numpy(xp): # no error stats.ttest_ind(a, b, trim=0.1) else: # NotImplementedError with pytest.raises(NotImplementedError, match=message): stats.ttest_ind(a, b, trim=0.1) @pytest.mark.parametrize("trim", [-.2, .5, 1]) def test_trim_bounds_error(self, trim): match = "Trimming percentage should be 0 <= `trim` < .5." with assert_raises(ValueError, match=match): stats.ttest_ind([1, 2], [2, 1], trim=trim) @make_xp_test_case(stats.ttest_ind)
Test_ttest_trim
python
walkccc__LeetCode
solutions/2923. Find Champion I/2923.py
{ "start": 0, "end": 378 }
class ____: def findChampion(self, grid: list[list[int]]) -> int: n = len(grid) inDegrees = [0] * n for i in range(n): for j in range(n): if i == j: continue if grid[i][j] == 1: inDegrees[j] += 1 else: inDegrees[i] += 1 return (-1 if inDegrees.count(0) > 1 else inDegrees.index(0))
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_row04.py
{ "start": 315, "end": 995 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_row04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_default_row(24) worksheet.write("A1", "Foo") worksheet.write("A10", "Bar") worksheet.write_comment("C4", "Hello", {"y_offset": 22}) worksheet.set_comments_author("John") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
prabhupant__python-ds
data_structures/graphs/dfs.py
{ "start": 37, "end": 647 }
class ____: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) def dfs_util(self, v, visited): visited[v] = True print(v, end=' ') for i in self.graph[v]: if visited[i] == False: self.dfs_util(i, visited) def dfs(self, v): visited = [False] * (len(self.graph)) self.dfs_util(v, visited) g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(0, 3) g.add_edge(1, 4) g.add_edge(2, 5) g.add_edge(3, 6) print(g.dfs(0))
Graph
python
pydantic__pydantic
pydantic/v1/env_settings.py
{ "start": 5720, "end": 6076 }
class ____: __slots__ = ('init_kwargs',) def __init__(self, init_kwargs: Dict[str, Any]): self.init_kwargs = init_kwargs def __call__(self, settings: BaseSettings) -> Dict[str, Any]: return self.init_kwargs def __repr__(self) -> str: return f'InitSettingsSource(init_kwargs={self.init_kwargs!r})'
InitSettingsSource
python
Pylons__pyramid
src/pyramid/config/assets.py
{ "start": 10429, "end": 13984 }
class ____: def _override( self, package, path, override_source, PackageOverrides=PackageOverrides ): pkg_name = package.__name__ override = self.registry.queryUtility(IPackageOverrides, name=pkg_name) if override is None: override = PackageOverrides(package) self.registry.registerUtility( override, IPackageOverrides, name=pkg_name ) override.insert(path, override_source) @action_method def override_asset(self, to_override, override_with, _override=None): """Add a :app:`Pyramid` asset override to the current configuration state. ``to_override`` is an :term:`asset specification` to the asset being overridden. ``override_with`` is an :term:`asset specification` to the asset that is performing the override. This may also be an absolute path. See :ref:`assets_chapter` for more information about asset overrides.""" if to_override == override_with: raise ConfigurationError( 'You cannot override an asset with itself' ) package = to_override path = '' if ':' in to_override: package, path = to_override.split(':', 1) # *_isdir = override is package or directory overridden_isdir = path == '' or path.endswith('/') if os.path.isabs(override_with): override_source = FSAssetSource(override_with) if not os.path.exists(override_with): raise ConfigurationError( 'Cannot override asset with an absolute path that does ' 'not exist' ) override_isdir = os.path.isdir(override_with) override_package = None override_prefix = override_with else: override_package = override_with override_prefix = '' if ':' in override_with: override_package, override_prefix = override_with.split(':', 1) __import__(override_package) to_package = sys.modules[override_package] override_source = PackageAssetSource(to_package, override_prefix) override_isdir = override_prefix == '' or override_with.endswith( '/' ) if overridden_isdir and (not override_isdir): raise ConfigurationError( 'A directory cannot be overridden with a file (put a ' 'slash at the end of override_with if necessary)' ) if (not overridden_isdir) and override_isdir: raise ConfigurationError( 'A file cannot be overridden with a directory (put a ' 'slash at the end of to_override if necessary)' ) override = _override or self._override # test jig def register(): __import__(package) from_package = sys.modules[package] override(from_package, path, override_source) intr = self.introspectable( 'asset overrides', (package, override_package, path, override_prefix), f'{to_override} -> {override_with}', 'asset override', ) intr['to_override'] = to_override intr['override_with'] = override_with self.action( None, register, introspectables=(intr,), order=PHASE1_CONFIG ) override_resource = override_asset # bw compat
AssetsConfiguratorMixin
python
jina-ai__jina
tests/integration/reload/test_flow_reload.py
{ "start": 663, "end": 899 }
class ____(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests() def foo(self, docs, **kwargs): for doc in docs: doc.text = 'MyExecutorBeforeReload'
MyExecutorBeforeReload
python
falconry__falcon
examples/asgilook/asgilook/images.py
{ "start": 33, "end": 910 }
class ____: def __init__(self, config, store): self._config = config self._store = store async def on_get(self, req, resp): resp.media = [image.serialize() for image in self._store.list_images()] async def on_get_image(self, req, resp, image_id): # NOTE: image_id: UUID is converted back to a string identifier. image = self._store.get(str(image_id)) if not image: raise falcon.HTTPNotFound resp.stream = await aiofiles.open(image.path, 'rb') resp.content_type = falcon.MEDIA_JPEG async def on_post(self, req, resp): data = await req.stream.read() image_id = str(self._config.uuid_generator()) image = await self._store.save(image_id, data) resp.location = image.uri resp.media = image.serialize() resp.status = falcon.HTTP_201
Images
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
{ "start": 4614, "end": 12095 }
class ____: @staticmethod def non_launchable_sqlite_instance(): @contextmanager def _non_launchable_sqlite_instance(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( temp_dir=temp_dir, overrides={ "scheduler": { "module": "dagster.utils.test", "class": "FilesystemTestScheduler", "config": {"base_dir": temp_dir}, }, "run_launcher": { "module": "dagster._core.test_utils", "class": "ExplodingRunLauncher", }, }, synchronous_run_coordinator=True, ) as instance: yield instance return MarkedManager( _non_launchable_sqlite_instance, [Marks.sqlite_instance, Marks.non_launchable] ) @staticmethod def non_launchable_postgres_instance(): @contextmanager def _non_launchable_postgres_instance(): with graphql_postgres_instance( overrides={ "run_launcher": { "module": "dagster._core.test_utils", "class": "ExplodingRunLauncher", }, }, synchronous_run_coordinator=True, ) as instance: yield instance return MarkedManager( _non_launchable_postgres_instance, [Marks.postgres_instance, Marks.non_launchable], ) @staticmethod def sqlite_instance_with_sync_run_launcher(): @contextmanager def _sqlite_instance(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( temp_dir=temp_dir, overrides={ "scheduler": { "module": "dagster.utils.test", "class": "FilesystemTestScheduler", "config": {"base_dir": temp_dir}, }, }, synchronous_run_launcher=True, ) as instance: yield instance return MarkedManager(_sqlite_instance, [Marks.sqlite_instance, Marks.sync_run_launcher]) # Runs launched with this instance won't actually execute since the graphql test suite # doesn't run the daemon process that launches queued runs @staticmethod def sqlite_instance_with_queued_run_coordinator(): @contextmanager def _sqlite_instance(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( temp_dir=temp_dir, overrides={ "scheduler": { "module": "dagster.utils.test", "class": "FilesystemTestScheduler", "config": {"base_dir": temp_dir}, }, "run_coordinator": { "module": "dagster._core.run_coordinator.queued_run_coordinator", "class": "QueuedRunCoordinator", }, }, ) as instance: yield instance return MarkedManager( _sqlite_instance, [Marks.sqlite_instance, Marks.queued_run_coordinator] ) @staticmethod def sqlite_instance_with_default_run_launcher(): @contextmanager def _sqlite_instance_with_default_hijack(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( temp_dir=temp_dir, overrides={ "scheduler": { "module": "dagster.utils.test", "class": "FilesystemTestScheduler", "config": {"base_dir": temp_dir}, }, }, synchronous_run_coordinator=True, ) as instance: yield instance return MarkedManager( _sqlite_instance_with_default_hijack, [Marks.sqlite_instance, Marks.default_run_launcher], ) @staticmethod def postgres_instance_with_sync_run_launcher(): @contextmanager def _postgres_instance(): with graphql_postgres_instance( synchronous_run_launcher=True, synchronous_run_coordinator=True, ) as instance: yield instance return MarkedManager( _postgres_instance, [Marks.postgres_instance, Marks.sync_run_launcher], ) @staticmethod def postgres_instance_with_default_run_launcher(): @contextmanager def _postgres_instance_with_default_hijack(): with graphql_postgres_instance(synchronous_run_coordinator=True) as instance: yield instance return MarkedManager( _postgres_instance_with_default_hijack, [Marks.postgres_instance, Marks.default_run_launcher], ) @staticmethod def consolidated_sqlite_instance(): @contextmanager def _sqlite_asset_instance(): with tempfile.TemporaryDirectory() as temp_dir: instance = DagsterInstance( instance_type=InstanceType.EPHEMERAL, local_artifact_storage=LocalArtifactStorage(temp_dir), run_storage=InMemoryRunStorage(), event_storage=ConsolidatedSqliteEventLogStorage(temp_dir), compute_log_manager=LocalComputeLogManager(temp_dir), run_coordinator=DefaultRunCoordinator(), run_launcher=SyncInMemoryRunLauncher(), scheduler=FilesystemTestScheduler(temp_dir), ) yield instance return MarkedManager(_sqlite_asset_instance, [Marks.asset_aware_instance]) @staticmethod def default_concurrency_sqlite_instance(): @contextmanager def _sqlite_with_default_concurrency_instance(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( temp_dir=temp_dir, overrides={ "scheduler": { "module": "dagster.utils.test", "class": "FilesystemTestScheduler", "config": {"base_dir": temp_dir}, }, "run_coordinator": { "module": "dagster._core.run_coordinator.queued_run_coordinator", "class": "QueuedRunCoordinator", }, "concurrency": { "default_op_concurrency_limit": 1, }, }, ) as instance: yield instance return MarkedManager( _sqlite_with_default_concurrency_instance, [Marks.sqlite_instance, Marks.queued_run_coordinator], )
InstanceManagers
python
sqlalchemy__sqlalchemy
test/orm/test_instrumentation.py
{ "start": 12145, "end": 13485 }
class ____(fixtures.MappedTest): def test_register_reserved_attribute(self): class T: pass instrumentation.register_class(T) manager = instrumentation.manager_of_class(T) sa = instrumentation.ClassManager.STATE_ATTR ma = instrumentation.ClassManager.MANAGER_ATTR def fails(method, attr): return assert_raises( KeyError, getattr(manager, method), attr, property() ) fails("install_member", sa) fails("install_member", ma) fails("install_descriptor", sa) fails("install_descriptor", ma) def test_mapped_stateattr(self): t = Table( "t", MetaData(), Column("id", Integer, primary_key=True), Column(instrumentation.ClassManager.STATE_ATTR, Integer), ) class T: pass assert_raises(KeyError, self.mapper_registry.map_imperatively, T, t) def test_mapped_managerattr(self): t = Table( "t", MetaData(), Column("id", Integer, primary_key=True), Column(instrumentation.ClassManager.MANAGER_ATTR, Integer), ) class T: pass assert_raises(KeyError, self.mapper_registry.map_imperatively, T, t)
NativeInstrumentationTest
python
Textualize__textual
src/textual/reactive.py
{ "start": 1013, "end": 1133 }
class ____(ReactiveError): """Raised when an attribute has public and private compute methods."""
TooManyComputesError
python
mlflow__mlflow
mlflow/pyspark/ml/__init__.py
{ "start": 7443, "end": 20456 }
class ____(NamedTuple): hierarchy: dict[str, Any] uid_to_indexed_name_map: dict[str, str] param_search_estimators: list[Any] def _traverse_stage(stage): from pyspark.ml import Pipeline yield stage if isinstance(stage, Pipeline): original_sub_stages = stage.getStages() try: iter(original_sub_stages) except TypeError: raise TypeError( f"Pipeline stages should be iterable, but found object {original_sub_stages}" ) for stage in original_sub_stages: yield from _traverse_stage(stage) else: # General support for params that of type Params for _, param_value in _get_stage_type_params(stage).items(): yield from _traverse_stage(param_value) def _get_uid_to_indexed_name_map(estimator): counter = defaultdict(int) uid_to_classname_and_count = {} for child in _traverse_stage(estimator): class_name = child.__class__.__name__ counter[class_name] += 1 uid_to_classname_and_count[child.uid] = (class_name, counter[class_name]) return { uid: f"{class_name}_{count}" if counter[class_name] > 1 else class_name for uid, (class_name, count) in uid_to_classname_and_count.items() } def _gen_stage_hierarchy_recursively(stage, uid_to_indexed_name_map): from pyspark.ml import Pipeline from pyspark.ml.classification import OneVsRest stage_name = uid_to_indexed_name_map[stage.uid] if isinstance(stage, Pipeline): sub_stages = [ _gen_stage_hierarchy_recursively(sub_stage, uid_to_indexed_name_map) for sub_stage in stage.getStages() ] return {"name": stage_name, "stages": sub_stages} elif isinstance(stage, OneVsRest): classifier_hierarchy = _gen_stage_hierarchy_recursively( stage.getClassifier(), uid_to_indexed_name_map ) return {"name": stage_name, "classifier": classifier_hierarchy} elif _is_parameter_search_estimator(stage): evaluator = stage.getEvaluator() tuned_estimator = stage.getEstimator() return { "name": stage_name, "evaluator": _gen_stage_hierarchy_recursively(evaluator, uid_to_indexed_name_map), "tuned_estimator": _gen_stage_hierarchy_recursively( tuned_estimator, uid_to_indexed_name_map ), } elif any(_get_stage_type_params(stage)): sub_params = {} for param_name, param_value in _get_stage_type_params(stage).items(): sub_hierarchy = _gen_stage_hierarchy_recursively(param_value, uid_to_indexed_name_map) sub_params[param_name] = sub_hierarchy return {"name": stage_name, "params": sub_params} else: return {"name": stage_name} def _gen_estimator_metadata(estimator): """ Returns an `_AutologgingEstimatorMetadata` object. The `_AutologgingEstimatorMetadata` object includes: - hierarchy: the hierarchy of the estimator, it will expand pipeline/meta estimator/param tuning estimator - uid_to_indexed_name_map: a map of `uid` -> `name`, each nested instance uid will be mapped to a fixed name. The naming rule is using `{class_name}` if the instance type occurs once, or `{class_name}_{index}` if the instance type occurs multiple times. The index order is in line with depth-first traversing. - param_search_estimators: a list includes all param search estimators in the hierarchy tree. """ uid_to_indexed_name_map = _get_uid_to_indexed_name_map(estimator) param_search_estimators = [ stage for stage in _traverse_stage(estimator) if _is_parameter_search_estimator(stage) ] hierarchy = _gen_stage_hierarchy_recursively(estimator, uid_to_indexed_name_map) metadata = _AutologgingEstimatorMetadata( hierarchy=hierarchy, uid_to_indexed_name_map=uid_to_indexed_name_map, param_search_estimators=param_search_estimators, ) estimator._autologging_metadata = metadata return metadata def _get_param_map(instance): return { param.name: instance.getOrDefault(param) for param in instance.params if instance.isDefined(param) } def _get_stage_type_params(instance): """ Get the param map of the instance where param value is of type pyspark.ml.param.Params """ from pyspark.ml.param import Params return { param.name: instance.getOrDefault(param) for param in instance.params if instance.isDefined(param) and isinstance(instance.getOrDefault(param), Params) } def _get_instance_param_map_recursively(instance, level, uid_to_indexed_name_map): from pyspark.ml.param import Params from pyspark.ml.pipeline import Pipeline param_map = _get_param_map(instance) expanded_param_map = {} is_pipeline = isinstance(instance, Pipeline) is_parameter_search_estimator = _is_parameter_search_estimator(instance) logged_param_name_prefix = "" if level == 0 else uid_to_indexed_name_map[instance.uid] + "." for param_name, param_value in param_map.items(): logged_param_name = logged_param_name_prefix + param_name if is_pipeline and param_name == "stages": expanded_param_map[logged_param_name] = [ uid_to_indexed_name_map[stage.uid] for stage in instance.getStages() ] for stage in instance.getStages(): stage_param_map = _get_instance_param_map_recursively( stage, level + 1, uid_to_indexed_name_map ) expanded_param_map.update(stage_param_map) elif is_parameter_search_estimator and param_name == "estimator": expanded_param_map[logged_param_name] = uid_to_indexed_name_map[param_value.uid] # skip log estimator's nested params because they will be logged as JSON artifact, # and they will be logged in nested runs as well. elif is_parameter_search_estimator and param_name == "estimatorParamMaps": # this param will be saved as JSON format artifact. pass elif isinstance(param_value, Params): # handle the case param value type inherits `pyspark.ml.param.Params` # e.g. param like # `OneVsRest.classifier`/`CrossValidator.evaluator` expanded_param_map[logged_param_name] = uid_to_indexed_name_map[param_value.uid] internal_param_map = _get_instance_param_map_recursively( param_value, level + 1, uid_to_indexed_name_map ) expanded_param_map.update(internal_param_map) else: expanded_param_map[logged_param_name] = param_value return expanded_param_map def _get_instance_param_map(instance, uid_to_indexed_name_map): return _get_instance_param_map_recursively( instance, level=0, uid_to_indexed_name_map=uid_to_indexed_name_map ) def _create_child_runs_for_parameter_search(parent_estimator, parent_model, parent_run, child_tags): client = MlflowClient() # Use the start time of the parent parameter search run as a rough estimate for the # start time of child runs, since we cannot precisely determine when each point # in the parameter search space was explored child_run_start_time = parent_run.info.start_time child_run_end_time = get_current_time_millis() estimator_param_maps = parent_estimator.getEstimatorParamMaps() tuned_estimator = parent_estimator.getEstimator() metrics_dict, _ = _get_param_search_metrics_and_best_index(parent_estimator, parent_model) for i, est_param in enumerate(estimator_param_maps): child_estimator = tuned_estimator.copy(est_param) tags_to_log = dict(child_tags) if child_tags else {} tags_to_log.update({MLFLOW_PARENT_RUN_ID: parent_run.info.run_id}) tags_to_log.update(_get_estimator_info_tags(child_estimator)) child_run = client.create_run( experiment_id=parent_run.info.experiment_id, start_time=child_run_start_time, tags=tags_to_log, ) params_to_log = _get_instance_param_map( child_estimator, parent_estimator._autologging_metadata.uid_to_indexed_name_map ) param_batches_to_log = _chunk_dict(params_to_log, chunk_size=MAX_PARAMS_TAGS_PER_BATCH) metrics_to_log = {k: v[i] for k, v in metrics_dict.items()} for params_batch, metrics_batch in zip_longest( param_batches_to_log, [metrics_to_log], fillvalue={} ): # Trim any parameter keys / values and metric keys that exceed the limits # imposed by corresponding MLflow Tracking APIs (e.g., LogParam, LogMetric) truncated_params_batch = _truncate_dict( params_batch, MAX_ENTITY_KEY_LENGTH, MAX_PARAM_VAL_LENGTH ) truncated_metrics_batch = _truncate_dict( metrics_batch, max_key_length=MAX_ENTITY_KEY_LENGTH ) client.log_batch( run_id=child_run.info.run_id, params=[ Param(str(key), str(value)) for key, value in truncated_params_batch.items() ], metrics=[ Metric(key=str(key), value=value, timestamp=child_run_end_time, step=0) for key, value in truncated_metrics_batch.items() ], ) client.set_terminated(run_id=child_run.info.run_id, end_time=child_run_end_time) def _log_parameter_search_results_as_artifact(param_maps, metrics_dict, run_id): import pandas as pd result_dict = defaultdict(list) result_dict["params"] = [] result_dict.update(metrics_dict) for param_map in param_maps: result_dict["params"].append(json.dumps(param_map)) for param_name, param_value in param_map.items(): result_dict[f"param.{param_name}"].append(param_value) results_df = pd.DataFrame.from_dict(result_dict) with TempDir() as t: results_path = t.path("search_results.csv") results_df.to_csv(results_path, index=False) MlflowClient().log_artifact(run_id, results_path) def _get_warning_msg_for_fit_call_with_a_list_of_params(estimator): return ( "Skip pyspark ML autologging when calling " + f"{_get_fully_qualified_class_name(estimator)}.fit with a list of params," + "if you want to autolog for this case, you convert code to call `fit` with " + "each single param map." ) def _get_tuning_param_maps(param_search_estimator, uid_to_indexed_name_map): def gen_log_key(param): if param.parent not in uid_to_indexed_name_map: raise ValueError( "Tuning params should not include params not owned by the tuned estimator, but " f"found a param {param}" ) return f"{uid_to_indexed_name_map[param.parent]}.{param.name}" return [ {gen_log_key(k): v for k, v in eps.items()} for eps in param_search_estimator.getEstimatorParamMaps() ] def _get_param_search_metrics_and_best_index(param_search_estimator, param_search_model): """ Return a tuple of `(metrics_dict, best_index)` `metrics_dict` is a dict of metric_name --> metric_values for each param map - For CrossValidatorModel, the result dict contains metrics of avg_metrics and std_metrics for each param map. - For TrainValidationSplitModel, the result dict contains metrics for each param map. `best_index` is the best index of trials. """ from pyspark.ml.tuning import CrossValidatorModel, TrainValidationSplitModel metrics_dict = {} metric_key = param_search_estimator.getEvaluator().getMetricName() if isinstance(param_search_model, CrossValidatorModel): avg_metrics = param_search_model.avgMetrics metrics_dict["avg_" + metric_key] = avg_metrics if hasattr(param_search_model, "stdMetrics"): metrics_dict["std_" + metric_key] = param_search_model.stdMetrics elif isinstance(param_search_model, TrainValidationSplitModel): avg_metrics = param_search_model.validationMetrics metrics_dict[metric_key] = avg_metrics else: raise RuntimeError(f"Unknown parameter search model type {type(param_search_model)}.") if param_search_estimator.getEvaluator().isLargerBetter(): best_index = np.argmax(avg_metrics) else: best_index = np.argmin(avg_metrics) return metrics_dict, best_index def _log_estimator_params(param_map): # Chunk model parameters to avoid hitting the log_batch API limit for chunk in _chunk_dict(param_map, chunk_size=MAX_PARAMS_TAGS_PER_BATCH): truncated = _truncate_dict(chunk, MAX_ENTITY_KEY_LENGTH, MAX_PARAM_VAL_LENGTH) mlflow.log_params(truncated)
_AutologgingEstimatorMetadata
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/parallel_package_b/package.py
{ "start": 275, "end": 547 }
class ____(Package): """Simple dependency package for testing parallel builds""" homepage = "http://www.example.com" has_code = False version("1.0") def install(self, spec, prefix): time.sleep(6) touch(prefix.dummy_file)
ParallelPackageB
python
Pylons__pyramid
tests/test_events.py
{ "start": 1994, "end": 2735 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.events import ApplicationCreated return ApplicationCreated def _makeOne(self, context=object()): return self._getTargetClass()(context) def test_class_conforms_to_IApplicationCreated(self): from zope.interface.verify import verifyClass from pyramid.interfaces import IApplicationCreated verifyClass(IApplicationCreated, self._getTargetClass()) def test_object_conforms_to_IApplicationCreated(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IApplicationCreated verifyObject(IApplicationCreated, self._makeOne())
ApplicationCreatedEventTests
python
boto__boto3
tests/functional/docs/test_cloudwatch.py
{ "start": 756, "end": 1850 }
class ____(BaseDocsFunctionalTests): def setUp(self): super().setUp() self.documenter = ServiceDocumenter( 'cloudwatch', session=Session(region_name='us-east-1'), root_docs_path=self.root_services_path, ) self.generated_contents = self.documenter.document_service() self.generated_contents = self.generated_contents.decode('utf-8') def test_put_action_overrides(self): put_action_contents = self.get_nested_file_contents( "cloudwatch", "metric", "put_data" ) # first line is an empty string self.assert_contains_lines_in_order( PUT_DATA_WARNING_MESSAGE.splitlines()[1:], put_action_contents, ) def test_put_action_override_not_present_in_other_action(self): put_alarm_contents = self.get_nested_file_contents( "cloudwatch", "metric", "put_alarm" ) for line in PUT_DATA_WARNING_MESSAGE.splitlines()[1:]: self.assertNotIn(line, put_alarm_contents)
TestCloudWatchMetricPutActionOverrides
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 15900, "end": 15976 }
class ____(Field[typing.Any]): """Field that applies no formatting."""
Raw
python
donnemartin__interactive-coding-challenges
recursion_dynamic/grid_path/test_grid_path.py
{ "start": 18, "end": 1020 }
class ____(unittest.TestCase): def test_grid_path(self): grid = Grid() self.assertEqual(grid.find_path(None), None) self.assertEqual(grid.find_path([[]]), None) max_rows = 8 max_cols = 4 matrix = [[1] * max_cols for _ in range(max_rows)] matrix[1][1] = 0 matrix[2][2] = 0 matrix[3][0] = 0 matrix[4][2] = 0 matrix[5][3] = 0 matrix[6][1] = 0 matrix[6][3] = 0 matrix[7][1] = 0 result = grid.find_path(matrix) expected = [(0, 0), (1, 0), (2, 0), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2), (6, 2), (7, 2), (7, 3)] self.assertEqual(result, expected) matrix[7][2] = 0 result = grid.find_path(matrix) self.assertEqual(result, None) print('Success: test_grid_path') def main(): test = TestGridPath() test.test_grid_path() if __name__ == '__main__': main()
TestGridPath
python
celery__celery
t/unit/tasks/test_tasks.py
{ "start": 997, "end": 1047 }
class ____(Task): priority = 10
TaskWithPriority
python
pytorch__pytorch
torch/optim/lr_scheduler.py
{ "start": 50777, "end": 56009 }
class ____(LRScheduler): r""" Set the learning rate of each parameter group using a cosine annealing schedule. The learning rate is updated recursively using: .. math:: \eta_{t+1} = \eta_{\min} + (\eta_t - \eta_{\min}) \cdot \frac{1 + \cos\left(\frac{(T_{cur}+1) \pi}{T_{max}}\right)} {1 + \cos\left(\frac{T_{cur} \pi}{T_{max}}\right)} This implements a recursive approximation of the closed-form schedule proposed in `SGDR: Stochastic Gradient Descent with Warm Restarts`_: .. math:: \eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min}) \left( 1 + \cos\left(\frac{T_{cur} \pi}{T_{max}}\right) \right) where: - :math:`\eta_t` is the learning rate at step :math:`t` - :math:`T_{cur}` is the number of epochs since the last restart - :math:`T_{max}` is the maximum number of epochs in a cycle Note: Although SGDR includes periodic restarts, this implementation performs cosine annealing **without restarts**, so :math:`T_{cur} = t` and increases monotonically with each call to :meth:`step`. Args: optimizer (Optimizer): Wrapped optimizer. T_max (int): Maximum number of iterations. eta_min (float): Minimum learning rate. Default: 0. last_epoch (int): The index of the last epoch. Default: -1. .. _SGDR\: Stochastic Gradient Descent with Warm Restarts: https://arxiv.org/abs/1608.03983 Example: >>> # xdoctest: +SKIP >>> num_epochs = 100 >>> scheduler = CosineAnnealingLR(optimizer, T_max=num_epochs) >>> for epoch in range(num_epochs): >>> train(...) >>> validate(...) >>> scheduler.step() .. image:: ../scripts/lr_scheduler_images/CosineAnnealingLR.png """ def __init__( self, optimizer: Optimizer, T_max: int, eta_min: float = 0.0, last_epoch: int = -1, ) -> None: # noqa: D107 self.T_max = T_max self.eta_min = eta_min super().__init__(optimizer, last_epoch) @override def get_lr(self) -> list[float | Tensor]: r"""Compute the next learning rate for each of the optimizer's :attr:`~torch.optim.Optimizer.param_groups`. Scales the ``group["lr"]``\s in the optimizer's :attr:`~torch.optim.Optimizer.param_groups` such that their learning rates approximate .. math:: \texttt{eta\_min} + \frac{1}{2} (\texttt{base\_lr} - \texttt{eta\_min}) \left(1 + \cos\left(\pi \cdot \frac{\texttt{last\_epoch}}{\texttt{T\_max}}\right) \right) Returns: list[float | Tensor]: A :class:`list` of learning rates for each of the optimizer's :attr:`~torch.optim.Optimizer.param_groups` with the same types as their current ``group["lr"]``\s. .. note:: If you're trying to inspect the most recent learning rate, use :meth:`get_last_lr()` instead. .. note:: The returned :class:`~torch.Tensor`\s are copies, and never alias the optimizer's ``group["lr"]``\s. """ _warn_get_lr_called_within_step(self) if self._is_initial: return _param_groups_val_list(self.optimizer, "lr") elif self._step_count == 1 and self.last_epoch > 0: return [ self.eta_min + (base_lr - self.eta_min) * (1 + math.cos((self.last_epoch) * math.pi / self.T_max)) / 2 for base_lr, group in zip( self.base_lrs, self.optimizer.param_groups, strict=True ) ] elif (self.last_epoch - 1 - self.T_max) % (2 * self.T_max) == 0: return [ group["lr"] + (base_lr - self.eta_min) * (1 - math.cos(math.pi / self.T_max)) / 2 for base_lr, group in zip( self.base_lrs, self.optimizer.param_groups, strict=True ) ] return [ (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / (1 + math.cos(math.pi * (self.last_epoch - 1) / self.T_max)) * (group["lr"] - self.eta_min) + self.eta_min for group in self.optimizer.param_groups ] def _get_closed_form_lr(self) -> list[float | Tensor]: r"""Compute learning rates for each of the optimizer's :attr:`~torch.optim.Optimizer.param_groups` at :attr:`last_epoch` using a closed-form formula. Uses :attr:`base_lrs` to compute learning rates. This method is called when an epoch is passed to :meth:`step`. Returns: list[float | Tensor]: A :class:`list` of learning rates for each of the optimizer's :attr:`~torch.optim.Optimizer.param_groups` with the same types as their current ``group["lr"]``\s. """ return [ self.eta_min + (base_lr - self.eta_min) * (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2 for base_lr in self.base_lrs ]
CosineAnnealingLR
python
h5py__h5py
h5py/tests/test_file.py
{ "start": 28146, "end": 28505 }
class ____(TestCase): """Check that h5py.File can't be pickled""" def test_dump_error(self): with File(self.mktemp(), 'w') as f1: with self.assertRaises(TypeError): pickle.dumps(f1) # unittest doesn't work with pytest fixtures (and possibly other features), # hence no subclassing TestCase @pytest.mark.mpi
TestPickle
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_index_tricks.py
{ "start": 20248, "end": 20782 }
class ____(TestCase): def test_diag_indices_from(self): x = np.random.random((4, 4)) r, c = diag_indices_from(x) assert_array_equal(r, np.arange(4)) assert_array_equal(c, np.arange(4)) def test_error_small_input(self): x = np.ones(7) with assert_raises(ValueError): diag_indices_from(x) def test_error_shape_mismatch(self): x = np.zeros((3, 3, 2, 3), dtype=int) with assert_raises(ValueError): diag_indices_from(x)
TestDiagIndicesFrom
python
kamyu104__LeetCode-Solutions
Python/reverse-degree-of-a-string.py
{ "start": 38, "end": 232 }
class ____(object): def reverseDegree(self, s): """ :type s: str :rtype: int """ return sum(i*(26-(ord(x)-ord('a'))) for i, x in enumerate(s, 1))
Solution
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 72614, "end": 73669 }
class ____(_ReferencePropertyBase): """This class defines properties that are cross references to a single target collection. Use this class when you want to create a cross-reference in the collection's config that is capable of having only cross-references to a single other collection. Attributes: name: The name of the property, REQUIRED. target_collection: The name of the target collection, REQUIRED. description: A description of the property. """ target_collection: str description: Optional[str] = Field(default=None) MultiTarget: ClassVar[Type[_ReferencePropertyMultiTarget]] = _ReferencePropertyMultiTarget def _to_dict(self) -> Dict[str, Any]: ret_dict = super()._to_dict() ret_dict["dataType"] = [_capitalize_first_letter(self.target_collection)] del ret_dict["target_collection"] return ret_dict PropertyType = Union[Property, ReferenceProperty, _ReferencePropertyMultiTarget] T = TypeVar("T", bound="_CollectionConfigCreate")
ReferenceProperty
python
sympy__sympy
sympy/polys/series/ringpython.py
{ "start": 39380, "end": 52101 }
class ____: """ Python implementation of power series ring over rational field :ref:`QQ`. This class provides comprehensive power series operations over the rational field, supporting series manipulations with precision handling and truncation. It extends the integer ring functionality with support for rational coefficients and integration. Parameters ========== prec : int, optional The default precision for power series operations. Default is 6. Examples ======== >>> from sympy.polys.series.ringpython import PythonPowerSeriesRingQQ >>> R = PythonPowerSeriesRingQQ() >>> s = R([1, (1, 2), (1, 3)]) # 1 + x/2 + x^2/3 >>> R.print(s) 1 + 1/2*x + 1/3*x**2 >>> s_int = R.integrate(s) # Integration >>> R.print(s_int) x + 1/4*x**2 + 1/9*x**3 >>> s_inv = R.inverse(R([1, (1, 2)])) # Inverse of 1 + x/2 >>> R.print(s_inv) 1 - 1/2*x + 1/4*x**2 - 1/8*x**3 + 1/16*x**4 - 1/32*x**5 + O(x**6) Note ==== The recommended way to create a power series ring is using the factory function which returns a new instance of the higher level PowerSeriesRing class with the ring generator: >>> from sympy.polys.series import power_series_ring >>> from sympy import QQ >>> R, x = power_series_ring("x", QQ, 6) >>> R Power Series Ring in x over QQ of size 6 >>> type(x) <class 'sympy.polys.series.ring.PowerSeriesElement'> This function automatically uses the Flint implementation if available for better performance, falling back to the Python implementation otherwise. See Also ======== sympy.polys.series.ringpython.PythonPowerSeriesRingZZ sympy.polys.series.ringflint.FlintPowerSeriesRingQQ sympy.polys.series.ring.power_series_ring sympy.polys.series.ring.PowerSeriesRingRing sympy.polys.series.ring.PowerSeriesRingField sympy.polys.series.ring.PowerSeriesElement """ _domain = QQ def __init__(self, prec: int = 6) -> None: if prec < 0: raise ValueError("Power series precision must be non-negative") self._prec = prec def __repr__(self) -> str: return ( f"Python Power Series Ring over {self._domain} with precision {self._prec}" ) def __eq__(self, other: object) -> bool: if not isinstance(other, PythonPowerSeriesRingQQ): return NotImplemented return self._prec == other.prec def __hash__(self) -> int: return hash((self._domain, self._prec)) def __call__( self, coeffs: Sequence[MPQ | int | tuple[int, int]], prec: int | None = None ) -> USeries[MPQ]: """ Create a power series from a list of coefficients. If `prec` is not specified, it defaults to the ring's precision. """ s: list[MPQ] = [] for c in coeffs: if isinstance(c, MPQ): s.append(c) elif isinstance(c, int): s.append(self._domain(c)) elif isinstance(c, tuple): s.append(self._domain(*c)) else: raise TypeError(f"Unsupported coefficient type: {type(c)}") return self.from_list(s, prec) @property def domain(self) -> Domain[MPQ]: """Return the ground domain of the power series ring.""" return self._domain @property def prec(self) -> int: """Return the ring's precision.""" return self._prec @property def one(self) -> USeries[MPQ]: if self._prec == 0: return ([], 0) return ([QQ(1)], None) @property def zero(self) -> USeries[MPQ]: if self._prec == 0: return ([], 0) return ([], None) @property def gen(self) -> USeries[MPQ]: if self._prec < 2: return ([], self._prec) return ([self._domain.one, self._domain.zero], None) def pretty( self, s: USeries[MPQ], *, symbol: str = "x", ascending: bool = True ) -> str: """Return a pretty-printed string representation of a power series.""" coeffs, prec = s return series_pprint(coeffs, prec, sym=symbol, ascending=ascending) def print( self, s: USeries[MPQ], *, symbol: str = "x", ascending: bool = True ) -> None: """Print a pretty-printed representation of a power series.""" print(self.pretty(s, symbol=symbol, ascending=ascending)) def from_list(self, coeffs: list[MPQ], prec: int | None = None) -> USeries[MPQ]: """ Create a power series from a list of ground coefficients. If `prec` is not specified, it defaults to the ring's precision. """ coeffs = dup_reverse(coeffs, QQ) if prec is None: if len(coeffs) <= self._prec: return coeffs, None else: prec = self._prec if len(coeffs) > prec: coeffs = dup_truncate(coeffs, prec, self._domain) return coeffs, prec def from_element(self, s: USeries[MPQ]) -> USeries[MPQ]: """Convert a power series element into the corresponding element of this ring.""" coeffs, prec = s return _useries(coeffs, prec, self._domain, self._prec) def to_list(self, s: USeries[MPQ]) -> list[MPQ]: """Return the list of series coefficients.""" coeffs, _ = s return coeffs[::-1] def to_dense(self, s: USeries[MPQ]) -> dup[MPQ]: """Return the coefficients of a power series as a dense list.""" return list(s[0]) def series_prec(self, s: USeries[MPQ]) -> int | None: """Return the precision of a power series.""" _, prec = s return prec def equal(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> bool | None: """Check if two power series are equal up to their minimum precision.""" return _useries_equality(s1, s2, self._domain, self._prec) def equal_repr(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> bool: """Check if two power series have the same representation.""" return _useries_equal_repr(s1, s2) def is_ground(self, arg: USeries[MPQ]) -> bool | None: """Check if a arg is a ground element of the power series ring.""" if self.prec == 0: return None return len(self.to_list(arg)) <= 1 def constant_coefficient(self, s: USeries[MPQ]) -> MPQ: """Return the constant coefficient of a power series.""" coeffs, _ = s if len(coeffs) > 0: return coeffs[-1] return self._domain.zero def positive(self, s: USeries[MPQ]) -> USeries[MPQ]: """Return the unary positive of a power series, adjusted to the ring's precision.""" return _useries_pos(s, self._domain, self._prec) def negative(self, s: USeries[MPQ]) -> USeries[MPQ]: """Return the unary negative of a power series.""" return _useries_neg(s, self._domain, self._prec) def add(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Add two power series.""" return _useries_add(s1, s2, self._domain, self._prec) def add_ground(self, s: USeries[MPQ], n: MPQ) -> USeries[MPQ]: """Add a ground element to a power series.""" return _useries_add_ground(s, n, self._domain, self._prec) def subtract(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Subtract two power series.""" return _useries_sub(s1, s2, self._domain, self._prec) def subtract_ground(self, s: USeries[MPQ], n: MPQ) -> USeries[MPQ]: """Subtract a ground element from a power series.""" return _useries_sub_ground(s, n, self._domain, self._prec) def rsubtract_ground(self, s: USeries[MPQ], n: MPQ) -> USeries[MPQ]: """Subtract a power series from a ground element.""" return _useries_rsub_ground(s, n, self._domain, self._prec) def multiply(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Multiply two power series.""" return _useries_mul(s1, s2, self._domain, self._prec) def multiply_ground(self, s: USeries[MPQ], n: MPQ) -> USeries[MPQ]: """Multiply a power series by a ground element.""" return _useries_mul_ground(s, n, self._domain, self._prec) def divide(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Divide two power series.""" return _useries_div(s1, s2, self._domain, self._prec) def pow_int(self, s: USeries[MPQ], n: int) -> USeries[MPQ]: """Raise a power series to a integer power.""" return _useries_pow_int(s, n, self._domain, self._prec) def square(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the square of a power series.""" return _useries_square(s, self._domain, self._prec) def sqrt(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the sqrt of a power series.""" return _useries_sqrt(s, self._domain, self._prec) def compose(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Compose two power series, `s1(s2)`.""" return _useries_compose(s1, s2, self._domain, self._prec) def inverse(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the multiplicative inverse of a power series.""" return _useries_inverse(s, self._domain, self._prec) def reversion(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the compositional inverse of a power series.""" return _useries_reversion(s, self._domain, self._prec) def truncate(self, s: USeries[MPQ], n: int) -> USeries[MPQ]: """Truncate a power series to `n` terms.""" return _useries_truncate(s, n, self._domain) def differentiate(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the derivative of a power series.""" return _useries_derivative(s, self._domain, self._prec) def integrate(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the integral of a power series.""" return _useries_integrate(s, self._domain, self._prec) def log(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the logarithm of a power series.""" return _useries_log(s, self._domain, self._prec) def log1p(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the logarithm of (1 + x) for a power series.""" return _useries_log1p(s, self._domain, self._prec) def exp(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the exponential of a power series.""" return _useries_exp(s, self._domain, self._prec) def expm1(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the exponential of a power series minus 1.""" return _useries_expm1(s, self._domain, self._prec) def atan(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the arctangent of a power series.""" return _useries_atan(s, self._domain, self._prec) def atanh(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the hyperbolic arctangent of a power series.""" return _useries_atanh(s, self._domain, self._prec) def asin(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the arcsine of a power series.""" return _useries_asin(s, self._domain, self._prec) def asinh(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the hyperbolic arcsine of a power series.""" return _useries_asinh(s, self._domain, self._prec) def tan(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the tangent of a power series.""" return _useries_tan(s, self._domain, self._prec) def tanh(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the hyperbolic tangent of a power series.""" return _useries_tanh(s, self._domain, self._prec) def sin(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the sine of a power series.""" return _useries_sin(s, self._domain, self._prec) def sinh(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the hyperbolic sine of a power series.""" return _useries_sinh(s, self._domain, self._prec) def cos(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the cosine of a power series.""" return _useries_cos(s, self._domain, self._prec) def cosh(self, s: USeries[MPQ]) -> USeries[MPQ]: """Compute the hyperbolic cosine of a power series.""" return _useries_cosh(s, self._domain, self._prec) def hypot(self, s1: USeries[MPQ], s2: USeries[MPQ]) -> USeries[MPQ]: """Compute the hypotenuse of two power series.""" return _useries_hypot(s1, s2, self._domain, self._prec)
PythonPowerSeriesRingQQ
python
mlflow__mlflow
mlflow/entities/model_registry/registered_model_alias.py
{ "start": 184, "end": 1053 }
class ____(_ModelRegistryEntity): """Alias object associated with a registered model.""" def __init__(self, alias, version): self._alias = alias self._version = version def __eq__(self, other): if type(other) is type(self): return self.__dict__ == other.__dict__ return False @property def alias(self): """String name of the alias.""" return self._alias @property def version(self): """String model version number that the alias points to.""" return self._version @classmethod def from_proto(cls, proto): return cls(proto.alias, proto.version) def to_proto(self): alias_proto = ProtoRegisteredModelAlias() alias_proto.alias = self.alias alias_proto.version = self.version return alias_proto
RegisteredModelAlias
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/data_version.py
{ "start": 9495, "end": 12216 }
class ____( NamedTuple( "_StaleCause", [ ("key", "AssetKeyPartitionKey"), ("category", StaleCauseCategory), ("reason", str), ("dependency", Optional["AssetKeyPartitionKey"]), ("children", Optional[Sequence["StaleCause"]]), ], ) ): def __new__( cls, key: Union["AssetKey", "AssetKeyPartitionKey"], category: StaleCauseCategory, reason: str, dependency: Optional[Union["AssetKey", "AssetKeyPartitionKey"]] = None, children: Optional[Sequence["StaleCause"]] = None, ): from dagster._core.definitions.events import AssetKey, AssetKeyPartitionKey return super().__new__( cls, AssetKeyPartitionKey(key) if isinstance(key, AssetKey) else key, category, reason, AssetKeyPartitionKey(dependency) if isinstance(dependency, AssetKey) else dependency, children, ) @property def asset_key(self) -> "AssetKey": return self.key.asset_key @property def partition_key(self) -> Optional[str]: return self.key.partition_key @property def dependency_asset_key(self) -> Optional["AssetKey"]: return self.dependency.asset_key if self.dependency else None @property def dependency_partition_key(self) -> Optional[str]: return self.dependency.partition_key if self.dependency else None @property def sort_key(self) -> str: if not hasattr(self, "_sort_key"): self._sort_key = f"{self.key}/{self.dependency}" if self.dependency else str(self.key) return self._sort_key @property def dedupe_key(self) -> int: # subset of properties that are safe to hash safe_tup = (self.key, self.category, self.reason, self.dependency) return hash(safe_tup) # If a partition has greater than this number of dependencies, we don't check # this edge for updated data or propagate other stale causes through this edge. # This constraint can be removed when we have thoroughly tested performance for # large upstream partition counts. SKIP_PARTITION_DATA_VERSION_DEPENDENCY_THRESHOLD = 100 # If an asset is self-dependent and has greater than this number of partitions, we don't check the # self-edge for updated data or propagate other stale causes through the edge. That is because the # current logic will recurse to the first partition, potentially throwing a recursion error. This # constraint can be removed when we have thoroughly tested performance for large partition counts on # self-dependent assets. SKIP_PARTITION_DATA_VERSION_SELF_DEPENDENCY_THRESHOLD = 100
StaleCause
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/services/public/test_task_instances.py
{ "start": 1267, "end": 1363 }
class ____: @staticmethod def clear_db(): clear_db_runs()
TestTaskInstanceEndpoint
python
plotly__plotly.py
tests/utils.py
{ "start": 102, "end": 2876 }
class ____(TestCase): def setUp(self): pio.templates.default = None def tearDown(self): pio.templates.default = "plotly" def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): for key in dict1: if key not in dict2: return ( False, "{0} should be {1}".format(list(dict1.keys()), list(dict2.keys())), ) for key in dict1: if isinstance(dict1[key], dict): equivalent, msg = compare_dict(dict1[key], dict2[key], tol=tol) elif isinstance(dict1[key], Num) and isinstance(dict2[key], Num): if not comp_nums(dict1[key], dict2[key], tol): return ( False, "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), ) elif is_num_list(dict1[key]) and is_num_list(dict2[key]): if not comp_num_list(dict1[key], dict2[key], tol): return ( False, "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), ) elif not (dict1[key] == dict2[key]): return ( False, "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), ) if not equivalent: return False, "['{0}']".format(key) + msg return equivalent, msg def strip_dict_params(d1, d2, ignore=["uid"]): """ Helper function for assert_dict_equal Nearly duplicate of assert_fig_equal in tests/test_optional/optional_utils.py Removes `ignore` params from d1 and/or d2 if they exist then returns stripped dictionaries :param (list|tuple) ignore: sequence of key names as strings that are removed from both d1 and d2 if they exist """ # deep copy d1 and d2 if "to_plotly_json" in dir(d1): d1_copy = copy.deepcopy(d1.to_plotly_json()) else: d1_copy = copy.deepcopy(d1) if "to_plotly_json" in dir(d2): d2_copy = copy.deepcopy(d2.to_plotly_json()) else: d2_copy = copy.deepcopy(d2) for key in ignore: if key in d1_copy.keys(): del d1_copy[key] if key in d2_copy.keys(): del d2_copy[key] return d1_copy, d2_copy def comp_nums(num1, num2, tol=10e-8): return abs(num1 - num2) < tol def comp_num_list(list1, list2, tol=10e-8): for item1, item2 in zip(list1, list2): if not comp_nums(item1, item2, tol): return False return True def is_num_list(item): try: for thing in item: if not isinstance(thing, Num): raise TypeError except TypeError: return False return True
TestCaseNoTemplate
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 165248, "end": 166034 }
class ____(Qwen3OmniMoePreTrainedModel): def __init__(self, config: Qwen3OmniMoeCode2WavConfig, layer_idx): super().__init__(config) in_dim = config.decoder_dim // 2**layer_idx out_dim = config.decoder_dim // 2 ** (layer_idx + 1) upsample_rate = config.upsample_rates[layer_idx] block = [ SnakeBeta(in_dim), Qwen3OmniMoeCausalTransConvNet(in_dim, out_dim, 2 * upsample_rate, upsample_rate), ] for dilation in (1, 3, 9): block.append(Qwen3OmniMoeCode2WavDecoderResidualUnit(out_dim, dilation)) self.block = nn.ModuleList(block) def forward(self, hidden): for block in self.block: hidden = block(hidden) return hidden
Qwen3OmniMoeCode2WavDecoderBlock
python
catalyst-team__catalyst
catalyst/callbacks/backward.py
{ "start": 245, "end": 2036 }
class ____(IBackwardCallback): """Optimizer callback, abstraction over backward step. Args: metric_key: a key to get loss from ``runner.batch_metrics`` grad_clip_fn: callable gradient cliping function or it's name grad_clip_params: key-value parameters for grad_clip_fn log_gradient: boolean flag to log gradient norm to ``runner.batch_metrics`` .. note:: Please follow the `minimal examples`_ sections for more use cases. .. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505 """ def __init__( self, metric_key: str, grad_clip_fn: Union[str, Callable] = None, grad_clip_params: Dict = None, log_gradient: bool = False, ): """Init.""" super().__init__() self.metric_key = metric_key if isinstance(grad_clip_fn, str): self.grad_clip_fn = REGISTRY.get(grad_clip_fn) else: self.grad_clip_fn = grad_clip_fn if grad_clip_params is not None: self.grad_clip_fn = partial(self.grad_clip_fn, **grad_clip_params) self._prefix_gradient = f"gradient/{metric_key}" self._log_gradient = log_gradient def on_batch_end(self, runner: "IRunner"): """Event handler.""" if runner.is_train_loader: loss = runner.batch_metrics[self.metric_key] runner.engine.backward(loss) if self.grad_clip_fn is not None: runner.engine.unscale_gradients() norm = self.grad_clip_fn(self.model.parameters()) if self._log_gradient: runner.batch_metrics[f"{self._prefix_gradient}/norm"] = norm __all__ = ["BackwardCallback"]
BackwardCallback
python
aimacode__aima-python
logic.py
{ "start": 32665, "end": 42795 }
class ____: def __init__(self, clauses): self.__twl = {} self.__watch_list = defaultdict(lambda: [set(), set()]) for c in clauses: self.add(c, None) def get_clauses(self): return self.__twl.keys() def set_first_watched(self, clause, new_watching): if len(clause.args) > 2: self.__twl[clause][0] = new_watching def set_second_watched(self, clause, new_watching): if len(clause.args) > 2: self.__twl[clause][1] = new_watching def get_first_watched(self, clause): if len(clause.args) == 2: return clause.args[0] if len(clause.args) > 2: return self.__twl[clause][0] return clause def get_second_watched(self, clause): if len(clause.args) == 2: return clause.args[-1] if len(clause.args) > 2: return self.__twl[clause][1] return clause def get_pos_watched(self, l): return self.__watch_list[l][0] def get_neg_watched(self, l): return self.__watch_list[l][1] def add(self, clause, model): self.__twl[clause] = self.__assign_watching_literals(clause, model) w1, p1 = inspect_literal(self.get_first_watched(clause)) w2, p2 = inspect_literal(self.get_second_watched(clause)) self.__watch_list[w1][0].add(clause) if p1 else self.__watch_list[w1][1].add(clause) if w1 != w2: self.__watch_list[w2][0].add(clause) if p2 else self.__watch_list[w2][1].add(clause) def remove(self, clause): w1, p1 = inspect_literal(self.get_first_watched(clause)) w2, p2 = inspect_literal(self.get_second_watched(clause)) del self.__twl[clause] self.__watch_list[w1][0].discard(clause) if p1 else self.__watch_list[w1][1].discard(clause) if w1 != w2: self.__watch_list[w2][0].discard(clause) if p2 else self.__watch_list[w2][1].discard(clause) def update_first_watched(self, clause, model): # if a non-zero literal different from the other watched literal is found found, new_watching = self.__find_new_watching_literal(clause, self.get_first_watched(clause), model) if found: # then it will replace the watched literal w, p = inspect_literal(self.get_second_watched(clause)) self.__watch_list[w][0].remove(clause) if p else self.__watch_list[w][1].remove(clause) self.set_second_watched(clause, new_watching) w, p = inspect_literal(new_watching) self.__watch_list[w][0].add(clause) if p else self.__watch_list[w][1].add(clause) return True def update_second_watched(self, clause, model): # if a non-zero literal different from the other watched literal is found found, new_watching = self.__find_new_watching_literal(clause, self.get_second_watched(clause), model) if found: # then it will replace the watched literal w, p = inspect_literal(self.get_first_watched(clause)) self.__watch_list[w][0].remove(clause) if p else self.__watch_list[w][1].remove(clause) self.set_first_watched(clause, new_watching) w, p = inspect_literal(new_watching) self.__watch_list[w][0].add(clause) if p else self.__watch_list[w][1].add(clause) return True def __find_new_watching_literal(self, clause, other_watched, model): # if a non-zero literal different from the other watched literal is found if len(clause.args) > 2: for l in disjuncts(clause): if l != other_watched and pl_true(l, model) is not False: # then it is returned return True, l return False, None def __assign_watching_literals(self, clause, model=None): if len(clause.args) > 2: if model is None or not model: return [clause.args[0], clause.args[-1]] else: return [next(l for l in disjuncts(clause) if pl_true(l, model) is None), next(l for l in disjuncts(clause) if pl_true(l, model) is False)] # ______________________________________________________________________________ # Walk-SAT [Figure 7.18] def WalkSAT(clauses, p=0.5, max_flips=10000): """Checks for satisfiability of all clauses by randomly flipping values of variables >>> WalkSAT([A & ~A], 0.5, 100) is None True """ # Set of all symbols in all clauses symbols = {sym for clause in clauses for sym in prop_symbols(clause)} # model is a random assignment of true/false to the symbols in clauses model = {s: random.choice([True, False]) for s in symbols} for i in range(max_flips): satisfied, unsatisfied = [], [] for clause in clauses: (satisfied if pl_true(clause, model) else unsatisfied).append(clause) if not unsatisfied: # if model satisfies all the clauses return model clause = random.choice(unsatisfied) if probability(p): sym = random.choice(list(prop_symbols(clause))) else: # Flip the symbol in clause that maximizes number of sat. clauses def sat_count(sym): # Return the the number of clauses satisfied after flipping the symbol. model[sym] = not model[sym] count = len([clause for clause in clauses if pl_true(clause, model)]) model[sym] = not model[sym] return count sym = max(prop_symbols(clause), key=sat_count) model[sym] = not model[sym] # If no solution is found within the flip limit, we return failure return None # ______________________________________________________________________________ # Map Coloring SAT Problems def MapColoringSAT(colors, neighbors): """Make a SAT for the problem of coloring a map with different colors for any two adjacent regions. Arguments are a list of colors, and a dict of {region: [neighbor,...]} entries. This dict may also be specified as a string of the form defined by parse_neighbors.""" if isinstance(neighbors, str): neighbors = parse_neighbors(neighbors) colors = UniversalDict(colors) clauses = [] for state in neighbors.keys(): clause = [expr(state + '_' + c) for c in colors[state]] clauses.append(clause) for t in itertools.combinations(clause, 2): clauses.append([~t[0], ~t[1]]) visited = set() adj = set(neighbors[state]) - visited visited.add(state) for n_state in adj: for col in colors[n_state]: clauses.append([expr('~' + state + '_' + col), expr('~' + n_state + '_' + col)]) return associate('&', map(lambda c: associate('|', c), clauses)) australia_sat = MapColoringSAT(list('RGB'), """SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: """) france_sat = MapColoringSAT(list('RGBY'), """AL: LO FC; AQ: MP LI PC; AU: LI CE BO RA LR MP; BO: CE IF CA FC RA AU; BR: NB PL; CA: IF PI LO FC BO; CE: PL NB NH IF BO AU LI PC; FC: BO CA LO AL RA; IF: NH PI CA BO CE; LI: PC CE AU MP AQ; LO: CA AL FC; LR: MP AU RA PA; MP: AQ LI AU LR; NB: NH CE PL BR; NH: PI IF CE NB; NO: PI; PA: LR RA; PC: PL CE LI AQ; PI: NH NO CA IF; PL: BR NB CE PC; RA: AU BO FC PA LR""") usa_sat = MapColoringSAT(list('RGBY'), """WA: OR ID; OR: ID NV CA; CA: NV AZ; NV: ID UT AZ; ID: MT WY UT; UT: WY CO AZ; MT: ND SD WY; WY: SD NE CO; CO: NE KA OK NM; NM: OK TX AZ; ND: MN SD; SD: MN IA NE; NE: IA MO KA; KA: MO OK; OK: MO AR TX; TX: AR LA; MN: WI IA; IA: WI IL MO; MO: IL KY TN AR; AR: MS TN LA; LA: MS; WI: MI IL; IL: IN KY; IN: OH KY; MS: TN AL; AL: TN GA FL; MI: OH IN; OH: PA WV KY; KY: WV VA TN; TN: VA NC GA; GA: NC SC FL; PA: NY NJ DE MD WV; WV: MD VA; VA: MD DC NC; NC: SC; NY: VT MA CT NJ; NJ: DE; DE: MD; MD: DC; VT: NH MA; MA: NH RI CT; CT: RI; ME: NH; HI: ; AK: """) # ______________________________________________________________________________ # Expr functions for WumpusKB and HybridWumpusAgent def facing_east(time): return Expr('FacingEast', time) def facing_west(time): return Expr('FacingWest', time) def facing_north(time): return Expr('FacingNorth', time) def facing_south(time): return Expr('FacingSouth', time) def wumpus(x, y): return Expr('W', x, y) def pit(x, y): return Expr('P', x, y) def breeze(x, y): return Expr('B', x, y) def stench(x, y): return Expr('S', x, y) def wumpus_alive(time): return Expr('WumpusAlive', time) def have_arrow(time): return Expr('HaveArrow', time) def percept_stench(time): return Expr('Stench', time) def percept_breeze(time): return Expr('Breeze', time) def percept_glitter(time): return Expr('Glitter', time) def percept_bump(time): return Expr('Bump', time) def percept_scream(time): return Expr('Scream', time) def move_forward(time): return Expr('Forward', time) def shoot(time): return Expr('Shoot', time) def turn_left(time): return Expr('TurnLeft', time) def turn_right(time): return Expr('TurnRight', time) def ok_to_move(x, y, time): return Expr('OK', x, y, time) def location(x, y, time=None): if time is None: return Expr('L', x, y) else: return Expr('L', x, y, time) # Symbols def implies(lhs, rhs): return Expr('==>', lhs, rhs) def equiv(lhs, rhs): return Expr('<=>', lhs, rhs) # Helper Function def new_disjunction(sentences): t = sentences[0] for i in range(1, len(sentences)): t |= sentences[i] return t # ______________________________________________________________________________
TwoWLClauseDatabase
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/conv_test.py
{ "start": 8646, "end": 10320 }
class ____(op_bench.TorchBenchmarkBase): def init(self, IC, OC, kernel, stride, N, D, H, W, device): self.inputs = {"input": torch.rand(N, IC, D, H, W, device=device)} self.convtranspose3d = nn.ConvTranspose3d(IC, OC, kernel, stride=stride).to( device=device ) self.set_module_name("ConvTranspose3d") def forward(self, input): return self.convtranspose3d(input) def get_memory_traffic_bytes(self): """Calculate memory traffic for ConvTranspose3d: read(input + weight) + write(output)""" input_tensor = self.inputs["input"] # Run forward to get output shape with torch.no_grad(): output = self.convtranspose3d(input_tensor) bytes_per_element = input_tensor.element_size() # Input: N × IC × D × H × W input_elements = input_tensor.numel() # Weight: IC × OC × kernel × kernel × kernel weight_elements = self.convtranspose3d.weight.numel() # Output: N × OC × D_out × H_out × W_out output_elements = output.numel() total_elements = input_elements + weight_elements + output_elements return total_elements * bytes_per_element op_bench.generate_pt_test(configs.conv_3d_configs_short, Conv3dBenchmark) op_bench.generate_pt_test(configs.conv_3d_configs_short, ConvTranspose3dBenchmark) op_bench.generate_pt_gradient_test( configs.remove_cpu(configs.conv_3d_configs_long), Conv3dBenchmark ) op_bench.generate_pt_gradient_test( configs.remove_cpu(configs.conv_3d_configs_long), ConvTranspose3dBenchmark ) if __name__ == "__main__": op_bench.benchmark_runner.main()
ConvTranspose3dBenchmark
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 69893, "end": 90383 }
class ____(Metric): """Approximates the AUC (Area under the curve) of the ROC or PR curves. The AUC (Area under the curve) of the ROC (Receiver operating characteristic; default) or PR (Precision Recall) curves are quality measures of binary classifiers. Unlike the accuracy, and like cross-entropy losses, ROC-AUC and PR-AUC evaluate all the operational points of a model. This class approximates AUCs using a Riemann sum. During the metric accumulation phrase, predictions are accumulated within predefined buckets by value. The AUC is then computed by interpolating per-bucket averages. These buckets define the evaluated operational points. This metric creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall. This value is ultimately returned as `auc`, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The `num_thresholds` variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. The quality of the approximation may vary dramatically depending on `num_thresholds`. The `thresholds` parameter can be used to manually specify thresholds which split the predictions more evenly. For a best approximation of the real AUC, `predictions` should be distributed approximately uniformly in the range [0, 1] (if `from_logits=False`). The quality of the AUC approximation may be poor if this is not the case. Setting `summation_method` to 'minoring' or 'majoring' can help quantify the error in the approximation by providing lower or upper bound estimate of the AUC. If `sample_weight` is `None`, weights default to 1. Use `sample_weight` of 0 to mask values. Args: num_thresholds: (Optional) Defaults to 200. The number of thresholds to use when discretizing the roc curve. Values must be > 1. curve: (Optional) Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. summation_method: (Optional) Specifies the [Riemann summation method]( https://en.wikipedia.org/wiki/Riemann_sum) used. 'interpolation' (default) applies mid-point summation scheme for `ROC`. For PR-AUC, interpolates (true/false) positives but not the ratio that is precision (see Davis & Goadrich 2006 for details); 'minoring' applies left summation for increasing intervals and right summation for decreasing intervals; 'majoring' does the opposite. name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. thresholds: (Optional) A list of floating point values to use as the thresholds for discretizing the curve. If set, the `num_thresholds` parameter is ignored. Values should be in [0, 1]. Endpoint thresholds equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be automatically included with these to correctly handle predictions equal to exactly 0 or 1. multi_label: boolean indicating whether multilabel data should be treated as such, wherein AUC is computed separately for each label and then averaged across labels, or (when False) if the data should be flattened into a single label before AUC computation. In the latter case, when multilabel data is passed to AUC, each label-prediction pair is treated as an individual data point. Should be set to False for multi-class data. num_labels: (Optional) The number of labels, used when `multi_label` is True. If `num_labels` is not specified, then state variables get created on the first call to `update_state`. label_weights: (Optional) list, array, or tensor of non-negative weights used to compute AUCs for multilabel data. When `multi_label` is True, the weights are applied to the individual label AUCs when they are averaged to produce the multi-label AUC. When it's False, they are used to weight the individual label predictions in computing the confusion matrix on the flattened data. Note that this is unlike class_weights in that class_weights weights the example depending on the value of its label, whereas label_weights depends only on the index of that label before flattening; therefore `label_weights` should not be used for multi-class data. from_logits: boolean indicating whether the predictions (`y_pred` in `update_state`) are probabilities or sigmoid logits. As a rule of thumb, when using a keras loss, the `from_logits` constructor argument of the loss should match the AUC `from_logits` constructor argument. Standalone usage: >>> m = tf.keras.metrics.AUC(num_thresholds=3) >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9]) >>> # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7] >>> # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] >>> # tp_rate = recall = [1, 0.5, 0], fp_rate = [1, 0, 0] >>> # auc = ((((1+0.5)/2)*(1-0)) + (((0.5+0)/2)*(0-0))) = 0.75 >>> m.result().numpy() 0.75 >>> m.reset_state() >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9], ... sample_weight=[1, 0, 0, 1]) >>> m.result().numpy() 1.0 Usage with `compile()` API: ```python # Reports the AUC of a model outputting a probability. model.compile(optimizer='sgd', loss=tf.keras.losses.BinaryCrossentropy(), metrics=[tf.keras.metrics.AUC()]) # Reports the AUC of a model outputting a logit. model.compile(optimizer='sgd', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=[tf.keras.metrics.AUC(from_logits=True)]) ``` """ def __init__(self, num_thresholds=200, curve='ROC', summation_method='interpolation', name=None, dtype=None, thresholds=None, multi_label=False, num_labels=None, label_weights=None, from_logits=False): # Validate configurations. if isinstance(curve, metrics_utils.AUCCurve) and curve not in list( metrics_utils.AUCCurve): raise ValueError('Invalid curve: "{}". Valid options are: "{}"'.format( curve, list(metrics_utils.AUCCurve))) if isinstance( summation_method, metrics_utils.AUCSummationMethod) and summation_method not in list( metrics_utils.AUCSummationMethod): raise ValueError( 'Invalid summation method: "{}". Valid options are: "{}"'.format( summation_method, list(metrics_utils.AUCSummationMethod))) # Update properties. if thresholds is not None: # If specified, use the supplied thresholds. self.num_thresholds = len(thresholds) + 2 thresholds = sorted(thresholds) self._thresholds_distributed_evenly = ( metrics_utils.is_evenly_distributed_thresholds( np.array([0.0] + thresholds + [1.0]))) else: if num_thresholds <= 1: raise ValueError('`num_thresholds` must be > 1.') # Otherwise, linearly interpolate (num_thresholds - 2) thresholds in # (0, 1). self.num_thresholds = num_thresholds thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2)] self._thresholds_distributed_evenly = True # Add an endpoint "threshold" below zero and above one for either # threshold method to account for floating point imprecisions. self._thresholds = np.array([0.0 - backend.epsilon()] + thresholds + [1.0 + backend.epsilon()]) if isinstance(curve, metrics_utils.AUCCurve): self.curve = curve else: self.curve = metrics_utils.AUCCurve.from_str(curve) if isinstance(summation_method, metrics_utils.AUCSummationMethod): self.summation_method = summation_method else: self.summation_method = metrics_utils.AUCSummationMethod.from_str( summation_method) super(AUC, self).__init__(name=name, dtype=dtype) # Handle multilabel arguments. self.multi_label = multi_label if label_weights is not None: label_weights = constant_op.constant(label_weights, dtype=self.dtype) checks = [ check_ops.assert_non_negative( label_weights, message='All values of `label_weights` must be non-negative.') ] with ops.control_dependencies(checks): self.label_weights = label_weights else: self.label_weights = None self._from_logits = from_logits self._built = False if self.multi_label: if num_labels: shape = tensor_shape.TensorShape([None, num_labels]) self._build(shape) else: if num_labels: raise ValueError( '`num_labels` is needed only when `multi_label` is True.') self._build(None) @property def thresholds(self): """The thresholds used for evaluating AUC.""" return list(self._thresholds) def _build(self, shape): """Initialize TP, FP, TN, and FN tensors, given the shape of the data.""" if self.multi_label: if shape.ndims != 2: raise ValueError('`y_true` must have rank=2 when `multi_label` is ' 'True. Found rank %s.' % shape.ndims) self._num_labels = shape[1] variable_shape = tensor_shape.TensorShape( [tensor_shape.Dimension(self.num_thresholds), self._num_labels]) else: variable_shape = tensor_shape.TensorShape( [tensor_shape.Dimension(self.num_thresholds)]) self._build_input_shape = shape # Create metric variables self.true_positives = self.add_weight( 'true_positives', shape=variable_shape, initializer=init_ops.zeros_initializer) self.true_negatives = self.add_weight( 'true_negatives', shape=variable_shape, initializer=init_ops.zeros_initializer) self.false_positives = self.add_weight( 'false_positives', shape=variable_shape, initializer=init_ops.zeros_initializer) self.false_negatives = self.add_weight( 'false_negatives', shape=variable_shape, initializer=init_ops.zeros_initializer) if self.multi_label: with ops.init_scope(): # This should only be necessary for handling v1 behavior. In v2, AUC # should be initialized outside of any tf.functions, and therefore in # eager mode. if not context.executing_eagerly(): backend._initialize_variables(backend._get_session()) # pylint: disable=protected-access self._built = True def update_state(self, y_true, y_pred, sample_weight=None): """Accumulates confusion matrix statistics. Args: y_true: The ground truth values. y_pred: The predicted values. sample_weight: Optional weighting of each example. Defaults to 1. Can be a `Tensor` whose rank is either 0, or the same rank as `y_true`, and must be broadcastable to `y_true`. Returns: Update op. """ deps = [] if not self._built: self._build(tensor_shape.TensorShape(y_pred.shape)) if self.multi_label or (self.label_weights is not None): # y_true should have shape (number of examples, number of labels). shapes = [ (y_true, ('N', 'L')) ] if self.multi_label: # TP, TN, FP, and FN should all have shape # (number of thresholds, number of labels). shapes.extend([(self.true_positives, ('T', 'L')), (self.true_negatives, ('T', 'L')), (self.false_positives, ('T', 'L')), (self.false_negatives, ('T', 'L'))]) if self.label_weights is not None: # label_weights should be of length equal to the number of labels. shapes.append((self.label_weights, ('L',))) deps = [ check_ops.assert_shapes( shapes, message='Number of labels is not consistent.') ] # Only forward label_weights to update_confusion_matrix_variables when # multi_label is False. Otherwise the averaging of individual label AUCs is # handled in AUC.result label_weights = None if self.multi_label else self.label_weights if self._from_logits: y_pred = activations.sigmoid(y_pred) with ops.control_dependencies(deps): return metrics_utils.update_confusion_matrix_variables( { metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: self.true_negatives, metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives, metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives, }, y_true, y_pred, self._thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, sample_weight=sample_weight, multi_label=self.multi_label, label_weights=label_weights) def interpolate_pr_auc(self): """Interpolation formula inspired by section 4 of Davis & Goadrich 2006. https://www.biostat.wisc.edu/~page/rocpr.pdf Note here we derive & use a closed formula not present in the paper as follows: Precision = TP / (TP + FP) = TP / P Modeling all of TP (true positive), FP (false positive) and their sum P = TP + FP (predicted positive) as varying linearly within each interval [A, B] between successive thresholds, we get Precision slope = dTP / dP = (TP_B - TP_A) / (P_B - P_A) = (TP - TP_A) / (P - P_A) Precision = (TP_A + slope * (P - P_A)) / P The area within the interval is (slope / total_pos_weight) times int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P} int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P} where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A) Bringing back the factor (slope / total_pos_weight) we'd put aside, we get slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight where dTP == TP_B - TP_A. Note that when P_A == 0 the above calculation simplifies into int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A) which is really equivalent to imputing constant precision throughout the first bucket having >0 true positives. Returns: pr_auc: an approximation of the area under the P-R curve. """ dtp = self.true_positives[:self.num_thresholds - 1] - self.true_positives[1:] p = self.true_positives + self.false_positives dp = p[:self.num_thresholds - 1] - p[1:] prec_slope = math_ops.div_no_nan( dtp, math_ops.maximum(dp, 0), name='prec_slope') intercept = self.true_positives[1:] - math_ops.multiply(prec_slope, p[1:]) safe_p_ratio = array_ops.where( math_ops.logical_and(p[:self.num_thresholds - 1] > 0, p[1:] > 0), math_ops.div_no_nan( p[:self.num_thresholds - 1], math_ops.maximum(p[1:], 0), name='recall_relative_ratio'), array_ops.ones_like(p[1:])) pr_auc_increment = math_ops.div_no_nan( prec_slope * (dtp + intercept * math_ops.log(safe_p_ratio)), math_ops.maximum(self.true_positives[1:] + self.false_negatives[1:], 0), name='pr_auc_increment') if self.multi_label: by_label_auc = math_ops.reduce_sum( pr_auc_increment, name=self.name + '_by_label', axis=0) if self.label_weights is None: # Evenly weighted average of the label AUCs. return math_ops.reduce_mean(by_label_auc, name=self.name) else: # Weighted average of the label AUCs. return math_ops.div_no_nan( math_ops.reduce_sum( math_ops.multiply(by_label_auc, self.label_weights)), math_ops.reduce_sum(self.label_weights), name=self.name) else: return math_ops.reduce_sum(pr_auc_increment, name='interpolate_pr_auc') def result(self): if (self.curve == metrics_utils.AUCCurve.PR and self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION ): # This use case is different and is handled separately. return self.interpolate_pr_auc() # Set `x` and `y` values for the curves based on `curve` config. recall = math_ops.div_no_nan(self.true_positives, self.true_positives + self.false_negatives) if self.curve == metrics_utils.AUCCurve.ROC: fp_rate = math_ops.div_no_nan(self.false_positives, self.false_positives + self.true_negatives) x = fp_rate y = recall else: # curve == 'PR'. precision = math_ops.div_no_nan( self.true_positives, self.true_positives + self.false_positives) x = recall y = precision # Find the rectangle heights based on `summation_method`. if self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION: # Note: the case ('PR', 'interpolation') has been handled above. heights = (y[:self.num_thresholds - 1] + y[1:]) / 2. elif self.summation_method == metrics_utils.AUCSummationMethod.MINORING: heights = math_ops.minimum(y[:self.num_thresholds - 1], y[1:]) else: # self.summation_method = metrics_utils.AUCSummationMethod.MAJORING: heights = math_ops.maximum(y[:self.num_thresholds - 1], y[1:]) # Sum up the areas of all the rectangles. if self.multi_label: riemann_terms = math_ops.multiply(x[:self.num_thresholds - 1] - x[1:], heights) by_label_auc = math_ops.reduce_sum( riemann_terms, name=self.name + '_by_label', axis=0) if self.label_weights is None: # Unweighted average of the label AUCs. return math_ops.reduce_mean(by_label_auc, name=self.name) else: # Weighted average of the label AUCs. return math_ops.div_no_nan( math_ops.reduce_sum( math_ops.multiply(by_label_auc, self.label_weights)), math_ops.reduce_sum(self.label_weights), name=self.name) else: return math_ops.reduce_sum( math_ops.multiply(x[:self.num_thresholds - 1] - x[1:], heights), name=self.name) def reset_state(self): if self._built: confusion_matrix_variables = (self.true_positives, self.true_negatives, self.false_positives, self.false_negatives) if self.multi_label: backend.batch_set_value( [(v, np.zeros((self.num_thresholds, self._num_labels))) for v in confusion_matrix_variables]) else: backend.batch_set_value([(v, np.zeros((self.num_thresholds,))) for v in confusion_matrix_variables]) def get_config(self): if is_tensor_or_variable(self.label_weights): label_weights = backend.eval(self.label_weights) else: label_weights = self.label_weights config = { 'num_thresholds': self.num_thresholds, 'curve': self.curve.value, 'summation_method': self.summation_method.value, # We remove the endpoint thresholds as an inverse of how the thresholds # were initialized. This ensures that a metric initialized from this # config has the same thresholds. 'thresholds': self.thresholds[1:-1], 'multi_label': self.multi_label, 'label_weights': label_weights } base_config = super(AUC, self).get_config() return dict(list(base_config.items()) + list(config.items()))
AUC
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/notification_through_screens.py
{ "start": 112, "end": 519 }
class ____(Screen): TARGET_DEPTH = 10 def __init__(self, count:int = TARGET_DEPTH) -> None: super().__init__() self._number = count def compose(self) -> ComposeResult: yield Label(f"Screen {self.TARGET_DEPTH - self._number}") def on_mount(self) -> None: if self._number > 0: self.app.push_screen(StackableScreen(self._number - 1))
StackableScreen
python
django-guardian__django-guardian
guardian/testapp/models.py
{ "start": 2840, "end": 3002 }
class ____(LogEntry): group = models.ForeignKey("auth.Group", null=True, blank=True, on_delete=models.CASCADE) objects = models.Manager()
LogEntryWithGroup
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 7445, "end": 8338 }
class ____(KeyError): """ Error raised when slicing a MultiIndex which has not been lexsorted. Subclass of `KeyError`. See Also -------- DataFrame.sort_index : Sort a DataFrame by its index. DataFrame.set_index : Set the DataFrame index using existing columns. Examples -------- >>> df = pd.DataFrame( ... { ... "cat": [0, 0, 1, 1], ... "color": ["white", "white", "brown", "black"], ... "lives": [4, 4, 3, 7], ... }, ... ) >>> df = df.set_index(["cat", "color"]) >>> df lives cat color 0 white 4 white 4 1 brown 3 black 7 >>> df.loc[(0, "black") : (1, "white")] Traceback (most recent call last): UnsortedIndexError: 'Key length (2) was greater than MultiIndex lexsort depth (1)' """
UnsortedIndexError
python
kamyu104__LeetCode-Solutions
Python/check-if-all-1s-are-at-least-length-k-places-away.py
{ "start": 29, "end": 393 }
class ____(object): def kLengthApart(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ prev = -k-1 for i in xrange(len(nums)): if not nums[i]: continue if i-prev <= k: return False prev = i return True
Solution
python
pydantic__pydantic
pydantic-core/tests/benchmarks/test_micro_benchmarks.py
{ "start": 2889, "end": 18159 }
class ____: @pytest.fixture(scope='class') def core_model_validator(self): class CoreModel: __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' return SchemaValidator( schema=core_schema.model_schema( cls=CoreModel, schema=core_schema.model_fields_schema( extra_behavior='allow', fields={f'field_{i}': {'type': 'model-field', 'schema': {'type': 'int'}} for i in range(100)}, ), ) ) data = {f'field_{99 - i}': i for i in range(100)} data['more'] = 'more data' @pytest.mark.benchmark(group='large model - python') def test_core_python(self, core_model_validator, benchmark): m = core_model_validator.validate_python(self.data) assert m.field_0 == 99 assert m.field_1 == 98 assert m.field_97 == 2 assert m.__pydantic_extra__ == {'more': 'more data'} benchmark(core_model_validator.validate_python, self.data) @pytest.mark.benchmark(group='large model - JSON') def test_core_json_fs(self, core_model_validator, benchmark): json_data = json.dumps(self.data) m = core_model_validator.validate_json(json_data) assert m.field_0 == 99 assert m.field_1 == 98 assert m.field_97 == 2 assert m.__pydantic_extra__ == {'more': 'more data'} benchmark(core_model_validator.validate_json, json_data) bool_cases = [True, False, 0, 1, '0', '1', 'true', 'false', 'True', 'False'] @pytest.mark.benchmark(group='bool') def test_bool_core(benchmark): schema_validator = SchemaValidator(core_schema.bool_schema()) @benchmark def t(): for case in bool_cases: schema_validator.validate_python(case) small_class_data = {'name': 'John', 'age': 42} @pytest.mark.benchmark(group='create small model') def test_small_class_core_dict(benchmark): model_schema = { 'type': 'typed-dict', 'fields': { 'name': {'type': 'typed-dict-field', 'schema': {'type': 'str'}}, 'age': {'type': 'typed-dict-field', 'schema': {'type': 'int'}}, }, } dict_schema_validator = SchemaValidator(model_schema) benchmark(dict_schema_validator.validate_python, small_class_data) @pytest.mark.benchmark(group='create small model') def test_small_class_core_model(benchmark): class MyCoreModel: # this is not required, but it avoids `__pydantic_fields_set__` being included in `__dict__` __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' # these are here just as decoration name: str age: int model_schema_validator = SchemaValidator( core_schema.model_schema( cls=MyCoreModel, schema=core_schema.model_fields_schema( fields={ 'name': core_schema.model_field(schema=core_schema.str_schema()), 'age': core_schema.model_field(schema=core_schema.int_schema()), } ), ) ) benchmark(model_schema_validator.validate_python, small_class_data) @pytest.mark.benchmark(group='string') def test_core_string_lax(benchmark): validator = SchemaValidator(core_schema.str_schema()) input_str = 'Hello ' * 20 assert validator.validate_python(input_str) == input_str benchmark(validator.validate_python, input_str) @pytest.mark.benchmark(group='string') def test_core_string_lax_wrong(benchmark): validator = SchemaValidator(core_schema.str_schema()) with pytest.raises(ValidationError, match='Input should be a valid string'): validator.validate_python(123) @benchmark def t(): try: validator.validate_python(123) except ValidationError: pass @pytest.mark.benchmark(group='string') def test_core_string_strict(benchmark): validator = SchemaValidator(core_schema.str_schema(strict=True)) input_str = 'Hello ' * 20 assert validator.validate_python(input_str) == input_str benchmark(validator.validate_python, input_str) @pytest.mark.benchmark(group='string') def test_core_string_strict_wrong(benchmark): validator = SchemaValidator(core_schema.str_schema(strict=True)) with pytest.raises(ValidationError, match='Input should be a valid string'): validator.validate_python(123) @benchmark def t(): try: validator.validate_python(123) except ValidationError: pass @pytest.mark.benchmark(group='string') def test_core_string_strict_wrong_str_e(benchmark): validator = SchemaValidator(core_schema.str_schema(strict=True)) with pytest.raises(ValidationError, match='Input should be a valid string'): validator.validate_python(123) @benchmark def t(): try: validator.validate_python(123) except ValidationError as e: str(e) @pytest.mark.benchmark(group='isinstance-string') def test_isinstance_string_lax_true(benchmark): validator = SchemaValidator(core_schema.str_schema()) input_str = 'Hello ' * 20 assert validator.isinstance_python(input_str) is True benchmark(validator.isinstance_python, input_str) @pytest.mark.benchmark(group='isinstance-string') def test_isinstance_string_lax_false(benchmark): validator = SchemaValidator(core_schema.str_schema()) assert validator.isinstance_python(123) is False benchmark(validator.isinstance_python, 123) @pytest.mark.benchmark(group='isinstance-string') def test_isinstance_string_strict_true(benchmark): validator = SchemaValidator(core_schema.str_schema(strict=True)) input_str = 'Hello ' * 20 assert validator.isinstance_python(input_str) is True benchmark(validator.isinstance_python, input_str) @pytest.mark.benchmark(group='isinstance-string') def test_isinstance_string_strict_false(benchmark): validator = SchemaValidator(core_schema.str_schema(strict=True)) assert validator.isinstance_python(123) is False benchmark(validator.isinstance_python, 123) @pytest.fixture def definition_model_data(): data = {'width': -1} _data = data for i in range(pydantic_core._pydantic_core._recursion_limit - 2): _data['branch'] = {'width': i} _data = _data['branch'] return data @skip_pypy_deep_stack @skip_wasm_deep_stack @pytest.mark.benchmark(group='recursive model') def test_definition_model_core(definition_model_data, benchmark): class CoreBranch: # this is not required, but it avoids `__pydantic_fields_set__` being included in `__dict__` __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' v = SchemaValidator( core_schema.definitions_schema( core_schema.definition_reference_schema(schema_ref='Branch'), [ core_schema.model_schema( CoreBranch, core_schema.model_fields_schema( { 'width': core_schema.model_field(core_schema.int_schema()), 'branch': core_schema.model_field( core_schema.with_default_schema( core_schema.nullable_schema( core_schema.definition_reference_schema(schema_ref='Branch') ), default=None, ) ), } ), ref='Branch', ) ], ) ) benchmark(v.validate_python, definition_model_data) @pytest.mark.benchmark(group='list[TypedDict]') def test_list_of_dict_models_core(benchmark): v = SchemaValidator( core_schema.list_schema( items_schema=core_schema.typed_dict_schema( fields={'width': core_schema.typed_dict_field(schema=core_schema.int_schema())} ) ) ) data = [{'width': i} for i in range(100)] benchmark(v.validate_python, data) list_of_ints_data = ([i for i in range(1000)], [str(i) for i in range(1000)]) @pytest.mark.benchmark(group='list[int]') def test_list_of_ints_core_py(benchmark): v = SchemaValidator(core_schema.list_schema(items_schema=core_schema.int_schema())) @benchmark def t(): v.validate_python(list_of_ints_data[0]) v.validate_python(list_of_ints_data[1]) @pytest.mark.benchmark(group='list[int] JSON') def test_list_of_ints_core_json(benchmark): v = SchemaValidator(core_schema.list_schema(items_schema=core_schema.int_schema())) json_data = [json.dumps(d) for d in list_of_ints_data] @benchmark def t(): v.validate_json(json_data[0]) v.validate_json(json_data[1]) list_of_strs_data = [str(i) for i in range(1000)] @pytest.mark.benchmark(group='list[str]') def test_list_of_strs_py_cached(benchmark): v = SchemaValidator(core_schema.list_schema(core_schema.str_schema())) benchmark(v.validate_python, list_of_strs_data) @pytest.mark.benchmark(group='list[str]') def test_list_of_strs_json_cached(benchmark): v = SchemaValidator(core_schema.list_schema(core_schema.str_schema())) json_data = json.dumps(list_of_strs_data) benchmark(v.validate_json, json_data) @pytest.mark.benchmark(group='list[str]') def test_list_of_strs_json_uncached(benchmark): v = SchemaValidator(core_schema.list_schema(core_schema.str_schema()), config=CoreConfig(cache_strings=False)) json_data = json.dumps(list_of_strs_data) benchmark(v.validate_json, json_data) @pytest.mark.benchmark(group='list[Any]') def test_list_of_any_core_py(benchmark): v = SchemaValidator(core_schema.list_schema()) @benchmark def t(): v.validate_python(list_of_ints_data[0]) v.validate_python(list_of_ints_data[1]) set_of_ints_data = ({i for i in range(1000)}, {str(i) for i in range(1000)}) set_of_ints_duplicates = ([i for i in range(100)] * 10, [str(i) for i in range(100)] * 10) @pytest.mark.benchmark(group='Set[int]') def test_set_of_ints_core(benchmark): v = SchemaValidator(core_schema.set_schema(items_schema=core_schema.int_schema())) @benchmark def t(): v.validate_python(set_of_ints_data[0]) v.validate_python(set_of_ints_data[1]) @pytest.mark.benchmark(group='Set[int]') def test_set_of_ints_core_duplicates(benchmark): v = SchemaValidator(core_schema.set_schema(items_schema=core_schema.int_schema())) @benchmark def t(): v.validate_python(set_of_ints_duplicates[0]) v.validate_python(set_of_ints_duplicates[1]) @pytest.mark.benchmark(group='Set[int]') def test_set_of_ints_core_length(benchmark): v = SchemaValidator(core_schema.set_schema(items_schema=core_schema.int_schema(), max_length=2000)) @benchmark def t(): v.validate_python(set_of_ints_data[0]) v.validate_python(set_of_ints_data[1]) @pytest.mark.benchmark(group='Set[int] JSON') def test_set_of_ints_core_json(benchmark): v = SchemaValidator(core_schema.set_schema(items_schema=core_schema.int_schema())) json_data = [json.dumps(list(d)) for d in set_of_ints_data] @benchmark def t(): v.validate_json(json_data[0]) v.validate_json(json_data[1]) @pytest.mark.benchmark(group='Set[int] JSON') def test_set_of_ints_core_json_duplicates(benchmark): v = SchemaValidator(core_schema.set_schema(items_schema=core_schema.int_schema())) json_data = [json.dumps(list(d)) for d in set_of_ints_duplicates] @benchmark def t(): v.validate_json(json_data[0]) v.validate_json(json_data[1]) frozenset_of_ints = frozenset({i for i in range(1000)}) frozenset_of_ints_duplicates = [i for i in range(100)] * 10 @pytest.mark.benchmark(group='FrozenSet[int]') def test_frozenset_of_ints_core(benchmark): v = SchemaValidator(core_schema.frozenset_schema(items_schema=core_schema.int_schema())) benchmark(v.validate_python, frozenset_of_ints) @pytest.mark.benchmark(group='FrozenSet[int]') def test_frozenset_of_ints_duplicates_core(benchmark): v = SchemaValidator(core_schema.frozenset_schema(items_schema=core_schema.int_schema())) benchmark(v.validate_python, frozenset_of_ints_duplicates) dict_of_ints_data = ({str(i): i for i in range(1000)}, {str(i): str(i) for i in range(1000)}) @pytest.mark.benchmark(group='dict[str, int]') def test_dict_of_ints_core(benchmark): v = SchemaValidator( core_schema.dict_schema(keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()) ) @benchmark def t(): v.validate_python(dict_of_ints_data[0]) v.validate_python(dict_of_ints_data[1]) @pytest.mark.benchmark(group='dict[any, any]') def test_dict_of_any_core(benchmark): v = SchemaValidator(core_schema.dict_schema()) @benchmark def t(): v.validate_python(dict_of_ints_data[0]) v.validate_python(dict_of_ints_data[1]) @pytest.mark.benchmark(group='dict[str, int] JSON') def test_dict_of_ints_core_json(benchmark): v = SchemaValidator( core_schema.dict_schema(keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()) ) json_data = [json.dumps(d) for d in dict_of_ints_data] @benchmark def t(): v.validate_json(json_data[0]) v.validate_json(json_data[1]) many_models_data = [{'age': i} for i in range(1000)] @pytest.mark.benchmark(group='list[DictSimpleMode]') def test_many_models_core_dict(benchmark): model_schema = { 'type': 'list', 'items_schema': { 'type': 'typed-dict', 'fields': {'age': {'type': 'typed-dict-field', 'schema': {'type': 'int'}}}, }, } v = SchemaValidator(model_schema) benchmark(v.validate_python, many_models_data) @pytest.mark.benchmark(group='list[SimpleMode]') def test_many_models_core_model(benchmark): class MyCoreModel: __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' v = SchemaValidator( core_schema.list_schema( items_schema=core_schema.model_schema( cls=MyCoreModel, schema=core_schema.model_fields_schema( fields={'age': core_schema.model_field(schema=core_schema.int_schema())} ), ) ) ) benchmark(v.validate_python, many_models_data) list_of_nullable_data = [None if i % 2 else i for i in range(1000)] @pytest.mark.benchmark(group='list[Nullable[int]]') def test_list_of_nullable_core(benchmark): v = SchemaValidator( core_schema.list_schema(items_schema=core_schema.nullable_schema(schema=core_schema.int_schema())) ) benchmark(v.validate_python, list_of_nullable_data) some_bytes = b'0' * 1000 @pytest.mark.benchmark(group='bytes') def test_bytes_core(benchmark): v = SchemaValidator(core_schema.bytes_schema()) benchmark(v.validate_python, some_bytes)
TestModelLarge
python
django__django
tests/auth_tests/operations_migrations/0002_rename_oldmodel_to_newmodel.py
{ "start": 35, "end": 276 }
class ____(migrations.Migration): dependencies = [ ("auth_tests", "0001_initial"), ] operations = [ migrations.RenameModel( old_name="OldModel", new_name="NewModel", ), ]
Migration
python
pypa__hatch
tests/utils/test_platform.py
{ "start": 1471, "end": 2933 }
class ____: def test_tag(self): assert Platform().macos is True def test_default_shell(self): assert Platform().default_shell == os.environ.get("SHELL", "bash") def test_format_for_subprocess_list(self): assert Platform().format_for_subprocess(["foo", "bar"], shell=False) == ["foo", "bar"] def test_format_for_subprocess_list_shell(self): assert Platform().format_for_subprocess(["foo", "bar"], shell=True) == ["foo", "bar"] def test_format_for_subprocess_string(self): assert Platform().format_for_subprocess("foo bar", shell=False) == ["foo", "bar"] def test_format_for_subprocess_string_shell(self): assert Platform().format_for_subprocess("foo bar", shell=True) == "foo bar" def test_home(self): platform = Platform() assert platform.home == platform.home == Path(os.path.expanduser("~")) def test_populate_default_popen_kwargs_executable(self, temp_dir): new_path = f"{os.environ.get('PATH', '')}{os.pathsep}{temp_dir}".strip(os.pathsep) executable = temp_dir / "sh" executable.touch() executable.chmod(executable.stat().st_mode | stat.S_IEXEC) kwargs = {} platform = Platform() with EnvVars({"DYLD_FOO": "bar", "PATH": new_path}): platform.populate_default_popen_kwargs(kwargs, shell=True) assert kwargs["executable"] == str(executable) @pytest.mark.requires_linux
TestMacOS
python
langchain-ai__langchain
libs/langchain/tests/integration_tests/test_schema.py
{ "start": 118, "end": 755 }
class ____: def test_tokenization(self) -> None: # Check that the tokenization is consistent with the GPT-2 tokenizer assert _get_token_ids_default_method("This is a test") == [1212, 318, 257, 1332] def test_empty_token(self) -> None: assert len(_get_token_ids_default_method("")) == 0 def test_multiple_tokens(self) -> None: assert len(_get_token_ids_default_method("a b c")) == 3 def test_special_tokens(self) -> None: # test for consistency when the default tokenizer is changed assert len(_get_token_ids_default_method("a:b_c d")) == 6
TestTokenCountingWithGPT2Tokenizer
python
Textualize__textual
src/textual/widgets/_list_view.py
{ "start": 552, "end": 14297 }
class ____(VerticalScroll, can_focus=True, can_focus_children=False): """A vertical list view widget. Displays a vertical list of `ListItem`s which can be highlighted and selected using the mouse or keyboard. Attributes: index: The index in the list that's currently highlighted. """ ALLOW_MAXIMIZE = True DEFAULT_CSS = """ ListView { background: $surface; & > ListItem { color: $foreground; height: auto; overflow: hidden hidden; width: 1fr; &.-hovered { background: $block-hover-background; } &.-highlight { color: $block-cursor-blurred-foreground; background: $block-cursor-blurred-background; text-style: $block-cursor-blurred-text-style; } } &:focus { background-tint: $foreground 5%; & > ListItem.-highlight { color: $block-cursor-foreground; background: $block-cursor-background; text-style: $block-cursor-text-style; } } } """ BINDINGS: ClassVar[list[BindingType]] = [ Binding("enter", "select_cursor", "Select", show=False), Binding("up", "cursor_up", "Cursor up", show=False), Binding("down", "cursor_down", "Cursor down", show=False), ] """ | Key(s) | Description | | :- | :- | | enter | Select the current item. | | up | Move the cursor up. | | down | Move the cursor down. | """ index = reactive[Optional[int]](None, init=False) """The index of the currently highlighted item.""" class Highlighted(Message): """Posted when the highlighted item changes. Highlighted item is controlled using up/down keys. Can be handled using `on_list_view_highlighted` in a subclass of `ListView` or in a parent widget in the DOM. """ ALLOW_SELECTOR_MATCH = {"item"} """Additional message attributes that can be used with the [`on` decorator][textual.on].""" def __init__(self, list_view: ListView, item: ListItem | None) -> None: super().__init__() self.list_view: ListView = list_view """The view that contains the item highlighted.""" self.item: ListItem | None = item """The highlighted item, if there is one highlighted.""" @property def control(self) -> ListView: """The view that contains the item highlighted. This is an alias for [`Highlighted.list_view`][textual.widgets.ListView.Highlighted.list_view] and is used by the [`on`][textual.on] decorator. """ return self.list_view class Selected(Message): """Posted when a list item is selected, e.g. when you press the enter key on it. Can be handled using `on_list_view_selected` in a subclass of `ListView` or in a parent widget in the DOM. """ ALLOW_SELECTOR_MATCH = {"item"} """Additional message attributes that can be used with the [`on` decorator][textual.on].""" def __init__(self, list_view: ListView, item: ListItem, index: int) -> None: super().__init__() self.list_view: ListView = list_view """The view that contains the item selected.""" self.item: ListItem = item """The selected item.""" self.index = index """Index of the selected item.""" @property def control(self) -> ListView: """The view that contains the item selected. This is an alias for [`Selected.list_view`][textual.widgets.ListView.Selected.list_view] and is used by the [`on`][textual.on] decorator. """ return self.list_view def __init__( self, *children: ListItem, initial_index: int | None = 0, name: str | None = None, id: str | None = None, classes: str | None = None, disabled: bool = False, ) -> None: """ Initialize a ListView. Args: *children: The ListItems to display in the list. initial_index: The index that should be highlighted when the list is first mounted. name: The name of the widget. id: The unique ID of the widget used in CSS/query selection. classes: The CSS classes of the widget. disabled: Whether the ListView is disabled or not. """ super().__init__( *children, name=name, id=id, classes=classes, disabled=disabled ) self._initial_index = initial_index def _on_mount(self, _: Mount) -> None: """Ensure the ListView is fully-settled after mounting.""" if self._initial_index is not None and self.children: index = self._initial_index if index >= len(self.children): index = 0 if self._nodes[index].disabled: for index, node in loop_from_index(self._nodes, index, wrap=True): if not node.disabled: break self.index = index @property def highlighted_child(self) -> ListItem | None: """The currently highlighted ListItem, or None if nothing is highlighted.""" if self.index is not None and 0 <= self.index < len(self._nodes): list_item = self._nodes[self.index] assert isinstance(list_item, ListItem) return list_item else: return None def validate_index(self, index: int | None) -> int | None: """Clamp the index to the valid range, or set to None if there's nothing to highlight. Args: index: The index to clamp. Returns: The clamped index. """ if index is None or not self._nodes: return None elif index < 0: return 0 elif index >= len(self._nodes): return len(self._nodes) - 1 return index def _is_valid_index(self, index: int | None) -> TypeGuard[int]: """Determine whether the current index is valid into the list of children.""" if index is None: return False return 0 <= index < len(self._nodes) def watch_index(self, old_index: int | None, new_index: int | None) -> None: """Updates the highlighting when the index changes.""" if new_index is not None: selected_widget = self._nodes[new_index] if selected_widget.region: self.scroll_to_widget(self._nodes[new_index], animate=False) else: # Call after refresh to permit a refresh operation self.call_after_refresh( self.scroll_to_widget, selected_widget, animate=False ) if self._is_valid_index(old_index): old_child = self._nodes[old_index] assert isinstance(old_child, ListItem) old_child.highlighted = False if ( new_index is not None and self._is_valid_index(new_index) and not self._nodes[new_index].disabled ): new_child = self._nodes[new_index] assert isinstance(new_child, ListItem) new_child.highlighted = True self.post_message(self.Highlighted(self, new_child)) else: self.post_message(self.Highlighted(self, None)) def extend(self, items: Iterable[ListItem]) -> AwaitMount: """Append multiple new ListItems to the end of the ListView. Args: items: The ListItems to append. Returns: An awaitable that yields control to the event loop until the DOM has been updated with the new child items. """ await_mount = self.mount(*items) return await_mount def append(self, item: ListItem) -> AwaitMount: """Append a new ListItem to the end of the ListView. Args: item: The ListItem to append. Returns: An awaitable that yields control to the event loop until the DOM has been updated with the new child item. """ return self.extend([item]) def clear(self) -> AwaitRemove: """Clear all items from the ListView. Returns: An awaitable that yields control to the event loop until the DOM has been updated to reflect all children being removed. """ await_remove = self.query("ListView > ListItem").remove() self.index = None return await_remove def insert(self, index: int, items: Iterable[ListItem]) -> AwaitMount: """Insert new ListItem(s) to specified index. Args: index: index to insert new ListItem. items: The ListItems to insert. Returns: An awaitable that yields control to the event loop until the DOM has been updated with the new child item. """ await_mount = self.mount(*items, before=index) return await_mount def pop(self, index: Optional[int] = None) -> AwaitComplete: """Remove last ListItem from ListView or Remove ListItem from ListView by index Args: index: index of ListItem to remove from ListView Returns: An awaitable that yields control to the event loop until the DOM has been updated to reflect item being removed. """ if len(self) == 0: raise IndexError("pop from empty list") index = index if index is not None else -1 item_to_remove = self.query("ListItem")[index] normalized_index = index if index >= 0 else index + len(self) async def do_pop() -> None: """Remove the item and update the highlighted index.""" await item_to_remove.remove() if self.index is not None: if normalized_index < self.index: self.index -= 1 elif normalized_index == self.index: old_index = self.index # Force a re-validation of the index self.index = self.index # If the index hasn't changed, the watcher won't be called # but we need to update the highlighted item if old_index == self.index: self.watch_index(old_index, self.index) return AwaitComplete(do_pop()) def remove_items(self, indices: Iterable[int]) -> AwaitComplete: """Remove ListItems from ListView by indices Args: indices: index(s) of ListItems to remove from ListView Returns: An awaitable object that waits for the direct children to be removed. """ items = self.query("ListItem") items_to_remove = [items[index] for index in indices] normalized_indices = set( index if index >= 0 else index + len(self) for index in indices ) async def do_remove_items() -> None: """Remove the items and update the highlighted index.""" await self.remove_children(items_to_remove) if self.index is not None: removed_before_highlighted = sum( 1 for index in normalized_indices if index < self.index ) if removed_before_highlighted: self.index -= removed_before_highlighted elif self.index in normalized_indices: old_index = self.index # Force a re-validation of the index self.index = self.index # If the index hasn't changed, the watcher won't be called # but we need to update the highlighted item if old_index == self.index: self.watch_index(old_index, self.index) return AwaitComplete(do_remove_items()) def action_select_cursor(self) -> None: """Select the current item in the list.""" selected_child = self.highlighted_child if selected_child is None: return self.post_message(self.Selected(self, selected_child, self.index)) def action_cursor_down(self) -> None: """Highlight the next item in the list.""" if self.index is None: if self._nodes: self.index = 0 else: index = self.index for index, item in loop_from_index(self._nodes, self.index, wrap=False): if not item.disabled: self.index = index break def action_cursor_up(self) -> None: """Highlight the previous item in the list.""" if self.index is None: if self._nodes: self.index = len(self._nodes) - 1 else: for index, item in loop_from_index( self._nodes, self.index, direction=-1, wrap=False ): if not item.disabled: self.index = index break def _on_list_item__child_clicked(self, event: ListItem._ChildClicked) -> None: event.stop() self.focus() self.index = self._nodes.index(event.item) self.post_message(self.Selected(self, event.item, self.index)) def __len__(self) -> int: """Compute the length (in number of items) of the list view.""" return len(self._nodes)
ListView
python
coleifer__peewee
tests/schema.py
{ "start": 30297, "end": 30787 }
class ____(ModelTestCase): requires = [User] def test_truncate_table(self): for i in range(3): User.create(username='u%s' % i) ctx = User._schema._truncate_table() if IS_SQLITE: self.assertSQL(ctx, 'DELETE FROM "users"', []) else: sql, _ = ctx.query() self.assertTrue(sql.startswith('TRUNCATE TABLE ')) User.truncate_table() self.assertEqual(User.select().count(), 0)
TestTruncateTable
python
astropy__astropy
astropy/cosmology/_src/parameter/core.py
{ "start": 2314, "end": 11317 }
class ____: r"""Cosmological parameter (descriptor). Should only be used with a :class:`~astropy.cosmology.Cosmology` subclass. Parameters ---------- default : Any (optional, keyword-only) Default value of the Parameter. If not given the Parameter must be set when initializing the cosmology. derived : bool (optional, keyword-only) Whether the Parameter is 'derived', default `False`. Derived parameters behave similarly to normal parameters, but are not sorted by the |Cosmology| signature (probably not there) and are not included in all methods. For reference, see ``Ode0`` in ``FlatFLRWMixin``, which removes :math:`\Omega_{de,0}`` as an independent parameter (:math:`\Omega_{de,0} \equiv 1 - \Omega_{tot}`). unit : unit-like or None (optional, keyword-only) The `~astropy.units.Unit` for the Parameter. If None (default) no unit as assumed. equivalencies : `~astropy.units.Equivalency` or sequence thereof Unit equivalencies for this Parameter. fvalidate : callable[[object, object, Any], Any] or str (optional, keyword-only) Function to validate the Parameter value from instances of the cosmology class. If "default", uses default validator to assign units (with equivalencies), if Parameter has units. For other valid string options, see ``Parameter._registry_validators``. 'fvalidate' can also be set through a decorator with :meth:`~astropy.cosmology.Parameter.validator`. doc : str or None (optional, keyword-only) Parameter description. Examples -------- For worked examples see :class:`~astropy.cosmology.FLRW`. """ _: KW_ONLY default: Any = MISSING """Default value of the Parameter. By default set to ``MISSING``, which indicates the parameter must be set when initializing the cosmology. """ derived: bool = False """Whether the Parameter can be set, or is derived, on the cosmology.""" # Units unit: _UnitField = _UnitField() """The unit of the Parameter (can be `None` for unitless).""" equivalencies: u.Equivalency | Sequence[u.Equivalency] = field(default_factory=list) """Unit equivalencies available when setting the parameter.""" # Setting fvalidate: _FValidateField = _FValidateField(default="default") """Function to validate/convert values when setting the Parameter.""" # Info doc: str | None = None """Parameter description.""" name: str = field(init=False, compare=True, default=None, repr=False) """The name of the Parameter on the Cosmology. Cannot be set directly. """ def __post_init__(self) -> None: self._fvalidate_in: FValidateCallable | str self._fvalidate: FValidateCallable object.__setattr__(self, "__doc__", self.doc) # Now setting a dummy attribute name. The cosmology class will call # `__set_name__`, passing the real attribute name. However, if Parameter is not # init'ed as a descriptor then this ensures that all declared fields exist. self.__set_name__(None, "name not initialized") def __set_name__(self, cosmo_cls: type, name: str) -> None: # attribute name on container cosmology class object.__setattr__(self, "name", name) # ------------------------------------------- # descriptor and property-like methods def __get__( self, cosmology: Union["astropy.cosmology.Cosmology", None], cosmo_cls: Union["type[astropy.cosmology.Cosmology]", None] = None, ) -> Any: # Get from class if cosmology is None: # If the Parameter is being set as part of a dataclass constructor, then we # raise an AttributeError if the default is MISSING. This is to prevent the # Parameter from being set as the default value of the dataclass field and # erroneously included in the class' __init__ signature. if self.default is MISSING and ( not is_dataclass(cosmo_cls) or self.name not in cosmo_cls.__dataclass_fields__ ): raise AttributeError return self # Get from instance return cosmology.__dict__[self.name] def __set__(self, cosmology: "astropy.cosmology.Cosmology", value: Any) -> None: """Allows attribute setting once. Raises AttributeError subsequently. """ # Raise error if setting 2nd time. The built-in Cosmology objects are frozen # dataclasses and this is redundant, however user defined cosmology classes do # not have to be frozen. if self.name in cosmology.__dict__: raise AttributeError(f"cannot assign to field {self.name!r}") # Change `self` to the default value if default is MISSING. # This is done for backwards compatibility only - so that Parameter can be used # in a dataclass and still return `self` when accessed from a class. # Accessing the Parameter object via `cosmo_cls.param_name` will be removed # in favor of `cosmo_cls.parameters["param_name"]`. if value is self: value = self.default # Validate value, generally setting units if present value = self.validate(cosmology, copy.deepcopy(value)) # Make the value read-only, if ndarray-like if hasattr(value, "setflags"): value.setflags(write=False) # Set the value on the cosmology cosmology.__dict__[self.name] = value # ------------------------------------------- # validate value def validator(self, fvalidate: FValidateCallable) -> "Parameter": """Make new Parameter with custom ``fvalidate``. Note: ``Parameter.fvalidator`` must be the top-most descriptor decorator. Parameters ---------- fvalidate : callable[[type, type, Any], Any] Returns ------- `~astropy.cosmology.Parameter` Copy of this Parameter but with custom ``fvalidate``. """ return self.clone(fvalidate=fvalidate) def validate(self, cosmology: "astropy.cosmology.Cosmology", value: Any) -> Any: """Run the validator on this Parameter. Parameters ---------- cosmology : `~astropy.cosmology.Cosmology` instance value : Any The object to validate. Returns ------- Any The output of calling ``fvalidate(cosmology, self, value)`` (yes, that parameter order). """ return self._fvalidate(cosmology, self, value) @staticmethod def register_validator(key, fvalidate: FValidateCallable | None = None) -> Any: """Decorator to register a new kind of validator function. Parameters ---------- key : str fvalidate : callable[[object, object, Any], Any] or None, optional Value validation function. Returns ------- ``validator`` or callable[``validator``] if validator is None returns a function that takes and registers a validator. This allows ``register_validator`` to be used as a decorator. """ return _register_validator(key, fvalidate=fvalidate) # ------------------------------------------- def clone(self, **kw: Any) -> "Parameter": """Clone this `Parameter`, changing any constructor argument. Parameters ---------- **kw Passed to constructor. The current values, eg. ``fvalidate`` are used as the default values, so an empty ``**kw`` is an exact copy. Examples -------- >>> p = Parameter() >>> p Parameter(derived=False, unit=None, equivalencies=[], fvalidate='default', doc=None) >>> p.clone(unit="km") Parameter(derived=False, unit=Unit("km"), equivalencies=[], fvalidate='default', doc=None) """ kw.setdefault("fvalidate", self._fvalidate_in) # prefer the input fvalidate cloned = replace(self, **kw) # Transfer over the __set_name__ stuff. If `clone` is used to make a # new descriptor, __set_name__ will be called again, overwriting this. cloned.__set_name__(None, self.name) return cloned def __repr__(self) -> str: """Return repr(self).""" fields_repr = ( # Get the repr, using the input fvalidate over the processed value f"{f.name}={(getattr(self, f.name if f.name != 'fvalidate' else '_fvalidate_in'))!r}" for f in fields(self) # Only show fields that should be displayed and are not sentinel values if f.repr and (f.name != "default" or self.default is not MISSING) ) return f"{self.__class__.__name__}({', '.join(fields_repr)})"
Parameter
python
spyder-ide__spyder
spyder/plugins/findinfiles/widgets/main_widget.py
{ "start": 1893, "end": 1994 }
class ____: Exclude = 'exclude_toolbar' Location = 'location_toolbar'
FindInFilesWidgetToolbars
python
pytorch__pytorch
test/distributed/test_c10d_spawn_gloo.py
{ "start": 596, "end": 8717 }
class ____(TestCase): def setUp(self): self.rank = 0 self.world_size = 1 self.file = tempfile.NamedTemporaryFile(delete=False) # noqa: P201 def tearDown(self): try: os.remove(self.file.name) except OSError: pass def _test_base(self, net, inp, check_allclose=True): store = c10d.FileStore(self.file.name, self.world_size) c10d.init_process_group( backend="gloo", store=store, rank=self.rank, world_size=self.world_size ) process_group = c10d.distributed_c10d._get_default_group() if inp[0].is_cuda: device_ids = [torch.cuda.current_device()] else: device_ids = None ddp = nn.parallel.DistributedDataParallel( copy.deepcopy(net), device_ids=device_ids, process_group=process_group ) net_opt = torch.optim.Adam(net.parameters(), lr=0.001) ddp_opt = torch.optim.Adam(ddp.parameters(), lr=0.001) for i, j in zip(ddp.parameters(), net.parameters()): self.assertTrue(i.allclose(j)) for _ in range(10): net_out = net(*inp) ddp_out = ddp(*inp) net_out.sum().backward() ddp_out.sum().backward() net_opt.step() ddp_opt.step() if check_allclose: for i, j in zip(ddp.parameters(), net.parameters()): self.assertTrue(i.allclose(j)) @requires_gloo() def test_cpu(self): self._test_base(nn.Linear(2, 2), [torch.randn(30, 2)]) @requires_gloo() @skip_but_pass_in_sandcastle_if(not TEST_CUDA, "At least 1 CUDA GPUS needed") def test_cuda(self): self._test_base(nn.Linear(2, 2).to(0), [torch.randn(30, 2).to(0)]) @requires_gloo() @skip_but_pass_in_sandcastle_if(not TEST_CUDA, "At least 1 CUDA GPUS needed") def test_rnn(self): # This test is inspired by the bug reported in # https://github.com/pytorch/pytorch/issues/36268 BATCH_SIZE = 12 # Divisible by 2, 3, 4 INPUT_DIM = 256 OUTPUT_DIM = 256 HIDDEN_DIM = 256 N_LAYERS = 3 SEQ_LEN = 100 class Net(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, hidden_layers): super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim self.hidden_layers = hidden_layers self.lstm = nn.LSTM( input_dim, hidden_dim, hidden_layers, batch_first=True ) self.h2o = nn.Linear(hidden_dim, output_dim) def forward(self, x, y): self.lstm.flatten_parameters() h_t, _ = self.lstm(x) output = self.h2o(h_t) loss = nn.functional.mse_loss(output, y) return loss net = Net(INPUT_DIM, HIDDEN_DIM, OUTPUT_DIM, N_LAYERS).to(0) inp = [ torch.randn((BATCH_SIZE, SEQ_LEN, INPUT_DIM)).to(0), torch.rand((BATCH_SIZE, SEQ_LEN, OUTPUT_DIM)).to(0), ] # Not checking result allclose as the parameter inconsistency exist # prior to this change. See #37079 self._test_base(net, inp, check_allclose=False) # Skip dev-asan as torch + multiprocessing spawn have known issues if not TEST_WITH_DEV_DBG_ASAN: class TestDistributedNNFunctionsGloo(TestDistributedNNFunctions): # Test Common Ops First. @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_broadcast(self): self._test_broadcast("gloo") @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_reduce(self): self._test_reduce("gloo") @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_allreduce(self): self._test_allreduce("gloo") @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_all_gather(self): self._test_all_gather("gloo") @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_all_to_all(self): self._test_all_to_all("gloo") @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_all_to_all_single(self): self._test_all_to_all_single("gloo") # Test Ops only supported in GLOO. @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_gather(self): store = c10d.FileStore(self.file_name, self.world_size) # This is required because these functions calls directly to the .dist and needs # the world to be initialized c10d.init_process_group( store=store, rank=self.rank, world_size=self.world_size, backend="gloo" ) device = torch.device(f"cuda:{self.rank}") x = torch.ones(5, 5, device=device) + self.rank x.requires_grad = True tensors = torch.distributed.nn.gather(x, 1) if self.rank == 1: for i, t in enumerate(tensors): self.assertEqual(t, torch.ones(5, 5, device=device) + i) elif self.rank == 0: for t in tensors: zeros = torch.zeros(5, 5, device=device) self.assertEqual(t, zeros) y = torch.sum(torch.stack(tensors), axis=0) z = y.sin().sum() z.backward() # Test gradient x_s = 3 * torch.ones(5, 5, device=device) self.assertEqual(x.grad, x_s.cos()) @requires_gloo() @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _torch_dist_nn_available, "torch.distributed.nn is not available" ) def test_scatter(self): store = c10d.FileStore(self.file_name, self.world_size) # This is required because these functions calls directly to the .dist and needs # the world to be initialized c10d.init_process_group( store=store, rank=self.rank, world_size=self.world_size, backend="gloo" ) device = torch.device(f"cuda:{self.rank}") x0 = torch.ones(5, 5, device=device) x1 = torch.ones(5, 5, device=device) + 1 x0.requires_grad = True x1.requires_grad = True y = torch.distributed.nn.scatter([x0, x1], 1) if self.rank == 1: self.assertEqual(y, 1 + torch.ones(5, 5, device=device)) elif self.rank == 0: self.assertEqual(y, torch.ones(5, 5, device=device)) z = y.sin().sum() z.backward() # Test gradient if self.rank == 1: x0_s = torch.ones(5, 5, device=device).cos() x1_s = (2 * torch.ones(5, 5, device=device)).cos() self.assertEqual(x0.grad, x0_s) self.assertEqual(x1.grad, x1_s) if self.rank == 0: self.assertEqual(x0.grad, torch.zeros(5, 5, device=device)) if __name__ == "__main__": run_tests()
DistributedDataParallelSingleProcessTest
python
pytorch__pytorch
torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py
{ "start": 624, "end": 13552 }
class ____(base_sparsifier.BaseSparsifier): r""" Base Data Sparsifier class for all Data sparsifiers. The abstract class accepts raw torch tensors / embedding / embedding bags (refer to SUPPORTED_TYPES above) to prepare for sparsification. In this case, mask (and parametrizations) is owned by the class and not by the user. Specifically, the container object inside the class maintains the mask and parametrizations of the input data Args: data_list (list of tuples) list of (name, data) tuples to sparsify. Lookup SUPPORTED_TYPES for type of data. Internally, a container module handles the data sparsification. defaults (dict) default configurations will be attached to the configuration. Only the keys that don't exist in the `config` will be updated. Example:: >>> # xdoctest: +SKIP >>> data_list = [('tensor_1', torch.randn(3,3)), ('tensor_2', torch.randn(4,4))] >>> defaults = {'sparsity_level': 0.7} >>> sparsifier = DerivedDataSparsifier(data_list = data_list, **defaults) # Some sparsifier that inherits BaseDataSparsifier >>> new_tensor_to_add = {'name': 'tensor_3', 'data': torch.randn(5,5), 'sparsity_level': 0.3} >>> sparsifier.add_data(**new_tensor_to_add) >>> # tensor_1 and tensor_2 will have sparsity_level of 0.7 but tensor_3 will have sparsity_level=0.3 """ def __init__(self, data_list: list[tuple[str, Any]] | None = None, **defaults): super().__init__(defaults=defaults) self._container = _Container() self.data_groups: dict[str, dict] = defaultdict(dict) # name -> {**config} if data_list is not None: # add data with default config here [self.add_data(name, data, **self.defaults) for name, data in data_list] def prepare(self, model, config): raise NotImplementedError("this function is undefined for this class") def _extract_weight(self, data): # extract the weight parameter instead of underlying data if type(data) in [torch.Tensor, nn.Parameter]: return data elif type(data) in EMBEDDING_TYPES: return data.weight def add_data(self, name: str, data, reuse_mask=True, **config): r"""Configures and parametrizes the internal container model with name and data. **Note**: 1. If the data with name already exists, it replaces the data. 2. While replacing, the old mask is reused when `reuse_mask=True` 3. If `reuse_mask=True`, then the replacing data needs to have the same shape as that of old data. 4. By default, the config of the replaced data is used as config for the replacing data, unless something is specified in the config dictionary. """ if type(data) not in SUPPORTED_TYPES: raise AssertionError( f"specified data type:{type(data)} not supported at the moment" ) local_args = copy.deepcopy(self.defaults) local_args.update(config) weight = self._extract_weight(data) # Bookkeeping in the container class mask = local_args.get("mask", torch.ones_like(weight)) param_class = local_args.get("parametrization", utils.FakeSparsity) if name in self.state: # If the named data already exists - replace warnings.warn( "Replacing existing data of the same name. - Did you mean a different name?", stacklevel=2, ) # reuse old config old_args = self.data_groups[name] local_args = copy.deepcopy(old_args) local_args.update(config) if reuse_mask: current_data = self.get_data(name=name) if weight.shape != current_data.shape: raise AssertionError( "to retain the old mask, the shape of the new data must be the same as the previous one" ) mask = self.get_mask( name=name ) # reuse mask instead of creating a new one self._delete_data(name=name) # parameter creates a deepcopy of the weight inside, so create a buffer self._container.register_buffer(name=name, tensor=weight) parametrize.register_parametrization(self._container, name, param_class(mask)) self.state[name]["mask"] = mask self.data_groups[name] = local_args return getattr(self._container, name) def get_data(self, name: str, return_original: bool = True): r"""Returns weight tensor (or data) Args: - name: name of the data to be returned - return_original returns weight tensor without applying parametrization if True else - returns the sparsified version (parametrized) """ if name not in self.data_groups: raise ValueError("data with specified name does not exist") if return_original: if not parametrize.is_parametrized(self._container, name): raise ValueError("mask squashed - original mask value does not exist") data = getattr(self._container.parametrizations, name).original return data else: return getattr(self._container, name) def _convert_mask(self, states, sparse_coo=True): r"""Converts the mask to sparse coo or dense tensors depending on the `sparse_coo` argument.""" states = copy.deepcopy(states) for state in states.values(): if sparse_coo: state["mask"] = state["mask"].to_sparse_coo() else: state["mask"] = state["mask"].to_dense() return states def state_dict(self): r"""Returns the state of the optimizer as a :class:`dict`. It contains: * state - contains name -> mask mapping. * data_groups - a list containing all sparsity configuration groups with the key name specifying the name of the data * container_state_dict - the state dictionary of the internal container model used for sparsification """ state = self._convert_mask(self.state) return { "state": state, "data_groups": self.data_groups, "_container": self._container.state_dict(), } def _load_container_from_state(self, states, data_groups, container_state_dict): r"""This restores the state of the container specifically based on the data present in state and data_groups If the data was parametrized, then the data would be added to the container and then parametrized, else it would just add the attribute the container. """ for name, state in states.items(): config_name = data_groups.get(name, None) if config_name is None: raise RuntimeError(f"Error loading {name}") # check if the data with such a name was parametrized, if so parametrize # otherwise just set the attribute and continue parametrized_name = f"parametrizations.{name}.original" parametrized = False data = container_state_dict.get(name, None) if name in container_state_dict: # the parametrization was probably removed for this data = container_state_dict.get(name) elif parametrized_name in container_state_dict: # so the weight was parametrized data = container_state_dict.get(parametrized_name) parametrized = True else: raise RuntimeError(f"Error loading {name}") self._container.register_buffer(name=name, tensor=data) if parametrized: # register parameter if parametrized mask = state.get("mask", torch.ones_like(data)) param_class = data_groups.get( "parametrization", utils.FakeSparsity ) # change once public_api for utils is fixed! parametrize.register_parametrization( self._container, name, param_class(mask) ) def load_state_dict(self, state_dict, strict=True): r"""The load_state_dict() restores the state of the sparsifier based on the state_dict Args: * state_dict - the dictionary that to which the current sparsifier needs to be restored to * strict - If True - the sparsifier is reset and is restored exactly to the state in state_dict. If False - the current sparsifier is not reset before loading the state_dict i.e. data added before loading the state_dict is not erased. """ states = copy.deepcopy(state_dict["state"]) data_groups = copy.deepcopy(state_dict["data_groups"]) container_state_dict = copy.deepcopy(state_dict["_container"]) states = self._convert_mask( states, sparse_coo=False ) # convert sparse coo mask to dense if strict: # if strict load -> then reset container self._container = _Container() self._load_container_from_state(states, data_groups, container_state_dict) if not strict: states.update(self.state) data_groups.update(self.data_groups) self.__setstate__({"state": states, "data_groups": data_groups}) def __setstate__(self, state): if "_container" in state: # If container object is in state then load model container_dict = state.pop("_container") self._container = _Container() state["state"] = self._convert_mask( state["state"], sparse_coo=False ) # convert sparse coo mask to dense self._load_container_from_state( state["state"], state["data_groups"], container_dict ) self.__dict__.update(state) def __getstate__(self): state = self._convert_mask(self.state) return { "defaults": self.defaults, "state": state, "data_groups": self.data_groups, "_container": self._container.state_dict(), } def __repr__(self): # type:ignore[override] format_string = self.__class__.__name__ + " (" for name, sparse_args in self.data_groups.items(): format_string += "\n" format_string += "\tData Group\n" format_string += f"\t name: {name}\n" for key in sorted(sparse_args.keys()): if key == "data": continue format_string += f"\t {key}: {sparse_args[key]}\n" format_string += ")" return format_string def get_mask(self, name: str): if name not in self.state: raise ValueError("data with specified name does not exist") return self.state[name]["mask"] def squash_mask(self, *args, leave_parametrized=True, names=None, **kwargs): r"""Squashes the sparse masks into the appropriate tensors. Also, accepts list of strings to squash mask for. If none, squashes mask for all the keys kwargs: * names: list of strings to squash mask for * sparsified: if true - applies the mask before squashing if false - does not apply the mask before squashing """ if names is None: names = list(self.data_groups.keys()) for name in names: parametrize.remove_parametrizations( self._container, name, leave_parametrized=leave_parametrized ) def step(self): # type:ignore[override] if not self.enable_mask_update: return with torch.no_grad(): for name, config in self.data_groups.items(): # get non-sparsified data data = self.get_data(name) # need name for the mask otherwise can directly pass mask? self.update_mask(name, data, **config) @abc.abstractmethod def update_mask(self, name, data, **kwargs): # type: ignore[override] pass def _delete_data(self, name): """Detaches some data from the sparsifier. Args: name (str) Name of the data to be removed from the sparsifier Note: Currently private. Kind of used as a helper function when replacing data of the same name """ self.squash_mask( names=[name], leave_parametrized=False ) # do not apply the mask while deleting delattr(self._container, name) self.state.pop(name) self.data_groups.pop(name)
BaseDataSparsifier
python
openai__openai-python
src/openai/resources/files.py
{ "start": 28759, "end": 29573 }
class ____: def __init__(self, files: Files) -> None: self._files = files self.create = to_streamed_response_wrapper( files.create, ) self.retrieve = to_streamed_response_wrapper( files.retrieve, ) self.list = to_streamed_response_wrapper( files.list, ) self.delete = to_streamed_response_wrapper( files.delete, ) self.content = to_custom_streamed_response_wrapper( files.content, StreamedBinaryAPIResponse, ) self.retrieve_content = ( # pyright: ignore[reportDeprecated] to_streamed_response_wrapper( files.retrieve_content, # pyright: ignore[reportDeprecated], ) )
FilesWithStreamingResponse
python
google__pytype
pytype/abstract/_instance_base.py
{ "start": 663, "end": 8972 }
class ____(_base.BaseValue): """A basic abstract value that represents instances. This class implements instances in the Python sense. Instances of the same class may vary. Note that the cls attribute will point to another abstract value that represents the class object itself, not to some special type representation. Attributes: members: A name->value dictionary of the instance's attributes. """ def __init__(self, name: str, ctx: "context.Context"): """Initialize a SimpleValue. Args: name: Name of this value. For debugging and error reporting. ctx: The abstract context. """ super().__init__(name, ctx) self._cls = None # lazily loaded 'cls' attribute self.members = datatypes.MonitorDict() # Lazily loaded to handle recursive types. # See Instance._load_instance_type_parameters(). self._instance_type_parameters: ( "datatypes.AliasingMonitorDict[str, cfg.Variable]" ) = datatypes.AliasingMonitorDict() # This attribute depends on self.cls, which isn't yet set to its true value. self._maybe_missing_members: bool | None = None # The latter caches the result of get_type_key. This is a recursive function # that has the potential to generate too many calls for large definitions. self._type_key: "frozenset[_base.BaseValue | _typing.LateAnnotation | tuple[str, frozenset]] | None" = (None) self._fullhash = None self._cached_changestamps = self._get_changestamps() def _get_changestamps(self) -> "tuple[int, int]": return ( self.members.changestamp, self._instance_type_parameters.changestamp, ) @property def instance_type_parameters( self, ) -> "datatypes.AliasingMonitorDict[str, cfg.Variable]": return self._instance_type_parameters @property def maybe_missing_members(self) -> bool: if self._maybe_missing_members is None: # maybe_missing_members indicates that every attribute access on this # object should always succeed. This is usually indicated by the class # setting _HAS_DYNAMIC_ATTRIBUTES = True. # This should apply to both the class and instances of the class. dyn_self = isinstance(self, class_mixin.Class) and self.is_dynamic dyn_cls = isinstance(self.cls, class_mixin.Class) and self.cls.is_dynamic self._maybe_missing_members = bool(dyn_self or dyn_cls) return self._maybe_missing_members @maybe_missing_members.setter def maybe_missing_members(self, v: bool) -> None: self._maybe_missing_members = v def has_instance_type_parameter(self, name: str) -> bool: """Check if the key is in `instance_type_parameters`.""" name = abstract_utils.full_type_name(self, name) return name in self.instance_type_parameters def get_instance_type_parameter( self, name: str, node: "cfg.CFGNode | None" = None ) -> "cfg.Variable": name = abstract_utils.full_type_name(self, name) param = self.instance_type_parameters.get(name) if not param: log.info("Creating new empty type param %s", name) if node is None: node = self.ctx.root_node param = self.ctx.program.NewVariable([], [], node) self.instance_type_parameters[name] = param return param def merge_instance_type_parameter( self, node: "cfg.CFGNode|None", name: str, value: "cfg.Variable" ) -> None: """Set the value of a type parameter. This will always add to the type parameter unlike set_attribute which will replace value from the same basic block. This is because type parameters may be affected by a side effect so we need to collect all the information regardless of multiple assignments in one basic block. Args: node: Optionally, the current CFG node. name: The name of the type parameter. value: The value that is being used for this type parameter as a Variable. """ name = abstract_utils.full_type_name(self, name) log.info("Modifying type param %s", name) if name in self.instance_type_parameters: self.instance_type_parameters[name].PasteVariable(value, node) else: self.instance_type_parameters[name] = value def _call_helper( self, node: "cfg.CFGNode", obj, binding: "cfg.Binding", args: function.Args, ) -> "tuple[cfg.CFGNode, cfg.Variable]": obj_binding = binding if obj == binding.data else obj.to_binding(node) node, var = self.ctx.attribute_handler.get_attribute( node, obj, "__call__", obj_binding ) if var is not None and var.bindings: return function.call_function(self.ctx, node, var, args, allow_never=True) else: raise error_types.NotCallable(self) def call( self, node: "cfg.CFGNode", func: "cfg.Binding", args: function.Args, alias_map: datatypes.UnionFind | None = None, ) -> "tuple[cfg.CFGNode, cfg.Variable]": return self._call_helper(node, self, func, args) def argcount(self, node: "cfg.CFGNode") -> int: node, var = self.ctx.attribute_handler.get_attribute( node, self, "__call__", self.to_binding(node) ) if var and var.bindings: return min(v.argcount(node) for v in var.data) else: # It doesn't matter what we return here, since any attempt to call this # value will lead to a not-callable error anyways. return 0 def __repr__(self) -> str: return f"<{self.name} [{self.cls!r}]>" def _get_class(self): return self.ctx.convert.unsolvable @property def cls(self): if not self.ctx.converter_minimally_initialized: return self.ctx.convert.unsolvable if not self._cls: self._cls = self.ctx.convert.unsolvable # prevent infinite recursion self._cls = self._get_class() return self._cls @cls.setter def cls(self, cls): self._cls = cls def set_class( self, node: "cfg.CFGNode", var: "cfg.Variable" ) -> "cfg.CFGNode": """Set the __class__ of an instance, for code that does "x.__class__ = y.""" # Simplification: Setting __class__ is done rarely, and supporting this # action would complicate pytype considerably by forcing us to track the # class in a variable, so we instead fall back to Any. try: new_cls = abstract_utils.get_atomic_value(var) except abstract_utils.ConversionError: self.cls = self.ctx.convert.unsolvable else: if self.cls != new_cls: self.cls = self.ctx.convert.unsolvable return node def update_caches(self, force: bool = False) -> None: cur_changestamps = self._get_changestamps() if self._cached_changestamps == cur_changestamps and not force: return self._fullhash = None self._type_key = None self._cached_changestamps = cur_changestamps def get_fullhash(self, seen: set[int] | None = None) -> int: self.update_caches() if not self._fullhash: if seen is None: seen = set() elif id(self) in seen: return self.get_default_fullhash() seen.add(id(self)) components = [type(self), self.cls.get_fullhash(seen), self.full_name] for d in (self.members, self._instance_type_parameters): components.append( abstract_utils.get_dict_fullhash_component(d, seen=seen) ) self._fullhash = hash(tuple(components)) return self._fullhash def get_type_key( self, seen: set[_base.BaseValue] | None = None ) -> "frozenset[_base.BaseValue | _typing.LateAnnotation | tuple[str, frozenset]] | type[_base.BaseValue]": self.update_caches() if not self._type_key: if seen is None: seen = set() elif self in seen: return self.get_default_type_key() seen.add(self) key = {self.cls} for name, var in self.instance_type_parameters.items(): subkey = frozenset(value.get_type_key(seen) for value in var.data) key.add((name, subkey)) self._type_key = frozenset(key) return self._type_key def _unique_parameters(self) -> "list[cfg.Variable]": parameters = super()._unique_parameters() parameters.extend(self.instance_type_parameters.values()) return parameters def instantiate(self, node: "cfg.CFGNode", container=None) -> "cfg.Variable": return Instance(self, self.ctx, container).to_variable(node)
SimpleValue
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/communicator_objects/unity_to_external_pb2_grpc.py
{ "start": 294, "end": 929 }
class ____(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Exchange = channel.unary_unary( '/communicator_objects.UnityToExternalProto/Exchange', request_serializer=mlagents__envs_dot_communicator__objects_dot_unity__message__pb2.UnityMessageProto.SerializeToString, response_deserializer=mlagents__envs_dot_communicator__objects_dot_unity__message__pb2.UnityMessageProto.FromString, )
UnityToExternalProtoStub
python
streamlit__streamlit
lib/tests/streamlit/external/pydantic_integration.py
{ "start": 683, "end": 2071 }
class ____(unittest.TestCase): def pydantic_model_definition(self): from pydantic import ( # type: ignore[import-not-found] BaseModel, root_validator, validator, ) class UserModel(BaseModel): name: str username: str password1: str password2: str @validator("name") def name_must_contain_space(cls, v): if " " not in v: raise ValueError("must contain a space") return v.title() @root_validator() def passwords_should_match(cls, values): if values["password1"] != values["password2"]: raise ValueError("passwords do not match") return values UserModel( name="John Doe", username="johndoe", password1="abcd", password2="abcd", ) def test_pydantic_v1_validator(self): """Test that the pydantic model with a v1 validator can be redefined without exception. This only works in pydantic >= 2.0.0. https://github.com/streamlit/streamlit/issues/3218 """ # Check that the model redefined without exception. self.pydantic_model_definition() self.pydantic_model_definition()
PydanticIntegrationTest
python
getsentry__sentry
tests/sentry/monitors/test_models.py
{ "start": 16405, "end": 19685 }
class ____(TestCase): """Test the is_muted computed property for Monitor.""" def test_is_muted_all_environments_muted(self): """Test that monitor.is_muted returns True when all environments are muted.""" monitor = self.create_monitor() env1 = self.create_environment(name="production") env2 = self.create_environment(name="staging") # Create two muted environments self.create_monitor_environment( monitor=monitor, environment_id=env1.id, is_muted=True, ) self.create_monitor_environment( monitor=monitor, environment_id=env2.id, is_muted=True, ) # Verify monitor.is_muted is True assert is_monitor_muted(monitor) is True def test_is_muted_some_environments_unmuted(self): """Test that monitor.is_muted returns False when any environment is unmuted.""" monitor = self.create_monitor() env1 = self.create_environment(name="production") env2 = self.create_environment(name="staging") # Create one muted and one unmuted environment self.create_monitor_environment( monitor=monitor, environment_id=env1.id, is_muted=True, ) self.create_monitor_environment( monitor=monitor, environment_id=env2.id, is_muted=False, ) # Verify monitor.is_muted is False assert is_monitor_muted(monitor) is False def test_is_muted_all_environments_unmuted(self): """Test that monitor.is_muted returns False when all environments are unmuted.""" monitor = self.create_monitor() env1 = self.create_environment(name="production") env2 = self.create_environment(name="staging") # Create two unmuted environments self.create_monitor_environment( monitor=monitor, environment_id=env1.id, is_muted=False, ) self.create_monitor_environment( monitor=monitor, environment_id=env2.id, is_muted=False, ) # Verify monitor.is_muted is False assert is_monitor_muted(monitor) is False def test_is_muted_no_environments(self): """Test that monitor.is_muted returns False when there are no environments.""" monitor = self.create_monitor() assert is_monitor_muted(monitor) is False def test_is_muted_single_environment(self): """Test is_muted works correctly with a single environment.""" # Test with muted environment monitor = self.create_monitor() env = self.create_environment(name="production") self.create_monitor_environment( monitor=monitor, environment_id=env.id, is_muted=True, ) assert is_monitor_muted(monitor) is True # Test with unmuted environment monitor2 = self.create_monitor() env2 = self.create_environment(name="staging") self.create_monitor_environment( monitor=monitor2, environment_id=env2.id, is_muted=False, ) assert is_monitor_muted(monitor2) is False
MonitorIsMutedPropertyTestCase
python
doocs__leetcode
solution/2800-2899/2851.String Transformation/Solution.py
{ "start": 1505, "end": 3413 }
class ____: M: int = 1000000007 def add(self, x: int, y: int) -> int: x += y if x >= self.M: x -= self.M return x def mul(self, x: int, y: int) -> int: return int(x * y % self.M) def getZ(self, s: str) -> List[int]: n = len(s) z = [0] * n left = right = 0 for i in range(1, n): if i <= right and z[i - left] <= right - i: z[i] = z[i - left] else: z_i = max(0, right - i + 1) while i + z_i < n and s[i + z_i] == s[z_i]: z_i += 1 z[i] = z_i if i + z[i] - 1 > right: left = i right = i + z[i] - 1 return z def matrixMultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: m = len(a) n = len(a[0]) p = len(b[0]) r = [[0] * p for _ in range(m)] for i in range(m): for j in range(p): for k in range(n): r[i][j] = self.add(r[i][j], self.mul(a[i][k], b[k][j])) return r def matrixPower(self, a: List[List[int]], y: int) -> List[List[int]]: n = len(a) r = [[0] * n for _ in range(n)] for i in range(n): r[i][i] = 1 x = [a[i][:] for i in range(n)] while y > 0: if y & 1: r = self.matrixMultiply(r, x) x = self.matrixMultiply(x, x) y >>= 1 return r def numberOfWays(self, s: str, t: str, k: int) -> int: n = len(s) dp = self.matrixPower([[0, 1], [n - 1, n - 2]], k)[0] s += t + t z = self.getZ(s) m = n + n result = 0 for i in range(n, m): if z[i] >= n: result = self.add(result, dp[0] if i - n == 0 else dp[1]) return result
Solution