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
846dd9d95b7ef196f1b0a13f
train
function
@git_support def match(command): return ('branch -d' in command.script and 'If you are sure you want to delete it' in command.output)
@git_support def match(command):
return ('branch -d' in command.script and 'If you are sure you want to delete it' in command.output)
from thefrick.utils import replace_argument from thefrick.specific.git import git_support @git_support def match(command):
28
64
36
8
19
earboxer/thefrick
thefrick/rules/git_branch_delete.py
Python
match
match
5
8
5
6
0a78508a98411274045046bd3585dc922b55ac81
bigcode/the-stack
train
c0f875caced49d86ce92f89b
train
class
class hsdp(terrascript.Provider): pass
class hsdp(terrascript.Provider):
pass
# terrascript/hsdp/__init__.py # Automatically generated by tools/makecode.py () import warnings warnings.warn( "using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2 ) import terrascript class hsdp(terrascript.Provider):
62
64
12
9
52
mjuenema/python-terrascript
terrascript/hsdp/__init__.py
Python
hsdp
hsdp
13
14
13
13
64a4976a9aa21f7f598bf9b47788c3fd302cf7ca
bigcode/the-stack
train
a478fbc3a35bc720253a7546
train
class
class CreateNetworkInfo(workflows.Step): action_class = CreateNetworkInfoAction contributes = ("net_name", "admin_state", "net_profile_id", "with_subnet", "shared")
class CreateNetworkInfo(workflows.Step):
action_class = CreateNetworkInfoAction contributes = ("net_name", "admin_state", "net_profile_id", "with_subnet", "shared")
network detail if a profile is used. class Meta(object): name = _("Network") help_text = _('Create a new network. ' 'In addition, a subnet associated with the network ' 'can be created in the following steps of this wizard.') class CreateNetworkInfo(work...
63
64
42
8
55
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateNetworkInfo
CreateNetworkInfo
109
112
109
109
297e6697e1041dc2024ec464b802d274a2ccca6a
bigcode/the-stack
train
3d4e937652aa46e6d6cfe79c
train
class
class CreateSubnetInfo(workflows.Step): action_class = CreateSubnetInfoAction contributes = ("subnet_name", "cidr", "ip_version", "gateway_ip", "no_gateway", "subnetpool", "prefixlen", "address_source")
class CreateSubnetInfo(workflows.Step):
action_class = CreateSubnetInfoAction contributes = ("subnet_name", "cidr", "ip_version", "gateway_ip", "no_gateway", "subnetpool", "prefixlen", "address_source")
): cleaned_data = super(CreateSubnetInfoAction, self).clean() with_subnet = cleaned_data.get('with_subnet') if not with_subnet: return cleaned_data self._check_subnet_data(cleaned_data) return cleaned_data class CreateSubnetInfo(workflows.Step):
64
64
56
8
55
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateSubnetInfo
CreateSubnetInfo
342
346
342
342
e77a08c78e6fee1153770e7b018ab5bb7c898282
bigcode/the-stack
train
43d87afdf8ba5db012f55e7c
train
class
class CreateSubnetDetail(workflows.Step): action_class = CreateSubnetDetailAction contributes = ("enable_dhcp", "ipv6_modes", "allocation_pools", "dns_nameservers", "host_routes")
class CreateSubnetDetail(workflows.Step):
action_class = CreateSubnetDetailAction contributes = ("enable_dhcp", "ipv6_modes", "allocation_pools", "dns_nameservers", "host_routes")
self).clean() self._check_allocation_pools(cleaned_data.get('allocation_pools')) self._check_host_routes(cleaned_data.get('host_routes')) self._check_dns_nameservers(cleaned_data.get('dns_nameservers')) return cleaned_data class CreateSubnetDetail(workflows.Step):
64
64
45
8
55
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateSubnetDetail
CreateSubnetDetail
469
472
469
469
37a9eb0d0c40e84687935738662149a3eacaf806
bigcode/the-stack
train
4e0b1071f979e822719d1a98
train
class
class CreateSubnetDetailAction(workflows.Action): enable_dhcp = forms.BooleanField(label=_("Enable DHCP"), initial=True, required=False) ipv6_modes = forms.ChoiceField( label=_("IPv6 Address Configuration Mode"), widget=forms.Select(attrs={ 'class...
class CreateSubnetDetailAction(workflows.Action):
enable_dhcp = forms.BooleanField(label=_("Enable DHCP"), initial=True, required=False) ipv6_modes = forms.ChoiceField( label=_("IPv6 Address Configuration Mode"), widget=forms.Select(attrs={ 'class': 'switched', 'data-switch-on': 'ipve...
the Network Address is " "too small (/%s).") % subnet.prefixlen self._errors['cidr'] = self.error_class([msg]) self._check_cidr_allowed(ip_version, subnet) if not no_gateway and gateway_ip: if netaddr.IPAddress(gateway_ip).version is not ip_versi...
256
256
1,121
9
247
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateSubnetDetailAction
CreateSubnetDetailAction
349
466
349
349
b619c7bc3450f8abe62654718aad2cc72b0a5e39
bigcode/the-stack
train
66a12447be3725b472b565a9
train
class
class CreateNetworkInfoAction(workflows.Action): net_name = forms.CharField(max_length=255, label=_("Network Name"), required=False) if api.neutron.is_port_profiles_supported(): widget = None else: widget = forms.HiddenInput() ...
class CreateNetworkInfoAction(workflows.Action):
net_name = forms.CharField(max_length=255, label=_("Network Name"), required=False) if api.neutron.is_port_profiles_supported(): widget = None else: widget = forms.HiddenInput() net_profile_id = forms.ThemableChoiceField(label...
.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # und...
170
170
569
9
161
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateNetworkInfoAction
CreateNetworkInfoAction
36
106
36
36
2cd65a54b39512d53ffb45915633a3b7370b4f22
bigcode/the-stack
train
21574ef21035a402585a0ccc
train
class
class CreateSubnetInfoAction(workflows.Action): subnet_name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={ }), label=_("Subnet Name"), required=False) addres...
class CreateSubnetInfoAction(workflows.Action):
subnet_name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={ }), label=_("Subnet Name"), required=False) address_source = forms.ChoiceField( required=F...
['shared'].help_text = _( 'Non admin users are not allowed to set shared option.') def get_network_profile_choices(self, request): profile_choices = [('', _("Select a profile"))] for profile in self._get_profiles(request, 'network'): profile_choices.append((profile.id, p...
256
256
2,017
9
247
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateSubnetInfoAction
CreateSubnetInfoAction
115
339
115
115
f77a0ffb7d39d8704db8c8e480d16c4a584f4700
bigcode/the-stack
train
2149f4cea527e80bae26665a
train
class
class CreateNetwork(workflows.Workflow): slug = "create_network" name = _("Create Network") finalize_button_name = _("Create") success_message = _('Created network "%s".') failure_message = _('Unable to create network "%s".') default_steps = (CreateNetworkInfo, CreateSubnetI...
class CreateNetwork(workflows.Workflow):
slug = "create_network" name = _("Create Network") finalize_button_name = _("Create") success_message = _('Created network "%s".') failure_message = _('Unable to create network "%s".') default_steps = (CreateNetworkInfo, CreateSubnetInfo, CreateSubnetDet...
continue self._convert_ip_address(ns, "dns_nameservers") def _check_host_routes(self, host_routes): for r in host_routes.split('\n'): r = r.strip() if not r: continue route = r.split(',') if len(route) != 2: msg = ...
256
256
1,298
7
249
vanduc95/Horizon
openstack_dashboard/dashboards/project/networks/workflows.py
Python
CreateNetwork
CreateNetwork
475
623
475
475
1a7785baa7cf59b9b6871020b23d43f356348c55
bigcode/the-stack
train
119bcca2b3e80284dabe8554
train
class
class MusicApplyView(HTTPMethodView): def get(self, request: Request, weekday: int): """ Response Music Apply Status """ pass def post(self, request: Request, weekday: int): """ Apply Music """ pass def delete(self, request: Request, weekday:...
class MusicApplyView(HTTPMethodView):
def get(self, request: Request, weekday: int): """ Response Music Apply Status """ pass def post(self, request: Request, weekday: int): """ Apply Music """ pass def delete(self, request: Request, weekday: int): """ Delete Musi...
from sanic.request import Request from sanic.views import HTTPMethodView class MusicApplyView(HTTPMethodView):
25
64
87
9
15
Nerd-Bear/DMS-Sanic
dms/views/apply/music.py
Python
MusicApplyView
MusicApplyView
5
22
5
5
cdf74450797a6ccdc6b5b2977ac847b951b2b28d
bigcode/the-stack
train
d029f568ced561b9f983db07
train
class
class MyError(Exception): pass
class MyError(Exception):
pass
urlparse # pylint:enable=import-error,no-name-in-module,wrong-import-order,relative-import from boxsdk.exception import BoxOAuthException from boxsdk.network.default_network import DefaultNetworkResponse from boxsdk.auth.oauth2 import OAuth2 from boxsdk.config import API class MyError(Exception):
64
64
8
5
58
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
MyError
MyError
23
24
23
23
3238c4dc6df497a1298a1f536f205c116a58957f
bigcode/the-stack
train
01717b2a4e8d575bf915ad6b
train
function
def test_token_requests_fail_after_close(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) auth.close() with pytest.raises(ValueError): auth.refresh(auth.access_token)
def test_token_requests_fail_after_close(client_id, client_secret, mock_box_session):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) auth.close() with pytest.raises(ValueError): auth.refresh(auth.access_token)
_true_after_close(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) auth.close() assert auth.closed is True def test_token_requests_fail_after_close(client_id, client_secret, mock_box_session):
64
64
58
17
46
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_token_requests_fail_after_close
test_token_requests_fail_after_close
412
416
412
412
7d1a64ef1680fda7b5a6a385a01fd986a4bf0530
bigcode/the-stack
train
8806c6eeb1220170ab8c25d3
train
function
def test_get_correct_authorization_url(redirect_url): # pylint:disable=redefined-outer-name fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' oauth2 = OAuth2( client_id=fake_client_id, client_secret=fake_client_secret, ) auth_url, csrf_token = oauth2.get...
def test_get_correct_authorization_url(redirect_url): # pylint:disable=redefined-outer-name
fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' oauth2 = OAuth2( client_id=fake_client_id, client_secret=fake_client_secret, ) auth_url, csrf_token = oauth2.get_authorization_url(redirect_url=redirect_url) expected_auth_url_format = '{0}?state={1}&resp...
?Ƅȁŕ=Ƅȁż', None)) def redirect_url(request): """A value for the `redirect_uri` query string parameter for OAuth2.""" return request.param def test_get_correct_authorization_url(redirect_url): # pylint:disable=redefined-outer-name
64
64
197
21
42
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_get_correct_authorization_url
test_get_correct_authorization_url
37
55
37
38
23bc7b653300a818de4e6a19c7ec0e900b15f5cc
bigcode/the-stack
train
7527cd924d4037ba0ee4fbf3
train
function
@pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_getting_bad_network_response( token_method, mock_box_session, bad_network_response, ): with pytest.raises(BoxOAuthException): ...
@pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_getting_bad_network_response( token_method, mock_box_session, bad_network_response, ):
with pytest.raises(BoxOAuthException): mock_box_session.request.return_value = bad_network_response oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) token_method(oauth)
='fake_code') return None @pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_getting_bad_network_response( token_method, mock_box_session, bad_network_response, ):
64
64
115
56
7
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_token_request_raises_box_oauth_exception_when_getting_bad_network_response
test_token_request_raises_box_oauth_exception_when_getting_bad_network_response
212
230
212
221
8f2de28322f500f14562baf7e5ba4aed68663eea
bigcode/the-stack
train
b9688d9224978254d1d6c2ea
train
function
@pytest.mark.parametrize('_', range(10)) def test_refresh_gives_back_the_correct_response_and_handles_multiple_requests( mock_box_session, successful_token_response, network_response_with_missing_tokens, _, ): # pylint:disable=redefined-outer-name fake_client_id = 'fake_client_id...
@pytest.mark.parametrize('_', range(10)) def test_refresh_gives_back_the_correct_response_and_handles_multiple_requests( mock_box_session, successful_token_response, network_response_with_missing_tokens, _, ): # pylint:disable=redefined-outer-name
fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_refresh_token = 'fake_refresh_token' fake_access_token = 'fake_access_token' # Setup the network layer so that if oauth makes more than one request, it will get a malformed response and failed # the test. mock_...
mock_token_callback.assert_called_once_with(access_token, refresh_token) assert access_token == successful_token_response.json()['access_token'] assert refresh_token == successful_token_response.json()['refresh_token'] @pytest.mark.parametrize('_', range(10)) def test_refresh_gives_back_the_correct_response_a...
93
93
313
54
39
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_refresh_gives_back_the_correct_response_and_handles_multiple_requests
test_refresh_gives_back_the_correct_response_and_handles_multiple_requests
161
199
161
168
cbacaffcb3f7247a8a3e7b43cd86d12a65ed434e
bigcode/the-stack
train
4e59d6079ff40bbd41d91195
train
function
@pytest.mark.parametrize('_', range(10)) def test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests( mock_box_session, successful_token_response, _, ): fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_refresh_token = 'fake_ref...
@pytest.mark.parametrize('_', range(10)) def test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests( mock_box_session, successful_token_response, _, ):
fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_refresh_token = 'fake_refresh_token' fake_access_token = 'fake_access_token' data = { 'grant_type': 'refresh_token', 'refresh_token': fake_refresh_token, 'client_id': fake_client_id, 'cli...
.authenticate(fake_auth_code) mock_box_session.request.assert_called_once_with( 'POST', '{0}/token'.format(API.OAUTH2_API_URL), data=data, headers={'content-type': 'application/x-www-form-urlencoded'}, access_token=None, ) assert oauth.access_token == successful_tok...
108
108
363
37
71
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests
test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests
91
137
91
96
79aa5b40ef72044102a6fd36152a7cb2c0c92d95
bigcode/the-stack
train
6543c4d6adcf8439196d0c48
train
function
@pytest.fixture(params=('https://url.com/foo?bar=baz', 'https://ȕŕľ.com/ƒőő?Ƅȁŕ=Ƅȁż', None)) def redirect_url(request): """A value for the `redirect_uri` query string parameter for OAuth2.""" return request.param
@pytest.fixture(params=('https://url.com/foo?bar=baz', 'https://ȕŕľ.com/ƒőő?Ƅȁŕ=Ƅȁż', None)) def redirect_url(request):
"""A value for the `redirect_uri` query string parameter for OAuth2.""" return request.param
Error(Exception): pass class MyBaseException(BaseException): pass @pytest.fixture(params=('https://url.com/foo?bar=baz', 'https://ȕŕľ.com/ƒőő?Ƅȁŕ=Ƅȁż', None)) def redirect_url(request):
64
64
70
48
15
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
redirect_url
redirect_url
31
34
31
32
543d4601fc10cb975a4ca50dedfd64274b91d89d
bigcode/the-stack
train
b193380eb63ec588f8628edc
train
function
@pytest.mark.parametrize(('close_args', 'close_kwargs'), [((False,), {}), ((), dict(revoke=False))]) def test_revoke_on_close_can_be_skipped(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs): auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token,...
@pytest.mark.parametrize(('close_args', 'close_kwargs'), [((False,), {}), ((), dict(revoke=False))]) def test_revoke_on_close_can_be_skipped(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs):
auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token, session=mock_box_session) with patch.object(auth, 'revoke') as mock_revoke: auth.close(*close_args, **close_kwargs) mock_revoke.assert_not_called()
voke=True) assert auth.closed is True @pytest.mark.parametrize(('close_args', 'close_kwargs'), [((False,), {}), ((), dict(revoke=False))]) def test_revoke_on_close_can_be_skipped(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs):
64
64
117
54
9
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_revoke_on_close_can_be_skipped
test_revoke_on_close_can_be_skipped
456
461
456
457
d4cf10e84416729ea3eddd99aff7b61717bdd1f5
bigcode/the-stack
train
d98fa84e8b73b3876205bcff
train
function
def test_closed_is_true_after_close(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) auth.close() assert auth.closed is True
def test_closed_is_true_after_close(client_id, client_secret, mock_box_session):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) auth.close() assert auth.closed is True
def test_closed_is_false_after_init(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) assert auth.closed is False def test_closed_is_true_after_close(client_id, client_secret, mock_box_session):
64
64
51
17
46
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_closed_is_true_after_close
test_closed_is_true_after_close
406
409
406
406
6d58e3842762b4b95ea02f2d0154905bbf4a8848
bigcode/the-stack
train
2e6a249f1008e446dec93873
train
function
def test_authenticate_stores_tokens_correctly(mock_box_session, successful_token_response): fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_auth_code = 'fake_auth_code' mock_box_session.request.return_value = successful_token_response mock_token_callback = Mock() ...
def test_authenticate_stores_tokens_correctly(mock_box_session, successful_token_response):
fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_auth_code = 'fake_auth_code' mock_box_session.request.return_value = successful_token_response mock_token_callback = Mock() oauth = OAuth2( client_id=fake_client_id, client_secret=fake_client_secret...
_with( 'POST', '{0}/token'.format(API.OAUTH2_API_URL), data=data, headers={'content-type': 'application/x-www-form-urlencoded'}, access_token=fake_access_token, ) def test_authenticate_stores_tokens_correctly(mock_box_session, successful_token_response):
64
64
158
17
47
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_authenticate_stores_tokens_correctly
test_authenticate_stores_tokens_correctly
140
158
140
140
22b3ca68f883a9301b8258cc96e8114f950095e0
bigcode/the-stack
train
b6d238a3f02721dcbca7ffcc
train
function
@pytest.mark.parametrize(('raise_from_block', 'raise_from_close', 'expected_exception'), [ (MyError, None, MyError), (None, BoxOAuthException(status=500), BoxOAuthException), (MyError, BoxOAuthException(status=500), MyError), ]) @pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=T...
@pytest.mark.parametrize(('raise_from_block', 'raise_from_close', 'expected_exception'), [ (MyError, None, MyError), (None, BoxOAuthException(status=500), BoxOAuthException), (MyError, BoxOAuthException(status=500), MyError), ]) @pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=T...
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) with patch.object(auth, 'close', side_effect=raise_from_close) as mock_close: with pytest.raises(expected_exception): with auth.closing(**close_kwargs): if raise_from_block: ...
@pytest.mark.parametrize(('raise_from_block', 'raise_from_close', 'expected_exception'), [ (MyError, None, MyError), (None, BoxOAuthException(status=500), BoxOAuthException), (MyError, BoxOAuthException(status=500), MyError), ]) @pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=T...
116
64
198
116
0
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_context_manager_reraises_first_exception_after_close
test_context_manager_reraises_first_exception_after_close
464
479
464
472
cc59808c92a4b269af6d3f366e1bb623aa6f10a5
bigcode/the-stack
train
afb173d18e4977c26bced6b5
train
class
class MyBaseException(BaseException): pass
class MyBaseException(BaseException):
pass
,no-name-in-module,wrong-import-order,relative-import from boxsdk.exception import BoxOAuthException from boxsdk.network.default_network import DefaultNetworkResponse from boxsdk.auth.oauth2 import OAuth2 from boxsdk.config import API class MyError(Exception): pass class MyBaseException(BaseException):
64
64
10
7
56
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
MyBaseException
MyBaseException
27
28
27
27
c0d0891edba41d14100287a1115ca7efbfcb4dbb
bigcode/the-stack
train
f9fed7eda6ca05cbbadbf681
train
function
def test_auth_object_is_closed_even_if_revoke_fails(client_id, client_secret, access_token, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token, session=mock_box_session) with patch.object(auth, 'revoke', side_effect=BoxOAuthException(status=500)): ...
def test_auth_object_is_closed_even_if_revoke_fails(client_id, client_secret, access_token, mock_box_session):
auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token, session=mock_box_session) with patch.object(auth, 'revoke', side_effect=BoxOAuthException(status=500)): with pytest.raises(BoxOAuthException): auth.close(revoke=True) assert auth.closed is True
mock_box_session) with patch.object(auth, 'revoke') as mock_revoke: auth.close(*close_args, **close_kwargs) mock_revoke.assert_called_once_with() def test_auth_object_is_closed_even_if_revoke_fails(client_id, client_secret, access_token, mock_box_session):
64
64
96
25
39
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_auth_object_is_closed_even_if_revoke_fails
test_auth_object_is_closed_even_if_revoke_fails
448
453
448
448
fac76fb906040e135458149d743f2ec41edbfa0d
bigcode/the-stack
train
2f371bf7292495b8a8d1fba5
train
function
@pytest.mark.parametrize( 'access_token,refresh_token,expected_token_to_revoke', ( ('fake_access_token', 'fake_refresh_token', 'fake_access_token'), (None, 'fake_refresh_token', 'fake_refresh_token') ) ) def test_revoke_sends_revoke_request( client_id, client_secret, ...
@pytest.mark.parametrize( 'access_token,refresh_token,expected_token_to_revoke', ( ('fake_access_token', 'fake_refresh_token', 'fake_access_token'), (None, 'fake_refresh_token', 'fake_refresh_token') ) ) def test_revoke_sends_revoke_request( client_id, client_secret, ...
mock_network_response = Mock() mock_network_response.ok = True mock_box_session.request.return_value = mock_network_response oauth.revoke() mock_box_session.request.assert_called_once_with( 'POST', '{0}/revoke'.format(API.OAUTH2_API_URL), data={ 'client_id': clien...
@pytest.mark.parametrize( 'access_token,refresh_token,expected_token_to_revoke', ( ('fake_access_token', 'fake_refresh_token', 'fake_access_token'), (None, 'fake_refresh_token', 'fake_refresh_token') ) ) def test_revoke_sends_revoke_request( client_id, client_secret, ...
91
64
200
91
0
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_revoke_sends_revoke_request
test_revoke_sends_revoke_request
331
360
331
345
27b0dff6553e6efd7deb7a696206dc5a3c4c380d
bigcode/the-stack
train
28bf756f696ca0fe37ec4ce9
train
function
@pytest.fixture() def token_method(request): """ Fixture that returns a partial method based on the method provided in request.param""" if request.param == OAuth2.refresh: return partial(OAuth2.refresh, access_token_to_refresh='fake_access_token') elif request.param == OAuth2.authenticate: r...
@pytest.fixture() def token_method(request):
""" Fixture that returns a partial method based on the method provided in request.param""" if request.param == OAuth2.refresh: return partial(OAuth2.refresh, access_token_to_refresh='fake_access_token') elif request.param == OAuth2.authenticate: return partial(OAuth2.authenticate, auth_code=...
same new access token and # refresh token. threads = [] for _ in range(4): threads.append(Thread(target=refresh_tokens_and_verify_the_response)) for thread in threads: thread.start() for thread in threads: thread.join() @pytest.fixture() def token_method(request):
64
64
78
8
56
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
token_method
token_method
202
209
202
203
024cb7360e99e7809806167adffcf7ecdcf05c0a
bigcode/the-stack
train
8243cef807acc81aa66f055f
train
function
def test_tokens_get_updated_after_noop_refresh(client_id, client_secret, access_token, new_access_token, refresh_token, mock_box_session): """`OAuth2` object should update its state with new tokens, after no-op refresh. If the protected method `_get_tokens()` returns new tokens, refresh is skipped, and tho...
def test_tokens_get_updated_after_noop_refresh(client_id, client_secret, access_token, new_access_token, refresh_token, mock_box_session):
"""`OAuth2` object should update its state with new tokens, after no-op refresh. If the protected method `_get_tokens()` returns new tokens, refresh is skipped, and those tokens are used. This is a regression test for issue #128 [1]. We would return the new tokens without updating the object state...
', '{0}/revoke'.format(API.OAUTH2_API_URL), data={ 'client_id': client_id, 'client_secret': client_secret, 'token': expected_token_to_revoke, }, access_token=access_token, ) assert oauth.access_token is None def test_tokens_get_updated_after_no...
93
93
312
29
63
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_tokens_get_updated_after_noop_refresh
test_tokens_get_updated_after_noop_refresh
363
398
363
363
335ac799555766579d76889ea2592ea99a762aef
bigcode/the-stack
train
6be41a34d30c3c8f2e046cb0
train
function
@pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded( token_method, mock_box_session, non_json_response, ): mock_box_session.request.return_value = no...
@pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded( token_method, mock_box_session, non_json_response, ):
mock_box_session.request.return_value = non_json_response oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) with pytest.raises(BoxOAuthException): token_method(oauth)
token_method(oauth) @pytest.mark.parametrize( 'token_method', [OAuth2.refresh, OAuth2.authenticate], indirect=True, ) def test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded( token_method, mock_box_session, non_json_response, ):
64
64
117
58
6
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded
test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded
233
251
233
242
aee49f7e3ec28c335c6b38c6387eed03f4a87ed4
bigcode/the-stack
train
636f5b5408755bb6dbbecf77
train
function
def test_token_request_allows_missing_refresh_token(mock_box_session): mock_network_response = Mock() mock_network_response.ok = True mock_network_response.json.return_value = {'access_token': 'fake_token'} mock_box_session.request.return_value = mock_network_response oauth = OAuth2( client_...
def test_token_request_allows_missing_refresh_token(mock_box_session):
mock_network_response = Mock() mock_network_response.ok = True mock_network_response.json.return_value = {'access_token': 'fake_token'} mock_box_session.request.return_value = mock_network_response oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_toke...
try: oauth.authenticate('fake_auth_code') pytest.fail('Should throw exception because of bad network response') except BoxOAuthException as exception: assert exception.code == 'Example Error' assert exception.message == 'Example Error Description' def test_token_request_allows_mi...
64
64
104
13
51
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_token_request_allows_missing_refresh_token
test_token_request_allows_missing_refresh_token
306
317
306
306
f1005969aad47beeaf3811ac3a14e8509ba026da
bigcode/the-stack
train
8d3789c6512d9edf42be86e5
train
function
@pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=True)]) def test_context_manager_skips_revoke_on_base_exception(client_id, client_secret, mock_box_session, close_kwargs): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) with patch.object(aut...
@pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=True)]) def test_context_manager_skips_revoke_on_base_exception(client_id, client_secret, mock_box_session, close_kwargs):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) with patch.object(auth, 'close') as mock_close: with pytest.raises(MyBaseException): with auth.closing(**close_kwargs): raise MyBaseException mock_close.assert_called_once_with(revok...
raise_from_block: raise raise_from_block mock_close.assert_called_once_with(**close_kwargs) @pytest.mark.parametrize('close_kwargs', [{}, dict(revoke=False), dict(revoke=True)]) def test_context_manager_skips_revoke_on_base_exception(client_id, client_secret, mock_box_session, close_kwargs):
64
64
113
43
21
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_context_manager_skips_revoke_on_base_exception
test_context_manager_skips_revoke_on_base_exception
482
489
482
483
7126d429a319d2be2560b23f323c80ca6dd41155
bigcode/the-stack
train
2be87f65674984034e51d50c
train
function
@pytest.mark.parametrize('test_method', [ partial(OAuth2.refresh, access_token_to_refresh='fake_access_token'), partial(OAuth2.authenticate, auth_code='fake_code') ]) def test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response( test_method, mock_box_session, net...
@pytest.mark.parametrize('test_method', [ partial(OAuth2.refresh, access_token_to_refresh='fake_access_token'), partial(OAuth2.authenticate, auth_code='fake_code') ]) def test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response( test_method, mock_box_session, net...
mock_box_session.request.return_value = network_response_with_missing_tokens oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) with pytest.raises(BoxOAuthException): test_method(oauth)
@pytest.mark.parametrize('test_method', [ partial(OAuth2.refresh, access_token_to_refresh='fake_access_token'), partial(OAuth2.authenticate, auth_code='fake_code') ]) def test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response( test_method, mock_box_session, net...
83
64
144
83
0
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response
test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response
269
287
269
278
e4f6f062560b365f8ca4e730c256faabd7437d3a
bigcode/the-stack
train
4375ace992f7b155b9ce68c3
train
function
def test_oauth_exception_error_and_error_description(mock_box_session, bad_network_response_400): mock_box_session.request.return_value = bad_network_response_400 oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) ...
def test_oauth_exception_error_and_error_description(mock_box_session, bad_network_response_400):
mock_box_session.request.return_value = bad_network_response_400 oauth = OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) try: oauth.authenticate('fake_auth_code') pytest.fail('Should throw exception bec...
= OAuth2( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) with pytest.raises(BoxOAuthException): test_method(oauth) def test_oauth_exception_error_and_error_description(mock_box_session, bad_network_response_400):
64
64
117
19
45
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_oauth_exception_error_and_error_description
test_oauth_exception_error_and_error_description
290
303
290
290
a9d50b5bd24e3f1fa7f531afa15bcd1a797b5977
bigcode/the-stack
train
5cfc88e3978d9ae3aa896d6b
train
function
def test_context_manager_fails_after_close(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) with auth.closing(): pass with pytest.raises(ValueError): with auth.closing(): assert False
def test_context_manager_fails_after_close(client_id, client_secret, mock_box_session):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) with auth.closing(): pass with pytest.raises(ValueError): with auth.closing(): assert False
client_secret=client_secret, session=mock_box_session) try: with auth.closing(): if raise_exception: raise MyError except MyError: pass assert auth.closed is True def test_context_manager_fails_after_close(client_id, client_secret, mock_box_session):
64
64
67
18
45
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_context_manager_fails_after_close
test_context_manager_fails_after_close
431
437
431
431
1aa3d596bf3db7930fa870edbf3db2bcdb34a47a
bigcode/the-stack
train
7aee2fe117751d58c603ca32
train
function
@pytest.mark.parametrize(('close_args', 'close_kwargs'), [((), {}), ((True,), {}), ((), dict(revoke=True))]) def test_revoke_on_close(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs): auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token, sessio...
@pytest.mark.parametrize(('close_args', 'close_kwargs'), [((), {}), ((True,), {}), ((), dict(revoke=True))]) def test_revoke_on_close(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs):
auth = OAuth2(client_id=client_id, client_secret=client_secret, access_token=access_token, session=mock_box_session) with patch.object(auth, 'revoke') as mock_revoke: auth.close(*close_args, **close_kwargs) mock_revoke.assert_called_once_with()
): with auth.closing(): assert False @pytest.mark.parametrize(('close_args', 'close_kwargs'), [((), {}), ((True,), {}), ((), dict(revoke=True))]) def test_revoke_on_close(client_id, client_secret, access_token, mock_box_session, close_args, close_kwargs):
64
64
117
53
10
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_revoke_on_close
test_revoke_on_close
440
445
440
441
9eacc53705f7ed3add7763071929053517da0ffa
bigcode/the-stack
train
484cd4f6672a47d08d22209c
train
function
@pytest.fixture() def oauth(client_id, client_secret, access_token, refresh_token, mock_box_session): return OAuth2( client_id=client_id, client_secret=client_secret, access_token=access_token, refresh_token=refresh_token, session=mock_box_session, )
@pytest.fixture() def oauth(client_id, client_secret, access_token, refresh_token, mock_box_session):
return OAuth2( client_id=client_id, client_secret=client_secret, access_token=access_token, refresh_token=refresh_token, session=mock_box_session, )
( client_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) oauth.send_token_request({}, access_token=None, expect_refresh_token=False) @pytest.fixture() def oauth(client_id, client_secret, access_token, refresh_token, mock_box_session):
64
64
63
21
43
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
oauth
oauth
320
328
320
321
a74c884988d9499a62ea1229895e8c6719e9b4ea
bigcode/the-stack
train
5405160f563197477cbe72d2
train
function
def test_closed_is_false_after_init(client_id, client_secret, mock_box_session): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) assert auth.closed is False
def test_closed_is_false_after_init(client_id, client_secret, mock_box_session):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) assert auth.closed is False
, refresh_token=refresh_token, session=mock_box_session, ) assert oauth.access_token == access_token assert oauth.refresh(access_token) == new_tokens assert oauth.access_token == new_access_token def test_closed_is_false_after_init(client_id, client_secret, mock_box_session):
64
64
47
17
46
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_closed_is_false_after_init
test_closed_is_false_after_init
401
403
401
401
3a6b387167123c9916d0f1be9f30377110b4685d
bigcode/the-stack
train
e369c1dd61de97b4c630ec97
train
function
@pytest.mark.parametrize('raise_exception', [False, True]) def test_context_manager_closes_auth_object(client_id, client_secret, mock_box_session, raise_exception): auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) try: with auth.closing(): if raise_ex...
@pytest.mark.parametrize('raise_exception', [False, True]) def test_context_manager_closes_auth_object(client_id, client_secret, mock_box_session, raise_exception):
auth = OAuth2(client_id=client_id, client_secret=client_secret, session=mock_box_session) try: with auth.closing(): if raise_exception: raise MyError except MyError: pass assert auth.closed is True
, client_secret=client_secret, session=mock_box_session) auth.close() with pytest.raises(ValueError): auth.refresh(auth.access_token) @pytest.mark.parametrize('raise_exception', [False, True]) def test_context_manager_closes_auth_object(client_id, client_secret, mock_box_session, raise_exception):
64
64
90
33
31
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_context_manager_closes_auth_object
test_context_manager_closes_auth_object
419
428
419
420
46f12d0a709a74a3b239c66ece6ce61841082fe8
bigcode/the-stack
train
55d7b69e0bdec1b33d4065d5
train
function
@pytest.fixture(params=[ ['access_token'], ['refresh_token'], [], ]) def network_response_with_missing_tokens(request): mock_network_response = Mock(DefaultNetworkResponse) mock_network_response.ok = True json_dict = {} for key in request.param: json_dict[key] = 'fake_token' mock...
@pytest.fixture(params=[ ['access_token'], ['refresh_token'], [], ]) def network_response_with_missing_tokens(request):
mock_network_response = Mock(DefaultNetworkResponse) mock_network_response.ok = True json_dict = {} for key in request.param: json_dict[key] = 'fake_token' mock_network_response.json.return_value = json_dict return mock_network_response
_id='', client_secret='', access_token='fake_access_token', session=mock_box_session, ) with pytest.raises(BoxOAuthException): token_method(oauth) @pytest.fixture(params=[ ['access_token'], ['refresh_token'], [], ]) def network_response_with_missing_tokens(request):
64
64
82
25
39
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
network_response_with_missing_tokens
network_response_with_missing_tokens
254
266
254
259
ec7bfa94a0a74742f5aefed29171d5cf8eaf8e01
bigcode/the-stack
train
305c32b8fe586675343999f1
train
function
def test_authenticate_send_post_request_with_correct_params(mock_box_session, successful_token_response): fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_auth_code = 'fake_auth_code' data = { 'grant_type': 'authorization_code', 'code': fake_auth_code, ...
def test_authenticate_send_post_request_with_correct_params(mock_box_session, successful_token_response):
fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' fake_auth_code = 'fake_auth_code' data = { 'grant_type': 'authorization_code', 'code': fake_auth_code, 'client_id': fake_client_id, 'client_secret': fake_client_secret, 'box_device_id': '0...
, csrf_token, fake_client_id, urlparse.quote_plus((redirect_url or '').encode('utf-8')), ) assert re.match('^box_csrf_token_[A-Za-z0-9]{16}$', csrf_token) def test_authenticate_send_post_request_with_correct_params(mock_box_session, successful_token_response):
70
70
236
18
52
jayneeljariwala/box-python-sdk
test/unit/auth/test_oauth2.py
Python
test_authenticate_send_post_request_with_correct_params
test_authenticate_send_post_request_with_correct_params
58
88
58
58
5f348b699b559bb2962dea70b1af5940d8ab4009
bigcode/the-stack
train
540dbd934bf0c479ba909be1
train
class
class IReactors(Iterable): '''Experimental API extension exposing Reactor objects''' __slots__ = [] _columns = [ 'Name', 'idx', 'Phases', 'Bus1', 'Bus2', 'SpecType', 'kV', 'kvar', 'IsDelta', 'Parallel', 'LCurve', ...
class IReactors(Iterable):
'''Experimental API extension exposing Reactor objects''' __slots__ = [] _columns = [ 'Name', 'idx', 'Phases', 'Bus1', 'Bus2', 'SpecType', 'kV', 'kvar', 'IsDelta', 'Parallel', 'LCurve', 'RCurve', 'R...
''' A compatibility layer for DSS C-API that mimics the official OpenDSS COM interface. Copyright (c) 2016-2020 Paulo Meira ''' from __future__ import absolute_import from .._cffi_api_util import Iterable class IReactors(Iterable):
60
256
2,234
7
52
dss-extensions/dss_python
dss/dss_capi_gr/IReactors.py
Python
IReactors
IReactors
9
266
9
9
4f3c6e9b66d216902e8069b55ab906550a59bbed
bigcode/the-stack
train
209c742113f7029365d48c63
train
function
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def unsubscribe_user_task(self, result, newsletters=[], optout=False): """Removes a user from the Basket subscription.""" if not result: return None newslett...
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def unsubscribe_user_task(self, result, newsletters=[], optout=False):
"""Removes a user from the Basket subscription.""" if not result: return None newsletters_to_unsubscribe = [] if result.get('status') == 'ok': email = result.get('email') token = result.get('token') # only unsubscribe from our newsletters if newsletters: ...
except basket.BasketException as exc: raise self.retry(exc=exc) return subscribe_result return None @shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def unsubscribe_user_task(self, result, newsletters=[]...
74
74
249
49
24
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
unsubscribe_user_task
unsubscribe_user_task
133
165
133
135
3c604d419a13be8b777d74ed00a88bfa481007af
bigcode/the-stack
train
87ac95a3bb1d966aa6c49c49
train
function
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def subscribe_user_task(self, result, email='', newsletters=[], sync='N', trigger_welcome='N'): """Subscribes a user to basket newsletters. The email to subscribe is prov...
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def subscribe_user_task(self, result, email='', newsletters=[], sync='N', trigger_welcome='N'):
"""Subscribes a user to basket newsletters. The email to subscribe is provided either from the result of the lookup task or from the profile of the user. """ if not result and not email: return None newsletters_to_subscribe = [] if result.get('status') == 'ok': # This is u...
result = {} try: result = basket.lookup_user(email=email) except MaxRetriesExceededError as exc: raise exc except basket.BasketException as exc: if not exc[0] == u'User not found': raise self.retry(exc=exc) result = exc.result return result @shared_task(b...
127
127
425
57
69
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
subscribe_user_task
subscribe_user_task
83
130
83
85
26faad56da742c6669276441c3ff0f11d5dc4d44
bigcode/the-stack
train
0b3af145fa74c4b8efcf4206
train
function
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def lookup_user_task(self, email): """Task responsible for getting information about a user in basket.""" # We need to return always a dictionary for the next task re...
@shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def lookup_user_task(self, email):
"""Task responsible for getting information about a user in basket.""" # We need to return always a dictionary for the next task result = {} try: result = basket.lookup_user(email=email) except MaxRetriesExceededError as exc: raise exc except basket.BasketException as exc: ...
_mail(subject, body, settings.FROM_NOREPLY, recipients_list, fail_silently=False) @shared_task(bind=True, base=DebugBasketTask, default_retry_delay=BASKET_TASK_RETRY_DELAY, max_retries=BASKET_TASK_MAX_RETRIES) def lookup_user_task(self, email):
64
64
140
43
21
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
lookup_user_task
lookup_user_task
64
80
64
66
8304fd29602b36a22e5d211a8398bfefe66fb8b0
bigcode/the-stack
train
44a2672bfef061783a134a53
train
function
@task def check_spam_account(instance_id, **kwargs): """Task to check if profile is spam according to akismet""" # Avoid circular dependencies from mozillians.users.models import AbuseReport, UserProfile spam = akismet_spam_check(**kwargs) profile = get_object_or_none(UserProfile, id=instance_id) ...
@task def check_spam_account(instance_id, **kwargs):
"""Task to check if profile is spam according to akismet""" # Avoid circular dependencies from mozillians.users.models import AbuseReport, UserProfile spam = akismet_spam_check(**kwargs) profile = get_object_or_none(UserProfile, id=instance_id) if spam and profile: kwargs = { ...
) UserProfile.objects.filter(full_name='').filter(user__date_joined__lt=now).delete() @task(ignore_result=False) def check_celery(): """Dummy celery task to check that everything runs smoothly.""" pass @task def check_spam_account(instance_id, **kwargs):
64
64
128
14
49
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
check_spam_account
check_spam_account
246
263
246
247
96328032617a2c8832b4fa594dae2bce8b3f1642
bigcode/the-stack
train
a7f4ef26570330c32f32f878
train
function
@shared_task() def update_email_in_basket(old_email, new_email): """Update user emails in Basket. This task is triggered when users change their email. The task checks whether the user is already subscribed with the old email. If there is a subscription we remove it and we register the new email. "...
@shared_task() def update_email_in_basket(old_email, new_email):
"""Update user emails in Basket. This task is triggered when users change their email. The task checks whether the user is already subscribed with the old email. If there is a subscription we remove it and we register the new email. """ if not BASKET_ENABLED or not waffle.switch_is_active('BASK...
')): return lookup_subtask = lookup_user_task.subtask((instance.user.email,)) subscribe_subtask = subscribe_user_task.subtask((instance.user.email, newsletters,)) chain(lookup_subtask | subscribe_subtask)() @shared_task() def update_email_in_basket(old_email, new_email):
64
64
133
16
48
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
update_email_in_basket
update_email_in_basket
194
211
194
195
8a133666c435defe3eef8222f11b299bc871f5b8
bigcode/the-stack
train
e97a28ec6bfe986bc09a120f
train
function
@shared_task() def subscribe_user_to_basket(instance_id, newsletters=[]): """Subscribe a user to Basket. This task subscribes a user to Basket, if not already subscribed and then updates his data on the Phonebook DataExtension. The task retries on failure at most BASKET_TASK_MAX_RETRIES times and if it...
@shared_task() def subscribe_user_to_basket(instance_id, newsletters=[]):
"""Subscribe a user to Basket. This task subscribes a user to Basket, if not already subscribed and then updates his data on the Phonebook DataExtension. The task retries on failure at most BASKET_TASK_MAX_RETRIES times and if it finally doesn't complete successfully, it emails the settings.BAS...
subscribe, optout=optout) except MaxRetriesExceededError as exc: raise exc except basket.BasketException as exc: raise self.retry(exc=exc) return unsubscribe_result return None @shared_task() def subscribe_user_to_ba...
64
64
211
16
47
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
subscribe_user_to_basket
subscribe_user_to_basket
168
191
168
169
260b0c286b1bf3031976c1641069957cea1e4451
bigcode/the-stack
train
35e2e764e6244ed92b524c32
train
function
@task(ignore_result=False) def check_celery(): """Dummy celery task to check that everything runs smoothly.""" pass
@task(ignore_result=False) def check_celery():
"""Dummy celery task to check that everything runs smoothly.""" pass
.""" # Avoid circular dependencies from mozillians.users.models import UserProfile now = datetime.now() - timedelta(days=days) UserProfile.objects.filter(full_name='').filter(user__date_joined__lt=now).delete() @task(ignore_result=False) def check_celery():
64
64
27
12
52
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
check_celery
check_celery
240
243
240
241
b0853fd17762c90c94021c3e52a1da9c26db6d81
bigcode/the-stack
train
11ef3b97722ce4583ca11836
train
function
@task def remove_incomplete_accounts(days=INCOMPLETE_ACC_MAX_DAYS): """Remove incomplete accounts older than INCOMPLETE_ACC_MAX_DAYS old.""" # Avoid circular dependencies from mozillians.users.models import UserProfile now = datetime.now() - timedelta(days=days) UserProfile.objects.filter(full_name...
@task def remove_incomplete_accounts(days=INCOMPLETE_ACC_MAX_DAYS):
"""Remove incomplete accounts older than INCOMPLETE_ACC_MAX_DAYS old.""" # Avoid circular dependencies from mozillians.users.models import UserProfile now = datetime.now() - timedelta(days=days) UserProfile.objects.filter(full_name='').filter(user__date_joined__lt=now).delete()
return # Lookup the email and then pass the result to the unsubscribe subtask chain( lookup_user_task.subtask((email,)) | unsubscribe_user_task.subtask((newsletters,)) ).delay() @task def remove_incomplete_accounts(days=INCOMPLETE_ACC_MAX_DAYS):
64
64
85
18
46
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
remove_incomplete_accounts
remove_incomplete_accounts
230
237
230
231
3a4c971934d32cf7aae0b306b2239008521715be
bigcode/the-stack
train
5a3d8e7a1e8235ac475953ce
train
class
class DebugBasketTask(Task): """Base Error Handing Abstract class for all the Basket Tasks.""" abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): # Fallback to ADMINS emails when BASKET_MANAGERS not defined basket_managers = getattr(settings, 'BASKET_MANAGERS', None) ...
class DebugBasketTask(Task):
"""Base Error Handing Abstract class for all the Basket Tasks.""" abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): # Fallback to ADMINS emails when BASKET_MANAGERS not defined basket_managers = getattr(settings, 'BASKET_MANAGERS', None) recipients_list = bask...
_ACC_MAX_DAYS = 7 MOZILLIANS_NEWSLETTERS = [BASKET_NDA_NEWSLETTER, BASKET_VOUCHED_NEWSLETTER] MOZILLIANS_URL = getattr(settings, 'SITE_URL', 'https://mozillians.org') class DebugBasketTask(Task):
64
64
213
6
58
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
DebugBasketTask
DebugBasketTask
35
61
35
35
f052c73c35f1b1618f66b4061a6500c02c432215
bigcode/the-stack
train
1cd8a06908aa332a7e910373
train
function
@shared_task() def unsubscribe_from_basket_task(email, newsletters=[]): """Remove user from Basket Task. This task unsubscribes a user from the Mozillians newsletter. """ if not BASKET_ENABLED or not waffle.switch_is_active('BASKET_SWITCH_ENABLED'): return # Lookup the email and then pass ...
@shared_task() def unsubscribe_from_basket_task(email, newsletters=[]):
"""Remove user from Basket Task. This task unsubscribes a user from the Mozillians newsletter. """ if not BASKET_ENABLED or not waffle.switch_is_active('BASKET_SWITCH_ENABLED'): return # Lookup the email and then pass the result to the unsubscribe subtask chain( lookup_user_tas...
ET_SWITCH_ENABLED'): return chain( lookup_user_task.subtask((old_email,)) | group( subscribe_user_task.subtask((new_email,)), unsubscribe_user_task.subtask() ) ).delay() @shared_task() def unsubscribe_from_basket_task(email, newsletters=[]):
64
64
107
15
49
yogesh-kamble/mozillians
mozillians/users/tasks.py
Python
unsubscribe_from_basket_task
unsubscribe_from_basket_task
214
227
214
215
335ce09aabe4545296660a12931a12b7e0fdb85b
bigcode/the-stack
train
1b4cac4c2fc3db1773e287e6
train
class
class BenchmarkMandateView(APIView): """ Return mandate rankings for for a particular government category """ schema = AutoSchema(manual_fields=[ coreapi.Field( 'category', required=True, location='query', schema=coreschema.String( ...
class BenchmarkMandateView(APIView):
""" Return mandate rankings for for a particular government category """ schema = AutoSchema(manual_fields=[ coreapi.Field( 'category', required=True, location='query', schema=coreschema.String( description='Unique government catego...
import coreapi import coreschema from rest_framework.schemas import AutoSchema from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from core.models import (Yearref, Govrank, Govindicatorrank) class Ben...
62
74
248
8
54
OpenUpSA/salga-mobile-api
api/benchmarks/views.py
Python
BenchmarkMandateView
BenchmarkMandateView
13
57
13
13
8f2c9f3eefac747a47eec3f87a204117dfb76fb4
bigcode/the-stack
train
cc4ac6c1e79860d713bd8249
train
class
class BenchmarkIndicatorView(APIView): """ Return a particular mandate indicator ranking for all governments within a particular government category """ schema = AutoSchema(manual_fields=[ coreapi.Field( 'indicator', required=True, location='path', ...
class BenchmarkIndicatorView(APIView):
""" Return a particular mandate indicator ranking for all governments within a particular government category """ schema = AutoSchema(manual_fields=[ coreapi.Field( 'indicator', required=True, location='path', schema=coreschema.String( ...
( status=status.HTTP_400_BAD_REQUEST ) query = Govrank\ .objects\ .filter(govid__gcid=category, yearid__yr=year) serialize = serializers.BenchmarkMandateSerializer( query, context={'request': requ...
87
87
291
7
80
OpenUpSA/salga-mobile-api
api/benchmarks/views.py
Python
BenchmarkIndicatorView
BenchmarkIndicatorView
60
112
60
60
b9700174a0ca16b9c17b5d70f5dd06f1a9092e1f
bigcode/the-stack
train
eb16fe37a029ebfee5c9e5a2
train
function
def validateValue(modelXbrl, elt, attrTag, baseXsdType, value, isNillable=False, isNil=False, facets=None): if baseXsdType: try: ''' if (len(value) == 0 and attrTag is None and not isNillable and baseXsdType not in ("anyType", "string", "normalizedString", "token", "...
def validateValue(modelXbrl, elt, attrTag, baseXsdType, value, isNillable=False, isNil=False, facets=None):
if baseXsdType: try: ''' if (len(value) == 0 and attrTag is None and not isNillable and baseXsdType not in ("anyType", "string", "normalizedString", "token", "NMTOKEN", "anyURI", "noContent")): raise ValueError("missing value for not nillable element"...
"]) modelXbrl.error(*errDesc,**errArgs) # when error is in an xbrli element, check any further unvalidated children if qnElt.namespaceURI == XbrlConst.xbrli and iElt < len(childEl...
256
256
3,313
33
223
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
validateValue
validateValue
319
569
319
319
4ba3f086a3bdb04d2b963550e75cd584289bb946
bigcode/the-stack
train
a91d8fcee2009cc7cbd8c185
train
function
def validateFacet(typeElt, facetElt): facetName = facetElt.localName value = facetElt.get("value") if facetName in ("length", "minLength", "maxLength", "totalDigits", "fractionDigits"): baseXsdType = "integer" facets = None elif facetName in ("minInclusive", "maxInclusive", "minExclusive...
def validateFacet(typeElt, facetElt):
facetName = facetElt.localName value = facetElt.get("value") if facetName in ("length", "minLength", "maxLength", "totalDigits", "fractionDigits"): baseXsdType = "integer" facets = None elif facetName in ("minInclusive", "maxInclusive", "minExclusive", "maxExclusive"): baseXsdTyp...
= xAttributes = {} xAttributes[attrTag] = ModelAttribute(elt, attrTag, xValid, xValue, sValue, value) else: elt.xValid = xValid elt.xValue = xValue elt.sValue = sValue def validateFacet(typeElt, facetElt):
67
67
226
9
57
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
validateFacet
validateFacet
571
592
571
571
be6a49e770ad4ba8e9af5a299094b1968917f4b9
bigcode/the-stack
train
229f05627c9d6c592608e5a5
train
function
def lxmlSchemaValidate(modelDocument): # lxml schema-validate modelDocument if modelDocument is None: return modelXbrl = modelDocument.modelXbrl cntlr = modelXbrl.modelManager.cntlr ns = modelDocument.xmlRootElement.qname.namespaceURI if ns: try: if ns in modelXbrl.na...
def lxmlSchemaValidate(modelDocument): # lxml schema-validate modelDocument
if modelDocument is None: return modelXbrl = modelDocument.modelXbrl cntlr = modelXbrl.modelManager.cntlr ns = modelDocument.xmlRootElement.qname.namespaceURI if ns: try: if ns in modelXbrl.namespaceDocs: xsdTree = modelXbrl.namespaceDocs[ns][0].xmlRootEle...
-pattern" facets = None else: baseXsdType = "string" facets = None validateValue(typeElt.modelXbrl, facetElt, None, baseXsdType, value, facets=facets) if facetElt.xValid == VALID: return facetElt.xValue return None def validateAnyWildcard(qnElt, qnAttr, attributeWildcard...
151
151
504
18
132
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
lxmlSchemaValidate
lxmlSchemaValidate
601
648
601
602
2153cff76af14bb94caa722e5470a91498ddb74e
bigcode/the-stack
train
c150ff44c3d61d6aa608abb2
train
function
def validate(modelXbrl, elt, recurse=True, attrQname=None, ixFacts=False): global ModelInlineValueObject, ixMsgCode if ModelInlineValueObject is None: from arelle.ModelInstanceObject import ModelInlineValueObject from arelle.XhtmlValidate import ixMsgCode isIxFact = isinstance(elt, ModelInli...
def validate(modelXbrl, elt, recurse=True, attrQname=None, ixFacts=False):
global ModelInlineValueObject, ixMsgCode if ModelInlineValueObject is None: from arelle.ModelInstanceObject import ModelInlineValueObject from arelle.XhtmlValidate import ixMsgCode isIxFact = isinstance(elt, ModelInlineValueObject) facets = None # attrQname can be provided for attri...
00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u0300-\u036F\u203F-\u2040]" baseXsdTypePatterns = { "Name": namePattern, "language": languagePattern, "languageOrEmpty": re_compile(r"[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$|$"), "NMTOKEN": NMTOKENPattern, ...
256
256
2,675
21
235
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
validate
validate
100
317
100
100
900f4582b219b15c616877a7bc5a7729c12d238d
bigcode/the-stack
train
ddba7aa602775c4aeea68767
train
function
def validateAnyWildcard(qnElt, qnAttr, attributeWildcards): # note wildcard is a set of possibly multiple values from inherited attribute groups for attributeWildcard in attributeWildcards: if attributeWildcard.allowsNamespace(qnAttr.namespaceURI): return True return False
def validateAnyWildcard(qnElt, qnAttr, attributeWildcards): # note wildcard is a set of possibly multiple values from inherited attribute groups
for attributeWildcard in attributeWildcards: if attributeWildcard.allowsNamespace(qnAttr.namespaceURI): return True return False
baseXsdType, value, facets=facets) if facetElt.xValid == VALID: return facetElt.xValue return None def validateAnyWildcard(qnElt, qnAttr, attributeWildcards): # note wildcard is a set of possibly multiple values from inherited attribute groups
64
64
62
32
31
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
validateAnyWildcard
validateAnyWildcard
594
599
594
595
de10906d5b1b21901eb5265419ee0a362887e2c8
bigcode/the-stack
train
30b0abbd4dfa517fe101df84
train
class
class XsdPattern(): # shim class for python wrapper of xsd pattern def compile(self, p): self.xsdPattern = p if r"\i" in p or r"\c" in p: p = p.replace(r"[\i-[:]]", iNameChar).replace(r"\i", iNameChar) \ .replace(r"[\c-[:]]", cMinusCNameChar).replace(r"\c", cNameChar...
class XsdPattern(): # shim class for python wrapper of xsd pattern
def compile(self, p): self.xsdPattern = p if r"\i" in p or r"\c" in p: p = p.replace(r"[\i-[:]]", iNameChar).replace(r"\i", iNameChar) \ .replace(r"[\c-[:]]", cMinusCNameChar).replace(r"\c", cNameChar) self.pyPattern = re_compile(p + "$") # must match whole strin...
file syntax error %(error)s"), messageArgs={"error": str(err)}, messageCode=msgCode, file=modelDocument.basename, level=logging.ERROR) modelDocument.modelXbrl.errors.append(msgCode) class XsdPattern(...
63
64
168
17
46
ThomasSchilder/Arelle
arelle/XmlValidate.py
Python
XsdPattern
XsdPattern
650
668
650
651
6b5d18b023f6a57518b10c2a150a244abf806041
bigcode/the-stack
train
7e5c9be9fa2f411ae469ba76
train
class
class EdgeGrip(QtWidgets.QWidget): def __init__(self, edges: Union[Qt.Edges, Qt.Edge], grip_size=6, parent=None): QtWidgets.QWidget.__init__(self, parent) self.edges = edges self.grip_size = grip_size # Sides if edges == Qt.TopEdge: self.setCursor(Qt.SizeVerCursor...
class EdgeGrip(QtWidgets.QWidget):
def __init__(self, edges: Union[Qt.Edges, Qt.Edge], grip_size=6, parent=None): QtWidgets.QWidget.__init__(self, parent) self.edges = edges self.grip_size = grip_size # Sides if edges == Qt.TopEdge: self.setCursor(Qt.SizeVerCursor) self.setFixedHeight(s...
.addWidget(EdgeGrip(Qt.BottomEdge | Qt.LeftEdge), 2, 0) self.grip_layout.addWidget(EdgeGrip(Qt.BottomEdge | Qt.RightEdge), 2, 2) self.grip_layout.setContentsMargins(0, 0, 0, 0) self.grip_layout.setSpacing(0) self.setLayout(self.grip_layout) class EdgeGrip(QtWidgets.QWidget):
90
90
301
8
82
adamerose/QStylish
qtstylish/modern_window.py
Python
EdgeGrip
EdgeGrip
97
127
97
97
e9fb9bb5e80c8a201525d1a7a9e0afd175b34b4a
bigcode/the-stack
train
87fe40bf4b4f64b14a8793e2
train
class
class ModernWindow(QtWidgets.QWidget): gripSize = 6 def __init__(self, widget: QtWidgets.QWidget): super().__init__() # Remove window title bar and frame self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint) self.title_bar = CustomTitleBar(self) self.main_widget = wi...
class ModernWindow(QtWidgets.QWidget):
gripSize = 6 def __init__(self, widget: QtWidgets.QWidget): super().__init__() # Remove window title bar and frame self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint) self.title_bar = CustomTitleBar(self) self.main_widget = widget # Set up layout s...
self.layout.addWidget(widget) self.setStyleSheet("width: 100%;" "padding: 0;" "margin: 0;") self.setContentsMargins(0, 0, 0, 0) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) def mousePressEvent...
115
115
384
8
107
adamerose/QStylish
qtstylish/modern_window.py
Python
ModernWindow
ModernWindow
60
94
60
60
bab10767b3af2f28b39f294377ab4155f95914d9
bigcode/the-stack
train
8b3fc52877d4e767e72f06e8
train
class
class TitleBarIcon(QtWidgets.QPushButton): def __init__(self, text, parent=None): super().__init__(text, parent) self.setStyleSheet("margin: 0;" "padding: 0px;" "font-size: 24px;" "width: 58px;" ...
class TitleBarIcon(QtWidgets.QPushButton):
def __init__(self, text, parent=None): super().__init__(text, parent) self.setStyleSheet("margin: 0;" "padding: 0px;" "font-size: 24px;" "width: 58px;" "height: 36px;") self.setConte...
# Aero snap still doesn't work https://bugreports.qt.io/browse/QTBUG-84466 from typing import Union from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtCore import Qt class TitleBarIcon(QtWidgets.QPushButton):
59
64
93
10
48
adamerose/QStylish
qtstylish/modern_window.py
Python
TitleBarIcon
TitleBarIcon
10
20
10
10
9916595ce33a7da56703e64536e4d07bad1f27fb
bigcode/the-stack
train
cdae839e7a9805e0edb454a1
train
class
class CustomTitleBar(QtWidgets.QFrame): def __init__(self, window_widget: QtWidgets.QWidget): super().__init__(window_widget) self.window_widget = window_widget self.minimize_button = TitleBarIcon("🗕") self.maximize_button = TitleBarIcon("🗖") self.exit_button = TitleBarIco...
class CustomTitleBar(QtWidgets.QFrame):
def __init__(self, window_widget: QtWidgets.QWidget): super().__init__(window_widget) self.window_widget = window_widget self.minimize_button = TitleBarIcon("🗕") self.maximize_button = TitleBarIcon("🗖") self.exit_button = TitleBarIcon("✕") self.minimize_button.cli...
Button): def __init__(self, text, parent=None): super().__init__(text, parent) self.setStyleSheet("margin: 0;" "padding: 0px;" "font-size: 24px;" "width: 58px;" "height: 36px;") self...
94
94
314
9
85
adamerose/QStylish
qtstylish/modern_window.py
Python
CustomTitleBar
CustomTitleBar
23
57
23
23
b71b3f6a757affcc296b3e52601ec0f560681a2a
bigcode/the-stack
train
ac733ee0d94b213ebd5cec48
train
function
def get_rendered_toctree(builder, docname, prune=False, collapse=True): """Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment. """ fulltoc = build_full_toctree(builder, docname, ...
def get_rendered_toctree(builder, docname, prune=False, collapse=True):
"""Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment. """ fulltoc = build_full_toctree(builder, docname, prune=prune, collapse=coll...
_rendered_toctree(app.builder, # pagename, # prune=False, # collapse=collapse, # ) #context['toctree'] = make_toctree def get_rendered_toctree(builder, docname, prune=False, co...
64
64
96
18
45
saylorsd/wprdc_etl
docs/source/fulltoc.py
Python
get_rendered_toctree
get_rendered_toctree
50
61
50
50
9c0b141351990c8caa252aafd6a94cb3ad06f5d3
bigcode/the-stack
train
747d5d32c9bbd4ecf5db1c91
train
function
def build_full_toctree(builder, docname, prune, collapse): """Return a single toctree starting from docname containing all sub-document doctrees. """ env = builder.env doctree = env.get_doctree(env.config.master_doc) toctrees = [] for toctreenode in doctree.traverse(addnodes.toctree): ...
def build_full_toctree(builder, docname, prune, collapse):
"""Return a single toctree starting from docname containing all sub-document doctrees. """ env = builder.env doctree = env.get_doctree(env.config.master_doc) toctrees = [] for toctreenode in doctree.traverse(addnodes.toctree): toctree = env.resolve_toctree(docname, builder, toctreeno...
""" fulltoc = build_full_toctree(builder, docname, prune=prune, collapse=collapse, ) rendered_toc = builder.render_partial(fulltoc)['fragment'] return rendered_toc def buil...
64
64
186
15
48
saylorsd/wprdc_etl
docs/source/fulltoc.py
Python
build_full_toctree
build_full_toctree
64
84
64
64
2f6352ef25bd8e2c60b91704f6e019eac887e995
bigcode/the-stack
train
50de9a617703231581b005e9
train
function
def setup(app): app.connect('html-page-context', html_page_context)
def setup(app):
app.connect('html-page-context', html_page_context)
toctrees: return None result = toctrees[0] for toctree in toctrees[1:]: if toctree: result.extend(toctree.children) env.resolve_references(result, docname, builder) return result def setup(app):
64
64
16
4
59
saylorsd/wprdc_etl
docs/source/fulltoc.py
Python
setup
setup
87
88
87
87
2b6de248040aad0d8a4c2c9d409e296bd9438318
bigcode/the-stack
train
328105ed39edf10e55271e30
train
function
def html_page_context(app, pagename, templatename, context, doctree): """Event handler for the html-page-context signal. Modifies the context directly. - Replaces the 'toc' value created by the HTML builder with one that shows all document titles and the local table of contents. - Sets display_...
def html_page_context(app, pagename, templatename, context, doctree):
"""Event handler for the html-page-context signal. Modifies the context directly. - Replaces the 'toc' value created by the HTML builder with one that shows all document titles and the local table of contents. - Sets display_toc to True so the table of contents is always displayed, even ...
IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sphinx import addnodes def html_page_context(app, pagename, templatename, context, doctree):
64
64
176
19
44
saylorsd/wprdc_etl
docs/source/fulltoc.py
Python
html_page_context
html_page_context
23
36
23
23
5366b23006d4d4a340efd1e08e955634c689f947
bigcode/the-stack
train
4df7b3b776adc4967dc0f6d8
train
function
def dtrace_compile_test_suite(): """Test suite for `dtrace_compile`.""" name = "dtrace_compile" output_text_match_test( name = "{}_generates_expected_header_contents".format(name), target_under_test = "//test/starlark_tests/targets_under_test/dtrace:dtrace", files_match = { ...
def dtrace_compile_test_suite():
"""Test suite for `dtrace_compile`.""" name = "dtrace_compile" output_text_match_test( name = "{}_generates_expected_header_contents".format(name), target_under_test = "//test/starlark_tests/targets_under_test/dtrace:dtrace", files_match = { "folder1/probes.h": ["PROVIDE...
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """`dtrace_compile` Starlark tests.""" load( ":rules/output_text_match_test.bzl", "output_text_match_test", ) def dtrace_compile_test_suite():
64
64
129
7
57
uber-common/rules_apple
test/starlark_tests/dtrace_compile_tests.bzl
Python
dtrace_compile_test_suite
dtrace_compile_test_suite
22
39
22
22
1918ed485c296eeb18c1c3c739bcd81a5261b191
bigcode/the-stack
train
924e11fe52f9196cf482e3ab
train
class
class SubscriptionsController(BaseController): """A Controller to access Endpoints in the pagarmeapisdk API.""" def __init__(self, config, auth_managers): super(SubscriptionsController, self).__init__(config, auth_managers) def renew_subscription(self, subscriptio...
class SubscriptionsController(BaseController):
"""A Controller to access Endpoints in the pagarmeapisdk API.""" def __init__(self, config, auth_managers): super(SubscriptionsController, self).__init__(config, auth_managers) def renew_subscription(self, subscription_id, idempotency_key=...
was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ from pagarmeapisdk.api_helper import APIHelper from pagarmeapisdk.configuration import Server from pagarmeapisdk.controllers.base_controller import BaseController from pagarmeapisdk.models.get_period_response import GetPeriodRespons...
256
256
14,049
7
248
pagarme/pagarme-python-sdk
pagarmeapisdk/controllers/subscriptions_controller.py
Python
SubscriptionsController
SubscriptionsController
28
1,995
28
29
782c9e09edefcff88cb62d3d379ecac0d7bb3aa1
bigcode/the-stack
train
0de96e4fa4d9dbb015943bfe
train
class
@pytest.mark.parametrize('name', ['CARTODBPOSITRON', 'CARTODBPOSITRON_RETINA']) class Test_CartoProviders(object): def test_type(self, name): p = getattr(bt, name) assert isinstance(p, WMTSTileSource) def test_url(self, name): p = getattr(bt, name) assert p.url == _CARTO_URLS[na...
@pytest.mark.parametrize('name', ['CARTODBPOSITRON', 'CARTODBPOSITRON_RETINA']) class Test_CartoProviders(object):
def test_type(self, name): p = getattr(bt, name) assert isinstance(p, WMTSTileSource) def test_url(self, name): p = getattr(bt, name) assert p.url == _CARTO_URLS[name] def test_attribution(self, name): p = getattr(bt, name) assert p.attribution == ( ...
def test_copies(self, name): p1 = getattr(bt, name) p2 = getattr(bt, name) assert p1 is not p2 @pytest.mark.parametrize('name', ['CARTODBPOSITRON', 'CARTODBPOSITRON_RETINA']) class Test_CartoProviders(object):
64
64
197
29
34
adsbxchange/bokeh
bokeh/tests/test_tile_providers.py
Python
Test_CartoProviders
Test_CartoProviders
103
123
103
104
4105c1fded782d59ca1e03a869ff5633f85c6652
bigcode/the-stack
train
a8e89d5fb7bd6a9625998b39
train
class
@pytest.mark.parametrize('name', [ 'STAMEN_TERRAIN', 'STAMEN_TERRAIN_RETINA', 'STAMEN_TONER', 'STAMEN_TONER_BACKGROUND', 'STAMEN_TONER_LABELS',]) class Test_StamenProviders(object): def test_type(self, name): p = getattr(bt, name) assert isinstance(p, WMTSTileSource) def test_url(self, name): ...
@pytest.mark.parametrize('name', [ 'STAMEN_TERRAIN', 'STAMEN_TERRAIN_RETINA', 'STAMEN_TONER', 'STAMEN_TONER_BACKGROUND', 'STAMEN_TONER_LABELS',]) class Test_StamenProviders(object):
def test_type(self, name): p = getattr(bt, name) assert isinstance(p, WMTSTileSource) def test_url(self, name): p = getattr(bt, name) assert p.url == _STAMEN_URLS[name] def test_attribution(self, name): p = getattr(bt, name) assert p.attribution == ( ...
# Public API #----------------------------------------------------------------------------- Test___all__ = verify_all(bt, ALL) @pytest.mark.parametrize('name', [ 'STAMEN_TERRAIN', 'STAMEN_TERRAIN_RETINA', 'STAMEN_TONER', 'STAMEN_TONER_BACKGROUND', 'STAMEN_TONER_LABELS',]) class Test_StamenProviders(object):
80
80
267
62
18
adsbxchange/bokeh
bokeh/tests/test_tile_providers.py
Python
Test_StamenProviders
Test_StamenProviders
79
101
79
80
74426b5606f045821bf9255f3bffc645cdec0e21
bigcode/the-stack
train
265eb9c01200c7b1454ad5c9
train
function
def test_bedrock_response_contains_expected_fields(): data = b"\x1c\x00\x00\x00\x00\x00\x00\x00\x004GT\x00\xb8\x83D\xde\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x124Vx\x00wMCPE;\xc2\xa7r\xc2\xa74G\xc2\xa7r\xc2\xa76a\xc2\xa7r\xc2\xa7ey\xc2\xa7r\xc2\xa72B\xc2\xa7r\xc2\xa71o\xc2\xa7r\xc2\xa79w\xc2\xa7r\xc2\xa7d...
def test_bedrock_response_contains_expected_fields():
data = b"\x1c\x00\x00\x00\x00\x00\x00\x00\x004GT\x00\xb8\x83D\xde\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x124Vx\x00wMCPE;\xc2\xa7r\xc2\xa74G\xc2\xa7r\xc2\xa76a\xc2\xa7r\xc2\xa7ey\xc2\xa7r\xc2\xa72B\xc2\xa7r\xc2\xa71o\xc2\xa7r\xc2\xa79w\xc2\xa7r\xc2\xa7ds\xc2\xa7r\xc2\xa74e\xc2\xa7r\xc2\xa76r;422;;1;69;3767...
from mcstatus.bedrock_status import BedrockServerStatus, BedrockStatusResponse def test_bedrock_response_contains_expected_fields():
28
93
313
10
17
MeRuslan/mcstatus
mcstatus/tests/test_bedrock_status.py
Python
test_bedrock_response_contains_expected_fields
test_bedrock_response_contains_expected_fields
4
16
4
4
09698deb2ea31734a4d38d2ce627c58dd24777bf
bigcode/the-stack
train
181f3e74e5aa8db5ac1070d1
train
function
def add_anchor_input(graph): """Add the missing const input for the GridAnchor node. Reference: 1. https://www.minds.ai/post/deploying-ssd-mobilenet-v2-on-the-nvidia-jetson-and-nano-platforms """ data = np.array([1, 1], dtype=np.float32) anchor_input = gs.create_node('AnchorInput', 'Const', val...
def add_anchor_input(graph):
"""Add the missing const input for the GridAnchor node. Reference: 1. https://www.minds.ai/post/deploying-ssd-mobilenet-v2-on-the-nvidia-jetson-and-nano-platforms """ data = np.array([1, 1], dtype=np.float32) anchor_input = gs.create_node('AnchorInput', 'Const', value=data) graph.append(anc...
/jkjung-avt/tensorrt_demos/issues/76#issuecomment-607879831 """ for node in graph.find_nodes_by_op('FusedBatchNormV3'): gs.update_node(node, op='FusedBatchNorm') return graph def add_anchor_input(graph):
64
64
124
6
57
sachinkmohan/tensorrt_demos_jp46
ssd/build_engine.py
Python
add_anchor_input
add_anchor_input
128
138
128
128
2ba9ace976891e53e60ef939a003be055876fd1e
bigcode/the-stack
train
9e153642a2af84d4fafe989a
train
function
def main(): parser = argparse.ArgumentParser() parser.add_argument('model', type=str, choices=list(MODEL_SPECS.keys())) args = parser.parse_args() # initialize if trt.__version__[0] < '7': ctypes.CDLL(LIB_FILE) TRT_LOGGER = trt.Logger(trt.Logger.INFO) trt.init_libnvinfer_plugins(TRT...
def main():
parser = argparse.ArgumentParser() parser.add_argument('model', type=str, choices=list(MODEL_SPECS.keys())) args = parser.parse_args() # initialize if trt.__version__[0] < '7': ctypes.CDLL(LIB_FILE) TRT_LOGGER = trt.Logger(trt.Logger.INFO) trt.init_libnvinfer_plugins(TRT_LOGGER, '')...
) if len(graph.find_nodes_by_op('GridAnchor_TRT')[0].input) < 1: graph = add_anchor_input(graph) if 'NMS' not in [node.name for node in graph.graph_outputs]: graph.remove(graph.graph_outputs, remove_exclusive_dependencies=False) if 'NMS' not in [node.name for node in graph.graph_outputs]...
111
111
372
3
107
sachinkmohan/tensorrt_demos_jp46
ssd/build_engine.py
Python
main
main
264
307
264
264
2ac64762dd71bd177e30896b345efa1b8b1d97e2
bigcode/the-stack
train
4a4f776d2d8645f548cc96c3
train
function
def add_plugin(graph, model, spec): """add_plugin Reference: 1. https://github.com/AastaNV/TRT_object_detection/blob/master/config/model_ssd_mobilenet_v1_coco_2018_01_28.py 2. https://github.com/AastaNV/TRT_object_detection/blob/master/config/model_ssd_mobilenet_v2_coco_2018_03_29.py 3. https://dev...
def add_plugin(graph, model, spec):
"""add_plugin Reference: 1. https://github.com/AastaNV/TRT_object_detection/blob/master/config/model_ssd_mobilenet_v1_coco_2018_01_28.py 2. https://github.com/AastaNV/TRT_object_detection/blob/master/config/model_ssd_mobilenet_v2_coco_2018_03_29.py 3. https://devtalk.nvidia.com/default/topic/105046...
talk.nvidia.com/default/topic/1066445/tensorrt/tensorrt-6-0-1-tensorflow-1-14-no-conversion-function-registered-for-layer-fusedbatchnormv3-yet/post/5403567/#5403567 2. https://github.com/jkjung-avt/tensorrt_demos/issues/76#issuecomment-607879831 """ for node in graph.find_nodes_by_op('FusedBatchNormV3'): ...
256
256
1,164
9
246
sachinkmohan/tensorrt_demos_jp46
ssd/build_engine.py
Python
add_plugin
add_plugin
140
261
140
140
713b6b81ac0322c01d55f48e29515fc41d0f6a95
bigcode/the-stack
train
03ba3c79d67c61a2a0e25f67
train
function
def replace_fusedbnv3(graph): """Replace all 'FusedBatchNormV3' in the graph with 'FusedBatchNorm'. 'FusedBatchNormV3' is not supported by UFF parser. Reference: 1. https://devtalk.nvidia.com/default/topic/1066445/tensorrt/tensorrt-6-0-1-tensorflow-1-14-no-conversion-function-registered-for-layer-fuse...
def replace_fusedbnv3(graph):
"""Replace all 'FusedBatchNormV3' in the graph with 'FusedBatchNorm'. 'FusedBatchNormV3' is not supported by UFF parser. Reference: 1. https://devtalk.nvidia.com/default/topic/1066445/tensorrt/tensorrt-6-0-1-tensorflow-1-14-no-conversion-function-registered-for-layer-fusedbatchnormv3-yet/post/5403567/...
://github.com/jkjung-avt/tensorrt_demos/issues/113#issuecomment-629900809 """ for node in graph.find_nodes_by_op('AddV2'): gs.update_node(node, op='Add') return graph def replace_fusedbnv3(graph):
64
64
181
9
54
sachinkmohan/tensorrt_demos_jp46
ssd/build_engine.py
Python
replace_fusedbnv3
replace_fusedbnv3
114
125
114
114
a2e334b615ca403d12186e0a4cb879e88e48e383
bigcode/the-stack
train
901111616505844ec989a509
train
function
def replace_addv2(graph): """Replace all 'AddV2' in the graph with 'Add'. 'AddV2' is not supported by UFF parser. Reference: 1. https://github.com/jkjung-avt/tensorrt_demos/issues/113#issuecomment-629900809 """ for node in graph.find_nodes_by_op('AddV2'): gs.update_node(node, op='Add')...
def replace_addv2(graph):
"""Replace all 'AddV2' in the graph with 'Add'. 'AddV2' is not supported by UFF parser. Reference: 1. https://github.com/jkjung-avt/tensorrt_demos/issues/113#issuecomment-629900809 """ for node in graph.find_nodes_by_op('AddV2'): gs.update_node(node, op='Add') return graph
_size': 0.95, 'input_order': [0, 2, 1], # order of loc_data, conf_data, priorbox_data }, } INPUT_DIMS = (3, 300, 300) DEBUG_UFF = False def replace_addv2(graph):
64
64
100
7
56
sachinkmohan/tensorrt_demos_jp46
ssd/build_engine.py
Python
replace_addv2
replace_addv2
101
111
101
101
3b93b6051df40e15ebf638f2ae3bb7564fdd11e3
bigcode/the-stack
train
8000fef0fb0b5c4dd7d0a4e9
train
class
class MPCController(Policy, Serializable): def __init__( self, name, env, dynamics_model, reward_model=None, discount=1, use_cem=False, n_candidates=1024, horizon=10, num_cem_iters=8, ...
class MPCController(Policy, Serializable):
def __init__( self, name, env, dynamics_model, reward_model=None, discount=1, use_cem=False, n_candidates=1024, horizon=10, num_cem_iters=8, percent_elites=0.1, use_reward_...
from learning_to_adapt.policies.base import Policy from learning_to_adapt.utils.serializable import Serializable import numpy as np class MPCController(Policy, Serializable):
35
256
1,074
8
26
jeonggwanlee/varibad
learning_to_adapt/policies/mpc_controller.py
Python
MPCController
MPCController
6
135
6
6
d7f50ff6b47b3971768a2a586cc4b60d23436e33
bigcode/the-stack
train
1efc42555e5d4d4bf4f61c97
train
class
class MTER(Recommender): """Multi-Task Explainable Recommendation Parameters ---------- name: string, optional, default: 'MTER' The name of the recommender model. rating_scale: float, optional, default: 5.0 The maximum rating score of the dataset. n_user_factors: int, optional...
class MTER(Recommender):
"""Multi-Task Explainable Recommendation Parameters ---------- name: string, optional, default: 'MTER' The name of the recommender model. rating_scale: float, optional, default: 5.0 The maximum rating score of the dataset. n_user_factors: int, optional, default: 15 The...
# Copyright 2018 The Cornac Authors. All Rights Reserved. # # 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-2.0 # # Unless required by applicable ...
221
256
4,059
7
213
aobo-y/cornac
cornac/models/mter/recom_mter.py
Python
MTER
MTER
32
532
32
32
66af273913abd039ed9378df26928f9471d76923
bigcode/the-stack
train
b74acf0fb2fcc1676a0126fd
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype_tol', [(onp.float32, 1e-5), (onp.float64, 1e-12)]) @pytest.mark.parametrize('shape', [(4, 4), (7, 7)]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', ...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype_tol', [(onp.float32, 1e-5), (onp.float64, 1e-12)]) @pytest.mark.parametrize('shape', [(4, 4), (7, 7)]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', ...
""" Feature: ALL TO ALL Description: test cases for cg Expectation: the result match scipy """ dtype, tol = dtype_tol A = create_sym_pos_matrix(shape, dtype) b = onp.random.random(shape[:1]).astype(dtype) M = _fetch_preconditioner(preconditioner, A) osp_res = osp_cg(A, b, M=M, ma...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype_tol', [(onp.float32, 1e-5), (onp.float64, 1e-12)]) @pytest.mark.parametrize('shape', [(4, 4), (7, 7)]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', ...
129
124
415
129
0
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_cg_against_scipy
test_cg_against_scipy
54
88
54
62
ed662c1a8042291a458908c5eaad885879dbfa27
bigcode/the-stack
train
7b0bce765ffb58b7551cdc6e
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu_graph(n, dtype): """ Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Exp...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu_graph(n, dtype):
""" Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the result match scipy """ context.set_context(mode=context.GRAPH_MODE) # add Identity matrix to make matrix A non-singular A = onp.random.rand(n, n).astype(dtype) b = onp.random.rand(n).astype(dtype)...
_like(b).astype(dtype)) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu_graph(n, dtype):
64
64
167
58
6
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_gmres_incremental_against_scipy_gpu_graph
test_gmres_incremental_against_scipy_gpu_graph
174
189
174
179
91df46baf4243fa6e89d95fda46afc1f6a4981f1
bigcode/the-stack
train
e394a594b9ba287da98b2b7a
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu(n, dtype): """ Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the r...
@pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu(n, dtype):
""" Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the result match scipy """ context.set_context(mode=context.PYNATIVE_MODE) # add Identity matrix to make matrix A non-singular A = onp.random.rand(n, n).astype(dtype) b = onp.random.rand(n).astype(dty...
actual_sta.asnumpy(), **kw) @pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu(n, dtype):
64
64
166
56
8
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_gmres_incremental_against_scipy_cpu
test_gmres_incremental_against_scipy_cpu
120
135
120
125
adca851b287f04936c09247733b342dbc95d27ba
bigcode/the-stack
train
3d2becdb4613f4e951e33e90
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu(n, dtype): """ Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectati...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu(n, dtype):
""" Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the result match scipy """ context.set_context(mode=context.PYNATIVE_MODE) # add Identity matrix to make matrix A non-singular A = onp.random.rand(n, n).astype(dtype) b = onp.random.rand(n).astype(dty...
.zeros_like(b).astype(dtype)) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_gpu(n, dtype):
64
64
167
57
7
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_gmres_incremental_against_scipy_gpu
test_gmres_incremental_against_scipy_gpu
156
171
156
161
7cac6b65a99c5290a832bd32807e1ed1fef19fb0
bigcode/the-stack
train
6041f4346165186edfd18fba
train
function
def gmres_compare_with_scipy(A, b, x): gmres_x, _ = msp.sparse.linalg.gmres(Tensor(A), Tensor(b), Tensor( x), tol=1e-07, atol=0, solve_method='incremental') scipy_x, _ = osp.sparse.linalg.gmres(A, b, x, tol=1e-07, atol=0) onp.testing.assert_almost_equal(scipy_x, gmres_x.asnumpy(), decimal=5)
def gmres_compare_with_scipy(A, b, x):
gmres_x, _ = msp.sparse.linalg.gmres(Tensor(A), Tensor(b), Tensor( x), tol=1e-07, atol=0, solve_method='incremental') scipy_x, _ = osp.sparse.linalg.gmres(A, b, x, tol=1e-07, atol=0) onp.testing.assert_almost_equal(scipy_x, gmres_x.asnumpy(), decimal=5)
from mindspore.common import Tensor from mindspore.scipy.sparse.linalg import cg as msp_cg from tests.st.scipy_st.utils import create_sym_pos_matrix, create_full_rank_matrix onp.random.seed(0) def gmres_compare_with_scipy(A, b, x):
64
64
111
14
50
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
gmres_compare_with_scipy
gmres_compare_with_scipy
29
33
29
29
33806bef3db1bf24efc787283d4535ad38f20eeb
bigcode/the-stack
train
bfb12eebdd10b2eb8da461aa
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu_graph(n, dtype): """ Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation:...
@pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu_graph(n, dtype):
""" Feature: ALL TO ALL Description: test cases for [N x N] X [N X 1] Expectation: the result match scipy """ context.set_context(mode=context.GRAPH_MODE) # add Identity matrix to make matrix A non-singular A = onp.random.rand(n, n).astype(dtype) b = onp.random.rand(n).astype(dtype)...
.zeros_like(b).astype(dtype)) @pytest.mark.level0 @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5]) @pytest.mark.parametrize('dtype', [onp.float64]) def test_gmres_incremental_against_scipy_cpu_graph(n, dtype):
64
64
166
57
7
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_gmres_incremental_against_scipy_cpu_graph
test_gmres_incremental_against_scipy_cpu_graph
138
153
138
143
8d83cf5da1050845d59f415cb8ff4fc629658b33
bigcode/the-stack
train
aec216099667e99e33d01669
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter', [...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter', [...
""" Feature: ALL TO ALL Description: test cases for gmres Expectation: the result match scipy """ context.set_context(mode=context.GRAPH_MODE) shape = (n, n) a = create_full_rank_matrix(shape, dtype) b = onp.random.rand(n).astype(dtype=dtype) tensor_a = Tensor(a) tensor_b = T...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter', [...
107
91
306
107
0
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_graph_batched_gmres_against_scipy
test_graph_batched_gmres_against_scipy
221
245
221
229
8dee73424ea9ad660b0e04990456e059493e3d8d
bigcode/the-stack
train
7d41e4037bcdfdd2af528c85
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [4, 5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter'...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [4, 5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter'...
""" Feature: ALL TO ALL Description: test cases for gmres Expectation: the result match scipy """ shape = (n, n) a = create_full_rank_matrix(shape, dtype) b = onp.random.rand(n).astype(dtype=dtype) M = _fetch_preconditioner(preconditioner, a) tensor_a = Tensor(a) tensor_b = T...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('n', [4, 5, 6]) @pytest.mark.parametrize('dtype', [onp.float64]) @pytest.mark.parametrize('preconditioner', [None, 'identity', 'exact', 'random']) @pytest.mark.parametrize('maxiter'...
112
91
304
112
0
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_pynative_batched_gmres_against_scipy
test_pynative_batched_gmres_against_scipy
192
218
192
200
ad7fe501ae311d3bfd70f6d233744c18aab2246f
bigcode/the-stack
train
11e29b98cb77ea6c86ff8adc
train
function
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype', [onp.float32, onp.float64]) @pytest.mark.parametrize('shape', [(2, 2)]) def test_cg_against_numpy(dtype, shape): """ Feature: ALL TO ALL Description: test cases...
@pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype', [onp.float32, onp.float64]) @pytest.mark.parametrize('shape', [(2, 2)]) def test_cg_against_numpy(dtype, shape):
""" Feature: ALL TO ALL Description: test cases for cg Expectation: the result match numpy """ A = create_sym_pos_matrix(shape, dtype) b = onp.random.random(shape[:1]).astype(dtype) expected = onp.linalg.solve(A, b) # using PYNATIVE MODE context.set_context(mode=context.PYNATIVE...
msp_res_sta.asnumpy(), **kw) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.platform_x86_cpu @pytest.mark.env_onecard @pytest.mark.parametrize('dtype', [onp.float32, onp.float64]) @pytest.mark.parametrize('shape', [(2, 2)]) def test_cg_against_numpy(dtype, shape):
76
76
256
66
10
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
test_cg_against_numpy
test_cg_against_numpy
91
117
91
97
8730372d72b35612121640aa89ac1188e72b3ab9
bigcode/the-stack
train
54ac857ccfba0ddf7b06203b
train
function
def _fetch_preconditioner(preconditioner, A): """ Returns one of various preconditioning matrices depending on the identifier `preconditioner' and the input matrix A whose inverse it supposedly approximates. """ if preconditioner == 'identity': M = onp.eye(A.shape[0], dtype=A.dtype) ...
def _fetch_preconditioner(preconditioner, A):
""" Returns one of various preconditioning matrices depending on the identifier `preconditioner' and the input matrix A whose inverse it supposedly approximates. """ if preconditioner == 'identity': M = onp.eye(A.shape[0], dtype=A.dtype) elif preconditioner == 'random': rando...
scipy_x, _ = osp.sparse.linalg.gmres(A, b, x, tol=1e-07, atol=0) onp.testing.assert_almost_equal(scipy_x, gmres_x.asnumpy(), decimal=5) def _fetch_preconditioner(preconditioner, A):
64
64
138
12
52
LaiYongqiang/mindspore
tests/st/scipy_st/sparse/test_linalg.py
Python
_fetch_preconditioner
_fetch_preconditioner
36
51
36
36
49f7683a388ddb2af7b81116160a891377a80c27
bigcode/the-stack
train
30b426098aedc77c748a0adf
train
class
class TestCLIInfo: def test_missing_settings(self, mocker: MockerFixture): mocked_get_settings = mocker.patch("fief.cli.get_settings") mocked_get_settings.side_effect = ValidationError([], Settings) result = runner.invoke(app, ["info"]) print(result.output) assert result.exi...
class TestCLIInfo:
def test_missing_settings(self, mocker: MockerFixture): mocked_get_settings = mocker.patch("fief.cli.get_settings") mocked_get_settings.side_effect = ValidationError([], Settings) result = runner.invoke(app, ["info"]) print(result.output) assert result.exit_code == 1 ...
from pydantic import ValidationError from pytest_mock import MockerFixture from typer.testing import CliRunner from fief.cli import app from fief.settings import Settings runner = CliRunner() class TestCLIInfo:
47
64
124
5
42
fief-dev/fief
backend/tests/test_cli.py
Python
TestCLIInfo
TestCLIInfo
11
24
11
11
aa692e8222517dcd10dd1e12677988a99914d6a1
bigcode/the-stack
train
4d5a2cafa9cd2b7b7c03452b
train
class
class Spec(Mapping): def __init__(self, app): with open(os.path.join(os.path.dirname(__file__), 'swagger.yml')) as swaggerfile: self.spec = make_backwards_compatible(load_yaml(swaggerfile)) self.spec['basePath'] = URL_PREFIX self.spec['paths'] = {} # if LOCAL_DEV: ...
class Spec(Mapping):
def __init__(self, app): with open(os.path.join(os.path.dirname(__file__), 'swagger.yml')) as swaggerfile: self.spec = make_backwards_compatible(load_yaml(swaggerfile)) self.spec['basePath'] = URL_PREFIX self.spec['paths'] = {} # if LOCAL_DEV: # self.spec['sch...
if field.get('nullable', False): field['x-nullable'] = field['nullable'] def load_yaml(stream): # based on <http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts> class OrderedLoader(yaml.Loader): pass def construct_mapping(loader, no...
168
169
564
5
163
appoll/training-data-analyst
start/swagger.py
Python
Spec
Spec
113
176
113
113
dcae31afd2ca8d70bc4b113ecf41578cef696fb0
bigcode/the-stack
train
e77b53fddb1c7c120cb50d1b
train
class
class FormatChecker(jsonschema.FormatChecker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) members = inspect.getmembers(self, predicate=lambda m: callable(m) and m.__name__.startswith('check_')) for name, function in members: self.checkers[name[len('che...
class FormatChecker(jsonschema.FormatChecker):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) members = inspect.getmembers(self, predicate=lambda m: callable(m) and m.__name__.startswith('check_')) for name, function in members: self.checkers[name[len('check_'):].replace('_', '-')] = (function, ValueEr...
: raise ValidationError(str(e)) except KeyError: raise ValidationError('Response `{}` not defined in schema'.format(response.status_code)) def validate_against_schema(self, data, schema): jsonschema.validate( data, schema, cls=VendorDraft4Validator, resolver=self...
80
80
267
8
72
appoll/training-data-analyst
start/swagger.py
Python
FormatChecker
FormatChecker
258
284
258
258
036ef87ad286ef46fc98e70de4791b7fea616f8e
bigcode/the-stack
train
4e1fe6158b6905c9e7f955cd
train
class
class ValidationError(Exception): pass
class ValidationError(Exception):
pass
abc import Mapping import jsonschema import inspect import os import pytz import yaml from flask import json, jsonify, request from werkzeug.exceptions import BadRequest, InternalServerError from collections import OrderedDict URL_PREFIX = f'/api/v{1}' class ValidationError(Exception):
63
64
8
5
58
appoll/training-data-analyst
start/swagger.py
Python
ValidationError
ValidationError
14
15
14
14
6d6b93c836c41a109e0e4d2c595017b99b44f329
bigcode/the-stack
train
0bc85e342c262e63b163b77e
train
function
def make_definition_backwards_compatible(definition): if definition.get('type') == 'object': for field in definition.get('properties', {}).values(): if field.get('nullable', False): field['x-nullable'] = field['nullable']
def make_definition_backwards_compatible(definition):
if definition.get('type') == 'object': for field in definition.get('properties', {}).values(): if field.get('nullable', False): field['x-nullable'] = field['nullable']
(active_exception)) except target_exception as e: return self.app.handle_exception(e) def make_backwards_compatible(spec): for name, definition in spec.get('definitions', {}).items(): make_definition_backwards_compatible(definition) return spec def make_definition_backwards_compati...
64
64
54
10
53
appoll/training-data-analyst
start/swagger.py
Python
make_definition_backwards_compatible
make_definition_backwards_compatible
89
93
89
89
cd1584b4cb26946016b8eb5c8e99230c168a7382
bigcode/the-stack
train
6c1288cd9ab7b08722eae400
train
class
class VendorDraft4Validator(jsonschema.validators.Draft4Validator): def __init__(self, *args, **kwargs): members = inspect.getmembers(self, predicate=lambda m: callable(m) and m.__name__.startswith('validate_')) for name, function in members: self.VALIDATORS[name[len('validate_'):]] = fu...
class VendorDraft4Validator(jsonschema.validators.Draft4Validator):
def __init__(self, *args, **kwargs): members = inspect.getmembers(self, predicate=lambda m: callable(m) and m.__name__.startswith('validate_')) for name, function in members: self.VALIDATORS[name[len('validate_'):]] = function super().__init__(*args, **kwargs) @staticmethod ...
def check_password(instance): return isinstance(instance, str) @staticmethod def check_timezone(instance): if isinstance(instance, str): try: pytz.timezone(instance) except pytz.exceptions.UnknownTimeZoneError: raise ValueError('Invalid t...
77
77
258
13
63
appoll/training-data-analyst
start/swagger.py
Python
VendorDraft4Validator
VendorDraft4Validator
286
309
286
286
debe114f521b0ddeffe6b9d156d104a5ea6bce2a
bigcode/the-stack
train
bb6f17ce5a2293e9a6ab65d5
train
function
def subdict(dct, include=None, exclude=None): return {k: v for k, v in dct.items() if (include is None or k in include) and (exclude is None or k not in exclude)}
def subdict(dct, include=None, exclude=None):
return {k: v for k, v in dct.items() if (include is None or k in include) and (exclude is None or k not in exclude)}
pass def construct_mapping(loader, node): loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(node)) OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) return yaml.load(stream, OrderedLoader) def subdict(dct, include=None, e...
64
64
48
12
52
appoll/training-data-analyst
start/swagger.py
Python
subdict
subdict
109
110
109
109
37820ed98ea4085a99b950427a42cb0615ccaf1e
bigcode/the-stack
train
87ed71e099fca7fd7b182c17
train
function
def make_backwards_compatible(spec): for name, definition in spec.get('definitions', {}).items(): make_definition_backwards_compatible(definition) return spec
def make_backwards_compatible(spec):
for name, definition in spec.get('definitions', {}).items(): make_definition_backwards_compatible(definition) return spec
, target_exception): # Hack to change the current-exception context. # Otherwise we would be unable to call Flask.handle_user_exception() try: raise target_exception(description=str(active_exception)) except target_exception as e: return self.app.handle_exception(...
64
64
36
8
56
appoll/training-data-analyst
start/swagger.py
Python
make_backwards_compatible
make_backwards_compatible
84
87
84
84
c1cbd0932d9f1d4ab598c662bf098ec255f7c638
bigcode/the-stack
train
fad3cee38593e3a6751b63ff
train
class
class Validator(object): def __init__(self, definitions): self.format_checker = FormatChecker() self.ref_resolver = jsonschema.RefResolver.from_schema(definitions) def validate_request(self, req, spec): self.validate_path(req, spec) self.validate_query(req, spec) self.va...
class Validator(object):
def __init__(self, definitions): self.format_checker = FormatChecker() self.ref_resolver = jsonschema.RefResolver.from_schema(definitions) def validate_request(self, req, spec): self.validate_path(req, spec) self.validate_query(req, spec) self.validate_body(req, spec) ...
_index + 1:])) if 'description' not in spec: spec['description'] = ' '.join(line.strip() for line in lines[:separator_index]) for param in spec.get('parameters', []): if 'schema' in param: make_definition_backwards_compatibl...
216
217
724
4
213
appoll/training-data-analyst
start/swagger.py
Python
Validator
Validator
179
255
179
179
17e1aabb5028fe90cd10d7a55d9a45ee6dd3b852
bigcode/the-stack
train
18d1925a179858796eff2cc9
train
class
class Swagger(object): def __init__(self, app=None, spec_endpoint='/swagger.json', **kwargs): self.app = None self.validator = None self.spec_endpoint = spec_endpoint if app is not None: self.init_app(app, **kwargs) def init_app(self, app, **kwargs): self.ap...
class Swagger(object):
def __init__(self, app=None, spec_endpoint='/swagger.json', **kwargs): self.app = None self.validator = None self.spec_endpoint = spec_endpoint if app is not None: self.init_app(app, **kwargs) def init_app(self, app, **kwargs): self.app = app self.a...
from collections.abc import Mapping import jsonschema import inspect import os import pytz import yaml from flask import json, jsonify, request from werkzeug.exceptions import BadRequest, InternalServerError from collections import OrderedDict URL_PREFIX = f'/api/v{1}' class ValidationError(Exception): pass clas...
75
134
447
4
70
appoll/training-data-analyst
start/swagger.py
Python
Swagger
Swagger
17
81
17
17
cdb4564732f4d58c3a2642ccf31a91cc75899645
bigcode/the-stack
train
71245d55030fde0659744dab
train
function
def load_yaml(stream): # based on <http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts> class OrderedLoader(yaml.Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(...
def load_yaml(stream): # based on <http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts>
class OrderedLoader(yaml.Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return OrderedDict(loader.construct_pairs(node)) OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping) return yaml.load(stream, Or...
in definition.get('properties', {}).values(): if field.get('nullable', False): field['x-nullable'] = field['nullable'] def load_yaml(stream): # based on <http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts>
64
64
95
34
30
appoll/training-data-analyst
start/swagger.py
Python
load_yaml
load_yaml
96
106
96
97
28665c9b12dae1ce939f291598d82049a9815101
bigcode/the-stack
train
3a9f7394f6bf79f176a06b73
train
class
class CreateComponentDialog(QtWidgets.QDialog): def __init__(self, parent=None): super(CreateComponentDialog, self).__init__(parent) self.setWindowFlags( QtCore.Qt.Dialog | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowCloseButtonHint ) title = ...
class CreateComponentDialog(QtWidgets.QDialog):
def __init__(self, parent=None): super(CreateComponentDialog, self).__init__(parent) self.setWindowFlags( QtCore.Qt.Dialog | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowCloseButtonHint ) title = QtWidgets.QLabel("Crear componente") tit...
from PyQt5 import QtWidgets, QtCore from widgets.spec_fields import AutocapField, StockNumberField from widgets import message_boxes from utils import utils_collection as utils from utils import db_manager from utils.styling import generic_title_style class CreateComponentDialog(QtWidgets.QDialog):
64
200
669
9
54
ivov/admin-stock
src/main/python/widgets/dialogs/create_component_dialog.py
Python
CreateComponentDialog
CreateComponentDialog
9
98
9
9
f34a903639c1eaf5de0e8bfaba9fcbbb72a446b5
bigcode/the-stack
train
9a901c6eb68607832c69d418
train
function
def create_dataset(cfg, split, split_name, length=0, transform=None): """ Create the complete dataloader for each of the splits. cfg = configuration information for the program split = list of the dataloaders name in registry split_name = 'train' || 'test' || 'val' """ data_list = [] fo...
def create_dataset(cfg, split, split_name, length=0, transform=None):
""" Create the complete dataloader for each of the splits. cfg = configuration information for the program split = list of the dataloaders name in registry split_name = 'train' || 'test' || 'val' """ data_list = [] for dataloader in split: act_class = DATALOADER[dataloader] ...
from torch.utils.data import ConcatDataset # Local imports from data_loader.dataloader_registry import DATALOADER def create_dataset(cfg, split, split_name, length=0, transform=None):
42
64
150
17
24
steff456/MLBase
utils/utils.py
Python
create_dataset
create_dataset
7
24
7
7
ffd6dbbbd53a766ed046a83bef22be1d66c07a34
bigcode/the-stack
train