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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0a46f422cfcab4741e70cd7c | train | function | def host_to_ips(host):
'''
Returns a list of IP addresses of a given hostname or None if not found.
'''
ips = []
try:
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):
if family == socket.AF_INE... | def host_to_ips(host):
| '''
Returns a list of IP addresses of a given hostname or None if not found.
'''
ips = []
try:
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):
if family == socket.AF_INET:
ip, ... | Return status of a port
'''
if not 1 <= int(port) <= 65535:
return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
out = sock.connect_ex((sanitize_host(host), int(port)))
return out
def host_to_ips(host):
| 64 | 64 | 134 | 6 | 57 | hvnsweeting/salt | salt/utils/network.py | Python | host_to_ips | host_to_ips | 58 | 75 | 58 | 58 | 07e4895266a9e2f8d436bb11835d91ffc7313e8b | bigcode/the-stack | train |
2ab1f377dc2eb2bfddf2ad3d | train | function | def subnets(interfaces=None):
'''
Returns a list of IPv4 subnets to which the host belongs
'''
return _subnets('inet', interfaces_=interfaces)
| def subnets(interfaces=None):
| '''
Returns a list of IPv4 subnets to which the host belongs
'''
return _subnets('inet', interfaces_=interfaces)
| in addrs:
intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet]))
if not intf.is_loopback:
ret.add(intf.network)
return [str(net) for net in sorted(ret)]
def subnets(interfaces=None):
| 63 | 64 | 38 | 7 | 56 | hvnsweeting/salt | salt/utils/network.py | Python | subnets | subnets | 761 | 765 | 761 | 761 | f938dd96a8fea3ad51591b8649be4c6264c14825 | bigcode/the-stack | train |
e2faa0b1b4e172b1b822390d | train | function | def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
'''
Return a socket object for the addr
IP-version agnostic
'''
version = ipaddress.ip_address(addr).version
if version == 4:
family = socket.AF_INET
elif version == 6:
family = socket.AF_INET6
return socket.socket(... | def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
| '''
Return a socket object for the addr
IP-version agnostic
'''
version = ipaddress.ip_address(addr).version
if version == 4:
family = socket.AF_INET
elif version == 6:
family = socket.AF_INET6
return socket.socket(family, type, proto)
| _address(addr).is_loopback])
def generate_minion_id():
'''
Return only first element of the hostname from all possible list.
:return:
'''
return _generate_minion_id().first() or 'localhost'
def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
| 64 | 64 | 86 | 16 | 48 | hvnsweeting/salt | salt/utils/network.py | Python | get_socket | get_socket | 152 | 163 | 152 | 152 | 21173a2b47b520afdae7de2b0b39867908c2bdb6 | bigcode/the-stack | train |
de2f5024b0c5d98fbfe26814 | train | function | def sanitize_host(host):
'''
Sanitize host string.
'''
return ''.join([
c for c in host[0:255] if c in (ascii_letters + digits + '.-')
])
| def sanitize_host(host):
| '''
Sanitize host string.
'''
return ''.join([
c for c in host[0:255] if c in (ascii_letters + digits + '.-')
])
| wmi
try:
import wmi
import salt.utils.winapi
except ImportError:
pass
# Import salt libs
import salt.utils
from salt._compat import subprocess, ipaddress
log = logging.getLogger(__name__)
# pylint: disable=C0103
def sanitize_host(host):
| 64 | 64 | 45 | 5 | 58 | hvnsweeting/salt | salt/utils/network.py | Python | sanitize_host | sanitize_host | 35 | 41 | 35 | 35 | a389525c4ccd5976aaeadc6964fe2ea929fa3010 | bigcode/the-stack | train |
23001236cfa5e8a40d0bbd6e | train | function | def get_net_start(ipaddr, netmask):
'''
Return the address of the network
'''
net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False)
return str(net.network_address)
| def get_net_start(ipaddr, netmask):
| '''
Return the address of the network
'''
net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False)
return str(net.network_address)
| .Description]['up'] = False
return ifaces
def interfaces():
'''
Return a dictionary of information about all the interfaces on the minion
'''
if salt.utils.is_windows():
return win_interfaces()
else:
return linux_interfaces()
def get_net_start(ipaddr, netmask):
| 64 | 64 | 51 | 10 | 54 | hvnsweeting/salt | salt/utils/network.py | Python | get_net_start | get_net_start | 635 | 640 | 635 | 635 | e9490877a9b23c8e4439244bdcf7906eacbed568 | bigcode/the-stack | train |
32dacacd8c71262c30f88633 | train | function | def cidr_to_ipv4_netmask(cidr_bits):
'''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
i... | def cidr_to_ipv4_netmask(cidr_bits):
| '''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
if cidr_bits >= 8:
netmask... | .168.3.0'
'10.209' -> '10.209.0.0'
'''
return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0,
4))
def cidr_to_ipv4_netmask(cidr_bits):
| 64 | 64 | 146 | 12 | 52 | hvnsweeting/salt | salt/utils/network.py | Python | cidr_to_ipv4_netmask | cidr_to_ipv4_netmask | 259 | 280 | 259 | 259 | d6b3fc9f7136fca1385b86fcff3c14dbb6edd99b | bigcode/the-stack | train |
7054aacd7c6abb175b98592d | train | function | def _netbsd_remotes_on(port, which_end):
'''
Returns set of ipv4 host addresses of remote established connections
on local tcp port port.
Parses output of shell 'sockstat' (NetBSD)
to get connections
$ sudo sockstat -4
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS... | def _netbsd_remotes_on(port, which_end):
| '''
Returns set of ipv4 host addresses of remote established connections
on local tcp port port.
Parses output of shell 'sockstat' (NetBSD)
to get connections
$ sudo sockstat -4
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
root python2.7 1456 29 tcp4... | 37', 'tcp4',
# '127.0.0.1:4505-', '127.0.0.1:55703']
# print chunks
if 'COMMAND' in chunks[1]:
continue # ignore header
if len(chunks) < 2:
continue
local = chunks[5]
remote = chunks[6]
lhost, lport = local.split(':')
rhost, rport... | 184 | 184 | 614 | 12 | 171 | hvnsweeting/salt | salt/utils/network.py | Python | _netbsd_remotes_on | _netbsd_remotes_on | 1,080 | 1,136 | 1,080 | 1,080 | 50b89d461e63ba86edd3dda98f84262dec4ff07e | bigcode/the-stack | train |
df6cf296172d64c0600bdb0a | train | function | def ip_addrs(interface=None, include_loopback=False, interface_data=None):
'''
Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is
ignored, unless 'include_loopback=True' is indicated. If 'interface' is
provided, then only IP addresses from that interface will be returned.
'''
re... | def ip_addrs(interface=None, include_loopback=False, interface_data=None):
| '''
Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is
ignored, unless 'include_loopback=True' is indicated. If 'interface' is
provided, then only IP addresses from that interface will be returned.
'''
return _ip_addrs(interface, include_loopback, interface_data, 'inet')
| for addr in addrs:
addr = ipaddress.ip_address(addr.get('address'))
if not addr.is_loopback or include_loopback:
ret.add(addr)
return [str(addr) for addr in sorted(ret)]
def ip_addrs(interface=None, include_loopback=False, interface_data=None):
| 63 | 64 | 94 | 16 | 47 | hvnsweeting/salt | salt/utils/network.py | Python | ip_addrs | ip_addrs | 826 | 832 | 826 | 826 | e3a9a5f0bd0344151d6dd7e6795d982af1e9c3c1 | bigcode/the-stack | train |
0673f9e943a2d49ccedbffa7 | train | function | def _get_iface_info(iface):
'''
If `iface` is available, return interface info and no error, otherwise
return no info and log and return an error
'''
iface_info = interfaces()
if iface in iface_info.keys():
return iface_info, False
else:
error_msg = ('Interface "{0}" not in ... | def _get_iface_info(iface):
| '''
If `iface` is available, return interface info and no error, otherwise
return no info and log and return an error
'''
iface_info = interfaces()
if iface in iface_info.keys():
return iface_info, False
else:
error_msg = ('Interface "{0}" not in available interfaces: "{1}"'... | _to_bits(ipaddr):
'''
Accepts an IPv4 dotted quad and returns a string representing its binary
counterpart
'''
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
def _get_iface_info(iface):
| 63 | 64 | 111 | 8 | 55 | hvnsweeting/salt | salt/utils/network.py | Python | _get_iface_info | _get_iface_info | 674 | 687 | 674 | 674 | c17795ea6a361efecfd488f724c9fcf74353fd72 | bigcode/the-stack | train |
834edbcd3c1fc20607e91f5a | train | function | def _openbsd_remotes_on(port, which_end):
'''
OpenBSD specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
$ netstat -nf inet
Active Internet connections
Proto R... | def _openbsd_remotes_on(port, which_end):
| '''
OpenBSD specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
$ netstat -nf inet
Active Internet connections
Proto Recv-Q Send-Q Local Address Forei... | ].split('.')
rport = remote.pop()
rhost = '.'.join(remote)
if which_end == 'local' and int(lport) != port: # ignore if local port not port
continue
if which_end == 'remote' and int(rport) != port: # ignore if remote port not port
continue
remotes.add(rh... | 100 | 100 | 336 | 12 | 87 | hvnsweeting/salt | salt/utils/network.py | Python | _openbsd_remotes_on | _openbsd_remotes_on | 1,139 | 1,173 | 1,139 | 1,139 | e84abdb1ff0409b95ad23bf27215ed5adb24c186 | bigcode/the-stack | train |
2c657906f90106d8c2793426 | train | function | def _generate_minion_id():
'''
Get list of possible host names and convention names.
:return:
'''
# There are three types of hostnames:
# 1. Network names. How host is accessed from the network.
# 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts)
... | def _generate_minion_id():
| '''
Get list of possible host names and convention names.
:return:
'''
# There are three types of hostnames:
# 1. Network names. How host is accessed from the network.
# 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts)
# 3. Convention names, a... | Return status of a port
'''
if not 1 <= int(port) <= 65535:
return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
out = sock.connect_ex((sanitize_host(host), int(port)))
return out
def host_to_ips(host):
'''
Returns a list of IP addresses of a given hostname or ... | 199 | 199 | 665 | 7 | 191 | hvnsweeting/salt | salt/utils/network.py | Python | _generate_minion_id | _generate_minion_id | 78 | 140 | 78 | 78 | b3e9a9bdf6fc133d5d2828e8eea3a49b89dcf7b6 | bigcode/the-stack | train |
1a1f054fe5aa1b4c0a22d2ee | train | function | def _interfaces_ifconfig(out):
'''
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]... | def _interfaces_ifconfig(out):
| '''
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
if salt.utils.is_sunos... | address'] = ipaddr
addr_obj['netmask'] = netmask
addr_obj['broadcast'] = broadcast
addr_obj['label'] = iflabel
data['inet'].append(addr_obj)
elif type_ == 'inet6':
... | 256 | 256 | 1,154 | 7 | 248 | hvnsweeting/salt | salt/utils/network.py | Python | _interfaces_ifconfig | _interfaces_ifconfig | 401 | 494 | 401 | 401 | af91dfd382d1ac055c05aff81b1fcbdf96c2d94d | bigcode/the-stack | train |
e8be939bd60627fa5300f3d6 | train | class | class Migration(migrations.Migration):
dependencies = [
('projectmanager', '0046_auto_20201008_2133'),
]
operations = [
migrations.RemoveField(
model_name='materialcategory',
name='parent',
),
migrations.RemoveField(
model_name='project',... | class Migration(migrations.Migration):
| dependencies = [
('projectmanager', '0046_auto_20201008_2133'),
]
operations = [
migrations.RemoveField(
model_name='materialcategory',
name='parent',
),
migrations.RemoveField(
model_name='project',
name='location',
),... | # Generated by Django 3.1 on 2020-10-08 19:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 43 | 65 | 217 | 7 | 35 | leonolan2020/phoenix | projectmanager/migrations/0047_auto_20201008_2245.py | Python | Migration | Migration | 7 | 40 | 7 | 8 | 0c1be7e5a9b55344bc847719c4a700561a159986 | bigcode/the-stack | train |
502b96ab16c63ae50769540b | train | class | class TestDatetime64Timezone(_DeprecationTestCase):
"""Parsing of datetime64 with timezones deprecated in 1.11.0, because
datetime64 is now timezone naive rather than UTC only.
It will be quite a while before we can remove this, because, at the very
least, a lot of existing code uses the 'Z' modifier t... | class TestDatetime64Timezone(_DeprecationTestCase):
| """Parsing of datetime64 with timezones deprecated in 1.11.0, because
datetime64 is now timezone naive rather than UTC only.
It will be quite a while before we can remove this, because, at the very
least, a lot of existing code uses the 'Z' modifier to avoid conversion
from local time to UTC, even ... | () as l:
warnings.filterwarnings("always")
assert_raises(TypeError, f, arg1, arg2)
assert_(not l)
else:
# py2
assert_warns(DeprecationWarning, f, arg1, arg2)
class Test... | 70 | 70 | 236 | 12 | 58 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestDatetime64Timezone | TestDatetime64Timezone | 243 | 261 | 243 | 243 | 6a5270209833aeca5b93640140e6a4bf1008e4d6 | bigcode/the-stack | train |
4e74372418bb6845b6ef9e00 | train | class | class _VisibleDeprecationTestCase(_DeprecationTestCase):
warning_cls = np.VisibleDeprecationWarning
| class _VisibleDeprecationTestCase(_DeprecationTestCase):
| warning_cls = np.VisibleDeprecationWarning
| 0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
"""
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
class _VisibleDeprecationTestCase(_DeprecationTestCase):
| 64 | 64 | 26 | 15 | 49 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | _VisibleDeprecationTestCase | _VisibleDeprecationTestCase | 136 | 137 | 136 | 136 | 2a8d3649493a63f0a23da710a835966bccbe39dc | bigcode/the-stack | train |
aa8d72fdd4f970952edbf790 | train | class | class TestShape1Fields(_DeprecationTestCase):
warning_cls = FutureWarning
# 2019-05-20, 1.17.0
def test_shape_1_fields(self):
self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
| class TestShape1Fields(_DeprecationTestCase):
| warning_cls = FutureWarning
# 2019-05-20, 1.17.0
def test_shape_1_fields(self):
self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
| , num=2)
# empty kwargs prevents any state actually changing which would break
# other tests.
self.assert_deprecated(np.set_numeric_ops, kwargs={})
assert_raises(ValueError, np.set_numeric_ops, add='abc')
class TestShape1Fields(_DeprecationTestCase):
| 64 | 64 | 65 | 12 | 52 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestShape1Fields | TestShape1Fields | 558 | 563 | 558 | 558 | 3b8d32a29d6365d92b1bae3866dff09784f20cb2 | bigcode/the-stack | train |
1eaaeed0eeb2279d136a88ae | train | class | class TestPyArray_AS1D(_DeprecationTestCase):
def test_npy_pyarrayas1d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
| class TestPyArray_AS1D(_DeprecationTestCase):
| def test_npy_pyarrayas1d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
| def test_npy_char_deprecation(self):
from numpy.core._multiarray_tests import npy_char_deprecation
self.assert_deprecated(npy_char_deprecation)
assert_(npy_char_deprecation() == 'S1')
class TestPyArray_AS1D(_DeprecationTestCase):
| 64 | 64 | 65 | 14 | 50 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestPyArray_AS1D | TestPyArray_AS1D | 403 | 406 | 403 | 403 | 95674f3b4d05f15e15675dec39e5687dec352d11 | bigcode/the-stack | train |
ce1cd2a1f10589b26ebf1d61 | train | class | class TestClassicIntDivision(_DeprecationTestCase):
"""
See #7949. Deprecate the numeric-style dtypes with -3 flag in python 2
if used for division
List of data types: https://docs.scipy.org/doc/numpy/user/basics.types.html
"""
def test_int_dtypes(self):
#scramble types and do some mix a... | class TestClassicIntDivision(_DeprecationTestCase):
| """
See #7949. Deprecate the numeric-style dtypes with -3 flag in python 2
if used for division
List of data types: https://docs.scipy.org/doc/numpy/user/basics.types.html
"""
def test_int_dtypes(self):
#scramble types and do some mix and match testing
deprecated_types = [
... | assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
def foo():
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
test_case_instance.assert_deprecated(foo)
test_case_instance.teardown()
c... | 71 | 71 | 237 | 12 | 59 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestClassicIntDivision | TestClassicIntDivision | 360 | 379 | 360 | 360 | 8f7085f7278e18c4e3bcc520946b076f6e4a6d23 | bigcode/the-stack | train |
6434075ffcc15125e9c33685 | train | class | class TestNonTupleNDIndexDeprecation(object):
def test_basic(self):
a = np.zeros((5, 5))
with warnings.catch_warnings():
warnings.filterwarnings('always')
assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_warns(FutureWarning, a.__getitem__, [slic... | class TestNonTupleNDIndexDeprecation(object):
| def test_basic(self):
a = np.zeros((5, 5))
with warnings.catch_warnings():
warnings.filterwarnings('always')
assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_warns(FutureWarning, a.__getitem__, [slice(None)])
warnings.filterwarnings... | self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
class _VisibleDeprecationTestCase(_DeprecationTestCase):
warning_cls = np.VisibleDeprecationWarning
class TestNonTupleNDIndexDeprecation(object):
| 64 | 64 | 158 | 11 | 52 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNonTupleNDIndexDeprecation | TestNonTupleNDIndexDeprecation | 140 | 153 | 140 | 140 | 4bab385b8fbfe241b9f78e9e46170329b19b03b3 | bigcode/the-stack | train |
38e4fb1c43398812cf22e66c | train | class | class TestNumericStyleTypecodes(_DeprecationTestCase):
"""
Deprecate the old numeric-style dtypes, which are especially
confusing for complex types, e.g. Complex32 -> complex64. When the
deprecation cycle is complete, the check for the strings should be
removed from PyArray_DescrConverter in descrip... | class TestNumericStyleTypecodes(_DeprecationTestCase):
| """
Deprecate the old numeric-style dtypes, which are especially
confusing for complex types, e.g. Complex32 -> complex64. When the
deprecation cycle is complete, the check for the strings should be
removed from PyArray_DescrConverter in descriptor.c, and the
deprecated keys should not be added ... | _negative(self):
args = (-5,)
kwargs = {'width': 2}
self.message = ("Insufficient bit width provided. This behavior "
"will raise an error in the future.")
self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
class TestNumericStyleTypecodes(_Deprecati... | 71 | 71 | 238 | 13 | 58 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNumericStyleTypecodes | TestNumericStyleTypecodes | 322 | 342 | 322 | 322 | e39cc20ce609a52dcc5bc809a7e1603ef4c52e36 | bigcode/the-stack | train |
9edb595476f5e6d9236631ba | train | class | class TestNonNumericConjugate(_DeprecationTestCase):
"""
Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,
which conflicts with the error behavior of np.conjugate.
"""
def test_conjugate(self):
for a in np.array(5), np.array(5j):
self.assert_not_deprecated(a.co... | class TestNonNumericConjugate(_DeprecationTestCase):
| """
Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,
which conflicts with the error behavior of np.conjugate.
"""
def test_conjugate(self):
for a in np.array(5), np.array(5j):
self.assert_not_deprecated(a.conjugate)
for a in (np.array('s'), np.array('2... | .array([1,2,3], dtype=dt1)
b = np.array([1,2,3], dtype=dt2)
self.assert_deprecated(op.div, args=(a,b))
dt2 = dt1
class TestNonNumericConjugate(_DeprecationTestCase):
| 64 | 64 | 133 | 14 | 49 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNonNumericConjugate | TestNonNumericConjugate | 382 | 392 | 382 | 382 | 27b3dce161295a1d32deaeb0123bb9a863c52958 | bigcode/the-stack | train |
83ece95e9a216298e9e38288 | train | class | class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
| class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
| def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
| .sctypeNA['?'])
self.assert_deprecated(lambda: np.typeNA['?'])
self.assert_deprecated(lambda: np.typeNA.get('?'))
class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
| 63 | 64 | 56 | 31 | 32 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestPositiveOnNonNumerical | TestPositiveOnNonNumerical | 482 | 485 | 482 | 483 | 1eb2342ade38033646afb5d6402df3b2c8bd5004 | bigcode/the-stack | train |
9033ba6cac7683deec60166b | train | class | class TestComparisonDeprecations(_DeprecationTestCase):
"""This tests the deprecation, for non-element-wise comparison logic.
This used to mean that when an error occurred during element-wise comparison
(i.e. broadcasting) NotImplemented was returned, but also in the comparison
itself, False was given i... | class TestComparisonDeprecations(_DeprecationTestCase):
| """This tests the deprecation, for non-element-wise comparison logic.
This used to mean that when an error occurred during element-wise comparison
(i.e. broadcasting) NotImplemented was returned, but also in the comparison
itself, False was given instead of the error.
Also test FutureWarning for th... | self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
"""
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
class _VisibleDeprecationTestC... | 255 | 256 | 929 | 13 | 242 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestComparisonDeprecations | TestComparisonDeprecations | 156 | 240 | 156 | 156 | 9e6b4e400a6d0126e353180640675891e0f2df56 | bigcode/the-stack | train |
5c0a7730010c785b57ecc8a5 | train | class | class TestNonZero(_DeprecationTestCase):
# 2019-05-26, 1.17.0
def test_zerod(self):
self.assert_deprecated(lambda: np.nonzero(np.array(0)))
self.assert_deprecated(lambda: np.nonzero(np.array(1)))
| class TestNonZero(_DeprecationTestCase):
# 2019-05-26, 1.17.0
| def test_zerod(self):
self.assert_deprecated(lambda: np.nonzero(np.array(0)))
self.assert_deprecated(lambda: np.nonzero(np.array(1)))
| 1.17.0
def test_shape_1_fields(self):
self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
class TestNonZero(_DeprecationTestCase):
# 2019-05-26, 1.17.0
| 64 | 64 | 66 | 28 | 36 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNonZero | TestNonZero | 566 | 570 | 566 | 567 | ee280706c5189cc734858dbcb372f06e5dc8d31d | bigcode/the-stack | train |
2e7ce3b30c9d3dbefe2e51bc | train | class | class TestNonCContiguousViewDeprecation(_DeprecationTestCase):
"""View of non-C-contiguous arrays deprecated in 1.11.0.
The deprecation will not be raised for arrays that are both C and F
contiguous, as C contiguous is dominant. There are more such arrays
with relaxed stride checking than without so th... | class TestNonCContiguousViewDeprecation(_DeprecationTestCase):
| """View of non-C-contiguous arrays deprecated in 1.11.0.
The deprecation will not be raised for arrays that are both C and F
contiguous, as C contiguous is dominant. There are more such arrays
with relaxed stride checking than without so the deprecation is not
as visible with relaxed stride checkin... | .timezone('US/Eastern')
dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz)
self.assert_deprecated(np.datetime64, args=(dt,))
class TestNonCContiguousViewDeprecation(_DeprecationTestCase):
| 63 | 64 | 142 | 17 | 47 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNonCContiguousViewDeprecation | TestNonCContiguousViewDeprecation | 264 | 275 | 264 | 264 | aec5a24674a1794f27eb6dc6f9da989dcef0c453 | bigcode/the-stack | train |
71cfdde14e2908b526d30e67 | train | class | class TestDatetimeEvent(_DeprecationTestCase):
# 2017-08-11, 1.14.0
def test_3_tuple(self):
for cls in (np.datetime64, np.timedelta64):
# two valid uses - (unit, num) and (unit, num, den, None)
self.assert_not_deprecated(cls, args=(1, ('ms', 2)))
self.assert_not_depre... | class TestDatetimeEvent(_DeprecationTestCase):
# 2017-08-11, 1.14.0
| def test_3_tuple(self):
for cls in (np.datetime64, np.timedelta64):
# two valid uses - (unit, num) and (unit, num, den, None)
self.assert_not_deprecated(cls, args=(1, ('ms', 2)))
self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None)))
# trying to use th... |
arr = np.arange(9).reshape(3, 3)
v = arr.T
self.assert_deprecated(npy_updateifcopy_deprecation, args=(v,))
class TestDatetimeEvent(_DeprecationTestCase):
# 2017-08-11, 1.14.0
| 67 | 68 | 228 | 28 | 40 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestDatetimeEvent | TestDatetimeEvent | 427 | 440 | 427 | 428 | f84773abaaffd9e34c27a21ec14abbae6959bba9 | bigcode/the-stack | train |
c2d7836431ea4361de0d8a77 | train | class | class Test_GetSet_NumericOps(_DeprecationTestCase):
# 2018-09-20, 1.16.0
def test_get_numeric_ops(self):
from numpy.core._multiarray_tests import getset_numericops
self.assert_deprecated(getset_numericops, num=2)
# empty kwargs prevents any state actually changing which would break
... | class Test_GetSet_NumericOps(_DeprecationTestCase):
# 2018-09-20, 1.16.0
| def test_get_numeric_ops(self):
from numpy.core._multiarray_tests import getset_numericops
self.assert_deprecated(getset_numericops, num=2)
# empty kwargs prevents any state actually changing which would break
# other tests.
self.assert_deprecated(np.set_numeric_ops, kwargs=... | ationWarning)
# Should not raise:
res = np.fromstring(x_str, sep=",", count=4)
assert_array_equal(res, x)
class Test_GetSet_NumericOps(_DeprecationTestCase):
# 2018-09-20, 1.16.0
| 64 | 64 | 114 | 31 | 33 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | Test_GetSet_NumericOps | Test_GetSet_NumericOps | 546 | 555 | 546 | 547 | 442ee843d5a21d0b41fde5147b13b3a667950507 | bigcode/the-stack | train |
2af2973c6c776779190155c0 | train | class | class TestRaggedArray(_DeprecationTestCase):
# 2019-11-29 1.18.0
def test_deprecate_ragged_arrays(self):
# NEP 34 deprecated automatic object dtype when creating ragged
# arrays. Also see the "ragged" tests in `test_multiarray`
arg = [1, [2, 3]]
self.assert_deprecated(np.array, a... | class TestRaggedArray(_DeprecationTestCase):
# 2019-11-29 1.18.0
| def test_deprecate_ragged_arrays(self):
# NEP 34 deprecated automatic object dtype when creating ragged
# arrays. Also see the "ragged" tests in `test_multiarray`
arg = [1, [2, 3]]
self.assert_deprecated(np.array, args=(arg,))
| zerod(self):
self.assert_deprecated(lambda: np.nonzero(np.array(0)))
self.assert_deprecated(lambda: np.nonzero(np.array(1)))
class TestRaggedArray(_DeprecationTestCase):
# 2019-11-29 1.18.0
| 63 | 64 | 98 | 29 | 34 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestRaggedArray | TestRaggedArray | 573 | 579 | 573 | 574 | c31de9379bec1fa49e93ee9262e5d6f43e8313cb | bigcode/the-stack | train |
19d942ed131a84a982acb60c | train | class | class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
"""Assigning the 'data' attribute of an ndarray is unsafe as pointed
out in gh-7093. Eventually, such assignment should NOT be allowed, but
in the interests of maintaining backwards compatibility, only a Deprecation-
Warning wil... | class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
| """Assigning the 'data' attribute of an ndarray is unsafe as pointed
out in gh-7093. Eventually, such assignment should NOT be allowed, but
in the interests of maintaining backwards compatibility, only a Deprecation-
Warning will be raised instead for the time being to give developers time to
re... | test_fortran_contiguous(self):
self.assert_deprecated(np.ones((2,2)).T.view, args=(complex,))
self.assert_deprecated(np.ones((2,2)).T.view, args=(np.int8,))
class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
| 63 | 64 | 171 | 16 | 48 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestArrayDataAttributeAssignmentDeprecation | TestArrayDataAttributeAssignmentDeprecation | 278 | 293 | 278 | 278 | cffa1626d03e79ee3a41ab7cb8cffdca06fecc53 | bigcode/the-stack | train |
a2598cb0f088485e4c70735e | train | class | class TestPyArray_AS2D(_DeprecationTestCase):
def test_npy_pyarrayas2d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
| class TestPyArray_AS2D(_DeprecationTestCase):
| def test_npy_pyarrayas2d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
| def test_npy_pyarrayas1d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
class TestPyArray_AS2D(_DeprecationTestCase):
| 64 | 64 | 65 | 14 | 50 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestPyArray_AS2D | TestPyArray_AS2D | 409 | 412 | 409 | 409 | 819d46168304805af5457aaaffe145b61d7b5ce9 | bigcode/the-stack | train |
d901ac26b5c79523f27d39ac | train | class | class TestFromStringAndFileInvalidData(_DeprecationTestCase):
# 2019-06-08, 1.17.0
# Tests should be moved to real tests when deprecation is done.
message = "string or file could not be read to its end"
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unp... | class TestFromStringAndFileInvalidData(_DeprecationTestCase):
# 2019-06-08, 1.17.0
# Tests should be moved to real tests when deprecation is done.
| message = "string or file could not be read to its end"
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_data_file(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
with tempfile.TemporaryFile(mode="w") as f:
... | _deprecated(lambda: np.typeNA.get('?'))
class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
def test_fr... | 164 | 165 | 550 | 47 | 118 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestFromStringAndFileInvalidData | TestFromStringAndFileInvalidData | 494 | 543 | 494 | 496 | a12f9651875763c8f40121889215e5eaa742bc1d | bigcode/the-stack | train |
2a594f5c6d9ce6f6df6176b1 | train | class | class Test_UPDATEIFCOPY(_DeprecationTestCase):
"""
v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use
WRITEBACKIFCOPY instead
"""
def test_npy_updateifcopy_deprecation(self):
from numpy.core._multiarray_tests import npy_updateifcopy_deprecation
arr = np.arange(9).resh... | class Test_UPDATEIFCOPY(_DeprecationTestCase):
| """
v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use
WRITEBACKIFCOPY instead
"""
def test_npy_updateifcopy_deprecation(self):
from numpy.core._multiarray_tests import npy_updateifcopy_deprecation
arr = np.arange(9).reshape(3, 3)
v = arr.T
self.assert... | ):
def test_npy_pyarrayas2d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
class Test_UPDATEIFCOPY(_DeprecationTestCase):
| 64 | 64 | 110 | 12 | 52 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | Test_UPDATEIFCOPY | Test_UPDATEIFCOPY | 415 | 424 | 415 | 415 | 25b081faed93c4237d9189c3cf432b8e3d722b99 | bigcode/the-stack | train |
556e2fd4c5523ee93c773c26 | train | class | class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
def test_fromstring(self):
self.assert_deprecated(np.fromstring, args=('\x00'*80,))
| class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
| def test_fromstring(self):
self.assert_deprecated(np.fromstring, args=('\x00'*80,))
| 8-06-28, 1.16.0
def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
| 64 | 64 | 50 | 26 | 38 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestFromstring | TestFromstring | 488 | 491 | 488 | 489 | f3428b18e36147cf4ec2450492ae472b6c803876 | bigcode/the-stack | train |
3125d6785747a239ecaf7ef5 | train | class | class TestGeneratorSum(_DeprecationTestCase):
# 2018-02-25, 1.15.0
def test_generator_sum(self):
self.assert_deprecated(np.sum, args=((i for i in range(5)),))
| class TestGeneratorSum(_DeprecationTestCase):
# 2018-02-25, 1.15.0
| def test_generator_sum(self):
self.assert_deprecated(np.sum, args=((i for i in range(5)),))
| 1.18.0
def test_alen(self):
self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))
class TestGeneratorSum(_DeprecationTestCase):
# 2018-02-25, 1.15.0
| 63 | 64 | 54 | 28 | 35 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestGeneratorSum | TestGeneratorSum | 468 | 471 | 468 | 469 | 35a0be4065d10c4ab32fb58f4a0b833257b499ff | bigcode/the-stack | train |
bf46e563281e230205553073 | train | class | class TestTestDeprecated(object):
def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
test_case_instance.setup()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
def foo():
... | class TestTestDeprecated(object):
| def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
test_case_instance.setup()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
def foo():
warnings.warn("foo", category... | 64', 'Void0'
]
if sys.version_info[0] < 3:
deprecated_types.extend(['Unicode0', 'String0'])
for dt in deprecated_types:
self.assert_deprecated(np.dtype, exceptions=(TypeError,),
args=(dt,))
class TestTestDeprecated(object):
| 63 | 64 | 91 | 6 | 58 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestTestDeprecated | TestTestDeprecated | 345 | 357 | 345 | 345 | e535b49dcb10f3a9ab05a9ddaca8deb0ceda46c9 | bigcode/the-stack | train |
8d65378d588278fb81d71efd | train | class | class _DeprecationTestCase(object):
# Just as warning: warnings uses re.match, so the start of this message
# must match.
message = ''
warning_cls = DeprecationWarning
def setup(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()
... | class _DeprecationTestCase(object):
# Just as warning: warnings uses re.match, so the start of this message
# must match.
| message = ''
warning_cls = DeprecationWarning
def setup(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()
# Do *not* ignore other DeprecationWarnings. Ignoring warnings
# can give very confusing results because of
# htt... | """
Tests related to deprecation warnings. Also a convenient place
to document how deprecations should eventually be turned into errors.
"""
from __future__ import division, absolute_import, print_function
import datetime
import sys
import operator
import warnings
import pytest
import shutil
import tempfile
import n... | 164 | 253 | 844 | 32 | 131 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | _DeprecationTestCase | _DeprecationTestCase | 30 | 133 | 30 | 32 | de34dfcdaf05485272c6d02c6da45ab7fab1fdf3 | bigcode/the-stack | train |
fffb036e2a5e035b449dc6cc | train | class | class TestAlen(_DeprecationTestCase):
# 2019-08-02, 1.18.0
def test_alen(self):
self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))
| class TestAlen(_DeprecationTestCase):
# 2019-08-02, 1.18.0
| def test_alen(self):
self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))
| .0
def test_bincount_minlength(self):
self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
class TestAlen(_DeprecationTestCase):
# 2019-08-02, 1.18.0
| 64 | 64 | 56 | 28 | 36 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestAlen | TestAlen | 462 | 465 | 462 | 463 | 7771c426dfb34a79b1d381566b42204cbd7a97a6 | bigcode/the-stack | train |
7c2f347fbe88945e941ce78a | train | class | class TestTruthTestingEmptyArrays(_DeprecationTestCase):
# 2017-09-25, 1.14.0
message = '.*truth value of an empty array is ambiguous.*'
def test_1d(self):
self.assert_deprecated(bool, args=(np.array([]),))
def test_2d(self):
self.assert_deprecated(bool, args=(np.zeros((1, 0)),))
... | class TestTruthTestingEmptyArrays(_DeprecationTestCase):
# 2017-09-25, 1.14.0
| message = '.*truth value of an empty array is ambiguous.*'
def test_1d(self):
self.assert_deprecated(bool, args=(np.array([]),))
def test_2d(self):
self.assert_deprecated(bool, args=(np.zeros((1, 0)),))
self.assert_deprecated(bool, args=(np.zeros((0, 1)),))
self.assert_depr... | ', 2, 1, 'event')))
self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63)))
class TestTruthTestingEmptyArrays(_DeprecationTestCase):
# 2017-09-25, 1.14.0
| 63 | 64 | 129 | 30 | 33 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestTruthTestingEmptyArrays | TestTruthTestingEmptyArrays | 443 | 453 | 443 | 444 | 9c0dbd8c98db9d71862258947ef19c2a179208df | bigcode/the-stack | train |
1355dee0d02b5e7ed63e753a | train | class | class TestSctypeNA(_VisibleDeprecationTestCase):
# 2018-06-24, 1.16
def test_sctypeNA(self):
self.assert_deprecated(lambda: np.sctypeNA['?'])
self.assert_deprecated(lambda: np.typeNA['?'])
self.assert_deprecated(lambda: np.typeNA.get('?'))
| class TestSctypeNA(_VisibleDeprecationTestCase):
# 2018-06-24, 1.16
| def test_sctypeNA(self):
self.assert_deprecated(lambda: np.sctypeNA['?'])
self.assert_deprecated(lambda: np.typeNA['?'])
self.assert_deprecated(lambda: np.typeNA.get('?'))
| -25, 1.15.0
def test_generator_sum(self):
self.assert_deprecated(np.sum, args=((i for i in range(5)),))
class TestSctypeNA(_VisibleDeprecationTestCase):
# 2018-06-24, 1.16
| 64 | 64 | 76 | 28 | 36 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestSctypeNA | TestSctypeNA | 474 | 479 | 474 | 475 | 80c7755a0f8d9f43d49122fecca793cf47755bb0 | bigcode/the-stack | train |
041ddc1b14030b340015c981 | train | class | class TestBincount(_DeprecationTestCase):
# 2017-06-01, 1.14.0
def test_bincount_minlength(self):
self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
| class TestBincount(_DeprecationTestCase):
# 2017-06-01, 1.14.0
| def test_bincount_minlength(self):
self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
| self.assert_deprecated(bool, args=(np.zeros((0, 1)),))
self.assert_deprecated(bool, args=(np.zeros((0, 0)),))
class TestBincount(_DeprecationTestCase):
# 2017-06-01, 1.14.0
| 64 | 64 | 62 | 29 | 35 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestBincount | TestBincount | 456 | 459 | 456 | 457 | f7f4c7d604985430dc46c4199535c54ce98044ec | bigcode/the-stack | train |
32cd059d4b9d710df288fd44 | train | class | class TestNPY_CHAR(_DeprecationTestCase):
# 2017-05-03, 1.13.0
def test_npy_char_deprecation(self):
from numpy.core._multiarray_tests import npy_char_deprecation
self.assert_deprecated(npy_char_deprecation)
assert_(npy_char_deprecation() == 'S1')
| class TestNPY_CHAR(_DeprecationTestCase):
# 2017-05-03, 1.13.0
| def test_npy_char_deprecation(self):
from numpy.core._multiarray_tests import npy_char_deprecation
self.assert_deprecated(npy_char_deprecation)
assert_(npy_char_deprecation() == 'S1')
| 6', 'M'),
np.array((1, 2), [('a', int), ('b', int)])):
self.assert_deprecated(a.conjugate)
class TestNPY_CHAR(_DeprecationTestCase):
# 2017-05-03, 1.13.0
| 64 | 64 | 79 | 29 | 35 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestNPY_CHAR | TestNPY_CHAR | 395 | 400 | 395 | 396 | a4c82b538910f9131d18f1eac9dec0e4dc6fa542 | bigcode/the-stack | train |
b2adb9717129c1ae7d38afd6 | train | class | class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):
"""
If a 'width' parameter is passed into ``binary_repr`` that is insufficient to
represent the number in base 2 (positive) or 2's complement (negative) form,
the function used to silently ignore the parameter and ret... | class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):
| """
If a 'width' parameter is passed into ``binary_repr`` that is insufficient to
represent the number in base 2 (positive) or 2's complement (negative) form,
the function used to silently ignore the parameter and return a representation
using the minimal number of bits needed for the form in questi... | 10)
self.message = ("Assigning the 'data' attribute is an "
"inherently unsafe operation and will "
"be removed in the future.")
self.assert_deprecated(a.__setattr__, args=('data', b.data))
class TestBinaryReprInsufficientWidthParameterForRepresentation(... | 71 | 71 | 239 | 18 | 53 | jcw780/numpy | numpy/core/tests/test_deprecations.py | Python | TestBinaryReprInsufficientWidthParameterForRepresentation | TestBinaryReprInsufficientWidthParameterForRepresentation | 296 | 319 | 296 | 296 | cca4250b1575c5450e2fdb3ac5c1f69e1c24c3ed | bigcode/the-stack | train |
81673e4d9a88979ad8f054e1 | train | class | class TSInterpolator(BaseTransformer):
"""Time series interpolator/re-sampler.
Transformer that rescales series for another number of points.
For each cell in dataframe transformer fits scipy linear interp1d
and samples user defined number of points. Points are generated
by numpy.linspace.
Aft... | class TSInterpolator(BaseTransformer):
| """Time series interpolator/re-sampler.
Transformer that rescales series for another number of points.
For each cell in dataframe transformer fits scipy linear interp1d
and samples user defined number of points. Points are generated
by numpy.linspace.
After transformation each cell will be a p... | # -*- coding: utf-8 -*-
"""Time series interpolator/re-sampler."""
import numpy as np
import pandas as pd
from scipy import interpolate
from sktime.transformations.base import BaseTransformer
__author__ = ["mloning"]
class TSInterpolator(BaseTransformer):
| 56 | 218 | 727 | 6 | 50 | biologioholic/sktime | sktime/transformations/panel/interpolate.py | Python | TSInterpolator | TSInterpolator | 12 | 103 | 12 | 12 | aba4c7b969409206255a8ead23137f91641aed08 | bigcode/the-stack | train |
7e2f3444847ff2ec14b9be1d | train | class | class Dataset(ABC):
def __init__(self, name: str):
self.path = DATASET_FOLDER / name
self.documents = None
self.sentences = None
def load(self, sentence_splitter: Callable = sent_tokenize, documents_limit: int = None):
# noinspection PyTypeChecker
self.documents = np.arr... | class Dataset(ABC):
| def __init__(self, name: str):
self.path = DATASET_FOLDER / name
self.documents = None
self.sentences = None
def load(self, sentence_splitter: Callable = sent_tokenize, documents_limit: int = None):
# noinspection PyTypeChecker
self.documents = np.array([Document(documen... | from abc import ABC, abstractmethod
from pathlib import Path
from typing import Callable
import numpy as np
import pandas as pd
from nltk.tokenize import sent_tokenize
from .document import Document
from .sentence import Sentence
DATASET_FOLDER = Path('resources', 'datasets')
class Dataset(ABC):
| 65 | 71 | 238 | 5 | 60 | AntonYermilov/article-writing-assistant | base/dataset.py | Python | Dataset | Dataset | 16 | 46 | 16 | 16 | d929d4581c28987c88a8c76838b30048b52f9875 | bigcode/the-stack | train |
c339c27e32f13ebb7ac512a4 | train | class | class NIPSPapersDataset(Dataset):
def _load(self, documents_limit: int = None) -> np.array:
df = pd.read_csv(self.path, compression='gzip', sep=',')
docs = df['paper_text'].values.astype(np.str)
random = np.random.RandomState(13)
random.shuffle(docs)
return docs if documents_... | class NIPSPapersDataset(Dataset):
| def _load(self, documents_limit: int = None) -> np.array:
df = pd.read_csv(self.path, compression='gzip', sep=',')
docs = df['paper_text'].values.astype(np.str)
random = np.random.RandomState(13)
random.shuffle(docs)
return docs if documents_limit is None else docs[:documents... | np.array:
pass
def get_docs(self) -> np.array:
return self.documents
def get_sentences(self) -> np.array:
return self.sentences
def __len__(self) -> int:
return len(self.sentences)
class NIPSPapersDataset(Dataset):
| 64 | 64 | 85 | 9 | 55 | AntonYermilov/article-writing-assistant | base/dataset.py | Python | NIPSPapersDataset | NIPSPapersDataset | 49 | 55 | 49 | 49 | eb9b42b4a60d73743154b2962acef3cf6962262f | bigcode/the-stack | train |
76a36f844becd9e76fee868b | train | function | def clip(a, a_min, a_max, out=None):
"""
Clip (limit) the values in a tensor.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Parame... | def clip(a, a_min, a_max, out=None):
| """
Clip (limit) the values in a tensor.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Parameters
----------
a : array_lik... |
@classmethod
def execute(cls, ctx, op):
inputs, device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)
inputs_iter = iter(inputs)
a = next(inputs_iter)
a_min = next(inputs_iter) if isinstance(op.a_min, type(op.outputs[0])... | 191 | 191 | 638 | 13 | 178 | sighingnow/mars | mars/tensor/arithmetic/clip.py | Python | clip | clip | 141 | 194 | 141 | 141 | 169575a8845510ffec812082f0e898b8cdfc12de | bigcode/the-stack | train |
51d3071d6493eb1caf5c568c | train | class | class TensorClip(TensorOperand, TensorElementWise):
_op_type_ = OperandDef.CLIP
_a = KeyField('a')
_a_min = AnyField('a_min')
_a_max = AnyField('a_max')
_out = KeyField('out')
@property
def a(self):
return self._a
@property
def a_min(self):
return self._a_min
... | class TensorClip(TensorOperand, TensorElementWise):
| _op_type_ = OperandDef.CLIP
_a = KeyField('a')
_a_min = AnyField('a_min')
_a_max = AnyField('a_max')
_out = KeyField('out')
@property
def a(self):
return self._a
@property
def a_min(self):
return self._a_min
@property
def a_max(self):
return self._... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | 243 | 247 | 825 | 11 | 231 | sighingnow/mars | mars/tensor/arithmetic/clip.py | Python | TensorClip | TensorClip | 31 | 138 | 31 | 31 | 4fb2788c959871fbd780eb644a12acd919e58259 | bigcode/the-stack | train |
9c43bee2ab625d9b6e175b31 | train | class | @unittest.skipIf(re.search(Constant.wget_connect_success_msg, wget_result)
is None, 'wget连接失败')
class Tools(unittest.TestCase):
def setUp(self):
self.log = Logger()
self.log.info('----Opengauss_Function_Gs_Install_Case0005开始执行----')
self.primary_root_node = Node('PrimaryRoot... | @unittest.skipIf(re.search(Constant.wget_connect_success_msg, wget_result)
is None, 'wget连接失败')
class Tools(unittest.TestCase):
| def setUp(self):
self.log = Logger()
self.log.info('----Opengauss_Function_Gs_Install_Case0005开始执行----')
self.primary_root_node = Node('PrimaryRoot')
self.primary_node = Node('PrimaryDbUser')
self.common = Common()
path = os.path.dirname(os.path.dirname(macro.DB_INSTA... | xml配置文件路径] --gsinit-parameter=--username=[初始用户]
6.清理环境
gs_uninstall 删除数据库:gs_uninstall --delete-data
postuninstall清理数据库:
./gs_postuninstall -U autotest -X [xml配置文件路径]
删除数据库相关目录:
rm -rf [数据库相关目录]
Expect :
1.下载解压成功
2.配置成功
3.成功
4.预安装成功
5.安装失败,错误码[GAUSS-50000]
6.清理成功
Hi... | 256 | 256 | 1,740 | 32 | 224 | opengauss-mirror/Yat | openGaussBase/testcase/TOOLS/COMPILATION/Opengauss_Function_Gs_Install_Case0005.py | Python | Tools | Tools | 59 | 198 | 59 | 61 | e1e3c86b9da62b1b7ada0759c62df9a3152ccc13 | bigcode/the-stack | train |
fe99638bc77dd3cd27bb9e84 | train | function | def readme():
with open('README.rst') as f:
return f.read()
| def readme():
| with open('README.rst') as f:
return f.read()
| from setuptools import setup, find_packages
# Get the long description from the README file
def readme():
| 22 | 64 | 20 | 4 | 17 | arkochem/shgo | setup.py | Python | readme | readme | 5 | 7 | 5 | 5 | a4a5443306d457c32e065eac77bdff78c35db20d | bigcode/the-stack | train |
518ed4d8b4fdf717565fc984 | train | class | class UCF101AsClips(data.Dataset):
"""
"""
def __init__(self, args, is_train, root=None, loader=default_loader,
replicates=1):
self.args = args
self.is_train = is_train
self.train_size = args.train_size
self.render_size = args.render_size
self.r... | class UCF101AsClips(data.Dataset):
| """
"""
def __init__(self, args, is_train, root=None, loader=default_loader,
replicates=1):
self.args = args
self.is_train = is_train
self.train_size = args.train_size
self.render_size = args.render_size
self.real_size = None
self.replic... | from __future__ import division
import os
import os.path
import os.path
import random
import math
import torch
import torch.utils.data as data
from .dataset_utils.util_func import *
from .dataset_utils import frame_utils
from . import dataset_read
class UCF101AsClips(data.Dataset):
| 66 | 256 | 947 | 10 | 55 | Kwanss/PCLNet | Datasets/UCF101.py | Python | UCF101AsClips | UCF101AsClips | 17 | 104 | 17 | 17 | 55c55f73e3fd4551c3cc76287a07cfc822114ac5 | bigcode/the-stack | train |
bb7514e8b6ed16c9269beb42 | train | function | def drawAndDelay(cars, race_track):
#fill screen with black
screen.fill(black)
#Draw player
for c in cars:
c.draw()
for seg in race_track:
seg.draw()
#Update the screen
pygame.display.flip()
| def drawAndDelay(cars, race_track):
#fill screen with black
| screen.fill(black)
#Draw player
for c in cars:
c.draw()
for seg in race_track:
seg.draw()
#Update the screen
pygame.display.flip()
| Add select neural nets to the selected list
selected.append(brains[i])
#Highlight selected cars
cars[i].line_thickness = 5
print('Selected: '+str(len(selected)))
return False
def drawAndDelay(cars, race_track):
#fill screen with black
| 64 | 64 | 60 | 17 | 46 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | drawAndDelay | drawAndDelay | 131 | 140 | 131 | 132 | 0304d7e6c5c7273b7204a0c577d9974ce1a6cd76 | bigcode/the-stack | train |
acce5ef21058b9c8d4b7d168 | train | function | def userInputToPlayer(player):
'''This is no longer in use.'''
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.moveForward()
if keys[pygame.K_DOWN]:
player.moveBackward()
if keys[pygame.K_LEFT]:
player.rotateLeft()
if keys[pygame.K_RIGHT]:
player.rota... | def userInputToPlayer(player):
| '''This is no longer in use.'''
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.moveForward()
if keys[pygame.K_DOWN]:
player.moveBackward()
if keys[pygame.K_LEFT]:
player.rotateLeft()
if keys[pygame.K_RIGHT]:
player.rotateRight()
if keys[pygame.K_... | #len(parents)-1 to the end of the list.
for _ in range(mutation_count):
p1 = random.choice(current_gen[len(parents)-1:])
if nudge:
mutateNudge(p1)
else:
mutateBlast(p1)
def userInputToPlayer(player):
| 64 | 64 | 104 | 7 | 57 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | userInputToPlayer | userInputToPlayer | 78 | 92 | 78 | 78 | 5b19350d3fc9688905eff0ae3eb028e5794d9355 | bigcode/the-stack | train |
85615507acead6c844ee5c95 | train | function | def mutateNudge(neural_net):
'''Adjust a random weight in the neural network.'''
layer = random.choice(neural_net.layers[1:])
neuron = random.choice(layer)
index = random.randint(0,len(neuron.weights)-1)
neuron.weights[index] += (random.random()-0.5)*0.1
if neuron.weights[index] > 1:
neu... | def mutateNudge(neural_net):
| '''Adjust a random weight in the neural network.'''
layer = random.choice(neural_net.layers[1:])
neuron = random.choice(layer)
index = random.randint(0,len(neuron.weights)-1)
neuron.weights[index] += (random.random()-0.5)*0.1
if neuron.weights[index] > 1:
neuron.weights[index] = 1
if... | _net):
'''Re-roll a random weight in the neural network.'''
layer = random.choice(neural_net.layers[1:])
neuron = random.choice(layer)
neuron.weights[random.randint(0,len(neuron.weights)-1)] = random.random()*2-1
def mutateNudge(neural_net):
| 64 | 64 | 109 | 8 | 55 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | mutateNudge | mutateNudge | 151 | 160 | 151 | 151 | 425b5eef8cb881ccaf14fa87947137d0f4e0b077 | bigcode/the-stack | train |
4b1ac767836e14c4d8eb02fb | train | function | def handleEvents(brains):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return True
#Press enter or space for a new generation. space gives
... | def handleEvents(brains):
| for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return True
#Press enter or space for a new generation. space gives
#a light nudge mutation.... | pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.moveForward()
if keys[pygame.K_DOWN]:
player.moveBackward()
if keys[pygame.K_LEFT]:
player.rotateLeft()
if keys[pygame.K_RIGHT]:
player.rotateRight()
if keys[pygame.K_a]:
player.accelerate()
if keys[py... | 90 | 90 | 300 | 6 | 84 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | handleEvents | handleEvents | 95 | 129 | 95 | 95 | 0fcf471185555b9de9ed17b658e2d45ff4f8dae9 | bigcode/the-stack | train |
15aee7c122dade38a2ea78c4 | train | function | def mutateBlast(neural_net):
'''Re-roll a random weight in the neural network.'''
layer = random.choice(neural_net.layers[1:])
neuron = random.choice(layer)
neuron.weights[random.randint(0,len(neuron.weights)-1)] = random.random()*2-1
| def mutateBlast(neural_net):
| '''Re-roll a random weight in the neural network.'''
layer = random.choice(neural_net.layers[1:])
neuron = random.choice(layer)
neuron.weights[random.randint(0,len(neuron.weights)-1)] = random.random()*2-1
| c in cars:
c.draw()
for seg in race_track:
seg.draw()
#Update the screen
pygame.display.flip()
#Delay to get 30 fps NOTE: Don't delay any more. It's already too slow.
#clock.tick(30)
def mutateBlast(neural_net):
| 64 | 64 | 61 | 7 | 57 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | mutateBlast | mutateBlast | 145 | 149 | 145 | 145 | f047d2234b0ecaa88356bbc98a8c74dc1b811edb | bigcode/the-stack | train |
ffb2d8529eac54c873e523bd | train | function | def getCar():
if use_ballistic:
return car_ballistic.CarBallistic(screen, 100, 200, friction,acceleration)
else:
return car.Car(screen, 100, 200)
| def getCar():
| if use_ballistic:
return car_ballistic.CarBallistic(screen, 100, 200, friction,acceleration)
else:
return car.Car(screen, 100, 200)
| Acceleration as a percentage of max speed per frame
#Attributes of the "normal" car
#Setup
pygame.init()
width = 900
height = 600
screen = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()
black = 0,0,0
def getCar():
| 64 | 64 | 46 | 4 | 59 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | getCar | getCar | 35 | 39 | 35 | 35 | 20483dc05fe8c2fc237f60af9cbdd7b6067f6f2e | bigcode/the-stack | train |
60b9f248bafe5224e62dd4f8 | train | function | def crossover(nnet1, nnet2):
'''Swap random neurons in a random layer between
neural nets.'''
layer_index = random.randint(1,len(nnet1.layers)-1)
layer1 = nnet1.layers[layer_index]
layer2 = nnet2.layers[layer_index]
split = random.randint(0,len(layer1)-1)
for i in range(split):
copy ... | def crossover(nnet1, nnet2):
| '''Swap random neurons in a random layer between
neural nets.'''
layer_index = random.randint(1,len(nnet1.layers)-1)
layer1 = nnet1.layers[layer_index]
layer2 = nnet2.layers[layer_index]
split = random.randint(0,len(layer1)-1)
for i in range(split):
copy = layer1[i].getCopy()
... | .weights[index] += (random.random()-0.5)*0.1
if neuron.weights[index] > 1:
neuron.weights[index] = 1
if neuron.weights[index] < -1:
neuron.weights[index] = -1
def crossover(nnet1, nnet2):
| 64 | 64 | 144 | 10 | 53 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | crossover | crossover | 164 | 176 | 164 | 164 | 258da010d25887ee3bcf5c4ef01e3f9ca6dadd0c | bigcode/the-stack | train |
c0b0d0553bb4d98e056e4ffe | train | function | def makeNewGeneration(current_gen,parents,nudge=True):
'''Both of the arguments to this function are lists
of neural networks.
current_gen is the current list of neural networks.
parents is a list of neural networks selected for breeding
the next generation.
nudge specifies which type of muta... | def makeNewGeneration(current_gen,parents,nudge=True):
| '''Both of the arguments to this function are lists
of neural networks.
current_gen is the current list of neural networks.
parents is a list of neural networks selected for breeding
the next generation.
nudge specifies which type of mutation to use.'''
if len(parents) == 0:
retur... | 900
height = 600
screen = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()
black = 0,0,0
def getCar():
if use_ballistic:
return car_ballistic.CarBallistic(screen, 100, 200, friction,acceleration)
else:
return car.Car(screen, 100, 200)
def makeNewGeneration(current_gen,paren... | 90 | 90 | 300 | 12 | 78 | nealholt/python_programming_curricula | CS3/0700_car_driving_neural_net_evolutionary/draft14/main.py | Python | makeNewGeneration | makeNewGeneration | 41 | 74 | 41 | 41 | 648268428499e103a58ce8809488a0991fe6e285 | bigcode/the-stack | train |
524cdc299dcd66680226bb74 | train | function | def _import_file(module_name, file_path, make_importable=False):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if make_importable:
sys.modules[module_name] = module
return module
| def _import_file(module_name, file_path, make_importable=False):
| spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if make_importable:
sys.modules[module_name] = module
return module
| np.random.seed(seed)
torch.set_rng_state(torch.manual_seed(seed).get_state())
random.seed(seed)
return seed
# from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
def _import_file(module_name, file_path, make_importable=False):
| 64 | 64 | 68 | 15 | 48 | tonysy/cvpods | cvpods/utils/env/env.py | Python | _import_file | _import_file | 44 | 50 | 44 | 44 | 74bdb354d55f520d6c96f8e8583f181b1e5be45c | bigcode/the-stack | train |
6392a341e0cdcdbd93ddc537 | train | function | def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file or a module in
the $cvpods_ENV_MODULE environment variable, that performs
custom setup work that may be necessary to their computing environment.
... | def setup_environment():
| """Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file or a module in
the $cvpods_ENV_MODULE environment variable, that performs
custom setup work that may be necessary to their computing environment.
"""
global _ENV_SET... | ENCV_OPENCL_RUNTIME"] = "disabled"
try:
import cv2
if int(cv2.__version__.split(".")[0]) >= 3:
cv2.ocl.setUseOpenCL(False)
except ImportError:
pass
_ENV_SETUP_DONE = False
def setup_environment():
| 64 | 64 | 141 | 4 | 59 | tonysy/cvpods | cvpods/utils/env/env.py | Python | setup_environment | setup_environment | 78 | 97 | 78 | 78 | adb4fe524752302f6d0188aee13f1f70812fa15f | bigcode/the-stack | train |
7ecd1597de0648e15be3831b | train | function | def _configure_libraries():
"""
Configurations for some libraries.
"""
# An environment option to disable `import cv2` globally,
# in case it leads to negative performance impact
disable_cv2 = int(os.environ.get("cvpods_DISABLE_CV2", False))
if disable_cv2:
sys.modules["cv2"] = None
... | def _configure_libraries():
| """
Configurations for some libraries.
"""
# An environment option to disable `import cv2` globally,
# in case it leads to negative performance impact
disable_cv2 = int(os.environ.get("cvpods_DISABLE_CV2", False))
if disable_cv2:
sys.modules["cv2"] = None
else:
# Disable ... | make_importable=False):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if make_importable:
sys.modules[module_name] = module
return module
def _configure_libraries():
| 64 | 64 | 174 | 6 | 57 | tonysy/cvpods | cvpods/utils/env/env.py | Python | _configure_libraries | _configure_libraries | 53 | 72 | 53 | 53 | e07f30d8316e648171f1be1ce139fa58cff7af86 | bigcode/the-stack | train |
5c84bd5426c1f59f13f2c5ce | train | function | def setup_custom_environment(custom_module):
"""
Load custom environment setup by importing a Python source file or a
module, and run the setup function.
"""
if custom_module.endswith(".py"):
module = _import_file("cvpods.utils.env.env.custom_module", custom_module)
else:
module ... | def setup_custom_environment(custom_module):
| """
Load custom environment setup by importing a Python source file or a
module, and run the setup function.
"""
if custom_module.endswith(".py"):
module = _import_file("cvpods.utils.env.env.custom_module", custom_module)
else:
module = importlib.import_module(custom_module)
... | _ENV_SETUP_DONE = True
_configure_libraries()
custom_module_path = os.environ.get("cvpods_ENV_MODULE")
if custom_module_path:
setup_custom_environment(custom_module_path)
else:
# The default setup is a no-op
pass
def setup_custom_environment(custom_module):
| 64 | 64 | 123 | 7 | 56 | tonysy/cvpods | cvpods/utils/env/env.py | Python | setup_custom_environment | setup_custom_environment | 100 | 113 | 100 | 100 | cfd2514124602e44e29ec070d89181aab85c5314 | bigcode/the-stack | train |
26a5eb8c7c84adbec2907ba1 | train | function | def seed_all_rng(seed=None):
"""
Set the random seed for the RNG in torch, numpy and python.
Args:
seed (int): if None, will use a strong random seed.
Returns:
seed (int): used seed value.
"""
if seed is None:
seed = (
os.getpid()
+ int(datetime.... | def seed_all_rng(seed=None):
| """
Set the random seed for the RNG in torch, numpy and python.
Args:
seed (int): if None, will use a strong random seed.
Returns:
seed (int): used seed value.
"""
if seed is None:
seed = (
os.getpid()
+ int(datetime.now().strftime("%S%f"))
... | from datetime import datetime
import numpy as np
import torch
__all__ = ["seed_all_rng", "setup_environment", "setup_custom_environment", "TORCH_VERSION"]
TORCH_VERSION = tuple(int(x) for x in torch.__version__.split(".")[:2])
def seed_all_rng(seed=None):
| 64 | 64 | 150 | 7 | 57 | tonysy/cvpods | cvpods/utils/env/env.py | Python | seed_all_rng | seed_all_rng | 19 | 40 | 19 | 19 | 4ccff2f95d10e6b755219f6b8a8942448d0fe166 | bigcode/the-stack | train |
c42063e5d42a60a83650d602 | train | class | class Role(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
device_name: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[Union[str, 'RoleTypes']]] = None,
... | class Role(pulumi.CustomResource):
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
device_name: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[Union[str, 'RoleTypes']]] = None,
name: Optional[pulumi.Input[st... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | 97 | 256 | 1,065 | 8 | 89 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/databoxedge/v20200501preview/role.py | Python | Role | Role | 15 | 118 | 15 | 15 | 66a58aaba13eecb6f59e5515bfbca16913ddbd87 | bigcode/the-stack | train |
2d749eacd354be6e73176ec0 | train | class | class OceanMonkey:
__instance = None
LOCAL = 0
CLUSTER = 1
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, settings_path=None):
self.__monkeys = {
MonkeyType.MAC... | class OceanMonkey:
| __instance = None
LOCAL = 0
CLUSTER = 1
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, settings_path=None):
self.__monkeys = {
MonkeyType.MACAQUE: self._consume... | """
This is the OceanMonkey engine which controls all the monkeys to crawling data
"""
import time
import importlib
import multiprocessing
import copy
import pickle
import threading
import asyncio
from threading import Lock, Condition
from oceanmonkey.core.monkey import MonkeyType
from oceanmonkey.core.request import ... | 201 | 256 | 4,931 | 4 | 196 | chipscoco/OceanMonkey | oceanmonkey/core/engine.py | Python | OceanMonkey | OceanMonkey | 30 | 552 | 30 | 30 | 05fb630657480c4b563b948f2fe14c3e4fc03c7f | bigcode/the-stack | train |
b5d6abc4415991b01e002f04 | train | function | def create_provider(handler_name: str, tests_src, config_name: str) -> gen_typing.TestProvider:
def prepare_fn(configs_path: str) -> str:
presets = loader.load_presets(configs_path, config_name)
spec_phase0.apply_constants_preset(presets)
spec_phase1.apply_constants_preset(presets)
... | def create_provider(handler_name: str, tests_src, config_name: str) -> gen_typing.TestProvider:
| def prepare_fn(configs_path: str) -> str:
presets = loader.load_presets(configs_path, config_name)
spec_phase0.apply_constants_preset(presets)
spec_phase1.apply_constants_preset(presets)
return config_name
def cases_fn() -> Iterable[gen_typing.TestCase]:
return generate_... | gen_from_tests.gen import generate_from_tests
from preset_loader import loader
from eth2spec.phase0 import spec as spec_phase0
from eth2spec.phase1 import spec as spec_phase1
def create_provider(handler_name: str, tests_src, config_name: str) -> gen_typing.TestProvider:
| 64 | 64 | 146 | 23 | 40 | osirusgroup/eth2.0-specs | test_generators/operations/main.py | Python | create_provider | create_provider | 19 | 35 | 19 | 20 | 600d4338fab05c054c622fc8978892d99488b6f8 | bigcode/the-stack | train |
799918b4f45a0da1cbab52eb | train | class | class AssemblyAssociatedContentFileAttribute(Attribute, _Attribute):
"""
This attribute is interpreted during the Extensible Application Markup Language (XAML) compilation process to associate loose content with a Windows Presentation Foundation (WPF) application.
AssemblyAssociatedContentFileAttribute(... | class AssemblyAssociatedContentFileAttribute(Attribute, _Attribute):
| """
This attribute is interpreted during the Extensible Application Markup Language (XAML) compilation process to associate loose content with a Windows Presentation Foundation (WPF) application.
AssemblyAssociatedContentFileAttribute(relativeContentFilePath: str)
"""
def __init__(self, *args):
... | Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no imports
# no functions
# classes
class AssemblyAssociatedContentFileAttribute(Attribute, _Attribute):
| 66 | 66 | 221 | 11 | 54 | YKato521/ironpython-stubs | release/stubs.min/System/Windows/Resources.py | Python | AssemblyAssociatedContentFileAttribute | AssemblyAssociatedContentFileAttribute | 12 | 41 | 12 | 12 | 2bce74e38f1797e7f1b4f75816dbf2ae471e8c43 | bigcode/the-stack | train |
e2f5b49c12e003eff3591f5e | train | function | def count_adap_maxpool(m, x, y):
kernel = torch.Tensor([*(x[0].shape[2:])])//torch.Tensor(list((m.output_size,))).squeeze()
kernel_ops = torch.prod(kernel)
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_adap_maxpool(m, x, y):
| kernel = torch.Tensor([*(x[0].shape[2:])])//torch.Tensor(list((m.output_size,))).squeeze()
kernel_ops = torch.prod(kernel)
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| )])
def count_maxpool(m, x, y):
kernel_ops = torch.prod(torch.Tensor([m.kernel_size]))
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
def count_adap_maxpool(m, x, y):
| 64 | 64 | 77 | 12 | 52 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_adap_maxpool | count_adap_maxpool | 101 | 107 | 101 | 101 | 27040078f0e7eee76ceb356ed7f3215001ef6e16 | bigcode/the-stack | train |
175bc451f9edb6fcabe0a7ae | train | function | def count_relu(m, x, y):
x = x[0]
nelements = x.numel()
total_ops = nelements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_relu(m, x, y):
| x = x[0]
nelements = x.numel()
total_ops = nelements
m.total_ops = torch.Tensor([int(total_ops)])
| )])
def count_bn(m, x, y):
x = x[0]
nelements = x.numel()
# subtract, divide, gamma, beta
total_ops = 4*nelements
m.total_ops = torch.Tensor([int(total_ops)])
def count_relu(m, x, y):
| 64 | 64 | 40 | 9 | 55 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_relu | count_relu | 72 | 78 | 72 | 72 | ebcb17f72b3cacec344d4099981597baf7bd5a9c | bigcode/the-stack | train |
b734615a5d1cf1e115f9ff7d | train | function | def count_linear(m, x, y):
# per output element
total_mul = m.in_features
total_add = m.in_features - 1
num_elements = y.numel()
total_ops = (total_mul + total_add) * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_linear(m, x, y):
# per output element
| total_mul = m.in_features
total_add = m.in_features - 1
num_elements = y.numel()
total_ops = (total_mul + total_add) * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| = torch.prod(kernel)
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
def count_linear(m, x, y):
# per output element
| 63 | 64 | 64 | 15 | 48 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_linear | count_linear | 130 | 137 | 130 | 131 | c2e3cae1e93fd4da26ab15f2b380ddc752cd3278 | bigcode/the-stack | train |
be5006cc1f3f8d369e828b07 | train | function | def count_adap_avgpool(m, x, y):
kernel = torch.Tensor([*(x[0].shape[2:])])//torch.Tensor(list((m.output_size,))).squeeze()
total_add = torch.prod(kernel)
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_adap_avgpool(m, x, y):
| kernel = torch.Tensor([*(x[0].shape[2:])])//torch.Tensor(list((m.output_size,))).squeeze()
total_add = torch.prod(kernel)
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| torch.prod(torch.Tensor([m.kernel_size]))
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
def count_adap_avgpool(m, x, y):
| 64 | 64 | 92 | 12 | 52 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_adap_avgpool | count_adap_avgpool | 119 | 127 | 119 | 119 | a2db3af9dcb5c10971582bf197486a1414438276 | bigcode/the-stack | train |
02dca6eda1df0efc9924271c | train | function | def count_convtranspose2d(m, x, y):
x = x[0]
cin = m.in_channels
cout = m.out_channels
kh, kw = m.kernel_size
batch_size = x.size()[0]
out_h = y.size(2)
out_w = y.size(3)
# ops per output element
# kernel_mul = kh * kw * cin
# kernel_add = kh * kw * cin - 1
kernel_ops = multiply_adds * kh * kw * cin // m.... | def count_convtranspose2d(m, x, y):
| x = x[0]
cin = m.in_channels
cout = m.out_channels
kh, kw = m.kernel_size
batch_size = x.size()[0]
out_h = y.size(2)
out_w = y.size(3)
# ops per output element
# kernel_mul = kh * kw * cin
# kernel_add = kh * kw * cin - 1
kernel_ops = multiply_adds * kh * kw * cin // m.groups
bias_ops = 1 if m.bias is no... |
# total ops
# num_out_elements = y.numel()
output_elements = batch_size * out_w * out_h * cout
total_ops = output_elements * ops_per_element
m.total_ops = torch.Tensor([int(total_ops)])
def count_convtranspose2d(m, x, y):
| 63 | 64 | 209 | 12 | 51 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_convtranspose2d | count_convtranspose2d | 35 | 60 | 35 | 35 | d3e13127170f69c4f69e6d8f381e2d5456bbf89e | bigcode/the-stack | train |
54924d6b37fbe8b94ca7958e | train | function | def count_softmax(m, x, y):
x = x[0]
batch_size, nfeatures = x.size()
total_exp = nfeatures
total_add = nfeatures - 1
total_div = nfeatures
total_ops = batch_size * (total_exp + total_add + total_div)
m.total_ops = torch.Tensor([int(total_ops)])
| def count_softmax(m, x, y):
| x = x[0]
batch_size, nfeatures = x.size()
total_exp = nfeatures
total_add = nfeatures - 1
total_div = nfeatures
total_ops = batch_size * (total_exp + total_add + total_div)
m.total_ops = torch.Tensor([int(total_ops)])
| lements
m.total_ops = torch.Tensor([int(total_ops)])
def count_relu(m, x, y):
x = x[0]
nelements = x.numel()
total_ops = nelements
m.total_ops = torch.Tensor([int(total_ops)])
def count_softmax(m, x, y):
| 63 | 64 | 74 | 10 | 53 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_softmax | count_softmax | 81 | 91 | 81 | 81 | 287475773b487ebd9e3638dad6be1e591aa2b477 | bigcode/the-stack | train |
d120bb104298ff488c028282 | train | function | def count_maxpool(m, x, y):
kernel_ops = torch.prod(torch.Tensor([m.kernel_size]))
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_maxpool(m, x, y):
| kernel_ops = torch.prod(torch.Tensor([m.kernel_size]))
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| features = x.size()
total_exp = nfeatures
total_add = nfeatures - 1
total_div = nfeatures
total_ops = batch_size * (total_exp + total_add + total_div)
m.total_ops = torch.Tensor([int(total_ops)])
def count_maxpool(m, x, y):
| 63 | 64 | 50 | 10 | 53 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_maxpool | count_maxpool | 94 | 99 | 94 | 94 | c3ad38e295afc4b1fcc9378c7643aca61de1e4bf | bigcode/the-stack | train |
2bac0a7373503f037364d6c7 | train | function | def count_bn(m, x, y):
x = x[0]
nelements = x.numel()
# subtract, divide, gamma, beta
total_ops = 4*nelements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_bn(m, x, y):
| x = x[0]
nelements = x.numel()
# subtract, divide, gamma, beta
total_ops = 4*nelements
m.total_ops = torch.Tensor([int(total_ops)])
| # output_elements = batch_size * out_w * out_h * cout
ops_per_element = m.weight.nelement()
output_elements = y.nelement()
total_ops = output_elements * ops_per_element
m.total_ops = torch.Tensor([int(total_ops)])
def count_bn(m, x, y):
| 63 | 64 | 53 | 9 | 54 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_bn | count_bn | 63 | 70 | 63 | 63 | c8586c85daa66498eb5da23f1b61e90a1bc637e1 | bigcode/the-stack | train |
0e9bcb5ac7aea10182bcca1d | train | function | def count_conv2d(m, x, y):
x = x[0]
cin = m.in_channels
cout = m.out_channels
kh, kw = m.kernel_size
batch_size = x.size()[0]
out_h = y.size(2)
out_w = y.size(3)
# ops per output element
# kernel_mul = kh * kw * cin
# kernel_add = kh * kw * cin - 1
kernel_ops = multiply_adds * kh * kw * cin // m.groups
b... | def count_conv2d(m, x, y):
| x = x[0]
cin = m.in_channels
cout = m.out_channels
kh, kw = m.kernel_size
batch_size = x.size()[0]
out_h = y.size(2)
out_w = y.size(3)
# ops per output element
# kernel_mul = kh * kw * cin
# kernel_add = kh * kw * cin - 1
kernel_ops = multiply_adds * kh * kw * cin // m.groups
bias_ops = 1 if m.bias is no... | import argparse
import torch
import torch.nn as nn
multiply_adds = 1
def count_conv2d(m, x, y):
| 30 | 64 | 189 | 11 | 18 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_conv2d | count_conv2d | 9 | 32 | 9 | 9 | 753fc9caa69ecc5b0123e15c3734cc1f02e9405c | bigcode/the-stack | train |
24b00adefc9e3f98a9353a12 | train | function | def count_avgpool(m, x, y):
total_add = torch.prod(torch.Tensor([m.kernel_size]))
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| def count_avgpool(m, x, y):
| total_add = torch.prod(torch.Tensor([m.kernel_size]))
total_div = 1
kernel_ops = total_add + total_div
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
| [2:])])//torch.Tensor(list((m.output_size,))).squeeze()
kernel_ops = torch.prod(kernel)
num_elements = y.numel()
total_ops = kernel_ops * num_elements
m.total_ops = torch.Tensor([int(total_ops)])
def count_avgpool(m, x, y):
| 63 | 64 | 65 | 10 | 53 | feferna/pytorch-OpCounter | thop/count_hooks.py | Python | count_avgpool | count_avgpool | 110 | 117 | 110 | 110 | 13ff94d47374efb5cfa5fbb13b96c517adcc2108 | bigcode/the-stack | train |
c328816beb251d37d590823b | train | class | class FileForm(ArvestustRecordFormMixin, forms.ModelForm):
class Meta:
model = File
exclude = ArvestustRecordFormMixin.Meta.exclude + ('likes', 'uploaded_by')
| class FileForm(ArvestustRecordFormMixin, forms.ModelForm):
| class Meta:
model = File
exclude = ArvestustRecordFormMixin.Meta.exclude + ('likes', 'uploaded_by')
| from django import forms
from ..models.file import File
from .arvestust_record import ArvestustRecordFormMixin
class FileForm(ArvestustRecordFormMixin, forms.ModelForm):
| 41 | 64 | 43 | 15 | 25 | lehvitus/arvestust | arvestust/forms/file.py | Python | FileForm | FileForm | 6 | 9 | 6 | 6 | 3ff3f8df32a3f5db7c924a00a116762001e9101d | bigcode/the-stack | train |
16094058c8a1df039a5a39b4 | train | function | def segment_image(img_file, exp=3):
org = cv2.imread(img_file,cv2.IMREAD_COLOR)
h, w = org.shape[:2]
# removing noise by using Non-local Means Denoising algorithm
img = cv2.fastNlMeansDenoisingColored(org,None,10,10,7,21)
# cv2.imshow('cleaned',img)
# Taking the red component out of RBG image... | def segment_image(img_file, exp=3):
| org = cv2.imread(img_file,cv2.IMREAD_COLOR)
h, w = org.shape[:2]
# removing noise by using Non-local Means Denoising algorithm
img = cv2.fastNlMeansDenoisingColored(org,None,10,10,7,21)
# cv2.imshow('cleaned',img)
# Taking the red component out of RBG image as it is less effected by shadow of... | import numpy as np, cv2, os
from threshold import otsu_threshold
from _8connected import get_8connected
from Area import areaThreshold_by_havg
def segment_image(img_file, exp=3):
| 46 | 234 | 781 | 10 | 35 | deepakrana47/Wheat-quality-detector | segment_formation_1.py | Python | segment_image | segment_image | 6 | 65 | 6 | 6 | 7fef1a266cd46c24c2813d6c57855135aebea4e7 | bigcode/the-stack | train |
573945fbd8dbc60bcac2aa33 | train | function | def get_files(indir):
indir = indir.rstrip('/')
flist =os.listdir(indir)
files = []
for f in flist:
f = indir+'/'+f
if os.path.isdir(f):
tfiles = get_files(f)
files += [tf for tf in tfiles]
else:
files.append(f)
return files
| def get_files(indir):
| indir = indir.rstrip('/')
flist =os.listdir(indir)
files = []
for f in flist:
f = indir+'/'+f
if os.path.isdir(f):
tfiles = get_files(f)
files += [tf for tf in tfiles]
else:
files.append(f)
return files
| (0, 0, 255), 1)
segments[i] = torg[s[i][0]:s[i][1],s[i][2]:s[i][3]]
# cv2.imwrite( "result_image.jpg", rect);
return segments, s
def get_files(indir):
| 64 | 64 | 77 | 6 | 57 | deepakrana47/Wheat-quality-detector | segment_formation_1.py | Python | get_files | get_files | 67 | 78 | 67 | 67 | 81ce1bccc1db3d1c7f48ea470582707ec825e85b | bigcode/the-stack | train |
fb6c326a03345f3368aa4eba | train | class | class GlobalPolicyProgressEnum(enum.Int):
NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETE = 2
| class GlobalPolicyProgressEnum(enum.Int):
| NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETE = 2
| :\InGame\Gameplay\Scripts\Server\global_policies\global_policy_enums.py
# Compiled at: 2019-01-17 02:35:04
# Size of source mod 2**32: 440 bytes
import enum
class GlobalPolicyProgressEnum(enum.Int):
| 64 | 64 | 28 | 8 | 55 | velocist/TS4CheatsInfo | Scripts/simulation/global_policies/global_policy_enums.py | Python | GlobalPolicyProgressEnum | GlobalPolicyProgressEnum | 9 | 12 | 9 | 9 | 6443e1468b82886b489d0a291e1ef4b436035644 | bigcode/the-stack | train |
a3b74e9bd7a2eb966123d9ff | train | class | class GlobalPolicyTokenType(enum.Int):
NAME = 0
PROGRESS = 1 | class GlobalPolicyTokenType(enum.Int):
| NAME = 0
PROGRESS = 1 | -01-17 02:35:04
# Size of source mod 2**32: 440 bytes
import enum
class GlobalPolicyProgressEnum(enum.Int):
NOT_STARTED = 0
IN_PROGRESS = 1
COMPLETE = 2
class GlobalPolicyTokenType(enum.Int):
| 64 | 64 | 20 | 8 | 55 | velocist/TS4CheatsInfo | Scripts/simulation/global_policies/global_policy_enums.py | Python | GlobalPolicyTokenType | GlobalPolicyTokenType | 15 | 17 | 15 | 15 | b1219a7a201f082a22761b27f7a6bee6ebe4d2c2 | bigcode/the-stack | train |
64dbbb58f7fa76caceafe75e | train | class | class Detection(object):
"""
This class represents a bounding box detection in a single image.
Parameters
----------
tlwh : array_like
Bounding box in format `(x, y, w, h)`.
confidence : float
Detector confidence score.
feature : array_like
A feature vector that desc... | class Detection(object):
| """
This class represents a bounding box detection in a single image.
Parameters
----------
tlwh : array_like
Bounding box in format `(x, y, w, h)`.
confidence : float
Detector confidence score.
feature : array_like
A feature vector that describes the object containe... | # vim: expandtab:ts=4:sw=4
import numpy as np
class Detection(object):
| 23 | 102 | 342 | 4 | 18 | rohitkuk/yolox_deepsort | deep_sort/deep_sort/sort/detection.py | Python | Detection | Detection | 5 | 50 | 5 | 5 | 495d7efb47c9528218f98712fb6d34e7f38a17ab | bigcode/the-stack | train |
401e64f3cab7ab5946c16028 | train | class | class SectorIndustryReportSchema(Schema):
"""SectorIndustryReportSchema."""
subscription_count = fields.Integer()
cycle_count = fields.Integer()
| class SectorIndustryReportSchema(Schema):
| """SectorIndustryReportSchema."""
subscription_count = fields.Integer()
cycle_count = fields.Integer()
| """Report Schemas."""
# Third-Party Libraries
from marshmallow import Schema, fields
class SectorIndustryReportSchema(Schema):
| 27 | 64 | 29 | 8 | 18 | cisagov/con-pca-api | src/api/schemas/reports_schema.py | Python | SectorIndustryReportSchema | SectorIndustryReportSchema | 6 | 10 | 6 | 6 | 800dc38c2e9534a1d4f711df9193bdbfde7ee4d8 | bigcode/the-stack | train |
401d4acb6a98795c7c8cd444 | train | class | class AggregateReportsSchema(Schema):
"""AggregateStatsSchema."""
customers_enrolled = fields.Integer()
status_reports_sent = fields.Integer()
cycle_reports_sent = fields.Integer()
yearly_reports_sent = fields.Integer()
federal_stats = fields.Nested(SectorIndustryReportSchema())
state_stats... | class AggregateReportsSchema(Schema):
| """AggregateStatsSchema."""
customers_enrolled = fields.Integer()
status_reports_sent = fields.Integer()
cycle_reports_sent = fields.Integer()
yearly_reports_sent = fields.Integer()
federal_stats = fields.Nested(SectorIndustryReportSchema())
state_stats = fields.Nested(SectorIndustryReportS... | """Report Schemas."""
# Third-Party Libraries
from marshmallow import Schema, fields
class SectorIndustryReportSchema(Schema):
"""SectorIndustryReportSchema."""
subscription_count = fields.Integer()
cycle_count = fields.Integer()
class AggregateReportsSchema(Schema):
| 55 | 64 | 134 | 7 | 48 | cisagov/con-pca-api | src/api/schemas/reports_schema.py | Python | AggregateReportsSchema | AggregateReportsSchema | 13 | 26 | 13 | 13 | f38b3be3bc537a69bd7720d169c58ba00c44e25b | bigcode/the-stack | train |
530e0e5ccfa0bcb8a252936c | train | class | class SharedKeysOperations(object):
"""SharedKeysOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:... | class SharedKeysOperations(object):
| """SharedKeysOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model se... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 110 | 256 | 1,540 | 6 | 103 | iscai-msft/azure-sdk-for-python | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_shared_keys_operations.py | Python | SharedKeysOperations | SharedKeysOperations | 19 | 166 | 19 | 19 | 03b71151c9115f830739f61e28c58bf85414cde6 | bigcode/the-stack | train |
be7d62f2a97e41704b890875 | train | class | class _SSLPipe(object):
"""An SSL "Pipe".
An SSL pipe allows you to communicate with an SSL/TLS protocol instance
through memory buffers. It can be used to implement a security layer for an
existing connection where you don't have access to the connection's file
descriptor, or for some reason... | class _SSLPipe(object):
| """An SSL "Pipe".
An SSL pipe allows you to communicate with an SSL/TLS protocol instance
through memory buffers. It can be used to implement a security layer for an
existing connection where you don't have access to the connection's file
descriptor, or for some reason you don't want to use it... | _hostname):
if server_side:
raise ValueError('Server side SSL needs a valid SSLContext')
# Client side may pass ssl=True to use a default
# context; in that case the sslcontext passed is None.
# The default is secure for client connections.
if hasattr(ssl, 'create_default_context'):
... | 255 | 256 | 2,106 | 7 | 248 | iveskim/cloudbase-init-installer | Python36_x86_Template/Lib/asyncio/sslproto.py | Python | _SSLPipe | _SSLPipe | 48 | 291 | 48 | 48 | 25a86ca4cef8dc5c2545e13393e23ecf2cc7c3f3 | bigcode/the-stack | train |
a862569f6c28916c0f72fed0 | train | function | def _create_transport_context(server_side, server_hostname):
if server_side:
raise ValueError('Server side SSL needs a valid SSLContext')
# Client side may pass ssl=True to use a default
# context; in that case the sslcontext passed is None.
# The default is secure for client connections.... | def _create_transport_context(server_side, server_hostname):
| if server_side:
raise ValueError('Server side SSL needs a valid SSLContext')
# Client side may pass ssl=True to use a default
# context; in that case the sslcontext passed is None.
# The default is secure for client connections.
if hasattr(ssl, 'create_default_context'):
# Py... |
import warnings
try:
import ssl
except ImportError: # pragma: no cover
ssl = None
from . import base_events
from . import compat
from . import protocols
from . import transports
from .log import logger
def _create_transport_context(server_side, server_hostname):
| 64 | 64 | 194 | 11 | 52 | iveskim/cloudbase-init-installer | Python36_x86_Template/Lib/asyncio/sslproto.py | Python | _create_transport_context | _create_transport_context | 15 | 34 | 15 | 15 | d643f2c2ab43e68b6bbb6d3d1a8f53f1a8271e05 | bigcode/the-stack | train |
292d46ecd6ce7a6ea44bf9db | train | function | def _is_sslproto_available():
return hasattr(ssl, "MemoryBIO")
| def _is_sslproto_available():
| return hasattr(ssl, "MemoryBIO")
| Context(ssl.PROTOCOL_SSLv23)
sslcontext.options |= ssl.OP_NO_SSLv2
sslcontext.options |= ssl.OP_NO_SSLv3
sslcontext.set_default_verify_paths()
sslcontext.verify_mode = ssl.CERT_REQUIRED
return sslcontext
def _is_sslproto_available():
| 64 | 64 | 17 | 7 | 56 | iveskim/cloudbase-init-installer | Python36_x86_Template/Lib/asyncio/sslproto.py | Python | _is_sslproto_available | _is_sslproto_available | 37 | 38 | 37 | 37 | 2aada4ef4470688a56d9e703b0b1405bc7a952ff | bigcode/the-stack | train |
5b4ddbd5122eafe51ed8e557 | train | class | class _SSLProtocolTransport(transports._FlowControlMixin,
transports.Transport):
def __init__(self, loop, ssl_protocol):
self._loop = loop
# SSLProtocol instance
self._ssl_protocol = ssl_protocol
self._closed = False
def get_extra_info(self,... | class _SSLProtocolTransport(transports._FlowControlMixin,
transports.Transport):
| def __init__(self, loop, ssl_protocol):
self._loop = loop
# SSLProtocol instance
self._ssl_protocol = ssl_protocol
self._closed = False
def get_extra_info(self, name, default=None):
"""Get optional transport information."""
return self._ssl_protocol._get_... | (ssldata, len(data))
ssldata = []
view = memoryview(data)
while True:
self._need_ssldata = False
try:
if offset < len(view):
offset += self._sslobj.write(view[offset:])
except ssl.SSLError as exc:
... | 256 | 256 | 859 | 16 | 240 | iveskim/cloudbase-init-installer | Python36_x86_Template/Lib/asyncio/sslproto.py | Python | _SSLProtocolTransport | _SSLProtocolTransport | 294 | 402 | 294 | 296 | b068a848abd37f1d5b439339c2b0c502d1c03246 | bigcode/the-stack | train |
9e2a1ba72fec261e46076e6a | train | class | class SSLProtocol(protocols.Protocol):
"""SSL protocol.
Implementation of SSL on top of a socket using incoming and outgoing
buffers which are ssl.MemoryBIO objects.
"""
def __init__(self, loop, app_protocol, sslcontext, waiter,
server_side=False, server_hostname=None,
... | class SSLProtocol(protocols.Protocol):
| """SSL protocol.
Implementation of SSL on top of a socket using incoming and outgoing
buffers which are ssl.MemoryBIO objects.
"""
def __init__(self, loop, app_protocol, sslcontext, waiter,
server_side=False, server_hostname=None,
call_connection_made=True... | and computation
concurrently.
"""
self._ssl_protocol._transport.set_write_buffer_limits(high, low)
def get_write_buffer_size(self):
"""Return the current size of the write buffer."""
return self._ssl_protocol._transport.get_write_buffer_size()
def write(self, ... | 256 | 256 | 2,215 | 7 | 249 | iveskim/cloudbase-init-installer | Python36_x86_Template/Lib/asyncio/sslproto.py | Python | SSLProtocol | SSLProtocol | 405 | 701 | 405 | 405 | 4a22573e5a5afa086def540e3828bb7fba6d564a | bigcode/the-stack | train |
18b6bfd5f0394e2020ab09a2 | train | function | def filter_fields(f):
@functools.wraps(f)
def inner_filter(*args, **kwargs):
result = f(*args, **kwargs)
fields = kwargs.get('fields')
if not fields:
try:
pos = f.__code__.co_varnames.index('fields')
fields = args[pos]
except (Index... | def filter_fields(f):
@functools.wraps(f)
| def inner_filter(*args, **kwargs):
result = f(*args, **kwargs)
fields = kwargs.get('fields')
if not fields:
try:
pos = f.__code__.co_varnames.index('fields')
fields = args[pos]
except (IndexError, ValueError):
return res... | = f(*args, **kwargs)
if result is None:
return None
elif isinstance(result, list):
return [r.to_dict() for r in result]
else:
return result.to_dict()
return inner
def filter_fields(f):
@functools.wraps(f)
| 64 | 64 | 140 | 14 | 49 | netsec/neutron | neutron/db/db_base_plugin_common.py | Python | filter_fields | filter_fields | 60 | 77 | 60 | 61 | d06a8da15574a77c47c39a75979b8ff1fd3fca7a | bigcode/the-stack | train |
c33a5afba333150f063c2d0d | train | function | def convert_result_to_dict(f):
@functools.wraps(f)
def inner(*args, **kwargs):
result = f(*args, **kwargs)
if result is None:
return None
elif isinstance(result, list):
return [r.to_dict() for r in result]
else:
return result.to_dict()
ret... | def convert_result_to_dict(f):
@functools.wraps(f)
| def inner(*args, **kwargs):
result = f(*args, **kwargs)
if result is None:
return None
elif isinstance(result, list):
return [r.to_dict() for r in result]
else:
return result.to_dict()
return inner
| 2
from neutron.objects import base as base_obj
from neutron.objects import ports as port_obj
from neutron.objects import subnet as subnet_obj
from neutron.objects import subnetpool as subnetpool_obj
LOG = logging.getLogger(__name__)
def convert_result_to_dict(f):
@functools.wraps(f)
| 64 | 64 | 77 | 16 | 48 | netsec/neutron | neutron/db/db_base_plugin_common.py | Python | convert_result_to_dict | convert_result_to_dict | 46 | 57 | 46 | 47 | 05a0132ce74f631e5348c9ec090a56cdaa492059 | bigcode/the-stack | train |
a186e693cddb63008ecccee2 | train | class | class DbBasePluginCommon(object):
"""Stores getters and helper methods for db_base_plugin_v2
All private getters and simple helpers like _make_*_dict were moved from
db_base_plugin_v2.
More complicated logic and public methods left in db_base_plugin_v2.
Main purpose of this class is to make getters... | class DbBasePluginCommon(object):
| """Stores getters and helper methods for db_base_plugin_v2
All private getters and simple helpers like _make_*_dict were moved from
db_base_plugin_v2.
More complicated logic and public methods left in db_base_plugin_v2.
Main purpose of this class is to make getters accessible for Ipam
backends.... | as port_obj
from neutron.objects import subnet as subnet_obj
from neutron.objects import subnetpool as subnetpool_obj
LOG = logging.getLogger(__name__)
def convert_result_to_dict(f):
@functools.wraps(f)
def inner(*args, **kwargs):
result = f(*args, **kwargs)
if result is None:
r... | 256 | 256 | 2,635 | 7 | 248 | netsec/neutron | neutron/db/db_base_plugin_common.py | Python | DbBasePluginCommon | DbBasePluginCommon | 80 | 347 | 80 | 80 | 8d71a00944f2184800276f6f05f7007d49945efd | bigcode/the-stack | train |
e65a50a696e53976f9d933fe | train | function | def test_dynamics_online():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'dynamics-online')
if os.path.isdir(dir_path):
ch1 = ["1-4", "1-5", "1-6", "1-7", "1-8", "1-9_1", "1-9_2", "1-9_3"]
ch2 = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7... | def test_dynamics_online():
| dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'dynamics-online')
if os.path.isdir(dir_path):
ch1 = ["1-4", "1-5", "1-6", "1-7", "1-8", "1-9_1", "1-9_2", "1-9_3"]
ch2 = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9",
... | _path):
l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6",
"tutor7"]
for i in l:
in_filepath = os.path.join("autolev-tutorial", i + ".al")
out_filepath = os.path.join("autolev-tutorial", i + ".py")
_test_examples(in_filepath, out_filep... | 104 | 104 | 349 | 7 | 97 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | test_dynamics_online | test_dynamics_online | 75 | 92 | 75 | 76 | 920efbc5aa98eb63e48282918efe1db52e22db7a | bigcode/the-stack | train |
c0b9f65ee2ea862f6ae76117 | train | function | def test_pydy_examples():
l = ["mass_spring_damper", "chaos_pendulum", "double_pendulum",
"non_min_pendulum"]
for i in l:
in_filepath = os.path.join("pydy-example-repo", i + ".al")
out_filepath = os.path.join("pydy-example-repo", i + ".py")
_test_examples(in_filepath, ... | def test_pydy_examples():
| l = ["mass_spring_damper", "chaos_pendulum", "double_pendulum",
"non_min_pendulum"]
for i in l:
in_filepath = os.path.join("pydy-example-repo", i + ".al")
out_filepath = os.path.join("pydy-example-repo", i + ".py")
_test_examples(in_filepath, out_filepath, i)
| "ruletest10",
"ruletest11", "ruletest12"]
for i in l:
in_filepath = i + ".al"
out_filepath = i + ".py"
_test_examples(in_filepath, out_filepath, i)
def test_pydy_examples():
| 64 | 64 | 99 | 8 | 56 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | test_pydy_examples | test_pydy_examples | 50 | 58 | 50 | 51 | a9ade2c1a435da51bd167b5279c3d1f35c81786c | bigcode/the-stack | train |
9ce1dafb6ab1370e41544a79 | train | function | def test_output_01():
"""Autolev example calculates the position, velocity, and acceleration of a
point and expresses in a single reference frame::
(1) FRAMES C,D,F
(2) VARIABLES FD'',DC''
(3) CONSTANTS R,L
(4) POINTS O,E
(5) SIMPROT(F,D,1,FD)
-... | def test_output_01():
| """Autolev example calculates the position, velocity, and acceleration of a
point and expresses in a single reference frame::
(1) FRAMES C,D,F
(2) VARIABLES FD'',DC''
(3) CONSTANTS R,L
(4) POINTS O,E
(5) SIMPROT(F,D,1,FD)
-> (6) F_D = [1, 0, 0; 0... | ", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9",
"circular"]
ch3 = ["3-1_1", "3-1_2", "3-2_1", "3-2_2", "3-2_3", "3-2_4", "3-2_5",
"3-3"]
ch4 = ["4-1_1", "4-2_1", "4-4_1", "4-4_2", "4-5_1", "4-5_2"]
chapters = [(ch1, "ch1"), (ch2, "ch2"), (ch3, "ch3")... | 256 | 256 | 1,297 | 6 | 250 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | test_output_01 | test_output_01 | 95 | 178 | 95 | 95 | 2c133bf79192184764e70eaa7bda46b04ff50edb | bigcode/the-stack | train |
fd343c01461d3d08ee4e16b0 | train | function | def _test_examples(in_filename, out_filename, test_name=""):
in_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
in_filename)
correct_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
out_filename)
with op... | def _test_examples(in_filename, out_filename, test_name=""):
| in_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
in_filename)
correct_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
out_filename)
with open(in_file_path) as f:
generated_code = parse_autolev(f... | import parse_autolev
antlr4 = import_module("antlr4")
if not antlr4:
disabled = True
FILE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
def _test_examples(in_filename, out_filename, test_name=""):
| 63 | 64 | 180 | 15 | 48 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | _test_examples | _test_examples | 17 | 35 | 17 | 18 | fff48e804b4a5b26cc919477884b4a9f25311010 | bigcode/the-stack | train |
36bf120a824343975ba41332 | train | function | def test_rule_tests():
l = ["ruletest1", "ruletest2", "ruletest3", "ruletest4", "ruletest5",
"ruletest6", "ruletest7", "ruletest8", "ruletest9", "ruletest10",
"ruletest11", "ruletest12"]
for i in l:
in_filepath = i + ".al"
out_filepath = i + ".py"
_test_examp... | def test_rule_tests():
| l = ["ruletest1", "ruletest2", "ruletest3", "ruletest4", "ruletest5",
"ruletest6", "ruletest7", "ruletest8", "ruletest9", "ruletest10",
"ruletest11", "ruletest12"]
for i in l:
in_filepath = i + ".al"
out_filepath = i + ".py"
_test_examples(in_filepath, out_filep... | line2 = generated_code.split('\n')[idx]
assert line1.rstrip() == line2.rstrip()
except Exception:
msg = 'mismatch in ' + test_name + ' in line no: {0}'
raise AssertionError(msg.format(idx+1))
def test_rule_tests():
| 63 | 64 | 120 | 6 | 57 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | test_rule_tests | test_rule_tests | 38 | 47 | 38 | 39 | 38ef86874adb4d46df12fb3cd0a8ab340f1a0096 | bigcode/the-stack | train |
39211921348f76e022d09948 | train | function | def test_autolev_tutorial():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'autolev-tutorial')
if os.path.isdir(dir_path):
l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6",
"tutor7"]
for i in l:
in_fil... | def test_autolev_tutorial():
| dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'autolev-tutorial')
if os.path.isdir(dir_path):
l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6",
"tutor7"]
for i in l:
in_filepath = os.path.join("autolev-tu... | in l:
in_filepath = os.path.join("pydy-example-repo", i + ".al")
out_filepath = os.path.join("pydy-example-repo", i + ".py")
_test_examples(in_filepath, out_filepath, i)
def test_autolev_tutorial():
| 64 | 64 | 140 | 9 | 55 | Michal-Gagala/sympy | sympy/parsing/tests/test_autolev.py | Python | test_autolev_tutorial | test_autolev_tutorial | 61 | 72 | 61 | 62 | 2aae93ae25eb1b1fc35b334cd7ba9b863ae284f5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.