repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
AltSchool/dynamic-rest | dynamic_rest/prefetch.py | FastQueryCompatMixin._get_django_queryset | def _get_django_queryset(self):
"""Return Django QuerySet with prefetches properly configured."""
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, 'query')
qs = fprefetch.query.queryset if has_query else None
prefetches.append(
Prefetch(field, queryset=qs)
)
queryset = self.queryset
if prefetches:
queryset = queryset.prefetch_related(*prefetches)
return queryset | python | def _get_django_queryset(self):
"""Return Django QuerySet with prefetches properly configured."""
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, 'query')
qs = fprefetch.query.queryset if has_query else None
prefetches.append(
Prefetch(field, queryset=qs)
)
queryset = self.queryset
if prefetches:
queryset = queryset.prefetch_related(*prefetches)
return queryset | [
"def",
"_get_django_queryset",
"(",
"self",
")",
":",
"prefetches",
"=",
"[",
"]",
"for",
"field",
",",
"fprefetch",
"in",
"self",
".",
"prefetches",
".",
"items",
"(",
")",
":",
"has_query",
"=",
"hasattr",
"(",
"fprefetch",
",",
"'query'",
")",
"qs",
... | Return Django QuerySet with prefetches properly configured. | [
"Return",
"Django",
"QuerySet",
"with",
"prefetches",
"properly",
"configured",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/prefetch.py#L225-L240 | train | 199,700 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | WithDynamicViewSetMixin.get_renderers | def get_renderers(self):
"""Optionally block Browsable API rendering. """
renderers = super(WithDynamicViewSetMixin, self).get_renderers()
if settings.ENABLE_BROWSABLE_API is False:
return [
r for r in renderers if not isinstance(r, BrowsableAPIRenderer)
]
else:
return renderers | python | def get_renderers(self):
"""Optionally block Browsable API rendering. """
renderers = super(WithDynamicViewSetMixin, self).get_renderers()
if settings.ENABLE_BROWSABLE_API is False:
return [
r for r in renderers if not isinstance(r, BrowsableAPIRenderer)
]
else:
return renderers | [
"def",
"get_renderers",
"(",
"self",
")",
":",
"renderers",
"=",
"super",
"(",
"WithDynamicViewSetMixin",
",",
"self",
")",
".",
"get_renderers",
"(",
")",
"if",
"settings",
".",
"ENABLE_BROWSABLE_API",
"is",
"False",
":",
"return",
"[",
"r",
"for",
"r",
"... | Optionally block Browsable API rendering. | [
"Optionally",
"block",
"Browsable",
"API",
"rendering",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L146-L154 | train | 199,701 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | WithDynamicViewSetMixin.get_request_feature | def get_request_feature(self, name):
"""Parses the request for a particular feature.
Arguments:
name: A feature name.
Returns:
A feature parsed from the URL if the feature is supported, or None.
"""
if '[]' in name:
# array-type
return self.request.query_params.getlist(
name) if name in self.features else None
elif '{}' in name:
# object-type (keys are not consistent)
return self._extract_object_params(
name) if name in self.features else {}
else:
# single-type
return self.request.query_params.get(
name) if name in self.features else None | python | def get_request_feature(self, name):
"""Parses the request for a particular feature.
Arguments:
name: A feature name.
Returns:
A feature parsed from the URL if the feature is supported, or None.
"""
if '[]' in name:
# array-type
return self.request.query_params.getlist(
name) if name in self.features else None
elif '{}' in name:
# object-type (keys are not consistent)
return self._extract_object_params(
name) if name in self.features else {}
else:
# single-type
return self.request.query_params.get(
name) if name in self.features else None | [
"def",
"get_request_feature",
"(",
"self",
",",
"name",
")",
":",
"if",
"'[]'",
"in",
"name",
":",
"# array-type",
"return",
"self",
".",
"request",
".",
"query_params",
".",
"getlist",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"features",
"else... | Parses the request for a particular feature.
Arguments:
name: A feature name.
Returns:
A feature parsed from the URL if the feature is supported, or None. | [
"Parses",
"the",
"request",
"for",
"a",
"particular",
"feature",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L156-L176 | train | 199,702 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | WithDynamicViewSetMixin._extract_object_params | def _extract_object_params(self, name):
"""
Extract object params, return as dict
"""
params = self.request.query_params.lists()
params_map = {}
prefix = name[:-1]
offset = len(prefix)
for name, value in params:
if name.startswith(prefix):
if name.endswith('}'):
name = name[offset:-1]
elif name.endswith('}[]'):
# strip off trailing []
# this fixes an Ember queryparams issue
name = name[offset:-3]
else:
# malformed argument like:
# filter{foo=bar
raise exceptions.ParseError(
'"%s" is not a well-formed filter key.' % name
)
else:
continue
params_map[name] = value
return params_map | python | def _extract_object_params(self, name):
"""
Extract object params, return as dict
"""
params = self.request.query_params.lists()
params_map = {}
prefix = name[:-1]
offset = len(prefix)
for name, value in params:
if name.startswith(prefix):
if name.endswith('}'):
name = name[offset:-1]
elif name.endswith('}[]'):
# strip off trailing []
# this fixes an Ember queryparams issue
name = name[offset:-3]
else:
# malformed argument like:
# filter{foo=bar
raise exceptions.ParseError(
'"%s" is not a well-formed filter key.' % name
)
else:
continue
params_map[name] = value
return params_map | [
"def",
"_extract_object_params",
"(",
"self",
",",
"name",
")",
":",
"params",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"lists",
"(",
")",
"params_map",
"=",
"{",
"}",
"prefix",
"=",
"name",
"[",
":",
"-",
"1",
"]",
"offset",
"=",
"len"... | Extract object params, return as dict | [
"Extract",
"object",
"params",
"return",
"as",
"dict"
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L178-L205 | train | 199,703 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | WithDynamicViewSetMixin.get_queryset | def get_queryset(self, queryset=None):
"""
Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset.
"""
serializer = self.get_serializer()
return getattr(self, 'queryset', serializer.Meta.model.objects.all()) | python | def get_queryset(self, queryset=None):
"""
Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset.
"""
serializer = self.get_serializer()
return getattr(self, 'queryset', serializer.Meta.model.objects.all()) | [
"def",
"get_queryset",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"serializer",
"=",
"self",
".",
"get_serializer",
"(",
")",
"return",
"getattr",
"(",
"self",
",",
"'queryset'",
",",
"serializer",
".",
"Meta",
".",
"model",
".",
"objects",
"."... | Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset. | [
"Returns",
"a",
"queryset",
"for",
"this",
"request",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L207-L215 | train | 199,704 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | WithDynamicViewSetMixin.get_request_fields | def get_request_fields(self):
"""Parses the INCLUDE and EXCLUDE features.
Extracts the dynamic field features from the request parameters
into a field map that can be passed to a serializer.
Returns:
A nested dict mapping serializer keys to
True (include) or False (exclude).
"""
if hasattr(self, '_request_fields'):
return self._request_fields
include_fields = self.get_request_feature(self.INCLUDE)
exclude_fields = self.get_request_feature(self.EXCLUDE)
request_fields = {}
for fields, include in(
(include_fields, True),
(exclude_fields, False)):
if fields is None:
continue
for field in fields:
field_segments = field.split('.')
num_segments = len(field_segments)
current_fields = request_fields
for i, segment in enumerate(field_segments):
last = i == num_segments - 1
if segment:
if last:
current_fields[segment] = include
else:
if segment not in current_fields:
current_fields[segment] = {}
current_fields = current_fields[segment]
elif not last:
# empty segment must be the last segment
raise exceptions.ParseError(
'"%s" is not a valid field.' %
field
)
self._request_fields = request_fields
return request_fields | python | def get_request_fields(self):
"""Parses the INCLUDE and EXCLUDE features.
Extracts the dynamic field features from the request parameters
into a field map that can be passed to a serializer.
Returns:
A nested dict mapping serializer keys to
True (include) or False (exclude).
"""
if hasattr(self, '_request_fields'):
return self._request_fields
include_fields = self.get_request_feature(self.INCLUDE)
exclude_fields = self.get_request_feature(self.EXCLUDE)
request_fields = {}
for fields, include in(
(include_fields, True),
(exclude_fields, False)):
if fields is None:
continue
for field in fields:
field_segments = field.split('.')
num_segments = len(field_segments)
current_fields = request_fields
for i, segment in enumerate(field_segments):
last = i == num_segments - 1
if segment:
if last:
current_fields[segment] = include
else:
if segment not in current_fields:
current_fields[segment] = {}
current_fields = current_fields[segment]
elif not last:
# empty segment must be the last segment
raise exceptions.ParseError(
'"%s" is not a valid field.' %
field
)
self._request_fields = request_fields
return request_fields | [
"def",
"get_request_fields",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_request_fields'",
")",
":",
"return",
"self",
".",
"_request_fields",
"include_fields",
"=",
"self",
".",
"get_request_feature",
"(",
"self",
".",
"INCLUDE",
")",
"exclud... | Parses the INCLUDE and EXCLUDE features.
Extracts the dynamic field features from the request parameters
into a field map that can be passed to a serializer.
Returns:
A nested dict mapping serializer keys to
True (include) or False (exclude). | [
"Parses",
"the",
"INCLUDE",
"and",
"EXCLUDE",
"features",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L217-L259 | train | 199,705 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | DynamicModelViewSet.update | def update(self, request, *args, **kwargs):
"""Update one or more model instances.
If ENABLE_BULK_UPDATE is set, multiple previously-fetched records
may be updated in a single call, provided their IDs.
If ENABLE_PATCH_ALL is set, multiple records
may be updated in a single PATCH call, even without knowing their IDs.
*WARNING*: ENABLE_PATCH_ALL should be considered an advanced feature
and used with caution. This feature must be enabled at the viewset level
and must also be requested explicitly by the client
via the "patch-all" query parameter.
This parameter can have one of the following values:
true (or 1): records will be fetched and then updated in a transaction loop
- The `Model.save` method will be called and model signals will run
- This can be slow if there are too many signals or many records in the query
- This is considered the more safe and default behavior
query: records will be updated in a single query
- The `QuerySet.update` method will be called and model signals will not run
- This will be fast, but may break data constraints that are controlled by signals
- This is considered unsafe but useful in certain situations
The server's successful response to a patch-all request
will NOT include any individual records. Instead, the response content will contain
a "meta" object with an "updated" count of updated records.
Examples:
Update one dog:
PATCH /dogs/1/
{
'fur': 'white'
}
Update many dogs by ID:
PATCH /dogs/
[
{'id': 1, 'fur': 'white'},
{'id': 2, 'fur': 'black'},
{'id': 3, 'fur': 'yellow'}
]
Update all dogs in a query:
PATCH /dogs/?filter{fur.contains}=brown&patch-all=true
{
'fur': 'gold'
}
""" # noqa
if self.ENABLE_BULK_UPDATE:
patch_all = self.get_request_patch_all()
if self.ENABLE_PATCH_ALL and patch_all:
# patch-all update
data = request.data
return self._patch_all(
data,
query=(patch_all == 'query')
)
else:
# bulk payload update
partial = 'partial' in kwargs
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._bulk_update(bulk_payload, partial)
# singular update
try:
return super(DynamicModelViewSet, self).update(request, *args,
**kwargs)
except AssertionError as e:
err = str(e)
if 'Fix your URL conf' in err:
# this error is returned by DRF if a client
# makes an update request (PUT or PATCH) without an ID
# since DREST supports bulk updates with IDs contained in data,
# we return a 400 instead of a 500 for this case,
# as this is not considered a misconfiguration
raise exceptions.ValidationError(err)
else:
raise | python | def update(self, request, *args, **kwargs):
"""Update one or more model instances.
If ENABLE_BULK_UPDATE is set, multiple previously-fetched records
may be updated in a single call, provided their IDs.
If ENABLE_PATCH_ALL is set, multiple records
may be updated in a single PATCH call, even without knowing their IDs.
*WARNING*: ENABLE_PATCH_ALL should be considered an advanced feature
and used with caution. This feature must be enabled at the viewset level
and must also be requested explicitly by the client
via the "patch-all" query parameter.
This parameter can have one of the following values:
true (or 1): records will be fetched and then updated in a transaction loop
- The `Model.save` method will be called and model signals will run
- This can be slow if there are too many signals or many records in the query
- This is considered the more safe and default behavior
query: records will be updated in a single query
- The `QuerySet.update` method will be called and model signals will not run
- This will be fast, but may break data constraints that are controlled by signals
- This is considered unsafe but useful in certain situations
The server's successful response to a patch-all request
will NOT include any individual records. Instead, the response content will contain
a "meta" object with an "updated" count of updated records.
Examples:
Update one dog:
PATCH /dogs/1/
{
'fur': 'white'
}
Update many dogs by ID:
PATCH /dogs/
[
{'id': 1, 'fur': 'white'},
{'id': 2, 'fur': 'black'},
{'id': 3, 'fur': 'yellow'}
]
Update all dogs in a query:
PATCH /dogs/?filter{fur.contains}=brown&patch-all=true
{
'fur': 'gold'
}
""" # noqa
if self.ENABLE_BULK_UPDATE:
patch_all = self.get_request_patch_all()
if self.ENABLE_PATCH_ALL and patch_all:
# patch-all update
data = request.data
return self._patch_all(
data,
query=(patch_all == 'query')
)
else:
# bulk payload update
partial = 'partial' in kwargs
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._bulk_update(bulk_payload, partial)
# singular update
try:
return super(DynamicModelViewSet, self).update(request, *args,
**kwargs)
except AssertionError as e:
err = str(e)
if 'Fix your URL conf' in err:
# this error is returned by DRF if a client
# makes an update request (PUT or PATCH) without an ID
# since DREST supports bulk updates with IDs contained in data,
# we return a 400 instead of a 500 for this case,
# as this is not considered a misconfiguration
raise exceptions.ValidationError(err)
else:
raise | [
"def",
"update",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa",
"if",
"self",
".",
"ENABLE_BULK_UPDATE",
":",
"patch_all",
"=",
"self",
".",
"get_request_patch_all",
"(",
")",
"if",
"self",
".",
"ENABLE_PATCH_... | Update one or more model instances.
If ENABLE_BULK_UPDATE is set, multiple previously-fetched records
may be updated in a single call, provided their IDs.
If ENABLE_PATCH_ALL is set, multiple records
may be updated in a single PATCH call, even without knowing their IDs.
*WARNING*: ENABLE_PATCH_ALL should be considered an advanced feature
and used with caution. This feature must be enabled at the viewset level
and must also be requested explicitly by the client
via the "patch-all" query parameter.
This parameter can have one of the following values:
true (or 1): records will be fetched and then updated in a transaction loop
- The `Model.save` method will be called and model signals will run
- This can be slow if there are too many signals or many records in the query
- This is considered the more safe and default behavior
query: records will be updated in a single query
- The `QuerySet.update` method will be called and model signals will not run
- This will be fast, but may break data constraints that are controlled by signals
- This is considered unsafe but useful in certain situations
The server's successful response to a patch-all request
will NOT include any individual records. Instead, the response content will contain
a "meta" object with an "updated" count of updated records.
Examples:
Update one dog:
PATCH /dogs/1/
{
'fur': 'white'
}
Update many dogs by ID:
PATCH /dogs/
[
{'id': 1, 'fur': 'white'},
{'id': 2, 'fur': 'black'},
{'id': 3, 'fur': 'yellow'}
]
Update all dogs in a query:
PATCH /dogs/?filter{fur.contains}=brown&patch-all=true
{
'fur': 'gold'
} | [
"Update",
"one",
"or",
"more",
"model",
"instances",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L514-L598 | train | 199,706 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | DynamicModelViewSet.create | def create(self, request, *args, **kwargs):
"""
Either create a single or many model instances in bulk
using the Serializer's many=True ability from Django REST >= 2.2.5.
The data can be represented by the serializer name (single or plural
forms), dict or list.
Examples:
POST /dogs/
{
"name": "Fido",
"age": 2
}
POST /dogs/
{
"dog": {
"name": "Lucky",
"age": 3
}
}
POST /dogs/
{
"dogs": [
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
]
}
POST /dogs/
[
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
]
"""
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._create_many(bulk_payload)
return super(DynamicModelViewSet, self).create(
request, *args, **kwargs) | python | def create(self, request, *args, **kwargs):
"""
Either create a single or many model instances in bulk
using the Serializer's many=True ability from Django REST >= 2.2.5.
The data can be represented by the serializer name (single or plural
forms), dict or list.
Examples:
POST /dogs/
{
"name": "Fido",
"age": 2
}
POST /dogs/
{
"dog": {
"name": "Lucky",
"age": 3
}
}
POST /dogs/
{
"dogs": [
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
]
}
POST /dogs/
[
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
]
"""
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._create_many(bulk_payload)
return super(DynamicModelViewSet, self).create(
request, *args, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bulk_payload",
"=",
"self",
".",
"_get_bulk_payload",
"(",
"request",
")",
"if",
"bulk_payload",
":",
"return",
"self",
".",
"_create_many",
"(",
"bulk_pa... | Either create a single or many model instances in bulk
using the Serializer's many=True ability from Django REST >= 2.2.5.
The data can be represented by the serializer name (single or plural
forms), dict or list.
Examples:
POST /dogs/
{
"name": "Fido",
"age": 2
}
POST /dogs/
{
"dog": {
"name": "Lucky",
"age": 3
}
}
POST /dogs/
{
"dogs": [
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
]
}
POST /dogs/
[
{"name": "Fido", "age": 2},
{"name": "Lucky", "age": 3}
] | [
"Either",
"create",
"a",
"single",
"or",
"many",
"model",
"instances",
"in",
"bulk",
"using",
"the",
"Serializer",
"s",
"many",
"=",
"True",
"ability",
"from",
"Django",
"REST",
">",
"=",
"2",
".",
"2",
".",
"5",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L643-L685 | train | 199,707 |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | DynamicModelViewSet.destroy | def destroy(self, request, *args, **kwargs):
"""
Either delete a single or many model instances in bulk
DELETE /dogs/
{
"dogs": [
{"id": 1},
{"id": 2}
]
}
DELETE /dogs/
[
{"id": 1},
{"id": 2}
]
"""
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._destroy_many(bulk_payload)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in kwargs:
# assume that it is a poorly formatted bulk request
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super(DynamicModelViewSet, self).destroy(
request, *args, **kwargs
) | python | def destroy(self, request, *args, **kwargs):
"""
Either delete a single or many model instances in bulk
DELETE /dogs/
{
"dogs": [
{"id": 1},
{"id": 2}
]
}
DELETE /dogs/
[
{"id": 1},
{"id": 2}
]
"""
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._destroy_many(bulk_payload)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in kwargs:
# assume that it is a poorly formatted bulk request
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
return super(DynamicModelViewSet, self).destroy(
request, *args, **kwargs
) | [
"def",
"destroy",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bulk_payload",
"=",
"self",
".",
"_get_bulk_payload",
"(",
"request",
")",
"if",
"bulk_payload",
":",
"return",
"self",
".",
"_destroy_many",
"(",
"bulk_... | Either delete a single or many model instances in bulk
DELETE /dogs/
{
"dogs": [
{"id": 1},
{"id": 2}
]
}
DELETE /dogs/
[
{"id": 1},
{"id": 2}
] | [
"Either",
"delete",
"a",
"single",
"or",
"many",
"model",
"instances",
"in",
"bulk"
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L696-L723 | train | 199,708 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithResourceKeyMixin.get_resource_key | def get_resource_key(self):
"""Return canonical resource key, usually the DB table name."""
model = self.get_model()
if model:
return get_model_table(model)
else:
return self.get_name() | python | def get_resource_key(self):
"""Return canonical resource key, usually the DB table name."""
model = self.get_model()
if model:
return get_model_table(model)
else:
return self.get_name() | [
"def",
"get_resource_key",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"get_model",
"(",
")",
"if",
"model",
":",
"return",
"get_model_table",
"(",
"model",
")",
"else",
":",
"return",
"self",
".",
"get_name",
"(",
")"
] | Return canonical resource key, usually the DB table name. | [
"Return",
"canonical",
"resource",
"key",
"usually",
"the",
"DB",
"table",
"name",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L40-L46 | train | 199,709 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | DynamicListSerializer.data | def data(self):
"""Get the data, after performing post-processing if necessary."""
data = super(DynamicListSerializer, self).data
processed_data = ReturnDict(
SideloadingProcessor(self, data).data,
serializer=self
) if self.child.envelope else ReturnList(
data,
serializer=self
)
processed_data = post_process(processed_data)
return processed_data | python | def data(self):
"""Get the data, after performing post-processing if necessary."""
data = super(DynamicListSerializer, self).data
processed_data = ReturnDict(
SideloadingProcessor(self, data).data,
serializer=self
) if self.child.envelope else ReturnList(
data,
serializer=self
)
processed_data = post_process(processed_data)
return processed_data | [
"def",
"data",
"(",
"self",
")",
":",
"data",
"=",
"super",
"(",
"DynamicListSerializer",
",",
"self",
")",
".",
"data",
"processed_data",
"=",
"ReturnDict",
"(",
"SideloadingProcessor",
"(",
"self",
",",
"data",
")",
".",
"data",
",",
"serializer",
"=",
... | Get the data, after performing post-processing if necessary. | [
"Get",
"the",
"data",
"after",
"performing",
"post",
"-",
"processing",
"if",
"necessary",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L88-L99 | train | 199,710 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin._dynamic_init | def _dynamic_init(self, only_fields, include_fields, exclude_fields):
"""
Modifies `request_fields` via higher-level dynamic field interfaces.
Arguments:
only_fields: List of field names to render.
All other fields will be deferred (respects sideloads).
include_fields: List of field names to include.
Adds to default field set, (respects sideloads).
`*` means include all fields.
exclude_fields: List of field names to exclude.
Removes from default field set. If set to '*', all fields are
removed, except for ones that are explicitly included.
"""
if not self.dynamic:
return
if (isinstance(self.request_fields, dict) and
self.request_fields.pop('*', None) is False):
exclude_fields = '*'
only_fields = set(only_fields or [])
include_fields = include_fields or []
exclude_fields = exclude_fields or []
if only_fields:
exclude_fields = '*'
include_fields = only_fields
if exclude_fields == '*':
# First exclude all, then add back in explicitly included fields.
include_fields = set(
list(include_fields) + [
field for field, val in six.iteritems(self.request_fields)
if val or val == {}
]
)
all_fields = set(self.get_all_fields().keys()) # this is slow
exclude_fields = all_fields - include_fields
elif include_fields == '*':
all_fields = set(self.get_all_fields().keys()) # this is slow
include_fields = all_fields
for name in exclude_fields:
self.request_fields[name] = False
for name in include_fields:
if not isinstance(self.request_fields.get(name), dict):
# not sideloading this field
self.request_fields[name] = True | python | def _dynamic_init(self, only_fields, include_fields, exclude_fields):
"""
Modifies `request_fields` via higher-level dynamic field interfaces.
Arguments:
only_fields: List of field names to render.
All other fields will be deferred (respects sideloads).
include_fields: List of field names to include.
Adds to default field set, (respects sideloads).
`*` means include all fields.
exclude_fields: List of field names to exclude.
Removes from default field set. If set to '*', all fields are
removed, except for ones that are explicitly included.
"""
if not self.dynamic:
return
if (isinstance(self.request_fields, dict) and
self.request_fields.pop('*', None) is False):
exclude_fields = '*'
only_fields = set(only_fields or [])
include_fields = include_fields or []
exclude_fields = exclude_fields or []
if only_fields:
exclude_fields = '*'
include_fields = only_fields
if exclude_fields == '*':
# First exclude all, then add back in explicitly included fields.
include_fields = set(
list(include_fields) + [
field for field, val in six.iteritems(self.request_fields)
if val or val == {}
]
)
all_fields = set(self.get_all_fields().keys()) # this is slow
exclude_fields = all_fields - include_fields
elif include_fields == '*':
all_fields = set(self.get_all_fields().keys()) # this is slow
include_fields = all_fields
for name in exclude_fields:
self.request_fields[name] = False
for name in include_fields:
if not isinstance(self.request_fields.get(name), dict):
# not sideloading this field
self.request_fields[name] = True | [
"def",
"_dynamic_init",
"(",
"self",
",",
"only_fields",
",",
"include_fields",
",",
"exclude_fields",
")",
":",
"if",
"not",
"self",
".",
"dynamic",
":",
"return",
"if",
"(",
"isinstance",
"(",
"self",
".",
"request_fields",
",",
"dict",
")",
"and",
"self... | Modifies `request_fields` via higher-level dynamic field interfaces.
Arguments:
only_fields: List of field names to render.
All other fields will be deferred (respects sideloads).
include_fields: List of field names to include.
Adds to default field set, (respects sideloads).
`*` means include all fields.
exclude_fields: List of field names to exclude.
Removes from default field set. If set to '*', all fields are
removed, except for ones that are explicitly included. | [
"Modifies",
"request_fields",
"via",
"higher",
"-",
"level",
"dynamic",
"field",
"interfaces",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L269-L319 | train | 199,711 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin.get_name | def get_name(cls):
"""Get the serializer name.
The name can be defined on the Meta class or will be generated
automatically from the model name.
"""
if not hasattr(cls.Meta, 'name'):
class_name = getattr(cls.get_model(), '__name__', None)
setattr(
cls.Meta,
'name',
inflection.underscore(class_name) if class_name else None
)
return cls.Meta.name | python | def get_name(cls):
"""Get the serializer name.
The name can be defined on the Meta class or will be generated
automatically from the model name.
"""
if not hasattr(cls.Meta, 'name'):
class_name = getattr(cls.get_model(), '__name__', None)
setattr(
cls.Meta,
'name',
inflection.underscore(class_name) if class_name else None
)
return cls.Meta.name | [
"def",
"get_name",
"(",
"cls",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
".",
"Meta",
",",
"'name'",
")",
":",
"class_name",
"=",
"getattr",
"(",
"cls",
".",
"get_model",
"(",
")",
",",
"'__name__'",
",",
"None",
")",
"setattr",
"(",
"cls",
"."... | Get the serializer name.
The name can be defined on the Meta class or will be generated
automatically from the model name. | [
"Get",
"the",
"serializer",
"name",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L330-L344 | train | 199,712 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin.get_plural_name | def get_plural_name(cls):
"""Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned.
"""
if not hasattr(cls.Meta, 'plural_name'):
setattr(
cls.Meta,
'plural_name',
inflection.pluralize(cls.get_name())
)
return cls.Meta.plural_name | python | def get_plural_name(cls):
"""Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned.
"""
if not hasattr(cls.Meta, 'plural_name'):
setattr(
cls.Meta,
'plural_name',
inflection.pluralize(cls.get_name())
)
return cls.Meta.plural_name | [
"def",
"get_plural_name",
"(",
"cls",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
".",
"Meta",
",",
"'plural_name'",
")",
":",
"setattr",
"(",
"cls",
".",
"Meta",
",",
"'plural_name'",
",",
"inflection",
".",
"pluralize",
"(",
"cls",
".",
"get_name",
... | Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned. | [
"Get",
"the",
"serializer",
"s",
"plural",
"name",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L347-L360 | train | 199,713 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin._all_fields | def _all_fields(self):
"""Returns the entire serializer field set.
Does not respect dynamic field inclusions/exclusions.
"""
if (
not settings.ENABLE_FIELDS_CACHE or
not self.ENABLE_FIELDS_CACHE or
self.__class__ not in FIELDS_CACHE
):
all_fields = super(
WithDynamicSerializerMixin,
self
).get_fields()
if (
settings.ENABLE_FIELDS_CACHE and
self.ENABLE_FIELDS_CACHE
):
FIELDS_CACHE[self.__class__] = all_fields
else:
all_fields = copy.copy(FIELDS_CACHE[self.__class__])
for k, field in six.iteritems(all_fields):
if hasattr(field, 'reset'):
field.reset()
for k, field in six.iteritems(all_fields):
field.field_name = k
field.parent = self
return all_fields | python | def _all_fields(self):
"""Returns the entire serializer field set.
Does not respect dynamic field inclusions/exclusions.
"""
if (
not settings.ENABLE_FIELDS_CACHE or
not self.ENABLE_FIELDS_CACHE or
self.__class__ not in FIELDS_CACHE
):
all_fields = super(
WithDynamicSerializerMixin,
self
).get_fields()
if (
settings.ENABLE_FIELDS_CACHE and
self.ENABLE_FIELDS_CACHE
):
FIELDS_CACHE[self.__class__] = all_fields
else:
all_fields = copy.copy(FIELDS_CACHE[self.__class__])
for k, field in six.iteritems(all_fields):
if hasattr(field, 'reset'):
field.reset()
for k, field in six.iteritems(all_fields):
field.field_name = k
field.parent = self
return all_fields | [
"def",
"_all_fields",
"(",
"self",
")",
":",
"if",
"(",
"not",
"settings",
".",
"ENABLE_FIELDS_CACHE",
"or",
"not",
"self",
".",
"ENABLE_FIELDS_CACHE",
"or",
"self",
".",
"__class__",
"not",
"in",
"FIELDS_CACHE",
")",
":",
"all_fields",
"=",
"super",
"(",
... | Returns the entire serializer field set.
Does not respect dynamic field inclusions/exclusions. | [
"Returns",
"the",
"entire",
"serializer",
"field",
"set",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L376-L406 | train | 199,714 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin.get_fields | def get_fields(self):
"""Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior.
"""
all_fields = self.get_all_fields()
if self.dynamic is False:
return all_fields
if self.id_only():
return {}
serializer_fields = copy.deepcopy(all_fields)
request_fields = self.request_fields
deferred = self._get_deferred_field_names(serializer_fields)
# apply request overrides
if request_fields:
for name, include in six.iteritems(request_fields):
if name not in serializer_fields:
raise exceptions.ParseError(
'"%s" is not a valid field name for "%s".' %
(name, self.get_name())
)
if include is not False and name in deferred:
deferred.remove(name)
elif include is False:
deferred.add(name)
for name in deferred:
serializer_fields.pop(name)
# Set read_only flags based on read_only_fields meta list.
# Here to cover DynamicFields not covered by DRF.
ro_fields = getattr(self.Meta, 'read_only_fields', [])
self.flag_fields(serializer_fields, ro_fields, 'read_only', True)
pw_fields = getattr(self.Meta, 'untrimmed_fields', [])
self.flag_fields(
serializer_fields,
pw_fields,
'trim_whitespace',
False,
)
# Toggle read_only flags for immutable fields.
# Note: This overrides `read_only` if both are set, to allow
# inferred DRF fields to be made immutable.
immutable_field_names = self._get_flagged_field_names(
serializer_fields,
'immutable'
)
self.flag_fields(
serializer_fields,
immutable_field_names,
'read_only',
value=False if self.get_request_method() == 'POST' else True
)
return serializer_fields | python | def get_fields(self):
"""Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior.
"""
all_fields = self.get_all_fields()
if self.dynamic is False:
return all_fields
if self.id_only():
return {}
serializer_fields = copy.deepcopy(all_fields)
request_fields = self.request_fields
deferred = self._get_deferred_field_names(serializer_fields)
# apply request overrides
if request_fields:
for name, include in six.iteritems(request_fields):
if name not in serializer_fields:
raise exceptions.ParseError(
'"%s" is not a valid field name for "%s".' %
(name, self.get_name())
)
if include is not False and name in deferred:
deferred.remove(name)
elif include is False:
deferred.add(name)
for name in deferred:
serializer_fields.pop(name)
# Set read_only flags based on read_only_fields meta list.
# Here to cover DynamicFields not covered by DRF.
ro_fields = getattr(self.Meta, 'read_only_fields', [])
self.flag_fields(serializer_fields, ro_fields, 'read_only', True)
pw_fields = getattr(self.Meta, 'untrimmed_fields', [])
self.flag_fields(
serializer_fields,
pw_fields,
'trim_whitespace',
False,
)
# Toggle read_only flags for immutable fields.
# Note: This overrides `read_only` if both are set, to allow
# inferred DRF fields to be made immutable.
immutable_field_names = self._get_flagged_field_names(
serializer_fields,
'immutable'
)
self.flag_fields(
serializer_fields,
immutable_field_names,
'read_only',
value=False if self.get_request_method() == 'POST' else True
)
return serializer_fields | [
"def",
"get_fields",
"(",
"self",
")",
":",
"all_fields",
"=",
"self",
".",
"get_all_fields",
"(",
")",
"if",
"self",
".",
"dynamic",
"is",
"False",
":",
"return",
"all_fields",
"if",
"self",
".",
"id_only",
"(",
")",
":",
"return",
"{",
"}",
"serializ... | Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior. | [
"Returns",
"the",
"serializer",
"s",
"field",
"set",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L449-L509 | train | 199,715 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin._faster_to_representation | def _faster_to_representation(self, instance):
"""Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists in DRF 3.2 but not 3.1)
Arguments:
instance: a model instance or data object
Returns:
Dict of primitive datatypes.
"""
ret = {}
fields = self._readable_fields
is_fast = isinstance(instance, prefetch.FastObject)
id_fields = self._readable_id_fields
for field in fields:
attribute = None
# we exclude dynamic fields here because the proper fastquery
# dereferencing happens in the `get_attribute` method now
if (
is_fast and
not isinstance(
field,
(DynamicGenericRelationField, DynamicRelationField)
)
):
if field in id_fields and field.source not in instance:
# TODO - make better.
attribute = instance.get(field.source + '_id')
ret[field.field_name] = attribute
continue
else:
try:
attribute = instance[field.source]
except KeyError:
# slower, but does more stuff
# Also, some temp debugging
if hasattr(instance, field.source):
attribute = getattr(instance, field.source)
else:
# Fall back on DRF behavior
attribute = field.get_attribute(instance)
print(
'Missing %s from %s' % (
field.field_name,
self.__class__.__name__
)
)
else:
try:
attribute = field.get_attribute(instance)
except SkipField:
continue
if attribute is None:
# We skip `to_representation` for `None` values so that
# fields do not have to explicitly deal with that case.
ret[field.field_name] = None
else:
ret[field.field_name] = field.to_representation(attribute)
return ret | python | def _faster_to_representation(self, instance):
"""Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists in DRF 3.2 but not 3.1)
Arguments:
instance: a model instance or data object
Returns:
Dict of primitive datatypes.
"""
ret = {}
fields = self._readable_fields
is_fast = isinstance(instance, prefetch.FastObject)
id_fields = self._readable_id_fields
for field in fields:
attribute = None
# we exclude dynamic fields here because the proper fastquery
# dereferencing happens in the `get_attribute` method now
if (
is_fast and
not isinstance(
field,
(DynamicGenericRelationField, DynamicRelationField)
)
):
if field in id_fields and field.source not in instance:
# TODO - make better.
attribute = instance.get(field.source + '_id')
ret[field.field_name] = attribute
continue
else:
try:
attribute = instance[field.source]
except KeyError:
# slower, but does more stuff
# Also, some temp debugging
if hasattr(instance, field.source):
attribute = getattr(instance, field.source)
else:
# Fall back on DRF behavior
attribute = field.get_attribute(instance)
print(
'Missing %s from %s' % (
field.field_name,
self.__class__.__name__
)
)
else:
try:
attribute = field.get_attribute(instance)
except SkipField:
continue
if attribute is None:
# We skip `to_representation` for `None` values so that
# fields do not have to explicitly deal with that case.
ret[field.field_name] = None
else:
ret[field.field_name] = field.to_representation(attribute)
return ret | [
"def",
"_faster_to_representation",
"(",
"self",
",",
"instance",
")",
":",
"ret",
"=",
"{",
"}",
"fields",
"=",
"self",
".",
"_readable_fields",
"is_fast",
"=",
"isinstance",
"(",
"instance",
",",
"prefetch",
".",
"FastObject",
")",
"id_fields",
"=",
"self"... | Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists in DRF 3.2 but not 3.1)
Arguments:
instance: a model instance or data object
Returns:
Dict of primitive datatypes. | [
"Modified",
"to_representation",
"with",
"optimizations",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L567-L634 | train | 199,716 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin._to_representation | def _to_representation(self, instance):
"""Uncached `to_representation`."""
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
).to_representation(instance)
if settings.ENABLE_LINKS:
# TODO: Make this function configurable to support other
# formats like JSON API link objects.
representation = merge_link_object(
self, representation, instance
)
if self.debug:
representation['_meta'] = {
'id': instance.pk,
'type': self.get_plural_name()
}
# tag the representation with the serializer and instance
return tag_dict(
representation,
serializer=self,
instance=instance,
embed=self.embed
) | python | def _to_representation(self, instance):
"""Uncached `to_representation`."""
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
).to_representation(instance)
if settings.ENABLE_LINKS:
# TODO: Make this function configurable to support other
# formats like JSON API link objects.
representation = merge_link_object(
self, representation, instance
)
if self.debug:
representation['_meta'] = {
'id': instance.pk,
'type': self.get_plural_name()
}
# tag the representation with the serializer and instance
return tag_dict(
representation,
serializer=self,
instance=instance,
embed=self.embed
) | [
"def",
"_to_representation",
"(",
"self",
",",
"instance",
")",
":",
"if",
"self",
".",
"enable_optimization",
":",
"representation",
"=",
"self",
".",
"_faster_to_representation",
"(",
"instance",
")",
"else",
":",
"representation",
"=",
"super",
"(",
"WithDyna... | Uncached `to_representation`. | [
"Uncached",
"to_representation",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L642-L672 | train | 199,717 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin.to_representation | def to_representation(self, instance):
"""Modified to_representation method. Optionally may cache objects.
Arguments:
instance: A model instance or data object.
Returns:
Instance ID if the serializer is meant to represent its ID.
Otherwise, a tagged data dict representation.
"""
if self.id_only():
return instance.pk
pk = getattr(instance, 'pk', None)
if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None:
return self._to_representation(instance)
else:
if pk not in self.obj_cache:
self.obj_cache[pk] = self._to_representation(instance)
return self.obj_cache[pk] | python | def to_representation(self, instance):
"""Modified to_representation method. Optionally may cache objects.
Arguments:
instance: A model instance or data object.
Returns:
Instance ID if the serializer is meant to represent its ID.
Otherwise, a tagged data dict representation.
"""
if self.id_only():
return instance.pk
pk = getattr(instance, 'pk', None)
if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None:
return self._to_representation(instance)
else:
if pk not in self.obj_cache:
self.obj_cache[pk] = self._to_representation(instance)
return self.obj_cache[pk] | [
"def",
"to_representation",
"(",
"self",
",",
"instance",
")",
":",
"if",
"self",
".",
"id_only",
"(",
")",
":",
"return",
"instance",
".",
"pk",
"pk",
"=",
"getattr",
"(",
"instance",
",",
"'pk'",
",",
"None",
")",
"if",
"not",
"settings",
".",
"ENA... | Modified to_representation method. Optionally may cache objects.
Arguments:
instance: A model instance or data object.
Returns:
Instance ID if the serializer is meant to represent its ID.
Otherwise, a tagged data dict representation. | [
"Modified",
"to_representation",
"method",
".",
"Optionally",
"may",
"cache",
"objects",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L674-L692 | train | 199,718 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | WithDynamicSerializerMixin.save | def save(self, *args, **kwargs):
"""Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None
instance = super(
WithDynamicSerializerMixin,
self
).save(
*args,
**kwargs
)
view = self._context.get('view')
if view and update:
if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5:
# Reload the object on update
# to get around prefetch cache issues
# Fixed in DRF in 3.5.0
instance = self.instance = view.get_object()
return instance | python | def save(self, *args, **kwargs):
"""Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None
instance = super(
WithDynamicSerializerMixin,
self
).save(
*args,
**kwargs
)
view = self._context.get('view')
if view and update:
if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5:
# Reload the object on update
# to get around prefetch cache issues
# Fixed in DRF in 3.5.0
instance = self.instance = view.get_object()
return instance | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"update",
"=",
"getattr",
"(",
"self",
",",
"'instance'",
",",
"None",
")",
"is",
"not",
"None",
"instance",
"=",
"super",
"(",
"WithDynamicSerializerMixin",
",",
"self",
... | Serializer save that address prefetch issues. | [
"Serializer",
"save",
"that",
"address",
"prefetch",
"issues",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L710-L727 | train | 199,719 |
AltSchool/dynamic-rest | dynamic_rest/serializers.py | DynamicEphemeralSerializer.to_representation | def to_representation(self, instance):
"""
Provides post processing. Sub-classes should implement their own
to_representation method, but pass the resulting dict through
this function to get tagging and field selection.
Arguments:
instance: Serialized dict, or object. If object,
it will be serialized by the super class's
to_representation() method.
"""
if not isinstance(instance, dict):
data = super(
DynamicEphemeralSerializer,
self
).to_representation(instance)
else:
data = instance
instance = EphemeralObject(data)
if self.id_only():
return data
else:
return tag_dict(data, serializer=self, instance=instance) | python | def to_representation(self, instance):
"""
Provides post processing. Sub-classes should implement their own
to_representation method, but pass the resulting dict through
this function to get tagging and field selection.
Arguments:
instance: Serialized dict, or object. If object,
it will be serialized by the super class's
to_representation() method.
"""
if not isinstance(instance, dict):
data = super(
DynamicEphemeralSerializer,
self
).to_representation(instance)
else:
data = instance
instance = EphemeralObject(data)
if self.id_only():
return data
else:
return tag_dict(data, serializer=self, instance=instance) | [
"def",
"to_representation",
"(",
"self",
",",
"instance",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"dict",
")",
":",
"data",
"=",
"super",
"(",
"DynamicEphemeralSerializer",
",",
"self",
")",
".",
"to_representation",
"(",
"instance",
")",
... | Provides post processing. Sub-classes should implement their own
to_representation method, but pass the resulting dict through
this function to get tagging and field selection.
Arguments:
instance: Serialized dict, or object. If object,
it will be serialized by the super class's
to_representation() method. | [
"Provides",
"post",
"processing",
".",
"Sub",
"-",
"classes",
"should",
"implement",
"their",
"own",
"to_representation",
"method",
"but",
"pass",
"the",
"resulting",
"dict",
"through",
"this",
"function",
"to",
"get",
"tagging",
"and",
"field",
"selection",
"."... | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L813-L837 | train | 199,720 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | get_directory | def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
def sort_key(r):
return r[0]
# TODO(ant): support arbitrarily nested
# structure, for now it is capped at a single level
# for UX reasons
for group_name, endpoints in sorted(
six.iteritems(directory),
key=sort_key
):
endpoints_list = []
for endpoint_name, endpoint in sorted(
six.iteritems(endpoints),
key=sort_key
):
if endpoint_name[:1] == '_':
continue
endpoint_url = get_url(endpoint.get('_url', None))
active = is_active_url(path, endpoint_url)
endpoints_list.append(
(endpoint_name, endpoint_url, [], active)
)
url = get_url(endpoints.get('_url', None))
active = is_active_url(path, url)
directory_list.append(
(group_name, url, endpoints_list, active)
)
return directory_list | python | def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
def sort_key(r):
return r[0]
# TODO(ant): support arbitrarily nested
# structure, for now it is capped at a single level
# for UX reasons
for group_name, endpoints in sorted(
six.iteritems(directory),
key=sort_key
):
endpoints_list = []
for endpoint_name, endpoint in sorted(
six.iteritems(endpoints),
key=sort_key
):
if endpoint_name[:1] == '_':
continue
endpoint_url = get_url(endpoint.get('_url', None))
active = is_active_url(path, endpoint_url)
endpoints_list.append(
(endpoint_name, endpoint_url, [], active)
)
url = get_url(endpoints.get('_url', None))
active = is_active_url(path, url)
directory_list.append(
(group_name, url, endpoints_list, active)
)
return directory_list | [
"def",
"get_directory",
"(",
"request",
")",
":",
"def",
"get_url",
"(",
"url",
")",
":",
"return",
"reverse",
"(",
"url",
",",
"request",
"=",
"request",
")",
"if",
"url",
"else",
"url",
"def",
"is_active_url",
"(",
"path",
",",
"url",
")",
":",
"re... | Get API directory as a nested list of lists. | [
"Get",
"API",
"directory",
"as",
"a",
"nested",
"list",
"of",
"lists",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L25-L65 | train | 199,721 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.get_api_root_view | def get_api_root_view(self, **kwargs):
"""Return API root view, using the global directory."""
class API(views.APIView):
_ignore_model_permissions = True
def get(self, request, *args, **kwargs):
directory_list = get_directory(request)
result = OrderedDict()
for group_name, url, endpoints, _ in directory_list:
if url:
result[group_name] = url
else:
group = OrderedDict()
for endpoint_name, url, _, _ in endpoints:
group[endpoint_name] = url
result[group_name] = group
return Response(result)
return API.as_view() | python | def get_api_root_view(self, **kwargs):
"""Return API root view, using the global directory."""
class API(views.APIView):
_ignore_model_permissions = True
def get(self, request, *args, **kwargs):
directory_list = get_directory(request)
result = OrderedDict()
for group_name, url, endpoints, _ in directory_list:
if url:
result[group_name] = url
else:
group = OrderedDict()
for endpoint_name, url, _, _ in endpoints:
group[endpoint_name] = url
result[group_name] = group
return Response(result)
return API.as_view() | [
"def",
"get_api_root_view",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"API",
"(",
"views",
".",
"APIView",
")",
":",
"_ignore_model_permissions",
"=",
"True",
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
... | Return API root view, using the global directory. | [
"Return",
"API",
"root",
"view",
"using",
"the",
"global",
"directory",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L88-L106 | train | 199,722 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.register | def register(self, prefix, viewset, base_name=None):
"""Add any registered route into a global API directory.
If the prefix includes a path separator,
store the URL in the directory under the first path segment.
Otherwise, store it as-is.
For example, if there are two registered prefixes,
'v1/users' and 'groups', `directory` will look liks:
{
'v1': {
'users': {
'_url': 'users-list'
'_viewset': <class 'UserViewSet'>
},
}
'groups': {
'_url': 'groups-list'
'_viewset': <class 'GroupViewSet'>
}
}
"""
if base_name is None:
base_name = prefix
super(DynamicRouter, self).register(prefix, viewset, base_name)
prefix_parts = prefix.split('/')
if len(prefix_parts) > 1:
prefix = prefix_parts[0]
endpoint = '/'.join(prefix_parts[1:])
else:
endpoint = prefix
prefix = None
if prefix and prefix not in directory:
current = directory[prefix] = {}
else:
current = directory.get(prefix, directory)
list_name = self.routes[0].name
url_name = list_name.format(basename=base_name)
if endpoint not in current:
current[endpoint] = {}
current[endpoint]['_url'] = url_name
current[endpoint]['_viewset'] = viewset | python | def register(self, prefix, viewset, base_name=None):
"""Add any registered route into a global API directory.
If the prefix includes a path separator,
store the URL in the directory under the first path segment.
Otherwise, store it as-is.
For example, if there are two registered prefixes,
'v1/users' and 'groups', `directory` will look liks:
{
'v1': {
'users': {
'_url': 'users-list'
'_viewset': <class 'UserViewSet'>
},
}
'groups': {
'_url': 'groups-list'
'_viewset': <class 'GroupViewSet'>
}
}
"""
if base_name is None:
base_name = prefix
super(DynamicRouter, self).register(prefix, viewset, base_name)
prefix_parts = prefix.split('/')
if len(prefix_parts) > 1:
prefix = prefix_parts[0]
endpoint = '/'.join(prefix_parts[1:])
else:
endpoint = prefix
prefix = None
if prefix and prefix not in directory:
current = directory[prefix] = {}
else:
current = directory.get(prefix, directory)
list_name = self.routes[0].name
url_name = list_name.format(basename=base_name)
if endpoint not in current:
current[endpoint] = {}
current[endpoint]['_url'] = url_name
current[endpoint]['_viewset'] = viewset | [
"def",
"register",
"(",
"self",
",",
"prefix",
",",
"viewset",
",",
"base_name",
"=",
"None",
")",
":",
"if",
"base_name",
"is",
"None",
":",
"base_name",
"=",
"prefix",
"super",
"(",
"DynamicRouter",
",",
"self",
")",
".",
"register",
"(",
"prefix",
"... | Add any registered route into a global API directory.
If the prefix includes a path separator,
store the URL in the directory under the first path segment.
Otherwise, store it as-is.
For example, if there are two registered prefixes,
'v1/users' and 'groups', `directory` will look liks:
{
'v1': {
'users': {
'_url': 'users-list'
'_viewset': <class 'UserViewSet'>
},
}
'groups': {
'_url': 'groups-list'
'_viewset': <class 'GroupViewSet'>
}
} | [
"Add",
"any",
"registered",
"route",
"into",
"a",
"global",
"API",
"directory",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L108-L154 | train | 199,723 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.register_resource | def register_resource(self, viewset, namespace=None):
"""
Register a viewset that should be considered the canonical
endpoint for a particular resource. In addition to generating
and registering the route, it adds the route in a reverse map
to allow DREST to build the canonical URL for a given resource.
Arguments:
viewset - viewset class, should have `serializer_class` attr.
namespace - (optional) URL namespace, e.g. 'v3'.
"""
# Try to extract resource name from viewset.
try:
serializer = viewset.serializer_class()
resource_key = serializer.get_resource_key()
resource_name = serializer.get_name()
path_name = serializer.get_plural_name()
except:
import traceback
traceback.print_exc()
raise Exception(
"Failed to extract resource name from viewset: '%s'."
" It, or its serializer, may not be DREST-compatible." % (
viewset
)
)
# Construct canonical path and register it.
if namespace:
namespace = namespace.rstrip('/') + '/'
base_path = namespace or ''
base_path = r'%s' % base_path + path_name
self.register(base_path, viewset)
# Make sure resource isn't already registered.
if resource_key in resource_map:
raise Exception(
"The resource '%s' has already been mapped to '%s'."
" Each resource can only be mapped to one canonical"
" path. " % (
resource_key,
resource_map[resource_key]['path']
)
)
# Register resource in reverse map.
resource_map[resource_key] = {
'path': base_path,
'viewset': viewset
}
# Make sure the resource name isn't registered, either
# TODO: Think of a better way to clean this up, there's a lot of
# duplicated effort here, between `resource_name` and `resource_key`
# This resource name -> key mapping is currently only used by
# the DynamicGenericRelationField
if resource_name in resource_name_map:
resource_key = resource_name_map[resource_name]
raise Exception(
"The resource name '%s' has already been mapped to '%s'."
" A resource name can only be used once." % (
resource_name,
resource_map[resource_key]['path']
)
)
# map the resource name to the resource key for easier lookup
resource_name_map[resource_name] = resource_key | python | def register_resource(self, viewset, namespace=None):
"""
Register a viewset that should be considered the canonical
endpoint for a particular resource. In addition to generating
and registering the route, it adds the route in a reverse map
to allow DREST to build the canonical URL for a given resource.
Arguments:
viewset - viewset class, should have `serializer_class` attr.
namespace - (optional) URL namespace, e.g. 'v3'.
"""
# Try to extract resource name from viewset.
try:
serializer = viewset.serializer_class()
resource_key = serializer.get_resource_key()
resource_name = serializer.get_name()
path_name = serializer.get_plural_name()
except:
import traceback
traceback.print_exc()
raise Exception(
"Failed to extract resource name from viewset: '%s'."
" It, or its serializer, may not be DREST-compatible." % (
viewset
)
)
# Construct canonical path and register it.
if namespace:
namespace = namespace.rstrip('/') + '/'
base_path = namespace or ''
base_path = r'%s' % base_path + path_name
self.register(base_path, viewset)
# Make sure resource isn't already registered.
if resource_key in resource_map:
raise Exception(
"The resource '%s' has already been mapped to '%s'."
" Each resource can only be mapped to one canonical"
" path. " % (
resource_key,
resource_map[resource_key]['path']
)
)
# Register resource in reverse map.
resource_map[resource_key] = {
'path': base_path,
'viewset': viewset
}
# Make sure the resource name isn't registered, either
# TODO: Think of a better way to clean this up, there's a lot of
# duplicated effort here, between `resource_name` and `resource_key`
# This resource name -> key mapping is currently only used by
# the DynamicGenericRelationField
if resource_name in resource_name_map:
resource_key = resource_name_map[resource_name]
raise Exception(
"The resource name '%s' has already been mapped to '%s'."
" A resource name can only be used once." % (
resource_name,
resource_map[resource_key]['path']
)
)
# map the resource name to the resource key for easier lookup
resource_name_map[resource_name] = resource_key | [
"def",
"register_resource",
"(",
"self",
",",
"viewset",
",",
"namespace",
"=",
"None",
")",
":",
"# Try to extract resource name from viewset.",
"try",
":",
"serializer",
"=",
"viewset",
".",
"serializer_class",
"(",
")",
"resource_key",
"=",
"serializer",
".",
"... | Register a viewset that should be considered the canonical
endpoint for a particular resource. In addition to generating
and registering the route, it adds the route in a reverse map
to allow DREST to build the canonical URL for a given resource.
Arguments:
viewset - viewset class, should have `serializer_class` attr.
namespace - (optional) URL namespace, e.g. 'v3'. | [
"Register",
"a",
"viewset",
"that",
"should",
"be",
"considered",
"the",
"canonical",
"endpoint",
"for",
"a",
"particular",
"resource",
".",
"In",
"addition",
"to",
"generating",
"and",
"registering",
"the",
"route",
"it",
"adds",
"the",
"route",
"in",
"a",
... | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L156-L224 | train | 199,724 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.get_canonical_path | def get_canonical_path(resource_key, pk=None):
"""
Return canonical resource path.
Arguments:
resource_key - Canonical resource key
i.e. Serializer.get_resource_key().
pk - (Optional) Object's primary key for a single-resource URL.
Returns: Absolute URL as string.
"""
if resource_key not in resource_map:
# Note: Maybe raise?
return None
base_path = get_script_prefix() + resource_map[resource_key]['path']
if pk:
return '%s/%s/' % (base_path, pk)
else:
return base_path | python | def get_canonical_path(resource_key, pk=None):
"""
Return canonical resource path.
Arguments:
resource_key - Canonical resource key
i.e. Serializer.get_resource_key().
pk - (Optional) Object's primary key for a single-resource URL.
Returns: Absolute URL as string.
"""
if resource_key not in resource_map:
# Note: Maybe raise?
return None
base_path = get_script_prefix() + resource_map[resource_key]['path']
if pk:
return '%s/%s/' % (base_path, pk)
else:
return base_path | [
"def",
"get_canonical_path",
"(",
"resource_key",
",",
"pk",
"=",
"None",
")",
":",
"if",
"resource_key",
"not",
"in",
"resource_map",
":",
"# Note: Maybe raise?",
"return",
"None",
"base_path",
"=",
"get_script_prefix",
"(",
")",
"+",
"resource_map",
"[",
"reso... | Return canonical resource path.
Arguments:
resource_key - Canonical resource key
i.e. Serializer.get_resource_key().
pk - (Optional) Object's primary key for a single-resource URL.
Returns: Absolute URL as string. | [
"Return",
"canonical",
"resource",
"path",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L227-L246 | train | 199,725 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.get_canonical_serializer | def get_canonical_serializer(
resource_key,
model=None,
instance=None,
resource_name=None
):
"""
Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object instance.
Returns: serializer class
"""
if model:
resource_key = get_model_table(model)
elif instance:
resource_key = instance._meta.db_table
elif resource_name:
resource_key = resource_name_map[resource_name]
if resource_key not in resource_map:
return None
return resource_map[resource_key]['viewset'].serializer_class | python | def get_canonical_serializer(
resource_key,
model=None,
instance=None,
resource_name=None
):
"""
Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object instance.
Returns: serializer class
"""
if model:
resource_key = get_model_table(model)
elif instance:
resource_key = instance._meta.db_table
elif resource_name:
resource_key = resource_name_map[resource_name]
if resource_key not in resource_map:
return None
return resource_map[resource_key]['viewset'].serializer_class | [
"def",
"get_canonical_serializer",
"(",
"resource_key",
",",
"model",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"resource_name",
"=",
"None",
")",
":",
"if",
"model",
":",
"resource_key",
"=",
"get_model_table",
"(",
"model",
")",
"elif",
"instance",
"... | Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object instance.
Returns: serializer class | [
"Return",
"canonical",
"serializer",
"for",
"a",
"given",
"resource",
"name",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L249-L276 | train | 199,726 |
AltSchool/dynamic-rest | dynamic_rest/routers.py | DynamicRouter.get_relation_routes | def get_relation_routes(self, viewset):
"""
Generate routes to serve relational objects. This method will add
a sub-URL for each relational field.
e.g.
A viewset for the following serializer:
class UserSerializer(..):
events = DynamicRelationField(EventSerializer, many=True)
groups = DynamicRelationField(GroupSerializer, many=True)
location = DynamicRelationField(LocationSerializer)
will have the following URLs added:
/users/<pk>/events/
/users/<pk>/groups/
/users/<pk>/location/
"""
routes = []
if not hasattr(viewset, 'serializer_class'):
return routes
if not hasattr(viewset, 'list_related'):
return routes
serializer = viewset.serializer_class()
fields = getattr(serializer, 'get_link_fields', lambda: [])()
route_name = '{basename}-{methodnamehyphen}'
for field_name, field in six.iteritems(fields):
methodname = 'list_related'
url = (
r'^{prefix}/{lookup}/(?P<field_name>%s)'
'{trailing_slash}$' % field_name
)
routes.append(Route(
url=url,
mapping={'get': methodname},
name=replace_methodname(route_name, field_name),
initkwargs={}
))
return routes | python | def get_relation_routes(self, viewset):
"""
Generate routes to serve relational objects. This method will add
a sub-URL for each relational field.
e.g.
A viewset for the following serializer:
class UserSerializer(..):
events = DynamicRelationField(EventSerializer, many=True)
groups = DynamicRelationField(GroupSerializer, many=True)
location = DynamicRelationField(LocationSerializer)
will have the following URLs added:
/users/<pk>/events/
/users/<pk>/groups/
/users/<pk>/location/
"""
routes = []
if not hasattr(viewset, 'serializer_class'):
return routes
if not hasattr(viewset, 'list_related'):
return routes
serializer = viewset.serializer_class()
fields = getattr(serializer, 'get_link_fields', lambda: [])()
route_name = '{basename}-{methodnamehyphen}'
for field_name, field in six.iteritems(fields):
methodname = 'list_related'
url = (
r'^{prefix}/{lookup}/(?P<field_name>%s)'
'{trailing_slash}$' % field_name
)
routes.append(Route(
url=url,
mapping={'get': methodname},
name=replace_methodname(route_name, field_name),
initkwargs={}
))
return routes | [
"def",
"get_relation_routes",
"(",
"self",
",",
"viewset",
")",
":",
"routes",
"=",
"[",
"]",
"if",
"not",
"hasattr",
"(",
"viewset",
",",
"'serializer_class'",
")",
":",
"return",
"routes",
"if",
"not",
"hasattr",
"(",
"viewset",
",",
"'list_related'",
")... | Generate routes to serve relational objects. This method will add
a sub-URL for each relational field.
e.g.
A viewset for the following serializer:
class UserSerializer(..):
events = DynamicRelationField(EventSerializer, many=True)
groups = DynamicRelationField(GroupSerializer, many=True)
location = DynamicRelationField(LocationSerializer)
will have the following URLs added:
/users/<pk>/events/
/users/<pk>/groups/
/users/<pk>/location/ | [
"Generate",
"routes",
"to",
"serve",
"relational",
"objects",
".",
"This",
"method",
"will",
"add",
"a",
"sub",
"-",
"URL",
"for",
"each",
"relational",
"field",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L287-L331 | train | 199,727 |
AltSchool/dynamic-rest | dynamic_rest/datastructures.py | TreeMap.get_paths | def get_paths(self):
"""Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths.
"""
paths = []
for key, child in six.iteritems(self):
if isinstance(child, TreeMap) and child:
# current child is an intermediate node
for path in child.get_paths():
path.insert(0, key)
paths.append(path)
else:
# current child is an endpoint
paths.append([key])
return paths | python | def get_paths(self):
"""Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths.
"""
paths = []
for key, child in six.iteritems(self):
if isinstance(child, TreeMap) and child:
# current child is an intermediate node
for path in child.get_paths():
path.insert(0, key)
paths.append(path)
else:
# current child is an endpoint
paths.append([key])
return paths | [
"def",
"get_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"key",
",",
"child",
"in",
"six",
".",
"iteritems",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"TreeMap",
")",
"and",
"child",
":",
"# current child is an inte... | Get all paths from the root to the leaves.
For example, given a chain like `{'a':{'b':{'c':None}}}`,
this method would return `[['a', 'b', 'c']]`.
Returns:
A list of lists of paths. | [
"Get",
"all",
"paths",
"from",
"the",
"root",
"to",
"the",
"leaves",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/datastructures.py#L8-L27 | train | 199,728 |
AltSchool/dynamic-rest | dynamic_rest/datastructures.py | TreeMap.insert | def insert(self, parts, leaf_value, update=False):
"""Add a list of nodes into the tree.
The list will be converted into a TreeMap (chain) and then
merged with the current TreeMap.
For example, this method would insert `['a','b','c']` as
`{'a':{'b':{'c':{}}}}`.
Arguments:
parts: List of nodes representing a chain.
leaf_value: Value to insert into the leaf of the chain.
update: Whether or not to update the leaf with the given value or
to replace the value.
Returns:
self
"""
tree = self
if not parts:
return tree
cur = tree
last = len(parts) - 1
for i, part in enumerate(parts):
if part not in cur:
cur[part] = TreeMap() if i != last else leaf_value
elif i == last: # found leaf
if update:
cur[part].update(leaf_value)
else:
cur[part] = leaf_value
cur = cur[part]
return self | python | def insert(self, parts, leaf_value, update=False):
"""Add a list of nodes into the tree.
The list will be converted into a TreeMap (chain) and then
merged with the current TreeMap.
For example, this method would insert `['a','b','c']` as
`{'a':{'b':{'c':{}}}}`.
Arguments:
parts: List of nodes representing a chain.
leaf_value: Value to insert into the leaf of the chain.
update: Whether or not to update the leaf with the given value or
to replace the value.
Returns:
self
"""
tree = self
if not parts:
return tree
cur = tree
last = len(parts) - 1
for i, part in enumerate(parts):
if part not in cur:
cur[part] = TreeMap() if i != last else leaf_value
elif i == last: # found leaf
if update:
cur[part].update(leaf_value)
else:
cur[part] = leaf_value
cur = cur[part]
return self | [
"def",
"insert",
"(",
"self",
",",
"parts",
",",
"leaf_value",
",",
"update",
"=",
"False",
")",
":",
"tree",
"=",
"self",
"if",
"not",
"parts",
":",
"return",
"tree",
"cur",
"=",
"tree",
"last",
"=",
"len",
"(",
"parts",
")",
"-",
"1",
"for",
"i... | Add a list of nodes into the tree.
The list will be converted into a TreeMap (chain) and then
merged with the current TreeMap.
For example, this method would insert `['a','b','c']` as
`{'a':{'b':{'c':{}}}}`.
Arguments:
parts: List of nodes representing a chain.
leaf_value: Value to insert into the leaf of the chain.
update: Whether or not to update the leaf with the given value or
to replace the value.
Returns:
self | [
"Add",
"a",
"list",
"of",
"nodes",
"into",
"the",
"tree",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/datastructures.py#L29-L64 | train | 199,729 |
AltSchool/dynamic-rest | dynamic_rest/tagged.py | tag_dict | def tag_dict(obj, *args, **kwargs):
"""Create a TaggedDict instance. Will either be a TaggedOrderedDict
or TaggedPlainDict depending on the type of `obj`."""
if isinstance(obj, OrderedDict):
return _TaggedOrderedDict(obj, *args, **kwargs)
else:
return _TaggedPlainDict(obj, *args, **kwargs) | python | def tag_dict(obj, *args, **kwargs):
"""Create a TaggedDict instance. Will either be a TaggedOrderedDict
or TaggedPlainDict depending on the type of `obj`."""
if isinstance(obj, OrderedDict):
return _TaggedOrderedDict(obj, *args, **kwargs)
else:
return _TaggedPlainDict(obj, *args, **kwargs) | [
"def",
"tag_dict",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"OrderedDict",
")",
":",
"return",
"_TaggedOrderedDict",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":... | Create a TaggedDict instance. Will either be a TaggedOrderedDict
or TaggedPlainDict depending on the type of `obj`. | [
"Create",
"a",
"TaggedDict",
"instance",
".",
"Will",
"either",
"be",
"a",
"TaggedOrderedDict",
"or",
"TaggedPlainDict",
"depending",
"on",
"the",
"type",
"of",
"obj",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/tagged.py#L5-L12 | train | 199,730 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | has_joins | def has_joins(queryset):
"""Return True iff. a queryset includes joins.
If this is the case, it is possible for the queryset
to return duplicate results.
"""
for join in six.itervalues(queryset.query.alias_map):
if join.join_type:
return True
return False | python | def has_joins(queryset):
"""Return True iff. a queryset includes joins.
If this is the case, it is possible for the queryset
to return duplicate results.
"""
for join in six.itervalues(queryset.query.alias_map):
if join.join_type:
return True
return False | [
"def",
"has_joins",
"(",
"queryset",
")",
":",
"for",
"join",
"in",
"six",
".",
"itervalues",
"(",
"queryset",
".",
"query",
".",
"alias_map",
")",
":",
"if",
"join",
".",
"join_type",
":",
"return",
"True",
"return",
"False"
] | Return True iff. a queryset includes joins.
If this is the case, it is possible for the queryset
to return duplicate results. | [
"Return",
"True",
"iff",
".",
"a",
"queryset",
"includes",
"joins",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L29-L38 | train | 199,731 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | FilterNode.generate_query_key | def generate_query_key(self, serializer):
"""Get the key that can be passed to Django's filter method.
To account for serialier field name rewrites, this method
translates serializer field names to model field names
by inspecting `serializer`.
For example, a query like `filter{users.events}` would be
returned as `users__events`.
Arguments:
serializer: A DRF serializer
Returns:
A filter key.
"""
rewritten = []
last = len(self.field) - 1
s = serializer
field = None
for i, field_name in enumerate(self.field):
# Note: .fields can be empty for related serializers that aren't
# sideloaded. Fields that are deferred also won't be present.
# If field name isn't in serializer.fields, get full list from
# get_all_fields() method. This is somewhat expensive, so only do
# this if we have to.
fields = s.fields
if field_name not in fields:
fields = getattr(s, 'get_all_fields', lambda: {})()
if field_name == 'pk':
rewritten.append('pk')
continue
if field_name not in fields:
raise ValidationError(
"Invalid filter field: %s" % field_name
)
field = fields[field_name]
# For remote fields, strip off '_set' for filtering. This is a
# weird Django inconsistency.
model_field_name = field.source or field_name
model_field = get_model_field(s.get_model(), model_field_name)
if isinstance(model_field, RelatedObject):
model_field_name = model_field.field.related_query_name()
# If get_all_fields() was used above, field could be unbound,
# and field.source would be None
rewritten.append(model_field_name)
if i == last:
break
# Recurse into nested field
s = getattr(field, 'serializer', None)
if isinstance(s, serializers.ListSerializer):
s = s.child
if not s:
raise ValidationError(
"Invalid nested filter field: %s" % field_name
)
if self.operator:
rewritten.append(self.operator)
return ('__'.join(rewritten), field) | python | def generate_query_key(self, serializer):
"""Get the key that can be passed to Django's filter method.
To account for serialier field name rewrites, this method
translates serializer field names to model field names
by inspecting `serializer`.
For example, a query like `filter{users.events}` would be
returned as `users__events`.
Arguments:
serializer: A DRF serializer
Returns:
A filter key.
"""
rewritten = []
last = len(self.field) - 1
s = serializer
field = None
for i, field_name in enumerate(self.field):
# Note: .fields can be empty for related serializers that aren't
# sideloaded. Fields that are deferred also won't be present.
# If field name isn't in serializer.fields, get full list from
# get_all_fields() method. This is somewhat expensive, so only do
# this if we have to.
fields = s.fields
if field_name not in fields:
fields = getattr(s, 'get_all_fields', lambda: {})()
if field_name == 'pk':
rewritten.append('pk')
continue
if field_name not in fields:
raise ValidationError(
"Invalid filter field: %s" % field_name
)
field = fields[field_name]
# For remote fields, strip off '_set' for filtering. This is a
# weird Django inconsistency.
model_field_name = field.source or field_name
model_field = get_model_field(s.get_model(), model_field_name)
if isinstance(model_field, RelatedObject):
model_field_name = model_field.field.related_query_name()
# If get_all_fields() was used above, field could be unbound,
# and field.source would be None
rewritten.append(model_field_name)
if i == last:
break
# Recurse into nested field
s = getattr(field, 'serializer', None)
if isinstance(s, serializers.ListSerializer):
s = s.child
if not s:
raise ValidationError(
"Invalid nested filter field: %s" % field_name
)
if self.operator:
rewritten.append(self.operator)
return ('__'.join(rewritten), field) | [
"def",
"generate_query_key",
"(",
"self",
",",
"serializer",
")",
":",
"rewritten",
"=",
"[",
"]",
"last",
"=",
"len",
"(",
"self",
".",
"field",
")",
"-",
"1",
"s",
"=",
"serializer",
"field",
"=",
"None",
"for",
"i",
",",
"field_name",
"in",
"enume... | Get the key that can be passed to Django's filter method.
To account for serialier field name rewrites, this method
translates serializer field names to model field names
by inspecting `serializer`.
For example, a query like `filter{users.events}` would be
returned as `users__events`.
Arguments:
serializer: A DRF serializer
Returns:
A filter key. | [
"Get",
"the",
"key",
"that",
"can",
"be",
"passed",
"to",
"Django",
"s",
"filter",
"method",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L73-L140 | train | 199,732 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend.filter_queryset | def filter_queryset(self, request, queryset, view):
"""Filter the queryset.
This is the main entry-point to this class, and
is called by DRF's list handler.
"""
self.request = request
self.view = view
# enable addition of extra filters (i.e., a Q())
# so custom filters can be added to the queryset without
# running into https://code.djangoproject.com/ticket/18437
# which, without this, would mean that filters added to the queryset
# after this is called may not behave as expected
extra_filters = self.view.get_extra_filters(request)
disable_prefetches = self.view.is_update()
self.DEBUG = settings.DEBUG
return self._build_queryset(
queryset=queryset,
extra_filters=extra_filters,
disable_prefetches=disable_prefetches,
) | python | def filter_queryset(self, request, queryset, view):
"""Filter the queryset.
This is the main entry-point to this class, and
is called by DRF's list handler.
"""
self.request = request
self.view = view
# enable addition of extra filters (i.e., a Q())
# so custom filters can be added to the queryset without
# running into https://code.djangoproject.com/ticket/18437
# which, without this, would mean that filters added to the queryset
# after this is called may not behave as expected
extra_filters = self.view.get_extra_filters(request)
disable_prefetches = self.view.is_update()
self.DEBUG = settings.DEBUG
return self._build_queryset(
queryset=queryset,
extra_filters=extra_filters,
disable_prefetches=disable_prefetches,
) | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"view",
"=",
"view",
"# enable addition of extra filters (i.e., a Q())",
"# so custom filters can be added to the queryset... | Filter the queryset.
This is the main entry-point to this class, and
is called by DRF's list handler. | [
"Filter",
"the",
"queryset",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L179-L203 | train | 199,733 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend._build_implicit_prefetches | def _build_implicit_prefetches(
self,
model,
prefetches,
requirements
):
"""Build a prefetch dictionary based on internal requirements."""
for source, remainder in six.iteritems(requirements):
if not remainder or isinstance(remainder, six.string_types):
# no further requirements to prefetch
continue
related_field = get_model_field(model, source)
related_model = get_related_model(related_field)
queryset = self._build_implicit_queryset(
related_model,
remainder
) if related_model else None
prefetches[source] = self._create_prefetch(
source,
queryset
)
return prefetches | python | def _build_implicit_prefetches(
self,
model,
prefetches,
requirements
):
"""Build a prefetch dictionary based on internal requirements."""
for source, remainder in six.iteritems(requirements):
if not remainder or isinstance(remainder, six.string_types):
# no further requirements to prefetch
continue
related_field = get_model_field(model, source)
related_model = get_related_model(related_field)
queryset = self._build_implicit_queryset(
related_model,
remainder
) if related_model else None
prefetches[source] = self._create_prefetch(
source,
queryset
)
return prefetches | [
"def",
"_build_implicit_prefetches",
"(",
"self",
",",
"model",
",",
"prefetches",
",",
"requirements",
")",
":",
"for",
"source",
",",
"remainder",
"in",
"six",
".",
"iteritems",
"(",
"requirements",
")",
":",
"if",
"not",
"remainder",
"or",
"isinstance",
"... | Build a prefetch dictionary based on internal requirements. | [
"Build",
"a",
"prefetch",
"dictionary",
"based",
"on",
"internal",
"requirements",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L327-L353 | train | 199,734 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend._build_implicit_queryset | def _build_implicit_queryset(self, model, requirements):
"""Build a queryset based on implicit requirements."""
queryset = self._make_model_queryset(model)
prefetches = {}
self._build_implicit_prefetches(
model,
prefetches,
requirements
)
prefetch = prefetches.values()
queryset = queryset.prefetch_related(*prefetch).distinct()
if self.DEBUG:
queryset._using_prefetches = prefetches
return queryset | python | def _build_implicit_queryset(self, model, requirements):
"""Build a queryset based on implicit requirements."""
queryset = self._make_model_queryset(model)
prefetches = {}
self._build_implicit_prefetches(
model,
prefetches,
requirements
)
prefetch = prefetches.values()
queryset = queryset.prefetch_related(*prefetch).distinct()
if self.DEBUG:
queryset._using_prefetches = prefetches
return queryset | [
"def",
"_build_implicit_queryset",
"(",
"self",
",",
"model",
",",
"requirements",
")",
":",
"queryset",
"=",
"self",
".",
"_make_model_queryset",
"(",
"model",
")",
"prefetches",
"=",
"{",
"}",
"self",
".",
"_build_implicit_prefetches",
"(",
"model",
",",
"pr... | Build a queryset based on implicit requirements. | [
"Build",
"a",
"queryset",
"based",
"on",
"implicit",
"requirements",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L358-L372 | train | 199,735 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend._build_requested_prefetches | def _build_requested_prefetches(
self,
prefetches,
requirements,
model,
fields,
filters
):
"""Build a prefetch dictionary based on request requirements."""
for name, field in six.iteritems(fields):
original_field = field
if isinstance(field, DynamicRelationField):
field = field.serializer
if isinstance(field, serializers.ListSerializer):
field = field.child
if not isinstance(field, serializers.ModelSerializer):
continue
source = field.source or name
if '.' in source:
raise ValidationError(
'nested relationship values '
'are not supported'
)
if source in prefetches:
# ignore duplicated sources
continue
is_remote = is_field_remote(model, source)
is_id_only = getattr(field, 'id_only', lambda: False)()
if is_id_only and not is_remote:
continue
related_queryset = getattr(original_field, 'queryset', None)
if callable(related_queryset):
related_queryset = related_queryset(field)
source = field.source or name
# Popping the source here (during explicit prefetch construction)
# guarantees that implicitly required prefetches that follow will
# not conflict.
required = requirements.pop(source, None)
prefetch_queryset = self._build_queryset(
serializer=field,
filters=filters.get(name, {}),
queryset=related_queryset,
requirements=required
)
# Note: There can only be one prefetch per source, even
# though there can be multiple fields pointing to
# the same source. This could break in some cases,
# but is mostly an issue on writes when we use all
# fields by default.
prefetches[source] = self._create_prefetch(
source,
prefetch_queryset
)
return prefetches | python | def _build_requested_prefetches(
self,
prefetches,
requirements,
model,
fields,
filters
):
"""Build a prefetch dictionary based on request requirements."""
for name, field in six.iteritems(fields):
original_field = field
if isinstance(field, DynamicRelationField):
field = field.serializer
if isinstance(field, serializers.ListSerializer):
field = field.child
if not isinstance(field, serializers.ModelSerializer):
continue
source = field.source or name
if '.' in source:
raise ValidationError(
'nested relationship values '
'are not supported'
)
if source in prefetches:
# ignore duplicated sources
continue
is_remote = is_field_remote(model, source)
is_id_only = getattr(field, 'id_only', lambda: False)()
if is_id_only and not is_remote:
continue
related_queryset = getattr(original_field, 'queryset', None)
if callable(related_queryset):
related_queryset = related_queryset(field)
source = field.source or name
# Popping the source here (during explicit prefetch construction)
# guarantees that implicitly required prefetches that follow will
# not conflict.
required = requirements.pop(source, None)
prefetch_queryset = self._build_queryset(
serializer=field,
filters=filters.get(name, {}),
queryset=related_queryset,
requirements=required
)
# Note: There can only be one prefetch per source, even
# though there can be multiple fields pointing to
# the same source. This could break in some cases,
# but is mostly an issue on writes when we use all
# fields by default.
prefetches[source] = self._create_prefetch(
source,
prefetch_queryset
)
return prefetches | [
"def",
"_build_requested_prefetches",
"(",
"self",
",",
"prefetches",
",",
"requirements",
",",
"model",
",",
"fields",
",",
"filters",
")",
":",
"for",
"name",
",",
"field",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
":",
"original_field",
"=",
"f... | Build a prefetch dictionary based on request requirements. | [
"Build",
"a",
"prefetch",
"dictionary",
"based",
"on",
"request",
"requirements",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L374-L437 | train | 199,736 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend._get_implicit_requirements | def _get_implicit_requirements(
self,
fields,
requirements
):
"""Extract internal prefetch requirements from serializer fields."""
for name, field in six.iteritems(fields):
source = field.source
# Requires may be manually set on the field -- if not,
# assume the field requires only its source.
requires = getattr(field, 'requires', None) or [source]
for require in requires:
if not require:
# ignore fields with empty source
continue
requirement = require.split('.')
if requirement[-1] == '':
# Change 'a.b.' -> 'a.b.*',
# supporting 'a.b.' for backwards compatibility.
requirement[-1] = '*'
requirements.insert(requirement, TreeMap(), update=True) | python | def _get_implicit_requirements(
self,
fields,
requirements
):
"""Extract internal prefetch requirements from serializer fields."""
for name, field in six.iteritems(fields):
source = field.source
# Requires may be manually set on the field -- if not,
# assume the field requires only its source.
requires = getattr(field, 'requires', None) or [source]
for require in requires:
if not require:
# ignore fields with empty source
continue
requirement = require.split('.')
if requirement[-1] == '':
# Change 'a.b.' -> 'a.b.*',
# supporting 'a.b.' for backwards compatibility.
requirement[-1] = '*'
requirements.insert(requirement, TreeMap(), update=True) | [
"def",
"_get_implicit_requirements",
"(",
"self",
",",
"fields",
",",
"requirements",
")",
":",
"for",
"name",
",",
"field",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
":",
"source",
"=",
"field",
".",
"source",
"# Requires may be manually set on the fie... | Extract internal prefetch requirements from serializer fields. | [
"Extract",
"internal",
"prefetch",
"requirements",
"from",
"serializer",
"fields",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L439-L460 | train | 199,737 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicFilterBackend._build_queryset | def _build_queryset(
self,
serializer=None,
filters=None,
queryset=None,
requirements=None,
extra_filters=None,
disable_prefetches=False,
):
"""Build a queryset that pulls in all data required by this request.
Handles nested prefetching of related data and deferring fields
at the queryset level.
Arguments:
serializer: An optional serializer to use a base for the queryset.
If no serializer is passed, the `get_serializer` method will
be used to initialize the base serializer for the viewset.
filters: An optional TreeMap of nested filters.
queryset: An optional base queryset.
requirements: An optional TreeMap of nested requirements.
"""
is_root_level = False
if not serializer:
serializer = self.view.get_serializer()
is_root_level = True
queryset = self._get_queryset(queryset=queryset, serializer=serializer)
model = getattr(serializer.Meta, 'model', None)
if not model:
return queryset
prefetches = {}
# build a nested Prefetch queryset
# based on request parameters and serializer fields
fields = serializer.fields
if requirements is None:
requirements = TreeMap()
self._get_implicit_requirements(
fields,
requirements
)
if filters is None:
filters = self._get_requested_filters()
# build nested Prefetch queryset
self._build_requested_prefetches(
prefetches,
requirements,
model,
fields,
filters
)
# build remaining prefetches out of internal requirements
# that are not already covered by request requirements
self._build_implicit_prefetches(
model,
prefetches,
requirements
)
# use requirements at this level to limit fields selected
# only do this for GET requests where we are not requesting the
# entire fieldset
if (
'*' not in requirements and
not self.view.is_update() and
not self.view.is_delete()
):
id_fields = getattr(serializer, 'get_id_fields', lambda: [])()
# only include local model fields
only = [
field for field in set(
id_fields + list(requirements.keys())
) if is_model_field(model, field) and
not is_field_remote(model, field)
]
queryset = queryset.only(*only)
# add request filters
query = self._filters_to_query(
includes=filters.get('_include'),
excludes=filters.get('_exclude'),
serializer=serializer
)
# add additional filters specified by calling view
if extra_filters:
query = extra_filters if not query else extra_filters & query
if query:
# Convert internal django ValidationError to
# APIException-based one in order to resolve validation error
# from 500 status code to 400.
try:
queryset = queryset.filter(query)
except InternalValidationError as e:
raise ValidationError(
dict(e) if hasattr(e, 'error_dict') else list(e)
)
except Exception as e:
# Some other Django error in parsing the filter.
# Very likely a bad query, so throw a ValidationError.
err_msg = getattr(e, 'message', '')
raise ValidationError(err_msg)
# A serializer can have this optional function
# to dynamically apply additional filters on
# any queries that will use that serializer
# You could use this to have (for example) different
# serializers for different subsets of a model or to
# implement permissions which work even in sideloads
if hasattr(serializer, 'filter_queryset'):
queryset = self._serializer_filter(
serializer=serializer,
queryset=queryset
)
# add prefetches and remove duplicates if necessary
prefetch = prefetches.values()
if prefetch and not disable_prefetches:
queryset = queryset.prefetch_related(*prefetch)
elif isinstance(queryset, Manager):
queryset = queryset.all()
if has_joins(queryset) or not is_root_level:
queryset = queryset.distinct()
if self.DEBUG:
queryset._using_prefetches = prefetches
return queryset | python | def _build_queryset(
self,
serializer=None,
filters=None,
queryset=None,
requirements=None,
extra_filters=None,
disable_prefetches=False,
):
"""Build a queryset that pulls in all data required by this request.
Handles nested prefetching of related data and deferring fields
at the queryset level.
Arguments:
serializer: An optional serializer to use a base for the queryset.
If no serializer is passed, the `get_serializer` method will
be used to initialize the base serializer for the viewset.
filters: An optional TreeMap of nested filters.
queryset: An optional base queryset.
requirements: An optional TreeMap of nested requirements.
"""
is_root_level = False
if not serializer:
serializer = self.view.get_serializer()
is_root_level = True
queryset = self._get_queryset(queryset=queryset, serializer=serializer)
model = getattr(serializer.Meta, 'model', None)
if not model:
return queryset
prefetches = {}
# build a nested Prefetch queryset
# based on request parameters and serializer fields
fields = serializer.fields
if requirements is None:
requirements = TreeMap()
self._get_implicit_requirements(
fields,
requirements
)
if filters is None:
filters = self._get_requested_filters()
# build nested Prefetch queryset
self._build_requested_prefetches(
prefetches,
requirements,
model,
fields,
filters
)
# build remaining prefetches out of internal requirements
# that are not already covered by request requirements
self._build_implicit_prefetches(
model,
prefetches,
requirements
)
# use requirements at this level to limit fields selected
# only do this for GET requests where we are not requesting the
# entire fieldset
if (
'*' not in requirements and
not self.view.is_update() and
not self.view.is_delete()
):
id_fields = getattr(serializer, 'get_id_fields', lambda: [])()
# only include local model fields
only = [
field for field in set(
id_fields + list(requirements.keys())
) if is_model_field(model, field) and
not is_field_remote(model, field)
]
queryset = queryset.only(*only)
# add request filters
query = self._filters_to_query(
includes=filters.get('_include'),
excludes=filters.get('_exclude'),
serializer=serializer
)
# add additional filters specified by calling view
if extra_filters:
query = extra_filters if not query else extra_filters & query
if query:
# Convert internal django ValidationError to
# APIException-based one in order to resolve validation error
# from 500 status code to 400.
try:
queryset = queryset.filter(query)
except InternalValidationError as e:
raise ValidationError(
dict(e) if hasattr(e, 'error_dict') else list(e)
)
except Exception as e:
# Some other Django error in parsing the filter.
# Very likely a bad query, so throw a ValidationError.
err_msg = getattr(e, 'message', '')
raise ValidationError(err_msg)
# A serializer can have this optional function
# to dynamically apply additional filters on
# any queries that will use that serializer
# You could use this to have (for example) different
# serializers for different subsets of a model or to
# implement permissions which work even in sideloads
if hasattr(serializer, 'filter_queryset'):
queryset = self._serializer_filter(
serializer=serializer,
queryset=queryset
)
# add prefetches and remove duplicates if necessary
prefetch = prefetches.values()
if prefetch and not disable_prefetches:
queryset = queryset.prefetch_related(*prefetch)
elif isinstance(queryset, Manager):
queryset = queryset.all()
if has_joins(queryset) or not is_root_level:
queryset = queryset.distinct()
if self.DEBUG:
queryset._using_prefetches = prefetches
return queryset | [
"def",
"_build_queryset",
"(",
"self",
",",
"serializer",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"queryset",
"=",
"None",
",",
"requirements",
"=",
"None",
",",
"extra_filters",
"=",
"None",
",",
"disable_prefetches",
"=",
"False",
",",
")",
":",
... | Build a queryset that pulls in all data required by this request.
Handles nested prefetching of related data and deferring fields
at the queryset level.
Arguments:
serializer: An optional serializer to use a base for the queryset.
If no serializer is passed, the `get_serializer` method will
be used to initialize the base serializer for the viewset.
filters: An optional TreeMap of nested filters.
queryset: An optional base queryset.
requirements: An optional TreeMap of nested requirements. | [
"Build",
"a",
"queryset",
"that",
"pulls",
"in",
"all",
"data",
"required",
"by",
"this",
"request",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L471-L608 | train | 199,738 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicSortingFilter.filter_queryset | def filter_queryset(self, request, queryset, view):
""""Filter the queryset, applying the ordering.
The `ordering_param` can be overwritten here.
In DRF, the ordering_param is 'ordering', but we support changing it
to allow the viewset to control the parameter.
"""
self.ordering_param = view.SORT
ordering = self.get_ordering(request, queryset, view)
if ordering:
return queryset.order_by(*ordering)
return queryset | python | def filter_queryset(self, request, queryset, view):
""""Filter the queryset, applying the ordering.
The `ordering_param` can be overwritten here.
In DRF, the ordering_param is 'ordering', but we support changing it
to allow the viewset to control the parameter.
"""
self.ordering_param = view.SORT
ordering = self.get_ordering(request, queryset, view)
if ordering:
return queryset.order_by(*ordering)
return queryset | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"self",
".",
"ordering_param",
"=",
"view",
".",
"SORT",
"ordering",
"=",
"self",
".",
"get_ordering",
"(",
"request",
",",
"queryset",
",",
"view",
")",
"if",... | Filter the queryset, applying the ordering.
The `ordering_param` can be overwritten here.
In DRF, the ordering_param is 'ordering', but we support changing it
to allow the viewset to control the parameter. | [
"Filter",
"the",
"queryset",
"applying",
"the",
"ordering",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L646-L659 | train | 199,739 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicSortingFilter.get_ordering | def get_ordering(self, request, queryset, view):
"""Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array.
"""
params = view.get_request_feature(view.SORT)
if params:
fields = [param.strip() for param in params]
valid_ordering, invalid_ordering = self.remove_invalid_fields(
queryset, fields, view
)
# if any of the sort fields are invalid, throw an error.
# else return the ordering
if invalid_ordering:
raise ValidationError(
"Invalid filter field: %s" % invalid_ordering
)
else:
return valid_ordering
# No sorting was included
return self.get_default_ordering(view) | python | def get_ordering(self, request, queryset, view):
"""Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array.
"""
params = view.get_request_feature(view.SORT)
if params:
fields = [param.strip() for param in params]
valid_ordering, invalid_ordering = self.remove_invalid_fields(
queryset, fields, view
)
# if any of the sort fields are invalid, throw an error.
# else return the ordering
if invalid_ordering:
raise ValidationError(
"Invalid filter field: %s" % invalid_ordering
)
else:
return valid_ordering
# No sorting was included
return self.get_default_ordering(view) | [
"def",
"get_ordering",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"params",
"=",
"view",
".",
"get_request_feature",
"(",
"view",
".",
"SORT",
")",
"if",
"params",
":",
"fields",
"=",
"[",
"param",
".",
"strip",
"(",
")",
"f... | Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array. | [
"Return",
"an",
"ordering",
"for",
"a",
"given",
"request",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L661-L684 | train | 199,740 |
AltSchool/dynamic-rest | dynamic_rest/filters.py | DynamicSortingFilter.remove_invalid_fields | def remove_invalid_fields(self, queryset, fields, view):
"""Remove invalid fields from an ordering.
Overwrites the DRF default remove_invalid_fields method to return
both the valid orderings and any invalid orderings.
"""
valid_orderings = []
invalid_orderings = []
# for each field sent down from the query param,
# determine if its valid or invalid
for term in fields:
stripped_term = term.lstrip('-')
# add back the '-' add the end if necessary
reverse_sort_term = '' if len(stripped_term) is len(term) else '-'
ordering = self.ordering_for(stripped_term, view)
if ordering:
valid_orderings.append(reverse_sort_term + ordering)
else:
invalid_orderings.append(term)
return valid_orderings, invalid_orderings | python | def remove_invalid_fields(self, queryset, fields, view):
"""Remove invalid fields from an ordering.
Overwrites the DRF default remove_invalid_fields method to return
both the valid orderings and any invalid orderings.
"""
valid_orderings = []
invalid_orderings = []
# for each field sent down from the query param,
# determine if its valid or invalid
for term in fields:
stripped_term = term.lstrip('-')
# add back the '-' add the end if necessary
reverse_sort_term = '' if len(stripped_term) is len(term) else '-'
ordering = self.ordering_for(stripped_term, view)
if ordering:
valid_orderings.append(reverse_sort_term + ordering)
else:
invalid_orderings.append(term)
return valid_orderings, invalid_orderings | [
"def",
"remove_invalid_fields",
"(",
"self",
",",
"queryset",
",",
"fields",
",",
"view",
")",
":",
"valid_orderings",
"=",
"[",
"]",
"invalid_orderings",
"=",
"[",
"]",
"# for each field sent down from the query param,",
"# determine if its valid or invalid",
"for",
"t... | Remove invalid fields from an ordering.
Overwrites the DRF default remove_invalid_fields method to return
both the valid orderings and any invalid orderings. | [
"Remove",
"invalid",
"fields",
"from",
"an",
"ordering",
"."
] | 5b0338c3dd8bc638d60c3bb92645857c5b89c920 | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/filters.py#L686-L709 | train | 199,741 |
Robpol86/terminaltables | terminaltables/build.py | combine | def combine(line, left, intersect, right):
"""Zip borders between items in `line`.
e.g. ('l', '1', 'c', '2', 'c', '3', 'r')
:param iter line: List to iterate.
:param left: Left border.
:param intersect: Column separator.
:param right: Right border.
:return: Yields combined objects.
"""
# Yield left border.
if left:
yield left
# Yield items with intersect characters.
if intersect:
try:
for j, i in enumerate(line, start=-len(line) + 1):
yield i
if j:
yield intersect
except TypeError: # Generator.
try:
item = next(line)
except StopIteration: # Was empty all along.
pass
else:
while True:
yield item
try:
peek = next(line)
except StopIteration:
break
yield intersect
item = peek
else:
for i in line:
yield i
# Yield right border.
if right:
yield right | python | def combine(line, left, intersect, right):
"""Zip borders between items in `line`.
e.g. ('l', '1', 'c', '2', 'c', '3', 'r')
:param iter line: List to iterate.
:param left: Left border.
:param intersect: Column separator.
:param right: Right border.
:return: Yields combined objects.
"""
# Yield left border.
if left:
yield left
# Yield items with intersect characters.
if intersect:
try:
for j, i in enumerate(line, start=-len(line) + 1):
yield i
if j:
yield intersect
except TypeError: # Generator.
try:
item = next(line)
except StopIteration: # Was empty all along.
pass
else:
while True:
yield item
try:
peek = next(line)
except StopIteration:
break
yield intersect
item = peek
else:
for i in line:
yield i
# Yield right border.
if right:
yield right | [
"def",
"combine",
"(",
"line",
",",
"left",
",",
"intersect",
",",
"right",
")",
":",
"# Yield left border.",
"if",
"left",
":",
"yield",
"left",
"# Yield items with intersect characters.",
"if",
"intersect",
":",
"try",
":",
"for",
"j",
",",
"i",
"in",
"enu... | Zip borders between items in `line`.
e.g. ('l', '1', 'c', '2', 'c', '3', 'r')
:param iter line: List to iterate.
:param left: Left border.
:param intersect: Column separator.
:param right: Right border.
:return: Yields combined objects. | [
"Zip",
"borders",
"between",
"items",
"in",
"line",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/build.py#L6-L49 | train | 199,742 |
Robpol86/terminaltables | terminaltables/build.py | build_row | def build_row(row, left, center, right):
"""Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3', '<'],
]
:param iter row: List of cells for one row.
:param str left: Left border.
:param str center: Column separator.
:param str right: Right border.
:return: Yields other generators that yield strings.
:rtype: iter
"""
if not row or not row[0]:
yield combine((), left, center, right)
return
for row_index in range(len(row[0])):
yield combine((c[row_index] for c in row), left, center, right) | python | def build_row(row, left, center, right):
"""Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3', '<'],
]
:param iter row: List of cells for one row.
:param str left: Left border.
:param str center: Column separator.
:param str right: Right border.
:return: Yields other generators that yield strings.
:rtype: iter
"""
if not row or not row[0]:
yield combine((), left, center, right)
return
for row_index in range(len(row[0])):
yield combine((c[row_index] for c in row), left, center, right) | [
"def",
"build_row",
"(",
"row",
",",
"left",
",",
"center",
",",
"right",
")",
":",
"if",
"not",
"row",
"or",
"not",
"row",
"[",
"0",
"]",
":",
"yield",
"combine",
"(",
"(",
")",
",",
"left",
",",
"center",
",",
"right",
")",
"return",
"for",
"... | Combine single or multi-lined cells into a single row of list of lists including borders.
Row must already be padded and extended so each cell has the same number of lines.
Example return value:
[
['>', 'Left ', '|', 'Center', '|', 'Right', '<'],
['>', 'Cell1', '|', 'Cell2 ', '|', 'Cell3', '<'],
]
:param iter row: List of cells for one row.
:param str left: Left border.
:param str center: Column separator.
:param str right: Right border.
:return: Yields other generators that yield strings.
:rtype: iter | [
"Combine",
"single",
"or",
"multi",
"-",
"lined",
"cells",
"into",
"a",
"single",
"row",
"of",
"list",
"of",
"lists",
"including",
"borders",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/build.py#L117-L140 | train | 199,743 |
Robpol86/terminaltables | setup.py | CheckVersion.run | def run(cls):
"""Check variables."""
project = __import__(IMPORT, fromlist=[''])
for expected, var in [('@Robpol86', '__author__'), (LICENSE, '__license__'), (VERSION, '__version__')]:
if getattr(project, var) != expected:
raise SystemExit('Mismatch: {0}'.format(var))
# Check changelog.
if not re.compile(r'^%s - \d{4}-\d{2}-\d{2}[\r\n]' % VERSION, re.MULTILINE).search(readme()):
raise SystemExit('Version not found in readme/changelog file.')
# Check tox.
if INSTALL_REQUIRES:
contents = readme('tox.ini')
section = re.compile(r'[\r\n]+install_requires =[\r\n]+(.+?)[\r\n]+\w', re.DOTALL).findall(contents)
if not section:
raise SystemExit('Missing install_requires section in tox.ini.')
in_tox = re.findall(r' ([^=]+)==[\w\d.-]+', section[0])
if INSTALL_REQUIRES != in_tox:
raise SystemExit('Missing/unordered pinned dependencies in tox.ini.') | python | def run(cls):
"""Check variables."""
project = __import__(IMPORT, fromlist=[''])
for expected, var in [('@Robpol86', '__author__'), (LICENSE, '__license__'), (VERSION, '__version__')]:
if getattr(project, var) != expected:
raise SystemExit('Mismatch: {0}'.format(var))
# Check changelog.
if not re.compile(r'^%s - \d{4}-\d{2}-\d{2}[\r\n]' % VERSION, re.MULTILINE).search(readme()):
raise SystemExit('Version not found in readme/changelog file.')
# Check tox.
if INSTALL_REQUIRES:
contents = readme('tox.ini')
section = re.compile(r'[\r\n]+install_requires =[\r\n]+(.+?)[\r\n]+\w', re.DOTALL).findall(contents)
if not section:
raise SystemExit('Missing install_requires section in tox.ini.')
in_tox = re.findall(r' ([^=]+)==[\w\d.-]+', section[0])
if INSTALL_REQUIRES != in_tox:
raise SystemExit('Missing/unordered pinned dependencies in tox.ini.') | [
"def",
"run",
"(",
"cls",
")",
":",
"project",
"=",
"__import__",
"(",
"IMPORT",
",",
"fromlist",
"=",
"[",
"''",
"]",
")",
"for",
"expected",
",",
"var",
"in",
"[",
"(",
"'@Robpol86'",
",",
"'__author__'",
")",
",",
"(",
"LICENSE",
",",
"'__license_... | Check variables. | [
"Check",
"variables",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/setup.py#L53-L70 | train | 199,744 |
Robpol86/terminaltables | terminaltables/terminal_io.py | terminal_size | def terminal_size(kernel32=None):
"""Get the width and height of the terminal.
http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/
http://stackoverflow.com/questions/17993814/why-the-irrelevant-code-made-a-difference
:param kernel32: Optional mock kernel32 object. For testing.
:return: Width (number of characters) and height (number of lines) of the terminal.
:rtype: tuple
"""
if IS_WINDOWS:
kernel32 = kernel32 or ctypes.windll.kernel32
try:
return get_console_info(kernel32, kernel32.GetStdHandle(STD_ERROR_HANDLE))
except OSError:
try:
return get_console_info(kernel32, kernel32.GetStdHandle(STD_OUTPUT_HANDLE))
except OSError:
return DEFAULT_WIDTH, DEFAULT_HEIGHT
try:
device = __import__('fcntl').ioctl(0, __import__('termios').TIOCGWINSZ, '\0\0\0\0\0\0\0\0')
except IOError:
return DEFAULT_WIDTH, DEFAULT_HEIGHT
height, width = struct.unpack('hhhh', device)[:2]
return width, height | python | def terminal_size(kernel32=None):
"""Get the width and height of the terminal.
http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/
http://stackoverflow.com/questions/17993814/why-the-irrelevant-code-made-a-difference
:param kernel32: Optional mock kernel32 object. For testing.
:return: Width (number of characters) and height (number of lines) of the terminal.
:rtype: tuple
"""
if IS_WINDOWS:
kernel32 = kernel32 or ctypes.windll.kernel32
try:
return get_console_info(kernel32, kernel32.GetStdHandle(STD_ERROR_HANDLE))
except OSError:
try:
return get_console_info(kernel32, kernel32.GetStdHandle(STD_OUTPUT_HANDLE))
except OSError:
return DEFAULT_WIDTH, DEFAULT_HEIGHT
try:
device = __import__('fcntl').ioctl(0, __import__('termios').TIOCGWINSZ, '\0\0\0\0\0\0\0\0')
except IOError:
return DEFAULT_WIDTH, DEFAULT_HEIGHT
height, width = struct.unpack('hhhh', device)[:2]
return width, height | [
"def",
"terminal_size",
"(",
"kernel32",
"=",
"None",
")",
":",
"if",
"IS_WINDOWS",
":",
"kernel32",
"=",
"kernel32",
"or",
"ctypes",
".",
"windll",
".",
"kernel32",
"try",
":",
"return",
"get_console_info",
"(",
"kernel32",
",",
"kernel32",
".",
"GetStdHand... | Get the width and height of the terminal.
http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/
http://stackoverflow.com/questions/17993814/why-the-irrelevant-code-made-a-difference
:param kernel32: Optional mock kernel32 object. For testing.
:return: Width (number of characters) and height (number of lines) of the terminal.
:rtype: tuple | [
"Get",
"the",
"width",
"and",
"height",
"of",
"the",
"terminal",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/terminal_io.py#L42-L68 | train | 199,745 |
Robpol86/terminaltables | terminaltables/terminal_io.py | set_terminal_title | def set_terminal_title(title, kernel32=None):
"""Set the terminal title.
:param title: The title to set (string, unicode, bytes accepted).
:param kernel32: Optional mock kernel32 object. For testing.
:return: If title changed successfully (Windows only, always True on Linux/OSX).
:rtype: bool
"""
try:
title_bytes = title.encode('utf-8')
except AttributeError:
title_bytes = title
if IS_WINDOWS:
kernel32 = kernel32 or ctypes.windll.kernel32
try:
is_ascii = all(ord(c) < 128 for c in title) # str/unicode.
except TypeError:
is_ascii = all(c < 128 for c in title) # bytes.
if is_ascii:
return kernel32.SetConsoleTitleA(title_bytes) != 0
else:
return kernel32.SetConsoleTitleW(title) != 0
# Linux/OSX.
sys.stdout.write(b'\033]0;' + title_bytes + b'\007')
return True | python | def set_terminal_title(title, kernel32=None):
"""Set the terminal title.
:param title: The title to set (string, unicode, bytes accepted).
:param kernel32: Optional mock kernel32 object. For testing.
:return: If title changed successfully (Windows only, always True on Linux/OSX).
:rtype: bool
"""
try:
title_bytes = title.encode('utf-8')
except AttributeError:
title_bytes = title
if IS_WINDOWS:
kernel32 = kernel32 or ctypes.windll.kernel32
try:
is_ascii = all(ord(c) < 128 for c in title) # str/unicode.
except TypeError:
is_ascii = all(c < 128 for c in title) # bytes.
if is_ascii:
return kernel32.SetConsoleTitleA(title_bytes) != 0
else:
return kernel32.SetConsoleTitleW(title) != 0
# Linux/OSX.
sys.stdout.write(b'\033]0;' + title_bytes + b'\007')
return True | [
"def",
"set_terminal_title",
"(",
"title",
",",
"kernel32",
"=",
"None",
")",
":",
"try",
":",
"title_bytes",
"=",
"title",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
"AttributeError",
":",
"title_bytes",
"=",
"title",
"if",
"IS_WINDOWS",
":",
"kernel32",... | Set the terminal title.
:param title: The title to set (string, unicode, bytes accepted).
:param kernel32: Optional mock kernel32 object. For testing.
:return: If title changed successfully (Windows only, always True on Linux/OSX).
:rtype: bool | [
"Set",
"the",
"terminal",
"title",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/terminal_io.py#L71-L98 | train | 199,746 |
Robpol86/terminaltables | example2.py | table_abcd | def table_abcd():
"""Return table string to be printed. Two tables on one line."""
table_instance = SingleTable([['A', 'B'], ['C', 'D']])
# Get first table lines.
table_instance.outer_border = False
table_inner_borders = table_instance.table.splitlines()
# Get second table lines.
table_instance.outer_border = True
table_instance.inner_heading_row_border = False
table_instance.inner_column_border = False
table_outer_borders = table_instance.table.splitlines()
# Combine.
smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len)
smallest += [''] * (len(largest) - len(smallest)) # Make both same size.
combined = list()
for i, row in enumerate(largest):
combined.append(row.ljust(10) + ' ' + smallest[i])
return '\n'.join(combined) | python | def table_abcd():
"""Return table string to be printed. Two tables on one line."""
table_instance = SingleTable([['A', 'B'], ['C', 'D']])
# Get first table lines.
table_instance.outer_border = False
table_inner_borders = table_instance.table.splitlines()
# Get second table lines.
table_instance.outer_border = True
table_instance.inner_heading_row_border = False
table_instance.inner_column_border = False
table_outer_borders = table_instance.table.splitlines()
# Combine.
smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len)
smallest += [''] * (len(largest) - len(smallest)) # Make both same size.
combined = list()
for i, row in enumerate(largest):
combined.append(row.ljust(10) + ' ' + smallest[i])
return '\n'.join(combined) | [
"def",
"table_abcd",
"(",
")",
":",
"table_instance",
"=",
"SingleTable",
"(",
"[",
"[",
"'A'",
",",
"'B'",
"]",
",",
"[",
"'C'",
",",
"'D'",
"]",
"]",
")",
"# Get first table lines.",
"table_instance",
".",
"outer_border",
"=",
"False",
"table_inner_borders... | Return table string to be printed. Two tables on one line. | [
"Return",
"table",
"string",
"to",
"be",
"printed",
".",
"Two",
"tables",
"on",
"one",
"line",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/example2.py#L40-L60 | train | 199,747 |
Robpol86/terminaltables | terminaltables/ascii_table.py | AsciiTable.column_max_width | def column_max_width(self, column_number):
"""Return the maximum width of a column based on the current terminal width.
:param int column_number: The column number to query.
:return: The max width of the column.
:rtype: int
"""
inner_widths = max_dimensions(self.table_data)[0]
outer_border = 2 if self.outer_border else 0
inner_border = 1 if self.inner_column_border else 0
padding = self.padding_left + self.padding_right
return column_max_width(inner_widths, column_number, outer_border, inner_border, padding) | python | def column_max_width(self, column_number):
"""Return the maximum width of a column based on the current terminal width.
:param int column_number: The column number to query.
:return: The max width of the column.
:rtype: int
"""
inner_widths = max_dimensions(self.table_data)[0]
outer_border = 2 if self.outer_border else 0
inner_border = 1 if self.inner_column_border else 0
padding = self.padding_left + self.padding_right
return column_max_width(inner_widths, column_number, outer_border, inner_border, padding) | [
"def",
"column_max_width",
"(",
"self",
",",
"column_number",
")",
":",
"inner_widths",
"=",
"max_dimensions",
"(",
"self",
".",
"table_data",
")",
"[",
"0",
"]",
"outer_border",
"=",
"2",
"if",
"self",
".",
"outer_border",
"else",
"0",
"inner_border",
"=",
... | Return the maximum width of a column based on the current terminal width.
:param int column_number: The column number to query.
:return: The max width of the column.
:rtype: int | [
"Return",
"the",
"maximum",
"width",
"of",
"a",
"column",
"based",
"on",
"the",
"current",
"terminal",
"width",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/ascii_table.py#L23-L35 | train | 199,748 |
Robpol86/terminaltables | terminaltables/ascii_table.py | AsciiTable.table_width | def table_width(self):
"""Return the width of the table including padding and borders."""
outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]
outer_border = 2 if self.outer_border else 0
inner_border = 1 if self.inner_column_border else 0
return table_width(outer_widths, outer_border, inner_border) | python | def table_width(self):
"""Return the width of the table including padding and borders."""
outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]
outer_border = 2 if self.outer_border else 0
inner_border = 1 if self.inner_column_border else 0
return table_width(outer_widths, outer_border, inner_border) | [
"def",
"table_width",
"(",
"self",
")",
":",
"outer_widths",
"=",
"max_dimensions",
"(",
"self",
".",
"table_data",
",",
"self",
".",
"padding_left",
",",
"self",
".",
"padding_right",
")",
"[",
"2",
"]",
"outer_border",
"=",
"2",
"if",
"self",
".",
"out... | Return the width of the table including padding and borders. | [
"Return",
"the",
"width",
"of",
"the",
"table",
"including",
"padding",
"and",
"borders",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/ascii_table.py#L50-L55 | train | 199,749 |
Robpol86/terminaltables | terminaltables/github_table.py | GithubFlavoredMarkdownTable.horizontal_border | def horizontal_border(self, _, outer_widths):
"""Handle the GitHub heading border.
E.g.:
|:---|:---:|---:|----|
:param _: Unused.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border strings in a generator.
:rtype: iter
"""
horizontal = str(self.CHAR_INNER_HORIZONTAL)
left = self.CHAR_OUTER_LEFT_VERTICAL
intersect = self.CHAR_INNER_VERTICAL
right = self.CHAR_OUTER_RIGHT_VERTICAL
columns = list()
for i, width in enumerate(outer_widths):
justify = self.justify_columns.get(i)
width = max(3, width) # Width should be at least 3 so justification can be applied.
if justify == 'left':
columns.append(':' + horizontal * (width - 1))
elif justify == 'right':
columns.append(horizontal * (width - 1) + ':')
elif justify == 'center':
columns.append(':' + horizontal * (width - 2) + ':')
else:
columns.append(horizontal * width)
return combine(columns, left, intersect, right) | python | def horizontal_border(self, _, outer_widths):
"""Handle the GitHub heading border.
E.g.:
|:---|:---:|---:|----|
:param _: Unused.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border strings in a generator.
:rtype: iter
"""
horizontal = str(self.CHAR_INNER_HORIZONTAL)
left = self.CHAR_OUTER_LEFT_VERTICAL
intersect = self.CHAR_INNER_VERTICAL
right = self.CHAR_OUTER_RIGHT_VERTICAL
columns = list()
for i, width in enumerate(outer_widths):
justify = self.justify_columns.get(i)
width = max(3, width) # Width should be at least 3 so justification can be applied.
if justify == 'left':
columns.append(':' + horizontal * (width - 1))
elif justify == 'right':
columns.append(horizontal * (width - 1) + ':')
elif justify == 'center':
columns.append(':' + horizontal * (width - 2) + ':')
else:
columns.append(horizontal * width)
return combine(columns, left, intersect, right) | [
"def",
"horizontal_border",
"(",
"self",
",",
"_",
",",
"outer_widths",
")",
":",
"horizontal",
"=",
"str",
"(",
"self",
".",
"CHAR_INNER_HORIZONTAL",
")",
"left",
"=",
"self",
".",
"CHAR_OUTER_LEFT_VERTICAL",
"intersect",
"=",
"self",
".",
"CHAR_INNER_VERTICAL"... | Handle the GitHub heading border.
E.g.:
|:---|:---:|---:|----|
:param _: Unused.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border strings in a generator.
:rtype: iter | [
"Handle",
"the",
"GitHub",
"heading",
"border",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/github_table.py#L24-L54 | train | 199,750 |
Robpol86/terminaltables | terminaltables/width_and_alignment.py | visible_width | def visible_width(string):
"""Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
:return: String's width.
:rtype: int
"""
if '\033' in string:
string = RE_COLOR_ANSI.sub('', string)
# Convert to unicode.
try:
string = string.decode('u8')
except (AttributeError, UnicodeEncodeError):
pass
width = 0
for char in string:
if unicodedata.east_asian_width(char) in ('F', 'W'):
width += 2
else:
width += 1
return width | python | def visible_width(string):
"""Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
:return: String's width.
:rtype: int
"""
if '\033' in string:
string = RE_COLOR_ANSI.sub('', string)
# Convert to unicode.
try:
string = string.decode('u8')
except (AttributeError, UnicodeEncodeError):
pass
width = 0
for char in string:
if unicodedata.east_asian_width(char) in ('F', 'W'):
width += 2
else:
width += 1
return width | [
"def",
"visible_width",
"(",
"string",
")",
":",
"if",
"'\\033'",
"in",
"string",
":",
"string",
"=",
"RE_COLOR_ANSI",
".",
"sub",
"(",
"''",
",",
"string",
")",
"# Convert to unicode.",
"try",
":",
"string",
"=",
"string",
".",
"decode",
"(",
"'u8'",
")... | Get the visible width of a unicode string.
Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters.
From: https://github.com/Robpol86/terminaltables/pull/9
:param str string: String to measure.
:return: String's width.
:rtype: int | [
"Get",
"the",
"visible",
"width",
"of",
"a",
"unicode",
"string",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/width_and_alignment.py#L11-L39 | train | 199,751 |
Robpol86/terminaltables | terminaltables/width_and_alignment.py | align_and_pad_cell | def align_and_pad_cell(string, align, inner_dimensions, padding, space=' '):
"""Align a string horizontally and vertically. Also add additional padding in both dimensions.
:param str string: Input string to operate on.
:param tuple align: Tuple that contains one of left/center/right and/or top/middle/bottom.
:param tuple inner_dimensions: Width and height ints to expand string to without padding.
:param iter padding: Number of space chars for left, right, top, and bottom (4 ints).
:param str space: Character to use as white space for resizing/padding (use single visible chars only).
:return: Padded cell split into lines.
:rtype: list
"""
if not hasattr(string, 'splitlines'):
string = str(string)
# Handle trailing newlines or empty strings, str.splitlines() does not satisfy.
lines = string.splitlines() or ['']
if string.endswith('\n'):
lines.append('')
# Vertically align and pad.
if 'bottom' in align:
lines = ([''] * (inner_dimensions[1] - len(lines) + padding[2])) + lines + ([''] * padding[3])
elif 'middle' in align:
delta = inner_dimensions[1] - len(lines)
lines = ([''] * (delta // 2 + delta % 2 + padding[2])) + lines + ([''] * (delta // 2 + padding[3]))
else:
lines = ([''] * padding[2]) + lines + ([''] * (inner_dimensions[1] - len(lines) + padding[3]))
# Horizontally align and pad.
for i, line in enumerate(lines):
new_width = inner_dimensions[0] + len(line) - visible_width(line)
if 'right' in align:
lines[i] = line.rjust(padding[0] + new_width, space) + (space * padding[1])
elif 'center' in align:
lines[i] = (space * padding[0]) + line.center(new_width, space) + (space * padding[1])
else:
lines[i] = (space * padding[0]) + line.ljust(new_width + padding[1], space)
return lines | python | def align_and_pad_cell(string, align, inner_dimensions, padding, space=' '):
"""Align a string horizontally and vertically. Also add additional padding in both dimensions.
:param str string: Input string to operate on.
:param tuple align: Tuple that contains one of left/center/right and/or top/middle/bottom.
:param tuple inner_dimensions: Width and height ints to expand string to without padding.
:param iter padding: Number of space chars for left, right, top, and bottom (4 ints).
:param str space: Character to use as white space for resizing/padding (use single visible chars only).
:return: Padded cell split into lines.
:rtype: list
"""
if not hasattr(string, 'splitlines'):
string = str(string)
# Handle trailing newlines or empty strings, str.splitlines() does not satisfy.
lines = string.splitlines() or ['']
if string.endswith('\n'):
lines.append('')
# Vertically align and pad.
if 'bottom' in align:
lines = ([''] * (inner_dimensions[1] - len(lines) + padding[2])) + lines + ([''] * padding[3])
elif 'middle' in align:
delta = inner_dimensions[1] - len(lines)
lines = ([''] * (delta // 2 + delta % 2 + padding[2])) + lines + ([''] * (delta // 2 + padding[3]))
else:
lines = ([''] * padding[2]) + lines + ([''] * (inner_dimensions[1] - len(lines) + padding[3]))
# Horizontally align and pad.
for i, line in enumerate(lines):
new_width = inner_dimensions[0] + len(line) - visible_width(line)
if 'right' in align:
lines[i] = line.rjust(padding[0] + new_width, space) + (space * padding[1])
elif 'center' in align:
lines[i] = (space * padding[0]) + line.center(new_width, space) + (space * padding[1])
else:
lines[i] = (space * padding[0]) + line.ljust(new_width + padding[1], space)
return lines | [
"def",
"align_and_pad_cell",
"(",
"string",
",",
"align",
",",
"inner_dimensions",
",",
"padding",
",",
"space",
"=",
"' '",
")",
":",
"if",
"not",
"hasattr",
"(",
"string",
",",
"'splitlines'",
")",
":",
"string",
"=",
"str",
"(",
"string",
")",
"# Hand... | Align a string horizontally and vertically. Also add additional padding in both dimensions.
:param str string: Input string to operate on.
:param tuple align: Tuple that contains one of left/center/right and/or top/middle/bottom.
:param tuple inner_dimensions: Width and height ints to expand string to without padding.
:param iter padding: Number of space chars for left, right, top, and bottom (4 ints).
:param str space: Character to use as white space for resizing/padding (use single visible chars only).
:return: Padded cell split into lines.
:rtype: list | [
"Align",
"a",
"string",
"horizontally",
"and",
"vertically",
".",
"Also",
"add",
"additional",
"padding",
"in",
"both",
"dimensions",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/width_and_alignment.py#L42-L81 | train | 199,752 |
Robpol86/terminaltables | terminaltables/width_and_alignment.py | max_dimensions | def max_dimensions(table_data, padding_left=0, padding_right=0, padding_top=0, padding_bottom=0):
"""Get maximum widths of each column and maximum height of each row.
:param iter table_data: List of list of strings (unmodified table data).
:param int padding_left: Number of space chars on left side of cell.
:param int padding_right: Number of space chars on right side of cell.
:param int padding_top: Number of empty lines on top side of cell.
:param int padding_bottom: Number of empty lines on bottom side of cell.
:return: 4-item tuple of n-item lists. Inner column widths and row heights, outer column widths and row heights.
:rtype: tuple
"""
inner_widths = [0] * (max(len(r) for r in table_data) if table_data else 0)
inner_heights = [0] * len(table_data)
# Find max width and heights.
for j, row in enumerate(table_data):
for i, cell in enumerate(row):
if not hasattr(cell, 'count') or not hasattr(cell, 'splitlines'):
cell = str(cell)
if not cell:
continue
inner_heights[j] = max(inner_heights[j], cell.count('\n') + 1)
inner_widths[i] = max(inner_widths[i], *[visible_width(l) for l in cell.splitlines()])
# Calculate with padding.
outer_widths = [padding_left + i + padding_right for i in inner_widths]
outer_heights = [padding_top + i + padding_bottom for i in inner_heights]
return inner_widths, inner_heights, outer_widths, outer_heights | python | def max_dimensions(table_data, padding_left=0, padding_right=0, padding_top=0, padding_bottom=0):
"""Get maximum widths of each column and maximum height of each row.
:param iter table_data: List of list of strings (unmodified table data).
:param int padding_left: Number of space chars on left side of cell.
:param int padding_right: Number of space chars on right side of cell.
:param int padding_top: Number of empty lines on top side of cell.
:param int padding_bottom: Number of empty lines on bottom side of cell.
:return: 4-item tuple of n-item lists. Inner column widths and row heights, outer column widths and row heights.
:rtype: tuple
"""
inner_widths = [0] * (max(len(r) for r in table_data) if table_data else 0)
inner_heights = [0] * len(table_data)
# Find max width and heights.
for j, row in enumerate(table_data):
for i, cell in enumerate(row):
if not hasattr(cell, 'count') or not hasattr(cell, 'splitlines'):
cell = str(cell)
if not cell:
continue
inner_heights[j] = max(inner_heights[j], cell.count('\n') + 1)
inner_widths[i] = max(inner_widths[i], *[visible_width(l) for l in cell.splitlines()])
# Calculate with padding.
outer_widths = [padding_left + i + padding_right for i in inner_widths]
outer_heights = [padding_top + i + padding_bottom for i in inner_heights]
return inner_widths, inner_heights, outer_widths, outer_heights | [
"def",
"max_dimensions",
"(",
"table_data",
",",
"padding_left",
"=",
"0",
",",
"padding_right",
"=",
"0",
",",
"padding_top",
"=",
"0",
",",
"padding_bottom",
"=",
"0",
")",
":",
"inner_widths",
"=",
"[",
"0",
"]",
"*",
"(",
"max",
"(",
"len",
"(",
... | Get maximum widths of each column and maximum height of each row.
:param iter table_data: List of list of strings (unmodified table data).
:param int padding_left: Number of space chars on left side of cell.
:param int padding_right: Number of space chars on right side of cell.
:param int padding_top: Number of empty lines on top side of cell.
:param int padding_bottom: Number of empty lines on bottom side of cell.
:return: 4-item tuple of n-item lists. Inner column widths and row heights, outer column widths and row heights.
:rtype: tuple | [
"Get",
"maximum",
"widths",
"of",
"each",
"column",
"and",
"maximum",
"height",
"of",
"each",
"row",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/width_and_alignment.py#L84-L113 | train | 199,753 |
Robpol86/terminaltables | terminaltables/width_and_alignment.py | column_max_width | def column_max_width(inner_widths, column_number, outer_border, inner_border, padding):
"""Determine the maximum width of a column based on the current terminal width.
:param iter inner_widths: List of widths (no padding) for each column.
:param int column_number: The column number to query.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:param int padding: Total padding per cell (left + right padding).
:return: The maximum width the column can be without causing line wrapping.
"""
column_count = len(inner_widths)
terminal_width = terminal_size()[0]
# Count how much space padding, outer, and inner borders take up.
non_data_space = outer_border
non_data_space += inner_border * (column_count - 1)
non_data_space += column_count * padding
# Exclude selected column's width.
data_space = sum(inner_widths) - inner_widths[column_number]
return terminal_width - data_space - non_data_space | python | def column_max_width(inner_widths, column_number, outer_border, inner_border, padding):
"""Determine the maximum width of a column based on the current terminal width.
:param iter inner_widths: List of widths (no padding) for each column.
:param int column_number: The column number to query.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:param int padding: Total padding per cell (left + right padding).
:return: The maximum width the column can be without causing line wrapping.
"""
column_count = len(inner_widths)
terminal_width = terminal_size()[0]
# Count how much space padding, outer, and inner borders take up.
non_data_space = outer_border
non_data_space += inner_border * (column_count - 1)
non_data_space += column_count * padding
# Exclude selected column's width.
data_space = sum(inner_widths) - inner_widths[column_number]
return terminal_width - data_space - non_data_space | [
"def",
"column_max_width",
"(",
"inner_widths",
",",
"column_number",
",",
"outer_border",
",",
"inner_border",
",",
"padding",
")",
":",
"column_count",
"=",
"len",
"(",
"inner_widths",
")",
"terminal_width",
"=",
"terminal_size",
"(",
")",
"[",
"0",
"]",
"# ... | Determine the maximum width of a column based on the current terminal width.
:param iter inner_widths: List of widths (no padding) for each column.
:param int column_number: The column number to query.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:param int padding: Total padding per cell (left + right padding).
:return: The maximum width the column can be without causing line wrapping. | [
"Determine",
"the",
"maximum",
"width",
"of",
"a",
"column",
"based",
"on",
"the",
"current",
"terminal",
"width",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/width_and_alignment.py#L116-L138 | train | 199,754 |
Robpol86/terminaltables | terminaltables/width_and_alignment.py | table_width | def table_width(outer_widths, outer_border, inner_border):
"""Determine the width of the entire table including borders and padding.
:param iter outer_widths: List of widths (with padding) for each column.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:return: The width of the table.
:rtype: int
"""
column_count = len(outer_widths)
# Count how much space outer and inner borders take up.
non_data_space = outer_border
if column_count:
non_data_space += inner_border * (column_count - 1)
# Space of all columns and their padding.
data_space = sum(outer_widths)
return data_space + non_data_space | python | def table_width(outer_widths, outer_border, inner_border):
"""Determine the width of the entire table including borders and padding.
:param iter outer_widths: List of widths (with padding) for each column.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:return: The width of the table.
:rtype: int
"""
column_count = len(outer_widths)
# Count how much space outer and inner borders take up.
non_data_space = outer_border
if column_count:
non_data_space += inner_border * (column_count - 1)
# Space of all columns and their padding.
data_space = sum(outer_widths)
return data_space + non_data_space | [
"def",
"table_width",
"(",
"outer_widths",
",",
"outer_border",
",",
"inner_border",
")",
":",
"column_count",
"=",
"len",
"(",
"outer_widths",
")",
"# Count how much space outer and inner borders take up.",
"non_data_space",
"=",
"outer_border",
"if",
"column_count",
":"... | Determine the width of the entire table including borders and padding.
:param iter outer_widths: List of widths (with padding) for each column.
:param int outer_border: Sum of left and right outer border visible widths.
:param int inner_border: Visible width of the inner border character.
:return: The width of the table.
:rtype: int | [
"Determine",
"the",
"width",
"of",
"the",
"entire",
"table",
"including",
"borders",
"and",
"padding",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/width_and_alignment.py#L141-L160 | train | 199,755 |
Robpol86/terminaltables | terminaltables/base_table.py | BaseTable.horizontal_border | def horizontal_border(self, style, outer_widths):
"""Build any kind of horizontal border for the table.
:param str style: Type of border to return.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border as a tuple of strings.
:rtype: tuple
"""
if style == 'top':
horizontal = self.CHAR_OUTER_TOP_HORIZONTAL
left = self.CHAR_OUTER_TOP_LEFT
intersect = self.CHAR_OUTER_TOP_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_TOP_RIGHT
title = self.title
elif style == 'bottom':
horizontal = self.CHAR_OUTER_BOTTOM_HORIZONTAL
left = self.CHAR_OUTER_BOTTOM_LEFT
intersect = self.CHAR_OUTER_BOTTOM_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_BOTTOM_RIGHT
title = None
elif style == 'heading':
horizontal = self.CHAR_H_INNER_HORIZONTAL
left = self.CHAR_H_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_H_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_H_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
elif style == 'footing':
horizontal = self.CHAR_F_INNER_HORIZONTAL
left = self.CHAR_F_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_F_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_F_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
else:
horizontal = self.CHAR_INNER_HORIZONTAL
left = self.CHAR_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
return build_border(outer_widths, horizontal, left, intersect, right, title) | python | def horizontal_border(self, style, outer_widths):
"""Build any kind of horizontal border for the table.
:param str style: Type of border to return.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border as a tuple of strings.
:rtype: tuple
"""
if style == 'top':
horizontal = self.CHAR_OUTER_TOP_HORIZONTAL
left = self.CHAR_OUTER_TOP_LEFT
intersect = self.CHAR_OUTER_TOP_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_TOP_RIGHT
title = self.title
elif style == 'bottom':
horizontal = self.CHAR_OUTER_BOTTOM_HORIZONTAL
left = self.CHAR_OUTER_BOTTOM_LEFT
intersect = self.CHAR_OUTER_BOTTOM_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_BOTTOM_RIGHT
title = None
elif style == 'heading':
horizontal = self.CHAR_H_INNER_HORIZONTAL
left = self.CHAR_H_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_H_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_H_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
elif style == 'footing':
horizontal = self.CHAR_F_INNER_HORIZONTAL
left = self.CHAR_F_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_F_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_F_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
else:
horizontal = self.CHAR_INNER_HORIZONTAL
left = self.CHAR_OUTER_LEFT_INTERSECT if self.outer_border else ''
intersect = self.CHAR_INNER_INTERSECT if self.inner_column_border else ''
right = self.CHAR_OUTER_RIGHT_INTERSECT if self.outer_border else ''
title = None
return build_border(outer_widths, horizontal, left, intersect, right, title) | [
"def",
"horizontal_border",
"(",
"self",
",",
"style",
",",
"outer_widths",
")",
":",
"if",
"style",
"==",
"'top'",
":",
"horizontal",
"=",
"self",
".",
"CHAR_OUTER_TOP_HORIZONTAL",
"left",
"=",
"self",
".",
"CHAR_OUTER_TOP_LEFT",
"intersect",
"=",
"self",
"."... | Build any kind of horizontal border for the table.
:param str style: Type of border to return.
:param iter outer_widths: List of widths (with padding) for each column.
:return: Prepared border as a tuple of strings.
:rtype: tuple | [
"Build",
"any",
"kind",
"of",
"horizontal",
"border",
"for",
"the",
"table",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/base_table.py#L71-L110 | train | 199,756 |
Robpol86/terminaltables | terminaltables/base_table.py | BaseTable.gen_row_lines | def gen_row_lines(self, row, style, inner_widths, height):
r"""Combine cells in row and group them into lines with vertical borders.
Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append
newline character to the end of joined line.
In:
['Row One Column One', 'Two', 'Three']
Out:
[
('|', ' Row One Column One ', '|', ' Two ', '|', ' Three ', '|'),
]
In:
['Row One\nColumn One', 'Two', 'Three'],
Out:
[
('|', ' Row One ', '|', ' Two ', '|', ' Three ', '|'),
('|', ' Column One ', '|', ' ', '|', ' ', '|'),
]
:param iter row: One row in the table. List of cells.
:param str style: Type of border characters to use.
:param iter inner_widths: List of widths (no padding) for each column.
:param int height: Inner height (no padding) (number of lines) to expand row to.
:return: Yields lines split into components in a list. Caller must ''.join() line.
"""
cells_in_row = list()
# Resize row if it doesn't have enough cells.
if len(row) != len(inner_widths):
row = row + [''] * (len(inner_widths) - len(row))
# Pad and align each cell. Split each cell into lines to support multi-line cells.
for i, cell in enumerate(row):
align = (self.justify_columns.get(i),)
inner_dimensions = (inner_widths[i], height)
padding = (self.padding_left, self.padding_right, 0, 0)
cells_in_row.append(align_and_pad_cell(cell, align, inner_dimensions, padding))
# Determine border characters.
if style == 'heading':
left = self.CHAR_H_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_H_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_H_OUTER_RIGHT_VERTICAL if self.outer_border else ''
elif style == 'footing':
left = self.CHAR_F_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_F_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_F_OUTER_RIGHT_VERTICAL if self.outer_border else ''
else:
left = self.CHAR_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_OUTER_RIGHT_VERTICAL if self.outer_border else ''
# Yield each line.
for line in build_row(cells_in_row, left, center, right):
yield line | python | def gen_row_lines(self, row, style, inner_widths, height):
r"""Combine cells in row and group them into lines with vertical borders.
Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append
newline character to the end of joined line.
In:
['Row One Column One', 'Two', 'Three']
Out:
[
('|', ' Row One Column One ', '|', ' Two ', '|', ' Three ', '|'),
]
In:
['Row One\nColumn One', 'Two', 'Three'],
Out:
[
('|', ' Row One ', '|', ' Two ', '|', ' Three ', '|'),
('|', ' Column One ', '|', ' ', '|', ' ', '|'),
]
:param iter row: One row in the table. List of cells.
:param str style: Type of border characters to use.
:param iter inner_widths: List of widths (no padding) for each column.
:param int height: Inner height (no padding) (number of lines) to expand row to.
:return: Yields lines split into components in a list. Caller must ''.join() line.
"""
cells_in_row = list()
# Resize row if it doesn't have enough cells.
if len(row) != len(inner_widths):
row = row + [''] * (len(inner_widths) - len(row))
# Pad and align each cell. Split each cell into lines to support multi-line cells.
for i, cell in enumerate(row):
align = (self.justify_columns.get(i),)
inner_dimensions = (inner_widths[i], height)
padding = (self.padding_left, self.padding_right, 0, 0)
cells_in_row.append(align_and_pad_cell(cell, align, inner_dimensions, padding))
# Determine border characters.
if style == 'heading':
left = self.CHAR_H_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_H_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_H_OUTER_RIGHT_VERTICAL if self.outer_border else ''
elif style == 'footing':
left = self.CHAR_F_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_F_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_F_OUTER_RIGHT_VERTICAL if self.outer_border else ''
else:
left = self.CHAR_OUTER_LEFT_VERTICAL if self.outer_border else ''
center = self.CHAR_INNER_VERTICAL if self.inner_column_border else ''
right = self.CHAR_OUTER_RIGHT_VERTICAL if self.outer_border else ''
# Yield each line.
for line in build_row(cells_in_row, left, center, right):
yield line | [
"def",
"gen_row_lines",
"(",
"self",
",",
"row",
",",
"style",
",",
"inner_widths",
",",
"height",
")",
":",
"cells_in_row",
"=",
"list",
"(",
")",
"# Resize row if it doesn't have enough cells.",
"if",
"len",
"(",
"row",
")",
"!=",
"len",
"(",
"inner_widths",... | r"""Combine cells in row and group them into lines with vertical borders.
Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append
newline character to the end of joined line.
In:
['Row One Column One', 'Two', 'Three']
Out:
[
('|', ' Row One Column One ', '|', ' Two ', '|', ' Three ', '|'),
]
In:
['Row One\nColumn One', 'Two', 'Three'],
Out:
[
('|', ' Row One ', '|', ' Two ', '|', ' Three ', '|'),
('|', ' Column One ', '|', ' ', '|', ' ', '|'),
]
:param iter row: One row in the table. List of cells.
:param str style: Type of border characters to use.
:param iter inner_widths: List of widths (no padding) for each column.
:param int height: Inner height (no padding) (number of lines) to expand row to.
:return: Yields lines split into components in a list. Caller must ''.join() line. | [
"r",
"Combine",
"cells",
"in",
"row",
"and",
"group",
"them",
"into",
"lines",
"with",
"vertical",
"borders",
"."
] | ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/base_table.py#L112-L169 | train | 199,757 |
mapbox/rio-color | rio_color/operations.py | simple_atmo_opstring | def simple_atmo_opstring(haze, contrast, bias):
"""Make a simple atmospheric correction formula."""
gamma_b = 1 - haze
gamma_g = 1 - (haze / 3.0)
ops = (
"gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}"
).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast, bias=bias)
return ops | python | def simple_atmo_opstring(haze, contrast, bias):
"""Make a simple atmospheric correction formula."""
gamma_b = 1 - haze
gamma_g = 1 - (haze / 3.0)
ops = (
"gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}"
).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast, bias=bias)
return ops | [
"def",
"simple_atmo_opstring",
"(",
"haze",
",",
"contrast",
",",
"bias",
")",
":",
"gamma_b",
"=",
"1",
"-",
"haze",
"gamma_g",
"=",
"1",
"-",
"(",
"haze",
"/",
"3.0",
")",
"ops",
"=",
"(",
"\"gamma g {gamma_g}, \"",
"\"gamma b {gamma_b}, \"",
"\"sigmoidal ... | Make a simple atmospheric correction formula. | [
"Make",
"a",
"simple",
"atmospheric",
"correction",
"formula",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/operations.py#L144-L151 | train | 199,758 |
mapbox/rio-color | rio_color/operations.py | _op_factory | def _op_factory(func, kwargs, opname, bands, rgb_op=False):
"""create an operation function closure
don't call directly, use parse_operations
returns a function which itself takes and returns ndarrays
"""
def f(arr):
# Avoid mutation by copying
newarr = arr.copy()
if rgb_op:
# apply func to array's first 3 bands, assumed r,g,b
# additional band(s) are untouched
newarr[0:3] = func(newarr[0:3], **kwargs)
else:
# apply func to array band at a time
for b in bands:
newarr[b - 1] = func(arr[b - 1], **kwargs)
return newarr
f.__name__ = str(opname)
return f | python | def _op_factory(func, kwargs, opname, bands, rgb_op=False):
"""create an operation function closure
don't call directly, use parse_operations
returns a function which itself takes and returns ndarrays
"""
def f(arr):
# Avoid mutation by copying
newarr = arr.copy()
if rgb_op:
# apply func to array's first 3 bands, assumed r,g,b
# additional band(s) are untouched
newarr[0:3] = func(newarr[0:3], **kwargs)
else:
# apply func to array band at a time
for b in bands:
newarr[b - 1] = func(arr[b - 1], **kwargs)
return newarr
f.__name__ = str(opname)
return f | [
"def",
"_op_factory",
"(",
"func",
",",
"kwargs",
",",
"opname",
",",
"bands",
",",
"rgb_op",
"=",
"False",
")",
":",
"def",
"f",
"(",
"arr",
")",
":",
"# Avoid mutation by copying",
"newarr",
"=",
"arr",
".",
"copy",
"(",
")",
"if",
"rgb_op",
":",
"... | create an operation function closure
don't call directly, use parse_operations
returns a function which itself takes and returns ndarrays | [
"create",
"an",
"operation",
"function",
"closure",
"don",
"t",
"call",
"directly",
"use",
"parse_operations",
"returns",
"a",
"function",
"which",
"itself",
"takes",
"and",
"returns",
"ndarrays"
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/operations.py#L184-L204 | train | 199,759 |
mapbox/rio-color | rio_color/operations.py | parse_operations | def parse_operations(ops_string):
"""Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays
"""
band_lookup = {"r": 1, "g": 2, "b": 3}
count = len(band_lookup)
opfuncs = {"saturation": saturation, "sigmoidal": sigmoidal, "gamma": gamma}
opkwargs = {
"saturation": ("proportion",),
"sigmoidal": ("contrast", "bias"),
"gamma": ("g",),
}
# Operations that assume RGB colorspace
rgb_ops = ("saturation",)
# split into tokens, commas are optional whitespace
tokens = [x.strip() for x in ops_string.replace(",", "").split(" ")]
operations = []
current = []
for token in tokens:
if token.lower() in opfuncs.keys():
if len(current) > 0:
operations.append(current)
current = []
current.append(token.lower())
if len(current) > 0:
operations.append(current)
result = []
for parts in operations:
opname = parts[0]
bandstr = parts[1]
args = parts[2:]
try:
func = opfuncs[opname]
except KeyError:
raise ValueError("{} is not a valid operation".format(opname))
if opname in rgb_ops:
# ignore bands, assumed to be in rgb
# push 2nd arg into args
args = [bandstr] + args
bands = (1, 2, 3)
else:
# 2nd arg is bands
# parse r,g,b ~= 1,2,3
bands = set()
for bs in bandstr:
try:
band = int(bs)
except ValueError:
band = band_lookup[bs.lower()]
if band < 1 or band > count:
raise ValueError(
"{} BAND must be between 1 and {}".format(opname, count)
)
bands.add(band)
# assume all args are float
args = [float(arg) for arg in args]
kwargs = dict(zip(opkwargs[opname], args))
# Create opperation function
f = _op_factory(
func=func,
kwargs=kwargs,
opname=opname,
bands=bands,
rgb_op=(opname in rgb_ops),
)
result.append(f)
return result | python | def parse_operations(ops_string):
"""Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays
"""
band_lookup = {"r": 1, "g": 2, "b": 3}
count = len(band_lookup)
opfuncs = {"saturation": saturation, "sigmoidal": sigmoidal, "gamma": gamma}
opkwargs = {
"saturation": ("proportion",),
"sigmoidal": ("contrast", "bias"),
"gamma": ("g",),
}
# Operations that assume RGB colorspace
rgb_ops = ("saturation",)
# split into tokens, commas are optional whitespace
tokens = [x.strip() for x in ops_string.replace(",", "").split(" ")]
operations = []
current = []
for token in tokens:
if token.lower() in opfuncs.keys():
if len(current) > 0:
operations.append(current)
current = []
current.append(token.lower())
if len(current) > 0:
operations.append(current)
result = []
for parts in operations:
opname = parts[0]
bandstr = parts[1]
args = parts[2:]
try:
func = opfuncs[opname]
except KeyError:
raise ValueError("{} is not a valid operation".format(opname))
if opname in rgb_ops:
# ignore bands, assumed to be in rgb
# push 2nd arg into args
args = [bandstr] + args
bands = (1, 2, 3)
else:
# 2nd arg is bands
# parse r,g,b ~= 1,2,3
bands = set()
for bs in bandstr:
try:
band = int(bs)
except ValueError:
band = band_lookup[bs.lower()]
if band < 1 or band > count:
raise ValueError(
"{} BAND must be between 1 and {}".format(opname, count)
)
bands.add(band)
# assume all args are float
args = [float(arg) for arg in args]
kwargs = dict(zip(opkwargs[opname], args))
# Create opperation function
f = _op_factory(
func=func,
kwargs=kwargs,
opname=opname,
bands=bands,
rgb_op=(opname in rgb_ops),
)
result.append(f)
return result | [
"def",
"parse_operations",
"(",
"ops_string",
")",
":",
"band_lookup",
"=",
"{",
"\"r\"",
":",
"1",
",",
"\"g\"",
":",
"2",
",",
"\"b\"",
":",
"3",
"}",
"count",
"=",
"len",
"(",
"band_lookup",
")",
"opfuncs",
"=",
"{",
"\"saturation\"",
":",
"saturati... | Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays | [
"Takes",
"a",
"string",
"of",
"operations",
"written",
"with",
"a",
"handy",
"DSL"
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/operations.py#L207-L286 | train | 199,760 |
mapbox/rio-color | rio_color/scripts/cli.py | check_jobs | def check_jobs(jobs):
"""Validate number of jobs."""
if jobs == 0:
raise click.UsageError("Jobs must be >= 1 or == -1")
elif jobs < 0:
import multiprocessing
jobs = multiprocessing.cpu_count()
return jobs | python | def check_jobs(jobs):
"""Validate number of jobs."""
if jobs == 0:
raise click.UsageError("Jobs must be >= 1 or == -1")
elif jobs < 0:
import multiprocessing
jobs = multiprocessing.cpu_count()
return jobs | [
"def",
"check_jobs",
"(",
"jobs",
")",
":",
"if",
"jobs",
"==",
"0",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"Jobs must be >= 1 or == -1\"",
")",
"elif",
"jobs",
"<",
"0",
":",
"import",
"multiprocessing",
"jobs",
"=",
"multiprocessing",
".",
"cpu_c... | Validate number of jobs. | [
"Validate",
"number",
"of",
"jobs",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/scripts/cli.py#L22-L30 | train | 199,761 |
mapbox/rio-color | rio_color/utils.py | to_math_type | def to_math_type(arr):
"""Convert an array from native integer dtype range to 0..1
scaling down linearly
"""
max_int = np.iinfo(arr.dtype).max
return arr.astype(math_type) / max_int | python | def to_math_type(arr):
"""Convert an array from native integer dtype range to 0..1
scaling down linearly
"""
max_int = np.iinfo(arr.dtype).max
return arr.astype(math_type) / max_int | [
"def",
"to_math_type",
"(",
"arr",
")",
":",
"max_int",
"=",
"np",
".",
"iinfo",
"(",
"arr",
".",
"dtype",
")",
".",
"max",
"return",
"arr",
".",
"astype",
"(",
"math_type",
")",
"/",
"max_int"
] | Convert an array from native integer dtype range to 0..1
scaling down linearly | [
"Convert",
"an",
"array",
"from",
"native",
"integer",
"dtype",
"range",
"to",
"0",
"..",
"1",
"scaling",
"down",
"linearly"
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/utils.py#L15-L20 | train | 199,762 |
mapbox/rio-color | rio_color/utils.py | scale_dtype | def scale_dtype(arr, dtype):
"""Convert an array from 0..1 to dtype, scaling up linearly
"""
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype) | python | def scale_dtype(arr, dtype):
"""Convert an array from 0..1 to dtype, scaling up linearly
"""
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype) | [
"def",
"scale_dtype",
"(",
"arr",
",",
"dtype",
")",
":",
"max_int",
"=",
"np",
".",
"iinfo",
"(",
"dtype",
")",
".",
"max",
"return",
"(",
"arr",
"*",
"max_int",
")",
".",
"astype",
"(",
"dtype",
")"
] | Convert an array from 0..1 to dtype, scaling up linearly | [
"Convert",
"an",
"array",
"from",
"0",
"..",
"1",
"to",
"dtype",
"scaling",
"up",
"linearly"
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/utils.py#L23-L27 | train | 199,763 |
mapbox/rio-color | rio_color/utils.py | magick_to_rio | def magick_to_rio(convert_opts):
"""Translate a limited subset of imagemagick convert commands
to rio color operations
Parameters
----------
convert_opts: String, imagemagick convert options
Returns
-------
operations string, ordered rio color operations
"""
ops = []
bands = None
def set_band(x):
global bands
if x.upper() == "RGB":
x = "RGB"
bands = x.upper()
set_band("RGB")
def append_sig(arg):
global bands
args = list(filter(None, re.split("[,x]+", arg)))
if len(args) == 1:
args.append(0.5)
elif len(args) == 2:
args[1] = float(args[1].replace("%", "")) / 100.0
ops.append("sigmoidal {} {} {}".format(bands, *args))
def append_gamma(arg):
global bands
ops.append("gamma {} {}".format(bands, arg))
def append_sat(arg):
args = list(filter(None, re.split("[,x]+", arg)))
# ignore args[0]
# convert to proportion
prop = float(args[1]) / 100
ops.append("saturation {}".format(prop))
nextf = None
for part in convert_opts.strip().split(" "):
if part == "-channel":
nextf = set_band
elif part == "+channel":
set_band("RGB")
nextf = None
elif part == "-sigmoidal-contrast":
nextf = append_sig
elif part == "-gamma":
nextf = append_gamma
elif part == "-modulate":
nextf = append_sat
else:
if nextf:
nextf(part)
nextf = None
return " ".join(ops) | python | def magick_to_rio(convert_opts):
"""Translate a limited subset of imagemagick convert commands
to rio color operations
Parameters
----------
convert_opts: String, imagemagick convert options
Returns
-------
operations string, ordered rio color operations
"""
ops = []
bands = None
def set_band(x):
global bands
if x.upper() == "RGB":
x = "RGB"
bands = x.upper()
set_band("RGB")
def append_sig(arg):
global bands
args = list(filter(None, re.split("[,x]+", arg)))
if len(args) == 1:
args.append(0.5)
elif len(args) == 2:
args[1] = float(args[1].replace("%", "")) / 100.0
ops.append("sigmoidal {} {} {}".format(bands, *args))
def append_gamma(arg):
global bands
ops.append("gamma {} {}".format(bands, arg))
def append_sat(arg):
args = list(filter(None, re.split("[,x]+", arg)))
# ignore args[0]
# convert to proportion
prop = float(args[1]) / 100
ops.append("saturation {}".format(prop))
nextf = None
for part in convert_opts.strip().split(" "):
if part == "-channel":
nextf = set_band
elif part == "+channel":
set_band("RGB")
nextf = None
elif part == "-sigmoidal-contrast":
nextf = append_sig
elif part == "-gamma":
nextf = append_gamma
elif part == "-modulate":
nextf = append_sat
else:
if nextf:
nextf(part)
nextf = None
return " ".join(ops) | [
"def",
"magick_to_rio",
"(",
"convert_opts",
")",
":",
"ops",
"=",
"[",
"]",
"bands",
"=",
"None",
"def",
"set_band",
"(",
"x",
")",
":",
"global",
"bands",
"if",
"x",
".",
"upper",
"(",
")",
"==",
"\"RGB\"",
":",
"x",
"=",
"\"RGB\"",
"bands",
"=",... | Translate a limited subset of imagemagick convert commands
to rio color operations
Parameters
----------
convert_opts: String, imagemagick convert options
Returns
-------
operations string, ordered rio color operations | [
"Translate",
"a",
"limited",
"subset",
"of",
"imagemagick",
"convert",
"commands",
"to",
"rio",
"color",
"operations"
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/utils.py#L30-L91 | train | 199,764 |
mapbox/rio-color | scripts/optimize_color.py | calc_downsample | def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target | python | def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target | [
"def",
"calc_downsample",
"(",
"w",
",",
"h",
",",
"target",
"=",
"400",
")",
":",
"if",
"w",
">",
"h",
":",
"return",
"h",
"/",
"target",
"elif",
"h",
">=",
"w",
":",
"return",
"w",
"/",
"target"
] | Calculate downsampling value. | [
"Calculate",
"downsampling",
"value",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L194-L199 | train | 199,765 |
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.move | def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval | python | def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval | [
"def",
"move",
"(",
"self",
")",
":",
"k",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"keys",
")",
"multiplier",
"=",
"random",
".",
"choice",
"(",
"(",
"0.95",
",",
"1.05",
")",
")",
"invalid_key",
"=",
"True",
"while",
"invalid_key",
":",
"#... | Create a state change. | [
"Create",
"a",
"state",
"change",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L77-L93 | train | 199,766 |
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.apply_color | def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr | python | def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr | [
"def",
"apply_color",
"(",
"self",
",",
"arr",
",",
"state",
")",
":",
"ops",
"=",
"self",
".",
"cmd",
"(",
"state",
")",
"for",
"func",
"in",
"parse_operations",
"(",
"ops",
")",
":",
"arr",
"=",
"func",
"(",
"arr",
")",
"return",
"arr"
] | Apply color formula to an array. | [
"Apply",
"color",
"formula",
"to",
"an",
"array",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L103-L108 | train | 199,767 |
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.energy | def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100 | python | def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100 | [
"def",
"energy",
"(",
"self",
")",
":",
"arr",
"=",
"self",
".",
"src",
".",
"copy",
"(",
")",
"arr",
"=",
"self",
".",
"apply_color",
"(",
"arr",
",",
"self",
".",
"state",
")",
"scores",
"=",
"[",
"histogram_distance",
"(",
"self",
".",
"ref",
... | Calculate state's energy. | [
"Calculate",
"state",
"s",
"energy",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L110-L118 | train | 199,768 |
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.update | def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw() | python | def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw() | [
"def",
"update",
"(",
"self",
",",
"step",
",",
"T",
",",
"E",
",",
"acceptance",
",",
"improvement",
")",
":",
"if",
"acceptance",
"is",
"None",
":",
"acceptance",
"=",
"0",
"if",
"improvement",
"is",
"None",
":",
"improvement",
"=",
"0",
"if",
"ste... | Print progress. | [
"Print",
"progress",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L124-L165 | train | 199,769 |
mapbox/rio-color | rio_color/workers.py | atmos_worker | def atmos_worker(srcs, window, ij, args):
"""A simple atmospheric correction user function."""
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
# should be scaled 0 to 1, scale to outtype
return scale_dtype(atmos, args["out_dtype"]) | python | def atmos_worker(srcs, window, ij, args):
"""A simple atmospheric correction user function."""
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
# should be scaled 0 to 1, scale to outtype
return scale_dtype(atmos, args["out_dtype"]) | [
"def",
"atmos_worker",
"(",
"srcs",
",",
"window",
",",
"ij",
",",
"args",
")",
":",
"src",
"=",
"srcs",
"[",
"0",
"]",
"rgb",
"=",
"src",
".",
"read",
"(",
"window",
"=",
"window",
")",
"rgb",
"=",
"to_math_type",
"(",
"rgb",
")",
"atmos",
"=",
... | A simple atmospheric correction user function. | [
"A",
"simple",
"atmospheric",
"correction",
"user",
"function",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/workers.py#L9-L18 | train | 199,770 |
mapbox/rio-color | rio_color/workers.py | color_worker | def color_worker(srcs, window, ij, args):
"""A user function."""
src = srcs[0]
arr = src.read(window=window)
arr = to_math_type(arr)
for func in parse_operations(args["ops_string"]):
arr = func(arr)
# scaled 0 to 1, now scale to outtype
return scale_dtype(arr, args["out_dtype"]) | python | def color_worker(srcs, window, ij, args):
"""A user function."""
src = srcs[0]
arr = src.read(window=window)
arr = to_math_type(arr)
for func in parse_operations(args["ops_string"]):
arr = func(arr)
# scaled 0 to 1, now scale to outtype
return scale_dtype(arr, args["out_dtype"]) | [
"def",
"color_worker",
"(",
"srcs",
",",
"window",
",",
"ij",
",",
"args",
")",
":",
"src",
"=",
"srcs",
"[",
"0",
"]",
"arr",
"=",
"src",
".",
"read",
"(",
"window",
"=",
"window",
")",
"arr",
"=",
"to_math_type",
"(",
"arr",
")",
"for",
"func",... | A user function. | [
"A",
"user",
"function",
"."
] | 4e9d7a9348608e66f9381fcdba98c13050e91c83 | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/workers.py#L21-L31 | train | 199,771 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry.add_raw_code | def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list)
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_CODE.append(string)
return | python | def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list)
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_CODE.append(string)
return | [
"def",
"add_raw_code",
"(",
"self",
",",
"string_or_list",
")",
":",
"if",
"_is_string",
"(",
"string_or_list",
")",
":",
"self",
".",
"_GMSH_CODE",
".",
"append",
"(",
"string_or_list",
")",
"else",
":",
"assert",
"isinstance",
"(",
"string_or_list",
",",
"... | Add raw Gmsh code. | [
"Add",
"raw",
"Gmsh",
"code",
"."
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L550-L559 | train | 199,772 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry._add_torus_extrude_lines | def _add_torus_extrude_lines(
self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0])
):
"""Create Gmsh code for the torus in the x-y plane under the coordinate
transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus
"""
self.add_comment("Torus")
# Add circle
x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0]))
# Get circles in y-z plane
Rc = numpy.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]])
c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc))
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi. This
# works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used
# for the following Extrude() step. The second [1] entry of the array
# is the surface that was created by the extrusion.
previous = c.line_loop.lines
angle = "2*Pi/3"
all_surfaces = []
for i in range(3):
self.add_comment("Round no. {}".format(i + 1))
for k, p in enumerate(previous):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
# ...
top, surf, _ = self.extrude(
p,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle,
)
all_surfaces.append(surf)
previous[k] = top
# compound_surface = CompoundSurface(all_surfaces)
surface_loop = self.add_surface_loop(all_surfaces)
vol = self.add_volume(surface_loop)
# The newline at the end is essential:
# If a GEO file doesn't end in a newline, Gmsh will report a syntax
# error.
self.add_comment("\n")
return vol | python | def _add_torus_extrude_lines(
self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0])
):
"""Create Gmsh code for the torus in the x-y plane under the coordinate
transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus
"""
self.add_comment("Torus")
# Add circle
x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0]))
# Get circles in y-z plane
Rc = numpy.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]])
c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc))
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi. This
# works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used
# for the following Extrude() step. The second [1] entry of the array
# is the surface that was created by the extrusion.
previous = c.line_loop.lines
angle = "2*Pi/3"
all_surfaces = []
for i in range(3):
self.add_comment("Round no. {}".format(i + 1))
for k, p in enumerate(previous):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
# ...
top, surf, _ = self.extrude(
p,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle,
)
all_surfaces.append(surf)
previous[k] = top
# compound_surface = CompoundSurface(all_surfaces)
surface_loop = self.add_surface_loop(all_surfaces)
vol = self.add_volume(surface_loop)
# The newline at the end is essential:
# If a GEO file doesn't end in a newline, Gmsh will report a syntax
# error.
self.add_comment("\n")
return vol | [
"def",
"_add_torus_extrude_lines",
"(",
"self",
",",
"irad",
",",
"orad",
",",
"lcar",
"=",
"None",
",",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
")",
",",
"x0",
"=",
"numpy",
".",
"array",
"(",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")",
")"... | Create Gmsh code for the torus in the x-y plane under the coordinate
transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus | [
"Create",
"Gmsh",
"code",
"for",
"the",
"torus",
"in",
"the",
"x",
"-",
"y",
"plane",
"under",
"the",
"coordinate",
"transformation"
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L775-L832 | train | 199,773 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry._add_torus_extrude_circle | def _add_torus_extrude_circle(
self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0])
):
"""Create Gmsh code for the torus under the coordinate transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus
"""
self.add_comment(76 * "-")
self.add_comment("Torus")
# Add circle
x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0]))
Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc))
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi. This
# works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used
# for the following Extrude() step. The second [1] entry of the array
# is the surface that was created by the extrusion. The third [2-end]
# is a list of all the planes of the lateral surface.
previous = c.plane_surface
all_volumes = []
num_steps = 3
for _ in range(num_steps):
top, vol, _ = self.extrude(
previous,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle="2*Pi/{}".format(num_steps),
)
previous = top
all_volumes.append(vol)
if self._gmsh_major() == 3:
# This actually returns the volume, but the gmsh 4 version doesn't have that
# feature. Hence, for compatibility, also ditch it here.
self.add_compound_volume(all_volumes)
else:
assert self._gmsh_major() == 4
self.add_raw_code(
"Compound Volume{{{}}};".format(",".join(v.id for v in all_volumes))
)
self.add_comment(76 * "-" + "\n")
return | python | def _add_torus_extrude_circle(
self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0])
):
"""Create Gmsh code for the torus under the coordinate transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus
"""
self.add_comment(76 * "-")
self.add_comment("Torus")
# Add circle
x0t = numpy.dot(R, numpy.array([0.0, orad, 0.0]))
Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
c = self.add_circle(x0 + x0t, irad, lcar=lcar, R=numpy.dot(R, Rc))
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi. This
# works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used
# for the following Extrude() step. The second [1] entry of the array
# is the surface that was created by the extrusion. The third [2-end]
# is a list of all the planes of the lateral surface.
previous = c.plane_surface
all_volumes = []
num_steps = 3
for _ in range(num_steps):
top, vol, _ = self.extrude(
previous,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle="2*Pi/{}".format(num_steps),
)
previous = top
all_volumes.append(vol)
if self._gmsh_major() == 3:
# This actually returns the volume, but the gmsh 4 version doesn't have that
# feature. Hence, for compatibility, also ditch it here.
self.add_compound_volume(all_volumes)
else:
assert self._gmsh_major() == 4
self.add_raw_code(
"Compound Volume{{{}}};".format(",".join(v.id for v in all_volumes))
)
self.add_comment(76 * "-" + "\n")
return | [
"def",
"_add_torus_extrude_circle",
"(",
"self",
",",
"irad",
",",
"orad",
",",
"lcar",
"=",
"None",
",",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
")",
",",
"x0",
"=",
"numpy",
".",
"array",
"(",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")",
")... | Create Gmsh code for the torus under the coordinate transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the torus
:param orad: outer radius of the torus | [
"Create",
"Gmsh",
"code",
"for",
"the",
"torus",
"under",
"the",
"coordinate",
"transformation"
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L834-L889 | train | 199,774 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry._add_pipe_by_rectangle_rotation | def _add_pipe_by_rectangle_rotation(
self,
outer_radius,
inner_radius,
length,
R=numpy.eye(3),
x0=numpy.array([0.0, 0.0, 0.0]),
lcar=None,
):
"""Hollow cylinder.
Define a rectangle, extrude it by rotation.
"""
self.add_comment("Define rectangle.")
X = numpy.array(
[
[0.0, outer_radius, -0.5 * length],
[0.0, outer_radius, +0.5 * length],
[0.0, inner_radius, +0.5 * length],
[0.0, inner_radius, -0.5 * length],
]
)
# Apply transformation.
X = [numpy.dot(R, x) + x0 for x in X]
# Create points set.
p = [self.add_point(x, lcar=lcar) for x in X]
# Define edges.
e = [
self.add_line(p[0], p[1]),
self.add_line(p[1], p[2]),
self.add_line(p[2], p[3]),
self.add_line(p[3], p[0]),
]
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Extrude all edges three times by 2*Pi/3.
previous = e
angle = "2*Pi/3"
all_surfaces = []
# com = []
self.add_comment("Extrude in 3 steps.")
for i in range(3):
self.add_comment("Step {}".format(i + 1))
for k, p in enumerate(previous):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
top, surf, _ = self.extrude(
p,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle,
)
# if k==0:
# com.append(surf)
# else:
# all_names.appends(surf)
all_surfaces.append(surf)
previous[k] = top
#
# cs = CompoundSurface(com)
# Now just add surface loop and volume.
# all_surfaces = all_names + [cs]
surface_loop = self.add_surface_loop(all_surfaces)
vol = self.add_volume(surface_loop)
return vol | python | def _add_pipe_by_rectangle_rotation(
self,
outer_radius,
inner_radius,
length,
R=numpy.eye(3),
x0=numpy.array([0.0, 0.0, 0.0]),
lcar=None,
):
"""Hollow cylinder.
Define a rectangle, extrude it by rotation.
"""
self.add_comment("Define rectangle.")
X = numpy.array(
[
[0.0, outer_radius, -0.5 * length],
[0.0, outer_radius, +0.5 * length],
[0.0, inner_radius, +0.5 * length],
[0.0, inner_radius, -0.5 * length],
]
)
# Apply transformation.
X = [numpy.dot(R, x) + x0 for x in X]
# Create points set.
p = [self.add_point(x, lcar=lcar) for x in X]
# Define edges.
e = [
self.add_line(p[0], p[1]),
self.add_line(p[1], p[2]),
self.add_line(p[2], p[3]),
self.add_line(p[3], p[0]),
]
rot_axis = [0.0, 0.0, 1.0]
rot_axis = numpy.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = numpy.dot(R, point_on_rot_axis) + x0
# Extrude all edges three times by 2*Pi/3.
previous = e
angle = "2*Pi/3"
all_surfaces = []
# com = []
self.add_comment("Extrude in 3 steps.")
for i in range(3):
self.add_comment("Step {}".format(i + 1))
for k, p in enumerate(previous):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
top, surf, _ = self.extrude(
p,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle,
)
# if k==0:
# com.append(surf)
# else:
# all_names.appends(surf)
all_surfaces.append(surf)
previous[k] = top
#
# cs = CompoundSurface(com)
# Now just add surface loop and volume.
# all_surfaces = all_names + [cs]
surface_loop = self.add_surface_loop(all_surfaces)
vol = self.add_volume(surface_loop)
return vol | [
"def",
"_add_pipe_by_rectangle_rotation",
"(",
"self",
",",
"outer_radius",
",",
"inner_radius",
",",
"length",
",",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
")",
",",
"x0",
"=",
"numpy",
".",
"array",
"(",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")... | Hollow cylinder.
Define a rectangle, extrude it by rotation. | [
"Hollow",
"cylinder",
".",
"Define",
"a",
"rectangle",
"extrude",
"it",
"by",
"rotation",
"."
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L910-L977 | train | 199,775 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry._add_pipe_by_circle_extrusion | def _add_pipe_by_circle_extrusion(
self,
outer_radius,
inner_radius,
length,
R=numpy.eye(3),
x0=numpy.array([0.0, 0.0, 0.0]),
lcar=None,
):
"""Hollow cylinder.
Define a ring, extrude it by translation.
"""
# Define ring which to Extrude by translation.
Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
c_inner = self.add_circle(
x0, inner_radius, lcar=lcar, R=numpy.dot(R, Rc), make_surface=False
)
circ = self.add_circle(
x0, outer_radius, lcar=lcar, R=numpy.dot(R, Rc), holes=[c_inner.line_loop]
)
# Now Extrude the ring surface.
_, vol, _ = self.extrude(
circ.plane_surface, translation_axis=numpy.dot(R, [length, 0, 0])
)
return vol | python | def _add_pipe_by_circle_extrusion(
self,
outer_radius,
inner_radius,
length,
R=numpy.eye(3),
x0=numpy.array([0.0, 0.0, 0.0]),
lcar=None,
):
"""Hollow cylinder.
Define a ring, extrude it by translation.
"""
# Define ring which to Extrude by translation.
Rc = numpy.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
c_inner = self.add_circle(
x0, inner_radius, lcar=lcar, R=numpy.dot(R, Rc), make_surface=False
)
circ = self.add_circle(
x0, outer_radius, lcar=lcar, R=numpy.dot(R, Rc), holes=[c_inner.line_loop]
)
# Now Extrude the ring surface.
_, vol, _ = self.extrude(
circ.plane_surface, translation_axis=numpy.dot(R, [length, 0, 0])
)
return vol | [
"def",
"_add_pipe_by_circle_extrusion",
"(",
"self",
",",
"outer_radius",
",",
"inner_radius",
",",
"length",
",",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
")",
",",
"x0",
"=",
"numpy",
".",
"array",
"(",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")",... | Hollow cylinder.
Define a ring, extrude it by translation. | [
"Hollow",
"cylinder",
".",
"Define",
"a",
"ring",
"extrude",
"it",
"by",
"translation",
"."
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L979-L1004 | train | 199,776 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry.translate | def translate(self, input_entity, vector):
"""Translates input_entity itself by vector.
Changes the input object.
"""
d = {1: "Line", 2: "Surface", 3: "Volume"}
self._GMSH_CODE.append(
"Translate {{{}}} {{ {}{{{}}}; }}".format(
", ".join([str(co) for co in vector]),
d[input_entity.dimension],
input_entity.id,
)
)
return | python | def translate(self, input_entity, vector):
"""Translates input_entity itself by vector.
Changes the input object.
"""
d = {1: "Line", 2: "Surface", 3: "Volume"}
self._GMSH_CODE.append(
"Translate {{{}}} {{ {}{{{}}}; }}".format(
", ".join([str(co) for co in vector]),
d[input_entity.dimension],
input_entity.id,
)
)
return | [
"def",
"translate",
"(",
"self",
",",
"input_entity",
",",
"vector",
")",
":",
"d",
"=",
"{",
"1",
":",
"\"Line\"",
",",
"2",
":",
"\"Surface\"",
",",
"3",
":",
"\"Volume\"",
"}",
"self",
".",
"_GMSH_CODE",
".",
"append",
"(",
"\"Translate {{{}}} {{ {}{{... | Translates input_entity itself by vector.
Changes the input object. | [
"Translates",
"input_entity",
"itself",
"by",
"vector",
"."
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L1006-L1019 | train | 199,777 |
nschloe/pygmsh | pygmsh/built_in/geometry.py | Geometry.symmetry | def symmetry(self, input_entity, coefficients, duplicate=True):
"""Transforms all elementary entities symmetrically to a plane. The vector
should contain four expressions giving the coefficients of the plane's equation.
"""
d = {1: "Line", 2: "Surface", 3: "Volume"}
entity = "{}{{{}}};".format(d[input_entity.dimension], input_entity.id)
if duplicate:
entity = "Duplicata{{{}}}".format(entity)
self._GMSH_CODE.append(
"Symmetry {{{}}} {{{}}}".format(
", ".join([str(co) for co in coefficients]), entity
)
)
return | python | def symmetry(self, input_entity, coefficients, duplicate=True):
"""Transforms all elementary entities symmetrically to a plane. The vector
should contain four expressions giving the coefficients of the plane's equation.
"""
d = {1: "Line", 2: "Surface", 3: "Volume"}
entity = "{}{{{}}};".format(d[input_entity.dimension], input_entity.id)
if duplicate:
entity = "Duplicata{{{}}}".format(entity)
self._GMSH_CODE.append(
"Symmetry {{{}}} {{{}}}".format(
", ".join([str(co) for co in coefficients]), entity
)
)
return | [
"def",
"symmetry",
"(",
"self",
",",
"input_entity",
",",
"coefficients",
",",
"duplicate",
"=",
"True",
")",
":",
"d",
"=",
"{",
"1",
":",
"\"Line\"",
",",
"2",
":",
"\"Surface\"",
",",
"3",
":",
"\"Volume\"",
"}",
"entity",
"=",
"\"{}{{{}}};\"",
".",... | Transforms all elementary entities symmetrically to a plane. The vector
should contain four expressions giving the coefficients of the plane's equation. | [
"Transforms",
"all",
"elementary",
"entities",
"symmetrically",
"to",
"a",
"plane",
".",
"The",
"vector",
"should",
"contain",
"four",
"expressions",
"giving",
"the",
"coefficients",
"of",
"the",
"plane",
"s",
"equation",
"."
] | 1a1a07481aebe6c161b60dd31e0fbe1ddf330d61 | https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L1021-L1036 | train | 199,778 |
spyder-ide/qtpy | qtpy/_patch/qcombobox.py | patch_qcombobox | def patch_qcombobox(QComboBox):
"""
In PySide, using Python objects as userData in QComboBox causes
Segmentation faults under certain conditions. Even in cases where it
doesn't, findData does not work correctly. Likewise, findData also does not
work correctly with Python objects when using PyQt4. On the other hand,
PyQt5 deals with this case correctly. We therefore patch QComboBox when
using PyQt4 and PySide to avoid issues.
"""
from ..QtGui import QIcon
from ..QtCore import Qt, QObject
class userDataWrapper():
"""
This class is used to wrap any userData object. If we don't do this,
then certain types of objects can cause segmentation faults or issues
depending on whether/how __getitem__ is defined.
"""
def __init__(self, data):
self.data = data
_addItem = QComboBox.addItem
def addItem(self, *args, **kwargs):
if len(args) == 3 or (not isinstance(args[0], QIcon)
and len(args) == 2):
args, kwargs['userData'] = args[:-1], args[-1]
if 'userData' in kwargs:
kwargs['userData'] = userDataWrapper(kwargs['userData'])
_addItem(self, *args, **kwargs)
_insertItem = QComboBox.insertItem
def insertItem(self, *args, **kwargs):
if len(args) == 4 or (not isinstance(args[1], QIcon)
and len(args) == 3):
args, kwargs['userData'] = args[:-1], args[-1]
if 'userData' in kwargs:
kwargs['userData'] = userDataWrapper(kwargs['userData'])
_insertItem(self, *args, **kwargs)
_setItemData = QComboBox.setItemData
def setItemData(self, index, value, role=Qt.UserRole):
value = userDataWrapper(value)
_setItemData(self, index, value, role=role)
_itemData = QComboBox.itemData
def itemData(self, index, role=Qt.UserRole):
userData = _itemData(self, index, role=role)
if isinstance(userData, userDataWrapper):
userData = userData.data
return userData
def findData(self, value):
for i in range(self.count()):
if self.itemData(i) == value:
return i
return -1
QComboBox.addItem = addItem
QComboBox.insertItem = insertItem
QComboBox.setItemData = setItemData
QComboBox.itemData = itemData
QComboBox.findData = findData | python | def patch_qcombobox(QComboBox):
"""
In PySide, using Python objects as userData in QComboBox causes
Segmentation faults under certain conditions. Even in cases where it
doesn't, findData does not work correctly. Likewise, findData also does not
work correctly with Python objects when using PyQt4. On the other hand,
PyQt5 deals with this case correctly. We therefore patch QComboBox when
using PyQt4 and PySide to avoid issues.
"""
from ..QtGui import QIcon
from ..QtCore import Qt, QObject
class userDataWrapper():
"""
This class is used to wrap any userData object. If we don't do this,
then certain types of objects can cause segmentation faults or issues
depending on whether/how __getitem__ is defined.
"""
def __init__(self, data):
self.data = data
_addItem = QComboBox.addItem
def addItem(self, *args, **kwargs):
if len(args) == 3 or (not isinstance(args[0], QIcon)
and len(args) == 2):
args, kwargs['userData'] = args[:-1], args[-1]
if 'userData' in kwargs:
kwargs['userData'] = userDataWrapper(kwargs['userData'])
_addItem(self, *args, **kwargs)
_insertItem = QComboBox.insertItem
def insertItem(self, *args, **kwargs):
if len(args) == 4 or (not isinstance(args[1], QIcon)
and len(args) == 3):
args, kwargs['userData'] = args[:-1], args[-1]
if 'userData' in kwargs:
kwargs['userData'] = userDataWrapper(kwargs['userData'])
_insertItem(self, *args, **kwargs)
_setItemData = QComboBox.setItemData
def setItemData(self, index, value, role=Qt.UserRole):
value = userDataWrapper(value)
_setItemData(self, index, value, role=role)
_itemData = QComboBox.itemData
def itemData(self, index, role=Qt.UserRole):
userData = _itemData(self, index, role=role)
if isinstance(userData, userDataWrapper):
userData = userData.data
return userData
def findData(self, value):
for i in range(self.count()):
if self.itemData(i) == value:
return i
return -1
QComboBox.addItem = addItem
QComboBox.insertItem = insertItem
QComboBox.setItemData = setItemData
QComboBox.itemData = itemData
QComboBox.findData = findData | [
"def",
"patch_qcombobox",
"(",
"QComboBox",
")",
":",
"from",
".",
".",
"QtGui",
"import",
"QIcon",
"from",
".",
".",
"QtCore",
"import",
"Qt",
",",
"QObject",
"class",
"userDataWrapper",
"(",
")",
":",
"\"\"\"\n This class is used to wrap any userData object... | In PySide, using Python objects as userData in QComboBox causes
Segmentation faults under certain conditions. Even in cases where it
doesn't, findData does not work correctly. Likewise, findData also does not
work correctly with Python objects when using PyQt4. On the other hand,
PyQt5 deals with this case correctly. We therefore patch QComboBox when
using PyQt4 and PySide to avoid issues. | [
"In",
"PySide",
"using",
"Python",
"objects",
"as",
"userData",
"in",
"QComboBox",
"causes",
"Segmentation",
"faults",
"under",
"certain",
"conditions",
".",
"Even",
"in",
"cases",
"where",
"it",
"doesn",
"t",
"findData",
"does",
"not",
"work",
"correctly",
".... | f22ca102b934c4605c0eaeae947c2f2ec90de9a5 | https://github.com/spyder-ide/qtpy/blob/f22ca102b934c4605c0eaeae947c2f2ec90de9a5/qtpy/_patch/qcombobox.py#L35-L101 | train | 199,779 |
xoolive/traffic | traffic/plugins/cesiumjs.py | to_czml | def to_czml(
traffic: Union[Traffic, SO6],
filename: Union[str, Path],
minimum_time: Optional[timelike] = None,
) -> None:
"""Generates a CesiumJS scenario file."""
if isinstance(traffic, Traffic):
if "baro_altitude" in traffic.data.columns:
traffic = traffic.query("baro_altitude == baro_altitude")
elif "altitude" in traffic.data.columns:
traffic = traffic.query("altitude == altitude")
if minimum_time is not None:
minimum_time = to_datetime(minimum_time)
traffic = cast(Traffic, traffic.query(f"timestamp >= '{minimum_time}'"))
if isinstance(filename, str):
filename = Path(filename)
if not filename.parent.exists():
filename.parent.mkdir(parents=True)
start = format_ts(traffic.start_time)
availability = f"{start}/{format_ts(traffic.end_time)}"
export = [
{
"id": "document",
"name": f"Traffic_{start}",
"version": "1.0",
"author": getpass.getuser(),
"clock": {
"interval": availability,
"currentTime": start,
"multiplier": _CZML_Params.default_time_multiplier,
},
}
]
for flight in traffic:
for elt in export_flight(flight):
export.append(elt)
with filename.open("w") as fh:
json.dump(export, fh, indent=2)
logging.info(f"Scenario file {filename} written") | python | def to_czml(
traffic: Union[Traffic, SO6],
filename: Union[str, Path],
minimum_time: Optional[timelike] = None,
) -> None:
"""Generates a CesiumJS scenario file."""
if isinstance(traffic, Traffic):
if "baro_altitude" in traffic.data.columns:
traffic = traffic.query("baro_altitude == baro_altitude")
elif "altitude" in traffic.data.columns:
traffic = traffic.query("altitude == altitude")
if minimum_time is not None:
minimum_time = to_datetime(minimum_time)
traffic = cast(Traffic, traffic.query(f"timestamp >= '{minimum_time}'"))
if isinstance(filename, str):
filename = Path(filename)
if not filename.parent.exists():
filename.parent.mkdir(parents=True)
start = format_ts(traffic.start_time)
availability = f"{start}/{format_ts(traffic.end_time)}"
export = [
{
"id": "document",
"name": f"Traffic_{start}",
"version": "1.0",
"author": getpass.getuser(),
"clock": {
"interval": availability,
"currentTime": start,
"multiplier": _CZML_Params.default_time_multiplier,
},
}
]
for flight in traffic:
for elt in export_flight(flight):
export.append(elt)
with filename.open("w") as fh:
json.dump(export, fh, indent=2)
logging.info(f"Scenario file {filename} written") | [
"def",
"to_czml",
"(",
"traffic",
":",
"Union",
"[",
"Traffic",
",",
"SO6",
"]",
",",
"filename",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"minimum_time",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"if"... | Generates a CesiumJS scenario file. | [
"Generates",
"a",
"CesiumJS",
"scenario",
"file",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/plugins/cesiumjs.py#L90-L135 | train | 199,780 |
xoolive/traffic | traffic/data/adsb/opensky.py | SensorRange.plot | def plot(self, ax: GeoAxesSubplot, **kwargs) -> Artist:
"""Plotting function. All arguments are passed to the geometry"""
if "facecolor" not in kwargs:
kwargs["facecolor"] = "None"
if "edgecolor" not in kwargs:
kwargs["edgecolor"] = ax._get_lines.get_next_color()
if "projection" in ax.__dict__:
return ax.add_geometries([self.shape], crs=PlateCarree(), **kwargs)
else:
return ax.add_patch(
MplPolygon(list(self.shape.exterior.coords), **kwargs)
) | python | def plot(self, ax: GeoAxesSubplot, **kwargs) -> Artist:
"""Plotting function. All arguments are passed to the geometry"""
if "facecolor" not in kwargs:
kwargs["facecolor"] = "None"
if "edgecolor" not in kwargs:
kwargs["edgecolor"] = ax._get_lines.get_next_color()
if "projection" in ax.__dict__:
return ax.add_geometries([self.shape], crs=PlateCarree(), **kwargs)
else:
return ax.add_patch(
MplPolygon(list(self.shape.exterior.coords), **kwargs)
) | [
"def",
"plot",
"(",
"self",
",",
"ax",
":",
"GeoAxesSubplot",
",",
"*",
"*",
"kwargs",
")",
"->",
"Artist",
":",
"if",
"\"facecolor\"",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"facecolor\"",
"]",
"=",
"\"None\"",
"if",
"\"edgecolor\"",
"not",
"in",
... | Plotting function. All arguments are passed to the geometry | [
"Plotting",
"function",
".",
"All",
"arguments",
"are",
"passed",
"to",
"the",
"geometry"
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L76-L89 | train | 199,781 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_states | def api_states(
self,
own: bool = False,
bounds: Union[
BaseGeometry, Tuple[float, float, float, float], None
] = None,
) -> StateVectors:
"""Returns the current state vectors from OpenSky REST API.
If own parameter is set to True, returns only the state vectors
associated to own sensors (requires authentication)
bounds parameter can be a shape or a tuple of float.
Official documentation
----------------------
Limitiations for anonymous (unauthenticated) users
Anonymous are those users who access the API without using credentials.
The limitations for anonymous users are:
Anonymous users can only get the most recent state vectors, i.e. the
time parameter will be ignored. Anonymous users can only retrieve data
with a time resultion of 10 seconds. That means, the API will return
state vectors for time now − (now mod 10)
Limitations for OpenSky users
An OpenSky user is anybody who uses a valid OpenSky account (see below)
to access the API. The rate limitations for OpenSky users are:
- OpenSky users can retrieve data of up to 1 hour in the past. If the
time parameter has a value t < now−3600 the API will return
400 Bad Request.
- OpenSky users can retrieve data with a time resultion of 5 seconds.
That means, if the time parameter was set to t , the API will return
state vectors for time t−(t mod 5).
"""
what = "own" if (own and self.auth is not None) else "all"
if bounds is not None:
try:
# thinking of shapely bounds attribute (in this order)
# I just don't want to add the shapely dependency here
west, south, east, north = bounds.bounds # type: ignore
except AttributeError:
west, south, east, north = bounds
what += f"?lamin={south}&lamax={north}&lomin={west}&lomax={east}"
c = requests.get(
f"https://opensky-network.org/api/states/{what}", auth=self.auth
)
if c.status_code != 200:
raise ValueError(c.content.decode())
r = pd.DataFrame.from_records(
c.json()["states"], columns=self._json_columns
)
r = r.drop(["origin_country", "spi", "sensors"], axis=1)
r = r.dropna()
return StateVectors(
self._format_dataframe(r, nautical_units=True), self
) | python | def api_states(
self,
own: bool = False,
bounds: Union[
BaseGeometry, Tuple[float, float, float, float], None
] = None,
) -> StateVectors:
"""Returns the current state vectors from OpenSky REST API.
If own parameter is set to True, returns only the state vectors
associated to own sensors (requires authentication)
bounds parameter can be a shape or a tuple of float.
Official documentation
----------------------
Limitiations for anonymous (unauthenticated) users
Anonymous are those users who access the API without using credentials.
The limitations for anonymous users are:
Anonymous users can only get the most recent state vectors, i.e. the
time parameter will be ignored. Anonymous users can only retrieve data
with a time resultion of 10 seconds. That means, the API will return
state vectors for time now − (now mod 10)
Limitations for OpenSky users
An OpenSky user is anybody who uses a valid OpenSky account (see below)
to access the API. The rate limitations for OpenSky users are:
- OpenSky users can retrieve data of up to 1 hour in the past. If the
time parameter has a value t < now−3600 the API will return
400 Bad Request.
- OpenSky users can retrieve data with a time resultion of 5 seconds.
That means, if the time parameter was set to t , the API will return
state vectors for time t−(t mod 5).
"""
what = "own" if (own and self.auth is not None) else "all"
if bounds is not None:
try:
# thinking of shapely bounds attribute (in this order)
# I just don't want to add the shapely dependency here
west, south, east, north = bounds.bounds # type: ignore
except AttributeError:
west, south, east, north = bounds
what += f"?lamin={south}&lamax={north}&lomin={west}&lomax={east}"
c = requests.get(
f"https://opensky-network.org/api/states/{what}", auth=self.auth
)
if c.status_code != 200:
raise ValueError(c.content.decode())
r = pd.DataFrame.from_records(
c.json()["states"], columns=self._json_columns
)
r = r.drop(["origin_country", "spi", "sensors"], axis=1)
r = r.dropna()
return StateVectors(
self._format_dataframe(r, nautical_units=True), self
) | [
"def",
"api_states",
"(",
"self",
",",
"own",
":",
"bool",
"=",
"False",
",",
"bounds",
":",
"Union",
"[",
"BaseGeometry",
",",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
",",
"float",
"]",
",",
"None",
"]",
"=",
"None",
",",
")",
"->",
"... | Returns the current state vectors from OpenSky REST API.
If own parameter is set to True, returns only the state vectors
associated to own sensors (requires authentication)
bounds parameter can be a shape or a tuple of float.
Official documentation
----------------------
Limitiations for anonymous (unauthenticated) users
Anonymous are those users who access the API without using credentials.
The limitations for anonymous users are:
Anonymous users can only get the most recent state vectors, i.e. the
time parameter will be ignored. Anonymous users can only retrieve data
with a time resultion of 10 seconds. That means, the API will return
state vectors for time now − (now mod 10)
Limitations for OpenSky users
An OpenSky user is anybody who uses a valid OpenSky account (see below)
to access the API. The rate limitations for OpenSky users are:
- OpenSky users can retrieve data of up to 1 hour in the past. If the
time parameter has a value t < now−3600 the API will return
400 Bad Request.
- OpenSky users can retrieve data with a time resultion of 5 seconds.
That means, if the time parameter was set to t , the API will return
state vectors for time t−(t mod 5). | [
"Returns",
"the",
"current",
"state",
"vectors",
"from",
"OpenSky",
"REST",
"API",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L133-L201 | train | 199,782 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_tracks | def api_tracks(self, icao24: str) -> Flight:
"""Returns a Flight corresponding to a given aircraft.
Official documentation
----------------------
Retrieve the trajectory for a certain aircraft at a given time. The
trajectory is a list of waypoints containing position, barometric
altitude, true track and an on-ground flag.
In contrast to state vectors, trajectories do not contain all
information we have about the flight, but rather show the aircraft’s
general movement pattern. For this reason, waypoints are selected among
available state vectors given the following set of rules:
- The first point is set immediately after the the aircraft’s expected
departure, or after the network received the first poisition when the
aircraft entered its reception range.
- The last point is set right before the aircraft’s expected arrival, or
the aircraft left the networks reception range.
- There is a waypoint at least every 15 minutes when the aircraft is
in-flight.
- A waypoint is added if the aircraft changes its track more than 2.5°.
- A waypoint is added if the aircraft changes altitude by more than 100m
(~330ft).
- A waypoint is added if the on-ground state changes.
Tracks are strongly related to flights. Internally, we compute flights
and tracks within the same processing step. As such, it may be
benificial to retrieve a list of flights with the API methods from
above, and use these results with the given time stamps to retrieve
detailed track information.
"""
c = requests.get(
f"https://opensky-network.org/api/tracks/?icao24={icao24}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
json = c.json()
df = pd.DataFrame.from_records(
json["path"],
columns=[
"timestamp",
"latitude",
"longitude",
"altitude",
"track",
"onground",
],
).assign(icao24=json["icao24"], callsign=json["callsign"])
return Flight(self._format_dataframe(df, nautical_units=True)) | python | def api_tracks(self, icao24: str) -> Flight:
"""Returns a Flight corresponding to a given aircraft.
Official documentation
----------------------
Retrieve the trajectory for a certain aircraft at a given time. The
trajectory is a list of waypoints containing position, barometric
altitude, true track and an on-ground flag.
In contrast to state vectors, trajectories do not contain all
information we have about the flight, but rather show the aircraft’s
general movement pattern. For this reason, waypoints are selected among
available state vectors given the following set of rules:
- The first point is set immediately after the the aircraft’s expected
departure, or after the network received the first poisition when the
aircraft entered its reception range.
- The last point is set right before the aircraft’s expected arrival, or
the aircraft left the networks reception range.
- There is a waypoint at least every 15 minutes when the aircraft is
in-flight.
- A waypoint is added if the aircraft changes its track more than 2.5°.
- A waypoint is added if the aircraft changes altitude by more than 100m
(~330ft).
- A waypoint is added if the on-ground state changes.
Tracks are strongly related to flights. Internally, we compute flights
and tracks within the same processing step. As such, it may be
benificial to retrieve a list of flights with the API methods from
above, and use these results with the given time stamps to retrieve
detailed track information.
"""
c = requests.get(
f"https://opensky-network.org/api/tracks/?icao24={icao24}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
json = c.json()
df = pd.DataFrame.from_records(
json["path"],
columns=[
"timestamp",
"latitude",
"longitude",
"altitude",
"track",
"onground",
],
).assign(icao24=json["icao24"], callsign=json["callsign"])
return Flight(self._format_dataframe(df, nautical_units=True)) | [
"def",
"api_tracks",
"(",
"self",
",",
"icao24",
":",
"str",
")",
"->",
"Flight",
":",
"c",
"=",
"requests",
".",
"get",
"(",
"f\"https://opensky-network.org/api/tracks/?icao24={icao24}\"",
")",
"if",
"c",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ValueE... | Returns a Flight corresponding to a given aircraft.
Official documentation
----------------------
Retrieve the trajectory for a certain aircraft at a given time. The
trajectory is a list of waypoints containing position, barometric
altitude, true track and an on-ground flag.
In contrast to state vectors, trajectories do not contain all
information we have about the flight, but rather show the aircraft’s
general movement pattern. For this reason, waypoints are selected among
available state vectors given the following set of rules:
- The first point is set immediately after the the aircraft’s expected
departure, or after the network received the first poisition when the
aircraft entered its reception range.
- The last point is set right before the aircraft’s expected arrival, or
the aircraft left the networks reception range.
- There is a waypoint at least every 15 minutes when the aircraft is
in-flight.
- A waypoint is added if the aircraft changes its track more than 2.5°.
- A waypoint is added if the aircraft changes altitude by more than 100m
(~330ft).
- A waypoint is added if the on-ground state changes.
Tracks are strongly related to flights. Internally, we compute flights
and tracks within the same processing step. As such, it may be
benificial to retrieve a list of flights with the API methods from
above, and use these results with the given time stamps to retrieve
detailed track information. | [
"Returns",
"a",
"Flight",
"corresponding",
"to",
"a",
"given",
"aircraft",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L203-L255 | train | 199,783 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_routes | def api_routes(self, callsign: str) -> Tuple[Airport, ...]:
"""Returns the route associated to a callsign."""
from .. import airports
c = requests.get(
f"https://opensky-network.org/api/routes?callsign={callsign}"
)
if c.status_code == 404:
raise ValueError("Unknown callsign")
if c.status_code != 200:
raise ValueError(c.content.decode())
json = c.json()
return tuple(airports[a] for a in json["route"]) | python | def api_routes(self, callsign: str) -> Tuple[Airport, ...]:
"""Returns the route associated to a callsign."""
from .. import airports
c = requests.get(
f"https://opensky-network.org/api/routes?callsign={callsign}"
)
if c.status_code == 404:
raise ValueError("Unknown callsign")
if c.status_code != 200:
raise ValueError(c.content.decode())
json = c.json()
return tuple(airports[a] for a in json["route"]) | [
"def",
"api_routes",
"(",
"self",
",",
"callsign",
":",
"str",
")",
"->",
"Tuple",
"[",
"Airport",
",",
"...",
"]",
":",
"from",
".",
".",
"import",
"airports",
"c",
"=",
"requests",
".",
"get",
"(",
"f\"https://opensky-network.org/api/routes?callsign={callsig... | Returns the route associated to a callsign. | [
"Returns",
"the",
"route",
"associated",
"to",
"a",
"callsign",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L257-L270 | train | 199,784 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_aircraft | def api_aircraft(
self,
icao24: str,
begin: Optional[timelike] = None,
end: Optional[timelike] = None,
) -> pd.DataFrame:
"""Returns a flight table associated to an aircraft.
Official documentation
----------------------
This API call retrieves flights for a particular aircraft within a
certain time interval. Resulting flights departed and arrived within
[begin, end]. If no flights are found for the given period, HTTP stats
404 - Not found is returned with an empty response body.
"""
if begin is None:
begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
begin = to_datetime(begin)
if end is None:
end = begin + timedelta(days=1)
else:
end = to_datetime(end)
begin = int(begin.timestamp())
end = int(end.timestamp())
c = requests.get(
f"https://opensky-network.org/api/flights/aircraft"
f"?icao24={icao24}&begin={begin}&end={end}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return (
pd.DataFrame.from_records(c.json())[
[
"firstSeen",
"lastSeen",
"icao24",
"callsign",
"estDepartureAirport",
"estArrivalAirport",
]
]
.assign(
firstSeen=lambda df: pd.to_datetime(
df.firstSeen * 1e9
).dt.tz_localize("utc"),
lastSeen=lambda df: pd.to_datetime(
df.lastSeen * 1e9
).dt.tz_localize("utc"),
)
.sort_values("lastSeen")
) | python | def api_aircraft(
self,
icao24: str,
begin: Optional[timelike] = None,
end: Optional[timelike] = None,
) -> pd.DataFrame:
"""Returns a flight table associated to an aircraft.
Official documentation
----------------------
This API call retrieves flights for a particular aircraft within a
certain time interval. Resulting flights departed and arrived within
[begin, end]. If no flights are found for the given period, HTTP stats
404 - Not found is returned with an empty response body.
"""
if begin is None:
begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
begin = to_datetime(begin)
if end is None:
end = begin + timedelta(days=1)
else:
end = to_datetime(end)
begin = int(begin.timestamp())
end = int(end.timestamp())
c = requests.get(
f"https://opensky-network.org/api/flights/aircraft"
f"?icao24={icao24}&begin={begin}&end={end}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return (
pd.DataFrame.from_records(c.json())[
[
"firstSeen",
"lastSeen",
"icao24",
"callsign",
"estDepartureAirport",
"estArrivalAirport",
]
]
.assign(
firstSeen=lambda df: pd.to_datetime(
df.firstSeen * 1e9
).dt.tz_localize("utc"),
lastSeen=lambda df: pd.to_datetime(
df.lastSeen * 1e9
).dt.tz_localize("utc"),
)
.sort_values("lastSeen")
) | [
"def",
"api_aircraft",
"(",
"self",
",",
"icao24",
":",
"str",
",",
"begin",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
"end",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
")",
"->",
"pd",
".",
"DataFrame",
":",
"if",
"beg... | Returns a flight table associated to an aircraft.
Official documentation
----------------------
This API call retrieves flights for a particular aircraft within a
certain time interval. Resulting flights departed and arrived within
[begin, end]. If no flights are found for the given period, HTTP stats
404 - Not found is returned with an empty response body. | [
"Returns",
"a",
"flight",
"table",
"associated",
"to",
"an",
"aircraft",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L272-L327 | train | 199,785 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_range | def api_range(
self, serial: str, date: Optional[timelike] = None
) -> SensorRange:
"""Wraps a polygon representing a sensor's range.
By default, returns the current range. Otherwise, you may enter a
specific day (as a string, as an epoch or as a datetime)
"""
if date is None:
date = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
else:
date = to_datetime(date)
date = int(date.timestamp())
c = requests.get(
f"https://opensky-network.org/api/range/days"
f"?days={date}&serials={serial}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return SensorRange(c.json()) | python | def api_range(
self, serial: str, date: Optional[timelike] = None
) -> SensorRange:
"""Wraps a polygon representing a sensor's range.
By default, returns the current range. Otherwise, you may enter a
specific day (as a string, as an epoch or as a datetime)
"""
if date is None:
date = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
else:
date = to_datetime(date)
date = int(date.timestamp())
c = requests.get(
f"https://opensky-network.org/api/range/days"
f"?days={date}&serials={serial}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return SensorRange(c.json()) | [
"def",
"api_range",
"(",
"self",
",",
"serial",
":",
"str",
",",
"date",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
")",
"->",
"SensorRange",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"round_time",
"(",
"datetime",
".",
"now",
"(",
... | Wraps a polygon representing a sensor's range.
By default, returns the current range. Otherwise, you may enter a
specific day (as a string, as an epoch or as a datetime) | [
"Wraps",
"a",
"polygon",
"representing",
"a",
"sensor",
"s",
"range",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L342-L363 | train | 199,786 |
xoolive/traffic | traffic/data/adsb/opensky.py | OpenSky.api_arrival | def api_arrival(
self,
airport: Union[str, Airport],
begin: Optional[timelike] = None,
end: Optional[timelike] = None,
) -> pd.DataFrame:
"""Returns a flight table associated to an airport.
By default, returns the current table. Otherwise, you may enter a
specific date (as a string, as an epoch or as a datetime)
Official documentation
----------------------
Retrieve flights for a certain airport which arrived within a given time
interval [begin, end]. If no flights are found for the given period,
HTTP stats 404 - Not found is returned with an empty response body.
"""
if isinstance(airport, str):
from .. import airports
airport_code = airports[airport].icao
else:
airport_code = airport.icao
if begin is None:
begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
begin = to_datetime(begin)
if end is None:
end = begin + timedelta(days=1)
else:
end = to_datetime(end)
begin = int(begin.timestamp())
end = int(end.timestamp())
c = requests.get(
f"https://opensky-network.org/api/flights/arrival"
f"?begin={begin}&airport={airport_code}&end={end}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return (
pd.DataFrame.from_records(c.json())[
[
"firstSeen",
"lastSeen",
"icao24",
"callsign",
"estDepartureAirport",
"estArrivalAirport",
]
]
.assign(
firstSeen=lambda df: pd.to_datetime(
df.firstSeen * 1e9
).dt.tz_localize("utc"),
lastSeen=lambda df: pd.to_datetime(
df.lastSeen * 1e9
).dt.tz_localize("utc"),
)
.sort_values("lastSeen")
) | python | def api_arrival(
self,
airport: Union[str, Airport],
begin: Optional[timelike] = None,
end: Optional[timelike] = None,
) -> pd.DataFrame:
"""Returns a flight table associated to an airport.
By default, returns the current table. Otherwise, you may enter a
specific date (as a string, as an epoch or as a datetime)
Official documentation
----------------------
Retrieve flights for a certain airport which arrived within a given time
interval [begin, end]. If no flights are found for the given period,
HTTP stats 404 - Not found is returned with an empty response body.
"""
if isinstance(airport, str):
from .. import airports
airport_code = airports[airport].icao
else:
airport_code = airport.icao
if begin is None:
begin = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
begin = to_datetime(begin)
if end is None:
end = begin + timedelta(days=1)
else:
end = to_datetime(end)
begin = int(begin.timestamp())
end = int(end.timestamp())
c = requests.get(
f"https://opensky-network.org/api/flights/arrival"
f"?begin={begin}&airport={airport_code}&end={end}"
)
if c.status_code != 200:
raise ValueError(c.content.decode())
return (
pd.DataFrame.from_records(c.json())[
[
"firstSeen",
"lastSeen",
"icao24",
"callsign",
"estDepartureAirport",
"estArrivalAirport",
]
]
.assign(
firstSeen=lambda df: pd.to_datetime(
df.firstSeen * 1e9
).dt.tz_localize("utc"),
lastSeen=lambda df: pd.to_datetime(
df.lastSeen * 1e9
).dt.tz_localize("utc"),
)
.sort_values("lastSeen")
) | [
"def",
"api_arrival",
"(",
"self",
",",
"airport",
":",
"Union",
"[",
"str",
",",
"Airport",
"]",
",",
"begin",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
"end",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
")",
"->",
"pd"... | Returns a flight table associated to an airport.
By default, returns the current table. Otherwise, you may enter a
specific date (as a string, as an epoch or as a datetime)
Official documentation
----------------------
Retrieve flights for a certain airport which arrived within a given time
interval [begin, end]. If no flights are found for the given period,
HTTP stats 404 - Not found is returned with an empty response body. | [
"Returns",
"a",
"flight",
"table",
"associated",
"to",
"an",
"airport",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L371-L437 | train | 199,787 |
xoolive/traffic | traffic/core/flight.py | Flight.start | def start(self) -> pd.Timestamp:
"""Returns the minimum timestamp value of the DataFrame."""
start = self.data.timestamp.min()
self.data = self.data.assign(start=start)
return start | python | def start(self) -> pd.Timestamp:
"""Returns the minimum timestamp value of the DataFrame."""
start = self.data.timestamp.min()
self.data = self.data.assign(start=start)
return start | [
"def",
"start",
"(",
"self",
")",
"->",
"pd",
".",
"Timestamp",
":",
"start",
"=",
"self",
".",
"data",
".",
"timestamp",
".",
"min",
"(",
")",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"assign",
"(",
"start",
"=",
"start",
")",
"return... | Returns the minimum timestamp value of the DataFrame. | [
"Returns",
"the",
"minimum",
"timestamp",
"value",
"of",
"the",
"DataFrame",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L144-L148 | train | 199,788 |
xoolive/traffic | traffic/core/flight.py | Flight.squawk | def squawk(self) -> Set[str]:
"""Returns all the unique squawk values in the trajectory."""
return set(self.data.squawk.ffill().bfill()) | python | def squawk(self) -> Set[str]:
"""Returns all the unique squawk values in the trajectory."""
return set(self.data.squawk.ffill().bfill()) | [
"def",
"squawk",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"set",
"(",
"self",
".",
"data",
".",
"squawk",
".",
"ffill",
"(",
")",
".",
"bfill",
"(",
")",
")"
] | Returns all the unique squawk values in the trajectory. | [
"Returns",
"all",
"the",
"unique",
"squawk",
"values",
"in",
"the",
"trajectory",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L219-L221 | train | 199,789 |
xoolive/traffic | traffic/core/flight.py | Flight.query_opensky | def query_opensky(self) -> Optional["Flight"]:
"""Return the equivalent Flight from OpenSky History."""
from ..data import opensky
query_params = {
"start": self.start,
"stop": self.stop,
"callsign": self.callsign,
"icao24": self.icao24,
}
return opensky.history(**query_params) | python | def query_opensky(self) -> Optional["Flight"]:
"""Return the equivalent Flight from OpenSky History."""
from ..data import opensky
query_params = {
"start": self.start,
"stop": self.stop,
"callsign": self.callsign,
"icao24": self.icao24,
}
return opensky.history(**query_params) | [
"def",
"query_opensky",
"(",
"self",
")",
"->",
"Optional",
"[",
"\"Flight\"",
"]",
":",
"from",
".",
".",
"data",
"import",
"opensky",
"query_params",
"=",
"{",
"\"start\"",
":",
"self",
".",
"start",
",",
"\"stop\"",
":",
"self",
".",
"stop",
",",
"\... | Return the equivalent Flight from OpenSky History. | [
"Return",
"the",
"equivalent",
"Flight",
"from",
"OpenSky",
"History",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L251-L261 | train | 199,790 |
xoolive/traffic | traffic/core/flight.py | Flight.coords | def coords(self) -> Iterator[Tuple[float, float, float]]:
"""Iterates on longitudes, latitudes and altitudes.
"""
data = self.data[self.data.longitude.notnull()]
yield from zip(data["longitude"], data["latitude"], data["altitude"]) | python | def coords(self) -> Iterator[Tuple[float, float, float]]:
"""Iterates on longitudes, latitudes and altitudes.
"""
data = self.data[self.data.longitude.notnull()]
yield from zip(data["longitude"], data["latitude"], data["altitude"]) | [
"def",
"coords",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
"]",
":",
"data",
"=",
"self",
".",
"data",
"[",
"self",
".",
"data",
".",
"longitude",
".",
"notnull",
"(",
")",
"]",
"yield",
"fro... | Iterates on longitudes, latitudes and altitudes. | [
"Iterates",
"on",
"longitudes",
"latitudes",
"and",
"altitudes",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L481-L486 | train | 199,791 |
xoolive/traffic | traffic/core/flight.py | Flight.xy_time | def xy_time(self) -> Iterator[Tuple[float, float, float]]:
"""Iterates on longitudes, latitudes and timestamps."""
iterator = iter(zip(self.coords, self.timestamp))
while True:
next_ = next(iterator, None)
if next_ is None:
return
coords, time = next_
yield (coords[0], coords[1], time.to_pydatetime().timestamp()) | python | def xy_time(self) -> Iterator[Tuple[float, float, float]]:
"""Iterates on longitudes, latitudes and timestamps."""
iterator = iter(zip(self.coords, self.timestamp))
while True:
next_ = next(iterator, None)
if next_ is None:
return
coords, time = next_
yield (coords[0], coords[1], time.to_pydatetime().timestamp()) | [
"def",
"xy_time",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
"]",
":",
"iterator",
"=",
"iter",
"(",
"zip",
"(",
"self",
".",
"coords",
",",
"self",
".",
"timestamp",
")",
")",
"while",
"True",
... | Iterates on longitudes, latitudes and timestamps. | [
"Iterates",
"on",
"longitudes",
"latitudes",
"and",
"timestamps",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L489-L497 | train | 199,792 |
xoolive/traffic | traffic/core/flight.py | Flight.split | def split(self, value=10, unit=None): # noqa: F811
"""Splits Flights in several legs.
By default, Flights are split if no value is given during 10 minutes.
"""
if type(value) == int and unit is None:
# default value is 10 m
unit = "m"
for data in _split(self.data, value, unit):
yield self.__class__(data) | python | def split(self, value=10, unit=None): # noqa: F811
"""Splits Flights in several legs.
By default, Flights are split if no value is given during 10 minutes.
"""
if type(value) == int and unit is None:
# default value is 10 m
unit = "m"
for data in _split(self.data, value, unit):
yield self.__class__(data) | [
"def",
"split",
"(",
"self",
",",
"value",
"=",
"10",
",",
"unit",
"=",
"None",
")",
":",
"# noqa: F811",
"if",
"type",
"(",
"value",
")",
"==",
"int",
"and",
"unit",
"is",
"None",
":",
"# default value is 10 m",
"unit",
"=",
"\"m\"",
"for",
"data",
... | Splits Flights in several legs.
By default, Flights are split if no value is given during 10 minutes. | [
"Splits",
"Flights",
"in",
"several",
"legs",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L696-L706 | train | 199,793 |
xoolive/traffic | traffic/core/flight.py | Flight.resample | def resample(self, rule: Union[str, int] = "1s") -> "Flight":
"""Resamples a Flight at a one point per second rate."""
if isinstance(rule, str):
data = (
self._handle_last_position()
.data.assign(start=self.start, stop=self.stop)
.set_index("timestamp")
.resample(rule)
.first() # better performance than min() for duplicate index
.interpolate()
.reset_index()
.fillna(method="pad")
)
elif isinstance(rule, int):
data = (
self._handle_last_position()
.data.set_index("timestamp")
.asfreq(
(self.stop - self.start) / (rule - 1), # type: ignore
method="nearest",
)
.reset_index()
)
else:
raise TypeError("rule must be a str or an int")
return self.__class__(data) | python | def resample(self, rule: Union[str, int] = "1s") -> "Flight":
"""Resamples a Flight at a one point per second rate."""
if isinstance(rule, str):
data = (
self._handle_last_position()
.data.assign(start=self.start, stop=self.stop)
.set_index("timestamp")
.resample(rule)
.first() # better performance than min() for duplicate index
.interpolate()
.reset_index()
.fillna(method="pad")
)
elif isinstance(rule, int):
data = (
self._handle_last_position()
.data.set_index("timestamp")
.asfreq(
(self.stop - self.start) / (rule - 1), # type: ignore
method="nearest",
)
.reset_index()
)
else:
raise TypeError("rule must be a str or an int")
return self.__class__(data) | [
"def",
"resample",
"(",
"self",
",",
"rule",
":",
"Union",
"[",
"str",
",",
"int",
"]",
"=",
"\"1s\"",
")",
"->",
"\"Flight\"",
":",
"if",
"isinstance",
"(",
"rule",
",",
"str",
")",
":",
"data",
"=",
"(",
"self",
".",
"_handle_last_position",
"(",
... | Resamples a Flight at a one point per second rate. | [
"Resamples",
"a",
"Flight",
"at",
"a",
"one",
"point",
"per",
"second",
"rate",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L729-L756 | train | 199,794 |
xoolive/traffic | traffic/core/flight.py | Flight.simplify | def simplify(
self,
tolerance: float,
altitude: Optional[str] = None,
z_factor: float = 3.048,
return_type: Type[Mask] = Type["Flight"],
) -> Mask:
"""Simplifies a trajectory with Douglas-Peucker algorithm.
The method uses latitude and longitude, projects the trajectory to a
conformal projection and applies the algorithm. By default, a 2D version
is called, unless you pass a column name for altitude (z parameter). You
may scale the z-axis for more relevance (z_factor); the default value
works well in most situations.
The method returns a Flight unless you specify a np.ndarray[bool] as
return_type for getting a mask.
"""
# returns a mask
mask = douglas_peucker(
df=self.data,
tolerance=tolerance,
lat="latitude",
lon="longitude",
z=altitude,
z_factor=z_factor,
)
if return_type == Type["Flight"]:
return self.__class__(self.data.loc[mask])
else:
return mask | python | def simplify(
self,
tolerance: float,
altitude: Optional[str] = None,
z_factor: float = 3.048,
return_type: Type[Mask] = Type["Flight"],
) -> Mask:
"""Simplifies a trajectory with Douglas-Peucker algorithm.
The method uses latitude and longitude, projects the trajectory to a
conformal projection and applies the algorithm. By default, a 2D version
is called, unless you pass a column name for altitude (z parameter). You
may scale the z-axis for more relevance (z_factor); the default value
works well in most situations.
The method returns a Flight unless you specify a np.ndarray[bool] as
return_type for getting a mask.
"""
# returns a mask
mask = douglas_peucker(
df=self.data,
tolerance=tolerance,
lat="latitude",
lon="longitude",
z=altitude,
z_factor=z_factor,
)
if return_type == Type["Flight"]:
return self.__class__(self.data.loc[mask])
else:
return mask | [
"def",
"simplify",
"(",
"self",
",",
"tolerance",
":",
"float",
",",
"altitude",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"z_factor",
":",
"float",
"=",
"3.048",
",",
"return_type",
":",
"Type",
"[",
"Mask",
"]",
"=",
"Type",
"[",
"\"Fligh... | Simplifies a trajectory with Douglas-Peucker algorithm.
The method uses latitude and longitude, projects the trajectory to a
conformal projection and applies the algorithm. By default, a 2D version
is called, unless you pass a column name for altitude (z parameter). You
may scale the z-axis for more relevance (z_factor); the default value
works well in most situations.
The method returns a Flight unless you specify a np.ndarray[bool] as
return_type for getting a mask. | [
"Simplifies",
"a",
"trajectory",
"with",
"Douglas",
"-",
"Peucker",
"algorithm",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L828-L858 | train | 199,795 |
xoolive/traffic | traffic/core/mixins.py | ShapelyMixin.project_shape | def project_shape(
self, projection: Union[pyproj.Proj, crs.Projection, None] = None
) -> base.BaseGeometry:
"""Projection for a decent representation of the structure.
By default, an equivalent projection is applied. Equivalent projections
locally respect areas, which is convenient for the area attribute.
"""
if self.shape is None:
return None
if isinstance(projection, crs.Projection):
projection = pyproj.Proj(projection.proj4_init)
if projection is None:
bounds = self.bounds
projection = pyproj.Proj(
proj="aea", # equivalent projection
lat_1=bounds[1],
lat_2=bounds[3],
lat_0=(bounds[1] + bounds[3]) / 2,
lon_0=(bounds[0] + bounds[2]) / 2,
)
projected_shape = transform(
partial(
pyproj.transform, pyproj.Proj(init="EPSG:4326"), projection
),
self.shape,
)
if not projected_shape.is_valid:
warnings.warn("The chosen projection is invalid for current shape")
return projected_shape | python | def project_shape(
self, projection: Union[pyproj.Proj, crs.Projection, None] = None
) -> base.BaseGeometry:
"""Projection for a decent representation of the structure.
By default, an equivalent projection is applied. Equivalent projections
locally respect areas, which is convenient for the area attribute.
"""
if self.shape is None:
return None
if isinstance(projection, crs.Projection):
projection = pyproj.Proj(projection.proj4_init)
if projection is None:
bounds = self.bounds
projection = pyproj.Proj(
proj="aea", # equivalent projection
lat_1=bounds[1],
lat_2=bounds[3],
lat_0=(bounds[1] + bounds[3]) / 2,
lon_0=(bounds[0] + bounds[2]) / 2,
)
projected_shape = transform(
partial(
pyproj.transform, pyproj.Proj(init="EPSG:4326"), projection
),
self.shape,
)
if not projected_shape.is_valid:
warnings.warn("The chosen projection is invalid for current shape")
return projected_shape | [
"def",
"project_shape",
"(",
"self",
",",
"projection",
":",
"Union",
"[",
"pyproj",
".",
"Proj",
",",
"crs",
".",
"Projection",
",",
"None",
"]",
"=",
"None",
")",
"->",
"base",
".",
"BaseGeometry",
":",
"if",
"self",
".",
"shape",
"is",
"None",
":"... | Projection for a decent representation of the structure.
By default, an equivalent projection is applied. Equivalent projections
locally respect areas, which is convenient for the area attribute. | [
"Projection",
"for",
"a",
"decent",
"representation",
"of",
"the",
"structure",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/mixins.py#L159-L192 | train | 199,796 |
xoolive/traffic | traffic/core/mixins.py | GeographyMixin.compute_xy | def compute_xy(
self, projection: Union[pyproj.Proj, crs.Projection, None] = None
):
"""Computes x and y columns from latitudes and longitudes.
The source projection is WGS84 (EPSG 4326).
The default destination projection is a Lambert Conformal Conical
projection centered on the data inside the dataframe.
For consistency reasons with pandas DataFrame, a new Traffic structure
is returned.
"""
if isinstance(projection, crs.Projection):
projection = pyproj.Proj(projection.proj4_init)
if projection is None:
projection = pyproj.Proj(
proj="lcc",
lat_1=self.data.latitude.min(),
lat_2=self.data.latitude.max(),
lat_0=self.data.latitude.mean(),
lon_0=self.data.longitude.mean(),
)
x, y = pyproj.transform(
pyproj.Proj(init="EPSG:4326"),
projection,
self.data.longitude.values,
self.data.latitude.values,
)
return self.__class__(self.data.assign(x=x, y=y)) | python | def compute_xy(
self, projection: Union[pyproj.Proj, crs.Projection, None] = None
):
"""Computes x and y columns from latitudes and longitudes.
The source projection is WGS84 (EPSG 4326).
The default destination projection is a Lambert Conformal Conical
projection centered on the data inside the dataframe.
For consistency reasons with pandas DataFrame, a new Traffic structure
is returned.
"""
if isinstance(projection, crs.Projection):
projection = pyproj.Proj(projection.proj4_init)
if projection is None:
projection = pyproj.Proj(
proj="lcc",
lat_1=self.data.latitude.min(),
lat_2=self.data.latitude.max(),
lat_0=self.data.latitude.mean(),
lon_0=self.data.longitude.mean(),
)
x, y = pyproj.transform(
pyproj.Proj(init="EPSG:4326"),
projection,
self.data.longitude.values,
self.data.latitude.values,
)
return self.__class__(self.data.assign(x=x, y=y)) | [
"def",
"compute_xy",
"(",
"self",
",",
"projection",
":",
"Union",
"[",
"pyproj",
".",
"Proj",
",",
"crs",
".",
"Projection",
",",
"None",
"]",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"projection",
",",
"crs",
".",
"Projection",
")",
":",
"pr... | Computes x and y columns from latitudes and longitudes.
The source projection is WGS84 (EPSG 4326).
The default destination projection is a Lambert Conformal Conical
projection centered on the data inside the dataframe.
For consistency reasons with pandas DataFrame, a new Traffic structure
is returned. | [
"Computes",
"x",
"and",
"y",
"columns",
"from",
"latitudes",
"and",
"longitudes",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/mixins.py#L198-L230 | train | 199,797 |
xoolive/traffic | traffic/core/traffic.py | Traffic.callsigns | def callsigns(self) -> Set[str]:
"""Return only the most relevant callsigns"""
sub = self.data.query("callsign == callsign")
return set(cs for cs in sub.callsign if len(cs) > 3 and " " not in cs) | python | def callsigns(self) -> Set[str]:
"""Return only the most relevant callsigns"""
sub = self.data.query("callsign == callsign")
return set(cs for cs in sub.callsign if len(cs) > 3 and " " not in cs) | [
"def",
"callsigns",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"sub",
"=",
"self",
".",
"data",
".",
"query",
"(",
"\"callsign == callsign\"",
")",
"return",
"set",
"(",
"cs",
"for",
"cs",
"in",
"sub",
".",
"callsign",
"if",
"len",
"(",
"... | Return only the most relevant callsigns | [
"Return",
"only",
"the",
"most",
"relevant",
"callsigns"
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/traffic.py#L246-L249 | train | 199,798 |
xoolive/traffic | traffic/core/traffic.py | Traffic.resample | def resample(
self,
rule: Union[str, int] = "1s",
max_workers: int = 4,
) -> "Traffic":
"""Resamples all trajectories, flight by flight.
`rule` defines the desired sample rate (default: 1s)
"""
with ProcessPoolExecutor(max_workers=max_workers) as executor:
cumul = []
tasks = {
executor.submit(flight.resample, rule): flight
for flight in self
}
for future in tqdm(as_completed(tasks), total=len(tasks)):
cumul.append(future.result())
return self.__class__.from_flights(cumul) | python | def resample(
self,
rule: Union[str, int] = "1s",
max_workers: int = 4,
) -> "Traffic":
"""Resamples all trajectories, flight by flight.
`rule` defines the desired sample rate (default: 1s)
"""
with ProcessPoolExecutor(max_workers=max_workers) as executor:
cumul = []
tasks = {
executor.submit(flight.resample, rule): flight
for flight in self
}
for future in tqdm(as_completed(tasks), total=len(tasks)):
cumul.append(future.result())
return self.__class__.from_flights(cumul) | [
"def",
"resample",
"(",
"self",
",",
"rule",
":",
"Union",
"[",
"str",
",",
"int",
"]",
"=",
"\"1s\"",
",",
"max_workers",
":",
"int",
"=",
"4",
",",
")",
"->",
"\"Traffic\"",
":",
"with",
"ProcessPoolExecutor",
"(",
"max_workers",
"=",
"max_workers",
... | Resamples all trajectories, flight by flight.
`rule` defines the desired sample rate (default: 1s) | [
"Resamples",
"all",
"trajectories",
"flight",
"by",
"flight",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/traffic.py#L371-L390 | train | 199,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.