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
0584538e92f8d63a8f733a78
train
class
class ActivatorModel(Document): """ ActivatorModel An abstract base class model that provides activate and deactivate fields. """ STATUS_CHOICES = ( (0, _('Inactive')), (1, _('Active')), ) status = IntField(choices=STATUS_CHOICES, default=1) activate_date = DateTimeF...
class ActivatorModel(Document):
""" ActivatorModel An abstract base class model that provides activate and deactivate fields. """ STATUS_CHOICES = ( (0, _('Inactive')), (1, _('Active')), ) status = IntField(choices=STATUS_CHOICES, default=1) activate_date = DateTimeField(blank=True, null=True, help_...
return super(ActivatorModelManager, self).get_queryset().filter(status=1) def inactive(self): """ Returns inactive instances of ActivatorModel: SomeModel.objects.inactive() """ return super(ActivatorModelManager, self).get_queryset().filter(status=0) class ActivatorModel(Document):
64
64
173
6
58
sainjusajan/django-oscar
oscar/lib/python2.7/site-packages/django_extensions/mongodb/models.py
Python
ActivatorModel
ActivatorModel
55
74
55
55
63d61d7b22ee56943f7fa1c3d02972d04102ee2a
bigcode/the-stack
train
5ffbb3dbf47731096ae31bb6
train
class
class ActivatorModelManager(QuerySetManager): """ ActivatorModelManager Manager to return instances of ActivatorModel: SomeModel.objects.active() / .inactive() """ def active(self): """ Returns active instances of ActivatorModel: SomeModel.objects.active() """ return super(Activato...
class ActivatorModelManager(QuerySetManager):
""" ActivatorModelManager Manager to return instances of ActivatorModel: SomeModel.objects.active() / .inactive() """ def active(self): """ Returns active instances of ActivatorModel: SomeModel.objects.active() """ return super(ActivatorModelManager, self).get_queryset().filter(stat...
"slug" field that populates from the title. """ title = StringField(max_length=255) slug = AutoSlugField(populate_from='title') description = StringField(blank=True, null=True) class Meta: abstract = True class ActivatorModelManager(QuerySetManager):
64
64
116
9
54
sainjusajan/django-oscar
oscar/lib/python2.7/site-packages/django_extensions/mongodb/models.py
Python
ActivatorModelManager
ActivatorModelManager
42
52
42
42
d0fba1fe244868cfc70ec35b0ec39373f7dfb6fc
bigcode/the-stack
train
b7b99785afab6ecab140d321
train
class
class TimeStampedModel(Document): """ TimeStampedModel An abstract base class model that provides self-managed "created" and "modified" fields. """ created = CreationDateTimeField() modified = ModificationDateTimeField() class Meta: abstract = True
class TimeStampedModel(Document):
""" TimeStampedModel An abstract base class model that provides self-managed "created" and "modified" fields. """ created = CreationDateTimeField() modified = ModificationDateTimeField() class Meta: abstract = True
as _ from mongoengine.document import Document from mongoengine.fields import DateTimeField, IntField, StringField from mongoengine.queryset import QuerySetManager from django_extensions.mongodb.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField, ) class TimeStampedModel(Docume...
64
64
60
6
58
sainjusajan/django-oscar
oscar/lib/python2.7/site-packages/django_extensions/mongodb/models.py
Python
TimeStampedModel
TimeStampedModel
17
26
17
17
13c0e48b7d33f36e3c41462dc3e0e76d4265238c
bigcode/the-stack
train
f66ddcc95cf346ce75d93f23
train
class
class Migration(migrations.Migration): dependencies = [ ('server', '0006_profile_speciality'), ] operations = [ migrations.AddField( model_name='appointment', name='appointment_type', field=models.CharField(default='Offline', max_length=20), ), ...
class Migration(migrations.Migration):
dependencies = [ ('server', '0006_profile_speciality'), ] operations = [ migrations.AddField( model_name='appointment', name='appointment_type', field=models.CharField(default='Offline', max_length=20), ), ]
# Generated by Django 2.0.2 on 2018-03-16 15:32 from django.db import migrations, models class Migration(migrations.Migration):
38
64
63
7
30
sampsontan/virtual-clinic
server/migrations/0007_appointment_appointment_type.py
Python
Migration
Migration
6
18
6
7
15595fbb42f168b547db55fcf9efdffe23ffb07b
bigcode/the-stack
train
274f2ac01a7cacedc3cea90e
train
function
def get_or_create_ip_address_node( local_client: DgraphClient, node_key: str, first_seen_timestamp: Millis, last_seen_timestamp: Millis, ip_address: str, # ip connections todo ) -> IpAddressView: ip_addr_props = { "first_seen_timestamp": first_seen_timestamp, "last_seen_times...
def get_or_create_ip_address_node( local_client: DgraphClient, node_key: str, first_seen_timestamp: Millis, last_seen_timestamp: Millis, ip_address: str, # ip connections todo ) -> IpAddressView:
ip_addr_props = { "first_seen_timestamp": first_seen_timestamp, "last_seen_timestamp": last_seen_timestamp, "ip_address": ip_address, } # type: Dict[str, Property] return cast( IpAddressView, upsert( client=local_client, type_name="IpAddress"...
.view_assertions import assert_views_equal def get_or_create_ip_address_node( local_client: DgraphClient, node_key: str, first_seen_timestamp: Millis, last_seen_timestamp: Millis, ip_address: str, # ip connections todo ) -> IpAddressView:
64
64
153
56
7
0xflotus/grapl
src/python/grapl_analyzerlib/tests/test_ip_address_node.py
Python
get_or_create_ip_address_node
get_or_create_ip_address_node
22
45
22
29
68c9692c65ca81c2a8e5b90dee00c32fe54b0296
bigcode/the-stack
train
80100c891787105d7885a8a6
train
class
@pytest.mark.integration_test class TestIpAddressQuery(unittest.TestCase): @hypothesis.settings(deadline=None,) @given( node_key=st.uuids(), first_seen_timestamp=st.datetimes(), last_seen_timestamp=st.datetimes(), ip_address=st.ip_addresses(v=4), # TODO: support ipv6? ) ...
@pytest.mark.integration_test class TestIpAddressQuery(unittest.TestCase): @hypothesis.settings(deadline=None,) @given( node_key=st.uuids(), first_seen_timestamp=st.datetimes(), last_seen_timestamp=st.datetimes(), ip_address=st.ip_addresses(v=4), # TODO: support ipv6? )
def test__single_ip_addr_node__query_by_node_key( self, node_key, first_seen_timestamp, last_seen_timestamp, ip_address, ): # current function's name, but don't need to copy-paste replace node_key = node_key_for_test(self, node_key) local_client = MasterGraphClient() cre...
), ) @pytest.mark.integration_test class TestIpAddressQuery(unittest.TestCase): @hypothesis.settings(deadline=None,) @given( node_key=st.uuids(), first_seen_timestamp=st.datetimes(), last_seen_timestamp=st.datetimes(), ip_address=st.ip_addresses(v=4), # TODO: support...
79
79
264
75
4
0xflotus/grapl
src/python/grapl_analyzerlib/tests/test_ip_address_node.py
Python
TestIpAddressQuery
TestIpAddressQuery
48
80
48
56
a71b59cd500d66e1289706c4ba0fa825635e9dc4
bigcode/the-stack
train
e942f74b9368ea2ba4527c23
train
function
def test_override_ref(): """#392/397: overriding reference-returning functions""" o = m.OverrideTest("asdf") # Not allowed (see associated .cpp comment) # i = o.str_ref() # assert o.str_ref() == "asdf" assert o.str_value() == "asdf" assert o.A_value().value == "hi" a = o.A_ref() as...
def test_override_ref():
"""#392/397: overriding reference-returning functions""" o = m.OverrideTest("asdf") # Not allowed (see associated .cpp comment) # i = o.str_ref() # assert o.str_ref() == "asdf" assert o.str_value() == "asdf" assert o.A_value().value == "hi" a = o.A_ref() assert a.value == "hi" ...
() assert msg(excinfo.value) == 'Tried to call pure virtual function "Base::dispatch"' p = PyClass1() return m.dispatch_issue_go(p) b = PyClass2() assert m.dispatch_issue_go(b) == "Yay.." def test_override_ref():
64
64
108
5
58
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_override_ref
test_override_ref
228
241
228
228
53a8b279a133a182dee209aeb75bc965f19435e3
bigcode/the-stack
train
1b59b8ac9a65dfdc795cd2d4
train
function
def test_alias_delay_initialization2(capture): """`A2`, unlike the above, is configured to always initialize the alias While the extra initialization and extra class layer has small virtual dispatch performance penalty, it also allows us to do more things with the trampoline class such as defining loca...
def test_alias_delay_initialization2(capture):
"""`A2`, unlike the above, is configured to always initialize the alias While the extra initialization and extra class layer has small virtual dispatch performance penalty, it also allows us to do more things with the trampoline class such as defining local variables and performing construction/destruc...
.call_f(a) del a pytest.gc_collect() assert capture == "A.f()" # Python version with capture: b = B() m.call_f(b) del b pytest.gc_collect() assert capture == """ PyA.PyA() PyA.f() In python f() PyA.~PyA() """ def test_a...
92
93
312
10
82
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_alias_delay_initialization2
test_alias_delay_initialization2
110
156
110
110
bf55f6fedb540e44f8607bcb5921e63bed46a809
bigcode/the-stack
train
47adc8d76756c7a0f7ded6f8
train
function
def test_inherited_virtuals(): class AR(m.A_Repeat): def unlucky_number(self): return 99 class AT(m.A_Tpl): def unlucky_number(self): return 999 obj = AR() assert obj.say_something(3) == "hihihi" assert obj.unlucky_number() == 99 assert obj.say_everythin...
def test_inherited_virtuals():
class AR(m.A_Repeat): def unlucky_number(self): return 99 class AT(m.A_Tpl): def unlucky_number(self): return 999 obj = AR() assert obj.say_something(3) == "hihihi" assert obj.unlucky_number() == 99 assert obj.say_everything() == "hi 99" obj = AT() ...
structions >= 0 def test_dispatch_issue(msg): """#159: virtual function dispatch has problems with similar-named functions""" class PyClass1(m.DispatchIssue): def dispatch(self): return "Yay.." class PyClass2(m.DispatchIssue): def dispatch(self): with pytest.raises...
256
256
1,110
7
249
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_inherited_virtuals
test_inherited_virtuals
244
370
244
244
f72616c5293d4f04c90d4d74959d590c77593cfd
bigcode/the-stack
train
028eeb532ec587a806e2383b
train
function
def test_issue_1454(): # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7) m.test_gil() m.test_gil_from_thread()
def test_issue_1454(): # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
m.test_gil() m.test_gil_from_thread()
() == -7 assert obj.lucky_number() == -1.375 assert obj.say_everything() == "BT -7" def test_issue_1454(): # Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
64
64
47
33
31
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_issue_1454
test_issue_1454
373
376
373
374
f0f33feb67d70232562e8838e0b39133bc46c420
bigcode/the-stack
train
34f11dedb5d9985ec3523f8d
train
function
def test_alias_delay_initialization1(capture): """`A` only initializes its trampoline class when we inherit from it If we just create and use an A instance directly, the trampoline initialization is bypassed and we only initialize an A() instead (for performance reasons). """ class B(m.A): ...
def test_alias_delay_initialization1(capture):
"""`A` only initializes its trampoline class when we inherit from it If we just create and use an A instance directly, the trampoline initialization is bypassed and we only initialize an A() instead (for performance reasons). """ class B(m.A): def __init__(self): super(B, self)....
ex12p2 assert cstats.alive() == 0 assert cstats.values() == ['10', '11', '17'] assert cstats.copy_constructions == 0 assert cstats.move_constructions >= 0 def test_alias_delay_initialization1(capture):
64
64
195
10
53
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_alias_delay_initialization1
test_alias_delay_initialization1
75
107
75
75
90c5f4868d204be258780f118c2e6ed06e0e78f6
bigcode/the-stack
train
cffaa249767b566663324c44
train
function
def test_override(capture, msg): class ExtendedExampleVirt(m.ExampleVirt): def __init__(self, state): super(ExtendedExampleVirt, self).__init__(state + 1) self.data = "Hello world" def run(self, value): print('ExtendedExampleVirt::run(%i), calling parent..' % val...
def test_override(capture, msg):
class ExtendedExampleVirt(m.ExampleVirt): def __init__(self, state): super(ExtendedExampleVirt, self).__init__(state + 1) self.data = "Hello world" def run(self, value): print('ExtendedExampleVirt::run(%i), calling parent..' % value) return super(Exte...
import pytest from pybind11_tests import ConstructorStats from pybind11_tests import virtual_functions as m def test_override(capture, msg):
31
194
649
8
22
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_override
test_override
6
72
6
6
d2de94990c8b65213603618d1bd0d714416654af
bigcode/the-stack
train
336f8ac1147abf6dbcb46d95
train
function
def test_dispatch_issue(msg): """#159: virtual function dispatch has problems with similar-named functions""" class PyClass1(m.DispatchIssue): def dispatch(self): return "Yay.." class PyClass2(m.DispatchIssue): def dispatch(self): with pytest.raises(RuntimeError) as ...
def test_dispatch_issue(msg):
"""#159: virtual function dispatch has problems with similar-named functions""" class PyClass1(m.DispatchIssue): def dispatch(self): return "Yay.." class PyClass2(m.DispatchIssue): def dispatch(self): with pytest.raises(RuntimeError) as excinfo: super...
() == ['4', '5', '7', '7'] assert nc_stats.copy_constructions == 0 assert mv_stats.copy_constructions == 1 assert nc_stats.move_constructions >= 0 assert mv_stats.move_constructions >= 0 def test_dispatch_issue(msg):
64
64
136
6
57
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_dispatch_issue
test_dispatch_issue
209
225
209
209
b40fbb2add46dd4de750486df49b443eadf98236
bigcode/the-stack
train
38009467825dac5e6a68d8b6
train
function
@pytest.unsupported_on_pypy @pytest.mark.skipif(not hasattr(m, "NCVirt"), reason="NCVirt test broken on ICPC") def test_move_support(): class NCVirtExt(m.NCVirt): def get_noncopyable(self, a, b): # Constructs and returns a new instance: nc = m.NonCopyable(a * a, b * b) re...
@pytest.unsupported_on_pypy @pytest.mark.skipif(not hasattr(m, "NCVirt"), reason="NCVirt test broken on ICPC") def test_move_support():
class NCVirtExt(m.NCVirt): def get_noncopyable(self, a, b): # Constructs and returns a new instance: nc = m.NonCopyable(a * a, b * b) return nc def get_movable(self, a, b): # Return a referenced copy self.movable = m.Movable(a, b) ...
.~PyA2() """ # Python subclass version with capture: b2 = B2() m.call_f(b2) del b2 pytest.gc_collect() assert capture == """ PyA2.PyA2() PyA2.f() In python B2.f() PyA2.~PyA2() """ # PyPy: Reference count > 1 causes call with noncopya...
141
141
471
34
107
martbelko/OpenXLSX
Python/library/pybind11/tests/test_virtual_functions.py
Python
test_move_support
test_move_support
161
206
161
163
614c7e8505c16608513654c4f34990d79ae95061
bigcode/the-stack
train
d869734915801883b9689b72
train
class
class SuiteRequirements(Requirements): @property def create_table(self): """target platform can emit basic CreateTable DDL.""" return exclusions.open() @property def drop_table(self): """target platform can emit basic DropTable DDL.""" return exclusions.open() @pr...
class SuiteRequirements(Requirements): @property
def create_table(self): """target platform can emit basic CreateTable DDL.""" return exclusions.open() @property def drop_table(self): """target platform can emit basic DropTable DDL.""" return exclusions.open() @property def table_ddl_if_exists(self): """...
# testing/requirements.py # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Global database feature support policy. Provides decorators to mark test...
132
256
7,731
10
121
python-gino/sqlalchemy
lib/sqlalchemy/testing/requirements.py
Python
SuiteRequirements
SuiteRequirements
29
1,388
29
30
689419477b31606d13f7f0308a45b49f800070b0
bigcode/the-stack
train
7886b79e3b666bc08d8d9465
train
class
class Requirements(object): pass
class Requirements(object):
pass
/mit-license.php """Global database feature support policy. Provides decorators to mark tests requiring specific feature support from the target database. External dialect test suites should subclass SuiteRequirements to provide specific inclusion/exclusions. """ import platform import sys from . import exclusion...
64
64
7
4
59
python-gino/sqlalchemy
lib/sqlalchemy/testing/requirements.py
Python
Requirements
Requirements
25
26
25
25
c721e9395751388c0b068105405469e46d5b82f5
bigcode/the-stack
train
4cd66cb264e2f4489c60f0d5
train
function
def send_email_to_admins( template_prefix: str, realm: Realm, from_name: Optional[str] = None, from_address: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, ) -> None: admins = realm.get_human_admin_users() admin_user_ids = [admin.id for admin in admin...
def send_email_to_admins( template_prefix: str, realm: Realm, from_name: Optional[str] = None, from_address: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, ) -> None:
admins = realm.get_human_admin_users() admin_user_ids = [admin.id for admin in admins] send_email( template_prefix, to_user_ids=admin_user_ids, from_name=from_name, from_address=from_address, language=language, context=context, )
raise e def send_email_to_admins( template_prefix: str, realm: Realm, from_name: Optional[str] = None, from_address: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, ) -> None:
64
64
126
61
2
icp1994/zulip
zerver/lib/send_email.py
Python
send_email_to_admins
send_email_to_admins
363
380
363
370
a7c1e39fbeda00d5be3577b3b3ed69e4fd849092
bigcode/the-stack
train
d834304cafab3697f30fbaaf
train
class
class DoubledEmailArgumentException(CommandError): def __init__(self, argument_name: str) -> None: msg = ( f"Argument '{argument_name}' is ambiguously present in both options and email template." ) super().__init__(msg)
class DoubledEmailArgumentException(CommandError):
def __init__(self, argument_name: str) -> None: msg = ( f"Argument '{argument_name}' is ambiguously present in both options and email template." ) super().__init__(msg)
, envelope_from, to_emails, reply_to=reply_to, headers=extra_headers ) if html_message is not None: mail.attach_alternative(html_message, "text/html") return mail class EmailNotDeliveredException(Exception): pass class DoubledEmailArgumentException(CommandError):
64
64
56
9
54
icp1994/zulip
zerver/lib/send_email.py
Python
DoubledEmailArgumentException
DoubledEmailArgumentException
201
206
201
201
3ac4153580307c25e9f31aea7b8c29570b53be2e
bigcode/the-stack
train
16925b75dec75a662572e4e6
train
function
def send_email( template_prefix: str, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, reply_to_email: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, ...
def send_email( template_prefix: str, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, reply_to_email: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, ...
mail = build_email( template_prefix, to_user_ids=to_user_ids, to_emails=to_emails, from_name=from_name, from_address=from_address, reply_to_email=reply_to_email, language=language, context=context, realm=realm, ) template = template_pre...
# migration to change or remove any emails in ScheduledEmail. def send_email( template_prefix: str, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, reply_to_email: Optional[str] = None, lang...
131
131
438
118
13
icp1994/zulip
zerver/lib/send_email.py
Python
send_email
send_email
217
271
217
229
259c8b486df97a104f27c1f43c8fd6e389c1fa83
bigcode/the-stack
train
2fd71626c0501b4bd4472ad6
train
function
def deliver_scheduled_emails(email: ScheduledEmail) -> None: data = orjson.loads(email.data) user_ids = list(email.users.values_list("id", flat=True)) if not user_ids and not email.address: # This state doesn't make sense, so something must be mutating, # or in the process of deleting, the o...
def deliver_scheduled_emails(email: ScheduledEmail) -> None:
data = orjson.loads(email.data) user_ids = list(email.users.values_list("id", flat=True)) if not user_ids and not email.address: # This state doesn't make sense, so something must be mutating, # or in the process of deleting, the object. We assume it will bring # things to a correct ...
to_email"] if "to_user_id" in job: if job["to_user_id"] is not None: job["to_user_ids"] = [job["to_user_id"]] del job["to_user_id"] def deliver_scheduled_emails(email: ScheduledEmail) -> None:
63
64
175
14
49
icp1994/zulip
zerver/lib/send_email.py
Python
deliver_scheduled_emails
deliver_scheduled_emails
427
443
427
427
12596a36b19a4d4ff3e9ec250dd0ba76bf547c10
bigcode/the-stack
train
617dfd9c9558ecf90d43c18b
train
class
class EmailNotDeliveredException(Exception): pass
class EmailNotDeliveredException(Exception):
pass
mail = EmailMultiAlternatives( email_subject, message, envelope_from, to_emails, reply_to=reply_to, headers=extra_headers ) if html_message is not None: mail.attach_alternative(html_message, "text/html") return mail class EmailNotDeliveredException(Exception):
64
64
10
7
56
icp1994/zulip
zerver/lib/send_email.py
Python
EmailNotDeliveredException
EmailNotDeliveredException
197
198
197
197
b85a347c40d315c02295debab27061759f7621fd
bigcode/the-stack
train
1886f8640e36131bdb675885
train
function
def clear_scheduled_invitation_emails(email: str) -> None: """Unlike most scheduled emails, invitation emails don't have an existing user object to key off of, so we filter by address here.""" items = ScheduledEmail.objects.filter( address__iexact=email, type=ScheduledEmail.INVITATION_REMINDER )...
def clear_scheduled_invitation_emails(email: str) -> None:
"""Unlike most scheduled emails, invitation emails don't have an existing user object to key off of, so we filter by address here.""" items = ScheduledEmail.objects.filter( address__iexact=email, type=ScheduledEmail.INVITATION_REMINDER ) items.delete()
admin.id for admin in admins] send_email( template_prefix, to_user_ids=admin_user_ids, from_name=from_name, from_address=from_address, language=language, context=context, ) def clear_scheduled_invitation_emails(email: str) -> None:
64
64
76
15
49
icp1994/zulip
zerver/lib/send_email.py
Python
clear_scheduled_invitation_emails
clear_scheduled_invitation_emails
383
389
383
383
4a67e9964c8ec99222792503ddf79600b13478c6
bigcode/the-stack
train
1e0ab69e0f0430f790a82174
train
class
class NoEmailArgumentException(CommandError): def __init__(self, argument_name: str) -> None: msg = f"Argument '{argument_name}' is required in either options or email template." super().__init__(msg)
class NoEmailArgumentException(CommandError):
def __init__(self, argument_name: str) -> None: msg = f"Argument '{argument_name}' is required in either options or email template." super().__init__(msg)
class DoubledEmailArgumentException(CommandError): def __init__(self, argument_name: str) -> None: msg = ( f"Argument '{argument_name}' is ambiguously present in both options and email template." ) super().__init__(msg) class NoEmailArgumentException(CommandError):
64
64
49
8
56
icp1994/zulip
zerver/lib/send_email.py
Python
NoEmailArgumentException
NoEmailArgumentException
209
212
209
209
c2b8d0f9850d73615e46d96ecdc62a1b9bffb025
bigcode/the-stack
train
14c90a7f4db40dbf62c0179b
train
function
@transaction.atomic(savepoint=False) def clear_scheduled_emails(user_id: int, email_type: Optional[int] = None) -> None: # We need to obtain a FOR UPDATE lock on the selected rows to keep a concurrent # execution of this function (or something else) from deleting them before we access # the .users attribute...
@transaction.atomic(savepoint=False) def clear_scheduled_emails(user_id: int, email_type: Optional[int] = None) -> None: # We need to obtain a FOR UPDATE lock on the selected rows to keep a concurrent # execution of this function (or something else) from deleting them before we access # the .users attribute...
items = ( ScheduledEmail.objects.filter(users__in=[user_id]) .prefetch_related("users") .select_for_update() ) if email_type is not None: items = items.filter(type=email_type) for item in items: item.users.remove(user_id) if item.users.all().count() == 0:...
@transaction.atomic(savepoint=False) def clear_scheduled_emails(user_id: int, email_type: Optional[int] = None) -> None: # We need to obtain a FOR UPDATE lock on the selected rows to keep a concurrent # execution of this function (or something else) from deleting them before we access # the .users attribute...
74
64
195
74
0
icp1994/zulip
zerver/lib/send_email.py
Python
clear_scheduled_emails
clear_scheduled_emails
392
411
392
396
d3487b8ccefbf3a2f501921242752f49220fc8a0
bigcode/the-stack
train
25f1d89a96c257f104accc02
train
function
def handle_send_email_format_changes(job: Dict[str, Any]) -> None: # Reformat any jobs that used the old to_email # and to_user_ids argument formats. if "to_email" in job: if job["to_email"] is not None: job["to_emails"] = [job["to_email"]] del job["to_email"] if "to_user_id"...
def handle_send_email_format_changes(job: Dict[str, Any]) -> None: # Reformat any jobs that used the old to_email # and to_user_ids argument formats.
if "to_email" in job: if job["to_email"] is not None: job["to_emails"] = [job["to_email"]] del job["to_email"] if "to_user_id" in job: if job["to_user_id"] is not None: job["to_user_ids"] = [job["to_user_id"]] del job["to_user_id"]
is accurate, thus we can reliably use it # to decide whether to delete the ScheduledEmail row. item.delete() def handle_send_email_format_changes(job: Dict[str, Any]) -> None: # Reformat any jobs that used the old to_email # and to_user_ids argument formats.
64
64
126
38
26
icp1994/zulip
zerver/lib/send_email.py
Python
handle_send_email_format_changes
handle_send_email_format_changes
414
424
414
416
ed61f7065460ebead1b10b2703c7250b5d887c38
bigcode/the-stack
train
8d9e08f98cbaaf3fa638aece
train
class
class FromAddress: SUPPORT = parseaddr(settings.ZULIP_ADMINISTRATOR)[1] NOREPLY = parseaddr(settings.NOREPLY_EMAIL_ADDRESS)[1] support_placeholder = "SUPPORT" no_reply_placeholder = "NO_REPLY" tokenized_no_reply_placeholder = "TOKENIZED_NO_REPLY" # Generates an unpredictable noreply address. ...
class FromAddress:
SUPPORT = parseaddr(settings.ZULIP_ADMINISTRATOR)[1] NOREPLY = parseaddr(settings.NOREPLY_EMAIL_ADDRESS)[1] support_placeholder = "SUPPORT" no_reply_placeholder = "NO_REPLY" tokenized_no_reply_placeholder = "TOKENIZED_NO_REPLY" # Generates an unpredictable noreply address. @staticmethod ...
, UserProfile, get_user_profile_by_id from zproject.email_backends import EmailLogBackEnd, get_forward_address MAX_CONNECTION_TRIES = 3 ## Logging setup ## logger = logging.getLogger("zulip.send_email") log_to_file(logger, settings.EMAIL_LOG_PATH) class FromAddress:
64
64
209
4
60
icp1994/zulip
zerver/lib/send_email.py
Python
FromAddress
FromAddress
41
67
41
41
7d4b5663cd16b51d2450cc8bf366b509dae05129
bigcode/the-stack
train
143a91cbad823c355169c833
train
function
def get_header(option: Optional[str], header: Optional[str], name: str) -> str: if option and header: raise DoubledEmailArgumentException(name) if not option and not header: raise NoEmailArgumentException(name) return str(option or header)
def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
if option and header: raise DoubledEmailArgumentException(name) if not option and not header: raise NoEmailArgumentException(name) return str(option or header)
_ids"] = user_ids if email.address is not None: data["to_emails"] = [email.address] handle_send_email_format_changes(data) send_email(**data) email.delete() def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
64
64
58
20
44
icp1994/zulip
zerver/lib/send_email.py
Python
get_header
get_header
446
451
446
446
628dc727d372d2bcf29509ddf5d8d7a036becf8f
bigcode/the-stack
train
47e73be3e883b2e39a486fc4
train
function
def build_email( template_prefix: str, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, reply_to_email: Optional[str] = None, language: Optional[str] = None, context: Mapping[str, Any] = {...
def build_email( template_prefix: str, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, reply_to_email: Optional[str] = None, language: Optional[str] = None, context: Mapping[str, Any] = {...
assert (to_user_ids is None) ^ (to_emails is None) if to_user_ids is not None: to_users = [get_user_profile_by_id(to_user_id) for to_user_id in to_user_ids] if realm is None: assert len({to_user.realm_id for to_user in to_users}) == 1 realm = to_users[0].realm to_...
noreply address. @staticmethod def tokenized_no_reply_address() -> str: if settings.ADD_TOKENS_TO_NOREPLY_ADDRESS: return parseaddr(settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS)[1].format( token=generate_key() ) return FromAddress.NOREPLY @staticmethod ...
256
256
1,304
117
139
icp1994/zulip
zerver/lib/send_email.py
Python
build_email
build_email
70
194
70
81
ee251396ca391fe890cb0aa5dada32d87490b309
bigcode/the-stack
train
def69ca8a3e54213eaef9fb4
train
function
def send_future_email( template_prefix: str, realm: Realm, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, delay: datetim...
def send_future_email( template_prefix: str, realm: Realm, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[str] = None, from_address: Optional[str] = None, language: Optional[str] = None, context: Dict[str, Any] = {}, delay: datetim...
template_name = template_prefix.split("/")[-1] email_fields = { "template_prefix": template_prefix, "from_name": from_name, "from_address": from_address, "language": language, "context": context, } if settings.DEVELOPMENT_LOG_EMAILS: send_email( ...
status != 250: # Close and connect again. connection.close() connection.open() return connection def send_future_email( template_prefix: str, realm: Realm, to_user_ids: Optional[List[int]] = None, to_emails: Optional[List[str]] = None, from_name: Optional[st...
118
118
394
94
23
icp1994/zulip
zerver/lib/send_email.py
Python
send_future_email
send_future_email
307
360
307
317
5db9272812de7616b85664e3350089a66502fbbc
bigcode/the-stack
train
68035bb50537b5da80c783c4
train
function
def send_custom_email(users: List[UserProfile], options: Dict[str, Any]) -> None: """ Can be used directly with from a management shell with send_custom_email(user_profile_list, dict( markdown_template_path="/path/to/markdown/file.md", subject="Email subject", from_name="Sender Name"...
def send_custom_email(users: List[UserProfile], options: Dict[str, Any]) -> None:
""" Can be used directly with from a management shell with send_custom_email(user_profile_list, dict( markdown_template_path="/path/to/markdown/file.md", subject="Email subject", from_name="Sender Name") ) """ with open(options["markdown_template_path"]) as f: te...
in the process of deleting, the object. We assume it will bring # things to a correct state, and we just do nothing except logging this event. logger.warning("ScheduledEmail id %s has empty users and address attributes.", email.id) return if user_ids: data["to_user_ids"] = user_ids...
188
188
629
21
167
icp1994/zulip
zerver/lib/send_email.py
Python
send_custom_email
send_custom_email
454
521
454
454
bcecef460898e125a0e1032ccf5710cab504540b
bigcode/the-stack
train
157b34d199f166de1f44342b
train
function
@backoff.on_exception(backoff.expo, OSError, max_tries=MAX_CONNECTION_TRIES, logger=None) def initialize_connection(connection: Optional[BaseEmailBackend] = None) -> BaseEmailBackend: if not connection: connection = get_connection() if connection.open(): # If it's a new connection, no need to n...
@backoff.on_exception(backoff.expo, OSError, max_tries=MAX_CONNECTION_TRIES, logger=None) def initialize_connection(connection: Optional[BaseEmailBackend] = None) -> BaseEmailBackend:
if not connection: connection = get_connection() if connection.open(): # If it's a new connection, no need to no-op to check connectivity return connection if isinstance(connection, EmailLogBackEnd) and not get_forward_address(): # With the development environment backend a...
%s email to %s: %s", template, mail.to, str(e), stack_info=True ) raise EmailNotDeliveredException @backoff.on_exception(backoff.expo, OSError, max_tries=MAX_CONNECTION_TRIES, logger=None) def initialize_connection(connection: Optional[BaseEmailBackend] = None) -> BaseEmailBackend:
75
75
252
44
30
icp1994/zulip
zerver/lib/send_email.py
Python
initialize_connection
initialize_connection
274
304
274
275
80309524baa92753a496314db7ad91de8059d8bd
bigcode/the-stack
train
7bb3a583a5ada78a71b34685
train
function
def delete(item): key(item).delete() return item
def delete(item):
key(item).delete() return item
(urlsafe=s) raise ValueError("Can no coerce value %s into a key." % s) def get(item): if isinstance(item, ndb.Query): return item.get() return key(item).get() def put(item): item.put() return item def delete(item):
64
64
14
4
59
yowmamasita/ferris3
ferris3/ndb.py
Python
delete
delete
175
177
175
175
1d29e236900e1f9bfbdc96b363deb27bcfbcc6e0
bigcode/the-stack
train
d78ef7ef1646b711e6d6d1ac
train
function
def paginate(query, limit=50, page_token=None): if page_token and not isinstance(page_token, Cursor): page_token = Cursor(urlsafe=page_token) # Force all falsy values into None if not page_token: page_token = None data, next_cursor, more = query.fetch_page(limit, start_cursor=page_toke...
def paginate(query, limit=50, page_token=None):
if page_token and not isinstance(page_token, Cursor): page_token = Cursor(urlsafe=page_token) # Force all falsy values into None if not page_token: page_token = None data, next_cursor, more = query.fetch_page(limit, start_cursor=page_token) return PaginationResults(items=data, nex...
if not kind == item_key.kind(): raise ValueError("Incorrect kind %s, expected %s" % (item_key.kind(), kind)) return item PaginationResults = namedtuple('PaginationResults', ['items', 'next_page_token']) def paginate(query, limit=50, page_token=None):
63
64
97
12
51
yowmamasita/ferris3
ferris3/ndb.py
Python
paginate
paginate
194
204
194
194
7ac1119b3132bf100d3f35def882277a2b834c01
bigcode/the-stack
train
27ea3a2e80f15116561d18be
train
function
def put(item): item.put() return item
def put(item):
item.put() return item
isinstance(s, types.StringTypes): return ndb.Key(urlsafe=s) raise ValueError("Can no coerce value %s into a key." % s) def get(item): if isinstance(item, ndb.Query): return item.get() return key(item).get() def put(item):
64
64
12
4
60
yowmamasita/ferris3
ferris3/ndb.py
Python
put
put
170
172
170
170
b052b4d8c25f0e61d8294be02bb8a3274305e7b8
bigcode/the-stack
train
07ad886def19b4fafa700a88
train
function
def get(item): if isinstance(item, ndb.Query): return item.get() return key(item).get()
def get(item):
if isinstance(item, ndb.Query): return item.get() return key(item).get()
, ndb.Model): return s.key if isinstance(s, ndb.Key): return s if isinstance(s, types.StringTypes): return ndb.Key(urlsafe=s) raise ValueError("Can no coerce value %s into a key." % s) def get(item):
64
64
25
4
60
yowmamasita/ferris3
ferris3/ndb.py
Python
get
get
164
167
164
164
acc6df3e0f8aa75933f5843ff8ab2f9d00784283
bigcode/the-stack
train
8f153c9917a9a6e992a86b5e
train
class
class ModelMeta(ndb.model.MetaModel): """ Ensures behaviors are constructed. """ def __init__(cls, name, bases, dct): super(ModelMeta, cls).__init__(name, bases, dct) # Make sure the Meta class has a proper chain if cls.__name__ != 'Model' and not issubclass(cls.Meta, Model.Meta...
class ModelMeta(ndb.model.MetaModel):
""" Ensures behaviors are constructed. """ def __init__(cls, name, bases, dct): super(ModelMeta, cls).__init__(name, bases, dct) # Make sure the Meta class has a proper chain if cls.__name__ != 'Model' and not issubclass(cls.Meta, Model.Meta): cls.Meta = type('Meta',...
""" Utilities that build on top of the built-in ndb. """ from google.appengine.ext import ndb from google.appengine.datastore.datastore_query import Cursor import types from collections import namedtuple class ModelMeta(ndb.model.MetaModel):
53
64
125
9
43
yowmamasita/ferris3
ferris3/ndb.py
Python
ModelMeta
ModelMeta
11
23
11
11
175b6b656feb290c919fbb94a4fdab5974287af1
bigcode/the-stack
train
cc0c0c4029c2accfce251669
train
class
class Model(ndb.Model): """ ``ndb.Model`` subclass that supports easier callbacks and behaviors. """ __metaclass__ = ModelMeta class Meta(object): behaviors = () def before_put(self): """ Called before an item is saved. :arg self: refers to the item that is abo...
class Model(ndb.Model):
""" ``ndb.Model`` subclass that supports easier callbacks and behaviors. """ __metaclass__ = ModelMeta class Meta(object): behaviors = () def before_put(self): """ Called before an item is saved. :arg self: refers to the item that is about to be saved :...
""" Utilities that build on top of the built-in ndb. """ from google.appengine.ext import ndb from google.appengine.datastore.datastore_query import Cursor import types from collections import namedtuple class ModelMeta(ndb.model.MetaModel): """ Ensures behaviors are constructed. """ def __init__(cls...
175
192
642
6
169
yowmamasita/ferris3
ferris3/ndb.py
Python
Model
Model
26
125
26
26
b09f1153c31e7ccbdece4ea842732fdd8f278b2c
bigcode/the-stack
train
57afc3845a3a06a64bbb682a
train
function
def key(s): if isinstance(s, ndb.Model): return s.key if isinstance(s, ndb.Key): return s if isinstance(s, types.StringTypes): return ndb.Key(urlsafe=s) raise ValueError("Can no coerce value %s into a key." % s)
def key(s):
if isinstance(s, ndb.Model): return s.key if isinstance(s, ndb.Key): return s if isinstance(s, types.StringTypes): return ndb.Key(urlsafe=s) raise ValueError("Can no coerce value %s into a key." % s)
instance): pass def after_put(self, instance): pass def before_delete(self, key): pass def after_delete(self, key): pass def before_get(self, key): pass def after_get(self, item): pass def key(s):
64
64
68
4
59
yowmamasita/ferris3
ferris3/ndb.py
Python
key
key
154
161
154
154
4e884f79589487997a3f459b4e9ec5c05fb91367
bigcode/the-stack
train
28936520b4912c1924d8a035
train
function
def check_kind(kind, item): if issubclass(kind, ndb.Model): kind = kind._get_kind() item_key = key(item) if not kind == item_key.kind(): raise ValueError("Incorrect kind %s, expected %s" % (item_key.kind(), kind)) return item
def check_kind(kind, item):
if issubclass(kind, ndb.Model): kind = kind._get_kind() item_key = key(item) if not kind == item_key.kind(): raise ValueError("Incorrect kind %s, expected %s" % (item_key.kind(), kind)) return item
a key." % s) def get(item): if isinstance(item, ndb.Query): return item.get() return key(item).get() def put(item): item.put() return item def delete(item): key(item).delete() return item def check_kind(kind, item):
64
64
68
7
56
yowmamasita/ferris3
ferris3/ndb.py
Python
check_kind
check_kind
180
188
180
180
fcff931dce245c283c44153cb36456dbd3cdd9ba
bigcode/the-stack
train
2a700c3dbfe11391e8185d94
train
class
class Behavior(object): """ Behaviors allow you to encapsulate callbacks into discrete units that can be combined together. """ def __init__(self, Model): self.Model = Model def before_put(self, instance): pass def after_put(self, instance): pass def before_delete(...
class Behavior(object):
""" Behaviors allow you to encapsulate callbacks into discrete units that can be combined together. """ def __init__(self, Model): self.Model = Model def before_put(self, instance): pass def after_put(self, instance): pass def before_delete(self, key): pass...
invoke_behaviors('before_get', key) return cls.before_get(key) @classmethod def _post_get_hook(cls, key, future): res = future.get_result() cls._invoke_behaviors('after_get', res) return cls.after_get(key, res) class Behavior(object):
64
64
107
4
60
yowmamasita/ferris3
ferris3/ndb.py
Python
Behavior
Behavior
128
151
128
128
04386740aebf7309b137e95a0c86b094bad4bdd0
bigcode/the-stack
train
0e25769d274afa324fa3a2e8
train
function
def gt_diff(gt0: GeoTransform, gt1: GeoTransform, diff_support: Dict[GT, bool], eps: Union[Number, Dict[GT, Number]]=0.0): if gt0 == gt1: return GT.SAME if isinstance(eps, Number): eps = {GT.INCOMPATIBLE_OFFSET: eps, GT.INCOMPATIBLE_PIXEL_SIZE: eps, GT.INCOMPATIBLE_ROTATION: eps} same = { ...
def gt_diff(gt0: GeoTransform, gt1: GeoTransform, diff_support: Dict[GT, bool], eps: Union[Number, Dict[GT, Number]]=0.0):
if gt0 == gt1: return GT.SAME if isinstance(eps, Number): eps = {GT.INCOMPATIBLE_OFFSET: eps, GT.INCOMPATIBLE_PIXEL_SIZE: eps, GT.INCOMPATIBLE_ROTATION: eps} same = { GT.INCOMPATIBLE_OFFSET: eps[GT.INCOMPATIBLE_OFFSET] >= (abs(gt0[0] - gt1[0]) + abs(gt0[3] - gt1[3])), ...
1 ALMOST_SAME = -2 COMPATIBLE_DIFF = -3 INCOMPATIBLE_OFFSET = 0 INCOMPATIBLE_PIXEL_SIZE = 1 INCOMPATIBLE_ROTATION = 2 NON_ZERO_ROTATION = 3 GeoTransform = Sequence[Number] def gt_diff(gt0: GeoTransform, gt1: GeoTransform, diff_support: Dict[GT, bool], eps: Union[Number, Dict[GT, Number]]=0.0):...
108
108
360
40
68
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
gt_diff
gt_diff
68
83
68
68
db0e1676e2d312254bede123bde7a65164d21ced
bigcode/the-stack
train
8a91d7d4469616ae03a01130
train
function
def parse_extent(extent: Union[str, Extent]) -> Extent: if isinstance(extent, str): return Extent[extent.upper()] elif isinstance(extent, Extent): return extent raise Exception('Error: Unknown extent %s' % extent)
def parse_extent(extent: Union[str, Extent]) -> Extent:
if isinstance(extent, str): return Extent[extent.upper()] elif isinstance(extent, Extent): return extent raise Exception('Error: Unknown extent %s' % extent)
import gdal from osgeo.utils.auxiliary.rectangle import GeoRectangle class Extent(Enum): IGNORE = 0 FAIL = 1 UNION = 2 INTERSECT = 3 def parse_extent(extent: Union[str, Extent]) -> Extent:
64
64
59
16
47
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
parse_extent
parse_extent
47
52
47
47
ea8d65121fbf244dcaf53e8791146bfb6fb6df3d
bigcode/the-stack
train
8cc751b2c09ed6d266ed3dc5
train
class
class Extent(Enum): IGNORE = 0 FAIL = 1 UNION = 2 INTERSECT = 3
class Extent(Enum):
IGNORE = 0 FAIL = 1 UNION = 2 INTERSECT = 3
OR OTHER # DEALINGS IN THE SOFTWARE. # ****************************************************************************** import math import tempfile from numbers import Number from enum import Enum from typing import Optional, Union, Sequence, Dict from osgeo import gdal from osgeo.utils.auxiliary.rectangle import GeoR...
64
64
32
5
58
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
Extent
Extent
40
44
40
40
df20c123ecb0423757767e25d5b34a47ef58b179
bigcode/the-stack
train
45509813642f4a21a4ab2f7d
train
function
def make_temp_vrt(ds, extent: GeoRectangle): options = gdal.BuildVRTOptions(outputBounds=(extent.min_x, extent.min_y, extent.max_x, extent.max_y)) vrt_filename = tempfile.mktemp(suffix='.vrt') vrt_ds = gdal.BuildVRT(vrt_filename, ds, options=options) if vrt_ds is None: raise Exception("Error! ca...
def make_temp_vrt(ds, extent: GeoRectangle):
options = gdal.BuildVRTOptions(outputBounds=(extent.min_x, extent.min_y, extent.max_x, extent.max_y)) vrt_filename = tempfile.mktemp(suffix='.vrt') vrt_ds = gdal.BuildVRT(vrt_filename, ds, options=options) if vrt_ds is None: raise Exception("Error! cannot create vrt. Cannot proceed") return ...
gt = (out_extent.left, gt[1], gt[2], out_extent.up, gt[4], gt[5]) return gt, (math.ceil(pix_extent.w), math.ceil(pix_extent.h)), out_extent def make_temp_vrt(ds, extent: GeoRectangle):
64
64
99
12
51
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
make_temp_vrt
make_temp_vrt
117
123
117
117
2a757f92e7202738d231c692527064c762b44a76
bigcode/the-stack
train
60e335d080bd54029b01ea53
train
function
def calc_geotransform_and_dimensions(geotransforms: Sequence[GeoTransform], dimensions, input_extent: Union[GeoRectangle, Extent] = None): # extents differ, but pixel size and rotation are the same. # we'll make a union or an intersection if geotransforms is None or len(geotransforms) != len(dimensions): ...
def calc_geotransform_and_dimensions(geotransforms: Sequence[GeoTransform], dimensions, input_extent: Union[GeoRectangle, Extent] = None): # extents differ, but pixel size and rotation are the same. # we'll make a union or an intersection
if geotransforms is None or len(geotransforms) != len(dimensions): raise Exception('Error! GeoTransforms and Dimensions have different lengths!') if isinstance(input_extent, GeoRectangle): gt = geotransforms[0] out_extent = input_extent.align(gt) elif isinstance(input_extent, Extent...
for reason in same.keys(): if not same[reason] and not diff_support[reason]: return reason # incompatible gt, returns the reason return GT.COMPATIBLE_DIFF def calc_geotransform_and_dimensions(geotransforms: Sequence[GeoTransform], dimensions, input_extent: Union[GeoRectangle, Extent] = None): ...
98
98
327
58
39
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
calc_geotransform_and_dimensions
calc_geotransform_and_dimensions
86
114
86
88
f181d0c31fd6a7e3a14148e3638e0f73a3c4b664
bigcode/the-stack
train
97642c9c99e4632831665b3f
train
class
class GT(Enum): SAME = -1 ALMOST_SAME = -2 COMPATIBLE_DIFF = -3 INCOMPATIBLE_OFFSET = 0 INCOMPATIBLE_PIXEL_SIZE = 1 INCOMPATIBLE_ROTATION = 2 NON_ZERO_ROTATION = 3
class GT(Enum):
SAME = -1 ALMOST_SAME = -2 COMPATIBLE_DIFF = -3 INCOMPATIBLE_OFFSET = 0 INCOMPATIBLE_PIXEL_SIZE = 1 INCOMPATIBLE_ROTATION = 2 NON_ZERO_ROTATION = 3
def parse_extent(extent: Union[str, Extent]) -> Extent: if isinstance(extent, str): return Extent[extent.upper()] elif isinstance(extent, Extent): return extent raise Exception('Error: Unknown extent %s' % extent) class GT(Enum):
64
64
69
4
60
jpapadakis/gdal
gdal/swig/python/osgeo/utils/auxiliary/extent_util.py
Python
GT
GT
55
62
55
55
710a2de758f3f04893d5a47e6add90a1a6a9a780
bigcode/the-stack
train
88d58055dafd2ce819724641
train
class
class Api: """ """ client = None def __init__(self, client): self.client = client def find(self, params): """Search profiles Parameters: :param params: """ return self.client.get("/profiles/v2/search/providers", params)
class Api:
""" """ client = None def __init__(self, client): self.client = client def find(self, params): """Search profiles Parameters: :param params: """ return self.client.get("/profiles/v2/search/providers", params)
the License. # # Author:: Maksym Novozhylov (mnovozhilov@upwork.com) # Copyright:: Copyright 2020(c) Upwork.com # License:: See LICENSE.txt and TOS - https://developers.upwork.com/api-tos.html class Api:
64
64
63
3
60
upwork/python-upwork
upwork/routers/freelancers/search.py
Python
Api
Api
15
31
15
15
c2eea638b88392fbeb50b45d2c7ea5a2f359723a
bigcode/the-stack
train
8037bc89573fff00d350b36c
train
class
class JoinPromotionTests(TestCase): def test_ticket_21150(self): b = Bravo.objects.create() c = Charlie.objects.create(bravo=b) qs = Charlie.objects.select_related('alfa').annotate(Count('bravo__charlie')) self.assertQuerysetEqual( qs, [c], lambda x: x) self.asser...
class JoinPromotionTests(TestCase):
def test_ticket_21150(self): b = Bravo.objects.create() c = Charlie.objects.create(bravo=b) qs = Charlie.objects.select_related('alfa').annotate(Count('bravo__charlie')) self.assertQuerysetEqual( qs, [c], lambda x: x) self.assertIs(qs[0].alfa, None) a = Al...
24 Hours'], lambda b: b.name) def test_annotate_reserved_word(self): """ Regression #18333 - Ensure annotated column name is properly quoted. """ vals = Book.objects.annotate(select=Count('authors__id')).aggregate(Sum('select'), Avg('select')) self.assertEqual(va...
105
105
353
7
98
benjaoming/django
tests/aggregation_regress/tests.py
Python
JoinPromotionTests
JoinPromotionTests
1,139
1,170
1,139
1,139
9dd2860876be39aec1149035f3b050d31de626e2
bigcode/the-stack
train
fe2560ef6049e00f194ae825
train
class
class AggregationOnRelationTest(TestCase): def setUp(self): self.a = Author.objects.create(name='Anssi', age=33) self.p = Publisher.objects.create(name='Manning', num_awards=3) Book.objects.create(isbn='asdf', name='Foo', pages=10, rating=0.1, price="0.0", contact...
class AggregationOnRelationTest(TestCase):
def setUp(self): self.a = Author.objects.create(name='Anssi', age=33) self.p = Publisher.objects.create(name='Manning', num_awards=3) Book.objects.create(isbn='asdf', name='Foo', pages=10, rating=0.1, price="0.0", contact=self.a, publisher=self.p, pubdate=datetime...
# But, as the join is nullable first use by annotate will be LOUTER qs = Charlie.objects.annotate(Count('alfa__name')) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_non_nullable_fk_not_promoted(self): qs = Book.objects.annotate(Count('contact__name')) self.asser...
96
96
320
9
87
benjaoming/django
tests/aggregation_regress/tests.py
Python
AggregationOnRelationTest
AggregationOnRelationTest
1,173
1,197
1,173
1,173
0fad53b702069279ca02b7fc289be738c506be7c
bigcode/the-stack
train
002250aa6a7e09085e120eb0
train
class
class AggregationTests(TestCase): fixtures = ["aggregation_regress.json"] def assertObjectAttrs(self, obj, **kwargs): for attr, value in six.iteritems(kwargs): self.assertEqual(getattr(obj, attr), value) def test_aggregates_in_where_clause(self): """ Regression test for...
class AggregationTests(TestCase):
fixtures = ["aggregation_regress.json"] def assertObjectAttrs(self, obj, **kwargs): for attr, value in six.iteritems(kwargs): self.assertEqual(getattr(obj, attr), value) def test_aggregates_in_where_clause(self): """ Regression test for #12822: DatabaseError: aggregates...
from __future__ import unicode_literals import datetime import pickle from decimal import Decimal from operator import attrgetter from django.core.exceptions import FieldError from django.contrib.contenttypes.models import ContentType from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F, Q from djan...
133
256
10,566
7
126
benjaoming/django
tests/aggregation_regress/tests.py
Python
AggregationTests
AggregationTests
19
1,136
19
19
d696bcb3f3963b881b114c64dec3817890b441db
bigcode/the-stack
train
21be6b2e257128c0ed0d8c90
train
function
def test_config_from_dict_raises_error_if_dataset_ambiguous(): with pytest.raises(ValueError): VitessceConfig.from_dict({ "version": "1.0.7", "name": "Test name", "description": "Test description", "datasets": [ { 'uid': 'A'...
def test_config_from_dict_raises_error_if_dataset_ambiguous():
with pytest.raises(ValueError): VitessceConfig.from_dict({ "version": "1.0.7", "name": "Test name", "description": "Test description", "datasets": [ { 'uid': 'A', 'name': 'My First Dataset', ...
"spatial", "props": { "cellRadius": 50 }, "coordinationScopes": { "spatialZoom": 'ABC' }, "x": 5, "y": 0, "w": 4, "h": 4 }, ], ...
93
93
310
14
79
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_from_dict_raises_error_if_dataset_ambiguous
test_config_from_dict_raises_error_if_dataset_ambiguous
606
660
606
606
be0e4e19f930914429d1c4145f745a774096b810
bigcode/the-stack
train
ed2b94c870d2edde19beb81a
train
function
def test_config_add_dataset_add_files(): vc = VitessceConfig() vc.add_dataset(name='My Chained Dataset').add_file( url="http://example.com/cells.json", data_type=dt.CELLS, file_type=ft.CELLS_JSON, ).add_file( url="http://example.com/cell_sets.json", data_type=dt.CELL_...
def test_config_add_dataset_add_files():
vc = VitessceConfig() vc.add_dataset(name='My Chained Dataset').add_file( url="http://example.com/cells.json", data_type=dt.CELLS, file_type=ft.CELLS_JSON, ).add_file( url="http://example.com/cell_sets.json", data_type=dt.CELL_SETS, file_type=ft.CELL_SETS_JSON...
"", "description": "", "datasets": [ { 'uid': 'A', 'name': 'My Dataset', 'files': [] } ], 'coordinationSpace': { 'dataset': { 'A': 'A' }, }, "layout": [], ...
83
83
279
8
75
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_dataset_add_files
test_config_add_dataset_add_files
63
106
63
63
ceecfe63550a93b69fa3b821e74c61d6256a3266
bigcode/the-stack
train
787d9237f3bfc31bc841cb87
train
function
def test_config_add_dataset(): vc = VitessceConfig() vc.add_dataset(name='My Dataset') vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ { 'uid': 'A', 'name': 'My Datas...
def test_config_add_dataset():
vc = VitessceConfig() vc.add_dataset(name='My Dataset') vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ { 'uid': 'A', 'name': 'My Dataset', 'files': [...
vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [], "coordinationSpace": {}, "layout": [], "initStrategy": "auto" } def test_config_add_dataset():
64
64
127
6
58
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_dataset
test_config_add_dataset
36
60
36
36
e5d7bac074936d04853ca1a547290ae2bfb8a831
bigcode/the-stack
train
2fced2b36dae982e294c590c
train
function
def test_config_creation(): vc = VitessceConfig() vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [], "coordinationSpace": {}, "layout": [], "initStrategy": "auto" }
def test_config_creation():
vc = VitessceConfig() vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [], "coordinationSpace": {}, "layout": [], "initStrategy": "auto" }
Type as ft, hconcat, vconcat, AbstractWrapper, make_repr, # Neither of these is in the source code, but they do appear in code which is eval'd. VitessceChainableConfig, VitessceConfigDatasetFile, ) def test_config_creation():
64
64
75
5
59
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_creation
test_config_creation
21
33
21
21
e86031c1db35d817b244b4d531a9c1c2ea9b5776
bigcode/the-stack
train
60067ad13ad43a08a8947bd9
train
function
def test_config_to_python_with_data_objects(): vc = VitessceConfig() class MockWrapperA(AbstractWrapper): def __init__(self, name, **kwargs): super().__init__(**kwargs) self._repr = make_repr(locals()) self.name = name def convert_and_save(self, dataset_uid,...
def test_config_to_python_with_data_objects():
vc = VitessceConfig() class MockWrapperA(AbstractWrapper): def __init__(self, name, **kwargs): super().__init__(**kwargs) self._repr = make_repr(locals()) self.name = name def convert_and_save(self, dataset_uid, obj_i): def get_molecules(base_url...
'B', 'name': 'My Second Dataset', 'files': [ { 'url': 'http://cells-2.json', 'type': 'cells', 'fileType': 'cells.json' } ] ...
193
193
646
9
184
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_to_python_with_data_objects
test_config_to_python_with_data_objects
663
732
663
663
0c4338a8f7fcdb8d1819ff8ac545057017c7c825
bigcode/the-stack
train
b36fa0cbf75df8e6abd6e3f4
train
function
def test_config_add_scatterplot_view_with_embedding_coordinations(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') my_view = vc.add_view(cm.SCATTERPLOT, dataset=my_dataset) et_scope, ez_scope, ex_scope, ey_scope = vc.add_coordination( ct.EMBEDDING_TYPE, ct.EMBEDDING_ZOOM...
def test_config_add_scatterplot_view_with_embedding_coordinations():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') my_view = vc.add_view(cm.SCATTERPLOT, dataset=my_dataset) et_scope, ez_scope, ex_scope, ey_scope = vc.add_coordination( ct.EMBEDDING_TYPE, ct.EMBEDDING_ZOOM, ct.EMBEDDING_TARGET_X, ct.EMBEDDING_TARGET_Y) my_view.use_coord...
{ 'A': 'A' }, 'embeddingType': { 'A': 'X_umap' } }, "layout": [ { 'component': 'scatterplot', 'coordinationScopes': { 'dataset': 'A', 'embeddingType': ...
124
124
414
14
110
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_scatterplot_view_with_embedding_coordinations
test_config_add_scatterplot_view_with_embedding_coordinations
194
256
194
194
5e38d2aff02ec8df4272ff989a472bcd7c430e37
bigcode/the-stack
train
5d06255321878fa889bbee41
train
function
def test_config_set_layout_multi_view_magic(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') v1 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v2 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v3 = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(v1 | (v2 / v3)) v...
def test_config_set_layout_multi_view_magic():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') v1 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v2 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v3 = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(v1 | (v2 / v3)) vc_dict = vc.to_dict() assert vc_dict == { ...
}, 'x': 6, 'y': 0, 'h': 6, 'w': 6, }, { 'component': 'spatial', 'coordinationScopes': { 'dataset': 'A', }, 'x': 6, '...
109
109
364
9
100
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_set_layout_multi_view_magic
test_config_set_layout_multi_view_magic
445
505
445
445
0de14fc0d6fd5d3bddb2cd77876d28db0b632883
bigcode/the-stack
train
26d97569179b68e4fb193556
train
function
def test_config_add_dataset_add_objects(): vc = VitessceConfig() class MockWrapperA(AbstractWrapper): def __init__(self, name, **kwargs): super().__init__(**kwargs) self.name = name def convert_and_save(self, dataset_uid, obj_i): def get_molecules(base_url):...
def test_config_add_dataset_add_objects():
vc = VitessceConfig() class MockWrapperA(AbstractWrapper): def __init__(self, name, **kwargs): super().__init__(**kwargs) self.name = name def convert_and_save(self, dataset_uid, obj_i): def get_molecules(base_url): return { ...
{ 'A': 2 }, 'embeddingTargetX': { 'A': 10 }, 'embeddingTargetY': { 'A': 11 }, }, "layout": [ { 'component': 'scatterplot', 'coordinationScopes': { ...
159
159
531
8
151
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_dataset_add_objects
test_config_add_dataset_add_objects
259
339
259
259
5a5bc37d19977a3c5e98a602753229b9e44a8364
bigcode/the-stack
train
be4b679f6fd15c28c438721a
train
function
def test_config_from_dict(): vc = VitessceConfig.from_dict({ "version": "1.0.7", "name": "Test name", "description": "Test description", "datasets": [ { 'uid': 'A', 'name': 'My First Dataset', 'files': [ ...
def test_config_from_dict():
vc = VitessceConfig.from_dict({ "version": "1.0.7", "name": "Test name", "description": "Test description", "datasets": [ { 'uid': 'A', 'name': 'My First Dataset', 'files': [ { 'ur...
'y': 0, 'h': 12, 'w': 6, }, { 'component': 'spatial', 'coordinationScopes': { 'dataset': 'A', }, 'x': 6, 'y': 0, 'h': 6, ...
153
153
512
6
147
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_from_dict
test_config_from_dict
508
603
508
508
912533eea1e1348183122b5fa994775ada825e61
bigcode/the-stack
train
e2848759f42f3e72d22887e1
train
function
def test_config_add_scatterplot_view_with_mapping(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') vc.add_view( cm.SCATTERPLOT, dataset=my_dataset, mapping="X_umap") vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "...
def test_config_add_scatterplot_view_with_mapping():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') vc.add_view( cm.SCATTERPLOT, dataset=my_dataset, mapping="X_umap") vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ {...
spatial', 'coordinationScopes': { 'dataset': 'A', }, 'h': 1, 'w': 1, 'x': 0, 'y': 0 } ], "initStrategy": "auto" } def test_config_add_scatterplot_view_with_mapping():
72
72
241
11
61
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_scatterplot_view_with_mapping
test_config_add_scatterplot_view_with_mapping
149
191
149
149
7a29c68ada067aa52adb7a9f41ddcb3e62c000f1
bigcode/the-stack
train
c94f8415d5bff2329308bb11
train
function
def test_config_set_layout_multi_view(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') v1 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v2 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v3 = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(hconcat(v1, vconcat(v2, v3))...
def test_config_set_layout_multi_view():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') v1 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v2 = vc.add_view(cm.SPATIAL, dataset=my_dataset) v3 = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(hconcat(v1, vconcat(v2, v3))) vc_dict = vc.to_dict() assert...
[] } ], 'coordinationSpace': { 'dataset': { 'A': 'A' }, }, "layout": [ { 'component': 'spatial', 'coordinationScopes': { 'dataset': 'A', }, ...
109
109
366
8
101
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_set_layout_multi_view
test_config_set_layout_multi_view
382
442
382
382
2e4160b735e5ecc20ff2d6721786b1870556c917
bigcode/the-stack
train
2538700fce7a7418235563c1
train
function
def test_config_set_layout_single_view(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') my_view = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(my_view) vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "descriptio...
def test_config_set_layout_single_view():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') my_view = vc.add_view(cm.SPATIAL, dataset=my_dataset) vc.layout(my_view) vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ ...
"fileType": "cell-sets.json" } ] }, ], 'coordinationSpace': { 'dataset': { 'A': 'A' }, }, "layout": [], "initStrategy": "auto" } def test_config_set_layout_single_view():
64
64
212
8
56
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_set_layout_single_view
test_config_set_layout_single_view
342
379
342
342
f7e64461c9c3e37368aeaf1bbae75e77ad4c9301
bigcode/the-stack
train
f582095c35ecb267112a61aa
train
function
def test_config_add_spatial_view(): vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') vc.add_view(cm.SPATIAL, dataset=my_dataset) vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ ...
def test_config_add_spatial_view():
vc = VitessceConfig() my_dataset = vc.add_dataset(name='My Dataset') vc.add_view(cm.SPATIAL, dataset=my_dataset) vc_dict = vc.to_dict() assert vc_dict == { "version": "1.0.7", "name": "", "description": "", "datasets": [ { 'uid': 'A', ...
'fileType': 'cell-sets.json' } ] }, ], 'coordinationSpace': { 'dataset': { 'A': 'A' }, }, "layout": [], "initStrategy": "auto" } def test_config_add_spatial_view():
64
64
203
8
56
vitessce/vitessce-jupyter
tests/test_config.py
Python
test_config_add_spatial_view
test_config_add_spatial_view
109
146
109
109
8005b5ca9ad3b941a56f341b20319152f76df294
bigcode/the-stack
train
b7d60a9c0ca022a1619e1461
train
class
class ExtendDatasetSharedMemory(BaseClientDatasetDecorator): # Since this class creates deterministic datasets (as in global data will always be before client data, # need to ensure that we shuffle the data during fitting (see BaseClient) def __init__(self, client_dataset: ClientDataset, ...
class ExtendDatasetSharedMemory(BaseClientDatasetDecorator): # Since this class creates deterministic datasets (as in global data will always be before client data, # need to ensure that we shuffle the data during fitting (see BaseClient)
def __init__(self, client_dataset: ClientDataset, subset_size: Tuple[int, int, int], shared_dataset: Dataset ): super().__init__(client_dataset) self.subset_size = subset_size self.shared_dataset = shared_dataset se...
from typing import Tuple import numpy as np from sources.utils.dataset import Dataset from sources.datasets.client_dataset_definitions.client_dataset_decorators.base_client_dataset_decorator import \ BaseClientDatasetDecorator from sources.datasets.client_dataset_definitions.client_dataset import ClientDataset cl...
102
240
802
47
54
M4rukku/impact_of_non_iid_data_in_federated_learning
sources/datasets/client_dataset_definitions/client_dataset_decorators/extend_dataset_shared_memory.py
Python
ExtendDatasetSharedMemory
ExtendDatasetSharedMemory
11
121
11
14
2860cb209515f55886584eba4888319f42c92703
bigcode/the-stack
train
7b6833a88f4df233a254bbf4
train
class
class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('password', 'first_name', 'last_name', 'email',) write_only_fields = ('password',) read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',) def restore_object(self, attrs, i...
class UserSerializer(serializers.ModelSerializer):
class Meta: model = User fields = ('password', 'first_name', 'last_name', 'email',) write_only_fields = ('password',) read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',) def restore_object(self, attrs, instance=None): # call set_password on user ...
User class SMSQueueSerializer(serializers.ModelSerializer): """ Serializing all the data in the SMSQueue """ class Meta: model = SMSQueue # fields = ('message', 'recepient', 'recepient_no', 'msg_status') class UserSerializer(serializers.ModelSerializer):
64
64
128
7
57
badili/livhealth_scripts
api/serializers.py
Python
UserSerializer
UserSerializer
15
27
15
15
9fec6b06f19a25f25b8abf1f4c4d21e7d7617be1
bigcode/the-stack
train
d5508b91f8ab53ccb8d79d47
train
class
class SMSQueueSerializer(serializers.ModelSerializer): """ Serializing all the data in the SMSQueue """ class Meta: model = SMSQueue
class SMSQueueSerializer(serializers.ModelSerializer):
""" Serializing all the data in the SMSQueue """ class Meta: model = SMSQueue
from rest_framework import serializers from models import SMSQueue from django.contrib.auth.models import User class SMSQueueSerializer(serializers.ModelSerializer):
28
64
33
8
19
badili/livhealth_scripts
api/serializers.py
Python
SMSQueueSerializer
SMSQueueSerializer
6
11
6
6
dae7eaef5f7dac6d4f627e463e01f3090ffbb795
bigcode/the-stack
train
3c658f4afa8672c96abffe94
train
function
def walk_budget(budget, categoryId: str): """ Walk all budget months If an amount is budgeted, add to running total Play all the transactions in that categoryId for that month If at the end the balance is negative: If overspendingHandling is 'Affectsbuffer, reset balance to 0...
def walk_budget(budget, categoryId: str):
""" Walk all budget months If an amount is budgeted, add to running total Play all the transactions in that categoryId for that month If at the end the balance is negative: If overspendingHandling is 'Affectsbuffer, reset balance to 0 If overspendingHandling is "Con...
from jsobject import Object from utils import find from transactions import transactions_by_month from transactions import play_transactions_category, transaction_touches_category def walk_budget(budget, categoryId: str):
41
129
430
11
29
gmarceau/pynab
envelopes.py
Python
walk_budget
walk_budget
6
58
6
6
70d243982ed8e776e7397544baa794cf7d155b21
bigcode/the-stack
train
882017a65a2c7d6fa39ae46e
train
function
@Andencento.on(andencento_cmd(pattern="link(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="link(?: |$)(.*)", allow_sudo=True)) async def permalink(mention): if mention.fwd_from: return """ For .link command, generates a link to the user's PM with a custom text. """ user, custom = awai...
@Andencento.on(andencento_cmd(pattern="link(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="link(?: |$)(.*)", allow_sudo=True)) async def permalink(mention):
if mention.fwd_from: return """ For .link command, generates a link to the user's PM with a custom text. """ user, custom = await get_user_from_event(mention) if not user: return if custom: await edit_or_reply( mention, f"[{custom}](tg://user?id={user.id}) \n\n\n ...
Read `{hl}plinfo create` to know how to use me") @Andencento.on(andencento_cmd(pattern="link(?: |$)(.*)", outgoing=True)) @Andencento.on(sudo_cmd(pattern="link(?: |$)(.*)", allow_sudo=True)) async def permalink(mention):
64
64
210
49
15
TeamIndianUserBot/Andencento
plugins/create.py
Python
permalink
permalink
70
89
70
72
e6e58bbf60c0e9e56f700b3622b9efb01a29d001
bigcode/the-stack
train
f351597cfae8bc143e9f99f0
train
function
async def get_user_from_id(user, event): if isinstance(user, str): user = int(user) try: user_obj = await event.client.get_entity(user) except (TypeError, ValueError) as err: await event.edit(str(err)) return None return user_obj
async def get_user_from_id(user, event):
if isinstance(user, str): user = int(user) try: user_obj = await event.client.get_entity(user) except (TypeError, ValueError) as err: await event.edit(str(err)) return None return user_obj
.get_entity(user_id) return user_obj try: user_obj = await event.client.get_entity(user) except (TypeError, ValueError) as err: await event.edit(str(err)) return None return user_obj, extra async def get_user_from_id(user, event):
64
64
65
10
53
TeamIndianUserBot/Andencento
plugins/create.py
Python
get_user_from_id
get_user_from_id
128
138
128
128
aada32ea10ca7869f8fd9efc78d447d56611dba1
bigcode/the-stack
train
250b664052fb6d634a2343da
train
function
@Andencento.on(andencento_cmd(pattern="create (b|g|c) (.*)")) # pylint:disable=E0602 @Andencento.on(sudo_cmd(pattern="create (b|g|c) (.*)", allow_sudo=True)) async def _(event): if event.fwd_from: return type_of_group = event.pattern_match.group(1) group_name = event.pattern_match.group(2) even...
@Andencento.on(andencento_cmd(pattern="create (b|g|c) (.*)")) # pylint:disable=E0602 @Andencento.on(sudo_cmd(pattern="create (b|g|c) (.*)", allow_sudo=True)) async def _(event):
if event.fwd_from: return type_of_group = event.pattern_match.group(1) group_name = event.pattern_match.group(2) event = await edit_or_reply(event, "Creating wait sar.....") if type_of_group == "b": try: result = await event.client( functions.messages.Crea...
from telethon.tl import functions from telethon.tl.types import MessageEntityMentionName from . import * @Andencento.on(andencento_cmd(pattern="create (b|g|c) (.*)")) # pylint:disable=E0602 @Andencento.on(sudo_cmd(pattern="create (b|g|c) (.*)", allow_sudo=True)) async def _(event):
87
152
509
63
24
TeamIndianUserBot/Andencento
plugins/create.py
Python
_
_
7
67
7
9
97c9253ea42ce80fbbb4a28aedec4510c449dec7
bigcode/the-stack
train
e33ab97e2297661d41b1e893
train
function
async def get_user_from_event(event): """Get the user from argument or replied message.""" args = event.pattern_match.group(1).split(":", 1) extra = None if event.reply_to_msg_id and not len(args) == 2: previous_message = await event.get_reply_message() user_obj = await event.client.get_...
async def get_user_from_event(event):
"""Get the user from argument or replied message.""" args = event.pattern_match.group(1).split(":", 1) extra = None if event.reply_to_msg_id and not len(args) == 2: previous_message = await event.get_reply_message() user_obj = await event.client.get_entity(previous_message.sender_id) ...
☝️" ) else: tag = ( user.first_name.replace("\u2060", "") if user.first_name else user.username ) await edit_or_reply( mention, f"[{tag}](tg://user?id={user.id}) \n\n ☝️ Tap to See ☝️" ) async def get_user_from_event(event):
80
80
268
8
72
TeamIndianUserBot/Andencento
plugins/create.py
Python
get_user_from_event
get_user_from_event
92
125
92
92
2b56d292d260ef1b7deb7ce395cbbfc6459beacd
bigcode/the-stack
train
db97933bd9d1c0da94d3e13a
train
class
class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(',') print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])]*len(self.array) sum_value = [int(self...
class SubArray:
def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(',') print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])]*len(self.array) sum_value = [int(self.array[0])]*len(s...
Yvonne This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem. The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. ''' from __future__ import print_function class SubArray:
64
64
147
4
59
joeyzhou85/python
dynamic_programming/longest_sub_array.py
Python
SubArray
SubArray
12
25
12
13
a078cd2ecceb52d3d39f598bcae50515a63ad371
bigcode/the-stack
train
cc5fa630349caa627827b31f
train
class
@ddt.ddt class ShareMigrationHelperTestCase(test.TestCase): """Tests ShareMigrationHelper.""" def setUp(self): super(ShareMigrationHelperTestCase, self).setUp() self.share = db_utils.create_share() self.share_instance = db_utils.create_share_instance( share_id=self.share['id...
@ddt.ddt class ShareMigrationHelperTestCase(test.TestCase):
"""Tests ShareMigrationHelper.""" def setUp(self): super(ShareMigrationHelperTestCase, self).setUp() self.share = db_utils.create_share() self.share_instance = db_utils.create_share_instance( share_id=self.share['id'], share_network_id='fake_network_id') ...
# Copyright 2015 Hitachi Data Systems inc. # 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...
236
256
2,406
16
219
deiter/manila
manila/tests/share/test_migration.py
Python
ShareMigrationHelperTestCase
ShareMigrationHelperTestCase
32
378
32
33
b904620a3191953121c17303e0c7e748794d5544
bigcode/the-stack
train
ddf7cfc7ec093a63cda1df2a
train
class
class CertificateResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribut...
class CertificateResponse(object):
""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute ...
# coding: utf-8 """ Pure Storage FlashBlade REST 1.X Python SDK Pure Storage FlashBlade REST 1.2 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/). OpenAPI spec version: 1.2 Contact: i...
136
221
739
5
130
bsamz-ps/purity_fb_python_client
purity_fb/purity_fb_1dot2/models/certificate_response.py
Python
CertificateResponse
CertificateResponse
19
153
19
19
aa4c14f3f86a8fab0aed9b20ec4fca168987dbe4
bigcode/the-stack
train
71c19b91f23eab6ab4ab580e
train
function
def gauss(sigma): phi = np.random.uniform(0,2*np.pi) gamma = -np.log(np.random.random()) r = sigma * np.sqrt(2*gamma) x = r*np.cos(phi) y = r*np.sin(phi) return x, y
def gauss(sigma):
phi = np.random.uniform(0,2*np.pi) gamma = -np.log(np.random.random()) r = sigma * np.sqrt(2*gamma) x = r*np.cos(phi) y = r*np.sin(phi) return x, y
range(1000): equiseses.append(reject_continuous(my_fun, 0, 1)) #%% _ = plt.hist(equiseses, density=True, bins=50) plt.xlim(0,1) #%% #1.18 def gauss(sigma):
64
64
63
6
57
juanitopereza/Tarea_7
MCMC_pi.py
Python
gauss
gauss
95
101
95
95
40c3888946eafb98a27460018fa790f57ceb5a44
bigcode/the-stack
train
5256951d1f6b8c3fc48b8e08
train
function
def direct_pi(N): hits = 0 for i in range(N): x = np.random.uniform(-1,1) y = np.random.uniform(-1,1) if(x**2 + y**2 < 1.0): hits +=1 return hits
def direct_pi(N):
hits = 0 for i in range(N): x = np.random.uniform(-1,1) y = np.random.uniform(-1,1) if(x**2 + y**2 < 1.0): hits +=1 return hits
import numpy as np import matplotlib.pyplot as plt #%% #1.1 def direct_pi(N):
23
64
64
5
17
juanitopereza/Tarea_7
MCMC_pi.py
Python
direct_pi
direct_pi
7
14
7
7
3888c92fa98127528de0c63fffc57b2a311a4d59
bigcode/the-stack
train
75ddef31106c90b298b59d1f
train
function
def reject_continuous(pf, xmin, xmax): acepta = True while acepta: x = np.random.uniform(xmin, xmax) gamma = np.random.uniform(0, 0.95) if (gamma > pf(x)): acepta = True else: acepta = False return x
def reject_continuous(pf, xmin, xmax):
acepta = True while acepta: x = np.random.uniform(xmin, xmax) gamma = np.random.uniform(0, 0.95) if (gamma > pf(x)): acepta = True else: acepta = False return x
= 0 for i in range(1000): esta = markov_two_site(esta, 0.8, 0.2) if esta: cuenta += 1 cuenta #%% #1.16 def reject_continuous(pf, xmin, xmax):
64
64
71
12
51
juanitopereza/Tarea_7
MCMC_pi.py
Python
reject_continuous
reject_continuous
68
77
68
68
cb1e04492cbb0354650df3efec4a85e9f614cf74
bigcode/the-stack
train
8365aa52609913cca227c951
train
function
def my_fun(x, mu=0.7, sigma=0.05): return 1.0/np.sqrt(2*np.pi*sigma**2) * np.exp(-(x-mu)**2/(2*sigma**2))
def my_fun(x, mu=0.7, sigma=0.05):
return 1.0/np.sqrt(2*np.pi*sigma**2) * np.exp(-(x-mu)**2/(2*sigma**2))
(xmin, xmax) gamma = np.random.uniform(0, 0.95) if (gamma > pf(x)): acepta = True else: acepta = False return x #%% def my_fun(x, mu=0.7, sigma=0.05):
63
64
51
17
46
juanitopereza/Tarea_7
MCMC_pi.py
Python
my_fun
my_fun
80
81
80
80
6fc1da7e0c19080b7ce457717887e46a9582e05b
bigcode/the-stack
train
3a2585f07d94c75b54dfd874
train
function
def markov_two_site(k, p0, p1): if(k == 0): l = 1 gamma = min(1,p1/p0) elif(k == 1): l = 0 gamma = min(1,p0/p1) rand = np.random.random() if(rand < gamma): k = l return k
def markov_two_site(k, p0, p1):
if(k == 0): l = 1 gamma = min(1,p1/p0) elif(k == 1): l = 0 gamma = min(1,p0/p1) rand = np.random.random() if(rand < gamma): k = l return k
< 1.0: hits +=1 return hits #%% pi_markov = markov_pi(4000, 0.3)*4/4000 pi_markov #%% #1.8 def markov_two_site(k, p0, p1):
64
64
82
13
50
juanitopereza/Tarea_7
MCMC_pi.py
Python
markov_two_site
markov_two_site
45
54
45
45
7bfb8eee1b50b13c1dad4fe0ca1f883541411dc5
bigcode/the-stack
train
6c8f17feb2bebfdbdd492a31
train
function
def markov_pi(N, delta): hits = 0 x = 1.0 y = 1.0 for i in range(N): dx = np.random.uniform(-delta, delta) dy = np.random.uniform(-delta, delta) if (abs(x + dx) < 1.0 and abs(y + dy) < 1.0): x += dx y += dy if (x**2 + y**2) < 1.0: hits ...
def markov_pi(N, delta):
hits = 0 x = 1.0 y = 1.0 for i in range(N): dx = np.random.uniform(-delta, delta) dy = np.random.uniform(-delta, delta) if (abs(x + dx) < 1.0 and abs(y + dy) < 1.0): x += dx y += dy if (x**2 + y**2) < 1.0: hits +=1 return hits
(-1,1) if(x**2 + y**2 < 1.0): hits +=1 return hits #%% pi_child = direct_pi(10000)*4/10000 pi_child #1.2 #%% def markov_pi(N, delta):
63
64
120
8
55
juanitopereza/Tarea_7
MCMC_pi.py
Python
markov_pi
markov_pi
23
35
23
23
a675e38a82e3e56937b8582cb343506f9f38c2a6
bigcode/the-stack
train
b2104656446de5ae3987dba5
train
function
def main(directory, images): ''' must make hallways with different lighting (backlit, frontlit) must have stuff on walls (papers, billboards, etc) ''' IMAGE_CLASS = CIM.GeneratedImage # ten pixels per inch IMG_GENR = DAG.ImageGenerator(IMAGE_CLASS, plaqueSize=75, resolution=10, randSeed=42) ...
def main(directory, images):
''' must make hallways with different lighting (backlit, frontlit) must have stuff on walls (papers, billboards, etc) ''' IMAGE_CLASS = CIM.GeneratedImage # ten pixels per inch IMG_GENR = DAG.ImageGenerator(IMAGE_CLASS, plaqueSize=75, resolution=10, randSeed=42) for n in range(images): ...
\ComputerScience\Thesis\RoomFinder\source\ImageGeneration\HALLWAYS\ -i 10 """ import DataGenerator as DAG import CustomImage as CIM import cv2 import numpy as np import os import random from argparse import ArgumentParser def main(directory, images):
64
64
173
6
57
Jacktavitt/navigate_building
source/ImageGeneration/hall_driver.py
Python
main
main
18
31
18
18
847b57025c36250b848cde54a9d29a72e60defd2
bigcode/the-stack
train
88edac48f06d432973176de1
train
class
class TrainingDataset(object): def __init__(self, source, img_size=(224, 224, 3), img_type='rgb', min_count=0, map_others=False, test_split=0.2, random_seed=0, memmap_directory=Non...
class TrainingDataset(object):
def __init__(self, source, img_size=(224, 224, 3), img_type='rgb', min_count=0, map_others=False, test_split=0.2, random_seed=0, memmap_directory=None): if len(img_size) !=...
from typing import NamedTuple from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical import numpy as np from scipy.stats.mstats import gmean from miso.data.filenames_dataset import FilenamesDataset from miso.data.image_dataset import ImageDataset from miso.data.tf_gener...
75
220
735
5
69
Thubaralei/particle-classification
miso/data/training_dataset.py
Python
TrainingDataset
TrainingDataset
13
94
13
13
cd94340556f41adf5a529f527e7f483d79620ace
bigcode/the-stack
train
e61e667edbcc2b2e54b86b01
train
function
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): """ Generates and returns a random string of given size. :size: Size of the desired random string. Default is 10 :type size: int :param chars: Characters from which random string is to be generated. Default ...
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
""" Generates and returns a random string of given size. :size: Size of the desired random string. Default is 10 :type size: int :param chars: Characters from which random string is to be generated. Default value is `abcdefghijklmnopqrstuvwxyz0123456789` :type chars: str :returns: A...
"""Utility functions for announcements model.""" import string import random from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
41
64
119
20
20
dojutsu-user/Health-Center-Portal
src/announcements/utils.py
Python
random_string_generator
random_string_generator
9
22
9
9
9e5b0a26ffdd1dcfa101b66d60f924eceb45751c
bigcode/the-stack
train
4cc6940b4c248b9c03c1cf59
train
function
def unique_slug_generator(instance, new_slug=None): """ Generates and returns a unique slug for the instance. It assumes that the `instance` have a `title` and `slug` field. The maximum length of the returned slug is 50. :instance: Instance for which the unique slug is needed :type instance: an...
def unique_slug_generator(instance, new_slug=None):
""" Generates and returns a unique slug for the instance. It assumes that the `instance` have a `title` and `slug` field. The maximum length of the returned slug is 50. :instance: Instance for which the unique slug is needed :type instance: announcements.models.Announcement :new_slug: Slug ...
from which random string is to be generated. Default value is `abcdefghijklmnopqrstuvwxyz0123456789` :type chars: str :returns: A random string. :rtype: str """ return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None):
67
67
225
10
57
dojutsu-user/Health-Center-Portal
src/announcements/utils.py
Python
unique_slug_generator
unique_slug_generator
25
52
25
25
72e5f36bcbb1db13d761e00476ef56b093724b47
bigcode/the-stack
train
d259672343249ade8a80fe74
train
class
class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where...
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from...
'fields': 'scope'} token_info_uri = _helpers.update_query_params( self.token_info_uri, query_params) resp, content = transport.request(http, token_info_uri) content = _helpers._from_bytes(content) if resp.status == http_client.OK: d = json.loads(content) ...
157
157
526
9
148
craigcitro/oauth2client
oauth2client/client.py
Python
AccessTokenCredentials
AccessTokenCredentials
905
980
905
905
0ec885e9afe35b26e62f1cba9f1ee2de3fa603f3
bigcode/the-stack
train
c6ebc52f73102d3777005e92
train
function
def _parse_expiry(expiry): if expiry and isinstance(expiry, datetime.datetime): return expiry.strftime(EXPIRY_FORMAT) else: return None
def _parse_expiry(expiry):
if expiry and isinstance(expiry, datetime.datetime): return expiry.strftime(EXPIRY_FORMAT) else: return None
): """Error retrieving the Application Default Credentials.""" class OAuth2DeviceCodeError(Error): """Error trying to retrieve a device code.""" class CryptoUnavailableError(Error, NotImplementedError): """Raised when a crypto library is required, but none is available.""" def _parse_expiry(expiry):
63
64
36
8
55
craigcitro/oauth2client
oauth2client/client.py
Python
_parse_expiry
_parse_expiry
183
187
183
183
9648268982dcde972d03b784202f5bfff46f080d
bigcode/the-stack
train
f5804262d2a4b1c64aff00db
train
function
def _raise_exception_for_missing_fields(missing_fields): raise ApplicationDefaultCredentialsError( 'The following field(s) must be defined: ' + ', '.join(missing_fields))
def _raise_exception_for_missing_fields(missing_fields):
raise ApplicationDefaultCredentialsError( 'The following field(s) must be defined: ' + ', '.join(missing_fields))
OGLE_TOKEN_URI, user_agent='Python client library') else: # client_credentials['type'] == SERVICE_ACCOUNT from oauth2client import service_account return service_account._JWTAccessCredentials.from_json_keyfile_dict( client_credentials) def _raise_exception_for_missing_fields...
64
64
38
11
53
craigcitro/oauth2client
oauth2client/client.py
Python
_raise_exception_for_missing_fields
_raise_exception_for_missing_fields
1,419
1,421
1,419
1,419
949e57d60515b42d7fa0000a890ce450dc6a49a4
bigcode/the-stack
train
161ff75e0339ec39d6bc2ac9
train
class
class VerifyJwtTokenError(Error): """Could not retrieve certificates for validation."""
class VerifyJwtTokenError(Error):
"""Could not retrieve certificates for validation."""
Error trying to revoke a token.""" class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow.""" class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" class VerifyJwtTokenError(Error):
63
64
16
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
VerifyJwtTokenError
VerifyJwtTokenError
163
164
163
163
1fbf4c5c4fa1e1138f00ec0d0fd489535801b185
bigcode/the-stack
train
5fa55cdc8a04c9e08dbd2ca2
train
class
class ApplicationDefaultCredentialsError(Error): """Error retrieving the Application Default Credentials."""
class ApplicationDefaultCredentialsError(Error):
"""Error retrieving the Application Default Credentials."""
class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" class VerifyJwtTokenError(Error): """Could not retrieve certificates for validation.""" class NonAsciiHeaderError(Error): """Header names and values must be ASCII strings.""" class ApplicationDefau...
63
64
16
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
ApplicationDefaultCredentialsError
ApplicationDefaultCredentialsError
171
172
171
171
96d29818d43d47e09af1ca5009178cad51f339b8
bigcode/the-stack
train
c57f081333098af72073618b
train
class
class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible."""
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
__(*args) self.status = kwargs.get('status') class TokenRevokeError(Error): """Error trying to revoke a token.""" class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow.""" class AccessTokenCredentialsError(Error):
63
64
20
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
AccessTokenCredentialsError
AccessTokenCredentialsError
159
160
159
159
7f309f7f26c7a6d21b6d78b1f74986cab98fa4d2
bigcode/the-stack
train
117031c856dd2b6a2e720da2
train
function
def _get_application_default_credential_GCE(): from oauth2client.contrib.gce import AppAssertionCredentials return AppAssertionCredentials()
def _get_application_default_credential_GCE():
from oauth2client.contrib.gce import AppAssertionCredentials return AppAssertionCredentials()
An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error)) def _get_application_default_credential_GAE(): from oauth2client.contrib.appengine import AppAssertionCredentials return AppAssertionCredentials([]) def _get_application_default_credential_GCE():
63
64
29
10
54
craigcitro/oauth2client
oauth2client/client.py
Python
_get_application_default_credential_GCE
_get_application_default_credential_GCE
1,438
1,441
1,438
1,438
41ba4bb6eda4ed44a9406e2816c117caafd0ca1b
bigcode/the-stack
train
9b9f1de443ea7919e2ff28cd
train
function
@_helpers.positional(3) def credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, ...
@_helpers.positional(3) def credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, ...
"""Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope:...
FlowExchangeError if the authorization code cannot be exchanged for an access token """ flow = OAuth2WebServerFlow(client_id, client_secret, scope, redirect_uri=redirect_uri, user_agent=user_agent, auth_...
163
163
546
46
116
craigcitro/oauth2client
oauth2client/client.py
Python
credentials_from_clientsecrets_and_code
credentials_from_clientsecrets_and_code
1,683
1,737
1,683
1,689
99ef77bbd7b29152f40112652b39540d31d4f712
bigcode/the-stack
train
09791517eaf626d810cab7df
train
function
def _parse_exchange_token_response(content): """Parses response of an exchange token request. Most providers return JSON but some (e.g. Facebook) return a url-encoded string. Args: content: The body of a response Returns: Content as a dictionary object. Note that the dict could be...
def _parse_exchange_token_response(content):
"""Parses response of an exchange token request. Most providers return JSON but some (e.g. Facebook) return a url-encoded string. Args: content: The body of a response Returns: Content as a dictionary object. Note that the dict could be empty, i.e. {}. That basically indic...
len(segments) != 3: raise VerifyJwtTokenError( 'Wrong number of segments in token: {0}'.format(id_token)) return json.loads( _helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1]))) def _parse_exchange_token_response(content):
63
64
185
8
55
craigcitro/oauth2client
oauth2client/client.py
Python
_parse_exchange_token_response
_parse_exchange_token_response
1,588
1,614
1,588
1,588
da6e1dea0bdbad2ed1c206a50be1cc0013fe9c1e
bigcode/the-stack
train
813c98b055a284b7ab7d65ed
train
class
class NonAsciiHeaderError(Error): """Header names and values must be ASCII strings."""
class NonAsciiHeaderError(Error):
"""Header names and values must be ASCII strings."""
"""The client secrets file called for an unknown type of OAuth 2.0 flow.""" class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" class VerifyJwtTokenError(Error): """Could not retrieve certificates for validation.""" class NonAsciiHeaderError(Error):
63
64
18
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
NonAsciiHeaderError
NonAsciiHeaderError
167
168
167
167
288662a0ee13ba412ad42c8ef671b1aff318fce0
bigcode/the-stack
train
7ae8a75fa1b763cd608fd1a3
train
function
def _oauth2_web_server_flow_params(kwargs): """Configures redirect URI parameters for OAuth2WebServerFlow.""" params = { 'access_type': 'offline', 'response_type': 'code', } params.update(kwargs) # Check for the presence of the deprecated approval_prompt param and # warn approp...
def _oauth2_web_server_flow_params(kwargs):
"""Configures redirect URI parameters for OAuth2WebServerFlow.""" params = { 'access_type': 'offline', 'response_type': 'code', } params.update(kwargs) # Check for the presence of the deprecated approval_prompt param and # warn appropriately. approval_prompt = params.get('a...
'), 'user_code_expiry': None, }) if 'expires_in' in response: kwargs['user_code_expiry'] = ( _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))) return cls(**kwargs) def _oauth2_web_server_flow_params(kwargs):
64
64
170
10
54
craigcitro/oauth2client
oauth2client/client.py
Python
_oauth2_web_server_flow_params
_oauth2_web_server_flow_params
1,778
1,802
1,778
1,778
89231b3f11838fb71fb43d9ed69921f1c662e6b9
bigcode/the-stack
train
e90e83a18923323cfd800b7f
train
function
def _in_gae_environment(): """Detects if the code is running in the App Engine environment. Returns: True if running in the GAE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL') try: import google...
def _in_gae_environment():
"""Detects if the code is running in the App Engine environment. Returns: True if running in the GAE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL') try: import google.appengine # noqa: unused ...
response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR) except socket.error: # socket.timeout or socket.error(64, 'Host is down') logger.info('Timeout attempting to reach GCE metadata service.') return False def _in_gae_environment():
64
64
161
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
_in_gae_environment
_in_gae_environment
1,008
1,030
1,008
1,008
5ac7b0dafed5f9ba870d6990e9586bbb63db9015
bigcode/the-stack
train
358129821de11add3cb561c9
train
function
def _require_crypto_or_die(): """Ensure we have a crypto library, or throw CryptoUnavailableError. The oauth2client.crypt module requires either PyCrypto or PyOpenSSL to be available in order to function, but these are optional dependencies. """ if not HAS_CRYPTO: raise CryptoUnavailabl...
def _require_crypto_or_die():
"""Ensure we have a crypto library, or throw CryptoUnavailableError. The oauth2client.crypt module requires either PyCrypto or PyOpenSSL to be available in order to function, but these are optional dependencies. """ if not HAS_CRYPTO: raise CryptoUnavailableError('No crypto library avai...
blob (of bytes). Args: blob: bytes, Message to be signed. Returns: tuple, A pair of the private key ID used to sign the blob and the signed contents. """ raise NotImplementedError('This method is abstract.') def _require_crypto_or_die():
63
64
76
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
_require_crypto_or_die
_require_crypto_or_die
1,518
1,526
1,518
1,518
52cdfff64a76c4cbb2738af7c0ccb5f4b1ee31ca
bigcode/the-stack
train
235afc731d95fdddc05b217d
train
class
class HttpAccessTokenRefreshError(AccessTokenRefreshError): """Error (with HTTP status) trying to refresh an expired access token.""" def __init__(self, *args, **kwargs): super(HttpAccessTokenRefreshError, self).__init__(*args) self.status = kwargs.get('status')
class HttpAccessTokenRefreshError(AccessTokenRefreshError):
"""Error (with HTTP status) trying to refresh an expired access token.""" def __init__(self, *args, **kwargs): super(HttpAccessTokenRefreshError, self).__init__(*args) self.status = kwargs.get('status')
Error(Exception): """Base error for this module.""" class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" class HttpAccessTokenRefreshError(AccessTokenRefres...
63
64
64
12
51
craigcitro/oauth2client
oauth2client/client.py
Python
HttpAccessTokenRefreshError
HttpAccessTokenRefreshError
144
148
144
144
17665238f968d60e0058772fc1e328ae99e34ff5
bigcode/the-stack
train
90ea27b5a815c034a2d5d9c8
train
function
def _get_well_known_file(): """Get the well known file produced by command 'gcloud auth login'.""" # TODO(orestica): Revisit this method once gcloud provides a better way # of pinpointing the exact location of the file. default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR) if default_config_dir i...
def _get_well_known_file():
"""Get the well known file produced by command 'gcloud auth login'.""" # TODO(orestica): Revisit this method once gcloud provides a better way # of pinpointing the exact location of the file. default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR) if default_config_dir is None: if os.name =...
credential_filename): return application_default_credential_filename else: raise ApplicationDefaultCredentialsError( 'File ' + application_default_credential_filename + ' (pointed by ' + GOOGLE_APPLICATION_CREDENTIALS + ' en...
64
65
218
8
57
craigcitro/oauth2client
oauth2client/client.py
Python
_get_well_known_file
_get_well_known_file
1,358
1,379
1,358
1,358
9baf9d083337922b8b3ad690e3ea01369df11e47
bigcode/the-stack
train
b1f50dd4a45b9550cede2d79
train
class
class TokenRevokeError(Error): """Error trying to revoke a token."""
class TokenRevokeError(Error):
"""Error trying to revoke a token."""
AccessTokenRefreshError): """Error (with HTTP status) trying to refresh an expired access token.""" def __init__(self, *args, **kwargs): super(HttpAccessTokenRefreshError, self).__init__(*args) self.status = kwargs.get('status') class TokenRevokeError(Error):
64
64
16
7
57
craigcitro/oauth2client
oauth2client/client.py
Python
TokenRevokeError
TokenRevokeError
151
152
151
151
541e6957a9461dbbbfe9059c6c5326e2c5628187
bigcode/the-stack
train