uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43fe8a514c7a3df2e8e18e57 | train | class | class Contributor(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=10)
address = models.TextField()
commodities = models.TextField(verbose_name="What you can contribute.... | class Contributor(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=10)
address = models.TextField()
commodities = models.TextField(verbose_name="What you can contribute. ( സംഭാവന ചെയ്യാന് ഉദ്ദേശിക്കുന്... | max_length=500,
verbose_name="Preferred Location to Volunteer"
)
is_spoc = models.BooleanField(default=False, verbose_name="Is point of contact")
joined = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Contributor(models.Model):
| 64 | 64 | 143 | 5 | 58 | yashness/rescuekerala | mainapp/models.py | Python | Contributor | Contributor | 159 | 175 | 159 | 159 | 80d806465fe120612951c4f53e05af88a3a23945 | bigcode/the-stack | train |
c7ec45f4b85cf462f81f5c2f | train | class | class NGO(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
)
organisation = models.CharField(max_length=250, verbose_name="Name of Organization (സംഘടനയുടെ പേര്)")
organisation_type = models.CharField(max_length=250, verbose_name="Type of Organization")
... | class NGO(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
)
organisation = models.CharField(max_length=250, verbose_name="Name of Organization (സംഘടനയുടെ പേര്)")
organisation_type = models.CharField(max_length=250, verbose_name="Type of Organization")
organisation_address = ... | choices = vol_categories,
verbose_name = "Area of volunteering"
)
is_spoc = models.BooleanField(default=False, verbose_name="Is point of contact")
joined = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class NGO(models.Model):
| 64 | 64 | 211 | 5 | 58 | yashness/rescuekerala | mainapp/models.py | Python | NGO | NGO | 134 | 156 | 134 | 134 | a79cf0775bdb9d1ad58ea3f6e0ec823088892ccb | bigcode/the-stack | train |
86c3101e72cb18ca01ade270 | train | class | class DistrictNeed(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
)
needs = models.TextField(verbose_name="Items required")
cnandpts = models.TextField(verbose_name="Contacts and collection points") #contacts and collection points
def __str__(self)... | class DistrictNeed(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
)
needs = models.TextField(verbose_name="Items required")
cnandpts = models.TextField(verbose_name="Contacts and collection points") #contacts and collection points
def __str__(self):
return self.get_district... | districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=11)
email = models.CharField(max_length=100)
def __str__(self):
return self.name + ' ' + self.get_district_display()
class DistrictNeed(models.Model):
| 64 | 64 | 76 | 6 | 58 | yashness/rescuekerala | mainapp/models.py | Python | DistrictNeed | DistrictNeed | 190 | 199 | 190 | 190 | dca2a5948114ce54153145bcd4085353cffe6979 | bigcode/the-stack | train |
2214f702cbc786349205e212 | train | class | class Volunteer(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=10)
organisation = models.CharField(max_length=250, verbose_name="Organization (സംഘടന) / Institution")
a... | class Volunteer(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=10)
organisation = models.CharField(max_length=250, verbose_name="Organization (സംഘടന) / Institution")
address = models.TextField()
... | (self.detailkit_util)
if(len(self.needothers.strip()) != 0):
out += "\nOther Needs :\n {}".format(self.needothers)
return out
def __str__(self):
return self.get_district_display() + ' ' + self.location
class Volunteer(models.Model):
| 64 | 64 | 153 | 5 | 58 | yashness/rescuekerala | mainapp/models.py | Python | Volunteer | Volunteer | 113 | 131 | 113 | 113 | 0c5d58d7cc78fa0e6c6a466a04a41b3896f0039d | bigcode/the-stack | train |
67dde21229f6c1963bc8486f | train | class | class Request(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
verbose_name='Districts - ജില്ല'
)
location = models.CharField(max_length=500,verbose_name='Location - സ്ഥലം')
requestee = models.CharField(max_length=100,verbose_name='Requestee - അപേ... | class Request(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
verbose_name='Districts - ജില്ല'
)
location = models.CharField(max_length=500,verbose_name='Location - സ്ഥലം')
requestee = models.CharField(max_length=100,verbose_name='Requestee - അപേക്ഷകന്റെ പേര്')
requeste... | ('ptm','Pathanamthitta - പത്തനംതിട്ട'),
('tvm','Thiruvananthapuram - തിരുവനന്തപുരം'),
('tcr','Thrissur - തൃശ്ശൂർ'),
('wnd','Wayanad - വയനാട്'),
)
status_types =(
('new', 'New'),
('pro', 'In progess'),
('sup', 'Supplied'),
)
contrib_status_types =(
('new', 'New'),
('ful', 'Fullfille... | 255 | 255 | 852 | 5 | 250 | yashness/rescuekerala | mainapp/models.py | Python | Request | Request | 54 | 111 | 54 | 54 | cdc986a604c5a9260e1419e8a5dd91bd9757b125 | bigcode/the-stack | train |
f81560c1316eeea016f96269 | train | class | class DistrictManager(models.Model):
district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=11)
email = models.CharField(max_length=100)
def __str__(self):
return self.name + ' ' + ... | class DistrictManager(models.Model):
| district = models.CharField(
max_length = 15,
choices = districts,
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=11)
email = models.CharField(max_length=100)
def __str__(self):
return self.name + ' ' + self.get_district_display()
| Eg: Shirts, torches etc ")
status = models.CharField(
max_length = 10,
choices = contrib_status_types,
default = 'new'
)
def __str__(self):
return self.name + ' ' + self.get_district_display()
class DistrictManager(models.Model):
| 64 | 64 | 81 | 6 | 58 | yashness/rescuekerala | mainapp/models.py | Python | DistrictManager | DistrictManager | 178 | 188 | 178 | 178 | 50c0fc5793867df505a8e07fe0a3ac61516b83ec | bigcode/the-stack | train |
de920553a7647e2cc69959a9 | train | class | class RescueCamp(models.Model):
verbose_name = 'Relief Camp'
name = models.CharField(max_length=50,verbose_name="Camp Name - ക്യാമ്പിന്റെ പേര്")
location = models.TextField(verbose_name="Address - അഡ്രസ്",blank=True,null=True)
district = models.CharField(
max_length=15,
choices=districts... | class RescueCamp(models.Model):
| verbose_name = 'Relief Camp'
name = models.CharField(max_length=50,verbose_name="Camp Name - ക്യാമ്പിന്റെ പേര്")
location = models.TextField(verbose_name="Address - അഡ്രസ്",blank=True,null=True)
district = models.CharField(
max_length=15,
choices=districts
)
taluk = models.CharFi... | 15,
choices = districts,
)
needs = models.TextField(verbose_name="Items required")
cnandpts = models.TextField(verbose_name="Contacts and collection points") #contacts and collection points
def __str__(self):
return self.get_district_display()
class DistrictCollection(models.Model):
... | 110 | 110 | 368 | 6 | 104 | yashness/rescuekerala | mainapp/models.py | Python | RescueCamp | RescueCamp | 211 | 233 | 211 | 211 | 28a3ed78b12078578ac869980d4d7f0c6fa1c803 | bigcode/the-stack | train |
50b5dfb562b7b38081093da1 | train | class | class DistrictCollection(models.Model):
district = models.CharField(
max_length=15,
choices=districts
)
collection = models.TextField(
verbose_name="Details of collected items"
)
| class DistrictCollection(models.Model):
| district = models.CharField(
max_length=15,
choices=districts
)
collection = models.TextField(
verbose_name="Details of collected items"
)
| 15,
choices = districts,
)
needs = models.TextField(verbose_name="Items required")
cnandpts = models.TextField(verbose_name="Contacts and collection points") #contacts and collection points
def __str__(self):
return self.get_district_display()
class DistrictCollection(models.Model):
| 64 | 64 | 45 | 6 | 58 | yashness/rescuekerala | mainapp/models.py | Python | DistrictCollection | DistrictCollection | 202 | 209 | 202 | 202 | e7d7b3e7bf93f97e3baf7eceffb77fd9d991c53a | bigcode/the-stack | train |
b7bd9420758a2c3630cc14f2 | train | class | class Person(models.Model):
name = models.CharField(max_length=30,blank=False,null=False,verbose_name="Name - പേര്")
phone = models.CharField(max_length=11,null=True,blank=True,verbose_name='Mobile - മൊബൈൽ')
age = models.IntegerField(null=True,blank=True,verbose_name="Age - പ്രായം")
gender = models.Inte... | class Person(models.Model):
| name = models.CharField(max_length=30,blank=False,null=False,verbose_name="Name - പേര്")
phone = models.CharField(max_length=11,null=True,blank=True,verbose_name='Mobile - മൊബൈൽ')
age = models.IntegerField(null=True,blank=True,verbose_name="Age - പ്രായം")
gender = models.IntegerField(
choices = ... | സാനിറ്ററി")
medical_req = models.TextField(blank=True,null=True,verbose_name="Medical - മെഡിക്കൽ")
other_req = models.TextField(blank=True,null=True,verbose_name="Other - മറ്റുള്ളവ")
class Meta:
verbose_name = 'Relief Camp'
def __str__(self):
return self.name
class Person(models.Model):... | 76 | 76 | 254 | 5 | 70 | yashness/rescuekerala | mainapp/models.py | Python | Person | Person | 236 | 256 | 236 | 236 | 778dcd51d04d5dbd9db3aa6481a5d6242fb14946 | bigcode/the-stack | train |
aae69d7b7106907503ca17fd | train | class | class TestUpdateWrapper(unittest.TestCase):
def check_wrapper(self, wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
# Check attributes were assigned
for name in assigned:
self.assertTrue(getattr(wr... | class TestUpdateWrapper(unittest.TestCase):
| def check_wrapper(self, wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
# Check attributes were assigned
for name in assigned:
self.assertTrue(getattr(wrapper, name) == getattr(wrapped, name))
... | 8, 'd': 9}))
def test_overriding_keywords(self):
self.assertEqual(self.a.keywords(a=3), ((self.a,), {'a': 3}))
self.assertEqual(self.A.keywords(self.a, a=3), ((self.a,), {'a': 3}))
def test_invalid_args(self):
with self.assertRaises(TypeError):
class B(object):
... | 256 | 256 | 930 | 8 | 248 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestUpdateWrapper | TestUpdateWrapper | 518 | 629 | 518 | 519 | 46c9812870c854afa9c1cdebd654a18849a15151 | bigcode/the-stack | train |
9f8970ec42bf5c2f009315b0 | train | class | class TestReduce(unittest.TestCase):
func = functools.reduce
def test_reduce(self):
class Squares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self):
return len(self.sofar)
def __getitem__(self... | class TestReduce(unittest.TestCase):
| func = functools.reduce
def test_reduce(self):
class Squares:
def __init__(self, max):
self.max = max
self.sofar = []
def __len__(self):
return len(self.sofar)
def __getitem__(self, i):
if not 0 <= i <... | self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertNotEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.__doc__, None)
self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():... | 240 | 240 | 801 | 7 | 233 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestReduce | TestReduce | 694 | 772 | 694 | 694 | 143a013eb19b0f1048c844f3cdc6b807880d4a59 | bigcode/the-stack | train |
3ffeca7642df5ffd1ea2ba6a | train | function | def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
| def signature(part):
| """ return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
| python module, whereas on CPython it is C (and so not really
# re-importable)
decimal = support.import_fresh_module('decimal', fresh=['_decimal'])
def capture(*args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
def signature(part):
| 64 | 64 | 31 | 4 | 59 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | signature | signature | 35 | 37 | 35 | 35 | add7d5e45c3c5f24ee37393022f4b0a44ae72569 | bigcode/the-stack | train |
6c1dc000fa8de707760ee999 | train | class | class TestLRUC(TestLRU, unittest.TestCase):
module = c_functools
cached_func = c_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
| class TestLRUC(TestLRU, unittest.TestCase):
| module = c_functools
cached_func = c_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
| ru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
class TestLRUC(TestLRU, unittest.TestCase):
| 64 | 64 | 84 | 12 | 51 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestLRUC | TestLRUC | 1,491 | 1,502 | 1,491 | 1,491 | 9829aa8208bda36b3b7e1487abc86f8882221696 | bigcode/the-stack | train |
e6696c81d84f840f5ec7af29 | train | class | class TestLRUPy(TestLRU, unittest.TestCase):
module = py_functools
cached_func = py_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
| class TestLRUPy(TestLRU, unittest.TestCase):
| module = py_functools
cached_func = py_cached_func,
@module.lru_cache()
def cached_meth(self, x, y):
return 3 * x + y
@staticmethod
@module.lru_cache()
def cached_staticmeth(x, y):
return 3 * x + y
| py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
@c_functools.lru_cache()
def c_cached_func(x, y):
return 3 * x + y
class TestLRUPy(TestLRU, unittest.TestCase):
| 64 | 64 | 85 | 13 | 50 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestLRUPy | TestLRUPy | 1,477 | 1,488 | 1,477 | 1,477 | 4b384c39d50331f17867874e0cd2b544edb68637 | bigcode/the-stack | train |
dcd53a20e16270500284ee18 | train | class | class TestSingleDispatch(unittest.TestCase):
def test_simple_overloads(self):
@functools.singledispatch
def g(obj):
return "base"
def g_int(i):
return "integer"
g.register(int, g_int)
self.assertEqual(g("str"), "base")
self.assertEqual(g(1), "i... | class TestSingleDispatch(unittest.TestCase):
| def test_simple_overloads(self):
@functools.singledispatch
def g(obj):
return "base"
def g_int(i):
return "integer"
g.register(int, g_int)
self.assertEqual(g("str"), "base")
self.assertEqual(g(1), "integer")
self.assertEqual(g([1,2,3]),... | funcs:
with self.subTest(func=f):
f_copy = copy.deepcopy(f)
self.assertIs(f_copy, f)
@py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
@c_functools.lru_cache()
def c_cached_func(x, y):
return 3 * x + y
class TestLRUPy(TestLRU, unittest.TestCas... | 256 | 256 | 4,649 | 8 | 247 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestSingleDispatch | TestSingleDispatch | 1,505 | 1,995 | 1,505 | 1,505 | 82872c9df24e6923bbac59b33b8e1f52ead84d98 | bigcode/the-stack | train |
d12bd1335d46c295de10ea24 | train | class | @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialC(TestPartial, unittest.TestCase):
if c_functools:
partial = c_functools.partial
def test_attributes_unwritable(self):
# attributes should not be writable
p = self.partial(capture, 1, 2, a=10, b=20)
... | @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialC(TestPartial, unittest.TestCase):
| if c_functools:
partial = c_functools.partial
def test_attributes_unwritable(self):
# attributes should not be writable
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertRaises(AttributeError, setattr, p, 'func', map)
self.assertRaises(AttributeError, setattr, p, 'a... | Equal(f.func, p.func)
f = None
support.gc_collect()
self.assertRaises(ReferenceError, getattr, p, 'func')
def test_with_bound_and_unbound_methods(self):
data = list(map(str, range(10)))
join = self.partial(str.join, '')
self.assertEqual(join(data), '0123456789')
... | 256 | 256 | 1,997 | 31 | 225 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestPartialC | TestPartialC | 178 | 383 | 178 | 179 | ba89c161660b3936e6da863eff86ef272b45ab05 | bigcode/the-stack | train |
71a2a0d9cde0f139688094ba | train | class | class TestWraps(TestUpdateWrapper):
def _default_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is still a bald faced lie"
@functools.wraps(f)
def wrapper():
pass
return wrappe... | class TestWraps(TestUpdateWrapper):
| def _default_update(self):
def f():
"""This is a test"""
pass
f.attr = 'This is also a test'
f.__wrapped__ = "This is still a bald faced lie"
@functools.wraps(f)
def wrapper():
pass
return wrapper, f
def test_default_update(sel... | _wrapper(wrapper, f, assign, update)
wrapper.dict_attr = 1
with self.assertRaises(AttributeError):
functools.update_wrapper(wrapper, f, assign, update)
@support.requires_docstrings
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and ab... | 143 | 144 | 482 | 8 | 135 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestWraps | TestWraps | 632 | 691 | 632 | 633 | e540bb39f0b36b7bff56f07204a89c43808432e7 | bigcode/the-stack | train |
4f218b0e78d3c44cf70d3cbd | train | class | class TestTotalOrdering(unittest.TestCase):
def test_total_ordering_lt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self... | class TestTotalOrdering(unittest.TestCase):
| def test_total_ordering_lt(self):
@functools.total_ordering
class A:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value =... | )
return (x > y) - (x < y)
values = [5, '3', 7, 2, '0', '1', 4, '10', 1]
values = sorted(values, key=self.cmp_to_key(mycmp))
self.assertEqual([int(value) for value in values],
[0, 1, 1, 2, 3, 4, 5, 7, 10])
def test_hash(self):
def mycmp(x, y):
... | 256 | 256 | 1,753 | 8 | 248 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestTotalOrdering | TestTotalOrdering | 868 | 1,069 | 868 | 869 | 6012980896a9856b3821806169644e679a16f4b0 | bigcode/the-stack | train |
ec6e1375b9f4346a4300ac38 | train | class | class TestPartialMethod(unittest.TestCase):
class A(object):
nothing = functools.partialmethod(capture)
positional = functools.partialmethod(capture, 1)
keywords = functools.partialmethod(capture, a=2)
both = functools.partialmethod(capture, 3, b=4)
nested = functools.parti... | class TestPartialMethod(unittest.TestCase):
| class A(object):
nothing = functools.partialmethod(capture)
positional = functools.partialmethod(capture, 1)
keywords = functools.partialmethod(capture, a=2)
both = functools.partialmethod(capture, 3, b=4)
nested = functools.partialmethod(positional, 5)
over_partial... | _copy)
finally:
f_copy.__setstate__((capture, (), {}, {}))
finally:
f.__setstate__((capture, (), {}, {}))
# Issue 6083: Reference counting bug
def test_setstate_refcount(self):
class BadSequence:
def __len__(self):
retu... | 256 | 256 | 1,506 | 8 | 247 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestPartialMethod | TestPartialMethod | 404 | 515 | 404 | 405 | 500d4e83f2c0af5051c97f55eb5e8c4e7be4b4ce | bigcode/the-stack | train |
c1fc158b3e9a1ac9fa10b510 | train | function | def capture(*args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
| def capture(*args, **kw):
| """capture all positional and keyword arguments"""
return args, kw
| this creates confusion for pickle because on pypy, _functools is a
# pure python module, whereas on CPython it is C (and so not really
# re-importable)
decimal = support.import_fresh_module('decimal', fresh=['_decimal'])
def capture(*args, **kw):
| 63 | 64 | 23 | 8 | 55 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | capture | capture | 30 | 32 | 30 | 30 | 6d0f2251a27d25a3db23667fcf589ae192f7b89f | bigcode/the-stack | train |
09ec7fff49a52a31beda3990 | train | class | class BadTuple(tuple):
def __add__(self, other):
return list(self) + list(other)
| class BadTuple(tuple):
| def __add__(self, other):
return list(self) + list(other)
| args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
class MyTuple(tuple):
pass
class BadTuple(tuple):
| 64 | 64 | 23 | 5 | 58 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | BadTuple | BadTuple | 42 | 44 | 42 | 42 | 0230614281960a3ee6915e99dc4f6104fc69a932 | bigcode/the-stack | train |
cbe45c1dbd6d6ba60c07f395 | train | class | @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
if c_functools:
cmp_to_key = c_functools.cmp_to_key
| @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
| if c_functools:
cmp_to_key = c_functools.cmp_to_key
| k = key(10)
self.assertRaises(TypeError, hash, k)
self.assertNotIsInstance(k, collections.Hashable)
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
| 64 | 64 | 56 | 35 | 29 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestCmpToKeyC | TestCmpToKeyC | 858 | 861 | 858 | 859 | ccfb88b5e49730533a420466cf825620aed8df3b | bigcode/the-stack | train |
6137602a7a4f49e3e6243d71 | train | class | class TestPartial:
def test_basic_examples(self):
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertTrue(callable(p))
self.assertEqual(p(3, 4, b=30, c=40),
((1, 2, 3, 4), dict(a=10, b=30, c=40)))
p = self.partial(map, lambda x: x*10)
self.assert... | class TestPartial:
| def test_basic_examples(self):
p = self.partial(capture, 1, 2, a=10, b=20)
self.assertTrue(callable(p))
self.assertEqual(p(3, 4, b=30, c=40),
((1, 2, 3, 4), dict(a=10, b=30, c=40)))
p = self.partial(map, lambda x: x*10)
self.assertEqual(list(p([1,2,3,... | pickle
from random import choice
import sys
from test import support
import unittest
from weakref import proxy
try:
import threading
except ImportError:
threading = None
import functools
py_functools = support.import_fresh_module('functools', blocked=['_functools'])
c_functools = functools
# pypy: was:
# c... | 256 | 256 | 1,265 | 4 | 251 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestPartial | TestPartial | 50 | 175 | 50 | 51 | 55bef28df5b68298fdfa99579d4a0c8637d2ea08 | bigcode/the-stack | train |
17934df783ad14386f7d0aa8 | train | class | class MyDict(dict):
pass
| class MyDict(dict):
| pass
| ):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
class MyTuple(tuple):
pass
class BadTuple(tuple):
def __add__(self, other):
return list(self) + list(other)
class MyDict(dict):
| 64 | 64 | 8 | 5 | 59 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | MyDict | MyDict | 46 | 47 | 46 | 46 | f48e269dbbf0d99df26f07864156f53a4046e6dc | bigcode/the-stack | train |
03179eb868d27f33e7c821bd | train | function | @c_functools.lru_cache()
def c_cached_func(x, y):
return 3 * x + y
| @c_functools.lru_cache()
def c_cached_func(x, y):
| return 3 * x + y
| Test(func=f):
f_copy = copy.deepcopy(f)
self.assertIs(f_copy, f)
@py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
@c_functools.lru_cache()
def c_cached_func(x, y):
| 64 | 64 | 26 | 17 | 46 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | c_cached_func | c_cached_func | 1,472 | 1,474 | 1,472 | 1,473 | 553bc57d5df23844108064add1d2898736c3df5d | bigcode/the-stack | train |
d36bf894139a7d5ef96d2d5f | train | class | class TestLRU:
def test_lru(self):
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=20)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(maxsize, 20)
self.assertEqual(currsize, 0)
self.assertEqual(hits, 0)
... | class TestLRU:
| def test_lru(self):
def orig(x, y):
return 3 * x + y
f = self.module.lru_cache(maxsize=20)(orig)
hits, misses, maxsize, currsize = f.cache_info()
self.assertEqual(maxsize, 20)
self.assertEqual(currsize, 0)
self.assertEqual(hits, 0)
self.assertEqual... | LessThanEqualTo(7)
with self.subTest("GE when equal"):
a = ComparatorNotImplemented(8)
b = ComparatorNotImplemented(8)
self.assertEqual(a, b)
with self.assertRaises(TypeError):
a >= b
with self.subTest("LE when equal"):
a = Co... | 256 | 256 | 3,766 | 5 | 250 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestLRU | TestLRU | 1,081 | 1,465 | 1,081 | 1,082 | 67f59fc1715601ed59441db774ad245b7d9903c9 | bigcode/the-stack | train |
13bbf59328b91307efd17ca9 | train | class | class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
cmp_to_key = staticmethod(py_functools.cmp_to_key)
| class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
| cmp_to_key = staticmethod(py_functools.cmp_to_key)
| unctools, 'requires the C _functools module')
class TestCmpToKeyC(TestCmpToKey, unittest.TestCase):
if c_functools:
cmp_to_key = c_functools.cmp_to_key
class TestCmpToKeyPy(TestCmpToKey, unittest.TestCase):
| 64 | 64 | 31 | 15 | 48 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestCmpToKeyPy | TestCmpToKeyPy | 864 | 865 | 864 | 864 | da10631771e97fb9744aa8b7d8497671b4f9850d | bigcode/the-stack | train |
353e3ff5d88982f24e3a330a | train | class | class MyTuple(tuple):
pass
| class MyTuple(tuple):
| pass
| =['_decimal'])
def capture(*args, **kw):
"""capture all positional and keyword arguments"""
return args, kw
def signature(part):
""" return the signature of a partial object """
return (part.func, part.args, part.keywords, part.__dict__)
class MyTuple(tuple):
| 64 | 64 | 8 | 5 | 59 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | MyTuple | MyTuple | 39 | 40 | 39 | 39 | 85ca9b80f1db061a2c43e310a0b9e0fb91bda3be | bigcode/the-stack | train |
4f2841d3b5d18eefae984842 | train | function | @py_functools.lru_cache()
def py_cached_func(x, y):
return 3 * x + y
| @py_functools.lru_cache()
def py_cached_func(x, y):
| return 3 * x + y
| cls.cached_staticmeth,
self.module.lru_cache(2)(part))
for f in funcs:
with self.subTest(func=f):
f_copy = copy.deepcopy(f)
self.assertIs(f_copy, f)
@py_functools.lru_cache()
def py_cached_func(x, y):
| 64 | 64 | 26 | 17 | 47 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | py_cached_func | py_cached_func | 1,468 | 1,470 | 1,468 | 1,469 | d3b31553ebe6580da8bec162b14adc6751140bdc | bigcode/the-stack | train |
e36c6ab8397181fce072db9e | train | class | @functools.total_ordering
class Orderable_LT:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
| @functools.total_ordering
class Orderable_LT:
| def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
| '__le__', '__ge__':
with self.subTest(method=name, proto=proto):
method = getattr(Orderable_LT, name)
method_copy = pickle.loads(pickle.dumps(method, proto))
self.assertIs(method_copy, method)
@functools.total_ordering
class Orderable_LT:
| 64 | 64 | 62 | 13 | 51 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | Orderable_LT | Orderable_LT | 1,071 | 1,078 | 1,071 | 1,072 | b871ff39c67458a0c6392763052201b7226c30ce | bigcode/the-stack | train |
155ce546b9e39306be7b0134 | train | class | class TestCmpToKey:
def test_cmp_to_key(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(cmp1)
self.assertEqual(key(3), key(3))
self.assertGreater(key(3), key(1))
self.assertGreaterEqual(key(3), key(3))
def cmp2(x, y):
re... | class TestCmpToKey:
| def test_cmp_to_key(self):
def cmp1(x, y):
return (x > y) - (x < y)
key = self.cmp_to_key(cmp1)
self.assertEqual(key(3), key(3))
self.assertGreater(key(3), key(1))
self.assertGreaterEqual(key(3), key(3))
def cmp2(x, y):
return int(x) - int(y)
... | .assertRaises(ValueError, self.func, 42, BadSeq())
# Test reduce()'s use of iterators.
def test_iterator_usage(self):
class SequenceClass:
def __init__(self, n):
self.n = n
def __getitem__(self, i):
if 0 <= i < self.n:
return i... | 238 | 239 | 798 | 6 | 232 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestCmpToKey | TestCmpToKey | 775 | 855 | 775 | 776 | 54f5e1e40cb4d46426081e0f09548c7363010151 | bigcode/the-stack | train |
0ffe4a96ad40d2824978cddb | train | class | class TestPartialPy(TestPartial, unittest.TestCase):
partial = staticmethod(py_functools.partial)
| class TestPartialPy(TestPartial, unittest.TestCase):
| partial = staticmethod(py_functools.partial)
| == 1:
return tuple(range(1000000))
elif key in (2, 3):
return {}
raise IndexError
f = self.partial(object)
self.assertRaises(TypeError, f.__setstate__, BadSequence())
class TestPartialPy(TestPartial, unittest.TestCase):
| 64 | 64 | 22 | 11 | 53 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestPartialPy | TestPartialPy | 386 | 387 | 386 | 386 | d6718e48d843fe4d89a518237e219281cceeaf26 | bigcode/the-stack | train |
f94d5dfc65136f298db9cd23 | train | class | @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialCSubclass(TestPartialC):
if c_functools:
partial = PartialSubclass
# partial subclasses are not optimized for nested calls
test_nested_optimization = None
| @unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialCSubclass(TestPartialC):
| if c_functools:
partial = PartialSubclass
# partial subclasses are not optimized for nested calls
test_nested_optimization = None
| , unittest.TestCase):
partial = staticmethod(py_functools.partial)
if c_functools:
class PartialSubclass(c_functools.partial):
pass
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestPartialCSubclass(TestPartialC):
| 64 | 64 | 61 | 29 | 34 | yxzoro/pypy | lib-python/3/test/test_functools.py | Python | TestPartialCSubclass | TestPartialCSubclass | 395 | 401 | 395 | 396 | 6ce6c1401854bc20b14cded8ff2e30bbd952cc97 | bigcode/the-stack | train |
24ae349a62ff4e87e2c795af | train | function | def main():
info('Prepare for CO2 analysis')
close(description='Jan Inlet')
open(description='Jan Ion Pump')
close(description='Microbone to Minibone')
open(description='Microbone to Turbo')
open(description='Microbone to Inlet Pipette')
close(description='Microbone to Getter NP-10C')
op... | def main():
| info('Prepare for CO2 analysis')
close(description='Jan Inlet')
open(description='Jan Ion Pump')
close(description='Microbone to Minibone')
open(description='Microbone to Turbo')
open(description='Microbone to Inlet Pipette')
close(description='Microbone to Getter NP-10C')
open(descripti... | '''
'''
def main():
| 5 | 64 | 118 | 3 | 2 | ASUPychron/pychron | docs/user_guide/operation/scripts/examples/argus/extraction/jan/test scripts/PrepareForCO2_NP10Analysis.py | Python | main | main | 4 | 16 | 4 | 4 | a535406a3378bb9b1c8484e4e42b114522b0e585 | bigcode/the-stack | train |
bf4cea79c3167d88c316d168 | train | class | class CalculateDBInstanceWeightRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Rds', '2014-08-15', 'CalculateDBInstanceWeight','rds')
def get_ResourceOwnerId(self):
return self.get_query_params().get('ResourceOwnerId')
def set_ResourceOwnerId(self,ResourceOwnerId):
self.add_query_p... | class CalculateDBInstanceWeightRequest(RpcRequest):
| def __init__(self):
RpcRequest.__init__(self, 'Rds', '2014-08-15', 'CalculateDBInstanceWeight','rds')
def get_ResourceOwnerId(self):
return self.get_query_params().get('ResourceOwnerId')
def set_ResourceOwnerId(self,ResourceOwnerId):
self.add_query_param('ResourceOwnerId',ResourceOwnerId)
def get_R... | law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request impo... | 80 | 80 | 267 | 10 | 69 | DataDog/aliyun-openapi-python-sdk | aliyun-python-sdk-rds/aliyunsdkrds/request/v20140815/CalculateDBInstanceWeightRequest.py | Python | CalculateDBInstanceWeightRequest | CalculateDBInstanceWeightRequest | 21 | 54 | 21 | 22 | 8dc2ad6fe80bc938520bcccbdff3caa9cfaa5de9 | bigcode/the-stack | train |
37458b5bf0de8476515ff178 | train | class | class ThreadsafeBoolean(object):
def __init__(self):
self._value = False
self._lock = threading.Lock()
@property
def val(self):
with self._lock:
return self._value
@val.setter
def val(self, value):
with self._lock:
self._value = value
| class ThreadsafeBoolean(object):
| def __init__(self):
self._value = False
self._lock = threading.Lock()
@property
def val(self):
with self._lock:
return self._value
@val.setter
def val(self, value):
with self._lock:
self._value = value
| predicate, max=100, msg="predicate"):
cnt = 0
while not predicate() and cnt < max:
sleep(0.01)
cnt += 1
if cnt == max:
self.fail("Test timed out waiting for " + msg)
class ThreadsafeBoolean(object):
| 64 | 64 | 74 | 6 | 58 | leolani/pepper | test/app_itest/test_resource.py | Python | ThreadsafeBoolean | ThreadsafeBoolean | 367 | 380 | 367 | 367 | 2bffa97bae42832f7a5fbe9412cb1a2d620aadf8 | bigcode/the-stack | train |
9220a17a3d0f7feed7a3cfae | train | class | class ResourceITest(unittest.TestCase):
def setUp(self):
setupTestComponents()
self.intention = TestIntention()
self.application = TestApplication(self.intention)
self.application._start()
sleep(1)
webrtc_buffer_size = self.intention.config_manager\
.get... | class ResourceITest(unittest.TestCase):
| def setUp(self):
setupTestComponents()
self.intention = TestIntention()
self.application = TestApplication(self.intention)
self.application._start()
sleep(1)
webrtc_buffer_size = self.intention.config_manager\
.get_config("pepper.framework.sensors.vad.we... | ="Talking"):
super(TalkingThread, self).__init__(name=name)
self._intention = intention
self.running = True
self.talking = False
self.talking_latch = threading.Event()
self.exit_latch = threading.Event()
def stop(self):
self.running = False
self.exit_... | 256 | 256 | 1,135 | 7 | 249 | leolani/pepper | test/app_itest/test_resource.py | Python | ResourceITest | ResourceITest | 236 | 364 | 236 | 236 | 8f8ef166cffdb381d640dcb673bca6d399967a74 | bigcode/the-stack | train |
3d4f646b82c0a864a7a0a58d | train | function | def setupTestComponents():
"""Workaround to overwrite static state in DIContainers across tests"""
global TestIntention
global TestApplication
with importlib_resources.path(__package__, "test.config") as test_config:
LocalConfigurationContainer.load_configuration(str(test_config), [])
clas... | def setupTestComponents():
| """Workaround to overwrite static state in DIContainers across tests"""
global TestIntention
global TestApplication
with importlib_resources.path(__package__, "test.config") as test_config:
LocalConfigurationContainer.load_configuration(str(test_config), [])
class TestBackendContainer(Back... | RecognitionComponent
from pepper.framework.application.text_to_speech import TextToSpeechComponent
from pepper.framework.infra.config.api import ConfigurationContainer
from pepper.framework.infra.config.local import LocalConfigurationContainer
from pepper.framework.infra.di_container import singleton, DIContainer
from ... | 196 | 196 | 654 | 5 | 191 | leolani/pepper | test/app_itest/test_resource.py | Python | setupTestComponents | setupTestComponents | 40 | 128 | 40 | 40 | 68b9912a86d0918c575c7794c415cb917b8d12b9 | bigcode/the-stack | train |
df2115cd579afe17976f509d | train | class | class ListeningThread(threading.Thread):
def __init__(self, speech_flag, microphone, webrtc_buffer_size, name="Listening"):
super(ListeningThread, self).__init__(name=name)
self._webrtc_buffer_size = webrtc_buffer_size
self._speech_flag = speech_flag
self._microphone = microphone
... | class ListeningThread(threading.Thread):
| def __init__(self, speech_flag, microphone, webrtc_buffer_size, name="Listening"):
super(ListeningThread, self).__init__(name=name)
self._webrtc_buffer_size = webrtc_buffer_size
self._speech_flag = speech_flag
self._microphone = microphone
self.running = True
self.lis... | None
def object_detector(self, target):
return None
class ApplicationContainer(TestBackendContainer,
TestSensorContainer,
SynchronousEventBusContainer,
ThreadedResourceContainer,
... | 161 | 161 | 537 | 7 | 154 | leolani/pepper | test/app_itest/test_resource.py | Python | ListeningThread | ListeningThread | 131 | 194 | 131 | 131 | 9b1123d0411de682eab10ef8c9519be8144b97c9 | bigcode/the-stack | train |
aba124296d9d72d7745d5004 | train | class | class TalkingThread(threading.Thread):
def __init__(self, intention, name="Talking"):
super(TalkingThread, self).__init__(name=name)
self._intention = intention
self.running = True
self.talking = False
self.talking_latch = threading.Event()
self.exit_latch = threading... | class TalkingThread(threading.Thread):
| def __init__(self, intention, name="Talking"):
super(TalkingThread, self).__init__(name=name)
self._intention = intention
self.running = True
self.talking = False
self.talking_latch = threading.Event()
self.exit_latch = threading.Event()
def stop(self):
s... | ._microphone.on_audio(AUDIO_FRAME)
logger.debug("Void %s-%s", i, j)
sleep(0.001)
self.listening_latch.clear()
logger.debug("Stopped listening")
self.exit_latch.set()
self.listening_latch.wait()
logger.debug("Thread %s stop... | 79 | 79 | 266 | 7 | 72 | leolani/pepper | test/app_itest/test_resource.py | Python | TalkingThread | TalkingThread | 196 | 233 | 196 | 196 | 54daa2087e83c2155fd8727715a8cfe3877e4598 | bigcode/the-stack | train |
7e55aa9482eed7ee690285ad | train | function | def train(encoder, decoder, dataset, batch_size, criterion, encoder_optimizer, decoder_optimizer):
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
i = 0
total_loss = []
for i_batch, sample_batched in enumerate(dataloader):
i += 1
#print('Now training image No.', i)... | def train(encoder, decoder, dataset, batch_size, criterion, encoder_optimizer, decoder_optimizer):
| dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
i = 0
total_loss = []
for i_batch, sample_batched in enumerate(dataloader):
i += 1
#print('Now training image No.', i)
image, caption = sample_batched['image'].cuda(), sample_batched['caption'].cuda()[0]
... | n_weights, encoder_outputs.view(-1, self.hidden_size)), dim=1)
context_with_attn = context_with_attn.unsqueeze(1)
output = torch.cat((embedded[0], context_with_attn[0]), 1)
output = self.attn_combine(output).view(1, 1, -1)
output = F.relu(output)
output, hidden = self.gru(output,... | 137 | 137 | 459 | 20 | 116 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | train | train | 199 | 244 | 199 | 199 | d8b0c01494620aca048309ce3c321b2db3db16ae | bigcode/the-stack | train |
f0ce2d6f8ceae5f59b41a83e | train | function | def evaluateRandomly(encoder, decoder, n_samples=5):
dataset = CocoDataset(val_image_dir, val_caption_dir, n_samples=n_samples, transform=data_transform)
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
i = 0
for i_batch, sample_batched in enumerate(dataloader):
image, caption = sam... | def evaluateRandomly(encoder, decoder, n_samples=5):
| dataset = CocoDataset(val_image_dir, val_caption_dir, n_samples=n_samples, transform=data_transform)
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
i = 0
for i_batch, sample_batched in enumerate(dataloader):
image, caption = sample_batched['image'].cuda(), sample_batched['caption'... | NTIALIAS)
# attention.save('result/Attention_{}.jpg'.format(i+1))
plt.subplot(4, n_col, i+2)
plt.imshow(attention)
plt.show()
plt.savefig(file_name)
def evaluateRandomly(encoder, decoder, n_samples=5):
| 64 | 64 | 178 | 14 | 50 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | evaluateRandomly | evaluateRandomly | 310 | 322 | 310 | 310 | 9081f9a860a521cac9c5b8e5f93f98d1ed7ca32d | bigcode/the-stack | train |
2aff0bf76a4390ec6f08740b | train | class | class CocoDataset(Dataset):
def __init__(self, image_dir, caption_dir, n_samples=5000, transform=None):
self.image_dir = image_dir
self.caption_dir = caption_dir
self.transform = transform
self.file_names = os.listdir(self.image_dir)[:n_samples]
self.word_tokenizor = WordPun... | class CocoDataset(Dataset):
| def __init__(self, image_dir, caption_dir, n_samples=5000, transform=None):
self.image_dir = image_dir
self.caption_dir = caption_dir
self.transform = transform
self.file_names = os.listdir(self.image_dir)[:n_samples]
self.word_tokenizor = WordPunctTokenizer()
self.id... | id_to_word = {id: word for word, id in word_to_id.items()}
max_length = max(length)
return id_to_word, word_to_id, len(id_to_word), max_length
id_to_word, word_to_id, vocab_size, max_length = prepare_vocabulary(val_caption_dir)
print('Vocab size: {}\nMax sentence length: {}'.format(vocab_size, max_length)... | 92 | 92 | 308 | 6 | 86 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | CocoDataset | CocoDataset | 85 | 113 | 85 | 86 | ca2a47ee22486b249f9974d62f3e0242a7e36a57 | bigcode/the-stack | train |
7159bb713d318a072ce9a1a2 | train | function | def prepare_vocabulary(path):
word_tokenizor = WordPunctTokenizer()
lines = open(path, encoding='utf-8').read().strip().split('\n')
captions = [line.split('\t')[1] for line in lines if len(line.split('\t'))==2]
captions = [word_tokenizor.tokenize(caption) for caption in captions]
captions = [[word.l... | def prepare_vocabulary(path):
| word_tokenizor = WordPunctTokenizer()
lines = open(path, encoding='utf-8').read().strip().split('\n')
captions = [line.split('\t')[1] for line in lines if len(line.split('\t'))==2]
captions = [word_tokenizor.tokenize(caption) for caption in captions]
captions = [[word.lower() for word in caption] fo... | 225])])
inv_normalize = transforms.Normalize(
mean=[-0.485/0.229, -0.456/0.224, -0.406/0.255],
std=[1/0.229, 1/0.224, 1/0.255]
)
def prepare_vocabulary(path):
| 70 | 70 | 235 | 6 | 64 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | prepare_vocabulary | prepare_vocabulary | 63 | 78 | 63 | 63 | aa0741ffbb8c2f58b2abe96bdeeb1ef101574dde | bigcode/the-stack | train |
9e2e17bc658c1e43c9760994 | train | function | def show_attention(attentions, image, file_name):
image = Image.open(os.path.join(val_image_dir, file_name))
image = transforms.Resize(224)(image)
image = transforms.RandomSizedCrop(224)(image)
#image.save('result/Original.jpg')
caption_length = len(attentions)
if caption_length%4 == 0:
... | def show_attention(attentions, image, file_name):
| image = Image.open(os.path.join(val_image_dir, file_name))
image = transforms.Resize(224)(image)
image = transforms.RandomSizedCrop(224)(image)
#image.save('result/Original.jpg')
caption_length = len(attentions)
if caption_length%4 == 0:
n_col = caption_length//4
else:
n_col ... | if topi.item() == word_to_id['<EOS>']:
decoded_words.append('<EOS>')
break
else:
decoded_words.append(id_to_word[topi.item()])
decoder_input = topi.squeeze().detach()
return decoded_words[:-1], attentions
def show_attention(attentions, im... | 69 | 69 | 233 | 11 | 57 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | show_attention | show_attention | 286 | 307 | 286 | 286 | 21b7fd089895cfa25700c0a94b615168ff33a8db | bigcode/the-stack | train |
352a6807bcc11129b2b32b19 | train | function | def evaluate(encoder, decoder, image):
with torch.no_grad():
features_for_initial_state, features_for_attention = encoder(image)
decoder_input = torch.tensor([[word_to_id['<SOS>']]], device=device)
decoder_hidden = features_for_initial_state
decoded_words = []
attentions = ... | def evaluate(encoder, decoder, image):
| with torch.no_grad():
features_for_initial_state, features_for_attention = encoder(image)
decoder_input = torch.tensor([[word_to_id['<SOS>']]], device=device)
decoder_hidden = features_for_initial_state
decoded_words = []
attentions = []
for di in range(max_length)... | _optimizer)
loss = np.mean(total_loss)
torch.save(encoder, 'model/encoder.pkl')
torch.save(decoder, 'model/decoder.pkl')
print('Iter: {}, Loss: {}, Total loss: {}'.format(i, loss, total_loss))
def evaluate(encoder, decoder, image):
| 64 | 64 | 179 | 9 | 55 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | evaluate | evaluate | 261 | 283 | 261 | 261 | f87cdad7e655ced03ef33e2f433588b29cf250e6 | bigcode/the-stack | train |
32a1561df0a0bed02ad48615 | train | class | class EncoderCNN(nn.Module):
def __init__(self, hidden_size):
super(EncoderCNN, self).__init__()
vggnet = models.vgg19(pretrained=True)
modules = list(vggnet.features.children())[:-1]
self.vggnet = nn.Sequential(*modules)
self.hidden_size = hidden_size
self.conv1 = nn... | class EncoderCNN(nn.Module):
| def __init__(self, hidden_size):
super(EncoderCNN, self).__init__()
vggnet = models.vgg19(pretrained=True)
modules = list(vggnet.features.children())[:-1]
self.vggnet = nn.Sequential(*modules)
self.hidden_size = hidden_size
self.conv1 = nn.Conv2d(512, self.hidden_size... | , 1)
caption = caption.long()
if self.transform:
image_new = self.transform(image)
sample = {'image': image_new, 'caption': caption}
return sample
######################################################################
# The Encoder
#
# The encoder of is a pre-trained VGG-1... | 78 | 78 | 262 | 6 | 72 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | EncoderCNN | EncoderCNN | 123 | 142 | 123 | 123 | aa8f71fe2cad1c1080bf345314d132cb9a188a5b | bigcode/the-stack | train |
089ab67c79a6bb7b9fa04ee2 | train | function | def cuda_variable(tensor):
if device == 'cuda':
return Variable(tensor.cuda())
else:
return Variable(tensor)
| def cuda_variable(tensor):
| if device == 'cuda':
return Variable(tensor.cuda())
else:
return Variable(tensor)
| import Variable
import torchvision.models as models
from torchvision import transforms, datasets
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pack_padded_sequence
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
def cuda_variable(tensor):
| 64 | 64 | 29 | 6 | 58 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | cuda_variable | cuda_variable | 33 | 37 | 33 | 33 | 6e9b26b4173df93850539d05430d42b84d652afb | bigcode/the-stack | train |
a12c0a7adfb9fdf343889da7 | train | class | class AttnDecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers, dropout_p=0.1):
super(AttnDecoderRNN, self).__init__()
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.dropout_p = dropout_p
... | class AttnDecoderRNN(nn.Module):
| def __init__(self, embed_size, hidden_size, vocab_size, num_layers, dropout_p=0.1):
super(AttnDecoderRNN, self).__init__()
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.dropout_p = dropout_p
self.dropout = nn.Dropout(sel... | 1, -1) # torch.Size([1, 1, 256]), combination of features in 14 locations
return features_for_initial_state, features_for_attention
######################################################################
# Attention Decoder
#
# If only the context vector is passed betweeen the encoder and decoder,
# that si... | 145 | 145 | 486 | 9 | 136 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | AttnDecoderRNN | AttnDecoderRNN | 158 | 196 | 158 | 158 | 4989a546f84548fb547d21671a352f5a6c6a95a2 | bigcode/the-stack | train |
d9311c433b15c6a6aea9b0f4 | train | function | def trainIters(encoder, decoder, learning_rate, weight_decay, batch_size, n_epochs=1, n_samples=50):
dataset = CocoDataset(val_image_dir, val_caption_dir, n_samples=n_samples, transform=data_transform)
criterion = nn.NLLLoss()
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate, weight_de... | def trainIters(encoder, decoder, learning_rate, weight_decay, batch_size, n_epochs=1, n_samples=50):
| dataset = CocoDataset(val_image_dir, val_caption_dir, n_samples=n_samples, transform=data_transform)
criterion = nn.NLLLoss()
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate, weight_decay=weight_decay)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate, weight_d... | <EOS>']:
break
total_loss.append(loss.item()/caption_length)
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
return total_loss
def trainIters(encoder, decoder, learning_rate, weight_decay, batch_size, n_epochs=1, n_samples=50):
| 64 | 64 | 184 | 28 | 35 | yc930401/Image-Captioning-pytorch | image_captioning.py | Python | trainIters | trainIters | 247 | 258 | 247 | 247 | 34b1ec6c6e65192d6bd184cebcf46ec4129d695d | bigcode/the-stack | train |
b732878b2eea287833e4abe7 | train | function | def _parseNormalHeader(fn):
with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
chunkedData = data.split("\n", 7)
objectType = chunkedData[1].split("=")[-1]
objectType = objectType.replace('"', "").strip()
data = chunkedData[-1]
maxT = chunkedData[-4].split("=")[-1].strip(... | def _parseNormalHeader(fn):
| with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
chunkedData = data.split("\n", 7)
objectType = chunkedData[1].split("=")[-1]
objectType = objectType.replace('"', "").strip()
data = chunkedData[-1]
maxT = chunkedData[-4].split("=")[-1].strip()
minT = chunkedData[-5]... | (dataList[i + 1]))
for i in range(0, len(dataList), 2)
if dataList[i].strip() != ""
]
po = PointObject2D(dataList, objectType, minT, maxT)
return po
def _parseNormalHeader(fn):
| 64 | 64 | 145 | 7 | 56 | mmcauliffe/praatIO | praatio/dataio.py | Python | _parseNormalHeader | _parseNormalHeader | 178 | 192 | 178 | 178 | 4185a0dbe5cf2056edc105010c2d27094e3e3abf | bigcode/the-stack | train |
0eb0cb521b5c78d17d663d05 | train | class | class PointObject1D(PointObject):
"""Points that only carry temporal information"""
def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
assert objectClass != PITCH
assert objectClass != DURATION
if maxTime is None:
maxTime = max(pointList)
super(P... | class PointObject1D(PointObject):
| """Points that only carry temporal information"""
def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
assert objectClass != PITCH
assert objectClass != DURATION
if maxTime is None:
maxTime = max(pointList)
super(PointObject1D, self).__init__(point... | ):
returnPointList = []
for entry in self.pointList[startIndex:]:
time = entry[0]
if time >= start:
if time <= stop:
returnPointList.append(time)
else:
break
return returnPointList
class PointObject... | 64 | 64 | 93 | 8 | 55 | mmcauliffe/praatIO | praatio/dataio.py | Python | PointObject1D | PointObject1D | 69 | 80 | 69 | 69 | 647cb6145c11756a5b22d56d5bcc900994d53bb1 | bigcode/the-stack | train |
06bb94c470545916e35cf735 | train | class | class PointObject2D(PointObject):
"""Points that carry a temporal value and some other value"""
def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
assert objectClass != POINT
if maxTime is None:
maxTime = max([timeV for timeV, _ in pointList])
super(Poin... | class PointObject2D(PointObject):
| """Points that carry a temporal value and some other value"""
def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
assert objectClass != POINT
if maxTime is None:
maxTime = max([timeV for timeV, _ in pointList])
super(PointObject2D, self).__init__(pointLis... | =None):
assert objectClass != PITCH
assert objectClass != DURATION
if maxTime is None:
maxTime = max(pointList)
super(PointObject1D, self).__init__(pointList, objectClass, minTime, maxTime)
class PointObject2D(PointObject):
| 64 | 64 | 97 | 8 | 56 | mmcauliffe/praatIO | praatio/dataio.py | Python | PointObject2D | PointObject2D | 83 | 93 | 83 | 83 | cef24e4ab00e4dbbfb29a7cb7a47b15ed3bfed04 | bigcode/the-stack | train |
6a3ed33307f426dfc50e59e4 | train | function | def _parseShortHeader(fn):
with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
chunkedData = data.split("\n", 6)
objectType = chunkedData[1].split("=")[-1]
objectType = objectType.replace('"', "").strip()
data = chunkedData[-1]
maxT = chunkedData[-3]
minT = chunkedData... | def _parseShortHeader(fn):
| with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
chunkedData = data.split("\n", 6)
objectType = chunkedData[1].split("=")[-1]
objectType = objectType.replace('"', "").strip()
data = chunkedData[-1]
maxT = chunkedData[-3]
minT = chunkedData[-4]
minT, maxT = floa... | float(minT), float(maxT)
return data, objectType, minT, maxT
def _getNextValue(data, start):
end = data.index("\n", start)
value = data[start + 1 : end]
return value, end
def _parseShortHeader(fn):
| 64 | 64 | 129 | 7 | 56 | mmcauliffe/praatIO | praatio/dataio.py | Python | _parseShortHeader | _parseShortHeader | 201 | 216 | 201 | 201 | b0cde49c5641e125529574547d7efafbdbeadadd | bigcode/the-stack | train |
3018cfbd442b93622fe11055 | train | function | def _getNextValue(data, start):
end = data.index("\n", start)
value = data[start + 1 : end]
return value, end
| def _getNextValue(data, start):
| end = data.index("\n", start)
value = data[start + 1 : end]
return value, end
| ].split("=")[-1].strip()
minT = chunkedData[-5].split("=")[-1].strip()
minT, maxT = float(minT), float(maxT)
return data, objectType, minT, maxT
def _getNextValue(data, start):
| 64 | 64 | 36 | 9 | 54 | mmcauliffe/praatIO | praatio/dataio.py | Python | _getNextValue | _getNextValue | 195 | 198 | 195 | 195 | 7610cad1ea681a5d0b0589c14d7f84ce723c6c58 | bigcode/the-stack | train |
0e9bbab63e585c55875b37f5 | train | function | def open2DPointObject(fn):
with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
if "xmin" in data[:100]: # Kindof lazy
data, objectType, minT, maxT = _parseNormalHeader(fn)
start = 0
dataList = []
while True:
try:
start = data.inde... | def open2DPointObject(fn):
| with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
if "xmin" in data[:100]: # Kindof lazy
data, objectType, minT, maxT = _parseNormalHeader(fn)
start = 0
dataList = []
while True:
try:
start = data.index("=", start)
e... | data, objectType, minT, maxT = _parseShortHeader(fn)
dataList = data.split("\n")
dataList = [
[
float(val),
]
for val in dataList
if val.strip() != ""
]
po = PointObject1D(dataList, objectType, minT, maxT)
return po
de... | 86 | 86 | 289 | 8 | 77 | mmcauliffe/praatIO | praatio/dataio.py | Python | open2DPointObject | open2DPointObject | 134 | 175 | 134 | 134 | 9e5e1fe3e8dc57d4656c8da2facdc42734cdd742 | bigcode/the-stack | train |
af3ea39251562c7bb9e72e7a | train | function | def open1DPointObject(fn):
with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
if "xmin" in data[:100]: # Kindof lazy
data, objectType, minT, maxT = _parseNormalHeader(fn)
start = 0
dataList = []
while True:
try:
start = data.inde... | def open1DPointObject(fn):
| with io.open(fn, "r", encoding="utf-8") as fd:
data = fd.read()
if "xmin" in data[:100]: # Kindof lazy
data, objectType, minT, maxT = _parseNormalHeader(fn)
start = 0
dataList = []
while True:
try:
start = data.index("=", start)
e... | =0, maxTime=None):
assert objectClass != POINT
if maxTime is None:
maxTime = max([timeV for timeV, _ in pointList])
super(PointObject2D, self).__init__(pointList, objectClass, minTime, maxTime)
def open1DPointObject(fn):
| 69 | 69 | 232 | 8 | 61 | mmcauliffe/praatIO | praatio/dataio.py | Python | open1DPointObject | open1DPointObject | 96 | 131 | 96 | 96 | 8928f1e706a336f99528e4bdbace79e709afa653 | bigcode/the-stack | train |
7519ca5106c7c5922d7669e9 | train | class | class PointObject(object):
def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
# Sanitize input
pointList = [tuple(row) for row in pointList]
self.pointList = pointList
self.objectClass = objectClass
self.minTime = minTime if minTime > 0 else 0
self... | class PointObject(object):
| def __init__(self, pointList, objectClass, minTime=0, maxTime=None):
# Sanitize input
pointList = [tuple(row) for row in pointList]
self.pointList = pointList
self.objectClass = objectClass
self.minTime = minTime if minTime > 0 else 0
self.maxTime = maxTime
def... | """
Code for reading, writing, and representing less complicated praat data files
see **examples/get_vowel_points.py**
"""
import io
POINT = "PointProcess"
PITCH = "PitchTier"
DURATION = "DurationTier"
class PointObject(object):
| 53 | 120 | 400 | 5 | 48 | mmcauliffe/praatIO | praatio/dataio.py | Python | PointObject | PointObject | 14 | 66 | 14 | 14 | dbe64e2a71d4633208f4ad9fb2bda342f05d2482 | bigcode/the-stack | train |
b15911cb94fea40095de35dd | train | class | class _NotInRepoError(RuntimeError):
"""Raised when the remote file is not present in the given repo"""
| class _NotInRepoError(RuntimeError):
| """Raised when the remote file is not present in the given repo"""
| )
_ROOT_DIR = Path(__file__).resolve().parent.parent
_SRC_PATH = Path('src')
class _PatchValidationError(Exception):
"""Raised when patch validation fails"""
class _UnexpectedSyntaxError(RuntimeError):
"""Raised when unexpected syntax is used in DEPS"""
class _NotInRepoError(RuntimeError):
| 64 | 64 | 24 | 9 | 55 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _NotInRepoError | _NotInRepoError | 90 | 91 | 90 | 90 | 2521dcc5384f2ec44782a604357b77c38180b21a | bigcode/the-stack | train |
3e6a8357f0c7cb0d15b97d2e | train | function | def _get_dep_value_url(deps_globals, dep_value):
"""Helper for _process_deps_entries"""
if isinstance(dep_value, str):
url = dep_value
elif isinstance(dep_value, dict):
if 'url' not in dep_value:
# Ignore other types like CIPD since
# it probably isn't necessary
... | def _get_dep_value_url(deps_globals, dep_value):
| """Helper for _process_deps_entries"""
if isinstance(dep_value, str):
url = dep_value
elif isinstance(dep_value, dict):
if 'url' not in dep_value:
# Ignore other types like CIPD since
# it probably isn't necessary
return None
url = dep_value['url']... | 404:
raise _NotInRepoError()
response.raise_for_status()
# Assume all files that need patching are compatible with UTF-8
return base64.b64decode(response.text, validate=True).decode('UTF-8')
def _get_dep_value_url(deps_globals, dep_value):
| 64 | 64 | 152 | 13 | 51 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_dep_value_url | _get_dep_value_url | 159 | 176 | 159 | 159 | f33373cf02c8e16758e5af0a73a84783e68d1629 | bigcode/the-stack | train |
12fbd1fa297b50c23cb61f32 | train | function | def _get_child_deps_tree(download_session, current_deps_tree, child_path, deps_use_relative_paths):
"""Helper for _download_source_file"""
repo_url, version, child_deps_tree = current_deps_tree[child_path]
if isinstance(child_deps_tree, str):
# Load unloaded DEPS
deps_globals = _parse_deps(
... | def _get_child_deps_tree(download_session, current_deps_tree, child_path, deps_use_relative_paths):
| """Helper for _download_source_file"""
repo_url, version, child_deps_tree = current_deps_tree[child_path]
if isinstance(child_deps_tree, str):
# Load unloaded DEPS
deps_globals = _parse_deps(
_download_googlesource_file(download_session, repo_url, version, child_deps_tree))
... | not recursive; i.e. it is fully loaded
grandchild_deps_tree = dict()
child_deps_tree[dep_path] = (*url.split('@'), grandchild_deps_tree)
def _get_child_deps_tree(download_session, current_deps_tree, child_path, deps_use_relative_paths):
| 64 | 64 | 178 | 23 | 41 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_child_deps_tree | _get_child_deps_tree | 207 | 218 | 207 | 207 | 46f7575ff2aeb04d7791fc5c7561ad4b99ce7e5f | bigcode/the-stack | train |
ec40079c0fc677e0ae313e7b | train | function | def _test_patches(series_iter, patch_cache, files_under_test):
"""
Tests the patches specified in the iterable series_iter
Returns a boolean indicating if any of the patches have failed
"""
for patch_path_str in series_iter:
for patched_file in patch_cache[patch_path_str]:
try:
... | def _test_patches(series_iter, patch_cache, files_under_test):
| """
Tests the patches specified in the iterable series_iter
Returns a boolean indicating if any of the patches have failed
"""
for patch_path_str in series_iter:
for patched_file in patch_cache[patch_path_str]:
try:
_apply_file_unidiff(patched_file, files_under_t... | _file:
files_under_test[patched_file_path] = None
else: # Patching an existing file
assert patched_file.is_modified_file
_modify_file_lines(patched_file, files_under_test[patched_file_path])
def _test_patches(series_iter, patch_cache, files_under_test):
| 64 | 64 | 207 | 15 | 49 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _test_patches | _test_patches | 533 | 555 | 533 | 533 | bf43ed24abb40b0939a081e9059177c3d41db219 | bigcode/the-stack | train |
68eb6b4c34ba2894160d736f | train | function | def _get_gitiles_git_log_date(log_entry):
"""Helper for _get_gitiles_git_log_date"""
return email.utils.parsedate_to_datetime(log_entry['committer']['time'])
| def _get_gitiles_git_log_date(log_entry):
| """Helper for _get_gitiles_git_log_date"""
return email.utils.parsedate_to_datetime(log_entry['committer']['time'])
| 'https://storage.googleapis.com/chromium-browser-official/chromium-{}.tar.xz'.format(
get_chromium_version()))
response.raise_for_status()
return email.utils.parsedate_to_datetime(response.headers['Last-Modified'])
def _get_gitiles_git_log_date(log_entry):
| 63 | 64 | 40 | 11 | 52 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_gitiles_git_log_date | _get_gitiles_git_log_date | 231 | 233 | 231 | 231 | dd612c707cb4e3109545eede8cbc18cc98f28adc | bigcode/the-stack | train |
d6402306a7ae59f6612d411b | train | class | class _PatchValidationError(Exception):
"""Raised when patch validation fails"""
| class _PatchValidationError(Exception):
| """Raised when patch validation fails"""
| :
def _get_requests_session():
raise RuntimeError('The Python module "requests" is required for remote'
'file downloading. It can be installed from PyPI.')
_ROOT_DIR = Path(__file__).resolve().parent.parent
_SRC_PATH = Path('src')
class _PatchValidationError(Exception):
| 64 | 64 | 15 | 7 | 57 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _PatchValidationError | _PatchValidationError | 82 | 83 | 82 | 82 | c10507d7c211387dbce9e19f6155d398900f8097 | bigcode/the-stack | train |
af783622484d139e71f048c2 | train | class | class _FallbackRepoManager:
"""Retrieves fallback repos and caches data needed for determining repos"""
_GN_REPO_URL = 'https://gn.googlesource.com/gn.git'
def __init__(self):
self._cache_gn_version = None
@property
def gn_version(self):
"""
Returns the version of the GN r... | class _FallbackRepoManager:
| """Retrieves fallback repos and caches data needed for determining repos"""
_GN_REPO_URL = 'https://gn.googlesource.com/gn.git'
def __init__(self):
self._cache_gn_version = None
@property
def gn_version(self):
"""
Returns the version of the GN repo for the Chromium version... | 'continuing with oldest entry...')
return git_log[-1]['commit']
# Do binary search
low_index = 0
high_index = len(git_log) - 1
mid_index = high_index
while low_index != high_index:
mid_index = low_index + (high_index - low_index) // 2
if _get_giti... | 130 | 130 | 436 | 6 | 124 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _FallbackRepoManager | _FallbackRepoManager | 269 | 312 | 269 | 269 | ca1db0e1c84f1486e4ae16d7cdf592cbd39d9500 | bigcode/the-stack | train |
06d422a8b7d18079fcf4415e | train | function | def _parse_deps(deps_text):
"""Returns a dict of parsed DEPS data"""
deps_globals = {'__builtins__': None}
deps_globals['Var'] = _deps_var(deps_globals)
exec(deps_text, deps_globals) #pylint: disable=exec-used
return deps_globals
| def _parse_deps(deps_text):
| """Returns a dict of parsed DEPS data"""
deps_globals = {'__builtins__': None}
deps_globals['Var'] = _deps_var(deps_globals)
exec(deps_text, deps_globals) #pylint: disable=exec-used
return deps_globals
| _deps_var(deps_globals):
"""Return a function that implements DEPS's Var() function"""
def _var_impl(var_name):
"""Implementation of Var() in DEPS"""
return deps_globals['vars'][var_name]
return _var_impl
def _parse_deps(deps_text):
| 64 | 64 | 70 | 9 | 54 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _parse_deps | _parse_deps | 134 | 139 | 134 | 134 | 4ed1cf2dfa399e73764bafd3508d66bcc2d215d6 | bigcode/the-stack | train |
6981fbe8954497016e7fb8a0 | train | function | def main():
"""CLI Entrypoint"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-s',
'--series',
type=Path,
metavar='FILE',
default=str(Path('patches', 'series')),
help='The series file listing patches to apply. Default: %(default)... | def main():
| """CLI Entrypoint"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-s',
'--series',
type=Path,
metavar='FILE',
default=str(Path('patches', 'series')),
help='The series file listing patches to apply. Default: %(default)s')
pars... | """
Helper for main to get files_under_test
Exits the program if --cache-remote debugging option is used
"""
if args.local:
files_under_test = _retrieve_local_files(required_files, args.local)
else: # --remote and --cache-remote
files_under_test = _retrieve_remote_files(required... | 169 | 169 | 566 | 3 | 165 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | main | main | 611 | 674 | 611 | 611 | 56efc34a1b5716165feb9977b3bc84005fbccc76 | bigcode/the-stack | train |
6729bf5c63d20a609beadc12 | train | function | def _modify_file_lines(patched_file, file_lines):
"""Helper for _apply_file_unidiff"""
# Cursor for keeping track of the current line during hunk application
# NOTE: The cursor is based on the line list index, not the line number!
line_cursor = None
for hunk in patched_file:
# Validate hunk ... | def _modify_file_lines(patched_file, file_lines):
| """Helper for _apply_file_unidiff"""
# Cursor for keeping track of the current line during hunk application
# NOTE: The cursor is based on the line list index, not the line number!
line_cursor = None
for hunk in patched_file:
# Validate hunk will match
if not hunk.is_valid():
... | try:
content = raw_content.decode(encoding)
break
except UnicodeDecodeError:
continue
if not content:
raise UnicodeDecodeError('Unable to decode with any encoding: %s' % file_path)
files[file_path] = content.split('\n')
... | 95 | 95 | 318 | 12 | 82 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _modify_file_lines | _modify_file_lines | 482 | 513 | 482 | 482 | 53780bbd7eda116144e7e9ef95205d14e852e173 | bigcode/the-stack | train |
ce9653df7d1e7a0bbbaf2737 | train | function | def _validate_deps(deps_text):
"""Returns True if the DEPS file passes validation; False otherwise"""
try:
_DepsNodeVisitor().visit(ast.parse(deps_text))
except _UnexpectedSyntaxError as exc:
get_logger().error('%s', exc)
return False
return True
| def _validate_deps(deps_text):
| """Returns True if the DEPS file passes validation; False otherwise"""
try:
_DepsNodeVisitor().visit(ast.parse(deps_text))
except _UnexpectedSyntaxError as exc:
get_logger().error('%s', exc)
return False
return True
| self._valid_syntax_types:
if isinstance(node, ast_type):
super().generic_visit(node)
return
raise _UnexpectedSyntaxError('Unexpected {} at line {}, column {}'.format(
type(node).__name__, node.lineno, node.col_offset))
def _validate_deps(deps_text):
| 64 | 64 | 67 | 9 | 55 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _validate_deps | _validate_deps | 114 | 121 | 114 | 114 | b4a46ce57b9d9e0f549783eac725efac93ccbe2e | bigcode/the-stack | train |
981d07f644d32d8aa15c19c4 | train | function | def _get_last_chromium_modification():
"""Returns the last modification date of the chromium-browser-official tar file"""
with _get_requests_session() as session:
response = session.head(
'https://storage.googleapis.com/chromium-browser-official/chromium-{}.tar.xz'.format(
ge... | def _get_last_chromium_modification():
| """Returns the last modification date of the chromium-browser-official tar file"""
with _get_requests_session() as session:
response = session.head(
'https://storage.googleapis.com/chromium-browser-official/chromium-{}.tar.xz'.format(
get_chromium_version()))
response... | ps_tree)
deps_use_relative_paths = deps_globals.get('use_relative_paths', False)
_process_deps_entries(deps_globals, child_deps_tree, child_path, deps_use_relative_paths)
return child_deps_tree, deps_use_relative_paths
def _get_last_chromium_modification():
| 64 | 64 | 95 | 10 | 53 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_last_chromium_modification | _get_last_chromium_modification | 221 | 228 | 221 | 221 | bf51b2c76c613ef3bafc6bedb2e38aeb14451915 | bigcode/the-stack | train |
d2cf5f90f206152fcfff841f | train | function | def _retrieve_remote_files(file_iter):
"""
Retrieves all file paths in file_iter from Google
file_iter is an iterable of strings that are relative UNIX paths to
files in the Chromium source.
Returns a dict of relative UNIX path strings to a list of lines in the file as strings
"""
fil... | def _retrieve_remote_files(file_iter):
| """
Retrieves all file paths in file_iter from Google
file_iter is an iterable of strings that are relative UNIX paths to
files in the Chromium source.
Returns a dict of relative UNIX path strings to a list of lines in the file as strings
"""
files = dict()
root_deps_tree = _init... | )
repo_url is the URL to the dependency's repository root
If the recursive dict is a string, then it is a string to the DEPS file to load
if needed
download_session is an active requests.Session() object
"""
root_deps_tree = {
_SRC_PATH: ('https://chromium.googlesource.c... | 109 | 109 | 365 | 8 | 100 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _retrieve_remote_files | _retrieve_remote_files | 403 | 449 | 403 | 403 | 9961283bed73935a347d17ec91fa882275b024a9 | bigcode/the-stack | train |
ab6f03776b264d061a3b038e | train | function | def _get_target_file_deps_node(download_session, root_deps_tree, target_file):
"""
Helper for _download_source_file
Returns the corresponding repo containing target_file based on the DEPS tree
"""
# The "deps" from the current DEPS file
current_deps_tree = root_deps_tree
current_node = None... | def _get_target_file_deps_node(download_session, root_deps_tree, target_file):
| """
Helper for _download_source_file
Returns the corresponding repo containing target_file based on the DEPS tree
"""
# The "deps" from the current DEPS file
current_deps_tree = root_deps_tree
current_node = None
# Path relative to the current node (i.e. DEPS file)
current_relative_... | _tree[_SRC_PATH]:
get_logger().info('Redirecting to GN repo version %s for path: %s', self.gn_version,
current_relative_path)
return (self._GN_REPO_URL, self.gn_version, new_relative_path)
return None, None, None
def _get_target_file_deps_node(do... | 81 | 81 | 273 | 19 | 61 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_target_file_deps_node | _get_target_file_deps_node | 315 | 343 | 315 | 315 | b17eb252b7f6ff1940b648e7fe1345e3f29f9acd | bigcode/the-stack | train |
7f5b6351282f133ea81b445f | train | function | def _initialize_deps_tree():
"""
Initializes and returns a dependency tree for DEPS files
The DEPS tree is a dict has the following format:
key - pathlib.Path relative to the DEPS file's path
value - tuple(repo_url, version, recursive dict here)
repo_url is the URL to the dependency's repos... | def _initialize_deps_tree():
| """
Initializes and returns a dependency tree for DEPS files
The DEPS tree is a dict has the following format:
key - pathlib.Path relative to the DEPS file's path
value - tuple(repo_url, version, recursive dict here)
repo_url is the URL to the dependency's repository root
If the rec... | NotInRepoError:
pass
get_logger().error('File "%s" (relative: "%s") not found in fallback repo "%s", version "%s"',
target_file, current_relative_path, repo_url, version)
raise _NotInRepoError()
def _initialize_deps_tree():
| 64 | 64 | 161 | 7 | 57 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _initialize_deps_tree | _initialize_deps_tree | 383 | 400 | 383 | 383 | f6fa73a265da6ce104cefd3c35dcbd92ecce43db | bigcode/the-stack | train |
74c3c8da609856b39c31a2b0 | train | function | def _retrieve_local_files(file_iter, source_dir):
"""
Retrieves all file paths in file_iter from the local source tree
file_iter is an iterable of strings that are relative UNIX paths to
files in the Chromium source.
Returns a dict of relative UNIX path strings to a list of lines in the file a... | def _retrieve_local_files(file_iter, source_dir):
| """
Retrieves all file paths in file_iter from the local source tree
file_iter is an iterable of strings that are relative UNIX paths to
files in the Chromium source.
Returns a dict of relative UNIX path strings to a list of lines in the file as strings
"""
files = dict()
for file_... | _file(
download_session, root_deps_tree, fallback_repo_manager, file_path).split('\n')
except _NotInRepoError:
get_logger().warning('Could not find "%s" remotely. Skipping...', file_path)
return files
def _retrieve_local_files(file_iter, source_dir):
| 65 | 65 | 219 | 11 | 53 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _retrieve_local_files | _retrieve_local_files | 452 | 479 | 452 | 452 | c39fab7f8f3500c96cb1868f83875ad997e57171 | bigcode/the-stack | train |
d2fb53dc49d78b1a659adce8 | train | function | def _apply_file_unidiff(patched_file, files_under_test):
"""Applies the unidiff.PatchedFile to the source files under testing"""
patched_file_path = Path(patched_file.path)
if patched_file.is_added_file:
if patched_file_path in files_under_test:
assert files_under_test[patched_file_path]... | def _apply_file_unidiff(patched_file, files_under_test):
| """Applies the unidiff.PatchedFile to the source files under testing"""
patched_file_path = Path(patched_file.path)
if patched_file.is_added_file:
if patched_file_path in files_under_test:
assert files_under_test[patched_file_path] is None
assert len(patched_file) == 1 # Should b... | Line '{}' does not match context line '{}' from patch".format(
file_lines[line_cursor], normalized_line))
line_cursor += 1
else:
assert line.line_type in (LINE_TYPE_EMPTY, LINE_TYPE_NO_NEWLINE)
def _apply_file_unidiff(patched_file, files_under_test... | 64 | 64 | 194 | 15 | 49 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _apply_file_unidiff | _apply_file_unidiff | 516 | 530 | 516 | 516 | 7da94f5f9214f6d74092c26d5a6278015880b206 | bigcode/the-stack | train |
38f68c1eb530ffcc295cba64 | train | function | def _process_deps_entries(deps_globals, child_deps_tree, child_path, deps_use_relative_paths):
"""Helper for _get_child_deps_tree"""
for dep_path_str, dep_value in deps_globals.get('deps', dict()).items():
url = _get_dep_value_url(deps_globals, dep_value)
if url is None:
continue
... | def _process_deps_entries(deps_globals, child_deps_tree, child_path, deps_use_relative_paths):
| """Helper for _get_child_deps_tree"""
for dep_path_str, dep_value in deps_globals.get('deps', dict()).items():
url = _get_dep_value_url(deps_globals, dep_value)
if url is None:
continue
dep_path = Path(dep_path_str)
if not deps_use_relative_paths:
try:
... | dep_value['url']
else:
raise NotImplementedError()
if '{' in url:
# Probably a Python format string
url = url.format(**deps_globals['vars'])
if url.count('@') != 1:
raise _PatchValidationError('Invalid number of @ symbols in URL: {}'.format(url))
return url
def _process_... | 96 | 96 | 320 | 23 | 72 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _process_deps_entries | _process_deps_entries | 179 | 204 | 179 | 179 | 8763d7393feb8252e3de07a8024d8a3019b9e8d0 | bigcode/the-stack | train |
6c2b650975f9f816155cefa0 | train | function | def _deps_var(deps_globals):
"""Return a function that implements DEPS's Var() function"""
def _var_impl(var_name):
"""Implementation of Var() in DEPS"""
return deps_globals['vars'][var_name]
return _var_impl
| def _deps_var(deps_globals):
| """Return a function that implements DEPS's Var() function"""
def _var_impl(var_name):
"""Implementation of Var() in DEPS"""
return deps_globals['vars'][var_name]
return _var_impl
| Returns True if the DEPS file passes validation; False otherwise"""
try:
_DepsNodeVisitor().visit(ast.parse(deps_text))
except _UnexpectedSyntaxError as exc:
get_logger().error('%s', exc)
return False
return True
def _deps_var(deps_globals):
| 64 | 64 | 56 | 8 | 55 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _deps_var | _deps_var | 124 | 131 | 124 | 124 | 19860a31092ee29f90f4331e1e26f9bc388c7823 | bigcode/the-stack | train |
4a0217c34cbb0ed36bd71605 | train | class | class _UnexpectedSyntaxError(RuntimeError):
"""Raised when unexpected syntax is used in DEPS"""
| class _UnexpectedSyntaxError(RuntimeError):
| """Raised when unexpected syntax is used in DEPS"""
| "requests" is required for remote'
'file downloading. It can be installed from PyPI.')
_ROOT_DIR = Path(__file__).resolve().parent.parent
_SRC_PATH = Path('src')
class _PatchValidationError(Exception):
"""Raised when patch validation fails"""
class _UnexpectedSyntaxError(RuntimeError... | 64 | 64 | 20 | 8 | 56 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _UnexpectedSyntaxError | _UnexpectedSyntaxError | 86 | 87 | 86 | 86 | 3b450ee6124e2629151be05db837e0e37ce05827 | bigcode/the-stack | train |
e2c54b4b1f861f900335659b | train | function | def _load_all_patches(series_iter, patches_dir):
"""
Returns a tuple of the following:
- boolean indicating success or failure of reading files
- dict of relative UNIX path strings to unidiff.PatchSet
"""
had_failure = False
unidiff_dict = dict()
for relative_path in series_iter:
... | def _load_all_patches(series_iter, patches_dir):
| """
Returns a tuple of the following:
- boolean indicating success or failure of reading files
- dict of relative UNIX path strings to unidiff.PatchSet
"""
had_failure = False
unidiff_dict = dict()
for relative_path in series_iter:
if relative_path in unidiff_dict:
co... | ().warning('Patch failed validation: %s', patch_path_str)
get_logger().debug(
'Specifically, file "%s" caused exception while applying:',
patched_file.path,
exc_info=True)
return True
return False
def _load_all_patches(serie... | 64 | 64 | 187 | 12 | 51 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _load_all_patches | _load_all_patches | 558 | 575 | 558 | 558 | 96ebde339af855db183ae95f293240e89284cf53 | bigcode/the-stack | train |
68cc621e8c4dd2acf1cb7812 | train | function | def _get_gitiles_commit_before_date(repo_url, target_branch, target_datetime):
"""Returns the hexadecimal hash of the closest commit before target_datetime"""
json_log_url = '{repo}/+log/{branch}?format=JSON'.format(repo=repo_url, branch=target_branch)
with _get_requests_session() as session:
respon... | def _get_gitiles_commit_before_date(repo_url, target_branch, target_datetime):
| """Returns the hexadecimal hash of the closest commit before target_datetime"""
json_log_url = '{repo}/+log/{branch}?format=JSON'.format(repo=repo_url, branch=target_branch)
with _get_requests_session() as session:
response = session.get(json_log_url)
response.raise_for_status()
git_... | .head(
'https://storage.googleapis.com/chromium-browser-official/chromium-{}.tar.xz'.format(
get_chromium_version()))
response.raise_for_status()
return email.utils.parsedate_to_datetime(response.headers['Last-Modified'])
def _get_gitiles_git_log_date(log_entry):
"""Hel... | 113 | 114 | 380 | 17 | 96 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_gitiles_commit_before_date | _get_gitiles_commit_before_date | 236 | 266 | 236 | 236 | 19edac2860b99f811d7a581cbb93ce323bdc2100 | bigcode/the-stack | train |
f23d4e2fc912881f4728b1a4 | train | function | def _get_files_under_test(args, required_files, parser):
"""
Helper for main to get files_under_test
Exits the program if --cache-remote debugging option is used
"""
if args.local:
files_under_test = _retrieve_local_files(required_files, args.local)
else: # --remote and --cache-remote
... | def _get_files_under_test(args, required_files, parser):
| """
Helper for main to get files_under_test
Exits the program if --cache-remote debugging option is used
"""
if args.local:
files_under_test = _retrieve_local_files(required_files, args.local)
else: # --remote and --cache-remote
files_under_test = _retrieve_remote_files(required... | ():
for patched_file in patch_set:
if patched_file.is_added_file:
new_files.add(patched_file.path)
elif patched_file.path not in new_files:
file_set.add(Path(patched_file.path))
return file_set
def _get_files_under_test(args, required_files, parser):
| 64 | 64 | 179 | 13 | 50 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_files_under_test | _get_files_under_test | 591 | 608 | 591 | 591 | 33dad95dd24cbea7cd391179f67bd85a3395b7c8 | bigcode/the-stack | train |
28878214135271e08272d74c | train | function | def _download_source_file(download_session, root_deps_tree, fallback_repo_manager, target_file):
"""
Downloads the source tree file from googlesource.com
download_session is an active requests.Session() object
deps_dir is a pathlib.Path to the directory containing a DEPS file.
"""
current_node,... | def _download_source_file(download_session, root_deps_tree, fallback_repo_manager, target_file):
| """
Downloads the source tree file from googlesource.com
download_session is an active requests.Session() object
deps_dir is a pathlib.Path to the directory containing a DEPS file.
"""
current_node, current_relative_path = _get_target_file_deps_node(download_session,
... |
continue
current_node = current_deps_tree[child_path]
# current_node will match with current_deps_tree after the following statement
current_deps_tree, deps_use_relative_paths = _get_child_deps_tree(
download_session, current_deps_tree, child_path, de... | 107 | 107 | 358 | 20 | 86 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _download_source_file | _download_source_file | 346 | 380 | 346 | 346 | a4e70ddad5916bc6257c17f846efd3ece89d9e51 | bigcode/the-stack | train |
24f39afabb3831872291aca3 | train | class | class _DepsNodeVisitor(ast.NodeVisitor):
_valid_syntax_types = (ast.mod, ast.expr_context, ast.boolop, ast.Assign, ast.Add, ast.Name,
ast.Dict, ast.Str, ast.NameConstant, ast.List, ast.BinOp)
_allowed_callables = ('Var', )
def visit_Call(self, node): #pylint: disable=invalid-name... | class _DepsNodeVisitor(ast.NodeVisitor):
| _valid_syntax_types = (ast.mod, ast.expr_context, ast.boolop, ast.Assign, ast.Add, ast.Name,
ast.Dict, ast.Str, ast.NameConstant, ast.List, ast.BinOp)
_allowed_callables = ('Var', )
def visit_Call(self, node): #pylint: disable=invalid-name
"""Override Call syntax handling... | Error(Exception):
"""Raised when patch validation fails"""
class _UnexpectedSyntaxError(RuntimeError):
"""Raised when unexpected syntax is used in DEPS"""
class _NotInRepoError(RuntimeError):
"""Raised when the remote file is not present in the given repo"""
class _DepsNodeVisitor(ast.NodeVisitor):
| 64 | 64 | 209 | 9 | 55 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _DepsNodeVisitor | _DepsNodeVisitor | 94 | 111 | 94 | 94 | f25d2d67749efc9d30138a6370bb85013c36f2d0 | bigcode/the-stack | train |
9df16a8ed4c2f7dd003827cf | train | function | def _download_googlesource_file(download_session, repo_url, version, relative_path):
"""
Returns the contents of the text file with path within the given
googlesource.com repo as a string.
"""
if 'googlesource.com' not in repo_url:
raise ValueError('Repository URL is not a googlesource.com U... | def _download_googlesource_file(download_session, repo_url, version, relative_path):
| """
Returns the contents of the text file with path within the given
googlesource.com repo as a string.
"""
if 'googlesource.com' not in repo_url:
raise ValueError('Repository URL is not a googlesource.com URL: {}'.format(repo_url))
full_url = repo_url + '/+/{}/{}?format=TEXT'.format(ver... | __builtins__': None}
deps_globals['Var'] = _deps_var(deps_globals)
exec(deps_text, deps_globals) #pylint: disable=exec-used
return deps_globals
def _download_googlesource_file(download_session, repo_url, version, relative_path):
| 64 | 64 | 186 | 19 | 44 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _download_googlesource_file | _download_googlesource_file | 142 | 156 | 142 | 142 | 971b6318cc995e3bafb223443a61df7b04806265 | bigcode/the-stack | train |
2b08c265fdf0a54e27274ed0 | train | function | def _get_required_files(patch_cache):
"""Returns an iterable of pathlib.Path files needed from the source tree for patching"""
new_files = set() # Files introduced by patches
file_set = set()
for patch_set in patch_cache.values():
for patched_file in patch_set:
if patched_file.is_add... | def _get_required_files(patch_cache):
| """Returns an iterable of pathlib.Path files needed from the source tree for patching"""
new_files = set() # Files introduced by patches
file_set = set()
for patch_set in patch_cache.values():
for patched_file in patch_set:
if patched_file.is_added_file:
new_files.add... | _text(encoding=ENCODING).endswith('\n'):
had_failure = True
get_logger().warning('Patch file does not end with newline: %s',
str(patches_dir / relative_path))
return had_failure, unidiff_dict
def _get_required_files(patch_cache):
| 64 | 64 | 104 | 9 | 54 | nikolowry/ungoogled-chromium | devutils/validate_patches.py | Python | _get_required_files | _get_required_files | 578 | 588 | 578 | 578 | c3800f2dc636915492cb39e127d2313ecd98a1ea | bigcode/the-stack | train |
b5ad8993ef89105abb0eed77 | train | function | def checkpoint_paths(path, pattern=r'checkpoint(\d+)\.pt'):
"""Retrieves all checkpoints found in `path` directory.
Checkpoints are identified by matching filename to the specified pattern. If
the pattern contains groups, the result will be sorted by the first group in
descending order.
"""
pt_... | def checkpoint_paths(path, pattern=r'checkpoint(\d+)\.pt'):
| """Retrieves all checkpoints found in `path` directory.
Checkpoints are identified by matching filename to the specified pattern. If
the pattern contains groups, the result will be sorted by the first group in
descending order.
"""
pt_regexp = re.compile(pattern)
files = os.listdir(path)
... | None:
task = tasks.setup_task(args)
# build model for ensemble
model = task.build_model(args)
model.load_state_dict(state['model'], strict=True)
ensemble.append(model)
return ensemble, args
def checkpoint_paths(path, pattern=r'checkpoint(\d+)\.pt'):
| 64 | 64 | 165 | 16 | 47 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | checkpoint_paths | checkpoint_paths | 163 | 179 | 163 | 163 | 6a21ddce61604cd6d3a6dc796606da9842b1d4af | bigcode/the-stack | train |
0cc721fbd990a2c7431e6ec1 | train | function | def convert_state_dict_type(state_dict, ttype=torch.FloatTensor):
if isinstance(state_dict, dict):
cpu_dict = OrderedDict()
for k, v in state_dict.items():
cpu_dict[k] = convert_state_dict_type(v)
return cpu_dict
elif isinstance(state_dict, list):
return [convert_stat... | def convert_state_dict_type(state_dict, ttype=torch.FloatTensor):
| if isinstance(state_dict, dict):
cpu_dict = OrderedDict()
for k, v in state_dict.items():
cpu_dict[k] = convert_state_dict_type(v)
return cpu_dict
elif isinstance(state_dict, list):
return [convert_state_dict_type(v) for v in state_dict]
elif torch.is_tensor(state... | torch_persistent_save(*args, **kwargs):
for i in range(3):
try:
return torch.save(*args, **kwargs)
except Exception:
if i == 2:
logging.error(traceback.format_exc())
def convert_state_dict_type(state_dict, ttype=torch.FloatTensor):
| 64 | 64 | 103 | 14 | 50 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | convert_state_dict_type | convert_state_dict_type | 191 | 202 | 191 | 191 | 0b8588c216fd019373e6f170f0dd73e7087e20e0 | bigcode/the-stack | train |
ef4b74b315a316be331451c5 | train | function | def load_checkpoint_to_cpu(path):
"""Loads a checkpoint to CPU (with upgrading for backward compatibility)."""
state = torch.load(
path, map_location=lambda s, l: default_restore_location(s, 'cpu'),
)
state = _upgrade_state_dict(state)
return state
| def load_checkpoint_to_cpu(path):
| """Loads a checkpoint to CPU (with upgrading for backward compatibility)."""
state = torch.load(
path, map_location=lambda s, l: default_restore_location(s, 'cpu'),
)
state = _upgrade_state_dict(state)
return state
| itr_state = extra_state['train_iterator']
epoch_itr = trainer.get_train_iterator(epoch=itr_state['epoch'])
epoch_itr.load_state_dict(itr_state)
else:
epoch_itr = trainer.get_train_iterator(epoch=0)
return extra_state, epoch_itr
def load_checkpoint_to_cpu(path):
| 64 | 64 | 61 | 7 | 56 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | load_checkpoint_to_cpu | load_checkpoint_to_cpu | 123 | 129 | 123 | 123 | 32ebdae5d8ceb61f43ce616e372f206804c53c54 | bigcode/the-stack | train |
15f9f72486dd628f1e7488b6 | train | function | def _upgrade_state_dict(state):
"""Helper for upgrading old model checkpoints."""
# add optimizer_history
if 'optimizer_history' not in state:
state['optimizer_history'] = [
{
'criterion_name': 'CrossEntropyCriterion',
'best_loss': state['best_loss'],
... | def _upgrade_state_dict(state):
| """Helper for upgrading old model checkpoints."""
# add optimizer_history
if 'optimizer_history' not in state:
state['optimizer_history'] = [
{
'criterion_name': 'CrossEntropyCriterion',
'best_loss': state['best_loss'],
},
]
sta... | num_updates, optim_history=None, extra_state=None,
):
if optim_history is None:
optim_history = []
if extra_state is None:
extra_state = {}
state_dict = {
'args': args,
'model': model_state_dict if model_state_dict else {},
'optimizer_history': optim_history + [
... | 159 | 159 | 533 | 7 | 152 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | _upgrade_state_dict | _upgrade_state_dict | 230 | 280 | 230 | 230 | df42644985b1331dff5c362346c39701b8f46043 | bigcode/the-stack | train |
7e1a3a11d5215976c916454a | train | function | def save_checkpoint(args, trainer, epoch_itr, val_loss):
if args.no_save or not distributed_utils.is_master(args):
return
write_timer = StopwatchMeter()
write_timer.start()
epoch = epoch_itr.epoch
end_of_epoch = epoch_itr.end_of_epoch()
updates = trainer.get_num_updates()
checkpoi... | def save_checkpoint(args, trainer, epoch_itr, val_loss):
| if args.no_save or not distributed_utils.is_master(args):
return
write_timer = StopwatchMeter()
write_timer.start()
epoch = epoch_itr.epoch
end_of_epoch = epoch_itr.end_of_epoch()
updates = trainer.get_num_updates()
checkpoint_conds = collections.OrderedDict()
checkpoint_conds... | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
from collections import OrderedDic... | 150 | 171 | 572 | 13 | 136 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | save_checkpoint | save_checkpoint | 25 | 87 | 25 | 25 | bf1b650e11604c9df6a255631888c04d8bc7faed | bigcode/the-stack | train |
f6848d7ef35acbcb5a6a64bf | train | function | def torch_persistent_save(*args, **kwargs):
for i in range(3):
try:
return torch.save(*args, **kwargs)
except Exception:
if i == 2:
logging.error(traceback.format_exc())
| def torch_persistent_save(*args, **kwargs):
| for i in range(3):
try:
return torch.save(*args, **kwargs)
except Exception:
if i == 2:
logging.error(traceback.format_exc())
| idx = int(m.group(1)) if len(m.groups()) > 0 else i
entries.append((idx, m.group(0)))
return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)]
def torch_persistent_save(*args, **kwargs):
| 63 | 64 | 51 | 11 | 52 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | torch_persistent_save | torch_persistent_save | 182 | 188 | 182 | 182 | a0260a5eda56ce18eb19282b96f01d3c91553e76 | bigcode/the-stack | train |
344d401907c3d387e6a6a78c | train | function | def load_model_ensemble(filenames, arg_overrides=None, task=None):
"""Loads an ensemble of models.
Args:
filenames (List[str]): checkpoint files to load
arg_overrides (Dict[str,Any], optional): override model args that
were used during model training
task (fairseq.tasks.Fair... | def load_model_ensemble(filenames, arg_overrides=None, task=None):
| """Loads an ensemble of models.
Args:
filenames (List[str]): checkpoint files to load
arg_overrides (Dict[str,Any], optional): override model args that
were used during model training
task (fairseq.tasks.FairseqTask, optional): task to use for loading
"""
ensemble = ... | CPU (with upgrading for backward compatibility)."""
state = torch.load(
path, map_location=lambda s, l: default_restore_location(s, 'cpu'),
)
state = _upgrade_state_dict(state)
return state
def load_model_ensemble(filenames, arg_overrides=None, task=None):
| 64 | 64 | 214 | 16 | 47 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | load_model_ensemble | load_model_ensemble | 132 | 160 | 132 | 132 | e5b2bdd40e22c300a86e9a86195fbd90ecde7f02 | bigcode/the-stack | train |
56d36714ecd20d1d83ec8780 | train | function | def load_pretrained_component_from_model(
component: Union[FairseqEncoder, FairseqDecoder], checkpoint: str
):
"""
Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the
provided `component` object. If state_dict fails to load, there may be a
mismatch in the architecture of the ... | def load_pretrained_component_from_model(
component: Union[FairseqEncoder, FairseqDecoder], checkpoint: str
):
| """
Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the
provided `component` object. If state_dict fails to load, there may be a
mismatch in the architecture of the corresponding `component` found in the
`checkpoint` file.
"""
if not os.path.exists(checkpoint):
... | train_iterator' not in state['extra_state']:
state['extra_state']['train_iterator'] = {
'epoch': state['extra_state']['epoch'],
'iterations_in_epoch': state['extra_state'].get('batch_offset', 0),
}
return state
def load_pretrained_component_from_model(
component: Union[Fa... | 83 | 83 | 279 | 26 | 56 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | load_pretrained_component_from_model | load_pretrained_component_from_model | 283 | 311 | 283 | 285 | 2996897d480465ce74b865376133212c33e33cbe | bigcode/the-stack | train |
e4aef8393ce9aa6badc4836d | train | function | def load_checkpoint(args, trainer):
"""Load a checkpoint and restore the training iterator."""
# only one worker should attempt to create the required dir
if args.distributed_rank == 0:
os.makedirs(args.save_dir, exist_ok=True)
if os.path.isabs(args.restore_file):
checkpoint_path = args... | def load_checkpoint(args, trainer):
| """Load a checkpoint and restore the training iterator."""
# only one worker should attempt to create the required dir
if args.distributed_rank == 0:
os.makedirs(args.save_dir, exist_ok=True)
if os.path.isabs(args.restore_file):
checkpoint_path = args.restore_file
else:
chec... | epoch checkpoints; checkpoints are sorted in descending order
checkpoints = checkpoint_paths(
args.save_dir, pattern=r'checkpoint(\d+)\.pt',
)
for old_chk in checkpoints[args.keep_last_epochs:]:
if os.path.lexists(old_chk):
os.remove(old_chk)
def load_che... | 69 | 69 | 232 | 7 | 62 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | load_checkpoint | load_checkpoint | 90 | 120 | 90 | 90 | 16edddb8de0ca3a93ba76ab15f96e051644056e3 | bigcode/the-stack | train |
17df9c3c73377ba1daff5a71 | train | function | def save_state(
filename, args, model_state_dict, criterion, optimizer, lr_scheduler,
num_updates, optim_history=None, extra_state=None,
):
if optim_history is None:
optim_history = []
if extra_state is None:
extra_state = {}
state_dict = {
'args': args,
'model': mode... | def save_state(
filename, args, model_state_dict, criterion, optimizer, lr_scheduler,
num_updates, optim_history=None, extra_state=None,
):
| if optim_history is None:
optim_history = []
if extra_state is None:
extra_state = {}
state_dict = {
'args': args,
'model': model_state_dict if model_state_dict else {},
'optimizer_history': optim_history + [
{
'criterion_name': criterion._... | ) for v in state_dict]
elif torch.is_tensor(state_dict):
return state_dict.type(ttype)
else:
return state_dict
def save_state(
filename, args, model_state_dict, criterion, optimizer, lr_scheduler,
num_updates, optim_history=None, extra_state=None,
):
| 64 | 64 | 172 | 33 | 30 | aishikchakraborty/fairseq-synsem | fairseq/checkpoint_utils.py | Python | save_state | save_state | 205 | 227 | 205 | 208 | bd17fc87fb0bc26a7a64e5166fcb615baede2e51 | bigcode/the-stack | train |
519447a75fb47c92047354c3 | train | function | def get_accuracy(dict, b, m, s, d):
count = 0
for i in range(len(b)):
if dict['bcateid'][i].index(1) == b[i]:
count += 1
ret_b = count / len(b)
count = 0
for i in range(len(m)):
if dict['mcateid'][i].index(1) == m[i]:
count += 1
ret_m = count / len(m... | def get_accuracy(dict, b, m, s, d):
| count = 0
for i in range(len(b)):
if dict['bcateid'][i].index(1) == b[i]:
count += 1
ret_b = count / len(b)
count = 0
for i in range(len(m)):
if dict['mcateid'][i].index(1) == m[i]:
count += 1
ret_m = count / len(m)
count = 0
for i in range(... | # -*- coding:utf-8 -*-
import numpy as np
import tensorflow as tf
import config
import json
import os
def get_accuracy(dict, b, m, s, d):
| 39 | 82 | 276 | 13 | 25 | Maxpridy/Team-Shrug | util.py | Python | get_accuracy | get_accuracy | 10 | 38 | 10 | 10 | fc25dfbf3df301aeec8309b0a417cf98cf9664c1 | bigcode/the-stack | train |
1ac72ddd99e97725b2ff5e9d | train | function | def make_label_weights(dict, b_weight=1., m_weight=1.2, s_weight=1.3, d_weight=1.4):
batch_labels = np.array(
[np.argmax(dict[target], 1) for target in ['bcateid', 'mcateid', 'scateid', 'dcateid']]).astype('float32').T
_label_weight = batch_labels.copy()
_label_weight[:, 2:][_label_weight[:, 2:... | def make_label_weights(dict, b_weight=1., m_weight=1.2, s_weight=1.3, d_weight=1.4):
| batch_labels = np.array(
[np.argmax(dict[target], 1) for target in ['bcateid', 'mcateid', 'scateid', 'dcateid']]).astype('float32').T
_label_weight = batch_labels.copy()
_label_weight[:, 2:][_label_weight[:, 2:] != 0] = 1.
_label_weight[:, 0] = b_weight
_label_weight[:, 1] = m_weight
... | + 0.0000001
ret_d = count / len_d
return [ret_b, ret_m, ret_s, ret_d]
def make_label_weights(dict, b_weight=1., m_weight=1.2, s_weight=1.3, d_weight=1.4):
| 64 | 64 | 166 | 32 | 32 | Maxpridy/Team-Shrug | util.py | Python | make_label_weights | make_label_weights | 40 | 51 | 40 | 40 | 70c25741adaecea9d3d5e58d2e543b3967f20d3d | bigcode/the-stack | train |
0094c95952fa701cca2ccd1f | train | function | def multi(n): return sum(x for x in range(1,n) if x%3==0 or x%5==0) if n>1 else 0
| def multi(n): | return sum(x for x in range(1,n) if x%3==0 or x%5==0) if n>1 else 0
| def multi(n): | 5 | 64 | 36 | 5 | 0 | git-bit-code/competetive_coding | codewars/multipleOf3or5.py | Python | multi | multi | 1 | 1 | 1 | 1 | 7c995991019c1363a55adce3d89b5d4f96a85f3f | bigcode/the-stack | train |
24826d48b2c2b8f5eeeb9c86 | train | function | def identity(module, name):
r"""Applies pruning reparametrization to the tensor corresponding to the
parameter called ``name`` in ``module`` without actually pruning any
units. Modifies module in place (and also return the modified module)
by:
1) adding a named buffer called ``name+'_mask'`` corresp... | def identity(module, name):
| r"""Applies pruning reparametrization to the tensor corresponding to the
parameter called ``name`` in ``module`` without actually pruning any
units. Modifies module in place (and also return the modified module)
by:
1) adding a named buffer called ``name+'_mask'`` corresponding to the
binary mas... | in terms of the original tensor
and the pruning mask.
Args:
module (nn.Module): module containing the tensor to prune
name (str): parameter name within ``module`` on which pruning
will act.
"""
return super(CustomFromMask, cls).apply(
... | 76 | 76 | 255 | 6 | 70 | wenhaopeter/read_pytorch_code | torch/nn/utils/prune.py | Python | identity | identity | 793 | 821 | 793 | 793 | 958cd0e03ab3359c026016f67df4f53456435e7a | bigcode/the-stack | train |
a676cea9a3c00074d5ec978c | train | function | def is_pruned(module):
r"""Check whether ``module`` is pruned by looking for
``forward_pre_hooks`` in its modules that inherit from the
:class:`BasePruningMethod`.
Args:
module (nn.Module): object that is either pruned or unpruned
Returns:
binary answer to whether ``module`` is pru... | def is_pruned(module):
| r"""Check whether ``module`` is pruned by looking for
``forward_pre_hooks`` in its modules that inherit from the
:class:`BasePruningMethod`.
Args:
module (nn.Module): object that is either pruned or unpruned
Returns:
binary answer to whether ``module`` is pruned.
Examples:
... | hook._tensor_name == name:
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError(
"Parameter '{}' of module {} has to be pruned "
"before pruning can be removed".format(name, module)
)
def is_pruned(module):
| 64 | 64 | 182 | 6 | 58 | wenhaopeter/read_pytorch_code | torch/nn/utils/prune.py | Python | is_pruned | is_pruned | 1,131 | 1,154 | 1,131 | 1,131 | 92b1e69e2711d43c6376a7b7ca1a3e1919801e92 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.