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
1a0032e98283dfd099bd6b5e
train
class
@total_ordering class _SemVerAPIFormat(object): """Basic semver x.y.z API format. Supports x, or x.y, or x.y.z """ def __init__(self, api_version_str): try: parts = api_version_str.split('.') parts += [0, 0] # At worst never read, at best minor/patch self.ma...
@total_ordering class _SemVerAPIFormat(object):
"""Basic semver x.y.z API format. Supports x, or x.y, or x.y.z """ def __init__(self, api_version_str): try: parts = api_version_str.split('.') parts += [0, 0] # At worst never read, at best minor/patch self.major = int(parts[0]) self.minor = int...
SDKProfile or string if isinstance(api_version, SDKProfile): api_version = _get_api_version_tuple(resource_type, api_version) return api_version except KeyError: raise APIVersionException(resource_type, api_profile) @total_ordering class _SemVerAPIFormat(object):
64
64
214
13
51
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
_SemVerAPIFormat
_SemVerAPIFormat
275
296
275
276
cdff799ab8019053fca90685aa2e8684bb56212b
bigcode/the-stack
train
8564df9ac1803b535e1d063e
train
function
def get_versioned_sdk_path(api_profile, resource_type, operation_group=None): """ Patch the unversioned sdk path to include the appropriate API version for the resource type in question. e.g. Converts azure.mgmt.storage.operations.storage_accounts_operations to azure.mgmt.stora...
def get_versioned_sdk_path(api_profile, resource_type, operation_group=None):
""" Patch the unversioned sdk path to include the appropriate API version for the resource type in question. e.g. Converts azure.mgmt.storage.operations.storage_accounts_operations to azure.mgmt.storage.v2016_12_01.operations.storage_accounts_operations az...
except (ImportError, AttributeError) as ex: if checked: return None raise ex def get_client_class(resource_type): return _get_attr(resource_type.import_prefix, '#' + resource_type.client_name) def get_versioned_sdk_path(api_profile, resource_type, operation_group=None):
64
64
179
16
48
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
get_versioned_sdk_path
get_versioned_sdk_path
431
445
431
431
e0d96d87e7e3e870d6c07d0cc42dcfca656fb171
bigcode/the-stack
train
1925ec2a01cddd323e906902
train
function
def _parse_api_version(api_version): """Will try to parse it as a date, and if not working as semver, and if still not working raise. """ try: return _DateAPIFormat(api_version) except ValueError: return _SemVerAPIFormat(api_version)
def _parse_api_version(api_version):
"""Will try to parse it as a date, and if not working as semver, and if still not working raise. """ try: return _DateAPIFormat(api_version) except ValueError: return _SemVerAPIFormat(api_version)
if self.mm < other.mm: return True if self.mm == other.mm: if self.dd < other.dd: return True if self.dd == other.dd: if self.preview and not other.preview: return True return False def _...
64
64
65
8
55
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
_parse_api_version
_parse_api_version
348
355
348
348
a023bdd1ab004f126987328f6835ba0d5579d8ac
bigcode/the-stack
train
809a4b9b7a15c6b05c7e305b
train
function
def supported_resource_type(api_profile, resource_type): if api_profile == 'latest' or resource_type is None: return True try: return bool(AZURE_API_PROFILES[api_profile][resource_type]) except KeyError: return False
def supported_resource_type(api_profile, resource_type):
if api_profile == 'latest' or resource_type is None: return True try: return bool(AZURE_API_PROFILES[api_profile][resource_type]) except KeyError: return False
ResourceType)) else api_profile if isinstance(api_version_obj, SDKProfile): api_version_obj = api_version_obj.profile.get(operation_group or '', api_version_obj.default_api_version) return _validate_api_version(api_version_obj, min_api, max_api) def supported_resource_type(api_profile, resource_type):
64
64
56
10
54
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
supported_resource_type
supported_resource_type
401
407
401
401
ee3b44297bc88e78cf0c329ff7fc292c37ea00bf
bigcode/the-stack
train
bc6f1ba0e8e454e445d02608
train
function
def supported_api_version(api_profile, resource_type, min_api=None, max_api=None, operation_group=None): """ Returns True if current API version for the resource type satisfies min/max range. To compare profile versions, set resource type to None. Can return a tuple<operation_group, bool> if the resourc...
def supported_api_version(api_profile, resource_type, min_api=None, max_api=None, operation_group=None):
""" Returns True if current API version for the resource type satisfies min/max range. To compare profile versions, set resource type to None. Can return a tuple<operation_group, bool> if the resource_type supports SDKProfile. note: Currently supports YYYY-MM-DD, YYYY-MM-DD-preview, YYYY-MM-DD-profi...
_api. """ if min_api and _cross_api_format_less_than(api_version_str, min_api): return False if max_api and _cross_api_format_less_than(max_api, api_version_str): return False return True def supported_api_version(api_profile, resource_type, min_api=None, max_api=None, operation_group=No...
74
74
249
22
51
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
supported_api_version
supported_api_version
382
398
382
382
13af5e3032957240d489c431cd463590e7125cb8
bigcode/the-stack
train
b22e98b0ad05c9bce02f83a7
train
function
def get_api_version(api_profile, resource_type, as_sdk_profile=False): """Get the API version of a resource type given an API profile. :param api_profile: The name of the API profile. :type api_profile: str. :param resource_type: The resource type. :type resource_type: ResourceType. :returns: ...
def get_api_version(api_profile, resource_type, as_sdk_profile=False):
"""Get the API version of a resource type given an API profile. :param api_profile: The name of the API profile. :type api_profile: str. :param resource_type: The resource type. :type resource_type: ResourceType. :returns: str -- the API version. :raises: APIVersionException """ tr...
: x): """Return a _ApiVersion instance where key are operation group and value are api version.""" return _ApiVersions(client_type=get_client_class(resource_type), sdk_profile=sdk_profile, post_process=post_process) def get_api_version(api_profile, resource_type, ...
64
64
176
15
49
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
get_api_version
get_api_version
254
272
254
254
5aa93a0ebdc0c93417645e5c019d7824112226fc
bigcode/the-stack
train
de2bdf7fecd3d0abbc08444a
train
class
class ResourceType(Enum): # pylint: disable=too-few-public-methods MGMT_APIMANAGEMENT = ('azure.mgmt.apimanagement', 'ApiManagementClient') MGMT_KUSTO = ('azure.mgmt.kusto', 'KustoManagementClient') MGMT_KEYVAULT = ('azure.mgmt.keyvault', 'KeyVaultManagementClient') MGMT_STORAGE = ('azure.mgmt.storage...
class ResourceType(Enum): # pylint: disable=too-few-public-methods
MGMT_APIMANAGEMENT = ('azure.mgmt.apimanagement', 'ApiManagementClient') MGMT_KUSTO = ('azure.mgmt.kusto', 'KustoManagementClient') MGMT_KEYVAULT = ('azure.mgmt.keyvault', 'KeyVaultManagementClient') MGMT_STORAGE = ('azure.mgmt.storage', 'StorageManagementClient') MGMT_COMPUTE = ('azure.mgmt.compute...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
232
256
1,103
18
213
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
ResourceType
ResourceType
33
104
33
34
463afd7dfb589adcdc336ff63293c9631d8f2e84
bigcode/the-stack
train
1f53a784d68604df2caf4e9e
train
function
def _get_attr(sdk_path, mod_attr_path, checked=True): try: attr_mod, attr_path = mod_attr_path.split('#') \ if '#' in mod_attr_path else (mod_attr_path, '') full_mod_path = '{}.{}'.format(sdk_path, attr_mod) if attr_mod else sdk_path op = import_module(full_mod_path) if a...
def _get_attr(sdk_path, mod_attr_path, checked=True):
try: attr_mod, attr_path = mod_attr_path.split('#') \ if '#' in mod_attr_path else (mod_attr_path, '') full_mod_path = '{}.{}'.format(sdk_path, attr_mod) if attr_mod else sdk_path op = import_module(full_mod_path) if attr_path: # Only load attributes if needed...
resource_type): if api_profile == 'latest' or resource_type is None: return True try: return bool(AZURE_API_PROFILES[api_profile][resource_type]) except KeyError: return False def _get_attr(sdk_path, mod_attr_path, checked=True):
64
64
136
15
48
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
_get_attr
_get_attr
410
424
410
410
3f8edb63e0f163331bf6d3e0ac78379f5fd25d70
bigcode/the-stack
train
9d5146076773e3385e5d43ea
train
class
class APIVersionException(Exception): def __init__(self, type_name, api_profile): super(APIVersionException, self).__init__(type_name, api_profile) self.type_name = type_name self.api_profile = api_profile def __str__(self): return "Unable to get API version for type '{}' in pro...
class APIVersionException(Exception):
def __init__(self, type_name, api_profile): super(APIVersionException, self).__init__(type_name, api_profile) self.type_name = type_name self.api_profile = api_profile def __str__(self): return "Unable to get API version for type '{}' in profile '{}'".format( self.ty...
rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # TODO Move this to a package shared by CLI and SDK from enum import Enum from functools import total_ordering ...
64
64
86
7
56
mdewan/azure-cli
src/azure-cli-core/azure/cli/core/profiles/_shared.py
Python
APIVersionException
APIVersionException
12
20
12
12
f1d5908be526a4b19f743643a863d939d95aeefb
bigcode/the-stack
train
fa8f8d207f61cd4e00f7e8d4
train
class
@factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, "user")
@factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory):
class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, "user")
", profile=None) name = factory.Faker("name") description = factory.Faker("text") public_credit_name = factory.Faker("name") public_credit_name_approved = True @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory):
64
64
44
22
41
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
UserFactory
UserFactory
153
158
153
154
199f996be2075a2278534cb639d4218ca01b29e7
bigcode/the-stack
train
e8d0151933cc8ee775face97
train
class
class SpeakerProposalUrlFactory(factory.django.DjangoModelFactory): class Meta: model = Url url = factory.Faker("url") url_type = factory.Iterator(UrlType.objects.all())
class SpeakerProposalUrlFactory(factory.django.DjangoModelFactory):
class Meta: model = Url url = factory.Faker("url") url_type = factory.Iterator(UrlType.objects.all())
= factory.Iterator([True, False]) class EventProposalUrlFactory(factory.django.DjangoModelFactory): class Meta: model = Url url = factory.Faker("url") url_type = factory.Iterator(UrlType.objects.all()) class SpeakerProposalUrlFactory(factory.django.DjangoModelFactory):
64
64
43
13
51
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
SpeakerProposalUrlFactory
SpeakerProposalUrlFactory
223
228
223
223
d01509372c3e43f56974207551f034ba0e3eb797
bigcode/the-stack
train
3aaf1ea22f030d5d61657864
train
class
class RevenueFactory(factory.django.DjangoModelFactory): class Meta: model = Revenue camp = factory.Faker("random_element", elements=Camp.objects.all()) debtor = factory.Faker("random_element", elements=Credebtor.objects.all()) user = factory.Faker("random_element", elements=User.objects.all())...
class RevenueFactory(factory.django.DjangoModelFactory):
class Meta: model = Revenue camp = factory.Faker("random_element", elements=Camp.objects.all()) debtor = factory.Faker("random_element", elements=Credebtor.objects.all()) user = factory.Faker("random_element", elements=User.objects.all()) amount = factory.Faker("random_int", min=20, max=200...
invoice_date = factory.Faker("date") responsible_team = factory.Faker("random_element", elements=Team.objects.all()) approved = factory.Faker("random_element", elements=[True, True, False]) notes = factory.Faker("text") class RevenueFactory(factory.django.DjangoModelFactory):
64
64
183
11
53
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
RevenueFactory
RevenueFactory
124
139
124
124
659767ee888b5b48f8056da3015084215cb7dc86
bigcode/the-stack
train
6ef33d680cafee13be5889f0
train
class
class SpeakerProposalFactory(factory.django.DjangoModelFactory): class Meta: model = SpeakerProposal name = factory.Faker("name") email = factory.Faker("email") biography = output_fake_md_description() submission_notes = factory.Iterator(["", output_fake_description()]) needs_oneday_tic...
class SpeakerProposalFactory(factory.django.DjangoModelFactory):
class Meta: model = SpeakerProposal name = factory.Faker("name") email = factory.Faker("email") biography = output_fake_md_description() submission_notes = factory.Iterator(["", output_fake_description()]) needs_oneday_ticket = factory.Iterator([True, False])
fake_text = "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "* [" + fake.sentence(nb_words=3) + "](" + fake.uri() + ")\n" return fake_text class SpeakerProposalFactory(factory.django.DjangoModelFactory):
64
64
73
12
51
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
SpeakerProposalFactory
SpeakerProposalFactory
192
200
192
192
a6f8382d2c0995ab0c5d2cbd29e3de192910718a
bigcode/the-stack
train
978d904261ccae99ec0aa5c4
train
class
class ChainFactory(factory.django.DjangoModelFactory): class Meta: model = Chain name = factory.Faker("company") slug = factory.LazyAttribute( lambda f: unique_slugify( f.name, Chain.objects.all().values_list("slug", flat=True) ) )
class ChainFactory(factory.django.DjangoModelFactory):
class Meta: model = Chain name = factory.Faker("company") slug = factory.LazyAttribute( lambda f: unique_slugify( f.name, Chain.objects.all().values_list("slug", flat=True) ) )
Find from utils.slugs import unique_slugify from villages.models import Village fake = Faker() # Faker.seed(0) tz = pytz.timezone("Europe/Copenhagen") logger = logging.getLogger("bornhack.%s" % __name__) class ChainFactory(factory.django.DjangoModelFactory):
64
64
65
11
53
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
ChainFactory
ChainFactory
78
87
78
78
e5273507cb096992355c39240bd243ca0d9bde55
bigcode/the-stack
train
d090e5602882bb0835b50392
train
function
def output_fake_description(): fake_text = "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "* [" + fake.sentence(nb_words=3) + "](" + fake.uri() + ")\n" return fake_text
def output_fake_description():
fake_text = "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "* [" + fake.sentence(nb_words=3) + "](" + fake.uri() + ")\n" return fake_text
fake_text += "* [" + fake.sentence(nb_words=3) + "](" + fake.uri() + ")\n" fake_text += "* [" + fake.sentence(nb_words=3) + "](" + fake.uri() + ")\n" return fake_text def output_fake_description():
64
64
58
5
58
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
output_fake_description
output_fake_description
186
189
186
186
9856b1e387dee5a1a7ebbdb470d173740a51faa4
bigcode/the-stack
train
c3e8a6b7f74b14b10e34c828
train
class
class EventProposalFactory(factory.django.DjangoModelFactory): class Meta: model = EventProposal user = factory.Iterator(User.objects.all()) title = factory.Faker("sentence") abstract = output_fake_md_description() allow_video_recording = factory.Iterator([True, True, True, False]) subm...
class EventProposalFactory(factory.django.DjangoModelFactory):
class Meta: model = EventProposal user = factory.Iterator(User.objects.all()) title = factory.Faker("sentence") abstract = output_fake_md_description() allow_video_recording = factory.Iterator([True, True, True, False]) submission_notes = factory.Iterator(["", output_fake_description()]...
name = factory.Faker("name") email = factory.Faker("email") biography = output_fake_md_description() submission_notes = factory.Iterator(["", output_fake_description()]) needs_oneday_ticket = factory.Iterator([True, False]) class EventProposalFactory(factory.django.DjangoModelFactory):
64
64
93
12
52
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
EventProposalFactory
EventProposalFactory
203
212
203
203
3484e57a02b8c88350d5aa1909986f40cdf6fb1a
bigcode/the-stack
train
8ead2ce8ea6317fc128c8850
train
class
class EventProposalUrlFactory(factory.django.DjangoModelFactory): class Meta: model = Url url = factory.Faker("url") url_type = factory.Iterator(UrlType.objects.all())
class EventProposalUrlFactory(factory.django.DjangoModelFactory):
class Meta: model = Url url = factory.Faker("url") url_type = factory.Iterator(UrlType.objects.all())
= output_fake_md_description() allow_video_recording = factory.Iterator([True, True, True, False]) submission_notes = factory.Iterator(["", output_fake_description()]) use_provided_speaker_laptop = factory.Iterator([True, False]) class EventProposalUrlFactory(factory.django.DjangoModelFactory):
64
64
43
13
51
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
EventProposalUrlFactory
EventProposalUrlFactory
215
220
215
215
ce24f6ac779cba0cb4023bd2f2b59179af96d06f
bigcode/the-stack
train
0988d02f10d4990b889430aa
train
class
class Command(BaseCommand): args = "none" help = "Create mock data for development instances" def create_camps(self): self.output("Creating camps...") camps = [ dict(year=2016, tagline="Initial Commit", colour="#004dff", read_only=True), dict(year=2017, tagline="Make...
class Command(BaseCommand):
args = "none" help = "Create mock data for development instances" def create_camps(self): self.output("Creating camps...") camps = [ dict(year=2016, tagline="Initial Commit", colour="#004dff", read_only=True), dict(year=2017, tagline="Make Tradition", colour="#750787...
SpeakerProposalFactory(factory.django.DjangoModelFactory): class Meta: model = SpeakerProposal name = factory.Faker("name") email = factory.Faker("email") biography = output_fake_md_description() submission_notes = factory.Iterator(["", output_fake_description()]) needs_oneday_ticket =...
256
256
13,867
5
251
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
Command
Command
231
1,962
231
231
c030804e9745e1d6140f38700cb820437b542f82
bigcode/the-stack
train
913995933c70dec07d2b5b50
train
class
class CredebtorFactory(factory.django.DjangoModelFactory): class Meta: model = Credebtor chain = factory.SubFactory(ChainFactory) name = factory.Faker("company") slug = factory.LazyAttribute( lambda f: unique_slugify( f.name, Credebtor.objects.all().values_list("slug", flat=...
class CredebtorFactory(factory.django.DjangoModelFactory):
class Meta: model = Credebtor chain = factory.SubFactory(ChainFactory) name = factory.Faker("company") slug = factory.LazyAttribute( lambda f: unique_slugify( f.name, Credebtor.objects.all().values_list("slug", flat=True) ) ) address = factory.Faker("address"...
: model = Chain name = factory.Faker("company") slug = factory.LazyAttribute( lambda f: unique_slugify( f.name, Chain.objects.all().values_list("slug", flat=True) ) ) class CredebtorFactory(factory.django.DjangoModelFactory):
64
64
105
13
51
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
CredebtorFactory
CredebtorFactory
90
102
90
90
f8d81fd97e713b1850f9f3babe55b40befe9ea09
bigcode/the-stack
train
972256a9545a02db3acea2fa
train
class
class EmailAddressFactory(factory.django.DjangoModelFactory): class Meta: model = EmailAddress primary = False verified = True
class EmailAddressFactory(factory.django.DjangoModelFactory):
class Meta: model = EmailAddress primary = False verified = True
public_credit_name_approved = True @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, "user") class EmailAddressFactory(factory.django.DjangoModelFactory):
64
64
32
12
52
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
EmailAddressFactory
EmailAddressFactory
161
166
161
161
0cff679960abefa4edd22803330b71923220794e
bigcode/the-stack
train
8da64fa2bc516211c2213585
train
class
class ExpenseFactory(factory.django.DjangoModelFactory): class Meta: model = Expense camp = factory.Faker("random_element", elements=Camp.objects.all()) creditor = factory.Faker("random_element", elements=Credebtor.objects.all()) user = factory.Faker("random_element", elements=User.objects.all(...
class ExpenseFactory(factory.django.DjangoModelFactory):
class Meta: model = Expense camp = factory.Faker("random_element", elements=Camp.objects.all()) creditor = factory.Faker("random_element", elements=Credebtor.objects.all()) user = factory.Faker("random_element", elements=User.objects.all()) amount = factory.Faker("random_int", min=20, max=2...
lambda f: unique_slugify( f.name, Credebtor.objects.all().values_list("slug", flat=True) ) ) address = factory.Faker("address", locale="dk_DK") notes = factory.Faker("text") class ExpenseFactory(factory.django.DjangoModelFactory):
64
64
205
11
53
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
ExpenseFactory
ExpenseFactory
105
121
105
105
aee2fc6e6212bab5f6ed0dda289ae7ce9a5cc936
bigcode/the-stack
train
b877c11526c22523eb36e169
train
function
def output_fake_md_description(): fake_text = "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "\n\n" fake_text += "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "\n\n" fake_text += "## " + fake.sentence(nb_words=3) + "\n" fake_text += "\n".join(fake.paragraph...
def output_fake_md_description():
fake_text = "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "\n\n" fake_text += "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) fake_text += "\n\n" fake_text += "## " + fake.sentence(nb_words=3) + "\n" fake_text += "\n".join(fake.paragraphs(nb=3, ext_word_list=None)) f...
Factory(factory.django.DjangoModelFactory): class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, "user") class EmailAddressFactory(factory.django.DjangoModelFactory): class Meta: model = EmailAddress primary = False verified = True def output_fake_md_descript...
69
69
233
6
62
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
output_fake_md_description
output_fake_md_description
169
183
169
169
18316dfc7d9474a268ccbb3fcb76ec970f25c3ab
bigcode/the-stack
train
a44611f02a27d11cc6a9d409
train
class
class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory("self.UserFactory", profile=None) name = factory.Faker("name") description = factory.Faker("text") public_credit_name = factory.Faker("name") public_credit_name_approved = True...
class ProfileFactory(factory.django.DjangoModelFactory):
class Meta: model = Profile user = factory.SubFactory("self.UserFactory", profile=None) name = factory.Faker("name") description = factory.Faker("text") public_credit_name = factory.Faker("name") public_credit_name_approved = True
invoice_date = factory.Faker("date") responsible_team = factory.Faker("random_element", elements=Team.objects.all()) approved = factory.Faker("random_element", elements=[True, True, False]) notes = factory.Faker("text") class ProfileFactory(factory.django.DjangoModelFactory):
64
64
72
11
53
bornhack/bornhack-website
src/utils/management/commands/bootstrap_devsite.py
Python
ProfileFactory
ProfileFactory
142
150
142
142
eae53a9ff6c338747e6e139f70589bfe9467fbbf
bigcode/the-stack
train
7797e732b6566ddaa329dfd2
train
class
class Docker(BaseRuntime): def __init__(self, image=None, dockerfile=None, mount=[], build_kwargs={}, run_kwargs={}): if bool(image) == bool(dockerfile): util.fail("Docker process must define exactly one of image or dockerfile") self.image = image self.dockerfile = dockerfile ...
class Docker(BaseRuntime):
def __init__(self, image=None, dockerfile=None, mount=[], build_kwargs={}, run_kwargs={}): if bool(image) == bool(dockerfile): util.fail("Docker process must define exactly one of image or dockerfile") self.image = image self.dockerfile = dockerfile self.mount = mount ...
) await self.proc.start() proc_info = await self.proc.show() self.proc_pid = proc_info["State"]["Pid"] life_cycle.set_state(self.name, life_cycle.State.STARTED) async def log_pipe(logger, pipe): async for line in pipe: logger(line) await asy...
256
256
992
5
251
ali-senguel/fairo
fbrp/src/fbrp/runtime/docker.py
Python
Docker
Docker
132
253
132
132
5d86b3cb8f0095d81e45112767e0b28b5f3100f8
bigcode/the-stack
train
dd1e693682972f342087594f
train
class
class Launcher(BaseLauncher): def __init__( self, image, mount: typing.List[str], name: str, proc_def: ProcDef, args: argparse.Namespace, **kwargs, ): self.image = image self.mount = mount self.name = name self.proc_def = pr...
class Launcher(BaseLauncher):
def __init__( self, image, mount: typing.List[str], name: str, proc_def: ProcDef, args: argparse.Namespace, **kwargs, ): self.image = image self.mount = mount self.name = name self.proc_def = proc_def self.args = arg...
from fbrp import life_cycle from fbrp import util from fbrp.runtime.base import BaseLauncher, BaseRuntime from fbrp.process import ProcDef import a0 import aiodocker import argparse import asyncio import contextlib import docker import io import json import os import pwd import sys import typing class Launcher(BaseLaun...
82
223
744
5
76
ali-senguel/fairo
fbrp/src/fbrp/runtime/docker.py
Python
Launcher
Launcher
19
129
19
19
edcd2458087fc0e4ad20b544e3441fd59adc52cf
bigcode/the-stack
train
cde049962fdd7bdc21edab73
train
class
class BlobIndexOutOfBoundsError(Exception): """Raised when reading a blob with index > total number of blobs."""
class BlobIndexOutOfBoundsError(Exception):
"""Raised when reading a blob with index > total number of blobs."""
.rdfvalues import crypto as rdf_crypto from grr_response_server import data_store from grr_response_server.databases import db from grr_response_server.rdfvalues import objects as rdf_objects class Error(Exception): """Base error class for signed_binary_utils.""" class BlobIndexOutOfBoundsError(Exception):
63
64
24
9
54
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
BlobIndexOutOfBoundsError
BlobIndexOutOfBoundsError
21
22
21
21
dc083b3eaf7c6a0376f4883a79cc3cd47cc66484
bigcode/the-stack
train
c9cf48910ef206d7892748df
train
function
def FetchBlobForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID, blob_index: int, ) -> rdf_crypto.SignedBlob: """Retrieves a single blob for the given binary from the datastore. Args: binary_id: An ID of the binary to be fetched. blob_index: Index of the blob to read. Returns: Signed...
def FetchBlobForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID, blob_index: int, ) -> rdf_crypto.SignedBlob:
"""Retrieves a single blob for the given binary from the datastore. Args: binary_id: An ID of the binary to be fetched. blob_index: Index of the blob to read. Returns: Signed blob. Raises: SignedBinaryNotFoundError: If no signed binary with the given URN exists. BlobIndexOutOfBoundsError:...
Blob(blob_id) for blob_id in blob_ids) blobs = ( rdf_crypto.SignedBlob.FromSerializedBytes(raw_blob) for raw_blob in raw_blobs) return blobs, timestamp def FetchBlobForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID, blob_index: int, ) -> rdf_crypto.SignedBlob:
76
76
256
34
41
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchBlobForSignedBinaryByID
FetchBlobForSignedBinaryByID
179
210
179
182
66a2b83c0c472fb8dd9be8526e31b308ad561aa5
bigcode/the-stack
train
f0c67628dda4a3524ee114ab
train
function
def StreamSignedBinaryContents(blob_iterator: Iterator[rdf_crypto.SignedBlob], chunk_size: int = 1024 ) -> Generator[bytes, None, None]: """Yields the contents of the given binary in chunks of the given size. Args: blob_iterator: An Iterator over all...
def StreamSignedBinaryContents(blob_iterator: Iterator[rdf_crypto.SignedBlob], chunk_size: int = 1024 ) -> Generator[bytes, None, None]:
"""Yields the contents of the given binary in chunks of the given size. Args: blob_iterator: An Iterator over all the binary's blobs. chunk_size: Size, in bytes, of the chunks to yield. """ all_blobs_read = False byte_buffer = io.BytesIO() while not all_blobs_read or byte_buffer.getvalue(): whi...
.UnknownSignedBinaryError: raise SignedBinaryNotFoundError(binary_id) last_reference = references.items[-1] return last_reference.offset + last_reference.size def StreamSignedBinaryContents(blob_iterator: Iterator[rdf_crypto.SignedBlob], chunk_size: int = 1024 ...
71
71
239
37
33
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
StreamSignedBinaryContents
StreamSignedBinaryContents
277
302
277
279
8d8c7eaebc14c4371756365363610fd6324d5ee3
bigcode/the-stack
train
37e608a04709e8602017479f
train
class
class Error(Exception): """Base error class for signed_binary_utils."""
class Error(Exception):
"""Base error class for signed_binary_utils."""
Tuple, Union from grr_response_core.lib import rdfvalue from grr_response_core.lib.rdfvalues import crypto as rdf_crypto from grr_response_server import data_store from grr_response_server.databases import db from grr_response_server.rdfvalues import objects as rdf_objects class Error(Exception):
64
64
14
4
59
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
Error
Error
17
18
17
17
1d49063c19743949eb112ea7aaf96680761abe96
bigcode/the-stack
train
2bc3bb8387776a2f6c54321e
train
function
def _SignedBinaryURNFromID(binary_id: rdf_objects.SignedBinaryID ) -> rdfvalue.RDFURN: """Converts a SignedBinaryID to the equivalent AFF4 URN.""" binary_type = binary_id.binary_type if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK: return GetAFF4PythonHackRoot().A...
def _SignedBinaryURNFromID(binary_id: rdf_objects.SignedBinaryID ) -> rdfvalue.RDFURN:
"""Converts a SignedBinaryID to the equivalent AFF4 URN.""" binary_type = binary_id.binary_type if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK: return GetAFF4PythonHackRoot().Add(binary_id.path) elif binary_type == rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE: return GetAFF4Exec...
=binary_urn.RelativeName(GetAFF4ExecutablesRoot())) else: raise ValueError("Unable to determine type of signed binary: %s." % binary_urn) def _SignedBinaryURNFromID(binary_id: rdf_objects.SignedBinaryID ) -> rdfvalue.RDFURN:
64
64
134
26
38
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
_SignedBinaryURNFromID
_SignedBinaryURNFromID
49
58
49
50
5a60dd45f77f0fd0205e42f3348bc35459be3295
bigcode/the-stack
train
6eebfec7ceb57cfa4634e88f
train
function
def FetchURNsForAllSignedBinaries() -> Sequence[rdfvalue.RDFURN]: """Returns URNs for all signed binaries in the datastore.""" return [ _SignedBinaryURNFromID(i) for i in data_store.REL_DB.ReadIDsForAllSignedBinaries() ]
def FetchURNsForAllSignedBinaries() -> Sequence[rdfvalue.RDFURN]:
"""Returns URNs for all signed binaries in the datastore.""" return [ _SignedBinaryURNFromID(i) for i in data_store.REL_DB.ReadIDsForAllSignedBinaries() ]
URN(binary_urn)) except db.UnknownSignedBinaryError: raise SignedBinaryNotFoundError(binary_urn) data_store.REL_DB.DeleteSignedBinaryReferences( SignedBinaryIDFromURN(binary_urn)) def FetchURNsForAllSignedBinaries() -> Sequence[rdfvalue.RDFURN]:
64
64
63
19
45
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchURNsForAllSignedBinaries
FetchURNsForAllSignedBinaries
142
147
142
142
43aed2dc7f72535dd253e02113fab321d3287baa
bigcode/the-stack
train
8db74218f63eb929fe5aedd0
train
function
def FetchBlobForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN, blob_index: int, ) -> rdf_crypto.SignedBlob: """Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. blob_index: Index of the blob to read. Returns: Signed blob. ...
def FetchBlobForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN, blob_index: int, ) -> rdf_crypto.SignedBlob:
"""Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. blob_index: Index of the blob to read. Returns: Signed blob. Raises: SignedBinaryNotFoundError: If no signed binary with the given URN exists. BlobIndexOutOfBoundsErro...
binary with the given URN exists. """ return FetchBlobsForSignedBinaryByID(SignedBinaryIDFromURN(binary_urn)) def FetchBlobForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN, blob_index: int, ) -> rdf_crypto.SignedBlob:
64
64
143
34
30
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchBlobForSignedBinaryByURN
FetchBlobForSignedBinaryByURN
232
250
232
235
b4f0e849be7b6384ecfbbd54397f7a97417f5aac
bigcode/the-stack
train
3b0b21995a2f7a1e24dd74df
train
function
def GetAFF4ExecutablesRoot(): return rdfvalue.RDFURN("aff4:/config/executables")
def GetAFF4ExecutablesRoot():
return rdfvalue.RDFURN("aff4:/config/executables")
class for signed_binary_utils.""" class BlobIndexOutOfBoundsError(Exception): """Raised when reading a blob with index > total number of blobs.""" def GetAFF4PythonHackRoot(): return rdfvalue.RDFURN("aff4:/config/python_hacks") def GetAFF4ExecutablesRoot():
64
64
24
8
56
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
GetAFF4ExecutablesRoot
GetAFF4ExecutablesRoot
29
30
29
29
303846f2825b992e1477b274543936e80c84b459
bigcode/the-stack
train
9a29d944cbd04b05f4be6af4
train
class
class SignedBinaryNotFoundError(Exception): """Exception raised when a signed binary is not found in the datastore.""" def __init__(self, binary_urn): super().__init__("Binary with urn %s was not found." % binary_urn)
class SignedBinaryNotFoundError(Exception):
"""Exception raised when a signed binary is not found in the datastore.""" def __init__(self, binary_urn): super().__init__("Binary with urn %s was not found." % binary_urn)
().Add(binary_id.path) elif binary_type == rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE: return GetAFF4ExecutablesRoot().Add(binary_id.path) else: raise ValueError("Unknown binary type %s." % binary_type) class SignedBinaryNotFoundError(Exception):
64
64
53
8
56
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
SignedBinaryNotFoundError
SignedBinaryNotFoundError
61
65
61
61
f123fca5e13e7f83b3b90d30878d3aac1727924b
bigcode/the-stack
train
c2260888438bd26d3a232c86
train
function
def FetchBlobsForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]: """Retrieves blobs for the given binary from the datastore. Args: binary_id: An ID of the binary to be fetched. Returns: A tuple containing an iterator for all ...
def FetchBlobsForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]:
"""Retrieves blobs for the given binary from the datastore. Args: binary_id: An ID of the binary to be fetched. Returns: A tuple containing an iterator for all the binary's blobs and an RDFDatetime representing when the binary's contents were saved to the datastore. Raises: SignedBinaryNo...
.""" return [ _SignedBinaryURNFromID(i) for i in data_store.REL_DB.ReadIDsForAllSignedBinaries() ] def FetchBlobsForSignedBinaryByID( binary_id: rdf_objects.SignedBinaryID ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]:
71
72
241
39
32
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchBlobsForSignedBinaryByID
FetchBlobsForSignedBinaryByID
150
176
150
152
5d6f653843dedc699e0be21e2fd16d3c640fbbcf
bigcode/the-stack
train
75b85f88468890236298788f
train
function
def GetAFF4PythonHackRoot(): return rdfvalue.RDFURN("aff4:/config/python_hacks")
def GetAFF4PythonHackRoot():
return rdfvalue.RDFURN("aff4:/config/python_hacks")
import db from grr_response_server.rdfvalues import objects as rdf_objects class Error(Exception): """Base error class for signed_binary_utils.""" class BlobIndexOutOfBoundsError(Exception): """Raised when reading a blob with index > total number of blobs.""" def GetAFF4PythonHackRoot():
63
64
24
8
55
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
GetAFF4PythonHackRoot
GetAFF4PythonHackRoot
25
26
25
25
752cbedb7454e5e6891e05d7379b69eb4f639c65
bigcode/the-stack
train
100f97ee49da315f3e441228
train
function
def DeleteSignedBinary(binary_urn: rdfvalue.RDFURN): """Deletes the binary with the given urn from the datastore. Args: binary_urn: RDFURN that serves as a unique identifier for the binary. Raises: SignedBinaryNotFoundError: If the signed binary does not exist. """ try: data_store.REL_DB.ReadSig...
def DeleteSignedBinary(binary_urn: rdfvalue.RDFURN):
"""Deletes the binary with the given urn from the datastore. Args: binary_urn: RDFURN that serves as a unique identifier for the binary. Raises: SignedBinaryNotFoundError: If the signed binary does not exist. """ try: data_store.REL_DB.ReadSignedBinaryReferences( SignedBinaryIDFromURN(bi...
( offset=current_offset, size=len(blob.data), blob_id=blob_id)) current_offset += len(blob.data) data_store.REL_DB.WriteSignedBinaryReferences( SignedBinaryIDFromURN(binary_urn), blob_references) def DeleteSignedBinary(binary_urn: rdfvalue.RDFURN):
64
64
131
14
50
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
DeleteSignedBinary
DeleteSignedBinary
124
139
124
124
664ee20ced6396cfb718f7a40a93fb52f6e5affb
bigcode/the-stack
train
e0f4ba306448fe867351678d
train
function
def WriteSignedBinaryBlobs(binary_urn: rdfvalue.RDFURN, blobs: Iterable[rdf_crypto.SignedBlob]): """Saves signed blobs to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: RDFURN that should serve as a uniqu...
def WriteSignedBinaryBlobs(binary_urn: rdfvalue.RDFURN, blobs: Iterable[rdf_crypto.SignedBlob]):
"""Saves signed blobs to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: RDFURN that should serve as a unique identifier for the binary. blobs: An Iterable of signed blobs to write to the datastore. """ blob_references = rdf...
_offset, size=len(chunk), blob_id=blob_id)) data_store.REL_DB.WriteSignedBinaryReferences( SignedBinaryIDFromURN(binary_urn), blob_references) def WriteSignedBinaryBlobs(binary_urn: rdfvalue.RDFURN, blobs: Iterable[rdf_crypto.SignedBlob]):
64
64
201
27
37
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
WriteSignedBinaryBlobs
WriteSignedBinaryBlobs
101
121
101
102
9a638408002656d6f8332905b6297d6a1d72b997
bigcode/the-stack
train
df7942991c94d7018d463fa6
train
function
def FetchSizeOfSignedBinary( binary_id_or_urn: Union[rdf_objects.SignedBinaryID, rdfvalue.RDFURN]) -> int: """Returns the size of the given binary (in bytes). Args: binary_id_or_urn: SignedBinaryID or RDFURN that uniquely identifies the binary. Raises: SignedBinar...
def FetchSizeOfSignedBinary( binary_id_or_urn: Union[rdf_objects.SignedBinaryID, rdfvalue.RDFURN]) -> int:
"""Returns the size of the given binary (in bytes). Args: binary_id_or_urn: SignedBinaryID or RDFURN that uniquely identifies the binary. Raises: SignedBinaryNotFoundError: If no signed binary with the given URN exists. """ if isinstance(binary_id_or_urn, rdfvalue.RDFURN): binary_id = Si...
blob index is too big. """ return FetchBlobForSignedBinaryByID( SignedBinaryIDFromURN(binary_urn), blob_index) def FetchSizeOfSignedBinary( binary_id_or_urn: Union[rdf_objects.SignedBinaryID, rdfvalue.RDFURN]) -> int:
64
64
193
33
31
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchSizeOfSignedBinary
FetchSizeOfSignedBinary
253
274
253
255
3cc1cd81189d75cc751933be47f1cf36311ee023
bigcode/the-stack
train
8a370b3a7bccec8ca66a7bc8
train
function
def FetchBlobsForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]: """Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. Returns: A tuple containing an iterator for all...
def FetchBlobsForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]:
"""Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. Returns: A tuple containing an iterator for all the binary's blobs and an RDFDatetime representing when the binary's contents were saved to the datastore. Raises: Sign...
_blob = data_store.BLOBS.ReadBlob(blob_id) return rdf_crypto.SignedBlob.FromSerializedBytes(raw_blob) def FetchBlobsForSignedBinaryByURN( binary_urn: rdfvalue.RDFURN ) -> Tuple[Iterator[rdf_crypto.SignedBlob], rdfvalue.RDFDatetime]:
64
64
146
39
25
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
FetchBlobsForSignedBinaryByURN
FetchBlobsForSignedBinaryByURN
213
229
213
215
6de515652f5884997ba4dab51e55bf75250cd977
bigcode/the-stack
train
aaee3cbbd8835e609df1d264
train
function
def SignedBinaryIDFromURN( binary_urn: rdfvalue.RDFURN) -> rdf_objects.SignedBinaryID: """Converts an AFF4 URN for a signed binary to a SignedBinaryID.""" if binary_urn.RelativeName(GetAFF4PythonHackRoot()): return rdf_objects.SignedBinaryID( binary_type=rdf_objects.SignedBinaryID.BinaryType.PYTHON_...
def SignedBinaryIDFromURN( binary_urn: rdfvalue.RDFURN) -> rdf_objects.SignedBinaryID:
"""Converts an AFF4 URN for a signed binary to a SignedBinaryID.""" if binary_urn.RelativeName(GetAFF4PythonHackRoot()): return rdf_objects.SignedBinaryID( binary_type=rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK, path=binary_urn.RelativeName(GetAFF4PythonHackRoot())) elif binary_urn.Rela...
rdfvalue.RDFURN("aff4:/config/python_hacks") def GetAFF4ExecutablesRoot(): return rdfvalue.RDFURN("aff4:/config/executables") def SignedBinaryIDFromURN( binary_urn: rdfvalue.RDFURN) -> rdf_objects.SignedBinaryID:
64
64
181
26
38
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
SignedBinaryIDFromURN
SignedBinaryIDFromURN
33
46
33
34
abd2c933af8819fc37c3f64103f864c7d53d8396
bigcode/the-stack
train
c744be7b49639264c3e036c3
train
function
def WriteSignedBinary(binary_urn: rdfvalue.RDFURN, binary_content: bytes, private_key: rdf_crypto.RSAPrivateKey, public_key: Optional[rdf_crypto.RSAPublicKey], chunk_size: int = 1024): """Signs a binary and saves it to the datasto...
def WriteSignedBinary(binary_urn: rdfvalue.RDFURN, binary_content: bytes, private_key: rdf_crypto.RSAPrivateKey, public_key: Optional[rdf_crypto.RSAPublicKey], chunk_size: int = 1024):
"""Signs a binary and saves it to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: URN that should serve as a unique identifier for the binary. binary_content: Contents of the binary, as raw bytes. private_key: Key that shoul...
"""Exception raised when a signed binary is not found in the datastore.""" def __init__(self, binary_urn): super().__init__("Binary with urn %s was not found." % binary_urn) def WriteSignedBinary(binary_urn: rdfvalue.RDFURN, binary_content: bytes, private_key: rdf_cr...
100
100
336
55
45
khanhgithead/grr
grr/server/grr_response_server/signed_binary_utils.py
Python
WriteSignedBinary
WriteSignedBinary
68
98
68
72
5cef73ad7bc809a6b0e8eb9837ef601b5bfe3467
bigcode/the-stack
train
daf248805a78ccd8f62d1f3d
train
function
@click.command() @click.argument('font_dir', type=click.Path(exists=True, file_okay=False)) def make_fonts(font_dir): print(font_dir)
@click.command() @click.argument('font_dir', type=click.Path(exists=True, file_okay=False)) def make_fonts(font_dir):
print(font_dir)
import click @click.command() @click.argument('font_dir', type=click.Path(exists=True, file_okay=False)) def make_fonts(font_dir):
31
64
33
28
2
vladimirgamalyan/hoi4_better_fonts
main.py
Python
make_fonts
make_fonts
4
7
4
6
a5b8e93f381dae12c6f08335e195fb23744b84e8
bigcode/the-stack
train
0a720cb51c046e5ec7a06798
train
function
def filter_list_clouds(auth_context, query_filter=None, sort=None, perm='read', as_dict=True): """Returns a list of clouds, which is filtered based on RBAC Mappings for non-Owners. """ clouds = list_clouds(auth_context.owner, query_filter=query_filter, sor...
def filter_list_clouds(auth_context, query_filter=None, sort=None, perm='read', as_dict=True):
"""Returns a list of clouds, which is filtered based on RBAC Mappings for non-Owners. """ clouds = list_clouds(auth_context.owner, query_filter=query_filter, sort=sort, as_dict=as_dict) if not auth_context.is_owner(): clouds = [cloud for cloud in clouds if cloud['id'...
c_count = Cloud.objects(owner=owner, deleted=None).count() if owner.clouds_count != c_count: owner.clouds_count = c_count owner.save() # SEC def filter_list_clouds(auth_context, query_filter=None, sort=None, perm='read', as_dict=True):
64
64
116
24
39
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
filter_list_clouds
filter_list_clouds
105
115
105
106
8235a6c3ede52534ceb89f7924e825a72f3a38fe
bigcode/the-stack
train
77a1d8168bd5b30fa842c889
train
function
def validate_cloud_title(title): if not re.search(r'^[0-9a-zA-Z]+[0-9a-zA-Z-_ .]{0,}[0-9a-zA-Z]+$', title): raise BadRequestError( "Cloud title may only contain ASCII letters, " "numbers, dashes and dots") return title
def validate_cloud_title(title):
if not re.search(r'^[0-9a-zA-Z]+[0-9a-zA-Z-_ .]{0,}[0-9a-zA-Z]+$', title): raise BadRequestError( "Cloud title may only contain ASCII letters, " "numbers, dashes and dots") return title
from mist.api.monitoring.methods import disable_monitoring_cloud from mist.api import config import logging logging.basicConfig(level=config.PY_LOG_LEVEL, format=config.PY_LOG_FORMAT, datefmt=config.PY_LOG_FORMAT_DATE) log = logging.getLogger(__name__) def validate_cloud_ti...
64
64
77
6
58
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
validate_cloud_title
validate_cloud_title
25
30
25
25
90c0f526d1243ac1a86c6287780c8f58e3381300
bigcode/the-stack
train
be7376aeefbbd9eaa2480c36
train
function
def add_cloud_v_2(owner, title, provider, params): """Add cloud to owner""" # FIXME: Some of these should be explicit arguments, others shouldn't exist fail_on_error = params.pop('fail_on_error', params.pop('remove_on_error', True)) params.pop('title', None) params.pop...
def add_cloud_v_2(owner, title, provider, params):
"""Add cloud to owner""" # FIXME: Some of these should be explicit arguments, others shouldn't exist fail_on_error = params.pop('fail_on_error', params.pop('remove_on_error', True)) params.pop('title', None) params.pop('provider', None) # Find proper Cloud subclass...
(title): if not re.search(r'^[0-9a-zA-Z]+[0-9a-zA-Z-_ .]{0,}[0-9a-zA-Z]+$', title): raise BadRequestError( "Cloud title may only contain ASCII letters, " "numbers, dashes and dots") return title def add_cloud_v_2(owner, title, provider, params):
87
87
293
14
72
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
add_cloud_v_2
add_cloud_v_2
33
66
33
33
8000b06a317a587b383b1fe78b0b2835216835d9
bigcode/the-stack
train
ac2f2edc7f04f7956cb810f5
train
function
def list_clouds(owner, query_filter=None, sort=None, as_dict=True): # TODO: apply query_filter & sorting clouds = Cloud.objects(owner=owner, deleted=None) if as_dict: if as_dict == 'v2': return [cloud.as_dict_v2() for cloud in clouds] else: return [cloud.as_dict() for...
def list_clouds(owner, query_filter=None, sort=None, as_dict=True): # TODO: apply query_filter & sorting
clouds = Cloud.objects(owner=owner, deleted=None) if as_dict: if as_dict == 'v2': return [cloud.as_dict_v2() for cloud in clouds] else: return [cloud.as_dict() for cloud in clouds] else: return clouds
auth_context.is_owner(): clouds = [cloud for cloud in clouds if cloud['id'] in auth_context.get_allowed_resources(rtype='clouds')] return clouds def list_clouds(owner, query_filter=None, sort=None, as_dict=True): # TODO: apply query_filter & sorting
64
64
89
27
36
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
list_clouds
list_clouds
118
127
118
119
f9bd02815e199368682d142ec64f68a4dde0a62c
bigcode/the-stack
train
2d597d36063181c3240f0489
train
function
def rename_cloud(owner, cloud_id, new_name): """Renames cloud with given cloud_id.""" log.info("Renaming cloud: %s", cloud_id) cloud = Cloud.objects.get(owner=owner, id=cloud_id, deleted=None) new_name = validate_cloud_title(new_name) cloud.ctl.rename(new_name) log.info("Successfully renamed clo...
def rename_cloud(owner, cloud_id, new_name):
"""Renames cloud with given cloud_id.""" log.info("Renaming cloud: %s", cloud_id) cloud = Cloud.objects.get(owner=owner, id=cloud_id, deleted=None) new_name = validate_cloud_title(new_name) cloud.ctl.rename(new_name) log.info("Successfully renamed cloud '%s'", cloud_id) trigger_session_updat...
with id '%s' added successfully.", cloud.id) c_count = Cloud.objects(owner=owner, deleted=None).count() if owner.clouds_count != c_count: owner.clouds_count = c_count owner.save() return ret def rename_cloud(owner, cloud_id, new_name):
64
64
94
11
52
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
rename_cloud
rename_cloud
69
76
69
69
5c9d014ff38b84f37c40923f2a305be088181aed
bigcode/the-stack
train
c1fbf0550f58a238e3643998
train
function
def remove_cloud(owner, cloud_id): """Deletes cloud with given cloud_id.""" log.info("Deleting cloud: %s", cloud_id) try: disable_monitoring_cloud(owner, cloud_id) except Exception as exc: log.warning("Couldn't disable monitoring before deleting cloud. " "Error: %r"...
def remove_cloud(owner, cloud_id):
"""Deletes cloud with given cloud_id.""" log.info("Deleting cloud: %s", cloud_id) try: disable_monitoring_cloud(owner, cloud_id) except Exception as exc: log.warning("Couldn't disable monitoring before deleting cloud. " "Error: %r", exc) try: cloud = Cl...
.objects.get(owner=owner, id=cloud_id, deleted=None) new_name = validate_cloud_title(new_name) cloud.ctl.rename(new_name) log.info("Successfully renamed cloud '%s'", cloud_id) trigger_session_update(owner, ['clouds']) def remove_cloud(owner, cloud_id):
63
64
176
8
55
SpiralUp/mist.api
src/mist/api/clouds/methods.py
Python
remove_cloud
remove_cloud
79
101
79
79
78737438f845698a1d7f896ad580e36aabe7709c
bigcode/the-stack
train
3053ef3ce61eb66a67b281b7
train
function
def _get_data(): return du.load_csv(__file__, 'DatasetName.csv')
def _get_data():
return du.load_csv(__file__, 'DatasetName.csv')
(): """ Load the strikes data and return a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0) def _get_data():
64
64
18
5
59
jbrockmendel/sm2
sm2/datasets/template_data.py
Python
_get_data
_get_data
60
61
60
60
b1032916d881dd40eb8abf9800df3329fc4cd77f
bigcode/the-stack
train
bb89db17cacb7d94fc760950
train
function
def load(as_pandas=None): """ Load the data and return a Dataset class instance. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns -------- Dataset insta...
def load(as_pandas=None):
""" Load the data and return a Dataset class instance. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns -------- Dataset instance: See DATASET_P...
so desired. """ DESCRSHORT = """A short description.""" DESCRLONG = """A longer description of the dataset.""" NOTE = """ Number of observations: Number of variables: Variable name definitions: Any other useful information that does not fit into the above categories. """ def load(as_pandas=None):
64
64
101
7
57
jbrockmendel/sm2
sm2/datasets/template_data.py
Python
load
load
28
44
28
28
993d606622ac585cacc9395f07824be7c3c79799
bigcode/the-stack
train
6550c41c92ec2a056d2bdfc7
train
function
def load_pandas(): """ Load the strikes data and return a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
def load_pandas():
""" Load the strikes data and return a Dataset class instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Series or numpy recarrays and arrays. If True, returns pandas. Returns -------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ return du.as_numpy_dataset(load_pandas(), as_pandas=as_pandas) def load_pandas():
64
64
63
5
59
jbrockmendel/sm2
sm2/datasets/template_data.py
Python
load_pandas
load_pandas
47
57
47
47
881fe6a078875928643a75e35849494989fb91f1
bigcode/the-stack
train
64580e82162d8a8a6a0f7fa2
train
class
class Circular(object): def __init__(self, list_): assert len(list_) > 0, "list is empty" self._list = list_ self._idx = 0 def __call__(self): if self._idx >= len(self._list): self._idx = 0 val = self._list[self._idx] self._idx += 1 retu...
class Circular(object):
def __init__(self, list_): assert len(list_) > 0, "list is empty" self._list = list_ self._idx = 0 def __call__(self): if self._idx >= len(self._list): self._idx = 0 val = self._list[self._idx] self._idx += 1 return val
""" Little functor objects """ from sdaudio import assert_py3 class Constant(object): def __init__(self, value): self._value = value def __call__(self): return self._value class Circular(object):
55
64
91
5
49
weegreenblobbie/sd_audio_hackers
20160821_wavetable_chorus/code/sdaudio/callables.py
Python
Circular
Circular
19
36
19
21
7efdebb8a834314c8d7ae994b43bd7802d0c51da
bigcode/the-stack
train
d3612b684b6d4ee77443b605
train
class
class Constant(object): def __init__(self, value): self._value = value def __call__(self): return self._value
class Constant(object):
def __init__(self, value): self._value = value def __call__(self): return self._value
""" Little functor objects """ from sdaudio import assert_py3 class Constant(object):
21
64
34
5
15
weegreenblobbie/sd_audio_hackers
20160821_wavetable_chorus/code/sdaudio/callables.py
Python
Constant
Constant
8
16
8
10
4f35b8dc288b741cc4581a7f93d59ad817a31e69
bigcode/the-stack
train
dd227eaba63c6bba6c309a8c
train
function
def revrot(strng, sz): if not len(strng) or sz <= 0 or len(strng) < sz: return '' new_strng = '' for strng_list in map(None, *([iter(strng)] * sz)): if not None in strng_list: new_strng += reverse_or_rotate(''.join(strng_list), sz) return new_strng
def revrot(strng, sz):
if not len(strng) or sz <= 0 or len(strng) < sz: return '' new_strng = '' for strng_list in map(None, *([iter(strng)] * sz)): if not None in strng_list: new_strng += reverse_or_rotate(''.join(strng_list), sz) return new_strng
" revrot("664438769", 8) --> "67834466" revrot("123456779", 8) --> "23456771" revrot("", 8) --> "" revrot("123456779", 0) --> "" ``` """ def revrot(strng, sz):
64
64
87
8
56
nirgn975/CodeWars
CodeWars/Python/Reverse or rotate?.py
Python
revrot
revrot
23
32
23
23
5eb57734a5c297c89b9cd9d58b6dff439cacc487
bigcode/the-stack
train
9d764546b69c71598aa7ad68
train
function
def reverse_or_rotate(string, limit): sum = 0 for index, value in enumerate(string): sum += pow(int(value), 2) if sum % 2 == 0: return string[::-1] return string[1:limit] + string[0]
def reverse_or_rotate(string, limit):
sum = 0 for index, value in enumerate(string): sum += pow(int(value), 2) if sum % 2 == 0: return string[::-1] return string[1:limit] + string[0]
new_strng = '' for strng_list in map(None, *([iter(strng)] * sz)): if not None in strng_list: new_strng += reverse_or_rotate(''.join(strng_list), sz) return new_strng def reverse_or_rotate(string, limit):
64
64
62
8
55
nirgn975/CodeWars
CodeWars/Python/Reverse or rotate?.py
Python
reverse_or_rotate
reverse_or_rotate
35
43
35
35
3cefe2b4f663497e72837350c6d008d54f163b19
bigcode/the-stack
train
7153bfbc42668d21a10a2e22
train
class
class TileMode(Enum): # pylint: disable=missing-function-docstring """linuxmint/muffin:/src/meta/common.h::MetaTileMode""" NONE = 0 LEFT = 1 RIGHT = 2 LEFT_TOP = 3 LEFT_BOTTOM = 4 RIGHT_TOP = 5 RIGHT_BOTTOM = 6 TOP = 7 BOTTOM = 8 MAXIMIZE = 9 def is_bottom(self: "Til...
class TileMode(Enum): # pylint: disable=missing-function-docstring
"""linuxmint/muffin:/src/meta/common.h::MetaTileMode""" NONE = 0 LEFT = 1 RIGHT = 2 LEFT_TOP = 3 LEFT_BOTTOM = 4 RIGHT_TOP = 5 RIGHT_BOTTOM = 6 TOP = 7 BOTTOM = 8 MAXIMIZE = 9 def is_bottom(self: "TileMode"): return self in [ TileMode.BOTTOM, ...
M_STATE_TILED = "_NET_WM_STATE_TILED" class TileMethod(Enum): """ Holding our breath ... https://github.com/linuxmint/muffin/issues/612 """ MOVERESIZE = 0 WMSTATE = 1 KEYBOARD = 2 class TileMode(Enum): # pylint: disable=missing-function-docstring
80
80
269
16
63
crashvb/xsessionp
xsessionp/muffin.py
Python
TileMode
TileMode
36
70
36
37
029957b6f932a62af253f1b5b96378918e1f1ca7
bigcode/the-stack
train
40d5a6493147abfef8ef8692
train
class
class TileType(Enum): """linuxmint/muffin:/src/meta/common.h::MetaWindowTileType""" NONE = 0 TILED = 1 SNAPPED = 2
class TileType(Enum):
"""linuxmint/muffin:/src/meta/common.h::MetaWindowTileType""" NONE = 0 TILED = 1 SNAPPED = 2
] def is_right(self: "TileMode"): return self in [TileMode.RIGHT, TileMode.RIGHT_BOTTOM, TileMode.RIGHT_TOP] def is_top(self: "TileMode"): return self in [TileMode.LEFT_TOP, TileMode.RIGHT_TOP, TileMode.TOP] class TileType(Enum):
64
64
43
5
59
crashvb/xsessionp
xsessionp/muffin.py
Python
TileType
TileType
73
78
73
73
6a3944521310b23452e30747dedd4d1b4290ae34
bigcode/the-stack
train
bb4f71760ca56c2b5842f9e2
train
class
class TileMethod(Enum): """ Holding our breath ... https://github.com/linuxmint/muffin/issues/612 """ MOVERESIZE = 0 WMSTATE = 1 KEYBOARD = 2
class TileMethod(Enum):
""" Holding our breath ... https://github.com/linuxmint/muffin/issues/612 """ MOVERESIZE = 0 WMSTATE = 1 KEYBOARD = 2
Session LOGGER = logging.getLogger(__name__) NET_WM_WINDOW_TILE_INFO = "_NET_WM_WINDOW_TILE_INFO" NET_WM_STATE_MAXIMIZED_VERT = "_NET_WM_STATE_MAXIMIZED_VERT" NET_WM_STATE_TILED = "_NET_WM_STATE_TILED" class TileMethod(Enum):
64
64
51
5
59
crashvb/xsessionp
xsessionp/muffin.py
Python
TileMethod
TileMethod
25
33
25
25
5c087a4a5652c72f3cd2d344ba5c20a2b4bcd5cc
bigcode/the-stack
train
ae72f22c0684ef4c4e40e102
train
class
class Muffin(XSession): """Interacts with muffin.""" def __init__(self, check: bool = True, xsession: XSession = None): super().__init__(check=check) if xsession: self.check = xsession.check self.display = xsession.display def _do_math(self, *, tile_mode: TileMode ...
class Muffin(XSession):
"""Interacts with muffin.""" def __init__(self, check: bool = True, xsession: XSession = None): super().__init__(check=check) if xsession: self.check = xsession.check self.display = xsession.display def _do_math(self, *, tile_mode: TileMode = TileMode.NONE): ...
4 RIGHT_TOP = 5 RIGHT_BOTTOM = 6 TOP = 7 BOTTOM = 8 MAXIMIZE = 9 def is_bottom(self: "TileMode"): return self in [ TileMode.BOTTOM, TileMode.LEFT_BOTTOM, TileMode.RIGHT_BOTTOM, ] def is_full_height(self: "TileMode"): return self ...
256
256
2,688
6
249
crashvb/xsessionp
xsessionp/muffin.py
Python
Muffin
Muffin
81
368
81
81
f0a4974aff55467837a47fc5f6ae03abed4202b8
bigcode/the-stack
train
cc93b3db951095081ded05aa
train
function
def generate(): sections = BatteryStatsSection.Load(raw_batterystats_fields) code_blocks = [] mapping = [] for section in sections: class_name = section.description.replace(" ", "").replace("-", "") vars = list(map(lambda item: convert_to_var_name(item), section.remaining_fields)) ...
def generate():
sections = BatteryStatsSection.Load(raw_batterystats_fields) code_blocks = [] mapping = [] for section in sections: class_name = section.description.replace(" ", "").replace("-", "") vars = list(map(lambda item: convert_to_var_name(item), section.remaining_fields)) init_vars = li...
return field.replace(" ", "_")\ .replace("-", "_")\ .replace("'", "")\ .lower()\ .replace("wi_fi", "wifi")\ .replace("1x", "_1x")\ .replace("(mah)", "mah") def generate():
64
64
194
3
61
cuongnguyen2190/pure-python-adb
scripts/batterystats_codegen.py
Python
generate
generate
97
116
97
97
9c95299705d5c1c2da8ce077d3039ed451b50c4a
bigcode/the-stack
train
100794c4159892ce73895134
train
function
def convert_to_var_name(field): return field.replace(" ", "_")\ .replace("-", "_")\ .replace("'", "")\ .lower()\ .replace("wi_fi", "wifi")\ .replace("1x", "_1x")\ .replace("(mah)", "mah")
def convert_to_var_name(field):
return field.replace(" ", "_")\ .replace("-", "_")\ .replace("'", "")\ .lower()\ .replace("wi_fi", "wifi")\ .replace("1x", "_1x")\ .replace("(mah)", "mah")
().startswith('"'): remaining_fields = list(map(lambda item: item.strip(), raw_fields[1:-1].split(","))) else: remaining_fields = [raw_fields.strip()] sections.append(BatteryStatsSection(id, description, remaining_fields)) return sections def convert_to_...
64
64
68
7
56
cuongnguyen2190/pure-python-adb
scripts/batterystats_codegen.py
Python
convert_to_var_name
convert_to_var_name
88
95
88
88
ea113519111c875da32c45f05f44cdf5976ab490
bigcode/the-stack
train
8d7dfb788fd8a853b447cff6
train
class
class BatteryStatsSection: def __init__(self, id, description, fields): self.id = id self.description = description self.remaining_fields = fields @staticmethod def Load(raw): sections = [] for line in raw.split('\n'): if not line: continu...
class BatteryStatsSection:
def __init__(self, id, description, fields): self.id = id self.description = description self.remaining_fields = fields @staticmethod def Load(raw): sections = [] for line in raw.split('\n'): if not line: continue id, descripti...
_platform_version = end_platform_version """ CLASS_TEMPLATE = """ class {CLASS_NAME}: def __init__(self, {VARS}): self.id = "{ID}" {INIT_VARS} """ GET_SECTION = """ def get_section(name): return mapping.get(name) """ class BatteryStatsSection:
64
64
143
5
59
cuongnguyen2190/pure-python-adb
scripts/batterystats_codegen.py
Python
BatteryStatsSection
BatteryStatsSection
64
85
64
64
38ee13d17532869a3023327e414cc6b21ed83d6f
bigcode/the-stack
train
4e139fa0addb0e7793fa20a1
train
class
class Cash(PositionLoader): """Calculate daily cash position Args: input_data_source: location of input data Attributes: starting_cash_balance (int): original cash injected into portfolio cash_flows (pd.DataFrame): dataframe containing cash flow information daily_cash_balan...
class Cash(PositionLoader):
"""Calculate daily cash position Args: input_data_source: location of input data Attributes: starting_cash_balance (int): original cash injected into portfolio cash_flows (pd.DataFrame): dataframe containing cash flow information daily_cash_balance (pd.Series): daily cash b...
_value_usd = self._get_daily_stocks_value_usd(stock_prices_usd) def _get_daily_shares_owned(self): stock_positions = self.positions[self.positions["yahoo_ticker"] != "cash"] daily_shares_owned = ( stock_positions.pivot( index="date", columns="yahoo_ticker", values="total...
165
165
551
5
159
julian-west/python_portfolio_tracker
ppt/portfolio_value.py
Python
Cash
Cash
50
121
50
50
05a912158259ad33623b060985c944720cf52312
bigcode/the-stack
train
749e35ee87f859ece2e0b27a
train
class
class Portfolio(StockPriceLoader): """Portfolio stats and info Args: input_data_source (str): location of csv with purchase info Attributes: stocks (object): Stock prices and daily stock values. See `Stocks` class cash (object): Cash balance. See `Cash` class portfolio_valu...
class Portfolio(StockPriceLoader):
"""Portfolio stats and info Args: input_data_source (str): location of csv with purchase info Attributes: stocks (object): Stock prices and daily stock values. See `Stocks` class cash (object): Cash balance. See `Cash` class portfolio_value_usd (pd.Series): daily total port...
["cash_balance_change"] = cashflows_df.apply( _calc_portfolio_cash_change, axis=1 ) cashflows_df["pf_cash_balance"] = cashflows_df["cash_balance_change"].cumsum() cashflows_df["external_cashflows"] = ( cashflows_df["inflows"] - cashflows_df["outflows"] ).cumsum() ...
99
99
330
7
92
julian-west/python_portfolio_tracker
ppt/portfolio_value.py
Python
Portfolio
Portfolio
124
163
124
124
3cbe65de11ad49d1f5a68d691b211d3b5e89e060
bigcode/the-stack
train
d059090c4dd3cc36bc113a3b
train
class
class Stocks(PositionLoader): """Calculate daily value of stocks Args: stock_prices_usd (pd.DataFrame): dataframe with the USD converted daily stock price of each ticker in the input csv input_data_source (str): location of input csv Attributes: daily_shares_owned (pd.Se...
class Stocks(PositionLoader):
"""Calculate daily value of stocks Args: stock_prices_usd (pd.DataFrame): dataframe with the USD converted daily stock price of each ticker in the input csv input_data_source (str): location of input csv Attributes: daily_shares_owned (pd.Series): pd.Series with the numb...
"""Calculate Portfolio Daily Value""" import pandas as pd from ppt.data_loader import BenchmarkLoader, PositionLoader, StockPriceLoader class Stocks(PositionLoader):
31
100
334
5
25
julian-west/python_portfolio_tracker
ppt/portfolio_value.py
Python
Stocks
Stocks
7
47
7
7
97551505329ade5231ee07ffc4270bd8a35df18a
bigcode/the-stack
train
dfa95828b7b28d824f8123b9
train
class
class TestSchemaLoader(unittest.TestCase): def setUp(self): self.maxDiff = None # Pseudo-fixtures def schema_base(self): return { 'base': { 'schema_details': {'root': True}, 'field_details': {'name': 'base', 'type': 'group'}, 'fi...
class TestSchemaLoader(unittest.TestCase):
def setUp(self): self.maxDiff = None # Pseudo-fixtures def schema_base(self): return { 'base': { 'schema_details': {'root': True}, 'field_details': {'name': 'base', 'type': 'group'}, 'fields': { 'message': { ...
import mock import os import pprint import sys import unittest sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from schema import loader class TestSchemaLoader(unittest.TestCase):
43
256
3,742
8
34
secops4thewin/ecs
scripts/tests/unit/test_schema_loader.py
Python
TestSchemaLoader
TestSchemaLoader
12
647
12
13
120a7b1379761eda65fd2f144d3dde6d9e736aa9
bigcode/the-stack
train
66c6eea01d5b343f3f2ea1b7
train
function
def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): """ Estimate the covariance matrix. Except for the handling of missing data this function does the same as `numpy.cov`. For more details and examples, see `numpy.cov`. By default, masked values are recognized as such. If `x...
def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):
""" Estimate the covariance matrix. Except for the handling of missing data this function does the same as `numpy.cov`. For more details and examples, see `numpy.cov`. By default, masked values are recognized as such. If `x` and `y` have the same shape, a common mask is allocated: if ``x[i,j]`...
).astype(int) else: y = array(y, copy=False, ndmin=2, dtype=float) ymask = ma.getmaskarray(y) if not allow_masked and ymask.any(): raise ValueError("Cannot process masked data.") if xmask.any() or ymask.any(): if y.shape == x.shape: # Define so...
218
218
729
23
195
waritthap/numpy
numpy/ma/extras.py
Python
cov
cov
1,299
1,369
1,299
1,299
eea77861abce06dd7c52b8dca5be43840afc178d
bigcode/the-stack
train
00eab3368df037de8aa6a272
train
function
def setxor1d(ar1, ar2, assume_unique=False): """ Set exclusive-or of 1-D arrays with unique elements. The output is always a masked array. See `numpy.setxor1d` for more details. See Also -------- numpy.setxor1d : Equivalent function for ndarrays. """ if not assume_unique: ar1 ...
def setxor1d(ar1, ar2, assume_unique=False):
""" Set exclusive-or of 1-D arrays with unique elements. The output is always a masked array. See `numpy.setxor1d` for more details. See Also -------- numpy.setxor1d : Equivalent function for ndarrays. """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) ...
faster than unique( intersect1d( ar1, ar2 ) )? aux = ma.concatenate((unique(ar1), unique(ar2))) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False):
64
65
218
15
49
waritthap/numpy
numpy/ma/extras.py
Python
setxor1d
setxor1d
1,117
1,141
1,117
1,117
0b966326ecf68356d8c2d9c7f681f52c3d61cc5c
bigcode/the-stack
train
7f17006bd3f9eab747cf6da3
train
function
def count_masked(arr, axis=None): """ Count the number of masked elements along the given axis. Parameters ---------- arr : array_like An array with (possibly) masked elements. axis : int, optional Axis along which to count. If None (default), a flattened version of the ...
def count_masked(arr, axis=None):
""" Count the number of masked elements along the given axis. Parameters ---------- arr : array_like An array with (possibly) masked elements. axis : int, optional Axis along which to count. If None (default), a flattened version of the array is used. Returns --...
) import numpy as np from numpy import ndarray, array as nxarray import numpy.core.umath as umath from numpy.core.multiarray import normalize_axis_index from numpy.core.numeric import normalize_axis_tuple from numpy.lib.function_base import _ureduce from numpy.lib.index_tricks import AxisConcatenator def isseque...
111
111
370
9
102
waritthap/numpy
numpy/ma/extras.py
Python
count_masked
count_masked
53
104
53
53
02bee3486754e42fda48c8c84218a9172d442a14
bigcode/the-stack
train
cd395eadcc5c527063a4c59d
train
function
def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """ Any masked values in x is propagated in y, and vice-versa. """ x = asarray(x) y = asarray(y) m = getmask(x) if y.ndim == 1: m = mask_or(m, getmask(y)) elif y.ndim == 2: my = getmask(mask_rows(y)) ...
def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
""" Any masked values in x is propagated in y, and vice-versa. """ x = asarray(x) y = asarray(y) m = getmask(x) if y.ndim == 1: m = mask_or(m, getmask(y)) elif y.ndim == 2: my = getmask(mask_rows(y)) if my is not nomask: m = mask_or(m, my[:, 0]) ...
zeros. """ _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
89
89
297
22
67
waritthap/numpy
numpy/ma/extras.py
Python
polyfit
polyfit
1,884
1,916
1,884
1,884
c73f0d855ce6018655b691477b30b93ec0c1d65c
bigcode/the-stack
train
5e4d56720b85a5bb9a55a377
train
function
def setdiff1d(ar1, ar2, assume_unique=False): """ Set difference of 1D arrays with unique elements. The output is always a masked array. See `numpy.setdiff1d` for more details. See Also -------- numpy.setdiff1d : Equivalent function for ndarrays. Examples -------- >>> x = np.m...
def setdiff1d(ar1, ar2, assume_unique=False):
""" Set difference of 1D arrays with unique elements. The output is always a masked array. See `numpy.setdiff1d` for more details. See Also -------- numpy.setdiff1d : Equivalent function for ndarrays. Examples -------- >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) >...
array. See `numpy.union1d` for more details. See also -------- numpy.union1d : Equivalent function for ndarrays. """ return unique(ma.concatenate((ar1, ar2), axis=None)) def setdiff1d(ar1, ar2, assume_unique=False):
64
64
208
15
49
waritthap/numpy
numpy/ma/extras.py
Python
setdiff1d
setdiff1d
1,223
1,248
1,223
1,223
31b04a7facd8e3438dee4e1a1652a9c63da27195
bigcode/the-stack
train
de5cc92050d8f65563da46d7
train
function
def clump_masked(a): """ Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice ...
def clump_masked(a):
""" Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, o...
>>> np.ma.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)] """ mask = getattr(a, '_mask', nomask) if mask is nomask: return [slice(0, a.size)] return _ezclump(~mask) def clump_masked(a):
78
78
260
7
71
waritthap/numpy
numpy/ma/extras.py
Python
clump_masked
clump_masked
1,826
1,862
1,826
1,826
420630f9099322f4eae9317be92e45aceefc9577
bigcode/the-stack
train
3d0140db51e7b650cf963038
train
function
def vander(x, n=None): """ Masked values in the input array result in rows of zeros. """ _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander
def vander(x, n=None):
""" Masked values in the input array result in rows of zeros. """ _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander
(6, 7, None), slice(8, 10, None)] """ mask = ma.getmask(a) if mask is nomask: return [] return _ezclump(mask) ############################################################################### # Polynomial fit # #######################...
63
64
69
8
55
waritthap/numpy
numpy/ma/extras.py
Python
vander
vander
1,870
1,879
1,870
1,870
f8b0174757b575f0b422b0f169bd8332a7e8f18d
bigcode/the-stack
train
c4f902a6ec67fa89d9a75e60
train
function
def union1d(ar1, ar2): """ Union of two arrays. The output is always a masked array. See `numpy.union1d` for more details. See also -------- numpy.union1d : Equivalent function for ndarrays. """ return unique(ma.concatenate((ar1, ar2), axis=None))
def union1d(ar1, ar2):
""" Union of two arrays. The output is always a masked array. See `numpy.union1d` for more details. See also -------- numpy.union1d : Equivalent function for ndarrays. """ return unique(ma.concatenate((ar1, ar2), axis=None))
. Notes ----- .. versionadded:: 1.13.0 """ element = ma.asarray(element) return in1d(element, test_elements, assume_unique=assume_unique, invert=invert).reshape(element.shape) def union1d(ar1, ar2):
64
64
74
10
54
waritthap/numpy
numpy/ma/extras.py
Python
union1d
union1d
1,209
1,220
1,209
1,209
156c03fa4cdc500c487daa30a47a89648e3097e3
bigcode/the-stack
train
ffeae262f9282a29deacd22e
train
function
def _median(a, axis=None, out=None, overwrite_input=False): # when an unmasked NaN is present return it, so we need to sort the NaN # values behind the mask if np.issubdtype(a.dtype, np.inexact): fill_value = np.inf else: fill_value = None if overwrite_input: if axis is None:...
def _median(a, axis=None, out=None, overwrite_input=False): # when an unmasked NaN is present return it, so we need to sort the NaN # values behind the mask
if np.issubdtype(a.dtype, np.inexact): fill_value = np.inf else: fill_value = None if overwrite_input: if axis is None: asorted = a.ravel() asorted.sort(fill_value=fill_value) else: a.sort(axis=axis, fill_value=fill_value) asort...
5), mask=[0]*6 + [1]*4) >>> np.ma.median(x) 2.5 >>> np.ma.median(x, axis=-1, overwrite_input=True) masked_array(data=[2.0, 5.0], mask=[False, False], fill_value=1e+20) """ if not hasattr(a, 'mask'): m = np.median(getdata(a, subok=True), axis=axis, ...
243
243
810
44
198
waritthap/numpy
numpy/ma/extras.py
Python
_median
_median
723
806
723
725
b13ec1a221527e3ad6155c3d1c762469e3d2c346
bigcode/the-stack
train
b8647e043b999d538aab12d9
train
function
def notmasked_contiguous(a, axis=None): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flatten...
def notmasked_contiguous(a, axis=None):
""" Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array, and this ...
>>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np.ma.masked >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) >>> np.ma.flatnotmasked_contiguous(a) [slice(3, 5, None), slice(6, 9, None)] >>> a[:] = np.ma.masked >>> np.ma.flatnotmasked_contiguous(a) [] """ m = getmask(a...
208
208
696
10
197
waritthap/numpy
numpy/ma/extras.py
Python
notmasked_contiguous
notmasked_contiguous
1,681
1,755
1,681
1,681
d29fcd1e60ea9206e037db17f0beb4a77cc1e1e6
bigcode/the-stack
train
07e2d2a0c084a9ef7059bba9
train
function
def clump_unmasked(a): """ Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice ...
def clump_unmasked(a):
""" Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, on...
2], idx[2::2]))) else: if len(idx) == 0: return [] r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])] if mask[-1]: r.append(slice(idx[-1], mask.size)) return r def clump_unmasked(a):
79
79
264
7
71
waritthap/numpy
numpy/ma/extras.py
Python
clump_unmasked
clump_unmasked
1,787
1,823
1,787
1,787
328e47f5966720ad15b5e2b9d2fd80da02db6035
bigcode/the-stack
train
9dfc859c232bcc9f715fe933
train
function
def masked_all_like(arr): """ Empty masked array with the properties of an existing array. Return an empty masked array of the same shape and dtype as the array `arr`, where all the data are masked. Parameters ---------- arr : ndarray An array describing the shape and dtype of the ...
def masked_all_like(arr):
""" Empty masked array with the properties of an existing array. Return an empty masked array of the same shape and dtype as the array `arr`, where all the data are masked. Parameters ---------- arr : ndarray An array describing the shape and dtype of the required MaskedArray. ...
64) The `dtype` parameter defines the underlying data type. >>> a = ma.masked_all((3, 3)) >>> a.dtype dtype('float64') >>> a = ma.masked_all((3, 3), dtype=np.int32) >>> a.dtype dtype('int32') """ a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, mak...
103
103
346
6
96
waritthap/numpy
numpy/ma/extras.py
Python
masked_all_like
masked_all_like
159
211
159
159
335672a7f5a074cd68ae441bdba74dc5cf7824c8
bigcode/the-stack
train
70272d2854599b6e61ca8868
train
function
def compress_rows(a): """ Suppress whole rows of a 2-D array that contain masked values. This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ a = asarray(a) if a.ndim != 2: rais...
def compress_rows(a):
""" Suppress whole rows of a 2-D array that contain masked values. This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ a = asarray(a) if a.ndim != 2: raise NotImplementedError(...
, 2], [4, 5], [7, 8]]) """ if asarray(x).ndim != 2: raise NotImplementedError("compress_rowcols works for 2D arrays only.") return compress_nd(x, axis=axis) def compress_rows(a):
64
64
109
5
59
waritthap/numpy
numpy/ma/extras.py
Python
compress_rows
compress_rows
906
921
906
906
f8f55ea6bdafc31ae52374adbf34acefd52359ba
bigcode/the-stack
train
44108b809fd3ef965357929e
train
function
def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ (This docstring should be overwritten) """ arr = array(arr, copy=False, subok=True) nd = arr.ndim axis = normalize_axis_index(axis, nd) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') indlist = list(range(nd)) indlist.remov...
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
""" (This docstring should be overwritten) """ arr = array(arr, copy=False, subok=True) nd = arr.ndim axis = normalize_axis_index(axis, nd) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = np....
return res atleast_1d = _fromnxfunction_allargs('atleast_1d') atleast_2d = _fromnxfunction_allargs('atleast_2d') atleast_3d = _fromnxfunction_allargs('atleast_3d') vstack = row_stack = _fromnxfunction_seq('vstack') hstack = _fromnxfunction_seq('hstack') column_stack = _fromnxfunction_seq('column_stack') dstack = _f...
231
231
773
19
211
waritthap/numpy
numpy/ma/extras.py
Python
apply_along_axis
apply_along_axis
379
458
379
379
95417262449267b04f8ccfb2ab699fcd653c1902
bigcode/the-stack
train
3500d039dc6321de6183027d
train
function
def average(a, axis=None, weights=None, returned=False): """ Return the weighted average of array over the given axis. Parameters ---------- a : array_like Data to be averaged. Masked entries are not taken into account in the computation. axis : int, optional Axis along ...
def average(a, axis=None, weights=None, returned=False):
""" Return the weighted average of array over the given axis. Parameters ---------- a : array_like Data to be averaged. Masked entries are not taken into account in the computation. axis : int, optional Axis along which to average `a`. If `None`, averaging is done over ...
14, 15], [--, --, --, --], [20, 21, 22, 23]]], mask=[[[False, True, False, False], [ True, True, True, True], [False, False, False, False]], [[False, True, False, False], [ True, True, True, True], [False, False, Fa...
255
256
933
13
242
waritthap/numpy
numpy/ma/extras.py
Python
average
average
535
638
535
535
0f1476f53f51ed06514d9c1800fa459313494272
bigcode/the-stack
train
2cd9a4a7e07513e5ae12e36e
train
function
def _ezclump(mask): """ Finds the clumps (groups of data with the same values) for a 1D bool array. Returns a series of slices. """ if mask.ndim > 1: mask = mask.ravel() idx = (mask[1:] ^ mask[:-1]).nonzero() idx = idx[0] + 1 if mask[0]: if len(idx) == 0: re...
def _ezclump(mask):
""" Finds the clumps (groups of data with the same values) for a 1D bool array. Returns a series of slices. """ if mask.ndim > 1: mask = mask.ravel() idx = (mask[1:] ^ mask[:-1]).nonzero() idx = idx[0] + 1 if mask[0]: if len(idx) == 0: return [slice(0, mask....
idx = [0, 0] idx[axis] = slice(None, None) # for i in range(a.shape[other]): idx[other] = i result.append(flatnotmasked_contiguous(a[tuple(idx)])) return result def _ezclump(mask):
64
64
214
7
56
waritthap/numpy
numpy/ma/extras.py
Python
_ezclump
_ezclump
1,758
1,784
1,758
1,758
311f0e007a537de4b522dd4bb7d9bc8e808d7dca
bigcode/the-stack
train
91cd8a23080cdb12597a4e33
train
function
def issequence(seq): """ Is seq a sequence (ndarray, list or tuple)? """ return isinstance(seq, (ndarray, tuple, list))
def issequence(seq):
""" Is seq a sequence (ndarray, list or tuple)? """ return isinstance(seq, (ndarray, tuple, list))
numpy import ndarray, array as nxarray import numpy.core.umath as umath from numpy.core.multiarray import normalize_axis_index from numpy.core.numeric import normalize_axis_tuple from numpy.lib.function_base import _ureduce from numpy.lib.index_tricks import AxisConcatenator def issequence(seq):
64
64
35
5
58
waritthap/numpy
numpy/ma/extras.py
Python
issequence
issequence
45
50
45
45
fdae50449a12f3bbadc51bb080b4d02a0fa992e4
bigcode/the-stack
train
b796e6fcd1436e62f75dfb90
train
function
def flatnotmasked_edges(a): """ Find the indices of the first and last unmasked values. Expects a 1-D `MaskedArray`, returns None if all values are masked. Parameters ---------- a : array_like Input 1-D `MaskedArray` Returns ------- edges : ndarray or None The indi...
def flatnotmasked_edges(a):
""" Find the indices of the first and last unmasked values. Expects a 1-D `MaskedArray`, returns None if all values are masked. Parameters ---------- a : array_like Input 1-D `MaskedArray` Returns ------- edges : ndarray or None The indices of first and last non-ma...
.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] masked_array(data=[1, 2, 3, ..., 4, 5, 6], mask=False, fill_value=999999) """ def __init__(self): MAxisConcatenator.__init__(self, 0) mr_ = mr_class() #####--------------------------------------------------------------------...
105
106
356
7
99
waritthap/numpy
numpy/ma/extras.py
Python
flatnotmasked_edges
flatnotmasked_edges
1,519
1,571
1,519
1,519
b96f62e79a8241db7c0b0ce8b61e5448161aa28e
bigcode/the-stack
train
4b59c95c24e02a742f974fd2
train
function
def _covhelper(x, y=None, rowvar=True, allow_masked=True): """ Private function for the computation of covariance and correlation coefficients. """ x = ma.array(x, ndmin=2, copy=True, dtype=float) xmask = ma.getmaskarray(x) # Quick exit if we can't process masked data if not allow_maske...
def _covhelper(x, y=None, rowvar=True, allow_masked=True):
""" Private function for the computation of covariance and correlation coefficients. """ x = ma.array(x, ndmin=2, copy=True, dtype=float) xmask = ma.getmaskarray(x) # Quick exit if we can't process masked data if not allow_masked and xmask.any(): raise ValueError("Cannot process...
, 2]) masked_array(data=[3, --], mask=[False, True], fill_value=999999) """ if assume_unique: ar1 = ma.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] ##################...
115
116
387
18
97
waritthap/numpy
numpy/ma/extras.py
Python
_covhelper
_covhelper
1,256
1,296
1,256
1,256
f6795af657368140322251001f1471c5b5152796
bigcode/the-stack
train
924363e88bada0f40b6267ae
train
function
def masked_all(shape, dtype=float): """ Empty masked array with all elements masked. Return an empty masked array of the given shape and dtype, where all the data are masked. Parameters ---------- shape : tuple Shape of the required MaskedArray. dtype : dtype, optional ...
def masked_all(shape, dtype=float):
""" Empty masked array with all elements masked. Return an empty masked array of the given shape and dtype, where all the data are masked. Parameters ---------- shape : tuple Shape of the required MaskedArray. dtype : dtype, optional Data type of the output. Return...
.count_masked(a) 3 When the `axis` keyword is used an array is returned. >>> ma.count_masked(a, axis=0) array([1, 1, 1]) >>> ma.count_masked(a, axis=1) array([0, 2, 1]) """ m = getmaskarray(arr) return m.sum(axis) def masked_all(shape, dtype=float):
93
93
312
8
85
waritthap/numpy
numpy/ma/extras.py
Python
masked_all
masked_all
107
156
107
107
b649e62dc8d25f539e6be73270a5af114ca51d6f
bigcode/the-stack
train
4f544c36ab26e3edea9241ce
train
class
class mr_class(MAxisConcatenator): """ Translate slice objects to concatenation along the first axis. This is the masked array version of `lib.index_tricks.RClass`. See Also -------- lib.index_tricks.RClass Examples -------- >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4...
class mr_class(MAxisConcatenator):
""" Translate slice objects to concatenation along the first axis. This is the masked array version of `lib.index_tricks.RClass`. See Also -------- lib.index_tricks.RClass Examples -------- >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] masked_array(data=[1, 2...
__getitem__(self, key): # matrix builder syntax, like 'a, b; c, d' if isinstance(key, str): raise MAError("Unavailable for masked array.") return super(MAxisConcatenator, self).__getitem__(key) class mr_class(MAxisConcatenator):
64
64
150
9
55
waritthap/numpy
numpy/ma/extras.py
Python
mr_class
mr_class
1,492
1,511
1,492
1,492
4a24a9d5d95ed497c221e913870db1cb44897ce4
bigcode/the-stack
train
3d6172f9799de62c7fbf47e2
train
function
def flatten_inplace(seq): """Flatten a sequence in place.""" k = 0 while (k != len(seq)): while hasattr(seq[k], '__iter__'): seq[k:(k + 1)] = seq[k] k += 1 return seq
def flatten_inplace(seq):
"""Flatten a sequence in place.""" k = 0 while (k != len(seq)): while hasattr(seq[k], '__iter__'): seq[k:(k + 1)] = seq[k] k += 1 return seq
function_seq('column_stack') dstack = _fromnxfunction_seq('dstack') stack = _fromnxfunction_seq('stack') hsplit = _fromnxfunction_single('hsplit') diagflat = _fromnxfunction_single('diagflat') #####-------------------------------------------------------------------------- #---- #####--------------------------------...
64
64
61
6
59
waritthap/numpy
numpy/ma/extras.py
Python
flatten_inplace
flatten_inplace
369
376
369
369
83355acfb1601c1296810270b451f0f89fabce2f
bigcode/the-stack
train
d2168b21f6ea51ca5b898b15
train
function
def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of an array is also present in a second array. The output is always a masked array. See `numpy.in1d` for more details. We recommend using :func:`isin` instead of `in1d` for new code. See Also -------- ...
def in1d(ar1, ar2, assume_unique=False, invert=False):
""" Test whether each element of an array is also present in a second array. The output is always a masked array. See `numpy.in1d` for more details. We recommend using :func:`isin` instead of `in1d` for new code. See Also -------- isin : Version of this function that preserves t...
( aux, to_end = 1, to_begin = 1 ) == 0 flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True])) # flag2 = ediff1d( flag ) == 0 flag2 = (flag[1:] == flag[:-1]) return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False):
96
96
322
17
79
waritthap/numpy
numpy/ma/extras.py
Python
in1d
in1d
1,144
1,183
1,144
1,144
3c547c2fc664b115230972341a8fa0b7f4dc56de
bigcode/the-stack
train
e4daa50aa680ec5fbe050d8a
train
class
class _fromnxfunction(object): """ Defines a wrapper to adapt NumPy functions to masked arrays. An instance of `_fromnxfunction` can be called with the same parameters as the wrapped NumPy function. The docstring of `newfunc` is adapted from the wrapped function as well, see `getdoc`. This cl...
class _fromnxfunction(object):
""" Defines a wrapper to adapt NumPy functions to masked arrays. An instance of `_fromnxfunction` can be called with the same parameters as the wrapped NumPy function. The docstring of `newfunc` is adapted from the wrapped function as well, see `getdoc`. This class should not be used directly...
True, True, True]], fill_value=1e+20, dtype=float32) The dtype of the masked array matches the dtype of `arr`. >>> arr.dtype dtype('float32') >>> ma.masked_all_like(arr).dtype dtype('float32') """ a = np.empty_like(arr).view(MaskedArray) a._mask = np.ones(a.shape, dtype...
118
118
396
7
112
waritthap/numpy
numpy/ma/extras.py
Python
_fromnxfunction
_fromnxfunction
217
269
217
217
46ce145c76e75b738a47e20d8137e3fac7bbcd86
bigcode/the-stack
train
c5861b255990aba0700f2413
train
function
def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Except for the handling of missing data this function does the same as `numpy.corrcoef`. For more details and examples, see `numpy.corrco...
def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True, ddof=np._NoValue):
""" Return Pearson product-moment correlation coefficients. Except for the handling of missing data this function does the same as `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple vari...
ValueError Raised if some values are missing and `allow_masked` is False. See Also -------- numpy.cov """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError("ddof must be an integer") # Set up ddof if ddof is None: if bias: d...
256
256
897
31
224
waritthap/numpy
numpy/ma/extras.py
Python
corrcoef
corrcoef
1,372
1,456
1,372
1,373
e40a010142488e8ded3f3431bf0d6509cad8c8c2
bigcode/the-stack
train
7ae021d9da79d52c911cfc69
train
function
def apply_over_axes(func, a, axes): """ (This docstring will be overwritten) """ val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res...
def apply_over_axes(func, a, axes):
""" (This docstring will be overwritten) """ val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res.ndim == val.ndim: val =...
, dtype=max_dtypes) else: result = asarray(outarr, dtype=max_dtypes) result.fill_value = ma.default_fill_value(result) return result apply_along_axis.__doc__ = np.apply_along_axis.__doc__ def apply_over_axes(func, a, axes):
63
64
159
10
53
waritthap/numpy
numpy/ma/extras.py
Python
apply_over_axes
apply_over_axes
462
484
462
462
740b968ac4c180b542bd2d85e02a6bbd028c00c2
bigcode/the-stack
train
acdaa25d118b78377a195aa2
train
function
def flatnotmasked_contiguous(a): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of `slice` objects (start index, end index). ..versi...
def flatnotmasked_contiguous(a):
""" Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of `slice` objects (start index, end index). ..versionchanged:: 1.15.0 No...
, 6]) """ a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compresse...
113
114
380
8
105
waritthap/numpy
numpy/ma/extras.py
Python
flatnotmasked_contiguous
flatnotmasked_contiguous
1,625
1,679
1,625
1,625
2529a13f43069653ad59176fe000e8d3e7359b76
bigcode/the-stack
train
b38b1dc1f5b15b71fb9b9f93
train
class
class MAxisConcatenator(AxisConcatenator): """ Translate slice objects to concatenation along an axis. For documentation on usage, see `mr_class`. See Also -------- mr_class """ concatenate = staticmethod(concatenate) @classmethod def makemat(cls, arr): # There used t...
class MAxisConcatenator(AxisConcatenator):
""" Translate slice objects to concatenation along an axis. For documentation on usage, see `mr_class`. See Also -------- mr_class """ concatenate = staticmethod(concatenate) @classmethod def makemat(cls, arr): # There used to be a view as np.matrix here, but we may e...
).var(axis=1) _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x)) return c / _denom #####-------------------------------------------------------------------------- #---- --- Concatenation helpers --- #####-------------------------------------------------------------------------- class...
63
64
214
12
52
waritthap/numpy
numpy/ma/extras.py
Python
MAxisConcatenator
MAxisConcatenator
1,462
1,489
1,462
1,462
14518824357060d52c02f6cc85f2ff99fc868349
bigcode/the-stack
train
0f76d53e21850498ad41a2d1
train
function
def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): """ Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int, optional ...
def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
""" Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int, optional Axis along which the medians are computed. The default (None) is ...
a and weights " "differ.") if wgt.ndim != 1: raise TypeError( "1D weights expected when shapes of a and weights differ.") if wgt.shape[0] != a.shape[axis]: raise ValueError( "Length of weights not compat...
225
225
751
18
206
waritthap/numpy
numpy/ma/extras.py
Python
median
median
641
721
641
641
23a2ec33f8f62855058a26629cf7f08cac9aac9e
bigcode/the-stack
train
80aa48561173feb13e99c558
train
class
class _fromnxfunction_single(_fromnxfunction): """ A version of `_fromnxfunction` that is called with a single array argument followed by auxiliary args that are passed verbatim for both the data and mask calls. """ def __call__(self, x, *args, **params): func = getattr(np, self.__name__...
class _fromnxfunction_single(_fromnxfunction):
""" A version of `_fromnxfunction` that is called with a single array argument followed by auxiliary args that are passed verbatim for both the data and mask calls. """ def __call__(self, x, *args, **params): func = getattr(np, self.__name__) if isinstance(x, ndarray): ...
function is applied to both the _data"\ " and the _mask, if any." return '\n'.join((sig, doc, locdoc)) return def __call__(self, *args, **params): pass class _fromnxfunction_single(_fromnxfunction):
64
64
173
11
52
waritthap/numpy
numpy/ma/extras.py
Python
_fromnxfunction_single
_fromnxfunction_single
272
287
272
272
fc2bf795bcbf44f62e5a31d0b50aa2695ee19097
bigcode/the-stack
train
dfedc2799c43bba7a0004880
train
function
def mask_rows(a, axis=None): """ Mask rows of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples ...
def mask_rows(a, axis=None):
""" Mask rows of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import n...
masked values. This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ a = asarray(a) if a.ndim != 2: raise NotImplementedError("compress_cols works for 2D arrays only.") return compr...
97
97
325
8
89
waritthap/numpy
numpy/ma/extras.py
Python
mask_rows
mask_rows
940
982
940
940
def28d55011666e0fb28d620ecacc24e533b42bc
bigcode/the-stack
train
1a06107a830b1b2bc05632e2
train
class
class _fromnxfunction_args(_fromnxfunction): """ A version of `_fromnxfunction` that is called with multiple array arguments. The first non-array-like input marks the beginning of the arguments that are passed verbatim for both the data and mask calls. Array arguments are processed independently and...
class _fromnxfunction_args(_fromnxfunction):
""" A version of `_fromnxfunction` that is called with multiple array arguments. The first non-array-like input marks the beginning of the arguments that are passed verbatim for both the data and mask calls. Array arguments are processed independently and the results are returned in a list. If o...
name__) _d = func(tuple([np.asarray(a) for a in x]), *args, **params) _m = func(tuple([getmaskarray(a) for a in x]), *args, **params) return masked_array(_d, mask=_m) class _fromnxfunction_args(_fromnxfunction):
69
69
230
11
58
waritthap/numpy
numpy/ma/extras.py
Python
_fromnxfunction_args
_fromnxfunction_args
303
325
303
303
28711b204e08c8947dca34ef429295d5c5d912db
bigcode/the-stack
train
6f6011d78eacdc7b6fe3bc0f
train
function
def intersect1d(ar1, ar2, assume_unique=False): """ Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent f...
def intersect1d(ar1, ar2, assume_unique=False):
""" Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent function for ndarrays. Examples --------...
, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output d...
79
79
266
14
64
waritthap/numpy
numpy/ma/extras.py
Python
intersect1d
intersect1d
1,085
1,114
1,085
1,085
58297efe1ea63375dcad2b5f280c6a6fc4232e3d
bigcode/the-stack
train